diff --git a/ent/db/billinginvoicelinediscount.go b/ent/db/billinginvoicelinediscount.go new file mode 100644 index 0000000000000000000000000000000000000000..374a501c5ddea80b9959eeefdb3bf69fb047c0b3 --- /dev/null +++ b/ent/db/billinginvoicelinediscount.go @@ -0,0 +1,279 @@ +// 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" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicelinediscount" +) + +// BillingInvoiceLineDiscount is the model entity for the BillingInvoiceLineDiscount schema. +type BillingInvoiceLineDiscount 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"` + // InvoicingAppExternalID holds the value of the "invoicing_app_external_id" field. + InvoicingAppExternalID *string `json:"invoicing_app_external_id,omitempty"` + // LineID holds the value of the "line_id" field. + LineID string `json:"line_id,omitempty"` + // ChildUniqueReferenceID holds the value of the "child_unique_reference_id" field. + ChildUniqueReferenceID *string `json:"child_unique_reference_id,omitempty"` + // Description holds the value of the "description" field. + Description *string `json:"description,omitempty"` + // Reason holds the value of the "reason" field. + Reason billing.DiscountReasonType `json:"reason,omitempty"` + // Amount holds the value of the "amount" field. + Amount alpacadecimal.Decimal `json:"amount,omitempty"` + // RoundingAmount holds the value of the "rounding_amount" field. + RoundingAmount *alpacadecimal.Decimal `json:"rounding_amount,omitempty"` + // SourceDiscount holds the value of the "source_discount" field. + SourceDiscount *billing.DiscountReason `json:"source_discount,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the BillingInvoiceLineDiscountQuery when eager-loading is set. + Edges BillingInvoiceLineDiscountEdges `json:"edges"` + selectValues sql.SelectValues +} + +// BillingInvoiceLineDiscountEdges holds the relations/edges for other nodes in the graph. +type BillingInvoiceLineDiscountEdges struct { + // BillingInvoiceLine holds the value of the billing_invoice_line edge. + BillingInvoiceLine *BillingInvoiceLine `json:"billing_invoice_line,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// BillingInvoiceLineOrErr returns the BillingInvoiceLine value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e BillingInvoiceLineDiscountEdges) BillingInvoiceLineOrErr() (*BillingInvoiceLine, error) { + if e.BillingInvoiceLine != nil { + return e.BillingInvoiceLine, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: billinginvoiceline.Label} + } + return nil, &NotLoadedError{edge: "billing_invoice_line"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*BillingInvoiceLineDiscount) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case billinginvoicelinediscount.FieldRoundingAmount: + values[i] = &sql.NullScanner{S: new(alpacadecimal.Decimal)} + case billinginvoicelinediscount.FieldAmount: + values[i] = new(alpacadecimal.Decimal) + case billinginvoicelinediscount.FieldID, billinginvoicelinediscount.FieldNamespace, billinginvoicelinediscount.FieldInvoicingAppExternalID, billinginvoicelinediscount.FieldLineID, billinginvoicelinediscount.FieldChildUniqueReferenceID, billinginvoicelinediscount.FieldDescription, billinginvoicelinediscount.FieldReason: + values[i] = new(sql.NullString) + case billinginvoicelinediscount.FieldCreatedAt, billinginvoicelinediscount.FieldUpdatedAt, billinginvoicelinediscount.FieldDeletedAt: + values[i] = new(sql.NullTime) + case billinginvoicelinediscount.FieldSourceDiscount: + values[i] = billinginvoicelinediscount.ValueScanner.SourceDiscount.ScanValue() + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the BillingInvoiceLineDiscount fields. +func (_m *BillingInvoiceLineDiscount) 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 billinginvoicelinediscount.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 billinginvoicelinediscount.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 billinginvoicelinediscount.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 billinginvoicelinediscount.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 billinginvoicelinediscount.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 billinginvoicelinediscount.FieldInvoicingAppExternalID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field invoicing_app_external_id", values[i]) + } else if value.Valid { + _m.InvoicingAppExternalID = new(string) + *_m.InvoicingAppExternalID = value.String + } + case billinginvoicelinediscount.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 billinginvoicelinediscount.FieldChildUniqueReferenceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field child_unique_reference_id", values[i]) + } else if value.Valid { + _m.ChildUniqueReferenceID = new(string) + *_m.ChildUniqueReferenceID = value.String + } + case billinginvoicelinediscount.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + _m.Description = new(string) + *_m.Description = value.String + } + case billinginvoicelinediscount.FieldReason: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field reason", values[i]) + } else if value.Valid { + _m.Reason = billing.DiscountReasonType(value.String) + } + case billinginvoicelinediscount.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 billinginvoicelinediscount.FieldRoundingAmount: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field rounding_amount", values[i]) + } else if value.Valid { + _m.RoundingAmount = new(alpacadecimal.Decimal) + *_m.RoundingAmount = *value.S.(*alpacadecimal.Decimal) + } + case billinginvoicelinediscount.FieldSourceDiscount: + if value, err := billinginvoicelinediscount.ValueScanner.SourceDiscount.FromValue(values[i]); err != nil { + return err + } else { + _m.SourceDiscount = value + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the BillingInvoiceLineDiscount. +// This includes values selected through modifiers, order, etc. +func (_m *BillingInvoiceLineDiscount) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryBillingInvoiceLine queries the "billing_invoice_line" edge of the BillingInvoiceLineDiscount entity. +func (_m *BillingInvoiceLineDiscount) QueryBillingInvoiceLine() *BillingInvoiceLineQuery { + return NewBillingInvoiceLineDiscountClient(_m.config).QueryBillingInvoiceLine(_m) +} + +// Update returns a builder for updating this BillingInvoiceLineDiscount. +// Note that you need to call BillingInvoiceLineDiscount.Unwrap() before calling this method if this BillingInvoiceLineDiscount +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *BillingInvoiceLineDiscount) Update() *BillingInvoiceLineDiscountUpdateOne { + return NewBillingInvoiceLineDiscountClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the BillingInvoiceLineDiscount 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 *BillingInvoiceLineDiscount) Unwrap() *BillingInvoiceLineDiscount { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: BillingInvoiceLineDiscount is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *BillingInvoiceLineDiscount) String() string { + var builder strings.Builder + builder.WriteString("BillingInvoiceLineDiscount(") + 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(", ") + if v := _m.InvoicingAppExternalID; v != nil { + builder.WriteString("invoicing_app_external_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("line_id=") + builder.WriteString(_m.LineID) + builder.WriteString(", ") + if v := _m.ChildUniqueReferenceID; v != nil { + builder.WriteString("child_unique_reference_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.Description; v != nil { + builder.WriteString("description=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("reason=") + builder.WriteString(fmt.Sprintf("%v", _m.Reason)) + builder.WriteString(", ") + builder.WriteString("amount=") + builder.WriteString(fmt.Sprintf("%v", _m.Amount)) + builder.WriteString(", ") + if v := _m.RoundingAmount; v != nil { + builder.WriteString("rounding_amount=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.SourceDiscount; v != nil { + builder.WriteString("source_discount=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteByte(')') + return builder.String() +} + +// BillingInvoiceLineDiscounts is a parsable slice of BillingInvoiceLineDiscount. +type BillingInvoiceLineDiscounts []*BillingInvoiceLineDiscount diff --git a/ent/db/billinginvoicelinediscount_create.go b/ent/db/billinginvoicelinediscount_create.go new file mode 100644 index 0000000000000000000000000000000000000000..c0dbb7022cda0f7636655b561fc44927ab725218 --- /dev/null +++ b/ent/db/billinginvoicelinediscount_create.go @@ -0,0 +1,1244 @@ +// 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" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicelinediscount" +) + +// BillingInvoiceLineDiscountCreate is the builder for creating a BillingInvoiceLineDiscount entity. +type BillingInvoiceLineDiscountCreate struct { + config + mutation *BillingInvoiceLineDiscountMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *BillingInvoiceLineDiscountCreate) SetNamespace(v string) *BillingInvoiceLineDiscountCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *BillingInvoiceLineDiscountCreate) SetCreatedAt(v time.Time) *BillingInvoiceLineDiscountCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *BillingInvoiceLineDiscountCreate) SetNillableCreatedAt(v *time.Time) *BillingInvoiceLineDiscountCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *BillingInvoiceLineDiscountCreate) SetUpdatedAt(v time.Time) *BillingInvoiceLineDiscountCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *BillingInvoiceLineDiscountCreate) SetNillableUpdatedAt(v *time.Time) *BillingInvoiceLineDiscountCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *BillingInvoiceLineDiscountCreate) SetDeletedAt(v time.Time) *BillingInvoiceLineDiscountCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *BillingInvoiceLineDiscountCreate) SetNillableDeletedAt(v *time.Time) *BillingInvoiceLineDiscountCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (_c *BillingInvoiceLineDiscountCreate) SetInvoicingAppExternalID(v string) *BillingInvoiceLineDiscountCreate { + _c.mutation.SetInvoicingAppExternalID(v) + return _c +} + +// SetNillableInvoicingAppExternalID sets the "invoicing_app_external_id" field if the given value is not nil. +func (_c *BillingInvoiceLineDiscountCreate) SetNillableInvoicingAppExternalID(v *string) *BillingInvoiceLineDiscountCreate { + if v != nil { + _c.SetInvoicingAppExternalID(*v) + } + return _c +} + +// SetLineID sets the "line_id" field. +func (_c *BillingInvoiceLineDiscountCreate) SetLineID(v string) *BillingInvoiceLineDiscountCreate { + _c.mutation.SetLineID(v) + return _c +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (_c *BillingInvoiceLineDiscountCreate) SetChildUniqueReferenceID(v string) *BillingInvoiceLineDiscountCreate { + _c.mutation.SetChildUniqueReferenceID(v) + return _c +} + +// SetNillableChildUniqueReferenceID sets the "child_unique_reference_id" field if the given value is not nil. +func (_c *BillingInvoiceLineDiscountCreate) SetNillableChildUniqueReferenceID(v *string) *BillingInvoiceLineDiscountCreate { + if v != nil { + _c.SetChildUniqueReferenceID(*v) + } + return _c +} + +// SetDescription sets the "description" field. +func (_c *BillingInvoiceLineDiscountCreate) SetDescription(v string) *BillingInvoiceLineDiscountCreate { + _c.mutation.SetDescription(v) + return _c +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_c *BillingInvoiceLineDiscountCreate) SetNillableDescription(v *string) *BillingInvoiceLineDiscountCreate { + if v != nil { + _c.SetDescription(*v) + } + return _c +} + +// SetReason sets the "reason" field. +func (_c *BillingInvoiceLineDiscountCreate) SetReason(v billing.DiscountReasonType) *BillingInvoiceLineDiscountCreate { + _c.mutation.SetReason(v) + return _c +} + +// SetAmount sets the "amount" field. +func (_c *BillingInvoiceLineDiscountCreate) SetAmount(v alpacadecimal.Decimal) *BillingInvoiceLineDiscountCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetRoundingAmount sets the "rounding_amount" field. +func (_c *BillingInvoiceLineDiscountCreate) SetRoundingAmount(v alpacadecimal.Decimal) *BillingInvoiceLineDiscountCreate { + _c.mutation.SetRoundingAmount(v) + return _c +} + +// SetNillableRoundingAmount sets the "rounding_amount" field if the given value is not nil. +func (_c *BillingInvoiceLineDiscountCreate) SetNillableRoundingAmount(v *alpacadecimal.Decimal) *BillingInvoiceLineDiscountCreate { + if v != nil { + _c.SetRoundingAmount(*v) + } + return _c +} + +// SetSourceDiscount sets the "source_discount" field. +func (_c *BillingInvoiceLineDiscountCreate) SetSourceDiscount(v *billing.DiscountReason) *BillingInvoiceLineDiscountCreate { + _c.mutation.SetSourceDiscount(v) + return _c +} + +// SetID sets the "id" field. +func (_c *BillingInvoiceLineDiscountCreate) SetID(v string) *BillingInvoiceLineDiscountCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *BillingInvoiceLineDiscountCreate) SetNillableID(v *string) *BillingInvoiceLineDiscountCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID. +func (_c *BillingInvoiceLineDiscountCreate) SetBillingInvoiceLineID(id string) *BillingInvoiceLineDiscountCreate { + _c.mutation.SetBillingInvoiceLineID(id) + return _c +} + +// SetBillingInvoiceLine sets the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_c *BillingInvoiceLineDiscountCreate) SetBillingInvoiceLine(v *BillingInvoiceLine) *BillingInvoiceLineDiscountCreate { + return _c.SetBillingInvoiceLineID(v.ID) +} + +// Mutation returns the BillingInvoiceLineDiscountMutation object of the builder. +func (_c *BillingInvoiceLineDiscountCreate) Mutation() *BillingInvoiceLineDiscountMutation { + return _c.mutation +} + +// Save creates the BillingInvoiceLineDiscount in the database. +func (_c *BillingInvoiceLineDiscountCreate) Save(ctx context.Context) (*BillingInvoiceLineDiscount, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *BillingInvoiceLineDiscountCreate) SaveX(ctx context.Context) *BillingInvoiceLineDiscount { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingInvoiceLineDiscountCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingInvoiceLineDiscountCreate) 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 *BillingInvoiceLineDiscountCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := billinginvoicelinediscount.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := billinginvoicelinediscount.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := billinginvoicelinediscount.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *BillingInvoiceLineDiscountCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "BillingInvoiceLineDiscount.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := billinginvoicelinediscount.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLineDiscount.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "BillingInvoiceLineDiscount.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "BillingInvoiceLineDiscount.updated_at"`)} + } + if _, ok := _c.mutation.LineID(); !ok { + return &ValidationError{Name: "line_id", err: errors.New(`db: missing required field "BillingInvoiceLineDiscount.line_id"`)} + } + if _, ok := _c.mutation.Reason(); !ok { + return &ValidationError{Name: "reason", err: errors.New(`db: missing required field "BillingInvoiceLineDiscount.reason"`)} + } + if v, ok := _c.mutation.Reason(); ok { + if err := billinginvoicelinediscount.ReasonValidator(v); err != nil { + return &ValidationError{Name: "reason", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLineDiscount.reason": %w`, err)} + } + } + if _, ok := _c.mutation.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`db: missing required field "BillingInvoiceLineDiscount.amount"`)} + } + if v, ok := _c.mutation.SourceDiscount(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "source_discount", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLineDiscount.source_discount": %w`, err)} + } + } + if len(_c.mutation.BillingInvoiceLineIDs()) == 0 { + return &ValidationError{Name: "billing_invoice_line", err: errors.New(`db: missing required edge "BillingInvoiceLineDiscount.billing_invoice_line"`)} + } + return nil +} + +func (_c *BillingInvoiceLineDiscountCreate) sqlSave(ctx context.Context) (*BillingInvoiceLineDiscount, 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 BillingInvoiceLineDiscount.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *BillingInvoiceLineDiscountCreate) createSpec() (*BillingInvoiceLineDiscount, *sqlgraph.CreateSpec, error) { + var ( + _node = &BillingInvoiceLineDiscount{config: _c.config} + _spec = sqlgraph.NewCreateSpec(billinginvoicelinediscount.Table, sqlgraph.NewFieldSpec(billinginvoicelinediscount.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(billinginvoicelinediscount.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(billinginvoicelinediscount.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(billinginvoicelinediscount.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(billinginvoicelinediscount.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.InvoicingAppExternalID(); ok { + _spec.SetField(billinginvoicelinediscount.FieldInvoicingAppExternalID, field.TypeString, value) + _node.InvoicingAppExternalID = &value + } + if value, ok := _c.mutation.ChildUniqueReferenceID(); ok { + _spec.SetField(billinginvoicelinediscount.FieldChildUniqueReferenceID, field.TypeString, value) + _node.ChildUniqueReferenceID = &value + } + if value, ok := _c.mutation.Description(); ok { + _spec.SetField(billinginvoicelinediscount.FieldDescription, field.TypeString, value) + _node.Description = &value + } + if value, ok := _c.mutation.Reason(); ok { + _spec.SetField(billinginvoicelinediscount.FieldReason, field.TypeEnum, value) + _node.Reason = value + } + if value, ok := _c.mutation.Amount(); ok { + _spec.SetField(billinginvoicelinediscount.FieldAmount, field.TypeOther, value) + _node.Amount = value + } + if value, ok := _c.mutation.RoundingAmount(); ok { + _spec.SetField(billinginvoicelinediscount.FieldRoundingAmount, field.TypeOther, value) + _node.RoundingAmount = &value + } + if value, ok := _c.mutation.SourceDiscount(); ok { + vv, err := billinginvoicelinediscount.ValueScanner.SourceDiscount.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(billinginvoicelinediscount.FieldSourceDiscount, field.TypeString, vv) + _node.SourceDiscount = value + } + if nodes := _c.mutation.BillingInvoiceLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicelinediscount.BillingInvoiceLineTable, + Columns: []string{billinginvoicelinediscount.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.LineID = nodes[0] + _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.BillingInvoiceLineDiscount.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.BillingInvoiceLineDiscountUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *BillingInvoiceLineDiscountCreate) OnConflict(opts ...sql.ConflictOption) *BillingInvoiceLineDiscountUpsertOne { + _c.conflict = opts + return &BillingInvoiceLineDiscountUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingInvoiceLineDiscount.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingInvoiceLineDiscountCreate) OnConflictColumns(columns ...string) *BillingInvoiceLineDiscountUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingInvoiceLineDiscountUpsertOne{ + create: _c, + } +} + +type ( + // BillingInvoiceLineDiscountUpsertOne is the builder for "upsert"-ing + // one BillingInvoiceLineDiscount node. + BillingInvoiceLineDiscountUpsertOne struct { + create *BillingInvoiceLineDiscountCreate + } + + // BillingInvoiceLineDiscountUpsert is the "OnConflict" setter. + BillingInvoiceLineDiscountUpsert struct { + *sql.UpdateSet + } +) + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingInvoiceLineDiscountUpsert) SetUpdatedAt(v time.Time) *BillingInvoiceLineDiscountUpsert { + u.Set(billinginvoicelinediscount.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsert) UpdateUpdatedAt() *BillingInvoiceLineDiscountUpsert { + u.SetExcluded(billinginvoicelinediscount.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingInvoiceLineDiscountUpsert) SetDeletedAt(v time.Time) *BillingInvoiceLineDiscountUpsert { + u.Set(billinginvoicelinediscount.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsert) UpdateDeletedAt() *BillingInvoiceLineDiscountUpsert { + u.SetExcluded(billinginvoicelinediscount.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingInvoiceLineDiscountUpsert) ClearDeletedAt() *BillingInvoiceLineDiscountUpsert { + u.SetNull(billinginvoicelinediscount.FieldDeletedAt) + return u +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (u *BillingInvoiceLineDiscountUpsert) SetInvoicingAppExternalID(v string) *BillingInvoiceLineDiscountUpsert { + u.Set(billinginvoicelinediscount.FieldInvoicingAppExternalID, v) + return u +} + +// UpdateInvoicingAppExternalID sets the "invoicing_app_external_id" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsert) UpdateInvoicingAppExternalID() *BillingInvoiceLineDiscountUpsert { + u.SetExcluded(billinginvoicelinediscount.FieldInvoicingAppExternalID) + return u +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (u *BillingInvoiceLineDiscountUpsert) ClearInvoicingAppExternalID() *BillingInvoiceLineDiscountUpsert { + u.SetNull(billinginvoicelinediscount.FieldInvoicingAppExternalID) + return u +} + +// SetLineID sets the "line_id" field. +func (u *BillingInvoiceLineDiscountUpsert) SetLineID(v string) *BillingInvoiceLineDiscountUpsert { + u.Set(billinginvoicelinediscount.FieldLineID, v) + return u +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsert) UpdateLineID() *BillingInvoiceLineDiscountUpsert { + u.SetExcluded(billinginvoicelinediscount.FieldLineID) + return u +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (u *BillingInvoiceLineDiscountUpsert) SetChildUniqueReferenceID(v string) *BillingInvoiceLineDiscountUpsert { + u.Set(billinginvoicelinediscount.FieldChildUniqueReferenceID, v) + return u +} + +// UpdateChildUniqueReferenceID sets the "child_unique_reference_id" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsert) UpdateChildUniqueReferenceID() *BillingInvoiceLineDiscountUpsert { + u.SetExcluded(billinginvoicelinediscount.FieldChildUniqueReferenceID) + return u +} + +// ClearChildUniqueReferenceID clears the value of the "child_unique_reference_id" field. +func (u *BillingInvoiceLineDiscountUpsert) ClearChildUniqueReferenceID() *BillingInvoiceLineDiscountUpsert { + u.SetNull(billinginvoicelinediscount.FieldChildUniqueReferenceID) + return u +} + +// SetDescription sets the "description" field. +func (u *BillingInvoiceLineDiscountUpsert) SetDescription(v string) *BillingInvoiceLineDiscountUpsert { + u.Set(billinginvoicelinediscount.FieldDescription, v) + return u +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsert) UpdateDescription() *BillingInvoiceLineDiscountUpsert { + u.SetExcluded(billinginvoicelinediscount.FieldDescription) + return u +} + +// ClearDescription clears the value of the "description" field. +func (u *BillingInvoiceLineDiscountUpsert) ClearDescription() *BillingInvoiceLineDiscountUpsert { + u.SetNull(billinginvoicelinediscount.FieldDescription) + return u +} + +// SetReason sets the "reason" field. +func (u *BillingInvoiceLineDiscountUpsert) SetReason(v billing.DiscountReasonType) *BillingInvoiceLineDiscountUpsert { + u.Set(billinginvoicelinediscount.FieldReason, v) + return u +} + +// UpdateReason sets the "reason" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsert) UpdateReason() *BillingInvoiceLineDiscountUpsert { + u.SetExcluded(billinginvoicelinediscount.FieldReason) + return u +} + +// SetAmount sets the "amount" field. +func (u *BillingInvoiceLineDiscountUpsert) SetAmount(v alpacadecimal.Decimal) *BillingInvoiceLineDiscountUpsert { + u.Set(billinginvoicelinediscount.FieldAmount, v) + return u +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsert) UpdateAmount() *BillingInvoiceLineDiscountUpsert { + u.SetExcluded(billinginvoicelinediscount.FieldAmount) + return u +} + +// SetRoundingAmount sets the "rounding_amount" field. +func (u *BillingInvoiceLineDiscountUpsert) SetRoundingAmount(v alpacadecimal.Decimal) *BillingInvoiceLineDiscountUpsert { + u.Set(billinginvoicelinediscount.FieldRoundingAmount, v) + return u +} + +// UpdateRoundingAmount sets the "rounding_amount" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsert) UpdateRoundingAmount() *BillingInvoiceLineDiscountUpsert { + u.SetExcluded(billinginvoicelinediscount.FieldRoundingAmount) + return u +} + +// ClearRoundingAmount clears the value of the "rounding_amount" field. +func (u *BillingInvoiceLineDiscountUpsert) ClearRoundingAmount() *BillingInvoiceLineDiscountUpsert { + u.SetNull(billinginvoicelinediscount.FieldRoundingAmount) + return u +} + +// SetSourceDiscount sets the "source_discount" field. +func (u *BillingInvoiceLineDiscountUpsert) SetSourceDiscount(v *billing.DiscountReason) *BillingInvoiceLineDiscountUpsert { + u.Set(billinginvoicelinediscount.FieldSourceDiscount, v) + return u +} + +// UpdateSourceDiscount sets the "source_discount" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsert) UpdateSourceDiscount() *BillingInvoiceLineDiscountUpsert { + u.SetExcluded(billinginvoicelinediscount.FieldSourceDiscount) + return u +} + +// ClearSourceDiscount clears the value of the "source_discount" field. +func (u *BillingInvoiceLineDiscountUpsert) ClearSourceDiscount() *BillingInvoiceLineDiscountUpsert { + u.SetNull(billinginvoicelinediscount.FieldSourceDiscount) + 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.BillingInvoiceLineDiscount.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(billinginvoicelinediscount.FieldID) +// }), +// ). +// Exec(ctx) +func (u *BillingInvoiceLineDiscountUpsertOne) UpdateNewValues() *BillingInvoiceLineDiscountUpsertOne { + 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(billinginvoicelinediscount.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(billinginvoicelinediscount.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(billinginvoicelinediscount.FieldCreatedAt) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingInvoiceLineDiscount.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingInvoiceLineDiscountUpsertOne) Ignore() *BillingInvoiceLineDiscountUpsertOne { + 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 *BillingInvoiceLineDiscountUpsertOne) DoNothing() *BillingInvoiceLineDiscountUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingInvoiceLineDiscountCreate.OnConflict +// documentation for more info. +func (u *BillingInvoiceLineDiscountUpsertOne) Update(set func(*BillingInvoiceLineDiscountUpsert)) *BillingInvoiceLineDiscountUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingInvoiceLineDiscountUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingInvoiceLineDiscountUpsertOne) SetUpdatedAt(v time.Time) *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsertOne) UpdateUpdatedAt() *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingInvoiceLineDiscountUpsertOne) SetDeletedAt(v time.Time) *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsertOne) UpdateDeletedAt() *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingInvoiceLineDiscountUpsertOne) ClearDeletedAt() *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.ClearDeletedAt() + }) +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (u *BillingInvoiceLineDiscountUpsertOne) SetInvoicingAppExternalID(v string) *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.SetInvoicingAppExternalID(v) + }) +} + +// UpdateInvoicingAppExternalID sets the "invoicing_app_external_id" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsertOne) UpdateInvoicingAppExternalID() *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.UpdateInvoicingAppExternalID() + }) +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (u *BillingInvoiceLineDiscountUpsertOne) ClearInvoicingAppExternalID() *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.ClearInvoicingAppExternalID() + }) +} + +// SetLineID sets the "line_id" field. +func (u *BillingInvoiceLineDiscountUpsertOne) SetLineID(v string) *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.SetLineID(v) + }) +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsertOne) UpdateLineID() *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.UpdateLineID() + }) +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (u *BillingInvoiceLineDiscountUpsertOne) SetChildUniqueReferenceID(v string) *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.SetChildUniqueReferenceID(v) + }) +} + +// UpdateChildUniqueReferenceID sets the "child_unique_reference_id" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsertOne) UpdateChildUniqueReferenceID() *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.UpdateChildUniqueReferenceID() + }) +} + +// ClearChildUniqueReferenceID clears the value of the "child_unique_reference_id" field. +func (u *BillingInvoiceLineDiscountUpsertOne) ClearChildUniqueReferenceID() *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.ClearChildUniqueReferenceID() + }) +} + +// SetDescription sets the "description" field. +func (u *BillingInvoiceLineDiscountUpsertOne) SetDescription(v string) *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsertOne) UpdateDescription() *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *BillingInvoiceLineDiscountUpsertOne) ClearDescription() *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.ClearDescription() + }) +} + +// SetReason sets the "reason" field. +func (u *BillingInvoiceLineDiscountUpsertOne) SetReason(v billing.DiscountReasonType) *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.SetReason(v) + }) +} + +// UpdateReason sets the "reason" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsertOne) UpdateReason() *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.UpdateReason() + }) +} + +// SetAmount sets the "amount" field. +func (u *BillingInvoiceLineDiscountUpsertOne) SetAmount(v alpacadecimal.Decimal) *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsertOne) UpdateAmount() *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.UpdateAmount() + }) +} + +// SetRoundingAmount sets the "rounding_amount" field. +func (u *BillingInvoiceLineDiscountUpsertOne) SetRoundingAmount(v alpacadecimal.Decimal) *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.SetRoundingAmount(v) + }) +} + +// UpdateRoundingAmount sets the "rounding_amount" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsertOne) UpdateRoundingAmount() *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.UpdateRoundingAmount() + }) +} + +// ClearRoundingAmount clears the value of the "rounding_amount" field. +func (u *BillingInvoiceLineDiscountUpsertOne) ClearRoundingAmount() *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.ClearRoundingAmount() + }) +} + +// SetSourceDiscount sets the "source_discount" field. +func (u *BillingInvoiceLineDiscountUpsertOne) SetSourceDiscount(v *billing.DiscountReason) *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.SetSourceDiscount(v) + }) +} + +// UpdateSourceDiscount sets the "source_discount" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsertOne) UpdateSourceDiscount() *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.UpdateSourceDiscount() + }) +} + +// ClearSourceDiscount clears the value of the "source_discount" field. +func (u *BillingInvoiceLineDiscountUpsertOne) ClearSourceDiscount() *BillingInvoiceLineDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.ClearSourceDiscount() + }) +} + +// Exec executes the query. +func (u *BillingInvoiceLineDiscountUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingInvoiceLineDiscountCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingInvoiceLineDiscountUpsertOne) 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 *BillingInvoiceLineDiscountUpsertOne) 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: BillingInvoiceLineDiscountUpsertOne.ID is not supported by MySQL driver. Use BillingInvoiceLineDiscountUpsertOne.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 *BillingInvoiceLineDiscountUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// BillingInvoiceLineDiscountCreateBulk is the builder for creating many BillingInvoiceLineDiscount entities in bulk. +type BillingInvoiceLineDiscountCreateBulk struct { + config + err error + builders []*BillingInvoiceLineDiscountCreate + conflict []sql.ConflictOption +} + +// Save creates the BillingInvoiceLineDiscount entities in the database. +func (_c *BillingInvoiceLineDiscountCreateBulk) Save(ctx context.Context) ([]*BillingInvoiceLineDiscount, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*BillingInvoiceLineDiscount, 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.(*BillingInvoiceLineDiscountMutation) + 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 *BillingInvoiceLineDiscountCreateBulk) SaveX(ctx context.Context) []*BillingInvoiceLineDiscount { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingInvoiceLineDiscountCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingInvoiceLineDiscountCreateBulk) 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.BillingInvoiceLineDiscount.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.BillingInvoiceLineDiscountUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *BillingInvoiceLineDiscountCreateBulk) OnConflict(opts ...sql.ConflictOption) *BillingInvoiceLineDiscountUpsertBulk { + _c.conflict = opts + return &BillingInvoiceLineDiscountUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingInvoiceLineDiscount.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingInvoiceLineDiscountCreateBulk) OnConflictColumns(columns ...string) *BillingInvoiceLineDiscountUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingInvoiceLineDiscountUpsertBulk{ + create: _c, + } +} + +// BillingInvoiceLineDiscountUpsertBulk is the builder for "upsert"-ing +// a bulk of BillingInvoiceLineDiscount nodes. +type BillingInvoiceLineDiscountUpsertBulk struct { + create *BillingInvoiceLineDiscountCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.BillingInvoiceLineDiscount.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(billinginvoicelinediscount.FieldID) +// }), +// ). +// Exec(ctx) +func (u *BillingInvoiceLineDiscountUpsertBulk) UpdateNewValues() *BillingInvoiceLineDiscountUpsertBulk { + 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(billinginvoicelinediscount.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(billinginvoicelinediscount.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(billinginvoicelinediscount.FieldCreatedAt) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingInvoiceLineDiscount.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingInvoiceLineDiscountUpsertBulk) Ignore() *BillingInvoiceLineDiscountUpsertBulk { + 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 *BillingInvoiceLineDiscountUpsertBulk) DoNothing() *BillingInvoiceLineDiscountUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingInvoiceLineDiscountCreateBulk.OnConflict +// documentation for more info. +func (u *BillingInvoiceLineDiscountUpsertBulk) Update(set func(*BillingInvoiceLineDiscountUpsert)) *BillingInvoiceLineDiscountUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingInvoiceLineDiscountUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingInvoiceLineDiscountUpsertBulk) SetUpdatedAt(v time.Time) *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsertBulk) UpdateUpdatedAt() *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingInvoiceLineDiscountUpsertBulk) SetDeletedAt(v time.Time) *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsertBulk) UpdateDeletedAt() *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingInvoiceLineDiscountUpsertBulk) ClearDeletedAt() *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.ClearDeletedAt() + }) +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (u *BillingInvoiceLineDiscountUpsertBulk) SetInvoicingAppExternalID(v string) *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.SetInvoicingAppExternalID(v) + }) +} + +// UpdateInvoicingAppExternalID sets the "invoicing_app_external_id" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsertBulk) UpdateInvoicingAppExternalID() *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.UpdateInvoicingAppExternalID() + }) +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (u *BillingInvoiceLineDiscountUpsertBulk) ClearInvoicingAppExternalID() *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.ClearInvoicingAppExternalID() + }) +} + +// SetLineID sets the "line_id" field. +func (u *BillingInvoiceLineDiscountUpsertBulk) SetLineID(v string) *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.SetLineID(v) + }) +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsertBulk) UpdateLineID() *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.UpdateLineID() + }) +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (u *BillingInvoiceLineDiscountUpsertBulk) SetChildUniqueReferenceID(v string) *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.SetChildUniqueReferenceID(v) + }) +} + +// UpdateChildUniqueReferenceID sets the "child_unique_reference_id" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsertBulk) UpdateChildUniqueReferenceID() *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.UpdateChildUniqueReferenceID() + }) +} + +// ClearChildUniqueReferenceID clears the value of the "child_unique_reference_id" field. +func (u *BillingInvoiceLineDiscountUpsertBulk) ClearChildUniqueReferenceID() *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.ClearChildUniqueReferenceID() + }) +} + +// SetDescription sets the "description" field. +func (u *BillingInvoiceLineDiscountUpsertBulk) SetDescription(v string) *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsertBulk) UpdateDescription() *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *BillingInvoiceLineDiscountUpsertBulk) ClearDescription() *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.ClearDescription() + }) +} + +// SetReason sets the "reason" field. +func (u *BillingInvoiceLineDiscountUpsertBulk) SetReason(v billing.DiscountReasonType) *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.SetReason(v) + }) +} + +// UpdateReason sets the "reason" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsertBulk) UpdateReason() *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.UpdateReason() + }) +} + +// SetAmount sets the "amount" field. +func (u *BillingInvoiceLineDiscountUpsertBulk) SetAmount(v alpacadecimal.Decimal) *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsertBulk) UpdateAmount() *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.UpdateAmount() + }) +} + +// SetRoundingAmount sets the "rounding_amount" field. +func (u *BillingInvoiceLineDiscountUpsertBulk) SetRoundingAmount(v alpacadecimal.Decimal) *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.SetRoundingAmount(v) + }) +} + +// UpdateRoundingAmount sets the "rounding_amount" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsertBulk) UpdateRoundingAmount() *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.UpdateRoundingAmount() + }) +} + +// ClearRoundingAmount clears the value of the "rounding_amount" field. +func (u *BillingInvoiceLineDiscountUpsertBulk) ClearRoundingAmount() *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.ClearRoundingAmount() + }) +} + +// SetSourceDiscount sets the "source_discount" field. +func (u *BillingInvoiceLineDiscountUpsertBulk) SetSourceDiscount(v *billing.DiscountReason) *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.SetSourceDiscount(v) + }) +} + +// UpdateSourceDiscount sets the "source_discount" field to the value that was provided on create. +func (u *BillingInvoiceLineDiscountUpsertBulk) UpdateSourceDiscount() *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.UpdateSourceDiscount() + }) +} + +// ClearSourceDiscount clears the value of the "source_discount" field. +func (u *BillingInvoiceLineDiscountUpsertBulk) ClearSourceDiscount() *BillingInvoiceLineDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineDiscountUpsert) { + s.ClearSourceDiscount() + }) +} + +// Exec executes the query. +func (u *BillingInvoiceLineDiscountUpsertBulk) 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 BillingInvoiceLineDiscountCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingInvoiceLineDiscountCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingInvoiceLineDiscountUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billinginvoicelinediscount_delete.go b/ent/db/billinginvoicelinediscount_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..02c3544e34182b84cbefd2cd12557bc789ac0030 --- /dev/null +++ b/ent/db/billinginvoicelinediscount_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/billinginvoicelinediscount" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingInvoiceLineDiscountDelete is the builder for deleting a BillingInvoiceLineDiscount entity. +type BillingInvoiceLineDiscountDelete struct { + config + hooks []Hook + mutation *BillingInvoiceLineDiscountMutation +} + +// Where appends a list predicates to the BillingInvoiceLineDiscountDelete builder. +func (_d *BillingInvoiceLineDiscountDelete) Where(ps ...predicate.BillingInvoiceLineDiscount) *BillingInvoiceLineDiscountDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *BillingInvoiceLineDiscountDelete) 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 *BillingInvoiceLineDiscountDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *BillingInvoiceLineDiscountDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(billinginvoicelinediscount.Table, sqlgraph.NewFieldSpec(billinginvoicelinediscount.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 +} + +// BillingInvoiceLineDiscountDeleteOne is the builder for deleting a single BillingInvoiceLineDiscount entity. +type BillingInvoiceLineDiscountDeleteOne struct { + _d *BillingInvoiceLineDiscountDelete +} + +// Where appends a list predicates to the BillingInvoiceLineDiscountDelete builder. +func (_d *BillingInvoiceLineDiscountDeleteOne) Where(ps ...predicate.BillingInvoiceLineDiscount) *BillingInvoiceLineDiscountDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *BillingInvoiceLineDiscountDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{billinginvoicelinediscount.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *BillingInvoiceLineDiscountDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billinginvoicelinediscount_query.go b/ent/db/billinginvoicelinediscount_query.go new file mode 100644 index 0000000000000000000000000000000000000000..fc23af6df6df68c3110f202427df97cb8ef9dac6 --- /dev/null +++ b/ent/db/billinginvoicelinediscount_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/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicelinediscount" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingInvoiceLineDiscountQuery is the builder for querying BillingInvoiceLineDiscount entities. +type BillingInvoiceLineDiscountQuery struct { + config + ctx *QueryContext + order []billinginvoicelinediscount.OrderOption + inters []Interceptor + predicates []predicate.BillingInvoiceLineDiscount + withBillingInvoiceLine *BillingInvoiceLineQuery + 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 BillingInvoiceLineDiscountQuery builder. +func (_q *BillingInvoiceLineDiscountQuery) Where(ps ...predicate.BillingInvoiceLineDiscount) *BillingInvoiceLineDiscountQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *BillingInvoiceLineDiscountQuery) Limit(limit int) *BillingInvoiceLineDiscountQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *BillingInvoiceLineDiscountQuery) Offset(offset int) *BillingInvoiceLineDiscountQuery { + _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 *BillingInvoiceLineDiscountQuery) Unique(unique bool) *BillingInvoiceLineDiscountQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *BillingInvoiceLineDiscountQuery) Order(o ...billinginvoicelinediscount.OrderOption) *BillingInvoiceLineDiscountQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryBillingInvoiceLine chains the current query on the "billing_invoice_line" edge. +func (_q *BillingInvoiceLineDiscountQuery) QueryBillingInvoiceLine() *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{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(billinginvoicelinediscount.Table, billinginvoicelinediscount.FieldID, selector), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoicelinediscount.BillingInvoiceLineTable, billinginvoicelinediscount.BillingInvoiceLineColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first BillingInvoiceLineDiscount entity from the query. +// Returns a *NotFoundError when no BillingInvoiceLineDiscount was found. +func (_q *BillingInvoiceLineDiscountQuery) First(ctx context.Context) (*BillingInvoiceLineDiscount, 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{billinginvoicelinediscount.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *BillingInvoiceLineDiscountQuery) FirstX(ctx context.Context) *BillingInvoiceLineDiscount { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first BillingInvoiceLineDiscount ID from the query. +// Returns a *NotFoundError when no BillingInvoiceLineDiscount ID was found. +func (_q *BillingInvoiceLineDiscountQuery) 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{billinginvoicelinediscount.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *BillingInvoiceLineDiscountQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single BillingInvoiceLineDiscount entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one BillingInvoiceLineDiscount entity is found. +// Returns a *NotFoundError when no BillingInvoiceLineDiscount entities are found. +func (_q *BillingInvoiceLineDiscountQuery) Only(ctx context.Context) (*BillingInvoiceLineDiscount, 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{billinginvoicelinediscount.Label} + default: + return nil, &NotSingularError{billinginvoicelinediscount.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *BillingInvoiceLineDiscountQuery) OnlyX(ctx context.Context) *BillingInvoiceLineDiscount { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only BillingInvoiceLineDiscount ID in the query. +// Returns a *NotSingularError when more than one BillingInvoiceLineDiscount ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *BillingInvoiceLineDiscountQuery) 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{billinginvoicelinediscount.Label} + default: + err = &NotSingularError{billinginvoicelinediscount.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *BillingInvoiceLineDiscountQuery) 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 BillingInvoiceLineDiscounts. +func (_q *BillingInvoiceLineDiscountQuery) All(ctx context.Context) ([]*BillingInvoiceLineDiscount, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*BillingInvoiceLineDiscount, *BillingInvoiceLineDiscountQuery]() + return withInterceptors[[]*BillingInvoiceLineDiscount](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *BillingInvoiceLineDiscountQuery) AllX(ctx context.Context) []*BillingInvoiceLineDiscount { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of BillingInvoiceLineDiscount IDs. +func (_q *BillingInvoiceLineDiscountQuery) 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(billinginvoicelinediscount.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *BillingInvoiceLineDiscountQuery) 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 *BillingInvoiceLineDiscountQuery) 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[*BillingInvoiceLineDiscountQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *BillingInvoiceLineDiscountQuery) 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 *BillingInvoiceLineDiscountQuery) 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 *BillingInvoiceLineDiscountQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the BillingInvoiceLineDiscountQuery 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 *BillingInvoiceLineDiscountQuery) Clone() *BillingInvoiceLineDiscountQuery { + if _q == nil { + return nil + } + return &BillingInvoiceLineDiscountQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]billinginvoicelinediscount.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.BillingInvoiceLineDiscount{}, _q.predicates...), + withBillingInvoiceLine: _q.withBillingInvoiceLine.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithBillingInvoiceLine tells the query-builder to eager-load the nodes that are connected to +// the "billing_invoice_line" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *BillingInvoiceLineDiscountQuery) WithBillingInvoiceLine(opts ...func(*BillingInvoiceLineQuery)) *BillingInvoiceLineDiscountQuery { + query := (&BillingInvoiceLineClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingInvoiceLine = 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.BillingInvoiceLineDiscount.Query(). +// GroupBy(billinginvoicelinediscount.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *BillingInvoiceLineDiscountQuery) GroupBy(field string, fields ...string) *BillingInvoiceLineDiscountGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &BillingInvoiceLineDiscountGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = billinginvoicelinediscount.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.BillingInvoiceLineDiscount.Query(). +// Select(billinginvoicelinediscount.FieldNamespace). +// Scan(ctx, &v) +func (_q *BillingInvoiceLineDiscountQuery) Select(fields ...string) *BillingInvoiceLineDiscountSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &BillingInvoiceLineDiscountSelect{BillingInvoiceLineDiscountQuery: _q} + sbuild.label = billinginvoicelinediscount.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a BillingInvoiceLineDiscountSelect configured with the given aggregations. +func (_q *BillingInvoiceLineDiscountQuery) Aggregate(fns ...AggregateFunc) *BillingInvoiceLineDiscountSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *BillingInvoiceLineDiscountQuery) 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 !billinginvoicelinediscount.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 *BillingInvoiceLineDiscountQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BillingInvoiceLineDiscount, error) { + var ( + nodes = []*BillingInvoiceLineDiscount{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withBillingInvoiceLine != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*BillingInvoiceLineDiscount).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &BillingInvoiceLineDiscount{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.withBillingInvoiceLine; query != nil { + if err := _q.loadBillingInvoiceLine(ctx, query, nodes, nil, + func(n *BillingInvoiceLineDiscount, e *BillingInvoiceLine) { n.Edges.BillingInvoiceLine = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *BillingInvoiceLineDiscountQuery) loadBillingInvoiceLine(ctx context.Context, query *BillingInvoiceLineQuery, nodes []*BillingInvoiceLineDiscount, init func(*BillingInvoiceLineDiscount), assign func(*BillingInvoiceLineDiscount, *BillingInvoiceLine)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*BillingInvoiceLineDiscount) + for i := range nodes { + fk := nodes[i].LineID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(billinginvoiceline.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 "line_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *BillingInvoiceLineDiscountQuery) 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 *BillingInvoiceLineDiscountQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(billinginvoicelinediscount.Table, billinginvoicelinediscount.Columns, sqlgraph.NewFieldSpec(billinginvoicelinediscount.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, billinginvoicelinediscount.FieldID) + for i := range fields { + if fields[i] != billinginvoicelinediscount.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withBillingInvoiceLine != nil { + _spec.Node.AddColumnOnce(billinginvoicelinediscount.FieldLineID) + } + } + 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 *BillingInvoiceLineDiscountQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(billinginvoicelinediscount.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = billinginvoicelinediscount.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 *BillingInvoiceLineDiscountQuery) ForUpdate(opts ...sql.LockOption) *BillingInvoiceLineDiscountQuery { + 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 *BillingInvoiceLineDiscountQuery) ForShare(opts ...sql.LockOption) *BillingInvoiceLineDiscountQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// BillingInvoiceLineDiscountGroupBy is the group-by builder for BillingInvoiceLineDiscount entities. +type BillingInvoiceLineDiscountGroupBy struct { + selector + build *BillingInvoiceLineDiscountQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *BillingInvoiceLineDiscountGroupBy) Aggregate(fns ...AggregateFunc) *BillingInvoiceLineDiscountGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *BillingInvoiceLineDiscountGroupBy) 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[*BillingInvoiceLineDiscountQuery, *BillingInvoiceLineDiscountGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *BillingInvoiceLineDiscountGroupBy) sqlScan(ctx context.Context, root *BillingInvoiceLineDiscountQuery, 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) +} + +// BillingInvoiceLineDiscountSelect is the builder for selecting fields of BillingInvoiceLineDiscount entities. +type BillingInvoiceLineDiscountSelect struct { + *BillingInvoiceLineDiscountQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *BillingInvoiceLineDiscountSelect) Aggregate(fns ...AggregateFunc) *BillingInvoiceLineDiscountSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *BillingInvoiceLineDiscountSelect) 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[*BillingInvoiceLineDiscountQuery, *BillingInvoiceLineDiscountSelect](ctx, _s.BillingInvoiceLineDiscountQuery, _s, _s.inters, v) +} + +func (_s *BillingInvoiceLineDiscountSelect) sqlScan(ctx context.Context, root *BillingInvoiceLineDiscountQuery, 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/ent/db/billinginvoicelinediscount_update.go b/ent/db/billinginvoicelinediscount_update.go new file mode 100644 index 0000000000000000000000000000000000000000..f0d59055ee31422f8ddbf5c7135a97defbd1d318 --- /dev/null +++ b/ent/db/billinginvoicelinediscount_update.go @@ -0,0 +1,749 @@ +// 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" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicelinediscount" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingInvoiceLineDiscountUpdate is the builder for updating BillingInvoiceLineDiscount entities. +type BillingInvoiceLineDiscountUpdate struct { + config + hooks []Hook + mutation *BillingInvoiceLineDiscountMutation +} + +// Where appends a list predicates to the BillingInvoiceLineDiscountUpdate builder. +func (_u *BillingInvoiceLineDiscountUpdate) Where(ps ...predicate.BillingInvoiceLineDiscount) *BillingInvoiceLineDiscountUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *BillingInvoiceLineDiscountUpdate) SetUpdatedAt(v time.Time) *BillingInvoiceLineDiscountUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *BillingInvoiceLineDiscountUpdate) SetDeletedAt(v time.Time) *BillingInvoiceLineDiscountUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *BillingInvoiceLineDiscountUpdate) SetNillableDeletedAt(v *time.Time) *BillingInvoiceLineDiscountUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *BillingInvoiceLineDiscountUpdate) ClearDeletedAt() *BillingInvoiceLineDiscountUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (_u *BillingInvoiceLineDiscountUpdate) SetInvoicingAppExternalID(v string) *BillingInvoiceLineDiscountUpdate { + _u.mutation.SetInvoicingAppExternalID(v) + return _u +} + +// SetNillableInvoicingAppExternalID sets the "invoicing_app_external_id" field if the given value is not nil. +func (_u *BillingInvoiceLineDiscountUpdate) SetNillableInvoicingAppExternalID(v *string) *BillingInvoiceLineDiscountUpdate { + if v != nil { + _u.SetInvoicingAppExternalID(*v) + } + return _u +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (_u *BillingInvoiceLineDiscountUpdate) ClearInvoicingAppExternalID() *BillingInvoiceLineDiscountUpdate { + _u.mutation.ClearInvoicingAppExternalID() + return _u +} + +// SetLineID sets the "line_id" field. +func (_u *BillingInvoiceLineDiscountUpdate) SetLineID(v string) *BillingInvoiceLineDiscountUpdate { + _u.mutation.SetLineID(v) + return _u +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_u *BillingInvoiceLineDiscountUpdate) SetNillableLineID(v *string) *BillingInvoiceLineDiscountUpdate { + if v != nil { + _u.SetLineID(*v) + } + return _u +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (_u *BillingInvoiceLineDiscountUpdate) SetChildUniqueReferenceID(v string) *BillingInvoiceLineDiscountUpdate { + _u.mutation.SetChildUniqueReferenceID(v) + return _u +} + +// SetNillableChildUniqueReferenceID sets the "child_unique_reference_id" field if the given value is not nil. +func (_u *BillingInvoiceLineDiscountUpdate) SetNillableChildUniqueReferenceID(v *string) *BillingInvoiceLineDiscountUpdate { + if v != nil { + _u.SetChildUniqueReferenceID(*v) + } + return _u +} + +// ClearChildUniqueReferenceID clears the value of the "child_unique_reference_id" field. +func (_u *BillingInvoiceLineDiscountUpdate) ClearChildUniqueReferenceID() *BillingInvoiceLineDiscountUpdate { + _u.mutation.ClearChildUniqueReferenceID() + return _u +} + +// SetDescription sets the "description" field. +func (_u *BillingInvoiceLineDiscountUpdate) SetDescription(v string) *BillingInvoiceLineDiscountUpdate { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *BillingInvoiceLineDiscountUpdate) SetNillableDescription(v *string) *BillingInvoiceLineDiscountUpdate { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *BillingInvoiceLineDiscountUpdate) ClearDescription() *BillingInvoiceLineDiscountUpdate { + _u.mutation.ClearDescription() + return _u +} + +// SetReason sets the "reason" field. +func (_u *BillingInvoiceLineDiscountUpdate) SetReason(v billing.DiscountReasonType) *BillingInvoiceLineDiscountUpdate { + _u.mutation.SetReason(v) + return _u +} + +// SetNillableReason sets the "reason" field if the given value is not nil. +func (_u *BillingInvoiceLineDiscountUpdate) SetNillableReason(v *billing.DiscountReasonType) *BillingInvoiceLineDiscountUpdate { + if v != nil { + _u.SetReason(*v) + } + return _u +} + +// SetAmount sets the "amount" field. +func (_u *BillingInvoiceLineDiscountUpdate) SetAmount(v alpacadecimal.Decimal) *BillingInvoiceLineDiscountUpdate { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *BillingInvoiceLineDiscountUpdate) SetNillableAmount(v *alpacadecimal.Decimal) *BillingInvoiceLineDiscountUpdate { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetRoundingAmount sets the "rounding_amount" field. +func (_u *BillingInvoiceLineDiscountUpdate) SetRoundingAmount(v alpacadecimal.Decimal) *BillingInvoiceLineDiscountUpdate { + _u.mutation.SetRoundingAmount(v) + return _u +} + +// SetNillableRoundingAmount sets the "rounding_amount" field if the given value is not nil. +func (_u *BillingInvoiceLineDiscountUpdate) SetNillableRoundingAmount(v *alpacadecimal.Decimal) *BillingInvoiceLineDiscountUpdate { + if v != nil { + _u.SetRoundingAmount(*v) + } + return _u +} + +// ClearRoundingAmount clears the value of the "rounding_amount" field. +func (_u *BillingInvoiceLineDiscountUpdate) ClearRoundingAmount() *BillingInvoiceLineDiscountUpdate { + _u.mutation.ClearRoundingAmount() + return _u +} + +// SetSourceDiscount sets the "source_discount" field. +func (_u *BillingInvoiceLineDiscountUpdate) SetSourceDiscount(v *billing.DiscountReason) *BillingInvoiceLineDiscountUpdate { + _u.mutation.SetSourceDiscount(v) + return _u +} + +// ClearSourceDiscount clears the value of the "source_discount" field. +func (_u *BillingInvoiceLineDiscountUpdate) ClearSourceDiscount() *BillingInvoiceLineDiscountUpdate { + _u.mutation.ClearSourceDiscount() + return _u +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID. +func (_u *BillingInvoiceLineDiscountUpdate) SetBillingInvoiceLineID(id string) *BillingInvoiceLineDiscountUpdate { + _u.mutation.SetBillingInvoiceLineID(id) + return _u +} + +// SetBillingInvoiceLine sets the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *BillingInvoiceLineDiscountUpdate) SetBillingInvoiceLine(v *BillingInvoiceLine) *BillingInvoiceLineDiscountUpdate { + return _u.SetBillingInvoiceLineID(v.ID) +} + +// Mutation returns the BillingInvoiceLineDiscountMutation object of the builder. +func (_u *BillingInvoiceLineDiscountUpdate) Mutation() *BillingInvoiceLineDiscountMutation { + return _u.mutation +} + +// ClearBillingInvoiceLine clears the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *BillingInvoiceLineDiscountUpdate) ClearBillingInvoiceLine() *BillingInvoiceLineDiscountUpdate { + _u.mutation.ClearBillingInvoiceLine() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *BillingInvoiceLineDiscountUpdate) 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 *BillingInvoiceLineDiscountUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *BillingInvoiceLineDiscountUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingInvoiceLineDiscountUpdate) 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 *BillingInvoiceLineDiscountUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := billinginvoicelinediscount.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *BillingInvoiceLineDiscountUpdate) check() error { + if v, ok := _u.mutation.Reason(); ok { + if err := billinginvoicelinediscount.ReasonValidator(v); err != nil { + return &ValidationError{Name: "reason", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLineDiscount.reason": %w`, err)} + } + } + if v, ok := _u.mutation.SourceDiscount(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "source_discount", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLineDiscount.source_discount": %w`, err)} + } + } + if _u.mutation.BillingInvoiceLineCleared() && len(_u.mutation.BillingInvoiceLineIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "BillingInvoiceLineDiscount.billing_invoice_line"`) + } + return nil +} + +func (_u *BillingInvoiceLineDiscountUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(billinginvoicelinediscount.Table, billinginvoicelinediscount.Columns, sqlgraph.NewFieldSpec(billinginvoicelinediscount.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(billinginvoicelinediscount.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(billinginvoicelinediscount.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(billinginvoicelinediscount.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.InvoicingAppExternalID(); ok { + _spec.SetField(billinginvoicelinediscount.FieldInvoicingAppExternalID, field.TypeString, value) + } + if _u.mutation.InvoicingAppExternalIDCleared() { + _spec.ClearField(billinginvoicelinediscount.FieldInvoicingAppExternalID, field.TypeString) + } + if value, ok := _u.mutation.ChildUniqueReferenceID(); ok { + _spec.SetField(billinginvoicelinediscount.FieldChildUniqueReferenceID, field.TypeString, value) + } + if _u.mutation.ChildUniqueReferenceIDCleared() { + _spec.ClearField(billinginvoicelinediscount.FieldChildUniqueReferenceID, field.TypeString) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(billinginvoicelinediscount.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(billinginvoicelinediscount.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.Reason(); ok { + _spec.SetField(billinginvoicelinediscount.FieldReason, field.TypeEnum, value) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(billinginvoicelinediscount.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.RoundingAmount(); ok { + _spec.SetField(billinginvoicelinediscount.FieldRoundingAmount, field.TypeOther, value) + } + if _u.mutation.RoundingAmountCleared() { + _spec.ClearField(billinginvoicelinediscount.FieldRoundingAmount, field.TypeOther) + } + if value, ok := _u.mutation.SourceDiscount(); ok { + vv, err := billinginvoicelinediscount.ValueScanner.SourceDiscount.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(billinginvoicelinediscount.FieldSourceDiscount, field.TypeString, vv) + } + if _u.mutation.SourceDiscountCleared() { + _spec.ClearField(billinginvoicelinediscount.FieldSourceDiscount, field.TypeString) + } + if _u.mutation.BillingInvoiceLineCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicelinediscount.BillingInvoiceLineTable, + Columns: []string{billinginvoicelinediscount.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingInvoiceLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicelinediscount.BillingInvoiceLineTable, + Columns: []string{billinginvoicelinediscount.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.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{billinginvoicelinediscount.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// BillingInvoiceLineDiscountUpdateOne is the builder for updating a single BillingInvoiceLineDiscount entity. +type BillingInvoiceLineDiscountUpdateOne struct { + config + fields []string + hooks []Hook + mutation *BillingInvoiceLineDiscountMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *BillingInvoiceLineDiscountUpdateOne) SetUpdatedAt(v time.Time) *BillingInvoiceLineDiscountUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *BillingInvoiceLineDiscountUpdateOne) SetDeletedAt(v time.Time) *BillingInvoiceLineDiscountUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *BillingInvoiceLineDiscountUpdateOne) SetNillableDeletedAt(v *time.Time) *BillingInvoiceLineDiscountUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *BillingInvoiceLineDiscountUpdateOne) ClearDeletedAt() *BillingInvoiceLineDiscountUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (_u *BillingInvoiceLineDiscountUpdateOne) SetInvoicingAppExternalID(v string) *BillingInvoiceLineDiscountUpdateOne { + _u.mutation.SetInvoicingAppExternalID(v) + return _u +} + +// SetNillableInvoicingAppExternalID sets the "invoicing_app_external_id" field if the given value is not nil. +func (_u *BillingInvoiceLineDiscountUpdateOne) SetNillableInvoicingAppExternalID(v *string) *BillingInvoiceLineDiscountUpdateOne { + if v != nil { + _u.SetInvoicingAppExternalID(*v) + } + return _u +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (_u *BillingInvoiceLineDiscountUpdateOne) ClearInvoicingAppExternalID() *BillingInvoiceLineDiscountUpdateOne { + _u.mutation.ClearInvoicingAppExternalID() + return _u +} + +// SetLineID sets the "line_id" field. +func (_u *BillingInvoiceLineDiscountUpdateOne) SetLineID(v string) *BillingInvoiceLineDiscountUpdateOne { + _u.mutation.SetLineID(v) + return _u +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_u *BillingInvoiceLineDiscountUpdateOne) SetNillableLineID(v *string) *BillingInvoiceLineDiscountUpdateOne { + if v != nil { + _u.SetLineID(*v) + } + return _u +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (_u *BillingInvoiceLineDiscountUpdateOne) SetChildUniqueReferenceID(v string) *BillingInvoiceLineDiscountUpdateOne { + _u.mutation.SetChildUniqueReferenceID(v) + return _u +} + +// SetNillableChildUniqueReferenceID sets the "child_unique_reference_id" field if the given value is not nil. +func (_u *BillingInvoiceLineDiscountUpdateOne) SetNillableChildUniqueReferenceID(v *string) *BillingInvoiceLineDiscountUpdateOne { + if v != nil { + _u.SetChildUniqueReferenceID(*v) + } + return _u +} + +// ClearChildUniqueReferenceID clears the value of the "child_unique_reference_id" field. +func (_u *BillingInvoiceLineDiscountUpdateOne) ClearChildUniqueReferenceID() *BillingInvoiceLineDiscountUpdateOne { + _u.mutation.ClearChildUniqueReferenceID() + return _u +} + +// SetDescription sets the "description" field. +func (_u *BillingInvoiceLineDiscountUpdateOne) SetDescription(v string) *BillingInvoiceLineDiscountUpdateOne { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *BillingInvoiceLineDiscountUpdateOne) SetNillableDescription(v *string) *BillingInvoiceLineDiscountUpdateOne { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *BillingInvoiceLineDiscountUpdateOne) ClearDescription() *BillingInvoiceLineDiscountUpdateOne { + _u.mutation.ClearDescription() + return _u +} + +// SetReason sets the "reason" field. +func (_u *BillingInvoiceLineDiscountUpdateOne) SetReason(v billing.DiscountReasonType) *BillingInvoiceLineDiscountUpdateOne { + _u.mutation.SetReason(v) + return _u +} + +// SetNillableReason sets the "reason" field if the given value is not nil. +func (_u *BillingInvoiceLineDiscountUpdateOne) SetNillableReason(v *billing.DiscountReasonType) *BillingInvoiceLineDiscountUpdateOne { + if v != nil { + _u.SetReason(*v) + } + return _u +} + +// SetAmount sets the "amount" field. +func (_u *BillingInvoiceLineDiscountUpdateOne) SetAmount(v alpacadecimal.Decimal) *BillingInvoiceLineDiscountUpdateOne { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *BillingInvoiceLineDiscountUpdateOne) SetNillableAmount(v *alpacadecimal.Decimal) *BillingInvoiceLineDiscountUpdateOne { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetRoundingAmount sets the "rounding_amount" field. +func (_u *BillingInvoiceLineDiscountUpdateOne) SetRoundingAmount(v alpacadecimal.Decimal) *BillingInvoiceLineDiscountUpdateOne { + _u.mutation.SetRoundingAmount(v) + return _u +} + +// SetNillableRoundingAmount sets the "rounding_amount" field if the given value is not nil. +func (_u *BillingInvoiceLineDiscountUpdateOne) SetNillableRoundingAmount(v *alpacadecimal.Decimal) *BillingInvoiceLineDiscountUpdateOne { + if v != nil { + _u.SetRoundingAmount(*v) + } + return _u +} + +// ClearRoundingAmount clears the value of the "rounding_amount" field. +func (_u *BillingInvoiceLineDiscountUpdateOne) ClearRoundingAmount() *BillingInvoiceLineDiscountUpdateOne { + _u.mutation.ClearRoundingAmount() + return _u +} + +// SetSourceDiscount sets the "source_discount" field. +func (_u *BillingInvoiceLineDiscountUpdateOne) SetSourceDiscount(v *billing.DiscountReason) *BillingInvoiceLineDiscountUpdateOne { + _u.mutation.SetSourceDiscount(v) + return _u +} + +// ClearSourceDiscount clears the value of the "source_discount" field. +func (_u *BillingInvoiceLineDiscountUpdateOne) ClearSourceDiscount() *BillingInvoiceLineDiscountUpdateOne { + _u.mutation.ClearSourceDiscount() + return _u +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID. +func (_u *BillingInvoiceLineDiscountUpdateOne) SetBillingInvoiceLineID(id string) *BillingInvoiceLineDiscountUpdateOne { + _u.mutation.SetBillingInvoiceLineID(id) + return _u +} + +// SetBillingInvoiceLine sets the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *BillingInvoiceLineDiscountUpdateOne) SetBillingInvoiceLine(v *BillingInvoiceLine) *BillingInvoiceLineDiscountUpdateOne { + return _u.SetBillingInvoiceLineID(v.ID) +} + +// Mutation returns the BillingInvoiceLineDiscountMutation object of the builder. +func (_u *BillingInvoiceLineDiscountUpdateOne) Mutation() *BillingInvoiceLineDiscountMutation { + return _u.mutation +} + +// ClearBillingInvoiceLine clears the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *BillingInvoiceLineDiscountUpdateOne) ClearBillingInvoiceLine() *BillingInvoiceLineDiscountUpdateOne { + _u.mutation.ClearBillingInvoiceLine() + return _u +} + +// Where appends a list predicates to the BillingInvoiceLineDiscountUpdate builder. +func (_u *BillingInvoiceLineDiscountUpdateOne) Where(ps ...predicate.BillingInvoiceLineDiscount) *BillingInvoiceLineDiscountUpdateOne { + _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 *BillingInvoiceLineDiscountUpdateOne) Select(field string, fields ...string) *BillingInvoiceLineDiscountUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated BillingInvoiceLineDiscount entity. +func (_u *BillingInvoiceLineDiscountUpdateOne) Save(ctx context.Context) (*BillingInvoiceLineDiscount, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *BillingInvoiceLineDiscountUpdateOne) SaveX(ctx context.Context) *BillingInvoiceLineDiscount { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *BillingInvoiceLineDiscountUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingInvoiceLineDiscountUpdateOne) 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 *BillingInvoiceLineDiscountUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := billinginvoicelinediscount.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *BillingInvoiceLineDiscountUpdateOne) check() error { + if v, ok := _u.mutation.Reason(); ok { + if err := billinginvoicelinediscount.ReasonValidator(v); err != nil { + return &ValidationError{Name: "reason", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLineDiscount.reason": %w`, err)} + } + } + if v, ok := _u.mutation.SourceDiscount(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "source_discount", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLineDiscount.source_discount": %w`, err)} + } + } + if _u.mutation.BillingInvoiceLineCleared() && len(_u.mutation.BillingInvoiceLineIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "BillingInvoiceLineDiscount.billing_invoice_line"`) + } + return nil +} + +func (_u *BillingInvoiceLineDiscountUpdateOne) sqlSave(ctx context.Context) (_node *BillingInvoiceLineDiscount, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(billinginvoicelinediscount.Table, billinginvoicelinediscount.Columns, sqlgraph.NewFieldSpec(billinginvoicelinediscount.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "BillingInvoiceLineDiscount.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, billinginvoicelinediscount.FieldID) + for _, f := range fields { + if !billinginvoicelinediscount.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != billinginvoicelinediscount.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(billinginvoicelinediscount.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(billinginvoicelinediscount.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(billinginvoicelinediscount.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.InvoicingAppExternalID(); ok { + _spec.SetField(billinginvoicelinediscount.FieldInvoicingAppExternalID, field.TypeString, value) + } + if _u.mutation.InvoicingAppExternalIDCleared() { + _spec.ClearField(billinginvoicelinediscount.FieldInvoicingAppExternalID, field.TypeString) + } + if value, ok := _u.mutation.ChildUniqueReferenceID(); ok { + _spec.SetField(billinginvoicelinediscount.FieldChildUniqueReferenceID, field.TypeString, value) + } + if _u.mutation.ChildUniqueReferenceIDCleared() { + _spec.ClearField(billinginvoicelinediscount.FieldChildUniqueReferenceID, field.TypeString) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(billinginvoicelinediscount.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(billinginvoicelinediscount.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.Reason(); ok { + _spec.SetField(billinginvoicelinediscount.FieldReason, field.TypeEnum, value) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(billinginvoicelinediscount.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.RoundingAmount(); ok { + _spec.SetField(billinginvoicelinediscount.FieldRoundingAmount, field.TypeOther, value) + } + if _u.mutation.RoundingAmountCleared() { + _spec.ClearField(billinginvoicelinediscount.FieldRoundingAmount, field.TypeOther) + } + if value, ok := _u.mutation.SourceDiscount(); ok { + vv, err := billinginvoicelinediscount.ValueScanner.SourceDiscount.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(billinginvoicelinediscount.FieldSourceDiscount, field.TypeString, vv) + } + if _u.mutation.SourceDiscountCleared() { + _spec.ClearField(billinginvoicelinediscount.FieldSourceDiscount, field.TypeString) + } + if _u.mutation.BillingInvoiceLineCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicelinediscount.BillingInvoiceLineTable, + Columns: []string{billinginvoicelinediscount.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingInvoiceLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicelinediscount.BillingInvoiceLineTable, + Columns: []string{billinginvoicelinediscount.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &BillingInvoiceLineDiscount{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{billinginvoicelinediscount.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/ent/db/billinginvoicelineusagediscount.go b/ent/db/billinginvoicelineusagediscount.go new file mode 100644 index 0000000000000000000000000000000000000000..3f7f3e18e3d789f224b00a6daebd4a5f2e2e869e --- /dev/null +++ b/ent/db/billinginvoicelineusagediscount.go @@ -0,0 +1,279 @@ +// 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" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicelineusagediscount" +) + +// BillingInvoiceLineUsageDiscount is the model entity for the BillingInvoiceLineUsageDiscount schema. +type BillingInvoiceLineUsageDiscount 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"` + // InvoicingAppExternalID holds the value of the "invoicing_app_external_id" field. + InvoicingAppExternalID *string `json:"invoicing_app_external_id,omitempty"` + // LineID holds the value of the "line_id" field. + LineID string `json:"line_id,omitempty"` + // ChildUniqueReferenceID holds the value of the "child_unique_reference_id" field. + ChildUniqueReferenceID *string `json:"child_unique_reference_id,omitempty"` + // Description holds the value of the "description" field. + Description *string `json:"description,omitempty"` + // Reason holds the value of the "reason" field. + Reason billing.DiscountReasonType `json:"reason,omitempty"` + // Quantity holds the value of the "quantity" field. + Quantity alpacadecimal.Decimal `json:"quantity,omitempty"` + // PreLinePeriodQuantity holds the value of the "pre_line_period_quantity" field. + PreLinePeriodQuantity *alpacadecimal.Decimal `json:"pre_line_period_quantity,omitempty"` + // ReasonDetails holds the value of the "reason_details" field. + ReasonDetails *billing.DiscountReason `json:"reason_details,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the BillingInvoiceLineUsageDiscountQuery when eager-loading is set. + Edges BillingInvoiceLineUsageDiscountEdges `json:"edges"` + selectValues sql.SelectValues +} + +// BillingInvoiceLineUsageDiscountEdges holds the relations/edges for other nodes in the graph. +type BillingInvoiceLineUsageDiscountEdges struct { + // BillingInvoiceLine holds the value of the billing_invoice_line edge. + BillingInvoiceLine *BillingInvoiceLine `json:"billing_invoice_line,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// BillingInvoiceLineOrErr returns the BillingInvoiceLine value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e BillingInvoiceLineUsageDiscountEdges) BillingInvoiceLineOrErr() (*BillingInvoiceLine, error) { + if e.BillingInvoiceLine != nil { + return e.BillingInvoiceLine, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: billinginvoiceline.Label} + } + return nil, &NotLoadedError{edge: "billing_invoice_line"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*BillingInvoiceLineUsageDiscount) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case billinginvoicelineusagediscount.FieldPreLinePeriodQuantity: + values[i] = &sql.NullScanner{S: new(alpacadecimal.Decimal)} + case billinginvoicelineusagediscount.FieldQuantity: + values[i] = new(alpacadecimal.Decimal) + case billinginvoicelineusagediscount.FieldID, billinginvoicelineusagediscount.FieldNamespace, billinginvoicelineusagediscount.FieldInvoicingAppExternalID, billinginvoicelineusagediscount.FieldLineID, billinginvoicelineusagediscount.FieldChildUniqueReferenceID, billinginvoicelineusagediscount.FieldDescription, billinginvoicelineusagediscount.FieldReason: + values[i] = new(sql.NullString) + case billinginvoicelineusagediscount.FieldCreatedAt, billinginvoicelineusagediscount.FieldUpdatedAt, billinginvoicelineusagediscount.FieldDeletedAt: + values[i] = new(sql.NullTime) + case billinginvoicelineusagediscount.FieldReasonDetails: + values[i] = billinginvoicelineusagediscount.ValueScanner.ReasonDetails.ScanValue() + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the BillingInvoiceLineUsageDiscount fields. +func (_m *BillingInvoiceLineUsageDiscount) 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 billinginvoicelineusagediscount.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 billinginvoicelineusagediscount.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 billinginvoicelineusagediscount.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 billinginvoicelineusagediscount.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 billinginvoicelineusagediscount.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 billinginvoicelineusagediscount.FieldInvoicingAppExternalID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field invoicing_app_external_id", values[i]) + } else if value.Valid { + _m.InvoicingAppExternalID = new(string) + *_m.InvoicingAppExternalID = value.String + } + case billinginvoicelineusagediscount.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 billinginvoicelineusagediscount.FieldChildUniqueReferenceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field child_unique_reference_id", values[i]) + } else if value.Valid { + _m.ChildUniqueReferenceID = new(string) + *_m.ChildUniqueReferenceID = value.String + } + case billinginvoicelineusagediscount.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + _m.Description = new(string) + *_m.Description = value.String + } + case billinginvoicelineusagediscount.FieldReason: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field reason", values[i]) + } else if value.Valid { + _m.Reason = billing.DiscountReasonType(value.String) + } + case billinginvoicelineusagediscount.FieldQuantity: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field quantity", values[i]) + } else if value != nil { + _m.Quantity = *value + } + case billinginvoicelineusagediscount.FieldPreLinePeriodQuantity: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field pre_line_period_quantity", values[i]) + } else if value.Valid { + _m.PreLinePeriodQuantity = new(alpacadecimal.Decimal) + *_m.PreLinePeriodQuantity = *value.S.(*alpacadecimal.Decimal) + } + case billinginvoicelineusagediscount.FieldReasonDetails: + if value, err := billinginvoicelineusagediscount.ValueScanner.ReasonDetails.FromValue(values[i]); err != nil { + return err + } else { + _m.ReasonDetails = value + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the BillingInvoiceLineUsageDiscount. +// This includes values selected through modifiers, order, etc. +func (_m *BillingInvoiceLineUsageDiscount) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryBillingInvoiceLine queries the "billing_invoice_line" edge of the BillingInvoiceLineUsageDiscount entity. +func (_m *BillingInvoiceLineUsageDiscount) QueryBillingInvoiceLine() *BillingInvoiceLineQuery { + return NewBillingInvoiceLineUsageDiscountClient(_m.config).QueryBillingInvoiceLine(_m) +} + +// Update returns a builder for updating this BillingInvoiceLineUsageDiscount. +// Note that you need to call BillingInvoiceLineUsageDiscount.Unwrap() before calling this method if this BillingInvoiceLineUsageDiscount +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *BillingInvoiceLineUsageDiscount) Update() *BillingInvoiceLineUsageDiscountUpdateOne { + return NewBillingInvoiceLineUsageDiscountClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the BillingInvoiceLineUsageDiscount 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 *BillingInvoiceLineUsageDiscount) Unwrap() *BillingInvoiceLineUsageDiscount { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: BillingInvoiceLineUsageDiscount is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *BillingInvoiceLineUsageDiscount) String() string { + var builder strings.Builder + builder.WriteString("BillingInvoiceLineUsageDiscount(") + 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(", ") + if v := _m.InvoicingAppExternalID; v != nil { + builder.WriteString("invoicing_app_external_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("line_id=") + builder.WriteString(_m.LineID) + builder.WriteString(", ") + if v := _m.ChildUniqueReferenceID; v != nil { + builder.WriteString("child_unique_reference_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.Description; v != nil { + builder.WriteString("description=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("reason=") + builder.WriteString(fmt.Sprintf("%v", _m.Reason)) + builder.WriteString(", ") + builder.WriteString("quantity=") + builder.WriteString(fmt.Sprintf("%v", _m.Quantity)) + builder.WriteString(", ") + if v := _m.PreLinePeriodQuantity; v != nil { + builder.WriteString("pre_line_period_quantity=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.ReasonDetails; v != nil { + builder.WriteString("reason_details=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteByte(')') + return builder.String() +} + +// BillingInvoiceLineUsageDiscounts is a parsable slice of BillingInvoiceLineUsageDiscount. +type BillingInvoiceLineUsageDiscounts []*BillingInvoiceLineUsageDiscount diff --git a/ent/db/billinginvoicelineusagediscount/billinginvoicelineusagediscount.go b/ent/db/billinginvoicelineusagediscount/billinginvoicelineusagediscount.go new file mode 100644 index 0000000000000000000000000000000000000000..00066b17110e2ddb1cb6393fc07148450015fa0f --- /dev/null +++ b/ent/db/billinginvoicelineusagediscount/billinginvoicelineusagediscount.go @@ -0,0 +1,191 @@ +// Code generated by ent, DO NOT EDIT. + +package billinginvoicelineusagediscount + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/billing" +) + +const ( + // Label holds the string label denoting the billinginvoicelineusagediscount type in the database. + Label = "billing_invoice_line_usage_discount" + // 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" + // FieldInvoicingAppExternalID holds the string denoting the invoicing_app_external_id field in the database. + FieldInvoicingAppExternalID = "invoicing_app_external_id" + // FieldLineID holds the string denoting the line_id field in the database. + FieldLineID = "line_id" + // FieldChildUniqueReferenceID holds the string denoting the child_unique_reference_id field in the database. + FieldChildUniqueReferenceID = "child_unique_reference_id" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // FieldReason holds the string denoting the reason field in the database. + FieldReason = "reason" + // FieldQuantity holds the string denoting the quantity field in the database. + FieldQuantity = "quantity" + // FieldPreLinePeriodQuantity holds the string denoting the pre_line_period_quantity field in the database. + FieldPreLinePeriodQuantity = "pre_line_period_quantity" + // FieldReasonDetails holds the string denoting the reason_details field in the database. + FieldReasonDetails = "reason_details" + // EdgeBillingInvoiceLine holds the string denoting the billing_invoice_line edge name in mutations. + EdgeBillingInvoiceLine = "billing_invoice_line" + // Table holds the table name of the billinginvoicelineusagediscount in the database. + Table = "billing_invoice_line_usage_discounts" + // BillingInvoiceLineTable is the table that holds the billing_invoice_line relation/edge. + BillingInvoiceLineTable = "billing_invoice_line_usage_discounts" + // BillingInvoiceLineInverseTable is the table name for the BillingInvoiceLine entity. + // It exists in this package in order to avoid circular dependency with the "billinginvoiceline" package. + BillingInvoiceLineInverseTable = "billing_invoice_lines" + // BillingInvoiceLineColumn is the table column denoting the billing_invoice_line relation/edge. + BillingInvoiceLineColumn = "line_id" +) + +// Columns holds all SQL columns for billinginvoicelineusagediscount fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldInvoicingAppExternalID, + FieldLineID, + FieldChildUniqueReferenceID, + FieldDescription, + FieldReason, + FieldQuantity, + FieldPreLinePeriodQuantity, + FieldReasonDetails, +} + +// 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 + // ValueScanner of all BillingInvoiceLineUsageDiscount fields. + ValueScanner struct { + ReasonDetails field.TypeValueScanner[*billing.DiscountReason] + } +) + +// ReasonValidator is a validator for the "reason" field enum values. It is called by the builders before save. +func ReasonValidator(r billing.DiscountReasonType) error { + switch r { + case "maximum_spend", "ratecard_percentage", "ratecard_usage": + return nil + default: + return fmt.Errorf("billinginvoicelineusagediscount: invalid enum value for reason field: %q", r) + } +} + +// OrderOption defines the ordering options for the BillingInvoiceLineUsageDiscount 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() +} + +// ByInvoicingAppExternalID orders the results by the invoicing_app_external_id field. +func ByInvoicingAppExternalID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoicingAppExternalID, opts...).ToFunc() +} + +// ByLineID orders the results by the line_id field. +func ByLineID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLineID, opts...).ToFunc() +} + +// ByChildUniqueReferenceID orders the results by the child_unique_reference_id field. +func ByChildUniqueReferenceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChildUniqueReferenceID, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, opts...).ToFunc() +} + +// ByReason orders the results by the reason field. +func ByReason(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldReason, opts...).ToFunc() +} + +// ByQuantity orders the results by the quantity field. +func ByQuantity(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldQuantity, opts...).ToFunc() +} + +// ByPreLinePeriodQuantity orders the results by the pre_line_period_quantity field. +func ByPreLinePeriodQuantity(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPreLinePeriodQuantity, opts...).ToFunc() +} + +// ByReasonDetails orders the results by the reason_details field. +func ByReasonDetails(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldReasonDetails, opts...).ToFunc() +} + +// ByBillingInvoiceLineField orders the results by billing_invoice_line field. +func ByBillingInvoiceLineField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBillingInvoiceLineStep(), sql.OrderByField(field, opts...)) + } +} +func newBillingInvoiceLineStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BillingInvoiceLineInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, BillingInvoiceLineTable, BillingInvoiceLineColumn), + ) +} diff --git a/ent/db/billinginvoicelineusagediscount/where.go b/ent/db/billinginvoicelineusagediscount/where.go new file mode 100644 index 0000000000000000000000000000000000000000..02f2860ec51a0b923eb8cef724093914c8313b46 --- /dev/null +++ b/ent/db/billinginvoicelineusagediscount/where.go @@ -0,0 +1,771 @@ +// Code generated by ent, DO NOT EDIT. + +package billinginvoicelineusagediscount + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(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.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(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.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(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.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEQ(FieldDeletedAt, v)) +} + +// InvoicingAppExternalID applies equality check predicate on the "invoicing_app_external_id" field. It's identical to InvoicingAppExternalIDEQ. +func InvoicingAppExternalID(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEQ(FieldInvoicingAppExternalID, v)) +} + +// LineID applies equality check predicate on the "line_id" field. It's identical to LineIDEQ. +func LineID(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEQ(FieldLineID, v)) +} + +// ChildUniqueReferenceID applies equality check predicate on the "child_unique_reference_id" field. It's identical to ChildUniqueReferenceIDEQ. +func ChildUniqueReferenceID(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEQ(FieldChildUniqueReferenceID, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEQ(FieldDescription, v)) +} + +// Quantity applies equality check predicate on the "quantity" field. It's identical to QuantityEQ. +func Quantity(v alpacadecimal.Decimal) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEQ(FieldQuantity, v)) +} + +// PreLinePeriodQuantity applies equality check predicate on the "pre_line_period_quantity" field. It's identical to PreLinePeriodQuantityEQ. +func PreLinePeriodQuantity(v alpacadecimal.Decimal) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEQ(FieldPreLinePeriodQuantity, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNotNull(FieldDeletedAt)) +} + +// InvoicingAppExternalIDEQ applies the EQ predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDEQ(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEQ(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDNEQ applies the NEQ predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDNEQ(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNEQ(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDIn applies the In predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDIn(vs ...string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldIn(FieldInvoicingAppExternalID, vs...)) +} + +// InvoicingAppExternalIDNotIn applies the NotIn predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDNotIn(vs ...string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNotIn(FieldInvoicingAppExternalID, vs...)) +} + +// InvoicingAppExternalIDGT applies the GT predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDGT(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGT(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDGTE applies the GTE predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDGTE(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGTE(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDLT applies the LT predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDLT(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLT(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDLTE applies the LTE predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDLTE(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLTE(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDContains applies the Contains predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDContains(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldContains(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDHasPrefix applies the HasPrefix predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDHasPrefix(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldHasPrefix(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDHasSuffix applies the HasSuffix predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDHasSuffix(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldHasSuffix(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDIsNil applies the IsNil predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDIsNil() predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldIsNull(FieldInvoicingAppExternalID)) +} + +// InvoicingAppExternalIDNotNil applies the NotNil predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDNotNil() predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNotNull(FieldInvoicingAppExternalID)) +} + +// InvoicingAppExternalIDEqualFold applies the EqualFold predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDEqualFold(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEqualFold(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDContainsFold applies the ContainsFold predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDContainsFold(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldContainsFold(FieldInvoicingAppExternalID, v)) +} + +// LineIDEQ applies the EQ predicate on the "line_id" field. +func LineIDEQ(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEQ(FieldLineID, v)) +} + +// LineIDNEQ applies the NEQ predicate on the "line_id" field. +func LineIDNEQ(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNEQ(FieldLineID, v)) +} + +// LineIDIn applies the In predicate on the "line_id" field. +func LineIDIn(vs ...string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldIn(FieldLineID, vs...)) +} + +// LineIDNotIn applies the NotIn predicate on the "line_id" field. +func LineIDNotIn(vs ...string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNotIn(FieldLineID, vs...)) +} + +// LineIDGT applies the GT predicate on the "line_id" field. +func LineIDGT(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGT(FieldLineID, v)) +} + +// LineIDGTE applies the GTE predicate on the "line_id" field. +func LineIDGTE(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGTE(FieldLineID, v)) +} + +// LineIDLT applies the LT predicate on the "line_id" field. +func LineIDLT(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLT(FieldLineID, v)) +} + +// LineIDLTE applies the LTE predicate on the "line_id" field. +func LineIDLTE(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLTE(FieldLineID, v)) +} + +// LineIDContains applies the Contains predicate on the "line_id" field. +func LineIDContains(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldContains(FieldLineID, v)) +} + +// LineIDHasPrefix applies the HasPrefix predicate on the "line_id" field. +func LineIDHasPrefix(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldHasPrefix(FieldLineID, v)) +} + +// LineIDHasSuffix applies the HasSuffix predicate on the "line_id" field. +func LineIDHasSuffix(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldHasSuffix(FieldLineID, v)) +} + +// LineIDEqualFold applies the EqualFold predicate on the "line_id" field. +func LineIDEqualFold(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEqualFold(FieldLineID, v)) +} + +// LineIDContainsFold applies the ContainsFold predicate on the "line_id" field. +func LineIDContainsFold(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldContainsFold(FieldLineID, v)) +} + +// ChildUniqueReferenceIDEQ applies the EQ predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDEQ(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEQ(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDNEQ applies the NEQ predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDNEQ(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNEQ(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDIn applies the In predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDIn(vs ...string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldIn(FieldChildUniqueReferenceID, vs...)) +} + +// ChildUniqueReferenceIDNotIn applies the NotIn predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDNotIn(vs ...string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNotIn(FieldChildUniqueReferenceID, vs...)) +} + +// ChildUniqueReferenceIDGT applies the GT predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDGT(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGT(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDGTE applies the GTE predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDGTE(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGTE(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDLT applies the LT predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDLT(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLT(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDLTE applies the LTE predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDLTE(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLTE(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDContains applies the Contains predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDContains(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldContains(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDHasPrefix applies the HasPrefix predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDHasPrefix(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldHasPrefix(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDHasSuffix applies the HasSuffix predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDHasSuffix(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldHasSuffix(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDIsNil applies the IsNil predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDIsNil() predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldIsNull(FieldChildUniqueReferenceID)) +} + +// ChildUniqueReferenceIDNotNil applies the NotNil predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDNotNil() predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNotNull(FieldChildUniqueReferenceID)) +} + +// ChildUniqueReferenceIDEqualFold applies the EqualFold predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDEqualFold(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEqualFold(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDContainsFold applies the ContainsFold predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDContainsFold(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldContainsFold(FieldChildUniqueReferenceID, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldContainsFold(FieldDescription, v)) +} + +// ReasonEQ applies the EQ predicate on the "reason" field. +func ReasonEQ(v billing.DiscountReasonType) predicate.BillingInvoiceLineUsageDiscount { + vc := v + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEQ(FieldReason, vc)) +} + +// ReasonNEQ applies the NEQ predicate on the "reason" field. +func ReasonNEQ(v billing.DiscountReasonType) predicate.BillingInvoiceLineUsageDiscount { + vc := v + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNEQ(FieldReason, vc)) +} + +// ReasonIn applies the In predicate on the "reason" field. +func ReasonIn(vs ...billing.DiscountReasonType) predicate.BillingInvoiceLineUsageDiscount { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldIn(FieldReason, v...)) +} + +// ReasonNotIn applies the NotIn predicate on the "reason" field. +func ReasonNotIn(vs ...billing.DiscountReasonType) predicate.BillingInvoiceLineUsageDiscount { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNotIn(FieldReason, v...)) +} + +// QuantityEQ applies the EQ predicate on the "quantity" field. +func QuantityEQ(v alpacadecimal.Decimal) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEQ(FieldQuantity, v)) +} + +// QuantityNEQ applies the NEQ predicate on the "quantity" field. +func QuantityNEQ(v alpacadecimal.Decimal) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNEQ(FieldQuantity, v)) +} + +// QuantityIn applies the In predicate on the "quantity" field. +func QuantityIn(vs ...alpacadecimal.Decimal) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldIn(FieldQuantity, vs...)) +} + +// QuantityNotIn applies the NotIn predicate on the "quantity" field. +func QuantityNotIn(vs ...alpacadecimal.Decimal) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNotIn(FieldQuantity, vs...)) +} + +// QuantityGT applies the GT predicate on the "quantity" field. +func QuantityGT(v alpacadecimal.Decimal) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGT(FieldQuantity, v)) +} + +// QuantityGTE applies the GTE predicate on the "quantity" field. +func QuantityGTE(v alpacadecimal.Decimal) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGTE(FieldQuantity, v)) +} + +// QuantityLT applies the LT predicate on the "quantity" field. +func QuantityLT(v alpacadecimal.Decimal) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLT(FieldQuantity, v)) +} + +// QuantityLTE applies the LTE predicate on the "quantity" field. +func QuantityLTE(v alpacadecimal.Decimal) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLTE(FieldQuantity, v)) +} + +// PreLinePeriodQuantityEQ applies the EQ predicate on the "pre_line_period_quantity" field. +func PreLinePeriodQuantityEQ(v alpacadecimal.Decimal) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldEQ(FieldPreLinePeriodQuantity, v)) +} + +// PreLinePeriodQuantityNEQ applies the NEQ predicate on the "pre_line_period_quantity" field. +func PreLinePeriodQuantityNEQ(v alpacadecimal.Decimal) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNEQ(FieldPreLinePeriodQuantity, v)) +} + +// PreLinePeriodQuantityIn applies the In predicate on the "pre_line_period_quantity" field. +func PreLinePeriodQuantityIn(vs ...alpacadecimal.Decimal) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldIn(FieldPreLinePeriodQuantity, vs...)) +} + +// PreLinePeriodQuantityNotIn applies the NotIn predicate on the "pre_line_period_quantity" field. +func PreLinePeriodQuantityNotIn(vs ...alpacadecimal.Decimal) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNotIn(FieldPreLinePeriodQuantity, vs...)) +} + +// PreLinePeriodQuantityGT applies the GT predicate on the "pre_line_period_quantity" field. +func PreLinePeriodQuantityGT(v alpacadecimal.Decimal) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGT(FieldPreLinePeriodQuantity, v)) +} + +// PreLinePeriodQuantityGTE applies the GTE predicate on the "pre_line_period_quantity" field. +func PreLinePeriodQuantityGTE(v alpacadecimal.Decimal) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldGTE(FieldPreLinePeriodQuantity, v)) +} + +// PreLinePeriodQuantityLT applies the LT predicate on the "pre_line_period_quantity" field. +func PreLinePeriodQuantityLT(v alpacadecimal.Decimal) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLT(FieldPreLinePeriodQuantity, v)) +} + +// PreLinePeriodQuantityLTE applies the LTE predicate on the "pre_line_period_quantity" field. +func PreLinePeriodQuantityLTE(v alpacadecimal.Decimal) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldLTE(FieldPreLinePeriodQuantity, v)) +} + +// PreLinePeriodQuantityIsNil applies the IsNil predicate on the "pre_line_period_quantity" field. +func PreLinePeriodQuantityIsNil() predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldIsNull(FieldPreLinePeriodQuantity)) +} + +// PreLinePeriodQuantityNotNil applies the NotNil predicate on the "pre_line_period_quantity" field. +func PreLinePeriodQuantityNotNil() predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNotNull(FieldPreLinePeriodQuantity)) +} + +// ReasonDetailsIsNil applies the IsNil predicate on the "reason_details" field. +func ReasonDetailsIsNil() predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldIsNull(FieldReasonDetails)) +} + +// ReasonDetailsNotNil applies the NotNil predicate on the "reason_details" field. +func ReasonDetailsNotNil() predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.FieldNotNull(FieldReasonDetails)) +} + +// HasBillingInvoiceLine applies the HasEdge predicate on the "billing_invoice_line" edge. +func HasBillingInvoiceLine() predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, BillingInvoiceLineTable, BillingInvoiceLineColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBillingInvoiceLineWith applies the HasEdge predicate on the "billing_invoice_line" edge with a given conditions (other predicates). +func HasBillingInvoiceLineWith(preds ...predicate.BillingInvoiceLine) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(func(s *sql.Selector) { + step := newBillingInvoiceLineStep() + 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.BillingInvoiceLineUsageDiscount) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.BillingInvoiceLineUsageDiscount) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.BillingInvoiceLineUsageDiscount) predicate.BillingInvoiceLineUsageDiscount { + return predicate.BillingInvoiceLineUsageDiscount(sql.NotPredicates(p)) +} diff --git a/ent/db/billinginvoicelineusagediscount_create.go b/ent/db/billinginvoicelineusagediscount_create.go new file mode 100644 index 0000000000000000000000000000000000000000..df79473ff83c8b48736714dbb6553f0ee5d17ddc --- /dev/null +++ b/ent/db/billinginvoicelineusagediscount_create.go @@ -0,0 +1,1244 @@ +// 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" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicelineusagediscount" +) + +// BillingInvoiceLineUsageDiscountCreate is the builder for creating a BillingInvoiceLineUsageDiscount entity. +type BillingInvoiceLineUsageDiscountCreate struct { + config + mutation *BillingInvoiceLineUsageDiscountMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetNamespace(v string) *BillingInvoiceLineUsageDiscountCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetCreatedAt(v time.Time) *BillingInvoiceLineUsageDiscountCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetNillableCreatedAt(v *time.Time) *BillingInvoiceLineUsageDiscountCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetUpdatedAt(v time.Time) *BillingInvoiceLineUsageDiscountCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetNillableUpdatedAt(v *time.Time) *BillingInvoiceLineUsageDiscountCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetDeletedAt(v time.Time) *BillingInvoiceLineUsageDiscountCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetNillableDeletedAt(v *time.Time) *BillingInvoiceLineUsageDiscountCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetInvoicingAppExternalID(v string) *BillingInvoiceLineUsageDiscountCreate { + _c.mutation.SetInvoicingAppExternalID(v) + return _c +} + +// SetNillableInvoicingAppExternalID sets the "invoicing_app_external_id" field if the given value is not nil. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetNillableInvoicingAppExternalID(v *string) *BillingInvoiceLineUsageDiscountCreate { + if v != nil { + _c.SetInvoicingAppExternalID(*v) + } + return _c +} + +// SetLineID sets the "line_id" field. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetLineID(v string) *BillingInvoiceLineUsageDiscountCreate { + _c.mutation.SetLineID(v) + return _c +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetChildUniqueReferenceID(v string) *BillingInvoiceLineUsageDiscountCreate { + _c.mutation.SetChildUniqueReferenceID(v) + return _c +} + +// SetNillableChildUniqueReferenceID sets the "child_unique_reference_id" field if the given value is not nil. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetNillableChildUniqueReferenceID(v *string) *BillingInvoiceLineUsageDiscountCreate { + if v != nil { + _c.SetChildUniqueReferenceID(*v) + } + return _c +} + +// SetDescription sets the "description" field. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetDescription(v string) *BillingInvoiceLineUsageDiscountCreate { + _c.mutation.SetDescription(v) + return _c +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetNillableDescription(v *string) *BillingInvoiceLineUsageDiscountCreate { + if v != nil { + _c.SetDescription(*v) + } + return _c +} + +// SetReason sets the "reason" field. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetReason(v billing.DiscountReasonType) *BillingInvoiceLineUsageDiscountCreate { + _c.mutation.SetReason(v) + return _c +} + +// SetQuantity sets the "quantity" field. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetQuantity(v alpacadecimal.Decimal) *BillingInvoiceLineUsageDiscountCreate { + _c.mutation.SetQuantity(v) + return _c +} + +// SetPreLinePeriodQuantity sets the "pre_line_period_quantity" field. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetPreLinePeriodQuantity(v alpacadecimal.Decimal) *BillingInvoiceLineUsageDiscountCreate { + _c.mutation.SetPreLinePeriodQuantity(v) + return _c +} + +// SetNillablePreLinePeriodQuantity sets the "pre_line_period_quantity" field if the given value is not nil. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetNillablePreLinePeriodQuantity(v *alpacadecimal.Decimal) *BillingInvoiceLineUsageDiscountCreate { + if v != nil { + _c.SetPreLinePeriodQuantity(*v) + } + return _c +} + +// SetReasonDetails sets the "reason_details" field. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetReasonDetails(v *billing.DiscountReason) *BillingInvoiceLineUsageDiscountCreate { + _c.mutation.SetReasonDetails(v) + return _c +} + +// SetID sets the "id" field. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetID(v string) *BillingInvoiceLineUsageDiscountCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetNillableID(v *string) *BillingInvoiceLineUsageDiscountCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetBillingInvoiceLineID(id string) *BillingInvoiceLineUsageDiscountCreate { + _c.mutation.SetBillingInvoiceLineID(id) + return _c +} + +// SetBillingInvoiceLine sets the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_c *BillingInvoiceLineUsageDiscountCreate) SetBillingInvoiceLine(v *BillingInvoiceLine) *BillingInvoiceLineUsageDiscountCreate { + return _c.SetBillingInvoiceLineID(v.ID) +} + +// Mutation returns the BillingInvoiceLineUsageDiscountMutation object of the builder. +func (_c *BillingInvoiceLineUsageDiscountCreate) Mutation() *BillingInvoiceLineUsageDiscountMutation { + return _c.mutation +} + +// Save creates the BillingInvoiceLineUsageDiscount in the database. +func (_c *BillingInvoiceLineUsageDiscountCreate) Save(ctx context.Context) (*BillingInvoiceLineUsageDiscount, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *BillingInvoiceLineUsageDiscountCreate) SaveX(ctx context.Context) *BillingInvoiceLineUsageDiscount { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingInvoiceLineUsageDiscountCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingInvoiceLineUsageDiscountCreate) 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 *BillingInvoiceLineUsageDiscountCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := billinginvoicelineusagediscount.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := billinginvoicelineusagediscount.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := billinginvoicelineusagediscount.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *BillingInvoiceLineUsageDiscountCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "BillingInvoiceLineUsageDiscount.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := billinginvoicelineusagediscount.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLineUsageDiscount.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "BillingInvoiceLineUsageDiscount.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "BillingInvoiceLineUsageDiscount.updated_at"`)} + } + if _, ok := _c.mutation.LineID(); !ok { + return &ValidationError{Name: "line_id", err: errors.New(`db: missing required field "BillingInvoiceLineUsageDiscount.line_id"`)} + } + if _, ok := _c.mutation.Reason(); !ok { + return &ValidationError{Name: "reason", err: errors.New(`db: missing required field "BillingInvoiceLineUsageDiscount.reason"`)} + } + if v, ok := _c.mutation.Reason(); ok { + if err := billinginvoicelineusagediscount.ReasonValidator(v); err != nil { + return &ValidationError{Name: "reason", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLineUsageDiscount.reason": %w`, err)} + } + } + if _, ok := _c.mutation.Quantity(); !ok { + return &ValidationError{Name: "quantity", err: errors.New(`db: missing required field "BillingInvoiceLineUsageDiscount.quantity"`)} + } + if v, ok := _c.mutation.ReasonDetails(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "reason_details", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLineUsageDiscount.reason_details": %w`, err)} + } + } + if len(_c.mutation.BillingInvoiceLineIDs()) == 0 { + return &ValidationError{Name: "billing_invoice_line", err: errors.New(`db: missing required edge "BillingInvoiceLineUsageDiscount.billing_invoice_line"`)} + } + return nil +} + +func (_c *BillingInvoiceLineUsageDiscountCreate) sqlSave(ctx context.Context) (*BillingInvoiceLineUsageDiscount, 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 BillingInvoiceLineUsageDiscount.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *BillingInvoiceLineUsageDiscountCreate) createSpec() (*BillingInvoiceLineUsageDiscount, *sqlgraph.CreateSpec, error) { + var ( + _node = &BillingInvoiceLineUsageDiscount{config: _c.config} + _spec = sqlgraph.NewCreateSpec(billinginvoicelineusagediscount.Table, sqlgraph.NewFieldSpec(billinginvoicelineusagediscount.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(billinginvoicelineusagediscount.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.InvoicingAppExternalID(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldInvoicingAppExternalID, field.TypeString, value) + _node.InvoicingAppExternalID = &value + } + if value, ok := _c.mutation.ChildUniqueReferenceID(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldChildUniqueReferenceID, field.TypeString, value) + _node.ChildUniqueReferenceID = &value + } + if value, ok := _c.mutation.Description(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldDescription, field.TypeString, value) + _node.Description = &value + } + if value, ok := _c.mutation.Reason(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldReason, field.TypeEnum, value) + _node.Reason = value + } + if value, ok := _c.mutation.Quantity(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldQuantity, field.TypeOther, value) + _node.Quantity = value + } + if value, ok := _c.mutation.PreLinePeriodQuantity(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldPreLinePeriodQuantity, field.TypeOther, value) + _node.PreLinePeriodQuantity = &value + } + if value, ok := _c.mutation.ReasonDetails(); ok { + vv, err := billinginvoicelineusagediscount.ValueScanner.ReasonDetails.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(billinginvoicelineusagediscount.FieldReasonDetails, field.TypeString, vv) + _node.ReasonDetails = value + } + if nodes := _c.mutation.BillingInvoiceLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicelineusagediscount.BillingInvoiceLineTable, + Columns: []string{billinginvoicelineusagediscount.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.LineID = nodes[0] + _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.BillingInvoiceLineUsageDiscount.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.BillingInvoiceLineUsageDiscountUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *BillingInvoiceLineUsageDiscountCreate) OnConflict(opts ...sql.ConflictOption) *BillingInvoiceLineUsageDiscountUpsertOne { + _c.conflict = opts + return &BillingInvoiceLineUsageDiscountUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingInvoiceLineUsageDiscount.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingInvoiceLineUsageDiscountCreate) OnConflictColumns(columns ...string) *BillingInvoiceLineUsageDiscountUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingInvoiceLineUsageDiscountUpsertOne{ + create: _c, + } +} + +type ( + // BillingInvoiceLineUsageDiscountUpsertOne is the builder for "upsert"-ing + // one BillingInvoiceLineUsageDiscount node. + BillingInvoiceLineUsageDiscountUpsertOne struct { + create *BillingInvoiceLineUsageDiscountCreate + } + + // BillingInvoiceLineUsageDiscountUpsert is the "OnConflict" setter. + BillingInvoiceLineUsageDiscountUpsert struct { + *sql.UpdateSet + } +) + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingInvoiceLineUsageDiscountUpsert) SetUpdatedAt(v time.Time) *BillingInvoiceLineUsageDiscountUpsert { + u.Set(billinginvoicelineusagediscount.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsert) UpdateUpdatedAt() *BillingInvoiceLineUsageDiscountUpsert { + u.SetExcluded(billinginvoicelineusagediscount.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingInvoiceLineUsageDiscountUpsert) SetDeletedAt(v time.Time) *BillingInvoiceLineUsageDiscountUpsert { + u.Set(billinginvoicelineusagediscount.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsert) UpdateDeletedAt() *BillingInvoiceLineUsageDiscountUpsert { + u.SetExcluded(billinginvoicelineusagediscount.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingInvoiceLineUsageDiscountUpsert) ClearDeletedAt() *BillingInvoiceLineUsageDiscountUpsert { + u.SetNull(billinginvoicelineusagediscount.FieldDeletedAt) + return u +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (u *BillingInvoiceLineUsageDiscountUpsert) SetInvoicingAppExternalID(v string) *BillingInvoiceLineUsageDiscountUpsert { + u.Set(billinginvoicelineusagediscount.FieldInvoicingAppExternalID, v) + return u +} + +// UpdateInvoicingAppExternalID sets the "invoicing_app_external_id" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsert) UpdateInvoicingAppExternalID() *BillingInvoiceLineUsageDiscountUpsert { + u.SetExcluded(billinginvoicelineusagediscount.FieldInvoicingAppExternalID) + return u +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (u *BillingInvoiceLineUsageDiscountUpsert) ClearInvoicingAppExternalID() *BillingInvoiceLineUsageDiscountUpsert { + u.SetNull(billinginvoicelineusagediscount.FieldInvoicingAppExternalID) + return u +} + +// SetLineID sets the "line_id" field. +func (u *BillingInvoiceLineUsageDiscountUpsert) SetLineID(v string) *BillingInvoiceLineUsageDiscountUpsert { + u.Set(billinginvoicelineusagediscount.FieldLineID, v) + return u +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsert) UpdateLineID() *BillingInvoiceLineUsageDiscountUpsert { + u.SetExcluded(billinginvoicelineusagediscount.FieldLineID) + return u +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (u *BillingInvoiceLineUsageDiscountUpsert) SetChildUniqueReferenceID(v string) *BillingInvoiceLineUsageDiscountUpsert { + u.Set(billinginvoicelineusagediscount.FieldChildUniqueReferenceID, v) + return u +} + +// UpdateChildUniqueReferenceID sets the "child_unique_reference_id" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsert) UpdateChildUniqueReferenceID() *BillingInvoiceLineUsageDiscountUpsert { + u.SetExcluded(billinginvoicelineusagediscount.FieldChildUniqueReferenceID) + return u +} + +// ClearChildUniqueReferenceID clears the value of the "child_unique_reference_id" field. +func (u *BillingInvoiceLineUsageDiscountUpsert) ClearChildUniqueReferenceID() *BillingInvoiceLineUsageDiscountUpsert { + u.SetNull(billinginvoicelineusagediscount.FieldChildUniqueReferenceID) + return u +} + +// SetDescription sets the "description" field. +func (u *BillingInvoiceLineUsageDiscountUpsert) SetDescription(v string) *BillingInvoiceLineUsageDiscountUpsert { + u.Set(billinginvoicelineusagediscount.FieldDescription, v) + return u +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsert) UpdateDescription() *BillingInvoiceLineUsageDiscountUpsert { + u.SetExcluded(billinginvoicelineusagediscount.FieldDescription) + return u +} + +// ClearDescription clears the value of the "description" field. +func (u *BillingInvoiceLineUsageDiscountUpsert) ClearDescription() *BillingInvoiceLineUsageDiscountUpsert { + u.SetNull(billinginvoicelineusagediscount.FieldDescription) + return u +} + +// SetReason sets the "reason" field. +func (u *BillingInvoiceLineUsageDiscountUpsert) SetReason(v billing.DiscountReasonType) *BillingInvoiceLineUsageDiscountUpsert { + u.Set(billinginvoicelineusagediscount.FieldReason, v) + return u +} + +// UpdateReason sets the "reason" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsert) UpdateReason() *BillingInvoiceLineUsageDiscountUpsert { + u.SetExcluded(billinginvoicelineusagediscount.FieldReason) + return u +} + +// SetQuantity sets the "quantity" field. +func (u *BillingInvoiceLineUsageDiscountUpsert) SetQuantity(v alpacadecimal.Decimal) *BillingInvoiceLineUsageDiscountUpsert { + u.Set(billinginvoicelineusagediscount.FieldQuantity, v) + return u +} + +// UpdateQuantity sets the "quantity" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsert) UpdateQuantity() *BillingInvoiceLineUsageDiscountUpsert { + u.SetExcluded(billinginvoicelineusagediscount.FieldQuantity) + return u +} + +// SetPreLinePeriodQuantity sets the "pre_line_period_quantity" field. +func (u *BillingInvoiceLineUsageDiscountUpsert) SetPreLinePeriodQuantity(v alpacadecimal.Decimal) *BillingInvoiceLineUsageDiscountUpsert { + u.Set(billinginvoicelineusagediscount.FieldPreLinePeriodQuantity, v) + return u +} + +// UpdatePreLinePeriodQuantity sets the "pre_line_period_quantity" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsert) UpdatePreLinePeriodQuantity() *BillingInvoiceLineUsageDiscountUpsert { + u.SetExcluded(billinginvoicelineusagediscount.FieldPreLinePeriodQuantity) + return u +} + +// ClearPreLinePeriodQuantity clears the value of the "pre_line_period_quantity" field. +func (u *BillingInvoiceLineUsageDiscountUpsert) ClearPreLinePeriodQuantity() *BillingInvoiceLineUsageDiscountUpsert { + u.SetNull(billinginvoicelineusagediscount.FieldPreLinePeriodQuantity) + return u +} + +// SetReasonDetails sets the "reason_details" field. +func (u *BillingInvoiceLineUsageDiscountUpsert) SetReasonDetails(v *billing.DiscountReason) *BillingInvoiceLineUsageDiscountUpsert { + u.Set(billinginvoicelineusagediscount.FieldReasonDetails, v) + return u +} + +// UpdateReasonDetails sets the "reason_details" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsert) UpdateReasonDetails() *BillingInvoiceLineUsageDiscountUpsert { + u.SetExcluded(billinginvoicelineusagediscount.FieldReasonDetails) + return u +} + +// ClearReasonDetails clears the value of the "reason_details" field. +func (u *BillingInvoiceLineUsageDiscountUpsert) ClearReasonDetails() *BillingInvoiceLineUsageDiscountUpsert { + u.SetNull(billinginvoicelineusagediscount.FieldReasonDetails) + 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.BillingInvoiceLineUsageDiscount.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(billinginvoicelineusagediscount.FieldID) +// }), +// ). +// Exec(ctx) +func (u *BillingInvoiceLineUsageDiscountUpsertOne) UpdateNewValues() *BillingInvoiceLineUsageDiscountUpsertOne { + 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(billinginvoicelineusagediscount.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(billinginvoicelineusagediscount.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(billinginvoicelineusagediscount.FieldCreatedAt) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingInvoiceLineUsageDiscount.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingInvoiceLineUsageDiscountUpsertOne) Ignore() *BillingInvoiceLineUsageDiscountUpsertOne { + 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 *BillingInvoiceLineUsageDiscountUpsertOne) DoNothing() *BillingInvoiceLineUsageDiscountUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingInvoiceLineUsageDiscountCreate.OnConflict +// documentation for more info. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) Update(set func(*BillingInvoiceLineUsageDiscountUpsert)) *BillingInvoiceLineUsageDiscountUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingInvoiceLineUsageDiscountUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) SetUpdatedAt(v time.Time) *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) UpdateUpdatedAt() *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) SetDeletedAt(v time.Time) *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) UpdateDeletedAt() *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) ClearDeletedAt() *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.ClearDeletedAt() + }) +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) SetInvoicingAppExternalID(v string) *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.SetInvoicingAppExternalID(v) + }) +} + +// UpdateInvoicingAppExternalID sets the "invoicing_app_external_id" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) UpdateInvoicingAppExternalID() *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.UpdateInvoicingAppExternalID() + }) +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) ClearInvoicingAppExternalID() *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.ClearInvoicingAppExternalID() + }) +} + +// SetLineID sets the "line_id" field. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) SetLineID(v string) *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.SetLineID(v) + }) +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) UpdateLineID() *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.UpdateLineID() + }) +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) SetChildUniqueReferenceID(v string) *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.SetChildUniqueReferenceID(v) + }) +} + +// UpdateChildUniqueReferenceID sets the "child_unique_reference_id" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) UpdateChildUniqueReferenceID() *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.UpdateChildUniqueReferenceID() + }) +} + +// ClearChildUniqueReferenceID clears the value of the "child_unique_reference_id" field. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) ClearChildUniqueReferenceID() *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.ClearChildUniqueReferenceID() + }) +} + +// SetDescription sets the "description" field. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) SetDescription(v string) *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) UpdateDescription() *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) ClearDescription() *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.ClearDescription() + }) +} + +// SetReason sets the "reason" field. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) SetReason(v billing.DiscountReasonType) *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.SetReason(v) + }) +} + +// UpdateReason sets the "reason" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) UpdateReason() *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.UpdateReason() + }) +} + +// SetQuantity sets the "quantity" field. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) SetQuantity(v alpacadecimal.Decimal) *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.SetQuantity(v) + }) +} + +// UpdateQuantity sets the "quantity" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) UpdateQuantity() *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.UpdateQuantity() + }) +} + +// SetPreLinePeriodQuantity sets the "pre_line_period_quantity" field. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) SetPreLinePeriodQuantity(v alpacadecimal.Decimal) *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.SetPreLinePeriodQuantity(v) + }) +} + +// UpdatePreLinePeriodQuantity sets the "pre_line_period_quantity" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) UpdatePreLinePeriodQuantity() *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.UpdatePreLinePeriodQuantity() + }) +} + +// ClearPreLinePeriodQuantity clears the value of the "pre_line_period_quantity" field. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) ClearPreLinePeriodQuantity() *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.ClearPreLinePeriodQuantity() + }) +} + +// SetReasonDetails sets the "reason_details" field. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) SetReasonDetails(v *billing.DiscountReason) *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.SetReasonDetails(v) + }) +} + +// UpdateReasonDetails sets the "reason_details" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) UpdateReasonDetails() *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.UpdateReasonDetails() + }) +} + +// ClearReasonDetails clears the value of the "reason_details" field. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) ClearReasonDetails() *BillingInvoiceLineUsageDiscountUpsertOne { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.ClearReasonDetails() + }) +} + +// Exec executes the query. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingInvoiceLineUsageDiscountCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingInvoiceLineUsageDiscountUpsertOne) 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 *BillingInvoiceLineUsageDiscountUpsertOne) 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: BillingInvoiceLineUsageDiscountUpsertOne.ID is not supported by MySQL driver. Use BillingInvoiceLineUsageDiscountUpsertOne.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 *BillingInvoiceLineUsageDiscountUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// BillingInvoiceLineUsageDiscountCreateBulk is the builder for creating many BillingInvoiceLineUsageDiscount entities in bulk. +type BillingInvoiceLineUsageDiscountCreateBulk struct { + config + err error + builders []*BillingInvoiceLineUsageDiscountCreate + conflict []sql.ConflictOption +} + +// Save creates the BillingInvoiceLineUsageDiscount entities in the database. +func (_c *BillingInvoiceLineUsageDiscountCreateBulk) Save(ctx context.Context) ([]*BillingInvoiceLineUsageDiscount, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*BillingInvoiceLineUsageDiscount, 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.(*BillingInvoiceLineUsageDiscountMutation) + 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 *BillingInvoiceLineUsageDiscountCreateBulk) SaveX(ctx context.Context) []*BillingInvoiceLineUsageDiscount { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingInvoiceLineUsageDiscountCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingInvoiceLineUsageDiscountCreateBulk) 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.BillingInvoiceLineUsageDiscount.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.BillingInvoiceLineUsageDiscountUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *BillingInvoiceLineUsageDiscountCreateBulk) OnConflict(opts ...sql.ConflictOption) *BillingInvoiceLineUsageDiscountUpsertBulk { + _c.conflict = opts + return &BillingInvoiceLineUsageDiscountUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingInvoiceLineUsageDiscount.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingInvoiceLineUsageDiscountCreateBulk) OnConflictColumns(columns ...string) *BillingInvoiceLineUsageDiscountUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingInvoiceLineUsageDiscountUpsertBulk{ + create: _c, + } +} + +// BillingInvoiceLineUsageDiscountUpsertBulk is the builder for "upsert"-ing +// a bulk of BillingInvoiceLineUsageDiscount nodes. +type BillingInvoiceLineUsageDiscountUpsertBulk struct { + create *BillingInvoiceLineUsageDiscountCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.BillingInvoiceLineUsageDiscount.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(billinginvoicelineusagediscount.FieldID) +// }), +// ). +// Exec(ctx) +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) UpdateNewValues() *BillingInvoiceLineUsageDiscountUpsertBulk { + 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(billinginvoicelineusagediscount.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(billinginvoicelineusagediscount.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(billinginvoicelineusagediscount.FieldCreatedAt) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingInvoiceLineUsageDiscount.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) Ignore() *BillingInvoiceLineUsageDiscountUpsertBulk { + 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 *BillingInvoiceLineUsageDiscountUpsertBulk) DoNothing() *BillingInvoiceLineUsageDiscountUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingInvoiceLineUsageDiscountCreateBulk.OnConflict +// documentation for more info. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) Update(set func(*BillingInvoiceLineUsageDiscountUpsert)) *BillingInvoiceLineUsageDiscountUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingInvoiceLineUsageDiscountUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) SetUpdatedAt(v time.Time) *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) UpdateUpdatedAt() *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) SetDeletedAt(v time.Time) *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) UpdateDeletedAt() *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) ClearDeletedAt() *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.ClearDeletedAt() + }) +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) SetInvoicingAppExternalID(v string) *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.SetInvoicingAppExternalID(v) + }) +} + +// UpdateInvoicingAppExternalID sets the "invoicing_app_external_id" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) UpdateInvoicingAppExternalID() *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.UpdateInvoicingAppExternalID() + }) +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) ClearInvoicingAppExternalID() *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.ClearInvoicingAppExternalID() + }) +} + +// SetLineID sets the "line_id" field. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) SetLineID(v string) *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.SetLineID(v) + }) +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) UpdateLineID() *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.UpdateLineID() + }) +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) SetChildUniqueReferenceID(v string) *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.SetChildUniqueReferenceID(v) + }) +} + +// UpdateChildUniqueReferenceID sets the "child_unique_reference_id" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) UpdateChildUniqueReferenceID() *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.UpdateChildUniqueReferenceID() + }) +} + +// ClearChildUniqueReferenceID clears the value of the "child_unique_reference_id" field. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) ClearChildUniqueReferenceID() *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.ClearChildUniqueReferenceID() + }) +} + +// SetDescription sets the "description" field. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) SetDescription(v string) *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) UpdateDescription() *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) ClearDescription() *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.ClearDescription() + }) +} + +// SetReason sets the "reason" field. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) SetReason(v billing.DiscountReasonType) *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.SetReason(v) + }) +} + +// UpdateReason sets the "reason" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) UpdateReason() *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.UpdateReason() + }) +} + +// SetQuantity sets the "quantity" field. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) SetQuantity(v alpacadecimal.Decimal) *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.SetQuantity(v) + }) +} + +// UpdateQuantity sets the "quantity" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) UpdateQuantity() *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.UpdateQuantity() + }) +} + +// SetPreLinePeriodQuantity sets the "pre_line_period_quantity" field. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) SetPreLinePeriodQuantity(v alpacadecimal.Decimal) *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.SetPreLinePeriodQuantity(v) + }) +} + +// UpdatePreLinePeriodQuantity sets the "pre_line_period_quantity" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) UpdatePreLinePeriodQuantity() *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.UpdatePreLinePeriodQuantity() + }) +} + +// ClearPreLinePeriodQuantity clears the value of the "pre_line_period_quantity" field. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) ClearPreLinePeriodQuantity() *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.ClearPreLinePeriodQuantity() + }) +} + +// SetReasonDetails sets the "reason_details" field. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) SetReasonDetails(v *billing.DiscountReason) *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.SetReasonDetails(v) + }) +} + +// UpdateReasonDetails sets the "reason_details" field to the value that was provided on create. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) UpdateReasonDetails() *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.UpdateReasonDetails() + }) +} + +// ClearReasonDetails clears the value of the "reason_details" field. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) ClearReasonDetails() *BillingInvoiceLineUsageDiscountUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUsageDiscountUpsert) { + s.ClearReasonDetails() + }) +} + +// Exec executes the query. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) 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 BillingInvoiceLineUsageDiscountCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingInvoiceLineUsageDiscountCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingInvoiceLineUsageDiscountUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billinginvoicelineusagediscount_delete.go b/ent/db/billinginvoicelineusagediscount_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..3ebceb81edee95fba789beee59ba28ef244ab264 --- /dev/null +++ b/ent/db/billinginvoicelineusagediscount_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/billinginvoicelineusagediscount" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingInvoiceLineUsageDiscountDelete is the builder for deleting a BillingInvoiceLineUsageDiscount entity. +type BillingInvoiceLineUsageDiscountDelete struct { + config + hooks []Hook + mutation *BillingInvoiceLineUsageDiscountMutation +} + +// Where appends a list predicates to the BillingInvoiceLineUsageDiscountDelete builder. +func (_d *BillingInvoiceLineUsageDiscountDelete) Where(ps ...predicate.BillingInvoiceLineUsageDiscount) *BillingInvoiceLineUsageDiscountDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *BillingInvoiceLineUsageDiscountDelete) 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 *BillingInvoiceLineUsageDiscountDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *BillingInvoiceLineUsageDiscountDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(billinginvoicelineusagediscount.Table, sqlgraph.NewFieldSpec(billinginvoicelineusagediscount.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 +} + +// BillingInvoiceLineUsageDiscountDeleteOne is the builder for deleting a single BillingInvoiceLineUsageDiscount entity. +type BillingInvoiceLineUsageDiscountDeleteOne struct { + _d *BillingInvoiceLineUsageDiscountDelete +} + +// Where appends a list predicates to the BillingInvoiceLineUsageDiscountDelete builder. +func (_d *BillingInvoiceLineUsageDiscountDeleteOne) Where(ps ...predicate.BillingInvoiceLineUsageDiscount) *BillingInvoiceLineUsageDiscountDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *BillingInvoiceLineUsageDiscountDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{billinginvoicelineusagediscount.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *BillingInvoiceLineUsageDiscountDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billinginvoicelineusagediscount_query.go b/ent/db/billinginvoicelineusagediscount_query.go new file mode 100644 index 0000000000000000000000000000000000000000..162ad5b04d5899d005d24df2d75d559f2f311b84 --- /dev/null +++ b/ent/db/billinginvoicelineusagediscount_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/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicelineusagediscount" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingInvoiceLineUsageDiscountQuery is the builder for querying BillingInvoiceLineUsageDiscount entities. +type BillingInvoiceLineUsageDiscountQuery struct { + config + ctx *QueryContext + order []billinginvoicelineusagediscount.OrderOption + inters []Interceptor + predicates []predicate.BillingInvoiceLineUsageDiscount + withBillingInvoiceLine *BillingInvoiceLineQuery + 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 BillingInvoiceLineUsageDiscountQuery builder. +func (_q *BillingInvoiceLineUsageDiscountQuery) Where(ps ...predicate.BillingInvoiceLineUsageDiscount) *BillingInvoiceLineUsageDiscountQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *BillingInvoiceLineUsageDiscountQuery) Limit(limit int) *BillingInvoiceLineUsageDiscountQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *BillingInvoiceLineUsageDiscountQuery) Offset(offset int) *BillingInvoiceLineUsageDiscountQuery { + _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 *BillingInvoiceLineUsageDiscountQuery) Unique(unique bool) *BillingInvoiceLineUsageDiscountQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *BillingInvoiceLineUsageDiscountQuery) Order(o ...billinginvoicelineusagediscount.OrderOption) *BillingInvoiceLineUsageDiscountQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryBillingInvoiceLine chains the current query on the "billing_invoice_line" edge. +func (_q *BillingInvoiceLineUsageDiscountQuery) QueryBillingInvoiceLine() *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{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(billinginvoicelineusagediscount.Table, billinginvoicelineusagediscount.FieldID, selector), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoicelineusagediscount.BillingInvoiceLineTable, billinginvoicelineusagediscount.BillingInvoiceLineColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first BillingInvoiceLineUsageDiscount entity from the query. +// Returns a *NotFoundError when no BillingInvoiceLineUsageDiscount was found. +func (_q *BillingInvoiceLineUsageDiscountQuery) First(ctx context.Context) (*BillingInvoiceLineUsageDiscount, 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{billinginvoicelineusagediscount.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *BillingInvoiceLineUsageDiscountQuery) FirstX(ctx context.Context) *BillingInvoiceLineUsageDiscount { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first BillingInvoiceLineUsageDiscount ID from the query. +// Returns a *NotFoundError when no BillingInvoiceLineUsageDiscount ID was found. +func (_q *BillingInvoiceLineUsageDiscountQuery) 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{billinginvoicelineusagediscount.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *BillingInvoiceLineUsageDiscountQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single BillingInvoiceLineUsageDiscount entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one BillingInvoiceLineUsageDiscount entity is found. +// Returns a *NotFoundError when no BillingInvoiceLineUsageDiscount entities are found. +func (_q *BillingInvoiceLineUsageDiscountQuery) Only(ctx context.Context) (*BillingInvoiceLineUsageDiscount, 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{billinginvoicelineusagediscount.Label} + default: + return nil, &NotSingularError{billinginvoicelineusagediscount.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *BillingInvoiceLineUsageDiscountQuery) OnlyX(ctx context.Context) *BillingInvoiceLineUsageDiscount { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only BillingInvoiceLineUsageDiscount ID in the query. +// Returns a *NotSingularError when more than one BillingInvoiceLineUsageDiscount ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *BillingInvoiceLineUsageDiscountQuery) 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{billinginvoicelineusagediscount.Label} + default: + err = &NotSingularError{billinginvoicelineusagediscount.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *BillingInvoiceLineUsageDiscountQuery) 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 BillingInvoiceLineUsageDiscounts. +func (_q *BillingInvoiceLineUsageDiscountQuery) All(ctx context.Context) ([]*BillingInvoiceLineUsageDiscount, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*BillingInvoiceLineUsageDiscount, *BillingInvoiceLineUsageDiscountQuery]() + return withInterceptors[[]*BillingInvoiceLineUsageDiscount](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *BillingInvoiceLineUsageDiscountQuery) AllX(ctx context.Context) []*BillingInvoiceLineUsageDiscount { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of BillingInvoiceLineUsageDiscount IDs. +func (_q *BillingInvoiceLineUsageDiscountQuery) 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(billinginvoicelineusagediscount.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *BillingInvoiceLineUsageDiscountQuery) 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 *BillingInvoiceLineUsageDiscountQuery) 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[*BillingInvoiceLineUsageDiscountQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *BillingInvoiceLineUsageDiscountQuery) 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 *BillingInvoiceLineUsageDiscountQuery) 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 *BillingInvoiceLineUsageDiscountQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the BillingInvoiceLineUsageDiscountQuery 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 *BillingInvoiceLineUsageDiscountQuery) Clone() *BillingInvoiceLineUsageDiscountQuery { + if _q == nil { + return nil + } + return &BillingInvoiceLineUsageDiscountQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]billinginvoicelineusagediscount.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.BillingInvoiceLineUsageDiscount{}, _q.predicates...), + withBillingInvoiceLine: _q.withBillingInvoiceLine.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithBillingInvoiceLine tells the query-builder to eager-load the nodes that are connected to +// the "billing_invoice_line" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *BillingInvoiceLineUsageDiscountQuery) WithBillingInvoiceLine(opts ...func(*BillingInvoiceLineQuery)) *BillingInvoiceLineUsageDiscountQuery { + query := (&BillingInvoiceLineClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingInvoiceLine = 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.BillingInvoiceLineUsageDiscount.Query(). +// GroupBy(billinginvoicelineusagediscount.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *BillingInvoiceLineUsageDiscountQuery) GroupBy(field string, fields ...string) *BillingInvoiceLineUsageDiscountGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &BillingInvoiceLineUsageDiscountGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = billinginvoicelineusagediscount.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.BillingInvoiceLineUsageDiscount.Query(). +// Select(billinginvoicelineusagediscount.FieldNamespace). +// Scan(ctx, &v) +func (_q *BillingInvoiceLineUsageDiscountQuery) Select(fields ...string) *BillingInvoiceLineUsageDiscountSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &BillingInvoiceLineUsageDiscountSelect{BillingInvoiceLineUsageDiscountQuery: _q} + sbuild.label = billinginvoicelineusagediscount.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a BillingInvoiceLineUsageDiscountSelect configured with the given aggregations. +func (_q *BillingInvoiceLineUsageDiscountQuery) Aggregate(fns ...AggregateFunc) *BillingInvoiceLineUsageDiscountSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *BillingInvoiceLineUsageDiscountQuery) 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 !billinginvoicelineusagediscount.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 *BillingInvoiceLineUsageDiscountQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BillingInvoiceLineUsageDiscount, error) { + var ( + nodes = []*BillingInvoiceLineUsageDiscount{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withBillingInvoiceLine != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*BillingInvoiceLineUsageDiscount).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &BillingInvoiceLineUsageDiscount{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.withBillingInvoiceLine; query != nil { + if err := _q.loadBillingInvoiceLine(ctx, query, nodes, nil, + func(n *BillingInvoiceLineUsageDiscount, e *BillingInvoiceLine) { n.Edges.BillingInvoiceLine = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *BillingInvoiceLineUsageDiscountQuery) loadBillingInvoiceLine(ctx context.Context, query *BillingInvoiceLineQuery, nodes []*BillingInvoiceLineUsageDiscount, init func(*BillingInvoiceLineUsageDiscount), assign func(*BillingInvoiceLineUsageDiscount, *BillingInvoiceLine)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*BillingInvoiceLineUsageDiscount) + for i := range nodes { + fk := nodes[i].LineID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(billinginvoiceline.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 "line_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *BillingInvoiceLineUsageDiscountQuery) 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 *BillingInvoiceLineUsageDiscountQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(billinginvoicelineusagediscount.Table, billinginvoicelineusagediscount.Columns, sqlgraph.NewFieldSpec(billinginvoicelineusagediscount.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, billinginvoicelineusagediscount.FieldID) + for i := range fields { + if fields[i] != billinginvoicelineusagediscount.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withBillingInvoiceLine != nil { + _spec.Node.AddColumnOnce(billinginvoicelineusagediscount.FieldLineID) + } + } + 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 *BillingInvoiceLineUsageDiscountQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(billinginvoicelineusagediscount.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = billinginvoicelineusagediscount.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 *BillingInvoiceLineUsageDiscountQuery) ForUpdate(opts ...sql.LockOption) *BillingInvoiceLineUsageDiscountQuery { + 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 *BillingInvoiceLineUsageDiscountQuery) ForShare(opts ...sql.LockOption) *BillingInvoiceLineUsageDiscountQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// BillingInvoiceLineUsageDiscountGroupBy is the group-by builder for BillingInvoiceLineUsageDiscount entities. +type BillingInvoiceLineUsageDiscountGroupBy struct { + selector + build *BillingInvoiceLineUsageDiscountQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *BillingInvoiceLineUsageDiscountGroupBy) Aggregate(fns ...AggregateFunc) *BillingInvoiceLineUsageDiscountGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *BillingInvoiceLineUsageDiscountGroupBy) 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[*BillingInvoiceLineUsageDiscountQuery, *BillingInvoiceLineUsageDiscountGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *BillingInvoiceLineUsageDiscountGroupBy) sqlScan(ctx context.Context, root *BillingInvoiceLineUsageDiscountQuery, 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) +} + +// BillingInvoiceLineUsageDiscountSelect is the builder for selecting fields of BillingInvoiceLineUsageDiscount entities. +type BillingInvoiceLineUsageDiscountSelect struct { + *BillingInvoiceLineUsageDiscountQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *BillingInvoiceLineUsageDiscountSelect) Aggregate(fns ...AggregateFunc) *BillingInvoiceLineUsageDiscountSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *BillingInvoiceLineUsageDiscountSelect) 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[*BillingInvoiceLineUsageDiscountQuery, *BillingInvoiceLineUsageDiscountSelect](ctx, _s.BillingInvoiceLineUsageDiscountQuery, _s, _s.inters, v) +} + +func (_s *BillingInvoiceLineUsageDiscountSelect) sqlScan(ctx context.Context, root *BillingInvoiceLineUsageDiscountQuery, 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/ent/db/billinginvoicelineusagediscount_update.go b/ent/db/billinginvoicelineusagediscount_update.go new file mode 100644 index 0000000000000000000000000000000000000000..ad725fa164b125f98daeb6684a8fc4d495c383b5 --- /dev/null +++ b/ent/db/billinginvoicelineusagediscount_update.go @@ -0,0 +1,749 @@ +// 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" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicelineusagediscount" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingInvoiceLineUsageDiscountUpdate is the builder for updating BillingInvoiceLineUsageDiscount entities. +type BillingInvoiceLineUsageDiscountUpdate struct { + config + hooks []Hook + mutation *BillingInvoiceLineUsageDiscountMutation +} + +// Where appends a list predicates to the BillingInvoiceLineUsageDiscountUpdate builder. +func (_u *BillingInvoiceLineUsageDiscountUpdate) Where(ps ...predicate.BillingInvoiceLineUsageDiscount) *BillingInvoiceLineUsageDiscountUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *BillingInvoiceLineUsageDiscountUpdate) SetUpdatedAt(v time.Time) *BillingInvoiceLineUsageDiscountUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *BillingInvoiceLineUsageDiscountUpdate) SetDeletedAt(v time.Time) *BillingInvoiceLineUsageDiscountUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *BillingInvoiceLineUsageDiscountUpdate) SetNillableDeletedAt(v *time.Time) *BillingInvoiceLineUsageDiscountUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *BillingInvoiceLineUsageDiscountUpdate) ClearDeletedAt() *BillingInvoiceLineUsageDiscountUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (_u *BillingInvoiceLineUsageDiscountUpdate) SetInvoicingAppExternalID(v string) *BillingInvoiceLineUsageDiscountUpdate { + _u.mutation.SetInvoicingAppExternalID(v) + return _u +} + +// SetNillableInvoicingAppExternalID sets the "invoicing_app_external_id" field if the given value is not nil. +func (_u *BillingInvoiceLineUsageDiscountUpdate) SetNillableInvoicingAppExternalID(v *string) *BillingInvoiceLineUsageDiscountUpdate { + if v != nil { + _u.SetInvoicingAppExternalID(*v) + } + return _u +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (_u *BillingInvoiceLineUsageDiscountUpdate) ClearInvoicingAppExternalID() *BillingInvoiceLineUsageDiscountUpdate { + _u.mutation.ClearInvoicingAppExternalID() + return _u +} + +// SetLineID sets the "line_id" field. +func (_u *BillingInvoiceLineUsageDiscountUpdate) SetLineID(v string) *BillingInvoiceLineUsageDiscountUpdate { + _u.mutation.SetLineID(v) + return _u +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_u *BillingInvoiceLineUsageDiscountUpdate) SetNillableLineID(v *string) *BillingInvoiceLineUsageDiscountUpdate { + if v != nil { + _u.SetLineID(*v) + } + return _u +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (_u *BillingInvoiceLineUsageDiscountUpdate) SetChildUniqueReferenceID(v string) *BillingInvoiceLineUsageDiscountUpdate { + _u.mutation.SetChildUniqueReferenceID(v) + return _u +} + +// SetNillableChildUniqueReferenceID sets the "child_unique_reference_id" field if the given value is not nil. +func (_u *BillingInvoiceLineUsageDiscountUpdate) SetNillableChildUniqueReferenceID(v *string) *BillingInvoiceLineUsageDiscountUpdate { + if v != nil { + _u.SetChildUniqueReferenceID(*v) + } + return _u +} + +// ClearChildUniqueReferenceID clears the value of the "child_unique_reference_id" field. +func (_u *BillingInvoiceLineUsageDiscountUpdate) ClearChildUniqueReferenceID() *BillingInvoiceLineUsageDiscountUpdate { + _u.mutation.ClearChildUniqueReferenceID() + return _u +} + +// SetDescription sets the "description" field. +func (_u *BillingInvoiceLineUsageDiscountUpdate) SetDescription(v string) *BillingInvoiceLineUsageDiscountUpdate { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *BillingInvoiceLineUsageDiscountUpdate) SetNillableDescription(v *string) *BillingInvoiceLineUsageDiscountUpdate { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *BillingInvoiceLineUsageDiscountUpdate) ClearDescription() *BillingInvoiceLineUsageDiscountUpdate { + _u.mutation.ClearDescription() + return _u +} + +// SetReason sets the "reason" field. +func (_u *BillingInvoiceLineUsageDiscountUpdate) SetReason(v billing.DiscountReasonType) *BillingInvoiceLineUsageDiscountUpdate { + _u.mutation.SetReason(v) + return _u +} + +// SetNillableReason sets the "reason" field if the given value is not nil. +func (_u *BillingInvoiceLineUsageDiscountUpdate) SetNillableReason(v *billing.DiscountReasonType) *BillingInvoiceLineUsageDiscountUpdate { + if v != nil { + _u.SetReason(*v) + } + return _u +} + +// SetQuantity sets the "quantity" field. +func (_u *BillingInvoiceLineUsageDiscountUpdate) SetQuantity(v alpacadecimal.Decimal) *BillingInvoiceLineUsageDiscountUpdate { + _u.mutation.SetQuantity(v) + return _u +} + +// SetNillableQuantity sets the "quantity" field if the given value is not nil. +func (_u *BillingInvoiceLineUsageDiscountUpdate) SetNillableQuantity(v *alpacadecimal.Decimal) *BillingInvoiceLineUsageDiscountUpdate { + if v != nil { + _u.SetQuantity(*v) + } + return _u +} + +// SetPreLinePeriodQuantity sets the "pre_line_period_quantity" field. +func (_u *BillingInvoiceLineUsageDiscountUpdate) SetPreLinePeriodQuantity(v alpacadecimal.Decimal) *BillingInvoiceLineUsageDiscountUpdate { + _u.mutation.SetPreLinePeriodQuantity(v) + return _u +} + +// SetNillablePreLinePeriodQuantity sets the "pre_line_period_quantity" field if the given value is not nil. +func (_u *BillingInvoiceLineUsageDiscountUpdate) SetNillablePreLinePeriodQuantity(v *alpacadecimal.Decimal) *BillingInvoiceLineUsageDiscountUpdate { + if v != nil { + _u.SetPreLinePeriodQuantity(*v) + } + return _u +} + +// ClearPreLinePeriodQuantity clears the value of the "pre_line_period_quantity" field. +func (_u *BillingInvoiceLineUsageDiscountUpdate) ClearPreLinePeriodQuantity() *BillingInvoiceLineUsageDiscountUpdate { + _u.mutation.ClearPreLinePeriodQuantity() + return _u +} + +// SetReasonDetails sets the "reason_details" field. +func (_u *BillingInvoiceLineUsageDiscountUpdate) SetReasonDetails(v *billing.DiscountReason) *BillingInvoiceLineUsageDiscountUpdate { + _u.mutation.SetReasonDetails(v) + return _u +} + +// ClearReasonDetails clears the value of the "reason_details" field. +func (_u *BillingInvoiceLineUsageDiscountUpdate) ClearReasonDetails() *BillingInvoiceLineUsageDiscountUpdate { + _u.mutation.ClearReasonDetails() + return _u +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID. +func (_u *BillingInvoiceLineUsageDiscountUpdate) SetBillingInvoiceLineID(id string) *BillingInvoiceLineUsageDiscountUpdate { + _u.mutation.SetBillingInvoiceLineID(id) + return _u +} + +// SetBillingInvoiceLine sets the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *BillingInvoiceLineUsageDiscountUpdate) SetBillingInvoiceLine(v *BillingInvoiceLine) *BillingInvoiceLineUsageDiscountUpdate { + return _u.SetBillingInvoiceLineID(v.ID) +} + +// Mutation returns the BillingInvoiceLineUsageDiscountMutation object of the builder. +func (_u *BillingInvoiceLineUsageDiscountUpdate) Mutation() *BillingInvoiceLineUsageDiscountMutation { + return _u.mutation +} + +// ClearBillingInvoiceLine clears the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *BillingInvoiceLineUsageDiscountUpdate) ClearBillingInvoiceLine() *BillingInvoiceLineUsageDiscountUpdate { + _u.mutation.ClearBillingInvoiceLine() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *BillingInvoiceLineUsageDiscountUpdate) 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 *BillingInvoiceLineUsageDiscountUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *BillingInvoiceLineUsageDiscountUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingInvoiceLineUsageDiscountUpdate) 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 *BillingInvoiceLineUsageDiscountUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := billinginvoicelineusagediscount.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *BillingInvoiceLineUsageDiscountUpdate) check() error { + if v, ok := _u.mutation.Reason(); ok { + if err := billinginvoicelineusagediscount.ReasonValidator(v); err != nil { + return &ValidationError{Name: "reason", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLineUsageDiscount.reason": %w`, err)} + } + } + if v, ok := _u.mutation.ReasonDetails(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "reason_details", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLineUsageDiscount.reason_details": %w`, err)} + } + } + if _u.mutation.BillingInvoiceLineCleared() && len(_u.mutation.BillingInvoiceLineIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "BillingInvoiceLineUsageDiscount.billing_invoice_line"`) + } + return nil +} + +func (_u *BillingInvoiceLineUsageDiscountUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(billinginvoicelineusagediscount.Table, billinginvoicelineusagediscount.Columns, sqlgraph.NewFieldSpec(billinginvoicelineusagediscount.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(billinginvoicelineusagediscount.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(billinginvoicelineusagediscount.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.InvoicingAppExternalID(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldInvoicingAppExternalID, field.TypeString, value) + } + if _u.mutation.InvoicingAppExternalIDCleared() { + _spec.ClearField(billinginvoicelineusagediscount.FieldInvoicingAppExternalID, field.TypeString) + } + if value, ok := _u.mutation.ChildUniqueReferenceID(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldChildUniqueReferenceID, field.TypeString, value) + } + if _u.mutation.ChildUniqueReferenceIDCleared() { + _spec.ClearField(billinginvoicelineusagediscount.FieldChildUniqueReferenceID, field.TypeString) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(billinginvoicelineusagediscount.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.Reason(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldReason, field.TypeEnum, value) + } + if value, ok := _u.mutation.Quantity(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldQuantity, field.TypeOther, value) + } + if value, ok := _u.mutation.PreLinePeriodQuantity(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldPreLinePeriodQuantity, field.TypeOther, value) + } + if _u.mutation.PreLinePeriodQuantityCleared() { + _spec.ClearField(billinginvoicelineusagediscount.FieldPreLinePeriodQuantity, field.TypeOther) + } + if value, ok := _u.mutation.ReasonDetails(); ok { + vv, err := billinginvoicelineusagediscount.ValueScanner.ReasonDetails.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(billinginvoicelineusagediscount.FieldReasonDetails, field.TypeString, vv) + } + if _u.mutation.ReasonDetailsCleared() { + _spec.ClearField(billinginvoicelineusagediscount.FieldReasonDetails, field.TypeString) + } + if _u.mutation.BillingInvoiceLineCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicelineusagediscount.BillingInvoiceLineTable, + Columns: []string{billinginvoicelineusagediscount.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingInvoiceLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicelineusagediscount.BillingInvoiceLineTable, + Columns: []string{billinginvoicelineusagediscount.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.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{billinginvoicelineusagediscount.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// BillingInvoiceLineUsageDiscountUpdateOne is the builder for updating a single BillingInvoiceLineUsageDiscount entity. +type BillingInvoiceLineUsageDiscountUpdateOne struct { + config + fields []string + hooks []Hook + mutation *BillingInvoiceLineUsageDiscountMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SetUpdatedAt(v time.Time) *BillingInvoiceLineUsageDiscountUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SetDeletedAt(v time.Time) *BillingInvoiceLineUsageDiscountUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SetNillableDeletedAt(v *time.Time) *BillingInvoiceLineUsageDiscountUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) ClearDeletedAt() *BillingInvoiceLineUsageDiscountUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SetInvoicingAppExternalID(v string) *BillingInvoiceLineUsageDiscountUpdateOne { + _u.mutation.SetInvoicingAppExternalID(v) + return _u +} + +// SetNillableInvoicingAppExternalID sets the "invoicing_app_external_id" field if the given value is not nil. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SetNillableInvoicingAppExternalID(v *string) *BillingInvoiceLineUsageDiscountUpdateOne { + if v != nil { + _u.SetInvoicingAppExternalID(*v) + } + return _u +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) ClearInvoicingAppExternalID() *BillingInvoiceLineUsageDiscountUpdateOne { + _u.mutation.ClearInvoicingAppExternalID() + return _u +} + +// SetLineID sets the "line_id" field. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SetLineID(v string) *BillingInvoiceLineUsageDiscountUpdateOne { + _u.mutation.SetLineID(v) + return _u +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SetNillableLineID(v *string) *BillingInvoiceLineUsageDiscountUpdateOne { + if v != nil { + _u.SetLineID(*v) + } + return _u +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SetChildUniqueReferenceID(v string) *BillingInvoiceLineUsageDiscountUpdateOne { + _u.mutation.SetChildUniqueReferenceID(v) + return _u +} + +// SetNillableChildUniqueReferenceID sets the "child_unique_reference_id" field if the given value is not nil. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SetNillableChildUniqueReferenceID(v *string) *BillingInvoiceLineUsageDiscountUpdateOne { + if v != nil { + _u.SetChildUniqueReferenceID(*v) + } + return _u +} + +// ClearChildUniqueReferenceID clears the value of the "child_unique_reference_id" field. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) ClearChildUniqueReferenceID() *BillingInvoiceLineUsageDiscountUpdateOne { + _u.mutation.ClearChildUniqueReferenceID() + return _u +} + +// SetDescription sets the "description" field. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SetDescription(v string) *BillingInvoiceLineUsageDiscountUpdateOne { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SetNillableDescription(v *string) *BillingInvoiceLineUsageDiscountUpdateOne { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) ClearDescription() *BillingInvoiceLineUsageDiscountUpdateOne { + _u.mutation.ClearDescription() + return _u +} + +// SetReason sets the "reason" field. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SetReason(v billing.DiscountReasonType) *BillingInvoiceLineUsageDiscountUpdateOne { + _u.mutation.SetReason(v) + return _u +} + +// SetNillableReason sets the "reason" field if the given value is not nil. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SetNillableReason(v *billing.DiscountReasonType) *BillingInvoiceLineUsageDiscountUpdateOne { + if v != nil { + _u.SetReason(*v) + } + return _u +} + +// SetQuantity sets the "quantity" field. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SetQuantity(v alpacadecimal.Decimal) *BillingInvoiceLineUsageDiscountUpdateOne { + _u.mutation.SetQuantity(v) + return _u +} + +// SetNillableQuantity sets the "quantity" field if the given value is not nil. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SetNillableQuantity(v *alpacadecimal.Decimal) *BillingInvoiceLineUsageDiscountUpdateOne { + if v != nil { + _u.SetQuantity(*v) + } + return _u +} + +// SetPreLinePeriodQuantity sets the "pre_line_period_quantity" field. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SetPreLinePeriodQuantity(v alpacadecimal.Decimal) *BillingInvoiceLineUsageDiscountUpdateOne { + _u.mutation.SetPreLinePeriodQuantity(v) + return _u +} + +// SetNillablePreLinePeriodQuantity sets the "pre_line_period_quantity" field if the given value is not nil. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SetNillablePreLinePeriodQuantity(v *alpacadecimal.Decimal) *BillingInvoiceLineUsageDiscountUpdateOne { + if v != nil { + _u.SetPreLinePeriodQuantity(*v) + } + return _u +} + +// ClearPreLinePeriodQuantity clears the value of the "pre_line_period_quantity" field. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) ClearPreLinePeriodQuantity() *BillingInvoiceLineUsageDiscountUpdateOne { + _u.mutation.ClearPreLinePeriodQuantity() + return _u +} + +// SetReasonDetails sets the "reason_details" field. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SetReasonDetails(v *billing.DiscountReason) *BillingInvoiceLineUsageDiscountUpdateOne { + _u.mutation.SetReasonDetails(v) + return _u +} + +// ClearReasonDetails clears the value of the "reason_details" field. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) ClearReasonDetails() *BillingInvoiceLineUsageDiscountUpdateOne { + _u.mutation.ClearReasonDetails() + return _u +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SetBillingInvoiceLineID(id string) *BillingInvoiceLineUsageDiscountUpdateOne { + _u.mutation.SetBillingInvoiceLineID(id) + return _u +} + +// SetBillingInvoiceLine sets the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SetBillingInvoiceLine(v *BillingInvoiceLine) *BillingInvoiceLineUsageDiscountUpdateOne { + return _u.SetBillingInvoiceLineID(v.ID) +} + +// Mutation returns the BillingInvoiceLineUsageDiscountMutation object of the builder. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) Mutation() *BillingInvoiceLineUsageDiscountMutation { + return _u.mutation +} + +// ClearBillingInvoiceLine clears the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) ClearBillingInvoiceLine() *BillingInvoiceLineUsageDiscountUpdateOne { + _u.mutation.ClearBillingInvoiceLine() + return _u +} + +// Where appends a list predicates to the BillingInvoiceLineUsageDiscountUpdate builder. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) Where(ps ...predicate.BillingInvoiceLineUsageDiscount) *BillingInvoiceLineUsageDiscountUpdateOne { + _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 *BillingInvoiceLineUsageDiscountUpdateOne) Select(field string, fields ...string) *BillingInvoiceLineUsageDiscountUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated BillingInvoiceLineUsageDiscount entity. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) Save(ctx context.Context) (*BillingInvoiceLineUsageDiscount, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) SaveX(ctx context.Context) *BillingInvoiceLineUsageDiscount { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) 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 *BillingInvoiceLineUsageDiscountUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := billinginvoicelineusagediscount.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) check() error { + if v, ok := _u.mutation.Reason(); ok { + if err := billinginvoicelineusagediscount.ReasonValidator(v); err != nil { + return &ValidationError{Name: "reason", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLineUsageDiscount.reason": %w`, err)} + } + } + if v, ok := _u.mutation.ReasonDetails(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "reason_details", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLineUsageDiscount.reason_details": %w`, err)} + } + } + if _u.mutation.BillingInvoiceLineCleared() && len(_u.mutation.BillingInvoiceLineIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "BillingInvoiceLineUsageDiscount.billing_invoice_line"`) + } + return nil +} + +func (_u *BillingInvoiceLineUsageDiscountUpdateOne) sqlSave(ctx context.Context) (_node *BillingInvoiceLineUsageDiscount, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(billinginvoicelineusagediscount.Table, billinginvoicelineusagediscount.Columns, sqlgraph.NewFieldSpec(billinginvoicelineusagediscount.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "BillingInvoiceLineUsageDiscount.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, billinginvoicelineusagediscount.FieldID) + for _, f := range fields { + if !billinginvoicelineusagediscount.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != billinginvoicelineusagediscount.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(billinginvoicelineusagediscount.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(billinginvoicelineusagediscount.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.InvoicingAppExternalID(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldInvoicingAppExternalID, field.TypeString, value) + } + if _u.mutation.InvoicingAppExternalIDCleared() { + _spec.ClearField(billinginvoicelineusagediscount.FieldInvoicingAppExternalID, field.TypeString) + } + if value, ok := _u.mutation.ChildUniqueReferenceID(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldChildUniqueReferenceID, field.TypeString, value) + } + if _u.mutation.ChildUniqueReferenceIDCleared() { + _spec.ClearField(billinginvoicelineusagediscount.FieldChildUniqueReferenceID, field.TypeString) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(billinginvoicelineusagediscount.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.Reason(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldReason, field.TypeEnum, value) + } + if value, ok := _u.mutation.Quantity(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldQuantity, field.TypeOther, value) + } + if value, ok := _u.mutation.PreLinePeriodQuantity(); ok { + _spec.SetField(billinginvoicelineusagediscount.FieldPreLinePeriodQuantity, field.TypeOther, value) + } + if _u.mutation.PreLinePeriodQuantityCleared() { + _spec.ClearField(billinginvoicelineusagediscount.FieldPreLinePeriodQuantity, field.TypeOther) + } + if value, ok := _u.mutation.ReasonDetails(); ok { + vv, err := billinginvoicelineusagediscount.ValueScanner.ReasonDetails.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(billinginvoicelineusagediscount.FieldReasonDetails, field.TypeString, vv) + } + if _u.mutation.ReasonDetailsCleared() { + _spec.ClearField(billinginvoicelineusagediscount.FieldReasonDetails, field.TypeString) + } + if _u.mutation.BillingInvoiceLineCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicelineusagediscount.BillingInvoiceLineTable, + Columns: []string{billinginvoicelineusagediscount.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingInvoiceLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicelineusagediscount.BillingInvoiceLineTable, + Columns: []string{billinginvoicelineusagediscount.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &BillingInvoiceLineUsageDiscount{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{billinginvoicelineusagediscount.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/ent/db/billinginvoicesplitlinegroup.go b/ent/db/billinginvoicesplitlinegroup.go new file mode 100644 index 0000000000000000000000000000000000000000..91cd8cac03477028998c4bbce2ef9e145a561b65 --- /dev/null +++ b/ent/db/billinginvoicesplitlinegroup.go @@ -0,0 +1,459 @@ +// 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/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicesplitlinegroup" + "github.com/openmeterio/openmeter/openmeter/ent/db/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionphase" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" +) + +// BillingInvoiceSplitLineGroup is the model entity for the BillingInvoiceSplitLineGroup schema. +type BillingInvoiceSplitLineGroup 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"` + // Metadata holds the value of the "metadata" field. + Metadata map[string]string `json:"metadata,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"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Description holds the value of the "description" field. + Description *string `json:"description,omitempty"` + // Currency holds the value of the "currency" field. + Currency currencyx.Code `json:"currency,omitempty"` + // ServicePeriodStart holds the value of the "service_period_start" field. + ServicePeriodStart time.Time `json:"service_period_start,omitempty"` + // ServicePeriodEnd holds the value of the "service_period_end" field. + ServicePeriodEnd time.Time `json:"service_period_end,omitempty"` + // UniqueReferenceID holds the value of the "unique_reference_id" field. + UniqueReferenceID *string `json:"unique_reference_id,omitempty"` + // RatecardDiscounts holds the value of the "ratecard_discounts" field. + RatecardDiscounts *billing.Discounts `json:"ratecard_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"` + // SubscriptionID holds the value of the "subscription_id" field. + SubscriptionID *string `json:"subscription_id,omitempty"` + // SubscriptionPhaseID holds the value of the "subscription_phase_id" field. + SubscriptionPhaseID *string `json:"subscription_phase_id,omitempty"` + // SubscriptionItemID holds the value of the "subscription_item_id" field. + SubscriptionItemID *string `json:"subscription_item_id,omitempty"` + // SubscriptionBillingPeriodFrom holds the value of the "subscription_billing_period_from" field. + SubscriptionBillingPeriodFrom *time.Time `json:"subscription_billing_period_from,omitempty"` + // SubscriptionBillingPeriodTo holds the value of the "subscription_billing_period_to" field. + SubscriptionBillingPeriodTo *time.Time `json:"subscription_billing_period_to,omitempty"` + // ChargeID holds the value of the "charge_id" field. + ChargeID *string `json:"charge_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the BillingInvoiceSplitLineGroupQuery when eager-loading is set. + Edges BillingInvoiceSplitLineGroupEdges `json:"edges"` + selectValues sql.SelectValues +} + +// BillingInvoiceSplitLineGroupEdges holds the relations/edges for other nodes in the graph. +type BillingInvoiceSplitLineGroupEdges struct { + // BillingInvoiceLines holds the value of the billing_invoice_lines edge. + BillingInvoiceLines []*BillingInvoiceLine `json:"billing_invoice_lines,omitempty"` + // Subscription holds the value of the subscription edge. + Subscription *Subscription `json:"subscription,omitempty"` + // SubscriptionPhase holds the value of the subscription_phase edge. + SubscriptionPhase *SubscriptionPhase `json:"subscription_phase,omitempty"` + // SubscriptionItem holds the value of the subscription_item edge. + SubscriptionItem *SubscriptionItem `json:"subscription_item,omitempty"` + // Charge holds the value of the charge edge. + Charge *Charge `json:"charge,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [5]bool +} + +// BillingInvoiceLinesOrErr returns the BillingInvoiceLines value or an error if the edge +// was not loaded in eager-loading. +func (e BillingInvoiceSplitLineGroupEdges) BillingInvoiceLinesOrErr() ([]*BillingInvoiceLine, error) { + if e.loadedTypes[0] { + return e.BillingInvoiceLines, nil + } + return nil, &NotLoadedError{edge: "billing_invoice_lines"} +} + +// SubscriptionOrErr returns the Subscription value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e BillingInvoiceSplitLineGroupEdges) SubscriptionOrErr() (*Subscription, error) { + if e.Subscription != nil { + return e.Subscription, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: subscription.Label} + } + return nil, &NotLoadedError{edge: "subscription"} +} + +// SubscriptionPhaseOrErr returns the SubscriptionPhase value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e BillingInvoiceSplitLineGroupEdges) SubscriptionPhaseOrErr() (*SubscriptionPhase, error) { + if e.SubscriptionPhase != nil { + return e.SubscriptionPhase, nil + } else if e.loadedTypes[2] { + return nil, &NotFoundError{label: subscriptionphase.Label} + } + return nil, &NotLoadedError{edge: "subscription_phase"} +} + +// SubscriptionItemOrErr returns the SubscriptionItem value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e BillingInvoiceSplitLineGroupEdges) SubscriptionItemOrErr() (*SubscriptionItem, error) { + if e.SubscriptionItem != nil { + return e.SubscriptionItem, nil + } else if e.loadedTypes[3] { + return nil, &NotFoundError{label: subscriptionitem.Label} + } + return nil, &NotLoadedError{edge: "subscription_item"} +} + +// 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 BillingInvoiceSplitLineGroupEdges) ChargeOrErr() (*Charge, error) { + if e.Charge != nil { + return e.Charge, nil + } else if e.loadedTypes[4] { + return nil, &NotFoundError{label: charge.Label} + } + return nil, &NotLoadedError{edge: "charge"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*BillingInvoiceSplitLineGroup) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case billinginvoicesplitlinegroup.FieldMetadata: + values[i] = new([]byte) + case billinginvoicesplitlinegroup.FieldID, billinginvoicesplitlinegroup.FieldNamespace, billinginvoicesplitlinegroup.FieldName, billinginvoicesplitlinegroup.FieldDescription, billinginvoicesplitlinegroup.FieldCurrency, billinginvoicesplitlinegroup.FieldUniqueReferenceID, billinginvoicesplitlinegroup.FieldFeatureKey, billinginvoicesplitlinegroup.FieldSubscriptionID, billinginvoicesplitlinegroup.FieldSubscriptionPhaseID, billinginvoicesplitlinegroup.FieldSubscriptionItemID, billinginvoicesplitlinegroup.FieldChargeID: + values[i] = new(sql.NullString) + case billinginvoicesplitlinegroup.FieldCreatedAt, billinginvoicesplitlinegroup.FieldUpdatedAt, billinginvoicesplitlinegroup.FieldDeletedAt, billinginvoicesplitlinegroup.FieldServicePeriodStart, billinginvoicesplitlinegroup.FieldServicePeriodEnd, billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom, billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo: + values[i] = new(sql.NullTime) + case billinginvoicesplitlinegroup.FieldRatecardDiscounts: + values[i] = billinginvoicesplitlinegroup.ValueScanner.RatecardDiscounts.ScanValue() + case billinginvoicesplitlinegroup.FieldPrice: + values[i] = billinginvoicesplitlinegroup.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 BillingInvoiceSplitLineGroup fields. +func (_m *BillingInvoiceSplitLineGroup) 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 billinginvoicesplitlinegroup.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 billinginvoicesplitlinegroup.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 billinginvoicesplitlinegroup.FieldMetadata: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field metadata", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Metadata); err != nil { + return fmt.Errorf("unmarshal field metadata: %w", err) + } + } + case billinginvoicesplitlinegroup.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 billinginvoicesplitlinegroup.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 billinginvoicesplitlinegroup.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 billinginvoicesplitlinegroup.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case billinginvoicesplitlinegroup.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + _m.Description = new(string) + *_m.Description = value.String + } + case billinginvoicesplitlinegroup.FieldCurrency: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field currency", values[i]) + } else if value.Valid { + _m.Currency = currencyx.Code(value.String) + } + case billinginvoicesplitlinegroup.FieldServicePeriodStart: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field service_period_start", values[i]) + } else if value.Valid { + _m.ServicePeriodStart = value.Time + } + case billinginvoicesplitlinegroup.FieldServicePeriodEnd: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field service_period_end", values[i]) + } else if value.Valid { + _m.ServicePeriodEnd = value.Time + } + case billinginvoicesplitlinegroup.FieldUniqueReferenceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field unique_reference_id", values[i]) + } else if value.Valid { + _m.UniqueReferenceID = new(string) + *_m.UniqueReferenceID = value.String + } + case billinginvoicesplitlinegroup.FieldRatecardDiscounts: + if value, err := billinginvoicesplitlinegroup.ValueScanner.RatecardDiscounts.FromValue(values[i]); err != nil { + return err + } else { + _m.RatecardDiscounts = value + } + case billinginvoicesplitlinegroup.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 = new(string) + *_m.FeatureKey = value.String + } + case billinginvoicesplitlinegroup.FieldPrice: + if value, err := billinginvoicesplitlinegroup.ValueScanner.Price.FromValue(values[i]); err != nil { + return err + } else { + _m.Price = value + } + case billinginvoicesplitlinegroup.FieldSubscriptionID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field subscription_id", values[i]) + } else if value.Valid { + _m.SubscriptionID = new(string) + *_m.SubscriptionID = value.String + } + case billinginvoicesplitlinegroup.FieldSubscriptionPhaseID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field subscription_phase_id", values[i]) + } else if value.Valid { + _m.SubscriptionPhaseID = new(string) + *_m.SubscriptionPhaseID = value.String + } + case billinginvoicesplitlinegroup.FieldSubscriptionItemID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field subscription_item_id", values[i]) + } else if value.Valid { + _m.SubscriptionItemID = new(string) + *_m.SubscriptionItemID = value.String + } + case billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field subscription_billing_period_from", values[i]) + } else if value.Valid { + _m.SubscriptionBillingPeriodFrom = new(time.Time) + *_m.SubscriptionBillingPeriodFrom = value.Time + } + case billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field subscription_billing_period_to", values[i]) + } else if value.Valid { + _m.SubscriptionBillingPeriodTo = new(time.Time) + *_m.SubscriptionBillingPeriodTo = value.Time + } + case billinginvoicesplitlinegroup.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 = new(string) + *_m.ChargeID = 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 BillingInvoiceSplitLineGroup. +// This includes values selected through modifiers, order, etc. +func (_m *BillingInvoiceSplitLineGroup) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryBillingInvoiceLines queries the "billing_invoice_lines" edge of the BillingInvoiceSplitLineGroup entity. +func (_m *BillingInvoiceSplitLineGroup) QueryBillingInvoiceLines() *BillingInvoiceLineQuery { + return NewBillingInvoiceSplitLineGroupClient(_m.config).QueryBillingInvoiceLines(_m) +} + +// QuerySubscription queries the "subscription" edge of the BillingInvoiceSplitLineGroup entity. +func (_m *BillingInvoiceSplitLineGroup) QuerySubscription() *SubscriptionQuery { + return NewBillingInvoiceSplitLineGroupClient(_m.config).QuerySubscription(_m) +} + +// QuerySubscriptionPhase queries the "subscription_phase" edge of the BillingInvoiceSplitLineGroup entity. +func (_m *BillingInvoiceSplitLineGroup) QuerySubscriptionPhase() *SubscriptionPhaseQuery { + return NewBillingInvoiceSplitLineGroupClient(_m.config).QuerySubscriptionPhase(_m) +} + +// QuerySubscriptionItem queries the "subscription_item" edge of the BillingInvoiceSplitLineGroup entity. +func (_m *BillingInvoiceSplitLineGroup) QuerySubscriptionItem() *SubscriptionItemQuery { + return NewBillingInvoiceSplitLineGroupClient(_m.config).QuerySubscriptionItem(_m) +} + +// QueryCharge queries the "charge" edge of the BillingInvoiceSplitLineGroup entity. +func (_m *BillingInvoiceSplitLineGroup) QueryCharge() *ChargeQuery { + return NewBillingInvoiceSplitLineGroupClient(_m.config).QueryCharge(_m) +} + +// Update returns a builder for updating this BillingInvoiceSplitLineGroup. +// Note that you need to call BillingInvoiceSplitLineGroup.Unwrap() before calling this method if this BillingInvoiceSplitLineGroup +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *BillingInvoiceSplitLineGroup) Update() *BillingInvoiceSplitLineGroupUpdateOne { + return NewBillingInvoiceSplitLineGroupClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroup) Unwrap() *BillingInvoiceSplitLineGroup { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: BillingInvoiceSplitLineGroup is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *BillingInvoiceSplitLineGroup) String() string { + var builder strings.Builder + builder.WriteString("BillingInvoiceSplitLineGroup(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("metadata=") + builder.WriteString(fmt.Sprintf("%v", _m.Metadata)) + 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("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + if v := _m.Description; v != nil { + builder.WriteString("description=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("currency=") + builder.WriteString(fmt.Sprintf("%v", _m.Currency)) + builder.WriteString(", ") + builder.WriteString("service_period_start=") + builder.WriteString(_m.ServicePeriodStart.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("service_period_end=") + builder.WriteString(_m.ServicePeriodEnd.Format(time.ANSIC)) + builder.WriteString(", ") + if v := _m.UniqueReferenceID; v != nil { + builder.WriteString("unique_reference_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.RatecardDiscounts; v != nil { + builder.WriteString("ratecard_discounts=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.FeatureKey; v != nil { + builder.WriteString("feature_key=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("price=") + builder.WriteString(fmt.Sprintf("%v", _m.Price)) + builder.WriteString(", ") + if v := _m.SubscriptionID; v != nil { + builder.WriteString("subscription_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SubscriptionPhaseID; v != nil { + builder.WriteString("subscription_phase_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SubscriptionItemID; v != nil { + builder.WriteString("subscription_item_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SubscriptionBillingPeriodFrom; v != nil { + builder.WriteString("subscription_billing_period_from=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + if v := _m.SubscriptionBillingPeriodTo; v != nil { + builder.WriteString("subscription_billing_period_to=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + if v := _m.ChargeID; v != nil { + builder.WriteString("charge_id=") + builder.WriteString(*v) + } + builder.WriteByte(')') + return builder.String() +} + +// BillingInvoiceSplitLineGroups is a parsable slice of BillingInvoiceSplitLineGroup. +type BillingInvoiceSplitLineGroups []*BillingInvoiceSplitLineGroup diff --git a/ent/db/billinginvoicesplitlinegroup/billinginvoicesplitlinegroup.go b/ent/db/billinginvoicesplitlinegroup/billinginvoicesplitlinegroup.go new file mode 100644 index 0000000000000000000000000000000000000000..a87f7b0738af6fc6314fe3898f4153da18f503f7 --- /dev/null +++ b/ent/db/billinginvoicesplitlinegroup/billinginvoicesplitlinegroup.go @@ -0,0 +1,342 @@ +// Code generated by ent, DO NOT EDIT. + +package billinginvoicesplitlinegroup + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/productcatalog" +) + +const ( + // Label holds the string label denoting the billinginvoicesplitlinegroup type in the database. + Label = "billing_invoice_split_line_group" + // 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" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // 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" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // FieldCurrency holds the string denoting the currency field in the database. + FieldCurrency = "currency" + // FieldServicePeriodStart holds the string denoting the service_period_start field in the database. + FieldServicePeriodStart = "service_period_start" + // FieldServicePeriodEnd holds the string denoting the service_period_end field in the database. + FieldServicePeriodEnd = "service_period_end" + // FieldUniqueReferenceID holds the string denoting the unique_reference_id field in the database. + FieldUniqueReferenceID = "unique_reference_id" + // FieldRatecardDiscounts holds the string denoting the ratecard_discounts field in the database. + FieldRatecardDiscounts = "ratecard_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" + // FieldSubscriptionID holds the string denoting the subscription_id field in the database. + FieldSubscriptionID = "subscription_id" + // FieldSubscriptionPhaseID holds the string denoting the subscription_phase_id field in the database. + FieldSubscriptionPhaseID = "subscription_phase_id" + // FieldSubscriptionItemID holds the string denoting the subscription_item_id field in the database. + FieldSubscriptionItemID = "subscription_item_id" + // FieldSubscriptionBillingPeriodFrom holds the string denoting the subscription_billing_period_from field in the database. + FieldSubscriptionBillingPeriodFrom = "subscription_billing_period_from" + // FieldSubscriptionBillingPeriodTo holds the string denoting the subscription_billing_period_to field in the database. + FieldSubscriptionBillingPeriodTo = "subscription_billing_period_to" + // FieldChargeID holds the string denoting the charge_id field in the database. + FieldChargeID = "charge_id" + // EdgeBillingInvoiceLines holds the string denoting the billing_invoice_lines edge name in mutations. + EdgeBillingInvoiceLines = "billing_invoice_lines" + // EdgeSubscription holds the string denoting the subscription edge name in mutations. + EdgeSubscription = "subscription" + // EdgeSubscriptionPhase holds the string denoting the subscription_phase edge name in mutations. + EdgeSubscriptionPhase = "subscription_phase" + // EdgeSubscriptionItem holds the string denoting the subscription_item edge name in mutations. + EdgeSubscriptionItem = "subscription_item" + // EdgeCharge holds the string denoting the charge edge name in mutations. + EdgeCharge = "charge" + // Table holds the table name of the billinginvoicesplitlinegroup in the database. + Table = "billing_invoice_split_line_groups" + // 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. + // It exists in this package in order to avoid circular dependency with the "billinginvoiceline" package. + BillingInvoiceLinesInverseTable = "billing_invoice_lines" + // BillingInvoiceLinesColumn is the table column denoting the billing_invoice_lines relation/edge. + BillingInvoiceLinesColumn = "split_line_group_id" + // SubscriptionTable is the table that holds the subscription relation/edge. + SubscriptionTable = "billing_invoice_split_line_groups" + // SubscriptionInverseTable is the table name for the Subscription entity. + // It exists in this package in order to avoid circular dependency with the "subscription" package. + SubscriptionInverseTable = "subscriptions" + // SubscriptionColumn is the table column denoting the subscription relation/edge. + SubscriptionColumn = "subscription_id" + // SubscriptionPhaseTable is the table that holds the subscription_phase relation/edge. + SubscriptionPhaseTable = "billing_invoice_split_line_groups" + // SubscriptionPhaseInverseTable is the table name for the SubscriptionPhase entity. + // It exists in this package in order to avoid circular dependency with the "subscriptionphase" package. + SubscriptionPhaseInverseTable = "subscription_phases" + // SubscriptionPhaseColumn is the table column denoting the subscription_phase relation/edge. + SubscriptionPhaseColumn = "subscription_phase_id" + // SubscriptionItemTable is the table that holds the subscription_item relation/edge. + SubscriptionItemTable = "billing_invoice_split_line_groups" + // SubscriptionItemInverseTable is the table name for the SubscriptionItem entity. + // It exists in this package in order to avoid circular dependency with the "subscriptionitem" package. + SubscriptionItemInverseTable = "subscription_items" + // SubscriptionItemColumn is the table column denoting the subscription_item relation/edge. + SubscriptionItemColumn = "subscription_item_id" + // ChargeTable is the table that holds the charge relation/edge. + ChargeTable = "billing_invoice_split_line_groups" + // 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 = "charge_id" +) + +// Columns holds all SQL columns for billinginvoicesplitlinegroup fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldMetadata, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldName, + FieldDescription, + FieldCurrency, + FieldServicePeriodStart, + FieldServicePeriodEnd, + FieldUniqueReferenceID, + FieldRatecardDiscounts, + FieldFeatureKey, + FieldPrice, + FieldSubscriptionID, + FieldSubscriptionPhaseID, + FieldSubscriptionItemID, + FieldSubscriptionBillingPeriodFrom, + FieldSubscriptionBillingPeriodTo, + FieldChargeID, +} + +// 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 + // CurrencyValidator is a validator for the "currency" field. It is called by the builders before save. + CurrencyValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string + // ValueScanner of all BillingInvoiceSplitLineGroup fields. + ValueScanner struct { + RatecardDiscounts field.TypeValueScanner[*billing.Discounts] + Price field.TypeValueScanner[*productcatalog.Price] + } +) + +// OrderOption defines the ordering options for the BillingInvoiceSplitLineGroup 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() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, opts...).ToFunc() +} + +// ByCurrency orders the results by the currency field. +func ByCurrency(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCurrency, opts...).ToFunc() +} + +// ByServicePeriodStart orders the results by the service_period_start field. +func ByServicePeriodStart(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldServicePeriodStart, opts...).ToFunc() +} + +// ByServicePeriodEnd orders the results by the service_period_end field. +func ByServicePeriodEnd(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldServicePeriodEnd, opts...).ToFunc() +} + +// ByUniqueReferenceID orders the results by the unique_reference_id field. +func ByUniqueReferenceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUniqueReferenceID, opts...).ToFunc() +} + +// ByRatecardDiscounts orders the results by the ratecard_discounts field. +func ByRatecardDiscounts(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRatecardDiscounts, 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() +} + +// BySubscriptionID orders the results by the subscription_id field. +func BySubscriptionID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSubscriptionID, opts...).ToFunc() +} + +// BySubscriptionPhaseID orders the results by the subscription_phase_id field. +func BySubscriptionPhaseID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSubscriptionPhaseID, opts...).ToFunc() +} + +// BySubscriptionItemID orders the results by the subscription_item_id field. +func BySubscriptionItemID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSubscriptionItemID, opts...).ToFunc() +} + +// BySubscriptionBillingPeriodFrom orders the results by the subscription_billing_period_from field. +func BySubscriptionBillingPeriodFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSubscriptionBillingPeriodFrom, opts...).ToFunc() +} + +// BySubscriptionBillingPeriodTo orders the results by the subscription_billing_period_to field. +func BySubscriptionBillingPeriodTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSubscriptionBillingPeriodTo, opts...).ToFunc() +} + +// ByChargeID orders the results by the charge_id field. +func ByChargeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChargeID, opts...).ToFunc() +} + +// ByBillingInvoiceLinesCount orders the results by billing_invoice_lines count. +func ByBillingInvoiceLinesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newBillingInvoiceLinesStep(), opts...) + } +} + +// ByBillingInvoiceLines orders the results by billing_invoice_lines terms. +func ByBillingInvoiceLines(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBillingInvoiceLinesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// BySubscriptionField orders the results by subscription field. +func BySubscriptionField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubscriptionStep(), sql.OrderByField(field, opts...)) + } +} + +// BySubscriptionPhaseField orders the results by subscription_phase field. +func BySubscriptionPhaseField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubscriptionPhaseStep(), sql.OrderByField(field, opts...)) + } +} + +// BySubscriptionItemField orders the results by subscription_item field. +func BySubscriptionItemField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubscriptionItemStep(), sql.OrderByField(field, opts...)) + } +} + +// 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...)) + } +} +func newBillingInvoiceLinesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BillingInvoiceLinesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, BillingInvoiceLinesTable, BillingInvoiceLinesColumn), + ) +} +func newSubscriptionStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SubscriptionInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionTable, SubscriptionColumn), + ) +} +func newSubscriptionPhaseStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SubscriptionPhaseInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionPhaseTable, SubscriptionPhaseColumn), + ) +} +func newSubscriptionItemStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SubscriptionItemInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionItemTable, SubscriptionItemColumn), + ) +} +func newChargeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ChargeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ChargeTable, ChargeColumn), + ) +} diff --git a/ent/db/billinginvoicesplitlinegroup/where.go b/ent/db/billinginvoicesplitlinegroup/where.go new file mode 100644 index 0000000000000000000000000000000000000000..75d8462aca73f35d101229d0b09c61c8e9a59dae --- /dev/null +++ b/ent/db/billinginvoicesplitlinegroup/where.go @@ -0,0 +1,1352 @@ +// Code generated by ent, DO NOT EDIT. + +package billinginvoicesplitlinegroup + +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/pkg/currencyx" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(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.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(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.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(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.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldName, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldDescription, v)) +} + +// Currency applies equality check predicate on the "currency" field. It's identical to CurrencyEQ. +func Currency(v currencyx.Code) predicate.BillingInvoiceSplitLineGroup { + vc := string(v) + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldCurrency, vc)) +} + +// ServicePeriodStart applies equality check predicate on the "service_period_start" field. It's identical to ServicePeriodStartEQ. +func ServicePeriodStart(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldServicePeriodStart, v)) +} + +// ServicePeriodEnd applies equality check predicate on the "service_period_end" field. It's identical to ServicePeriodEndEQ. +func ServicePeriodEnd(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldServicePeriodEnd, v)) +} + +// UniqueReferenceID applies equality check predicate on the "unique_reference_id" field. It's identical to UniqueReferenceIDEQ. +func UniqueReferenceID(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldUniqueReferenceID, v)) +} + +// FeatureKey applies equality check predicate on the "feature_key" field. It's identical to FeatureKeyEQ. +func FeatureKey(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldFeatureKey, v)) +} + +// SubscriptionID applies equality check predicate on the "subscription_id" field. It's identical to SubscriptionIDEQ. +func SubscriptionID(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldSubscriptionID, v)) +} + +// SubscriptionPhaseID applies equality check predicate on the "subscription_phase_id" field. It's identical to SubscriptionPhaseIDEQ. +func SubscriptionPhaseID(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionItemID applies equality check predicate on the "subscription_item_id" field. It's identical to SubscriptionItemIDEQ. +func SubscriptionItemID(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldSubscriptionItemID, v)) +} + +// SubscriptionBillingPeriodFrom applies equality check predicate on the "subscription_billing_period_from" field. It's identical to SubscriptionBillingPeriodFromEQ. +func SubscriptionBillingPeriodFrom(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldSubscriptionBillingPeriodFrom, v)) +} + +// SubscriptionBillingPeriodTo applies equality check predicate on the "subscription_billing_period_to" field. It's identical to SubscriptionBillingPeriodToEQ. +func SubscriptionBillingPeriodTo(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldSubscriptionBillingPeriodTo, v)) +} + +// ChargeID applies equality check predicate on the "charge_id" field. It's identical to ChargeIDEQ. +func ChargeID(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldChargeID, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContainsFold(FieldNamespace, v)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotNull(FieldMetadata)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotNull(FieldDeletedAt)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContainsFold(FieldName, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContainsFold(FieldDescription, v)) +} + +// CurrencyEQ applies the EQ predicate on the "currency" field. +func CurrencyEQ(v currencyx.Code) predicate.BillingInvoiceSplitLineGroup { + vc := string(v) + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldCurrency, vc)) +} + +// CurrencyNEQ applies the NEQ predicate on the "currency" field. +func CurrencyNEQ(v currencyx.Code) predicate.BillingInvoiceSplitLineGroup { + vc := string(v) + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNEQ(FieldCurrency, vc)) +} + +// CurrencyIn applies the In predicate on the "currency" field. +func CurrencyIn(vs ...currencyx.Code) predicate.BillingInvoiceSplitLineGroup { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIn(FieldCurrency, v...)) +} + +// CurrencyNotIn applies the NotIn predicate on the "currency" field. +func CurrencyNotIn(vs ...currencyx.Code) predicate.BillingInvoiceSplitLineGroup { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotIn(FieldCurrency, v...)) +} + +// CurrencyGT applies the GT predicate on the "currency" field. +func CurrencyGT(v currencyx.Code) predicate.BillingInvoiceSplitLineGroup { + vc := string(v) + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGT(FieldCurrency, vc)) +} + +// CurrencyGTE applies the GTE predicate on the "currency" field. +func CurrencyGTE(v currencyx.Code) predicate.BillingInvoiceSplitLineGroup { + vc := string(v) + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGTE(FieldCurrency, vc)) +} + +// CurrencyLT applies the LT predicate on the "currency" field. +func CurrencyLT(v currencyx.Code) predicate.BillingInvoiceSplitLineGroup { + vc := string(v) + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLT(FieldCurrency, vc)) +} + +// CurrencyLTE applies the LTE predicate on the "currency" field. +func CurrencyLTE(v currencyx.Code) predicate.BillingInvoiceSplitLineGroup { + vc := string(v) + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLTE(FieldCurrency, vc)) +} + +// CurrencyContains applies the Contains predicate on the "currency" field. +func CurrencyContains(v currencyx.Code) predicate.BillingInvoiceSplitLineGroup { + vc := string(v) + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContains(FieldCurrency, vc)) +} + +// CurrencyHasPrefix applies the HasPrefix predicate on the "currency" field. +func CurrencyHasPrefix(v currencyx.Code) predicate.BillingInvoiceSplitLineGroup { + vc := string(v) + return predicate.BillingInvoiceSplitLineGroup(sql.FieldHasPrefix(FieldCurrency, vc)) +} + +// CurrencyHasSuffix applies the HasSuffix predicate on the "currency" field. +func CurrencyHasSuffix(v currencyx.Code) predicate.BillingInvoiceSplitLineGroup { + vc := string(v) + return predicate.BillingInvoiceSplitLineGroup(sql.FieldHasSuffix(FieldCurrency, vc)) +} + +// CurrencyEqualFold applies the EqualFold predicate on the "currency" field. +func CurrencyEqualFold(v currencyx.Code) predicate.BillingInvoiceSplitLineGroup { + vc := string(v) + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEqualFold(FieldCurrency, vc)) +} + +// CurrencyContainsFold applies the ContainsFold predicate on the "currency" field. +func CurrencyContainsFold(v currencyx.Code) predicate.BillingInvoiceSplitLineGroup { + vc := string(v) + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContainsFold(FieldCurrency, vc)) +} + +// ServicePeriodStartEQ applies the EQ predicate on the "service_period_start" field. +func ServicePeriodStartEQ(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldServicePeriodStart, v)) +} + +// ServicePeriodStartNEQ applies the NEQ predicate on the "service_period_start" field. +func ServicePeriodStartNEQ(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNEQ(FieldServicePeriodStart, v)) +} + +// ServicePeriodStartIn applies the In predicate on the "service_period_start" field. +func ServicePeriodStartIn(vs ...time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIn(FieldServicePeriodStart, vs...)) +} + +// ServicePeriodStartNotIn applies the NotIn predicate on the "service_period_start" field. +func ServicePeriodStartNotIn(vs ...time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotIn(FieldServicePeriodStart, vs...)) +} + +// ServicePeriodStartGT applies the GT predicate on the "service_period_start" field. +func ServicePeriodStartGT(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGT(FieldServicePeriodStart, v)) +} + +// ServicePeriodStartGTE applies the GTE predicate on the "service_period_start" field. +func ServicePeriodStartGTE(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGTE(FieldServicePeriodStart, v)) +} + +// ServicePeriodStartLT applies the LT predicate on the "service_period_start" field. +func ServicePeriodStartLT(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLT(FieldServicePeriodStart, v)) +} + +// ServicePeriodStartLTE applies the LTE predicate on the "service_period_start" field. +func ServicePeriodStartLTE(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLTE(FieldServicePeriodStart, v)) +} + +// ServicePeriodEndEQ applies the EQ predicate on the "service_period_end" field. +func ServicePeriodEndEQ(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldServicePeriodEnd, v)) +} + +// ServicePeriodEndNEQ applies the NEQ predicate on the "service_period_end" field. +func ServicePeriodEndNEQ(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNEQ(FieldServicePeriodEnd, v)) +} + +// ServicePeriodEndIn applies the In predicate on the "service_period_end" field. +func ServicePeriodEndIn(vs ...time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIn(FieldServicePeriodEnd, vs...)) +} + +// ServicePeriodEndNotIn applies the NotIn predicate on the "service_period_end" field. +func ServicePeriodEndNotIn(vs ...time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotIn(FieldServicePeriodEnd, vs...)) +} + +// ServicePeriodEndGT applies the GT predicate on the "service_period_end" field. +func ServicePeriodEndGT(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGT(FieldServicePeriodEnd, v)) +} + +// ServicePeriodEndGTE applies the GTE predicate on the "service_period_end" field. +func ServicePeriodEndGTE(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGTE(FieldServicePeriodEnd, v)) +} + +// ServicePeriodEndLT applies the LT predicate on the "service_period_end" field. +func ServicePeriodEndLT(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLT(FieldServicePeriodEnd, v)) +} + +// ServicePeriodEndLTE applies the LTE predicate on the "service_period_end" field. +func ServicePeriodEndLTE(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLTE(FieldServicePeriodEnd, v)) +} + +// UniqueReferenceIDEQ applies the EQ predicate on the "unique_reference_id" field. +func UniqueReferenceIDEQ(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDNEQ applies the NEQ predicate on the "unique_reference_id" field. +func UniqueReferenceIDNEQ(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNEQ(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDIn applies the In predicate on the "unique_reference_id" field. +func UniqueReferenceIDIn(vs ...string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIn(FieldUniqueReferenceID, vs...)) +} + +// UniqueReferenceIDNotIn applies the NotIn predicate on the "unique_reference_id" field. +func UniqueReferenceIDNotIn(vs ...string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotIn(FieldUniqueReferenceID, vs...)) +} + +// UniqueReferenceIDGT applies the GT predicate on the "unique_reference_id" field. +func UniqueReferenceIDGT(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGT(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDGTE applies the GTE predicate on the "unique_reference_id" field. +func UniqueReferenceIDGTE(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGTE(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDLT applies the LT predicate on the "unique_reference_id" field. +func UniqueReferenceIDLT(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLT(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDLTE applies the LTE predicate on the "unique_reference_id" field. +func UniqueReferenceIDLTE(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLTE(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDContains applies the Contains predicate on the "unique_reference_id" field. +func UniqueReferenceIDContains(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContains(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDHasPrefix applies the HasPrefix predicate on the "unique_reference_id" field. +func UniqueReferenceIDHasPrefix(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldHasPrefix(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDHasSuffix applies the HasSuffix predicate on the "unique_reference_id" field. +func UniqueReferenceIDHasSuffix(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldHasSuffix(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDIsNil applies the IsNil predicate on the "unique_reference_id" field. +func UniqueReferenceIDIsNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIsNull(FieldUniqueReferenceID)) +} + +// UniqueReferenceIDNotNil applies the NotNil predicate on the "unique_reference_id" field. +func UniqueReferenceIDNotNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotNull(FieldUniqueReferenceID)) +} + +// UniqueReferenceIDEqualFold applies the EqualFold predicate on the "unique_reference_id" field. +func UniqueReferenceIDEqualFold(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEqualFold(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDContainsFold applies the ContainsFold predicate on the "unique_reference_id" field. +func UniqueReferenceIDContainsFold(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContainsFold(FieldUniqueReferenceID, v)) +} + +// RatecardDiscountsIsNil applies the IsNil predicate on the "ratecard_discounts" field. +func RatecardDiscountsIsNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIsNull(FieldRatecardDiscounts)) +} + +// RatecardDiscountsNotNil applies the NotNil predicate on the "ratecard_discounts" field. +func RatecardDiscountsNotNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotNull(FieldRatecardDiscounts)) +} + +// FeatureKeyEQ applies the EQ predicate on the "feature_key" field. +func FeatureKeyEQ(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldFeatureKey, v)) +} + +// FeatureKeyNEQ applies the NEQ predicate on the "feature_key" field. +func FeatureKeyNEQ(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNEQ(FieldFeatureKey, v)) +} + +// FeatureKeyIn applies the In predicate on the "feature_key" field. +func FeatureKeyIn(vs ...string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIn(FieldFeatureKey, vs...)) +} + +// FeatureKeyNotIn applies the NotIn predicate on the "feature_key" field. +func FeatureKeyNotIn(vs ...string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotIn(FieldFeatureKey, vs...)) +} + +// FeatureKeyGT applies the GT predicate on the "feature_key" field. +func FeatureKeyGT(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGT(FieldFeatureKey, v)) +} + +// FeatureKeyGTE applies the GTE predicate on the "feature_key" field. +func FeatureKeyGTE(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGTE(FieldFeatureKey, v)) +} + +// FeatureKeyLT applies the LT predicate on the "feature_key" field. +func FeatureKeyLT(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLT(FieldFeatureKey, v)) +} + +// FeatureKeyLTE applies the LTE predicate on the "feature_key" field. +func FeatureKeyLTE(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLTE(FieldFeatureKey, v)) +} + +// FeatureKeyContains applies the Contains predicate on the "feature_key" field. +func FeatureKeyContains(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContains(FieldFeatureKey, v)) +} + +// FeatureKeyHasPrefix applies the HasPrefix predicate on the "feature_key" field. +func FeatureKeyHasPrefix(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldHasPrefix(FieldFeatureKey, v)) +} + +// FeatureKeyHasSuffix applies the HasSuffix predicate on the "feature_key" field. +func FeatureKeyHasSuffix(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldHasSuffix(FieldFeatureKey, v)) +} + +// FeatureKeyIsNil applies the IsNil predicate on the "feature_key" field. +func FeatureKeyIsNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIsNull(FieldFeatureKey)) +} + +// FeatureKeyNotNil applies the NotNil predicate on the "feature_key" field. +func FeatureKeyNotNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotNull(FieldFeatureKey)) +} + +// FeatureKeyEqualFold applies the EqualFold predicate on the "feature_key" field. +func FeatureKeyEqualFold(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEqualFold(FieldFeatureKey, v)) +} + +// FeatureKeyContainsFold applies the ContainsFold predicate on the "feature_key" field. +func FeatureKeyContainsFold(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContainsFold(FieldFeatureKey, v)) +} + +// SubscriptionIDEQ applies the EQ predicate on the "subscription_id" field. +func SubscriptionIDEQ(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldSubscriptionID, v)) +} + +// SubscriptionIDNEQ applies the NEQ predicate on the "subscription_id" field. +func SubscriptionIDNEQ(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNEQ(FieldSubscriptionID, v)) +} + +// SubscriptionIDIn applies the In predicate on the "subscription_id" field. +func SubscriptionIDIn(vs ...string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIn(FieldSubscriptionID, vs...)) +} + +// SubscriptionIDNotIn applies the NotIn predicate on the "subscription_id" field. +func SubscriptionIDNotIn(vs ...string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotIn(FieldSubscriptionID, vs...)) +} + +// SubscriptionIDGT applies the GT predicate on the "subscription_id" field. +func SubscriptionIDGT(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGT(FieldSubscriptionID, v)) +} + +// SubscriptionIDGTE applies the GTE predicate on the "subscription_id" field. +func SubscriptionIDGTE(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGTE(FieldSubscriptionID, v)) +} + +// SubscriptionIDLT applies the LT predicate on the "subscription_id" field. +func SubscriptionIDLT(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLT(FieldSubscriptionID, v)) +} + +// SubscriptionIDLTE applies the LTE predicate on the "subscription_id" field. +func SubscriptionIDLTE(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLTE(FieldSubscriptionID, v)) +} + +// SubscriptionIDContains applies the Contains predicate on the "subscription_id" field. +func SubscriptionIDContains(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContains(FieldSubscriptionID, v)) +} + +// SubscriptionIDHasPrefix applies the HasPrefix predicate on the "subscription_id" field. +func SubscriptionIDHasPrefix(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldHasPrefix(FieldSubscriptionID, v)) +} + +// SubscriptionIDHasSuffix applies the HasSuffix predicate on the "subscription_id" field. +func SubscriptionIDHasSuffix(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldHasSuffix(FieldSubscriptionID, v)) +} + +// SubscriptionIDIsNil applies the IsNil predicate on the "subscription_id" field. +func SubscriptionIDIsNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIsNull(FieldSubscriptionID)) +} + +// SubscriptionIDNotNil applies the NotNil predicate on the "subscription_id" field. +func SubscriptionIDNotNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotNull(FieldSubscriptionID)) +} + +// SubscriptionIDEqualFold applies the EqualFold predicate on the "subscription_id" field. +func SubscriptionIDEqualFold(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEqualFold(FieldSubscriptionID, v)) +} + +// SubscriptionIDContainsFold applies the ContainsFold predicate on the "subscription_id" field. +func SubscriptionIDContainsFold(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContainsFold(FieldSubscriptionID, v)) +} + +// SubscriptionPhaseIDEQ applies the EQ predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDEQ(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDNEQ applies the NEQ predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDNEQ(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNEQ(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDIn applies the In predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDIn(vs ...string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIn(FieldSubscriptionPhaseID, vs...)) +} + +// SubscriptionPhaseIDNotIn applies the NotIn predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDNotIn(vs ...string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotIn(FieldSubscriptionPhaseID, vs...)) +} + +// SubscriptionPhaseIDGT applies the GT predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDGT(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGT(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDGTE applies the GTE predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDGTE(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGTE(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDLT applies the LT predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDLT(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLT(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDLTE applies the LTE predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDLTE(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLTE(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDContains applies the Contains predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDContains(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContains(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDHasPrefix applies the HasPrefix predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDHasPrefix(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldHasPrefix(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDHasSuffix applies the HasSuffix predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDHasSuffix(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldHasSuffix(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDIsNil applies the IsNil predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDIsNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIsNull(FieldSubscriptionPhaseID)) +} + +// SubscriptionPhaseIDNotNil applies the NotNil predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDNotNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotNull(FieldSubscriptionPhaseID)) +} + +// SubscriptionPhaseIDEqualFold applies the EqualFold predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDEqualFold(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEqualFold(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDContainsFold applies the ContainsFold predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDContainsFold(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContainsFold(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionItemIDEQ applies the EQ predicate on the "subscription_item_id" field. +func SubscriptionItemIDEQ(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDNEQ applies the NEQ predicate on the "subscription_item_id" field. +func SubscriptionItemIDNEQ(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNEQ(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDIn applies the In predicate on the "subscription_item_id" field. +func SubscriptionItemIDIn(vs ...string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIn(FieldSubscriptionItemID, vs...)) +} + +// SubscriptionItemIDNotIn applies the NotIn predicate on the "subscription_item_id" field. +func SubscriptionItemIDNotIn(vs ...string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotIn(FieldSubscriptionItemID, vs...)) +} + +// SubscriptionItemIDGT applies the GT predicate on the "subscription_item_id" field. +func SubscriptionItemIDGT(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGT(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDGTE applies the GTE predicate on the "subscription_item_id" field. +func SubscriptionItemIDGTE(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGTE(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDLT applies the LT predicate on the "subscription_item_id" field. +func SubscriptionItemIDLT(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLT(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDLTE applies the LTE predicate on the "subscription_item_id" field. +func SubscriptionItemIDLTE(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLTE(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDContains applies the Contains predicate on the "subscription_item_id" field. +func SubscriptionItemIDContains(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContains(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDHasPrefix applies the HasPrefix predicate on the "subscription_item_id" field. +func SubscriptionItemIDHasPrefix(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldHasPrefix(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDHasSuffix applies the HasSuffix predicate on the "subscription_item_id" field. +func SubscriptionItemIDHasSuffix(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldHasSuffix(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDIsNil applies the IsNil predicate on the "subscription_item_id" field. +func SubscriptionItemIDIsNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIsNull(FieldSubscriptionItemID)) +} + +// SubscriptionItemIDNotNil applies the NotNil predicate on the "subscription_item_id" field. +func SubscriptionItemIDNotNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotNull(FieldSubscriptionItemID)) +} + +// SubscriptionItemIDEqualFold applies the EqualFold predicate on the "subscription_item_id" field. +func SubscriptionItemIDEqualFold(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEqualFold(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDContainsFold applies the ContainsFold predicate on the "subscription_item_id" field. +func SubscriptionItemIDContainsFold(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContainsFold(FieldSubscriptionItemID, v)) +} + +// SubscriptionBillingPeriodFromEQ applies the EQ predicate on the "subscription_billing_period_from" field. +func SubscriptionBillingPeriodFromEQ(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldSubscriptionBillingPeriodFrom, v)) +} + +// SubscriptionBillingPeriodFromNEQ applies the NEQ predicate on the "subscription_billing_period_from" field. +func SubscriptionBillingPeriodFromNEQ(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNEQ(FieldSubscriptionBillingPeriodFrom, v)) +} + +// SubscriptionBillingPeriodFromIn applies the In predicate on the "subscription_billing_period_from" field. +func SubscriptionBillingPeriodFromIn(vs ...time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIn(FieldSubscriptionBillingPeriodFrom, vs...)) +} + +// SubscriptionBillingPeriodFromNotIn applies the NotIn predicate on the "subscription_billing_period_from" field. +func SubscriptionBillingPeriodFromNotIn(vs ...time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotIn(FieldSubscriptionBillingPeriodFrom, vs...)) +} + +// SubscriptionBillingPeriodFromGT applies the GT predicate on the "subscription_billing_period_from" field. +func SubscriptionBillingPeriodFromGT(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGT(FieldSubscriptionBillingPeriodFrom, v)) +} + +// SubscriptionBillingPeriodFromGTE applies the GTE predicate on the "subscription_billing_period_from" field. +func SubscriptionBillingPeriodFromGTE(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGTE(FieldSubscriptionBillingPeriodFrom, v)) +} + +// SubscriptionBillingPeriodFromLT applies the LT predicate on the "subscription_billing_period_from" field. +func SubscriptionBillingPeriodFromLT(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLT(FieldSubscriptionBillingPeriodFrom, v)) +} + +// SubscriptionBillingPeriodFromLTE applies the LTE predicate on the "subscription_billing_period_from" field. +func SubscriptionBillingPeriodFromLTE(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLTE(FieldSubscriptionBillingPeriodFrom, v)) +} + +// SubscriptionBillingPeriodFromIsNil applies the IsNil predicate on the "subscription_billing_period_from" field. +func SubscriptionBillingPeriodFromIsNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIsNull(FieldSubscriptionBillingPeriodFrom)) +} + +// SubscriptionBillingPeriodFromNotNil applies the NotNil predicate on the "subscription_billing_period_from" field. +func SubscriptionBillingPeriodFromNotNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotNull(FieldSubscriptionBillingPeriodFrom)) +} + +// SubscriptionBillingPeriodToEQ applies the EQ predicate on the "subscription_billing_period_to" field. +func SubscriptionBillingPeriodToEQ(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldSubscriptionBillingPeriodTo, v)) +} + +// SubscriptionBillingPeriodToNEQ applies the NEQ predicate on the "subscription_billing_period_to" field. +func SubscriptionBillingPeriodToNEQ(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNEQ(FieldSubscriptionBillingPeriodTo, v)) +} + +// SubscriptionBillingPeriodToIn applies the In predicate on the "subscription_billing_period_to" field. +func SubscriptionBillingPeriodToIn(vs ...time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIn(FieldSubscriptionBillingPeriodTo, vs...)) +} + +// SubscriptionBillingPeriodToNotIn applies the NotIn predicate on the "subscription_billing_period_to" field. +func SubscriptionBillingPeriodToNotIn(vs ...time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotIn(FieldSubscriptionBillingPeriodTo, vs...)) +} + +// SubscriptionBillingPeriodToGT applies the GT predicate on the "subscription_billing_period_to" field. +func SubscriptionBillingPeriodToGT(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGT(FieldSubscriptionBillingPeriodTo, v)) +} + +// SubscriptionBillingPeriodToGTE applies the GTE predicate on the "subscription_billing_period_to" field. +func SubscriptionBillingPeriodToGTE(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGTE(FieldSubscriptionBillingPeriodTo, v)) +} + +// SubscriptionBillingPeriodToLT applies the LT predicate on the "subscription_billing_period_to" field. +func SubscriptionBillingPeriodToLT(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLT(FieldSubscriptionBillingPeriodTo, v)) +} + +// SubscriptionBillingPeriodToLTE applies the LTE predicate on the "subscription_billing_period_to" field. +func SubscriptionBillingPeriodToLTE(v time.Time) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLTE(FieldSubscriptionBillingPeriodTo, v)) +} + +// SubscriptionBillingPeriodToIsNil applies the IsNil predicate on the "subscription_billing_period_to" field. +func SubscriptionBillingPeriodToIsNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIsNull(FieldSubscriptionBillingPeriodTo)) +} + +// SubscriptionBillingPeriodToNotNil applies the NotNil predicate on the "subscription_billing_period_to" field. +func SubscriptionBillingPeriodToNotNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotNull(FieldSubscriptionBillingPeriodTo)) +} + +// ChargeIDEQ applies the EQ predicate on the "charge_id" field. +func ChargeIDEQ(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEQ(FieldChargeID, v)) +} + +// ChargeIDNEQ applies the NEQ predicate on the "charge_id" field. +func ChargeIDNEQ(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNEQ(FieldChargeID, v)) +} + +// ChargeIDIn applies the In predicate on the "charge_id" field. +func ChargeIDIn(vs ...string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIn(FieldChargeID, vs...)) +} + +// ChargeIDNotIn applies the NotIn predicate on the "charge_id" field. +func ChargeIDNotIn(vs ...string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotIn(FieldChargeID, vs...)) +} + +// ChargeIDGT applies the GT predicate on the "charge_id" field. +func ChargeIDGT(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGT(FieldChargeID, v)) +} + +// ChargeIDGTE applies the GTE predicate on the "charge_id" field. +func ChargeIDGTE(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldGTE(FieldChargeID, v)) +} + +// ChargeIDLT applies the LT predicate on the "charge_id" field. +func ChargeIDLT(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLT(FieldChargeID, v)) +} + +// ChargeIDLTE applies the LTE predicate on the "charge_id" field. +func ChargeIDLTE(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldLTE(FieldChargeID, v)) +} + +// ChargeIDContains applies the Contains predicate on the "charge_id" field. +func ChargeIDContains(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContains(FieldChargeID, v)) +} + +// ChargeIDHasPrefix applies the HasPrefix predicate on the "charge_id" field. +func ChargeIDHasPrefix(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldHasPrefix(FieldChargeID, v)) +} + +// ChargeIDHasSuffix applies the HasSuffix predicate on the "charge_id" field. +func ChargeIDHasSuffix(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldHasSuffix(FieldChargeID, v)) +} + +// ChargeIDIsNil applies the IsNil predicate on the "charge_id" field. +func ChargeIDIsNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldIsNull(FieldChargeID)) +} + +// ChargeIDNotNil applies the NotNil predicate on the "charge_id" field. +func ChargeIDNotNil() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldNotNull(FieldChargeID)) +} + +// ChargeIDEqualFold applies the EqualFold predicate on the "charge_id" field. +func ChargeIDEqualFold(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldEqualFold(FieldChargeID, v)) +} + +// ChargeIDContainsFold applies the ContainsFold predicate on the "charge_id" field. +func ChargeIDContainsFold(v string) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.FieldContainsFold(FieldChargeID, v)) +} + +// HasBillingInvoiceLines applies the HasEdge predicate on the "billing_invoice_lines" edge. +func HasBillingInvoiceLines() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, BillingInvoiceLinesTable, BillingInvoiceLinesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBillingInvoiceLinesWith applies the HasEdge predicate on the "billing_invoice_lines" edge with a given conditions (other predicates). +func HasBillingInvoiceLinesWith(preds ...predicate.BillingInvoiceLine) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(func(s *sql.Selector) { + step := newBillingInvoiceLinesStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSubscription applies the HasEdge predicate on the "subscription" edge. +func HasSubscription() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionTable, SubscriptionColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubscriptionWith applies the HasEdge predicate on the "subscription" edge with a given conditions (other predicates). +func HasSubscriptionWith(preds ...predicate.Subscription) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(func(s *sql.Selector) { + step := newSubscriptionStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSubscriptionPhase applies the HasEdge predicate on the "subscription_phase" edge. +func HasSubscriptionPhase() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionPhaseTable, SubscriptionPhaseColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubscriptionPhaseWith applies the HasEdge predicate on the "subscription_phase" edge with a given conditions (other predicates). +func HasSubscriptionPhaseWith(preds ...predicate.SubscriptionPhase) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(func(s *sql.Selector) { + step := newSubscriptionPhaseStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSubscriptionItem applies the HasEdge predicate on the "subscription_item" edge. +func HasSubscriptionItem() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionItemTable, SubscriptionItemColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubscriptionItemWith applies the HasEdge predicate on the "subscription_item" edge with a given conditions (other predicates). +func HasSubscriptionItemWith(preds ...predicate.SubscriptionItem) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(func(s *sql.Selector) { + step := newSubscriptionItemStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasCharge applies the HasEdge predicate on the "charge" edge. +func HasCharge() predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, 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.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(func(s *sql.Selector) { + step := newChargeStep() + 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.BillingInvoiceSplitLineGroup) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.BillingInvoiceSplitLineGroup) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.BillingInvoiceSplitLineGroup) predicate.BillingInvoiceSplitLineGroup { + return predicate.BillingInvoiceSplitLineGroup(sql.NotPredicates(p)) +} diff --git a/ent/db/billinginvoicesplitlinegroup_create.go b/ent/db/billinginvoicesplitlinegroup_create.go new file mode 100644 index 0000000000000000000000000000000000000000..afc07bfc4fe279926029a1a9f118b694f1a4464c --- /dev/null +++ b/ent/db/billinginvoicesplitlinegroup_create.go @@ -0,0 +1,1562 @@ +// 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/billing" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicesplitlinegroup" + "github.com/openmeterio/openmeter/openmeter/ent/db/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionphase" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" +) + +// BillingInvoiceSplitLineGroupCreate is the builder for creating a BillingInvoiceSplitLineGroup entity. +type BillingInvoiceSplitLineGroupCreate struct { + config + mutation *BillingInvoiceSplitLineGroupMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetNamespace(v string) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetMetadata sets the "metadata" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetMetadata(v map[string]string) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetMetadata(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetCreatedAt(v time.Time) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *BillingInvoiceSplitLineGroupCreate) SetNillableCreatedAt(v *time.Time) *BillingInvoiceSplitLineGroupCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetUpdatedAt(v time.Time) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *BillingInvoiceSplitLineGroupCreate) SetNillableUpdatedAt(v *time.Time) *BillingInvoiceSplitLineGroupCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetDeletedAt(v time.Time) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *BillingInvoiceSplitLineGroupCreate) SetNillableDeletedAt(v *time.Time) *BillingInvoiceSplitLineGroupCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetName sets the "name" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetName(v string) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetName(v) + return _c +} + +// SetDescription sets the "description" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetDescription(v string) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetDescription(v) + return _c +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_c *BillingInvoiceSplitLineGroupCreate) SetNillableDescription(v *string) *BillingInvoiceSplitLineGroupCreate { + if v != nil { + _c.SetDescription(*v) + } + return _c +} + +// SetCurrency sets the "currency" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetCurrency(v currencyx.Code) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetCurrency(v) + return _c +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetServicePeriodStart(v time.Time) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetServicePeriodStart(v) + return _c +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetServicePeriodEnd(v time.Time) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetServicePeriodEnd(v) + return _c +} + +// SetUniqueReferenceID sets the "unique_reference_id" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetUniqueReferenceID(v string) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetUniqueReferenceID(v) + return _c +} + +// SetNillableUniqueReferenceID sets the "unique_reference_id" field if the given value is not nil. +func (_c *BillingInvoiceSplitLineGroupCreate) SetNillableUniqueReferenceID(v *string) *BillingInvoiceSplitLineGroupCreate { + if v != nil { + _c.SetUniqueReferenceID(*v) + } + return _c +} + +// SetRatecardDiscounts sets the "ratecard_discounts" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetRatecardDiscounts(v *billing.Discounts) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetRatecardDiscounts(v) + return _c +} + +// SetFeatureKey sets the "feature_key" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetFeatureKey(v string) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetFeatureKey(v) + return _c +} + +// SetNillableFeatureKey sets the "feature_key" field if the given value is not nil. +func (_c *BillingInvoiceSplitLineGroupCreate) SetNillableFeatureKey(v *string) *BillingInvoiceSplitLineGroupCreate { + if v != nil { + _c.SetFeatureKey(*v) + } + return _c +} + +// SetPrice sets the "price" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetPrice(v *productcatalog.Price) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetPrice(v) + return _c +} + +// SetSubscriptionID sets the "subscription_id" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetSubscriptionID(v string) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetSubscriptionID(v) + return _c +} + +// SetNillableSubscriptionID sets the "subscription_id" field if the given value is not nil. +func (_c *BillingInvoiceSplitLineGroupCreate) SetNillableSubscriptionID(v *string) *BillingInvoiceSplitLineGroupCreate { + if v != nil { + _c.SetSubscriptionID(*v) + } + return _c +} + +// SetSubscriptionPhaseID sets the "subscription_phase_id" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetSubscriptionPhaseID(v string) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetSubscriptionPhaseID(v) + return _c +} + +// SetNillableSubscriptionPhaseID sets the "subscription_phase_id" field if the given value is not nil. +func (_c *BillingInvoiceSplitLineGroupCreate) SetNillableSubscriptionPhaseID(v *string) *BillingInvoiceSplitLineGroupCreate { + if v != nil { + _c.SetSubscriptionPhaseID(*v) + } + return _c +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetSubscriptionItemID(v string) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetSubscriptionItemID(v) + return _c +} + +// SetNillableSubscriptionItemID sets the "subscription_item_id" field if the given value is not nil. +func (_c *BillingInvoiceSplitLineGroupCreate) SetNillableSubscriptionItemID(v *string) *BillingInvoiceSplitLineGroupCreate { + if v != nil { + _c.SetSubscriptionItemID(*v) + } + return _c +} + +// SetSubscriptionBillingPeriodFrom sets the "subscription_billing_period_from" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetSubscriptionBillingPeriodFrom(v time.Time) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetSubscriptionBillingPeriodFrom(v) + return _c +} + +// SetNillableSubscriptionBillingPeriodFrom sets the "subscription_billing_period_from" field if the given value is not nil. +func (_c *BillingInvoiceSplitLineGroupCreate) SetNillableSubscriptionBillingPeriodFrom(v *time.Time) *BillingInvoiceSplitLineGroupCreate { + if v != nil { + _c.SetSubscriptionBillingPeriodFrom(*v) + } + return _c +} + +// SetSubscriptionBillingPeriodTo sets the "subscription_billing_period_to" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetSubscriptionBillingPeriodTo(v time.Time) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetSubscriptionBillingPeriodTo(v) + return _c +} + +// SetNillableSubscriptionBillingPeriodTo sets the "subscription_billing_period_to" field if the given value is not nil. +func (_c *BillingInvoiceSplitLineGroupCreate) SetNillableSubscriptionBillingPeriodTo(v *time.Time) *BillingInvoiceSplitLineGroupCreate { + if v != nil { + _c.SetSubscriptionBillingPeriodTo(*v) + } + return _c +} + +// SetChargeID sets the "charge_id" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetChargeID(v string) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetChargeID(v) + return _c +} + +// SetNillableChargeID sets the "charge_id" field if the given value is not nil. +func (_c *BillingInvoiceSplitLineGroupCreate) SetNillableChargeID(v *string) *BillingInvoiceSplitLineGroupCreate { + if v != nil { + _c.SetChargeID(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *BillingInvoiceSplitLineGroupCreate) SetID(v string) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *BillingInvoiceSplitLineGroupCreate) SetNillableID(v *string) *BillingInvoiceSplitLineGroupCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// AddBillingInvoiceLineIDs adds the "billing_invoice_lines" edge to the BillingInvoiceLine entity by IDs. +func (_c *BillingInvoiceSplitLineGroupCreate) AddBillingInvoiceLineIDs(ids ...string) *BillingInvoiceSplitLineGroupCreate { + _c.mutation.AddBillingInvoiceLineIDs(ids...) + return _c +} + +// AddBillingInvoiceLines adds the "billing_invoice_lines" edges to the BillingInvoiceLine entity. +func (_c *BillingInvoiceSplitLineGroupCreate) AddBillingInvoiceLines(v ...*BillingInvoiceLine) *BillingInvoiceSplitLineGroupCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddBillingInvoiceLineIDs(ids...) +} + +// SetSubscription sets the "subscription" edge to the Subscription entity. +func (_c *BillingInvoiceSplitLineGroupCreate) SetSubscription(v *Subscription) *BillingInvoiceSplitLineGroupCreate { + return _c.SetSubscriptionID(v.ID) +} + +// SetSubscriptionPhase sets the "subscription_phase" edge to the SubscriptionPhase entity. +func (_c *BillingInvoiceSplitLineGroupCreate) SetSubscriptionPhase(v *SubscriptionPhase) *BillingInvoiceSplitLineGroupCreate { + return _c.SetSubscriptionPhaseID(v.ID) +} + +// SetSubscriptionItem sets the "subscription_item" edge to the SubscriptionItem entity. +func (_c *BillingInvoiceSplitLineGroupCreate) SetSubscriptionItem(v *SubscriptionItem) *BillingInvoiceSplitLineGroupCreate { + return _c.SetSubscriptionItemID(v.ID) +} + +// SetCharge sets the "charge" edge to the Charge entity. +func (_c *BillingInvoiceSplitLineGroupCreate) SetCharge(v *Charge) *BillingInvoiceSplitLineGroupCreate { + return _c.SetChargeID(v.ID) +} + +// Mutation returns the BillingInvoiceSplitLineGroupMutation object of the builder. +func (_c *BillingInvoiceSplitLineGroupCreate) Mutation() *BillingInvoiceSplitLineGroupMutation { + return _c.mutation +} + +// Save creates the BillingInvoiceSplitLineGroup in the database. +func (_c *BillingInvoiceSplitLineGroupCreate) Save(ctx context.Context) (*BillingInvoiceSplitLineGroup, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *BillingInvoiceSplitLineGroupCreate) SaveX(ctx context.Context) *BillingInvoiceSplitLineGroup { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingInvoiceSplitLineGroupCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingInvoiceSplitLineGroupCreate) 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 *BillingInvoiceSplitLineGroupCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := billinginvoicesplitlinegroup.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := billinginvoicesplitlinegroup.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := billinginvoicesplitlinegroup.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *BillingInvoiceSplitLineGroupCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "BillingInvoiceSplitLineGroup.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := billinginvoicesplitlinegroup.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceSplitLineGroup.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "BillingInvoiceSplitLineGroup.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "BillingInvoiceSplitLineGroup.updated_at"`)} + } + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "BillingInvoiceSplitLineGroup.name"`)} + } + if _, ok := _c.mutation.Currency(); !ok { + return &ValidationError{Name: "currency", err: errors.New(`db: missing required field "BillingInvoiceSplitLineGroup.currency"`)} + } + if v, ok := _c.mutation.Currency(); ok { + if err := billinginvoicesplitlinegroup.CurrencyValidator(string(v)); err != nil { + return &ValidationError{Name: "currency", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceSplitLineGroup.currency": %w`, err)} + } + } + if _, ok := _c.mutation.ServicePeriodStart(); !ok { + return &ValidationError{Name: "service_period_start", err: errors.New(`db: missing required field "BillingInvoiceSplitLineGroup.service_period_start"`)} + } + if _, ok := _c.mutation.ServicePeriodEnd(); !ok { + return &ValidationError{Name: "service_period_end", err: errors.New(`db: missing required field "BillingInvoiceSplitLineGroup.service_period_end"`)} + } + if v, ok := _c.mutation.RatecardDiscounts(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "ratecard_discounts", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceSplitLineGroup.ratecard_discounts": %w`, err)} + } + } + if _, ok := _c.mutation.Price(); !ok { + return &ValidationError{Name: "price", err: errors.New(`db: missing required field "BillingInvoiceSplitLineGroup.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 "BillingInvoiceSplitLineGroup.price": %w`, err)} + } + } + return nil +} + +func (_c *BillingInvoiceSplitLineGroupCreate) sqlSave(ctx context.Context) (*BillingInvoiceSplitLineGroup, 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 BillingInvoiceSplitLineGroup.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *BillingInvoiceSplitLineGroupCreate) createSpec() (*BillingInvoiceSplitLineGroup, *sqlgraph.CreateSpec, error) { + var ( + _node = &BillingInvoiceSplitLineGroup{config: _c.config} + _spec = sqlgraph.NewCreateSpec(billinginvoicesplitlinegroup.Table, sqlgraph.NewFieldSpec(billinginvoicesplitlinegroup.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(billinginvoicesplitlinegroup.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Metadata(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldMetadata, field.TypeJSON, value) + _node.Metadata = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Description(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldDescription, field.TypeString, value) + _node.Description = &value + } + if value, ok := _c.mutation.Currency(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldCurrency, field.TypeString, value) + _node.Currency = value + } + if value, ok := _c.mutation.ServicePeriodStart(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldServicePeriodStart, field.TypeTime, value) + _node.ServicePeriodStart = value + } + if value, ok := _c.mutation.ServicePeriodEnd(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldServicePeriodEnd, field.TypeTime, value) + _node.ServicePeriodEnd = value + } + if value, ok := _c.mutation.UniqueReferenceID(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldUniqueReferenceID, field.TypeString, value) + _node.UniqueReferenceID = &value + } + if value, ok := _c.mutation.RatecardDiscounts(); ok { + vv, err := billinginvoicesplitlinegroup.ValueScanner.RatecardDiscounts.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(billinginvoicesplitlinegroup.FieldRatecardDiscounts, field.TypeString, vv) + _node.RatecardDiscounts = value + } + if value, ok := _c.mutation.FeatureKey(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldFeatureKey, field.TypeString, value) + _node.FeatureKey = &value + } + if value, ok := _c.mutation.Price(); ok { + vv, err := billinginvoicesplitlinegroup.ValueScanner.Price.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(billinginvoicesplitlinegroup.FieldPrice, field.TypeString, vv) + _node.Price = value + } + if value, ok := _c.mutation.SubscriptionBillingPeriodFrom(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom, field.TypeTime, value) + _node.SubscriptionBillingPeriodFrom = &value + } + if value, ok := _c.mutation.SubscriptionBillingPeriodTo(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo, field.TypeTime, value) + _node.SubscriptionBillingPeriodTo = &value + } + if nodes := _c.mutation.BillingInvoiceLinesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billinginvoicesplitlinegroup.BillingInvoiceLinesTable, + Columns: []string{billinginvoicesplitlinegroup.BillingInvoiceLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.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.SubscriptionIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicesplitlinegroup.SubscriptionTable, + Columns: []string{billinginvoicesplitlinegroup.SubscriptionColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscription.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.SubscriptionID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.SubscriptionPhaseIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicesplitlinegroup.SubscriptionPhaseTable, + Columns: []string{billinginvoicesplitlinegroup.SubscriptionPhaseColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionphase.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.SubscriptionPhaseID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.SubscriptionItemIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicesplitlinegroup.SubscriptionItemTable, + Columns: []string{billinginvoicesplitlinegroup.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.SubscriptionItemID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.ChargeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicesplitlinegroup.ChargeTable, + Columns: []string{billinginvoicesplitlinegroup.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.ChargeID = &nodes[0] + _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.BillingInvoiceSplitLineGroup.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.BillingInvoiceSplitLineGroupUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *BillingInvoiceSplitLineGroupCreate) OnConflict(opts ...sql.ConflictOption) *BillingInvoiceSplitLineGroupUpsertOne { + _c.conflict = opts + return &BillingInvoiceSplitLineGroupUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingInvoiceSplitLineGroup.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingInvoiceSplitLineGroupCreate) OnConflictColumns(columns ...string) *BillingInvoiceSplitLineGroupUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingInvoiceSplitLineGroupUpsertOne{ + create: _c, + } +} + +type ( + // BillingInvoiceSplitLineGroupUpsertOne is the builder for "upsert"-ing + // one BillingInvoiceSplitLineGroup node. + BillingInvoiceSplitLineGroupUpsertOne struct { + create *BillingInvoiceSplitLineGroupCreate + } + + // BillingInvoiceSplitLineGroupUpsert is the "OnConflict" setter. + BillingInvoiceSplitLineGroupUpsert struct { + *sql.UpdateSet + } +) + +// SetMetadata sets the "metadata" field. +func (u *BillingInvoiceSplitLineGroupUpsert) SetMetadata(v map[string]string) *BillingInvoiceSplitLineGroupUpsert { + u.Set(billinginvoicesplitlinegroup.FieldMetadata, v) + return u +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsert) UpdateMetadata() *BillingInvoiceSplitLineGroupUpsert { + u.SetExcluded(billinginvoicesplitlinegroup.FieldMetadata) + return u +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *BillingInvoiceSplitLineGroupUpsert) ClearMetadata() *BillingInvoiceSplitLineGroupUpsert { + u.SetNull(billinginvoicesplitlinegroup.FieldMetadata) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingInvoiceSplitLineGroupUpsert) SetUpdatedAt(v time.Time) *BillingInvoiceSplitLineGroupUpsert { + u.Set(billinginvoicesplitlinegroup.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsert) UpdateUpdatedAt() *BillingInvoiceSplitLineGroupUpsert { + u.SetExcluded(billinginvoicesplitlinegroup.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingInvoiceSplitLineGroupUpsert) SetDeletedAt(v time.Time) *BillingInvoiceSplitLineGroupUpsert { + u.Set(billinginvoicesplitlinegroup.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsert) UpdateDeletedAt() *BillingInvoiceSplitLineGroupUpsert { + u.SetExcluded(billinginvoicesplitlinegroup.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingInvoiceSplitLineGroupUpsert) ClearDeletedAt() *BillingInvoiceSplitLineGroupUpsert { + u.SetNull(billinginvoicesplitlinegroup.FieldDeletedAt) + return u +} + +// SetName sets the "name" field. +func (u *BillingInvoiceSplitLineGroupUpsert) SetName(v string) *BillingInvoiceSplitLineGroupUpsert { + u.Set(billinginvoicesplitlinegroup.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsert) UpdateName() *BillingInvoiceSplitLineGroupUpsert { + u.SetExcluded(billinginvoicesplitlinegroup.FieldName) + return u +} + +// SetDescription sets the "description" field. +func (u *BillingInvoiceSplitLineGroupUpsert) SetDescription(v string) *BillingInvoiceSplitLineGroupUpsert { + u.Set(billinginvoicesplitlinegroup.FieldDescription, v) + return u +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsert) UpdateDescription() *BillingInvoiceSplitLineGroupUpsert { + u.SetExcluded(billinginvoicesplitlinegroup.FieldDescription) + return u +} + +// ClearDescription clears the value of the "description" field. +func (u *BillingInvoiceSplitLineGroupUpsert) ClearDescription() *BillingInvoiceSplitLineGroupUpsert { + u.SetNull(billinginvoicesplitlinegroup.FieldDescription) + return u +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (u *BillingInvoiceSplitLineGroupUpsert) SetServicePeriodStart(v time.Time) *BillingInvoiceSplitLineGroupUpsert { + u.Set(billinginvoicesplitlinegroup.FieldServicePeriodStart, v) + return u +} + +// UpdateServicePeriodStart sets the "service_period_start" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsert) UpdateServicePeriodStart() *BillingInvoiceSplitLineGroupUpsert { + u.SetExcluded(billinginvoicesplitlinegroup.FieldServicePeriodStart) + return u +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (u *BillingInvoiceSplitLineGroupUpsert) SetServicePeriodEnd(v time.Time) *BillingInvoiceSplitLineGroupUpsert { + u.Set(billinginvoicesplitlinegroup.FieldServicePeriodEnd, v) + return u +} + +// UpdateServicePeriodEnd sets the "service_period_end" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsert) UpdateServicePeriodEnd() *BillingInvoiceSplitLineGroupUpsert { + u.SetExcluded(billinginvoicesplitlinegroup.FieldServicePeriodEnd) + return u +} + +// SetRatecardDiscounts sets the "ratecard_discounts" field. +func (u *BillingInvoiceSplitLineGroupUpsert) SetRatecardDiscounts(v *billing.Discounts) *BillingInvoiceSplitLineGroupUpsert { + u.Set(billinginvoicesplitlinegroup.FieldRatecardDiscounts, v) + return u +} + +// UpdateRatecardDiscounts sets the "ratecard_discounts" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsert) UpdateRatecardDiscounts() *BillingInvoiceSplitLineGroupUpsert { + u.SetExcluded(billinginvoicesplitlinegroup.FieldRatecardDiscounts) + return u +} + +// ClearRatecardDiscounts clears the value of the "ratecard_discounts" field. +func (u *BillingInvoiceSplitLineGroupUpsert) ClearRatecardDiscounts() *BillingInvoiceSplitLineGroupUpsert { + u.SetNull(billinginvoicesplitlinegroup.FieldRatecardDiscounts) + return u +} + +// SetSubscriptionBillingPeriodFrom sets the "subscription_billing_period_from" field. +func (u *BillingInvoiceSplitLineGroupUpsert) SetSubscriptionBillingPeriodFrom(v time.Time) *BillingInvoiceSplitLineGroupUpsert { + u.Set(billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom, v) + return u +} + +// UpdateSubscriptionBillingPeriodFrom sets the "subscription_billing_period_from" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsert) UpdateSubscriptionBillingPeriodFrom() *BillingInvoiceSplitLineGroupUpsert { + u.SetExcluded(billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom) + return u +} + +// ClearSubscriptionBillingPeriodFrom clears the value of the "subscription_billing_period_from" field. +func (u *BillingInvoiceSplitLineGroupUpsert) ClearSubscriptionBillingPeriodFrom() *BillingInvoiceSplitLineGroupUpsert { + u.SetNull(billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom) + return u +} + +// SetSubscriptionBillingPeriodTo sets the "subscription_billing_period_to" field. +func (u *BillingInvoiceSplitLineGroupUpsert) SetSubscriptionBillingPeriodTo(v time.Time) *BillingInvoiceSplitLineGroupUpsert { + u.Set(billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo, v) + return u +} + +// UpdateSubscriptionBillingPeriodTo sets the "subscription_billing_period_to" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsert) UpdateSubscriptionBillingPeriodTo() *BillingInvoiceSplitLineGroupUpsert { + u.SetExcluded(billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo) + return u +} + +// ClearSubscriptionBillingPeriodTo clears the value of the "subscription_billing_period_to" field. +func (u *BillingInvoiceSplitLineGroupUpsert) ClearSubscriptionBillingPeriodTo() *BillingInvoiceSplitLineGroupUpsert { + u.SetNull(billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo) + return u +} + +// SetChargeID sets the "charge_id" field. +func (u *BillingInvoiceSplitLineGroupUpsert) SetChargeID(v string) *BillingInvoiceSplitLineGroupUpsert { + u.Set(billinginvoicesplitlinegroup.FieldChargeID, v) + return u +} + +// UpdateChargeID sets the "charge_id" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsert) UpdateChargeID() *BillingInvoiceSplitLineGroupUpsert { + u.SetExcluded(billinginvoicesplitlinegroup.FieldChargeID) + return u +} + +// ClearChargeID clears the value of the "charge_id" field. +func (u *BillingInvoiceSplitLineGroupUpsert) ClearChargeID() *BillingInvoiceSplitLineGroupUpsert { + u.SetNull(billinginvoicesplitlinegroup.FieldChargeID) + 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.BillingInvoiceSplitLineGroup.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(billinginvoicesplitlinegroup.FieldID) +// }), +// ). +// Exec(ctx) +func (u *BillingInvoiceSplitLineGroupUpsertOne) UpdateNewValues() *BillingInvoiceSplitLineGroupUpsertOne { + 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(billinginvoicesplitlinegroup.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(billinginvoicesplitlinegroup.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(billinginvoicesplitlinegroup.FieldCreatedAt) + } + if _, exists := u.create.mutation.Currency(); exists { + s.SetIgnore(billinginvoicesplitlinegroup.FieldCurrency) + } + if _, exists := u.create.mutation.UniqueReferenceID(); exists { + s.SetIgnore(billinginvoicesplitlinegroup.FieldUniqueReferenceID) + } + if _, exists := u.create.mutation.FeatureKey(); exists { + s.SetIgnore(billinginvoicesplitlinegroup.FieldFeatureKey) + } + if _, exists := u.create.mutation.Price(); exists { + s.SetIgnore(billinginvoicesplitlinegroup.FieldPrice) + } + if _, exists := u.create.mutation.SubscriptionID(); exists { + s.SetIgnore(billinginvoicesplitlinegroup.FieldSubscriptionID) + } + if _, exists := u.create.mutation.SubscriptionPhaseID(); exists { + s.SetIgnore(billinginvoicesplitlinegroup.FieldSubscriptionPhaseID) + } + if _, exists := u.create.mutation.SubscriptionItemID(); exists { + s.SetIgnore(billinginvoicesplitlinegroup.FieldSubscriptionItemID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingInvoiceSplitLineGroup.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingInvoiceSplitLineGroupUpsertOne) Ignore() *BillingInvoiceSplitLineGroupUpsertOne { + 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 *BillingInvoiceSplitLineGroupUpsertOne) DoNothing() *BillingInvoiceSplitLineGroupUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingInvoiceSplitLineGroupCreate.OnConflict +// documentation for more info. +func (u *BillingInvoiceSplitLineGroupUpsertOne) Update(set func(*BillingInvoiceSplitLineGroupUpsert)) *BillingInvoiceSplitLineGroupUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingInvoiceSplitLineGroupUpsert{UpdateSet: update}) + })) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *BillingInvoiceSplitLineGroupUpsertOne) SetMetadata(v map[string]string) *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertOne) UpdateMetadata() *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *BillingInvoiceSplitLineGroupUpsertOne) ClearMetadata() *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingInvoiceSplitLineGroupUpsertOne) SetUpdatedAt(v time.Time) *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertOne) UpdateUpdatedAt() *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingInvoiceSplitLineGroupUpsertOne) SetDeletedAt(v time.Time) *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertOne) UpdateDeletedAt() *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingInvoiceSplitLineGroupUpsertOne) ClearDeletedAt() *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *BillingInvoiceSplitLineGroupUpsertOne) SetName(v string) *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertOne) UpdateName() *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *BillingInvoiceSplitLineGroupUpsertOne) SetDescription(v string) *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertOne) UpdateDescription() *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *BillingInvoiceSplitLineGroupUpsertOne) ClearDescription() *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.ClearDescription() + }) +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (u *BillingInvoiceSplitLineGroupUpsertOne) SetServicePeriodStart(v time.Time) *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetServicePeriodStart(v) + }) +} + +// UpdateServicePeriodStart sets the "service_period_start" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertOne) UpdateServicePeriodStart() *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateServicePeriodStart() + }) +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (u *BillingInvoiceSplitLineGroupUpsertOne) SetServicePeriodEnd(v time.Time) *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetServicePeriodEnd(v) + }) +} + +// UpdateServicePeriodEnd sets the "service_period_end" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertOne) UpdateServicePeriodEnd() *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateServicePeriodEnd() + }) +} + +// SetRatecardDiscounts sets the "ratecard_discounts" field. +func (u *BillingInvoiceSplitLineGroupUpsertOne) SetRatecardDiscounts(v *billing.Discounts) *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetRatecardDiscounts(v) + }) +} + +// UpdateRatecardDiscounts sets the "ratecard_discounts" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertOne) UpdateRatecardDiscounts() *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateRatecardDiscounts() + }) +} + +// ClearRatecardDiscounts clears the value of the "ratecard_discounts" field. +func (u *BillingInvoiceSplitLineGroupUpsertOne) ClearRatecardDiscounts() *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.ClearRatecardDiscounts() + }) +} + +// SetSubscriptionBillingPeriodFrom sets the "subscription_billing_period_from" field. +func (u *BillingInvoiceSplitLineGroupUpsertOne) SetSubscriptionBillingPeriodFrom(v time.Time) *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetSubscriptionBillingPeriodFrom(v) + }) +} + +// UpdateSubscriptionBillingPeriodFrom sets the "subscription_billing_period_from" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertOne) UpdateSubscriptionBillingPeriodFrom() *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateSubscriptionBillingPeriodFrom() + }) +} + +// ClearSubscriptionBillingPeriodFrom clears the value of the "subscription_billing_period_from" field. +func (u *BillingInvoiceSplitLineGroupUpsertOne) ClearSubscriptionBillingPeriodFrom() *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.ClearSubscriptionBillingPeriodFrom() + }) +} + +// SetSubscriptionBillingPeriodTo sets the "subscription_billing_period_to" field. +func (u *BillingInvoiceSplitLineGroupUpsertOne) SetSubscriptionBillingPeriodTo(v time.Time) *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetSubscriptionBillingPeriodTo(v) + }) +} + +// UpdateSubscriptionBillingPeriodTo sets the "subscription_billing_period_to" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertOne) UpdateSubscriptionBillingPeriodTo() *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateSubscriptionBillingPeriodTo() + }) +} + +// ClearSubscriptionBillingPeriodTo clears the value of the "subscription_billing_period_to" field. +func (u *BillingInvoiceSplitLineGroupUpsertOne) ClearSubscriptionBillingPeriodTo() *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.ClearSubscriptionBillingPeriodTo() + }) +} + +// SetChargeID sets the "charge_id" field. +func (u *BillingInvoiceSplitLineGroupUpsertOne) SetChargeID(v string) *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetChargeID(v) + }) +} + +// UpdateChargeID sets the "charge_id" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertOne) UpdateChargeID() *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateChargeID() + }) +} + +// ClearChargeID clears the value of the "charge_id" field. +func (u *BillingInvoiceSplitLineGroupUpsertOne) ClearChargeID() *BillingInvoiceSplitLineGroupUpsertOne { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.ClearChargeID() + }) +} + +// Exec executes the query. +func (u *BillingInvoiceSplitLineGroupUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingInvoiceSplitLineGroupCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingInvoiceSplitLineGroupUpsertOne) 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 *BillingInvoiceSplitLineGroupUpsertOne) 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: BillingInvoiceSplitLineGroupUpsertOne.ID is not supported by MySQL driver. Use BillingInvoiceSplitLineGroupUpsertOne.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 *BillingInvoiceSplitLineGroupUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// BillingInvoiceSplitLineGroupCreateBulk is the builder for creating many BillingInvoiceSplitLineGroup entities in bulk. +type BillingInvoiceSplitLineGroupCreateBulk struct { + config + err error + builders []*BillingInvoiceSplitLineGroupCreate + conflict []sql.ConflictOption +} + +// Save creates the BillingInvoiceSplitLineGroup entities in the database. +func (_c *BillingInvoiceSplitLineGroupCreateBulk) Save(ctx context.Context) ([]*BillingInvoiceSplitLineGroup, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*BillingInvoiceSplitLineGroup, 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.(*BillingInvoiceSplitLineGroupMutation) + 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 *BillingInvoiceSplitLineGroupCreateBulk) SaveX(ctx context.Context) []*BillingInvoiceSplitLineGroup { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingInvoiceSplitLineGroupCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingInvoiceSplitLineGroupCreateBulk) 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.BillingInvoiceSplitLineGroup.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.BillingInvoiceSplitLineGroupUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *BillingInvoiceSplitLineGroupCreateBulk) OnConflict(opts ...sql.ConflictOption) *BillingInvoiceSplitLineGroupUpsertBulk { + _c.conflict = opts + return &BillingInvoiceSplitLineGroupUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingInvoiceSplitLineGroup.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingInvoiceSplitLineGroupCreateBulk) OnConflictColumns(columns ...string) *BillingInvoiceSplitLineGroupUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingInvoiceSplitLineGroupUpsertBulk{ + create: _c, + } +} + +// BillingInvoiceSplitLineGroupUpsertBulk is the builder for "upsert"-ing +// a bulk of BillingInvoiceSplitLineGroup nodes. +type BillingInvoiceSplitLineGroupUpsertBulk struct { + create *BillingInvoiceSplitLineGroupCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.BillingInvoiceSplitLineGroup.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(billinginvoicesplitlinegroup.FieldID) +// }), +// ). +// Exec(ctx) +func (u *BillingInvoiceSplitLineGroupUpsertBulk) UpdateNewValues() *BillingInvoiceSplitLineGroupUpsertBulk { + 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(billinginvoicesplitlinegroup.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(billinginvoicesplitlinegroup.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(billinginvoicesplitlinegroup.FieldCreatedAt) + } + if _, exists := b.mutation.Currency(); exists { + s.SetIgnore(billinginvoicesplitlinegroup.FieldCurrency) + } + if _, exists := b.mutation.UniqueReferenceID(); exists { + s.SetIgnore(billinginvoicesplitlinegroup.FieldUniqueReferenceID) + } + if _, exists := b.mutation.FeatureKey(); exists { + s.SetIgnore(billinginvoicesplitlinegroup.FieldFeatureKey) + } + if _, exists := b.mutation.Price(); exists { + s.SetIgnore(billinginvoicesplitlinegroup.FieldPrice) + } + if _, exists := b.mutation.SubscriptionID(); exists { + s.SetIgnore(billinginvoicesplitlinegroup.FieldSubscriptionID) + } + if _, exists := b.mutation.SubscriptionPhaseID(); exists { + s.SetIgnore(billinginvoicesplitlinegroup.FieldSubscriptionPhaseID) + } + if _, exists := b.mutation.SubscriptionItemID(); exists { + s.SetIgnore(billinginvoicesplitlinegroup.FieldSubscriptionItemID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingInvoiceSplitLineGroup.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingInvoiceSplitLineGroupUpsertBulk) Ignore() *BillingInvoiceSplitLineGroupUpsertBulk { + 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 *BillingInvoiceSplitLineGroupUpsertBulk) DoNothing() *BillingInvoiceSplitLineGroupUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingInvoiceSplitLineGroupCreateBulk.OnConflict +// documentation for more info. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) Update(set func(*BillingInvoiceSplitLineGroupUpsert)) *BillingInvoiceSplitLineGroupUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingInvoiceSplitLineGroupUpsert{UpdateSet: update}) + })) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) SetMetadata(v map[string]string) *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) UpdateMetadata() *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) ClearMetadata() *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) SetUpdatedAt(v time.Time) *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) UpdateUpdatedAt() *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) SetDeletedAt(v time.Time) *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) UpdateDeletedAt() *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) ClearDeletedAt() *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) SetName(v string) *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) UpdateName() *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) SetDescription(v string) *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) UpdateDescription() *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) ClearDescription() *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.ClearDescription() + }) +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) SetServicePeriodStart(v time.Time) *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetServicePeriodStart(v) + }) +} + +// UpdateServicePeriodStart sets the "service_period_start" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) UpdateServicePeriodStart() *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateServicePeriodStart() + }) +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) SetServicePeriodEnd(v time.Time) *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetServicePeriodEnd(v) + }) +} + +// UpdateServicePeriodEnd sets the "service_period_end" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) UpdateServicePeriodEnd() *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateServicePeriodEnd() + }) +} + +// SetRatecardDiscounts sets the "ratecard_discounts" field. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) SetRatecardDiscounts(v *billing.Discounts) *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetRatecardDiscounts(v) + }) +} + +// UpdateRatecardDiscounts sets the "ratecard_discounts" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) UpdateRatecardDiscounts() *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateRatecardDiscounts() + }) +} + +// ClearRatecardDiscounts clears the value of the "ratecard_discounts" field. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) ClearRatecardDiscounts() *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.ClearRatecardDiscounts() + }) +} + +// SetSubscriptionBillingPeriodFrom sets the "subscription_billing_period_from" field. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) SetSubscriptionBillingPeriodFrom(v time.Time) *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetSubscriptionBillingPeriodFrom(v) + }) +} + +// UpdateSubscriptionBillingPeriodFrom sets the "subscription_billing_period_from" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) UpdateSubscriptionBillingPeriodFrom() *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateSubscriptionBillingPeriodFrom() + }) +} + +// ClearSubscriptionBillingPeriodFrom clears the value of the "subscription_billing_period_from" field. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) ClearSubscriptionBillingPeriodFrom() *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.ClearSubscriptionBillingPeriodFrom() + }) +} + +// SetSubscriptionBillingPeriodTo sets the "subscription_billing_period_to" field. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) SetSubscriptionBillingPeriodTo(v time.Time) *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetSubscriptionBillingPeriodTo(v) + }) +} + +// UpdateSubscriptionBillingPeriodTo sets the "subscription_billing_period_to" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) UpdateSubscriptionBillingPeriodTo() *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateSubscriptionBillingPeriodTo() + }) +} + +// ClearSubscriptionBillingPeriodTo clears the value of the "subscription_billing_period_to" field. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) ClearSubscriptionBillingPeriodTo() *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.ClearSubscriptionBillingPeriodTo() + }) +} + +// SetChargeID sets the "charge_id" field. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) SetChargeID(v string) *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.SetChargeID(v) + }) +} + +// UpdateChargeID sets the "charge_id" field to the value that was provided on create. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) UpdateChargeID() *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.UpdateChargeID() + }) +} + +// ClearChargeID clears the value of the "charge_id" field. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) ClearChargeID() *BillingInvoiceSplitLineGroupUpsertBulk { + return u.Update(func(s *BillingInvoiceSplitLineGroupUpsert) { + s.ClearChargeID() + }) +} + +// Exec executes the query. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) 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 BillingInvoiceSplitLineGroupCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingInvoiceSplitLineGroupCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingInvoiceSplitLineGroupUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billinginvoicesplitlinegroup_delete.go b/ent/db/billinginvoicesplitlinegroup_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..683e4567e0c00e13bf64e1bc755dce464042b684 --- /dev/null +++ b/ent/db/billinginvoicesplitlinegroup_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/billinginvoicesplitlinegroup" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingInvoiceSplitLineGroupDelete is the builder for deleting a BillingInvoiceSplitLineGroup entity. +type BillingInvoiceSplitLineGroupDelete struct { + config + hooks []Hook + mutation *BillingInvoiceSplitLineGroupMutation +} + +// Where appends a list predicates to the BillingInvoiceSplitLineGroupDelete builder. +func (_d *BillingInvoiceSplitLineGroupDelete) Where(ps ...predicate.BillingInvoiceSplitLineGroup) *BillingInvoiceSplitLineGroupDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *BillingInvoiceSplitLineGroupDelete) 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 *BillingInvoiceSplitLineGroupDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *BillingInvoiceSplitLineGroupDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(billinginvoicesplitlinegroup.Table, sqlgraph.NewFieldSpec(billinginvoicesplitlinegroup.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 +} + +// BillingInvoiceSplitLineGroupDeleteOne is the builder for deleting a single BillingInvoiceSplitLineGroup entity. +type BillingInvoiceSplitLineGroupDeleteOne struct { + _d *BillingInvoiceSplitLineGroupDelete +} + +// Where appends a list predicates to the BillingInvoiceSplitLineGroupDelete builder. +func (_d *BillingInvoiceSplitLineGroupDeleteOne) Where(ps ...predicate.BillingInvoiceSplitLineGroup) *BillingInvoiceSplitLineGroupDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *BillingInvoiceSplitLineGroupDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{billinginvoicesplitlinegroup.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *BillingInvoiceSplitLineGroupDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billinginvoicesplitlinegroup_query.go b/ent/db/billinginvoicesplitlinegroup_query.go new file mode 100644 index 0000000000000000000000000000000000000000..0aabc0837885135de3bd3c86f67d23a591e46356 --- /dev/null +++ b/ent/db/billinginvoicesplitlinegroup_query.go @@ -0,0 +1,961 @@ +// 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/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicesplitlinegroup" + "github.com/openmeterio/openmeter/openmeter/ent/db/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionphase" +) + +// BillingInvoiceSplitLineGroupQuery is the builder for querying BillingInvoiceSplitLineGroup entities. +type BillingInvoiceSplitLineGroupQuery struct { + config + ctx *QueryContext + order []billinginvoicesplitlinegroup.OrderOption + inters []Interceptor + predicates []predicate.BillingInvoiceSplitLineGroup + withBillingInvoiceLines *BillingInvoiceLineQuery + withSubscription *SubscriptionQuery + withSubscriptionPhase *SubscriptionPhaseQuery + withSubscriptionItem *SubscriptionItemQuery + withCharge *ChargeQuery + 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 BillingInvoiceSplitLineGroupQuery builder. +func (_q *BillingInvoiceSplitLineGroupQuery) Where(ps ...predicate.BillingInvoiceSplitLineGroup) *BillingInvoiceSplitLineGroupQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *BillingInvoiceSplitLineGroupQuery) Limit(limit int) *BillingInvoiceSplitLineGroupQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *BillingInvoiceSplitLineGroupQuery) Offset(offset int) *BillingInvoiceSplitLineGroupQuery { + _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 *BillingInvoiceSplitLineGroupQuery) Unique(unique bool) *BillingInvoiceSplitLineGroupQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *BillingInvoiceSplitLineGroupQuery) Order(o ...billinginvoicesplitlinegroup.OrderOption) *BillingInvoiceSplitLineGroupQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryBillingInvoiceLines chains the current query on the "billing_invoice_lines" edge. +func (_q *BillingInvoiceSplitLineGroupQuery) QueryBillingInvoiceLines() *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{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(billinginvoicesplitlinegroup.Table, billinginvoicesplitlinegroup.FieldID, selector), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, billinginvoicesplitlinegroup.BillingInvoiceLinesTable, billinginvoicesplitlinegroup.BillingInvoiceLinesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySubscription chains the current query on the "subscription" edge. +func (_q *BillingInvoiceSplitLineGroupQuery) QuerySubscription() *SubscriptionQuery { + query := (&SubscriptionClient{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(billinginvoicesplitlinegroup.Table, billinginvoicesplitlinegroup.FieldID, selector), + sqlgraph.To(subscription.Table, subscription.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoicesplitlinegroup.SubscriptionTable, billinginvoicesplitlinegroup.SubscriptionColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySubscriptionPhase chains the current query on the "subscription_phase" edge. +func (_q *BillingInvoiceSplitLineGroupQuery) QuerySubscriptionPhase() *SubscriptionPhaseQuery { + query := (&SubscriptionPhaseClient{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(billinginvoicesplitlinegroup.Table, billinginvoicesplitlinegroup.FieldID, selector), + sqlgraph.To(subscriptionphase.Table, subscriptionphase.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoicesplitlinegroup.SubscriptionPhaseTable, billinginvoicesplitlinegroup.SubscriptionPhaseColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySubscriptionItem chains the current query on the "subscription_item" edge. +func (_q *BillingInvoiceSplitLineGroupQuery) QuerySubscriptionItem() *SubscriptionItemQuery { + query := (&SubscriptionItemClient{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(billinginvoicesplitlinegroup.Table, billinginvoicesplitlinegroup.FieldID, selector), + sqlgraph.To(subscriptionitem.Table, subscriptionitem.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoicesplitlinegroup.SubscriptionItemTable, billinginvoicesplitlinegroup.SubscriptionItemColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCharge chains the current query on the "charge" edge. +func (_q *BillingInvoiceSplitLineGroupQuery) 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(billinginvoicesplitlinegroup.Table, billinginvoicesplitlinegroup.FieldID, selector), + sqlgraph.To(charge.Table, charge.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoicesplitlinegroup.ChargeTable, billinginvoicesplitlinegroup.ChargeColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first BillingInvoiceSplitLineGroup entity from the query. +// Returns a *NotFoundError when no BillingInvoiceSplitLineGroup was found. +func (_q *BillingInvoiceSplitLineGroupQuery) First(ctx context.Context) (*BillingInvoiceSplitLineGroup, 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{billinginvoicesplitlinegroup.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *BillingInvoiceSplitLineGroupQuery) FirstX(ctx context.Context) *BillingInvoiceSplitLineGroup { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first BillingInvoiceSplitLineGroup ID from the query. +// Returns a *NotFoundError when no BillingInvoiceSplitLineGroup ID was found. +func (_q *BillingInvoiceSplitLineGroupQuery) 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{billinginvoicesplitlinegroup.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *BillingInvoiceSplitLineGroupQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single BillingInvoiceSplitLineGroup entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one BillingInvoiceSplitLineGroup entity is found. +// Returns a *NotFoundError when no BillingInvoiceSplitLineGroup entities are found. +func (_q *BillingInvoiceSplitLineGroupQuery) Only(ctx context.Context) (*BillingInvoiceSplitLineGroup, 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{billinginvoicesplitlinegroup.Label} + default: + return nil, &NotSingularError{billinginvoicesplitlinegroup.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *BillingInvoiceSplitLineGroupQuery) OnlyX(ctx context.Context) *BillingInvoiceSplitLineGroup { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only BillingInvoiceSplitLineGroup ID in the query. +// Returns a *NotSingularError when more than one BillingInvoiceSplitLineGroup ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *BillingInvoiceSplitLineGroupQuery) 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{billinginvoicesplitlinegroup.Label} + default: + err = &NotSingularError{billinginvoicesplitlinegroup.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *BillingInvoiceSplitLineGroupQuery) 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 BillingInvoiceSplitLineGroups. +func (_q *BillingInvoiceSplitLineGroupQuery) All(ctx context.Context) ([]*BillingInvoiceSplitLineGroup, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*BillingInvoiceSplitLineGroup, *BillingInvoiceSplitLineGroupQuery]() + return withInterceptors[[]*BillingInvoiceSplitLineGroup](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *BillingInvoiceSplitLineGroupQuery) AllX(ctx context.Context) []*BillingInvoiceSplitLineGroup { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of BillingInvoiceSplitLineGroup IDs. +func (_q *BillingInvoiceSplitLineGroupQuery) 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(billinginvoicesplitlinegroup.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *BillingInvoiceSplitLineGroupQuery) 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 *BillingInvoiceSplitLineGroupQuery) 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[*BillingInvoiceSplitLineGroupQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *BillingInvoiceSplitLineGroupQuery) 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 *BillingInvoiceSplitLineGroupQuery) 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 *BillingInvoiceSplitLineGroupQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the BillingInvoiceSplitLineGroupQuery 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 *BillingInvoiceSplitLineGroupQuery) Clone() *BillingInvoiceSplitLineGroupQuery { + if _q == nil { + return nil + } + return &BillingInvoiceSplitLineGroupQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]billinginvoicesplitlinegroup.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.BillingInvoiceSplitLineGroup{}, _q.predicates...), + withBillingInvoiceLines: _q.withBillingInvoiceLines.Clone(), + withSubscription: _q.withSubscription.Clone(), + withSubscriptionPhase: _q.withSubscriptionPhase.Clone(), + withSubscriptionItem: _q.withSubscriptionItem.Clone(), + withCharge: _q.withCharge.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// 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 *BillingInvoiceSplitLineGroupQuery) WithBillingInvoiceLines(opts ...func(*BillingInvoiceLineQuery)) *BillingInvoiceSplitLineGroupQuery { + query := (&BillingInvoiceLineClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingInvoiceLines = query + return _q +} + +// WithSubscription tells the query-builder to eager-load the nodes that are connected to +// the "subscription" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *BillingInvoiceSplitLineGroupQuery) WithSubscription(opts ...func(*SubscriptionQuery)) *BillingInvoiceSplitLineGroupQuery { + query := (&SubscriptionClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSubscription = query + return _q +} + +// WithSubscriptionPhase tells the query-builder to eager-load the nodes that are connected to +// the "subscription_phase" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *BillingInvoiceSplitLineGroupQuery) WithSubscriptionPhase(opts ...func(*SubscriptionPhaseQuery)) *BillingInvoiceSplitLineGroupQuery { + query := (&SubscriptionPhaseClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSubscriptionPhase = query + return _q +} + +// WithSubscriptionItem tells the query-builder to eager-load the nodes that are connected to +// the "subscription_item" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *BillingInvoiceSplitLineGroupQuery) WithSubscriptionItem(opts ...func(*SubscriptionItemQuery)) *BillingInvoiceSplitLineGroupQuery { + query := (&SubscriptionItemClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSubscriptionItem = query + return _q +} + +// 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 *BillingInvoiceSplitLineGroupQuery) WithCharge(opts ...func(*ChargeQuery)) *BillingInvoiceSplitLineGroupQuery { + query := (&ChargeClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCharge = 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.BillingInvoiceSplitLineGroup.Query(). +// GroupBy(billinginvoicesplitlinegroup.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *BillingInvoiceSplitLineGroupQuery) GroupBy(field string, fields ...string) *BillingInvoiceSplitLineGroupGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &BillingInvoiceSplitLineGroupGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = billinginvoicesplitlinegroup.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.BillingInvoiceSplitLineGroup.Query(). +// Select(billinginvoicesplitlinegroup.FieldNamespace). +// Scan(ctx, &v) +func (_q *BillingInvoiceSplitLineGroupQuery) Select(fields ...string) *BillingInvoiceSplitLineGroupSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &BillingInvoiceSplitLineGroupSelect{BillingInvoiceSplitLineGroupQuery: _q} + sbuild.label = billinginvoicesplitlinegroup.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a BillingInvoiceSplitLineGroupSelect configured with the given aggregations. +func (_q *BillingInvoiceSplitLineGroupQuery) Aggregate(fns ...AggregateFunc) *BillingInvoiceSplitLineGroupSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *BillingInvoiceSplitLineGroupQuery) 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 !billinginvoicesplitlinegroup.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 *BillingInvoiceSplitLineGroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BillingInvoiceSplitLineGroup, error) { + var ( + nodes = []*BillingInvoiceSplitLineGroup{} + _spec = _q.querySpec() + loadedTypes = [5]bool{ + _q.withBillingInvoiceLines != nil, + _q.withSubscription != nil, + _q.withSubscriptionPhase != nil, + _q.withSubscriptionItem != nil, + _q.withCharge != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*BillingInvoiceSplitLineGroup).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &BillingInvoiceSplitLineGroup{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.withBillingInvoiceLines; query != nil { + if err := _q.loadBillingInvoiceLines(ctx, query, nodes, + func(n *BillingInvoiceSplitLineGroup) { n.Edges.BillingInvoiceLines = []*BillingInvoiceLine{} }, + func(n *BillingInvoiceSplitLineGroup, e *BillingInvoiceLine) { + n.Edges.BillingInvoiceLines = append(n.Edges.BillingInvoiceLines, e) + }); err != nil { + return nil, err + } + } + if query := _q.withSubscription; query != nil { + if err := _q.loadSubscription(ctx, query, nodes, nil, + func(n *BillingInvoiceSplitLineGroup, e *Subscription) { n.Edges.Subscription = e }); err != nil { + return nil, err + } + } + if query := _q.withSubscriptionPhase; query != nil { + if err := _q.loadSubscriptionPhase(ctx, query, nodes, nil, + func(n *BillingInvoiceSplitLineGroup, e *SubscriptionPhase) { n.Edges.SubscriptionPhase = e }); err != nil { + return nil, err + } + } + if query := _q.withSubscriptionItem; query != nil { + if err := _q.loadSubscriptionItem(ctx, query, nodes, nil, + func(n *BillingInvoiceSplitLineGroup, e *SubscriptionItem) { n.Edges.SubscriptionItem = e }); err != nil { + return nil, err + } + } + if query := _q.withCharge; query != nil { + if err := _q.loadCharge(ctx, query, nodes, nil, + func(n *BillingInvoiceSplitLineGroup, e *Charge) { n.Edges.Charge = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *BillingInvoiceSplitLineGroupQuery) loadBillingInvoiceLines(ctx context.Context, query *BillingInvoiceLineQuery, nodes []*BillingInvoiceSplitLineGroup, init func(*BillingInvoiceSplitLineGroup), assign func(*BillingInvoiceSplitLineGroup, *BillingInvoiceLine)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*BillingInvoiceSplitLineGroup) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + query.withFKs = true + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(billinginvoiceline.FieldSplitLineGroupID) + } + query.Where(predicate.BillingInvoiceLine(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(billinginvoicesplitlinegroup.BillingInvoiceLinesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.SplitLineGroupID + if fk == nil { + return fmt.Errorf(`foreign-key "split_line_group_id" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "split_line_group_id" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *BillingInvoiceSplitLineGroupQuery) loadSubscription(ctx context.Context, query *SubscriptionQuery, nodes []*BillingInvoiceSplitLineGroup, init func(*BillingInvoiceSplitLineGroup), assign func(*BillingInvoiceSplitLineGroup, *Subscription)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*BillingInvoiceSplitLineGroup) + for i := range nodes { + if nodes[i].SubscriptionID == nil { + continue + } + fk := *nodes[i].SubscriptionID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(subscription.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 "subscription_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *BillingInvoiceSplitLineGroupQuery) loadSubscriptionPhase(ctx context.Context, query *SubscriptionPhaseQuery, nodes []*BillingInvoiceSplitLineGroup, init func(*BillingInvoiceSplitLineGroup), assign func(*BillingInvoiceSplitLineGroup, *SubscriptionPhase)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*BillingInvoiceSplitLineGroup) + for i := range nodes { + if nodes[i].SubscriptionPhaseID == nil { + continue + } + fk := *nodes[i].SubscriptionPhaseID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(subscriptionphase.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 "subscription_phase_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *BillingInvoiceSplitLineGroupQuery) loadSubscriptionItem(ctx context.Context, query *SubscriptionItemQuery, nodes []*BillingInvoiceSplitLineGroup, init func(*BillingInvoiceSplitLineGroup), assign func(*BillingInvoiceSplitLineGroup, *SubscriptionItem)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*BillingInvoiceSplitLineGroup) + for i := range nodes { + if nodes[i].SubscriptionItemID == nil { + continue + } + fk := *nodes[i].SubscriptionItemID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(subscriptionitem.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 "subscription_item_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *BillingInvoiceSplitLineGroupQuery) loadCharge(ctx context.Context, query *ChargeQuery, nodes []*BillingInvoiceSplitLineGroup, init func(*BillingInvoiceSplitLineGroup), assign func(*BillingInvoiceSplitLineGroup, *Charge)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*BillingInvoiceSplitLineGroup) + for i := range nodes { + if nodes[i].ChargeID == nil { + continue + } + 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(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 "charge_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *BillingInvoiceSplitLineGroupQuery) 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 *BillingInvoiceSplitLineGroupQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(billinginvoicesplitlinegroup.Table, billinginvoicesplitlinegroup.Columns, sqlgraph.NewFieldSpec(billinginvoicesplitlinegroup.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, billinginvoicesplitlinegroup.FieldID) + for i := range fields { + if fields[i] != billinginvoicesplitlinegroup.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withSubscription != nil { + _spec.Node.AddColumnOnce(billinginvoicesplitlinegroup.FieldSubscriptionID) + } + if _q.withSubscriptionPhase != nil { + _spec.Node.AddColumnOnce(billinginvoicesplitlinegroup.FieldSubscriptionPhaseID) + } + if _q.withSubscriptionItem != nil { + _spec.Node.AddColumnOnce(billinginvoicesplitlinegroup.FieldSubscriptionItemID) + } + if _q.withCharge != nil { + _spec.Node.AddColumnOnce(billinginvoicesplitlinegroup.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 *BillingInvoiceSplitLineGroupQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(billinginvoicesplitlinegroup.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = billinginvoicesplitlinegroup.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 *BillingInvoiceSplitLineGroupQuery) ForUpdate(opts ...sql.LockOption) *BillingInvoiceSplitLineGroupQuery { + 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 *BillingInvoiceSplitLineGroupQuery) ForShare(opts ...sql.LockOption) *BillingInvoiceSplitLineGroupQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// BillingInvoiceSplitLineGroupGroupBy is the group-by builder for BillingInvoiceSplitLineGroup entities. +type BillingInvoiceSplitLineGroupGroupBy struct { + selector + build *BillingInvoiceSplitLineGroupQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *BillingInvoiceSplitLineGroupGroupBy) Aggregate(fns ...AggregateFunc) *BillingInvoiceSplitLineGroupGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *BillingInvoiceSplitLineGroupGroupBy) 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[*BillingInvoiceSplitLineGroupQuery, *BillingInvoiceSplitLineGroupGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *BillingInvoiceSplitLineGroupGroupBy) sqlScan(ctx context.Context, root *BillingInvoiceSplitLineGroupQuery, 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) +} + +// BillingInvoiceSplitLineGroupSelect is the builder for selecting fields of BillingInvoiceSplitLineGroup entities. +type BillingInvoiceSplitLineGroupSelect struct { + *BillingInvoiceSplitLineGroupQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *BillingInvoiceSplitLineGroupSelect) Aggregate(fns ...AggregateFunc) *BillingInvoiceSplitLineGroupSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *BillingInvoiceSplitLineGroupSelect) 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[*BillingInvoiceSplitLineGroupQuery, *BillingInvoiceSplitLineGroupSelect](ctx, _s.BillingInvoiceSplitLineGroupQuery, _s, _s.inters, v) +} + +func (_s *BillingInvoiceSplitLineGroupSelect) sqlScan(ctx context.Context, root *BillingInvoiceSplitLineGroupQuery, 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/ent/db/billinginvoicesplitlinegroup_update.go b/ent/db/billinginvoicesplitlinegroup_update.go new file mode 100644 index 0000000000000000000000000000000000000000..a45a4bae704e0a1a329ce3ec08e5ff4a65ff2428 --- /dev/null +++ b/ent/db/billinginvoicesplitlinegroup_update.go @@ -0,0 +1,899 @@ +// 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/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicesplitlinegroup" + "github.com/openmeterio/openmeter/openmeter/ent/db/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingInvoiceSplitLineGroupUpdate is the builder for updating BillingInvoiceSplitLineGroup entities. +type BillingInvoiceSplitLineGroupUpdate struct { + config + hooks []Hook + mutation *BillingInvoiceSplitLineGroupMutation +} + +// Where appends a list predicates to the BillingInvoiceSplitLineGroupUpdate builder. +func (_u *BillingInvoiceSplitLineGroupUpdate) Where(ps ...predicate.BillingInvoiceSplitLineGroup) *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *BillingInvoiceSplitLineGroupUpdate) SetMetadata(v map[string]string) *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *BillingInvoiceSplitLineGroupUpdate) ClearMetadata() *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *BillingInvoiceSplitLineGroupUpdate) SetUpdatedAt(v time.Time) *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *BillingInvoiceSplitLineGroupUpdate) SetDeletedAt(v time.Time) *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *BillingInvoiceSplitLineGroupUpdate) SetNillableDeletedAt(v *time.Time) *BillingInvoiceSplitLineGroupUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *BillingInvoiceSplitLineGroupUpdate) ClearDeletedAt() *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *BillingInvoiceSplitLineGroupUpdate) SetName(v string) *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *BillingInvoiceSplitLineGroupUpdate) SetNillableName(v *string) *BillingInvoiceSplitLineGroupUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *BillingInvoiceSplitLineGroupUpdate) SetDescription(v string) *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *BillingInvoiceSplitLineGroupUpdate) SetNillableDescription(v *string) *BillingInvoiceSplitLineGroupUpdate { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *BillingInvoiceSplitLineGroupUpdate) ClearDescription() *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.ClearDescription() + return _u +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (_u *BillingInvoiceSplitLineGroupUpdate) SetServicePeriodStart(v time.Time) *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.SetServicePeriodStart(v) + return _u +} + +// SetNillableServicePeriodStart sets the "service_period_start" field if the given value is not nil. +func (_u *BillingInvoiceSplitLineGroupUpdate) SetNillableServicePeriodStart(v *time.Time) *BillingInvoiceSplitLineGroupUpdate { + if v != nil { + _u.SetServicePeriodStart(*v) + } + return _u +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (_u *BillingInvoiceSplitLineGroupUpdate) SetServicePeriodEnd(v time.Time) *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.SetServicePeriodEnd(v) + return _u +} + +// SetNillableServicePeriodEnd sets the "service_period_end" field if the given value is not nil. +func (_u *BillingInvoiceSplitLineGroupUpdate) SetNillableServicePeriodEnd(v *time.Time) *BillingInvoiceSplitLineGroupUpdate { + if v != nil { + _u.SetServicePeriodEnd(*v) + } + return _u +} + +// SetRatecardDiscounts sets the "ratecard_discounts" field. +func (_u *BillingInvoiceSplitLineGroupUpdate) SetRatecardDiscounts(v *billing.Discounts) *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.SetRatecardDiscounts(v) + return _u +} + +// ClearRatecardDiscounts clears the value of the "ratecard_discounts" field. +func (_u *BillingInvoiceSplitLineGroupUpdate) ClearRatecardDiscounts() *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.ClearRatecardDiscounts() + return _u +} + +// SetSubscriptionBillingPeriodFrom sets the "subscription_billing_period_from" field. +func (_u *BillingInvoiceSplitLineGroupUpdate) SetSubscriptionBillingPeriodFrom(v time.Time) *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.SetSubscriptionBillingPeriodFrom(v) + return _u +} + +// SetNillableSubscriptionBillingPeriodFrom sets the "subscription_billing_period_from" field if the given value is not nil. +func (_u *BillingInvoiceSplitLineGroupUpdate) SetNillableSubscriptionBillingPeriodFrom(v *time.Time) *BillingInvoiceSplitLineGroupUpdate { + if v != nil { + _u.SetSubscriptionBillingPeriodFrom(*v) + } + return _u +} + +// ClearSubscriptionBillingPeriodFrom clears the value of the "subscription_billing_period_from" field. +func (_u *BillingInvoiceSplitLineGroupUpdate) ClearSubscriptionBillingPeriodFrom() *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.ClearSubscriptionBillingPeriodFrom() + return _u +} + +// SetSubscriptionBillingPeriodTo sets the "subscription_billing_period_to" field. +func (_u *BillingInvoiceSplitLineGroupUpdate) SetSubscriptionBillingPeriodTo(v time.Time) *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.SetSubscriptionBillingPeriodTo(v) + return _u +} + +// SetNillableSubscriptionBillingPeriodTo sets the "subscription_billing_period_to" field if the given value is not nil. +func (_u *BillingInvoiceSplitLineGroupUpdate) SetNillableSubscriptionBillingPeriodTo(v *time.Time) *BillingInvoiceSplitLineGroupUpdate { + if v != nil { + _u.SetSubscriptionBillingPeriodTo(*v) + } + return _u +} + +// ClearSubscriptionBillingPeriodTo clears the value of the "subscription_billing_period_to" field. +func (_u *BillingInvoiceSplitLineGroupUpdate) ClearSubscriptionBillingPeriodTo() *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.ClearSubscriptionBillingPeriodTo() + return _u +} + +// SetChargeID sets the "charge_id" field. +func (_u *BillingInvoiceSplitLineGroupUpdate) SetChargeID(v string) *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.SetChargeID(v) + return _u +} + +// SetNillableChargeID sets the "charge_id" field if the given value is not nil. +func (_u *BillingInvoiceSplitLineGroupUpdate) SetNillableChargeID(v *string) *BillingInvoiceSplitLineGroupUpdate { + if v != nil { + _u.SetChargeID(*v) + } + return _u +} + +// ClearChargeID clears the value of the "charge_id" field. +func (_u *BillingInvoiceSplitLineGroupUpdate) ClearChargeID() *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.ClearChargeID() + return _u +} + +// AddBillingInvoiceLineIDs adds the "billing_invoice_lines" edge to the BillingInvoiceLine entity by IDs. +func (_u *BillingInvoiceSplitLineGroupUpdate) AddBillingInvoiceLineIDs(ids ...string) *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.AddBillingInvoiceLineIDs(ids...) + return _u +} + +// AddBillingInvoiceLines adds the "billing_invoice_lines" edges to the BillingInvoiceLine entity. +func (_u *BillingInvoiceSplitLineGroupUpdate) AddBillingInvoiceLines(v ...*BillingInvoiceLine) *BillingInvoiceSplitLineGroupUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddBillingInvoiceLineIDs(ids...) +} + +// SetCharge sets the "charge" edge to the Charge entity. +func (_u *BillingInvoiceSplitLineGroupUpdate) SetCharge(v *Charge) *BillingInvoiceSplitLineGroupUpdate { + return _u.SetChargeID(v.ID) +} + +// Mutation returns the BillingInvoiceSplitLineGroupMutation object of the builder. +func (_u *BillingInvoiceSplitLineGroupUpdate) Mutation() *BillingInvoiceSplitLineGroupMutation { + return _u.mutation +} + +// ClearBillingInvoiceLines clears all "billing_invoice_lines" edges to the BillingInvoiceLine entity. +func (_u *BillingInvoiceSplitLineGroupUpdate) ClearBillingInvoiceLines() *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.ClearBillingInvoiceLines() + return _u +} + +// RemoveBillingInvoiceLineIDs removes the "billing_invoice_lines" edge to BillingInvoiceLine entities by IDs. +func (_u *BillingInvoiceSplitLineGroupUpdate) RemoveBillingInvoiceLineIDs(ids ...string) *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.RemoveBillingInvoiceLineIDs(ids...) + return _u +} + +// RemoveBillingInvoiceLines removes "billing_invoice_lines" edges to BillingInvoiceLine entities. +func (_u *BillingInvoiceSplitLineGroupUpdate) RemoveBillingInvoiceLines(v ...*BillingInvoiceLine) *BillingInvoiceSplitLineGroupUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveBillingInvoiceLineIDs(ids...) +} + +// ClearCharge clears the "charge" edge to the Charge entity. +func (_u *BillingInvoiceSplitLineGroupUpdate) ClearCharge() *BillingInvoiceSplitLineGroupUpdate { + _u.mutation.ClearCharge() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *BillingInvoiceSplitLineGroupUpdate) 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 *BillingInvoiceSplitLineGroupUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *BillingInvoiceSplitLineGroupUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingInvoiceSplitLineGroupUpdate) 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 *BillingInvoiceSplitLineGroupUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := billinginvoicesplitlinegroup.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +func (_u *BillingInvoiceSplitLineGroupUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(billinginvoicesplitlinegroup.Table, billinginvoicesplitlinegroup.Columns, sqlgraph.NewFieldSpec(billinginvoicesplitlinegroup.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.Metadata(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(billinginvoicesplitlinegroup.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(billinginvoicesplitlinegroup.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(billinginvoicesplitlinegroup.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.ServicePeriodStart(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldServicePeriodStart, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodEnd(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldServicePeriodEnd, field.TypeTime, value) + } + if _u.mutation.UniqueReferenceIDCleared() { + _spec.ClearField(billinginvoicesplitlinegroup.FieldUniqueReferenceID, field.TypeString) + } + if value, ok := _u.mutation.RatecardDiscounts(); ok { + vv, err := billinginvoicesplitlinegroup.ValueScanner.RatecardDiscounts.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(billinginvoicesplitlinegroup.FieldRatecardDiscounts, field.TypeString, vv) + } + if _u.mutation.RatecardDiscountsCleared() { + _spec.ClearField(billinginvoicesplitlinegroup.FieldRatecardDiscounts, field.TypeString) + } + if _u.mutation.FeatureKeyCleared() { + _spec.ClearField(billinginvoicesplitlinegroup.FieldFeatureKey, field.TypeString) + } + if value, ok := _u.mutation.SubscriptionBillingPeriodFrom(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom, field.TypeTime, value) + } + if _u.mutation.SubscriptionBillingPeriodFromCleared() { + _spec.ClearField(billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom, field.TypeTime) + } + if value, ok := _u.mutation.SubscriptionBillingPeriodTo(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo, field.TypeTime, value) + } + if _u.mutation.SubscriptionBillingPeriodToCleared() { + _spec.ClearField(billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo, field.TypeTime) + } + if _u.mutation.BillingInvoiceLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billinginvoicesplitlinegroup.BillingInvoiceLinesTable, + Columns: []string{billinginvoicesplitlinegroup.BillingInvoiceLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedBillingInvoiceLinesIDs(); len(nodes) > 0 && !_u.mutation.BillingInvoiceLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billinginvoicesplitlinegroup.BillingInvoiceLinesTable, + Columns: []string{billinginvoicesplitlinegroup.BillingInvoiceLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.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.BillingInvoiceLinesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billinginvoicesplitlinegroup.BillingInvoiceLinesTable, + Columns: []string{billinginvoicesplitlinegroup.BillingInvoiceLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.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.ChargeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicesplitlinegroup.ChargeTable, + Columns: []string{billinginvoicesplitlinegroup.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.M2O, + Inverse: true, + Table: billinginvoicesplitlinegroup.ChargeTable, + Columns: []string{billinginvoicesplitlinegroup.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 _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{billinginvoicesplitlinegroup.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// BillingInvoiceSplitLineGroupUpdateOne is the builder for updating a single BillingInvoiceSplitLineGroup entity. +type BillingInvoiceSplitLineGroupUpdateOne struct { + config + fields []string + hooks []Hook + mutation *BillingInvoiceSplitLineGroupMutation +} + +// SetMetadata sets the "metadata" field. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SetMetadata(v map[string]string) *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) ClearMetadata() *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SetUpdatedAt(v time.Time) *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SetDeletedAt(v time.Time) *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SetNillableDeletedAt(v *time.Time) *BillingInvoiceSplitLineGroupUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) ClearDeletedAt() *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SetName(v string) *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SetNillableName(v *string) *BillingInvoiceSplitLineGroupUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SetDescription(v string) *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SetNillableDescription(v *string) *BillingInvoiceSplitLineGroupUpdateOne { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) ClearDescription() *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.ClearDescription() + return _u +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SetServicePeriodStart(v time.Time) *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.SetServicePeriodStart(v) + return _u +} + +// SetNillableServicePeriodStart sets the "service_period_start" field if the given value is not nil. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SetNillableServicePeriodStart(v *time.Time) *BillingInvoiceSplitLineGroupUpdateOne { + if v != nil { + _u.SetServicePeriodStart(*v) + } + return _u +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SetServicePeriodEnd(v time.Time) *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.SetServicePeriodEnd(v) + return _u +} + +// SetNillableServicePeriodEnd sets the "service_period_end" field if the given value is not nil. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SetNillableServicePeriodEnd(v *time.Time) *BillingInvoiceSplitLineGroupUpdateOne { + if v != nil { + _u.SetServicePeriodEnd(*v) + } + return _u +} + +// SetRatecardDiscounts sets the "ratecard_discounts" field. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SetRatecardDiscounts(v *billing.Discounts) *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.SetRatecardDiscounts(v) + return _u +} + +// ClearRatecardDiscounts clears the value of the "ratecard_discounts" field. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) ClearRatecardDiscounts() *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.ClearRatecardDiscounts() + return _u +} + +// SetSubscriptionBillingPeriodFrom sets the "subscription_billing_period_from" field. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SetSubscriptionBillingPeriodFrom(v time.Time) *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.SetSubscriptionBillingPeriodFrom(v) + return _u +} + +// SetNillableSubscriptionBillingPeriodFrom sets the "subscription_billing_period_from" field if the given value is not nil. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SetNillableSubscriptionBillingPeriodFrom(v *time.Time) *BillingInvoiceSplitLineGroupUpdateOne { + if v != nil { + _u.SetSubscriptionBillingPeriodFrom(*v) + } + return _u +} + +// ClearSubscriptionBillingPeriodFrom clears the value of the "subscription_billing_period_from" field. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) ClearSubscriptionBillingPeriodFrom() *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.ClearSubscriptionBillingPeriodFrom() + return _u +} + +// SetSubscriptionBillingPeriodTo sets the "subscription_billing_period_to" field. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SetSubscriptionBillingPeriodTo(v time.Time) *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.SetSubscriptionBillingPeriodTo(v) + return _u +} + +// SetNillableSubscriptionBillingPeriodTo sets the "subscription_billing_period_to" field if the given value is not nil. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SetNillableSubscriptionBillingPeriodTo(v *time.Time) *BillingInvoiceSplitLineGroupUpdateOne { + if v != nil { + _u.SetSubscriptionBillingPeriodTo(*v) + } + return _u +} + +// ClearSubscriptionBillingPeriodTo clears the value of the "subscription_billing_period_to" field. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) ClearSubscriptionBillingPeriodTo() *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.ClearSubscriptionBillingPeriodTo() + return _u +} + +// SetChargeID sets the "charge_id" field. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SetChargeID(v string) *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.SetChargeID(v) + return _u +} + +// SetNillableChargeID sets the "charge_id" field if the given value is not nil. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SetNillableChargeID(v *string) *BillingInvoiceSplitLineGroupUpdateOne { + if v != nil { + _u.SetChargeID(*v) + } + return _u +} + +// ClearChargeID clears the value of the "charge_id" field. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) ClearChargeID() *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.ClearChargeID() + return _u +} + +// AddBillingInvoiceLineIDs adds the "billing_invoice_lines" edge to the BillingInvoiceLine entity by IDs. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) AddBillingInvoiceLineIDs(ids ...string) *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.AddBillingInvoiceLineIDs(ids...) + return _u +} + +// AddBillingInvoiceLines adds the "billing_invoice_lines" edges to the BillingInvoiceLine entity. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) AddBillingInvoiceLines(v ...*BillingInvoiceLine) *BillingInvoiceSplitLineGroupUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddBillingInvoiceLineIDs(ids...) +} + +// SetCharge sets the "charge" edge to the Charge entity. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SetCharge(v *Charge) *BillingInvoiceSplitLineGroupUpdateOne { + return _u.SetChargeID(v.ID) +} + +// Mutation returns the BillingInvoiceSplitLineGroupMutation object of the builder. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) Mutation() *BillingInvoiceSplitLineGroupMutation { + return _u.mutation +} + +// ClearBillingInvoiceLines clears all "billing_invoice_lines" edges to the BillingInvoiceLine entity. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) ClearBillingInvoiceLines() *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.ClearBillingInvoiceLines() + return _u +} + +// RemoveBillingInvoiceLineIDs removes the "billing_invoice_lines" edge to BillingInvoiceLine entities by IDs. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) RemoveBillingInvoiceLineIDs(ids ...string) *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.RemoveBillingInvoiceLineIDs(ids...) + return _u +} + +// RemoveBillingInvoiceLines removes "billing_invoice_lines" edges to BillingInvoiceLine entities. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) RemoveBillingInvoiceLines(v ...*BillingInvoiceLine) *BillingInvoiceSplitLineGroupUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveBillingInvoiceLineIDs(ids...) +} + +// ClearCharge clears the "charge" edge to the Charge entity. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) ClearCharge() *BillingInvoiceSplitLineGroupUpdateOne { + _u.mutation.ClearCharge() + return _u +} + +// Where appends a list predicates to the BillingInvoiceSplitLineGroupUpdate builder. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) Where(ps ...predicate.BillingInvoiceSplitLineGroup) *BillingInvoiceSplitLineGroupUpdateOne { + _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 *BillingInvoiceSplitLineGroupUpdateOne) Select(field string, fields ...string) *BillingInvoiceSplitLineGroupUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated BillingInvoiceSplitLineGroup entity. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) Save(ctx context.Context) (*BillingInvoiceSplitLineGroup, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) SaveX(ctx context.Context) *BillingInvoiceSplitLineGroup { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingInvoiceSplitLineGroupUpdateOne) 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 *BillingInvoiceSplitLineGroupUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := billinginvoicesplitlinegroup.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +func (_u *BillingInvoiceSplitLineGroupUpdateOne) sqlSave(ctx context.Context) (_node *BillingInvoiceSplitLineGroup, err error) { + _spec := sqlgraph.NewUpdateSpec(billinginvoicesplitlinegroup.Table, billinginvoicesplitlinegroup.Columns, sqlgraph.NewFieldSpec(billinginvoicesplitlinegroup.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "BillingInvoiceSplitLineGroup.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, billinginvoicesplitlinegroup.FieldID) + for _, f := range fields { + if !billinginvoicesplitlinegroup.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != billinginvoicesplitlinegroup.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.Metadata(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(billinginvoicesplitlinegroup.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(billinginvoicesplitlinegroup.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(billinginvoicesplitlinegroup.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.ServicePeriodStart(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldServicePeriodStart, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodEnd(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldServicePeriodEnd, field.TypeTime, value) + } + if _u.mutation.UniqueReferenceIDCleared() { + _spec.ClearField(billinginvoicesplitlinegroup.FieldUniqueReferenceID, field.TypeString) + } + if value, ok := _u.mutation.RatecardDiscounts(); ok { + vv, err := billinginvoicesplitlinegroup.ValueScanner.RatecardDiscounts.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(billinginvoicesplitlinegroup.FieldRatecardDiscounts, field.TypeString, vv) + } + if _u.mutation.RatecardDiscountsCleared() { + _spec.ClearField(billinginvoicesplitlinegroup.FieldRatecardDiscounts, field.TypeString) + } + if _u.mutation.FeatureKeyCleared() { + _spec.ClearField(billinginvoicesplitlinegroup.FieldFeatureKey, field.TypeString) + } + if value, ok := _u.mutation.SubscriptionBillingPeriodFrom(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom, field.TypeTime, value) + } + if _u.mutation.SubscriptionBillingPeriodFromCleared() { + _spec.ClearField(billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom, field.TypeTime) + } + if value, ok := _u.mutation.SubscriptionBillingPeriodTo(); ok { + _spec.SetField(billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo, field.TypeTime, value) + } + if _u.mutation.SubscriptionBillingPeriodToCleared() { + _spec.ClearField(billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo, field.TypeTime) + } + if _u.mutation.BillingInvoiceLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billinginvoicesplitlinegroup.BillingInvoiceLinesTable, + Columns: []string{billinginvoicesplitlinegroup.BillingInvoiceLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedBillingInvoiceLinesIDs(); len(nodes) > 0 && !_u.mutation.BillingInvoiceLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billinginvoicesplitlinegroup.BillingInvoiceLinesTable, + Columns: []string{billinginvoicesplitlinegroup.BillingInvoiceLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.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.BillingInvoiceLinesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billinginvoicesplitlinegroup.BillingInvoiceLinesTable, + Columns: []string{billinginvoicesplitlinegroup.BillingInvoiceLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.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.ChargeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicesplitlinegroup.ChargeTable, + Columns: []string{billinginvoicesplitlinegroup.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.M2O, + Inverse: true, + Table: billinginvoicesplitlinegroup.ChargeTable, + Columns: []string{billinginvoicesplitlinegroup.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) + } + _node = &BillingInvoiceSplitLineGroup{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{billinginvoicesplitlinegroup.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/ent/db/billinginvoiceusagebasedlineconfig.go b/ent/db/billinginvoiceusagebasedlineconfig.go new file mode 100644 index 0000000000000000000000000000000000000000..836c30a3613e3851eb06f457e0711702f3c48f7d --- /dev/null +++ b/ent/db/billinginvoiceusagebasedlineconfig.go @@ -0,0 +1,200 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceusagebasedlineconfig" + "github.com/openmeterio/openmeter/openmeter/productcatalog" +) + +// BillingInvoiceUsageBasedLineConfig is the model entity for the BillingInvoiceUsageBasedLineConfig schema. +type BillingInvoiceUsageBasedLineConfig 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"` + // PriceType holds the value of the "price_type" field. + PriceType productcatalog.PriceType `json:"price_type,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"` + // PreLinePeriodQuantity holds the value of the "pre_line_period_quantity" field. + PreLinePeriodQuantity *alpacadecimal.Decimal `json:"pre_line_period_quantity,omitempty"` + // MeteredPreLinePeriodQuantity holds the value of the "metered_pre_line_period_quantity" field. + MeteredPreLinePeriodQuantity *alpacadecimal.Decimal `json:"metered_pre_line_period_quantity,omitempty"` + // MeteredQuantity holds the value of the "metered_quantity" field. + MeteredQuantity *alpacadecimal.Decimal `json:"metered_quantity,omitempty"` + // UnitConfig holds the value of the "unit_config" field. + UnitConfig *productcatalog.UnitConfig `json:"unit_config,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*BillingInvoiceUsageBasedLineConfig) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity, billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity, billinginvoiceusagebasedlineconfig.FieldMeteredQuantity: + values[i] = &sql.NullScanner{S: new(alpacadecimal.Decimal)} + case billinginvoiceusagebasedlineconfig.FieldID, billinginvoiceusagebasedlineconfig.FieldNamespace, billinginvoiceusagebasedlineconfig.FieldPriceType, billinginvoiceusagebasedlineconfig.FieldFeatureKey: + values[i] = new(sql.NullString) + case billinginvoiceusagebasedlineconfig.FieldPrice: + values[i] = billinginvoiceusagebasedlineconfig.ValueScanner.Price.ScanValue() + case billinginvoiceusagebasedlineconfig.FieldUnitConfig: + values[i] = billinginvoiceusagebasedlineconfig.ValueScanner.UnitConfig.ScanValue() + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the BillingInvoiceUsageBasedLineConfig fields. +func (_m *BillingInvoiceUsageBasedLineConfig) 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 billinginvoiceusagebasedlineconfig.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 billinginvoiceusagebasedlineconfig.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 billinginvoiceusagebasedlineconfig.FieldPriceType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field price_type", values[i]) + } else if value.Valid { + _m.PriceType = productcatalog.PriceType(value.String) + } + case billinginvoiceusagebasedlineconfig.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 = new(string) + *_m.FeatureKey = value.String + } + case billinginvoiceusagebasedlineconfig.FieldPrice: + if value, err := billinginvoiceusagebasedlineconfig.ValueScanner.Price.FromValue(values[i]); err != nil { + return err + } else { + _m.Price = value + } + case billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field pre_line_period_quantity", values[i]) + } else if value.Valid { + _m.PreLinePeriodQuantity = new(alpacadecimal.Decimal) + *_m.PreLinePeriodQuantity = *value.S.(*alpacadecimal.Decimal) + } + case billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field metered_pre_line_period_quantity", values[i]) + } else if value.Valid { + _m.MeteredPreLinePeriodQuantity = new(alpacadecimal.Decimal) + *_m.MeteredPreLinePeriodQuantity = *value.S.(*alpacadecimal.Decimal) + } + case billinginvoiceusagebasedlineconfig.FieldMeteredQuantity: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field metered_quantity", values[i]) + } else if value.Valid { + _m.MeteredQuantity = new(alpacadecimal.Decimal) + *_m.MeteredQuantity = *value.S.(*alpacadecimal.Decimal) + } + case billinginvoiceusagebasedlineconfig.FieldUnitConfig: + if value, err := billinginvoiceusagebasedlineconfig.ValueScanner.UnitConfig.FromValue(values[i]); err != nil { + return err + } else { + _m.UnitConfig = value + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the BillingInvoiceUsageBasedLineConfig. +// This includes values selected through modifiers, order, etc. +func (_m *BillingInvoiceUsageBasedLineConfig) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this BillingInvoiceUsageBasedLineConfig. +// Note that you need to call BillingInvoiceUsageBasedLineConfig.Unwrap() before calling this method if this BillingInvoiceUsageBasedLineConfig +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *BillingInvoiceUsageBasedLineConfig) Update() *BillingInvoiceUsageBasedLineConfigUpdateOne { + return NewBillingInvoiceUsageBasedLineConfigClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the BillingInvoiceUsageBasedLineConfig 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 *BillingInvoiceUsageBasedLineConfig) Unwrap() *BillingInvoiceUsageBasedLineConfig { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: BillingInvoiceUsageBasedLineConfig is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *BillingInvoiceUsageBasedLineConfig) String() string { + var builder strings.Builder + builder.WriteString("BillingInvoiceUsageBasedLineConfig(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("price_type=") + builder.WriteString(fmt.Sprintf("%v", _m.PriceType)) + builder.WriteString(", ") + if v := _m.FeatureKey; v != nil { + builder.WriteString("feature_key=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("price=") + builder.WriteString(fmt.Sprintf("%v", _m.Price)) + builder.WriteString(", ") + if v := _m.PreLinePeriodQuantity; v != nil { + builder.WriteString("pre_line_period_quantity=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.MeteredPreLinePeriodQuantity; v != nil { + builder.WriteString("metered_pre_line_period_quantity=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.MeteredQuantity; v != nil { + builder.WriteString("metered_quantity=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.UnitConfig; v != nil { + builder.WriteString("unit_config=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteByte(')') + return builder.String() +} + +// BillingInvoiceUsageBasedLineConfigs is a parsable slice of BillingInvoiceUsageBasedLineConfig. +type BillingInvoiceUsageBasedLineConfigs []*BillingInvoiceUsageBasedLineConfig diff --git a/ent/db/billinginvoiceusagebasedlineconfig/billinginvoiceusagebasedlineconfig.go b/ent/db/billinginvoiceusagebasedlineconfig/billinginvoiceusagebasedlineconfig.go new file mode 100644 index 0000000000000000000000000000000000000000..c4042876c6947e9c37c0ff0d5cc0362ec4821352 --- /dev/null +++ b/ent/db/billinginvoiceusagebasedlineconfig/billinginvoiceusagebasedlineconfig.go @@ -0,0 +1,129 @@ +// Code generated by ent, DO NOT EDIT. + +package billinginvoiceusagebasedlineconfig + +import ( + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/productcatalog" +) + +const ( + // Label holds the string label denoting the billinginvoiceusagebasedlineconfig type in the database. + Label = "billing_invoice_usage_based_line_config" + // 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" + // FieldPriceType holds the string denoting the price_type field in the database. + FieldPriceType = "price_type" + // 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" + // FieldPreLinePeriodQuantity holds the string denoting the pre_line_period_quantity field in the database. + FieldPreLinePeriodQuantity = "pre_line_period_quantity" + // FieldMeteredPreLinePeriodQuantity holds the string denoting the metered_pre_line_period_quantity field in the database. + FieldMeteredPreLinePeriodQuantity = "metered_pre_line_period_quantity" + // FieldMeteredQuantity holds the string denoting the metered_quantity field in the database. + FieldMeteredQuantity = "metered_quantity" + // FieldUnitConfig holds the string denoting the unit_config field in the database. + FieldUnitConfig = "unit_config" + // Table holds the table name of the billinginvoiceusagebasedlineconfig in the database. + Table = "billing_invoice_usage_based_line_configs" +) + +// Columns holds all SQL columns for billinginvoiceusagebasedlineconfig fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldPriceType, + FieldFeatureKey, + FieldPrice, + FieldPreLinePeriodQuantity, + FieldMeteredPreLinePeriodQuantity, + FieldMeteredQuantity, + FieldUnitConfig, +} + +// 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 + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string + // ValueScanner of all BillingInvoiceUsageBasedLineConfig fields. + ValueScanner struct { + Price field.TypeValueScanner[*productcatalog.Price] + UnitConfig field.TypeValueScanner[*productcatalog.UnitConfig] + } +) + +// PriceTypeValidator is a validator for the "price_type" field enum values. It is called by the builders before save. +func PriceTypeValidator(pt productcatalog.PriceType) error { + switch pt { + case "flat", "unit", "tiered", "dynamic", "package": + return nil + default: + return fmt.Errorf("billinginvoiceusagebasedlineconfig: invalid enum value for price_type field: %q", pt) + } +} + +// OrderOption defines the ordering options for the BillingInvoiceUsageBasedLineConfig 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() +} + +// ByPriceType orders the results by the price_type field. +func ByPriceType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPriceType, 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() +} + +// ByPreLinePeriodQuantity orders the results by the pre_line_period_quantity field. +func ByPreLinePeriodQuantity(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPreLinePeriodQuantity, opts...).ToFunc() +} + +// ByMeteredPreLinePeriodQuantity orders the results by the metered_pre_line_period_quantity field. +func ByMeteredPreLinePeriodQuantity(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMeteredPreLinePeriodQuantity, opts...).ToFunc() +} + +// ByMeteredQuantity orders the results by the metered_quantity field. +func ByMeteredQuantity(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMeteredQuantity, opts...).ToFunc() +} + +// ByUnitConfig orders the results by the unit_config field. +func ByUnitConfig(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUnitConfig, opts...).ToFunc() +} diff --git a/ent/db/billinginvoiceusagebasedlineconfig/where.go b/ent/db/billinginvoiceusagebasedlineconfig/where.go new file mode 100644 index 0000000000000000000000000000000000000000..61cd7e9bac412fb9263b3977cde72ffe65b33469 --- /dev/null +++ b/ent/db/billinginvoiceusagebasedlineconfig/where.go @@ -0,0 +1,435 @@ +// Code generated by ent, DO NOT EDIT. + +package billinginvoiceusagebasedlineconfig + +import ( + "entgo.io/ent/dialect/sql" + "github.com/alpacahq/alpacadecimal" + "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.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldEQ(FieldNamespace, v)) +} + +// FeatureKey applies equality check predicate on the "feature_key" field. It's identical to FeatureKeyEQ. +func FeatureKey(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldEQ(FieldFeatureKey, v)) +} + +// PreLinePeriodQuantity applies equality check predicate on the "pre_line_period_quantity" field. It's identical to PreLinePeriodQuantityEQ. +func PreLinePeriodQuantity(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldEQ(FieldPreLinePeriodQuantity, v)) +} + +// MeteredPreLinePeriodQuantity applies equality check predicate on the "metered_pre_line_period_quantity" field. It's identical to MeteredPreLinePeriodQuantityEQ. +func MeteredPreLinePeriodQuantity(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldEQ(FieldMeteredPreLinePeriodQuantity, v)) +} + +// MeteredQuantity applies equality check predicate on the "metered_quantity" field. It's identical to MeteredQuantityEQ. +func MeteredQuantity(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldEQ(FieldMeteredQuantity, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldContainsFold(FieldNamespace, v)) +} + +// PriceTypeEQ applies the EQ predicate on the "price_type" field. +func PriceTypeEQ(v productcatalog.PriceType) predicate.BillingInvoiceUsageBasedLineConfig { + vc := v + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldEQ(FieldPriceType, vc)) +} + +// PriceTypeNEQ applies the NEQ predicate on the "price_type" field. +func PriceTypeNEQ(v productcatalog.PriceType) predicate.BillingInvoiceUsageBasedLineConfig { + vc := v + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldNEQ(FieldPriceType, vc)) +} + +// PriceTypeIn applies the In predicate on the "price_type" field. +func PriceTypeIn(vs ...productcatalog.PriceType) predicate.BillingInvoiceUsageBasedLineConfig { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldIn(FieldPriceType, v...)) +} + +// PriceTypeNotIn applies the NotIn predicate on the "price_type" field. +func PriceTypeNotIn(vs ...productcatalog.PriceType) predicate.BillingInvoiceUsageBasedLineConfig { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldNotIn(FieldPriceType, v...)) +} + +// FeatureKeyEQ applies the EQ predicate on the "feature_key" field. +func FeatureKeyEQ(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldEQ(FieldFeatureKey, v)) +} + +// FeatureKeyNEQ applies the NEQ predicate on the "feature_key" field. +func FeatureKeyNEQ(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldNEQ(FieldFeatureKey, v)) +} + +// FeatureKeyIn applies the In predicate on the "feature_key" field. +func FeatureKeyIn(vs ...string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldIn(FieldFeatureKey, vs...)) +} + +// FeatureKeyNotIn applies the NotIn predicate on the "feature_key" field. +func FeatureKeyNotIn(vs ...string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldNotIn(FieldFeatureKey, vs...)) +} + +// FeatureKeyGT applies the GT predicate on the "feature_key" field. +func FeatureKeyGT(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldGT(FieldFeatureKey, v)) +} + +// FeatureKeyGTE applies the GTE predicate on the "feature_key" field. +func FeatureKeyGTE(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldGTE(FieldFeatureKey, v)) +} + +// FeatureKeyLT applies the LT predicate on the "feature_key" field. +func FeatureKeyLT(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldLT(FieldFeatureKey, v)) +} + +// FeatureKeyLTE applies the LTE predicate on the "feature_key" field. +func FeatureKeyLTE(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldLTE(FieldFeatureKey, v)) +} + +// FeatureKeyContains applies the Contains predicate on the "feature_key" field. +func FeatureKeyContains(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldContains(FieldFeatureKey, v)) +} + +// FeatureKeyHasPrefix applies the HasPrefix predicate on the "feature_key" field. +func FeatureKeyHasPrefix(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldHasPrefix(FieldFeatureKey, v)) +} + +// FeatureKeyHasSuffix applies the HasSuffix predicate on the "feature_key" field. +func FeatureKeyHasSuffix(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldHasSuffix(FieldFeatureKey, v)) +} + +// FeatureKeyIsNil applies the IsNil predicate on the "feature_key" field. +func FeatureKeyIsNil() predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldIsNull(FieldFeatureKey)) +} + +// FeatureKeyNotNil applies the NotNil predicate on the "feature_key" field. +func FeatureKeyNotNil() predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldNotNull(FieldFeatureKey)) +} + +// FeatureKeyEqualFold applies the EqualFold predicate on the "feature_key" field. +func FeatureKeyEqualFold(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldEqualFold(FieldFeatureKey, v)) +} + +// FeatureKeyContainsFold applies the ContainsFold predicate on the "feature_key" field. +func FeatureKeyContainsFold(v string) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldContainsFold(FieldFeatureKey, v)) +} + +// PreLinePeriodQuantityEQ applies the EQ predicate on the "pre_line_period_quantity" field. +func PreLinePeriodQuantityEQ(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldEQ(FieldPreLinePeriodQuantity, v)) +} + +// PreLinePeriodQuantityNEQ applies the NEQ predicate on the "pre_line_period_quantity" field. +func PreLinePeriodQuantityNEQ(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldNEQ(FieldPreLinePeriodQuantity, v)) +} + +// PreLinePeriodQuantityIn applies the In predicate on the "pre_line_period_quantity" field. +func PreLinePeriodQuantityIn(vs ...alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldIn(FieldPreLinePeriodQuantity, vs...)) +} + +// PreLinePeriodQuantityNotIn applies the NotIn predicate on the "pre_line_period_quantity" field. +func PreLinePeriodQuantityNotIn(vs ...alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldNotIn(FieldPreLinePeriodQuantity, vs...)) +} + +// PreLinePeriodQuantityGT applies the GT predicate on the "pre_line_period_quantity" field. +func PreLinePeriodQuantityGT(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldGT(FieldPreLinePeriodQuantity, v)) +} + +// PreLinePeriodQuantityGTE applies the GTE predicate on the "pre_line_period_quantity" field. +func PreLinePeriodQuantityGTE(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldGTE(FieldPreLinePeriodQuantity, v)) +} + +// PreLinePeriodQuantityLT applies the LT predicate on the "pre_line_period_quantity" field. +func PreLinePeriodQuantityLT(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldLT(FieldPreLinePeriodQuantity, v)) +} + +// PreLinePeriodQuantityLTE applies the LTE predicate on the "pre_line_period_quantity" field. +func PreLinePeriodQuantityLTE(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldLTE(FieldPreLinePeriodQuantity, v)) +} + +// PreLinePeriodQuantityIsNil applies the IsNil predicate on the "pre_line_period_quantity" field. +func PreLinePeriodQuantityIsNil() predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldIsNull(FieldPreLinePeriodQuantity)) +} + +// PreLinePeriodQuantityNotNil applies the NotNil predicate on the "pre_line_period_quantity" field. +func PreLinePeriodQuantityNotNil() predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldNotNull(FieldPreLinePeriodQuantity)) +} + +// MeteredPreLinePeriodQuantityEQ applies the EQ predicate on the "metered_pre_line_period_quantity" field. +func MeteredPreLinePeriodQuantityEQ(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldEQ(FieldMeteredPreLinePeriodQuantity, v)) +} + +// MeteredPreLinePeriodQuantityNEQ applies the NEQ predicate on the "metered_pre_line_period_quantity" field. +func MeteredPreLinePeriodQuantityNEQ(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldNEQ(FieldMeteredPreLinePeriodQuantity, v)) +} + +// MeteredPreLinePeriodQuantityIn applies the In predicate on the "metered_pre_line_period_quantity" field. +func MeteredPreLinePeriodQuantityIn(vs ...alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldIn(FieldMeteredPreLinePeriodQuantity, vs...)) +} + +// MeteredPreLinePeriodQuantityNotIn applies the NotIn predicate on the "metered_pre_line_period_quantity" field. +func MeteredPreLinePeriodQuantityNotIn(vs ...alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldNotIn(FieldMeteredPreLinePeriodQuantity, vs...)) +} + +// MeteredPreLinePeriodQuantityGT applies the GT predicate on the "metered_pre_line_period_quantity" field. +func MeteredPreLinePeriodQuantityGT(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldGT(FieldMeteredPreLinePeriodQuantity, v)) +} + +// MeteredPreLinePeriodQuantityGTE applies the GTE predicate on the "metered_pre_line_period_quantity" field. +func MeteredPreLinePeriodQuantityGTE(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldGTE(FieldMeteredPreLinePeriodQuantity, v)) +} + +// MeteredPreLinePeriodQuantityLT applies the LT predicate on the "metered_pre_line_period_quantity" field. +func MeteredPreLinePeriodQuantityLT(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldLT(FieldMeteredPreLinePeriodQuantity, v)) +} + +// MeteredPreLinePeriodQuantityLTE applies the LTE predicate on the "metered_pre_line_period_quantity" field. +func MeteredPreLinePeriodQuantityLTE(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldLTE(FieldMeteredPreLinePeriodQuantity, v)) +} + +// MeteredPreLinePeriodQuantityIsNil applies the IsNil predicate on the "metered_pre_line_period_quantity" field. +func MeteredPreLinePeriodQuantityIsNil() predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldIsNull(FieldMeteredPreLinePeriodQuantity)) +} + +// MeteredPreLinePeriodQuantityNotNil applies the NotNil predicate on the "metered_pre_line_period_quantity" field. +func MeteredPreLinePeriodQuantityNotNil() predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldNotNull(FieldMeteredPreLinePeriodQuantity)) +} + +// MeteredQuantityEQ applies the EQ predicate on the "metered_quantity" field. +func MeteredQuantityEQ(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldEQ(FieldMeteredQuantity, v)) +} + +// MeteredQuantityNEQ applies the NEQ predicate on the "metered_quantity" field. +func MeteredQuantityNEQ(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldNEQ(FieldMeteredQuantity, v)) +} + +// MeteredQuantityIn applies the In predicate on the "metered_quantity" field. +func MeteredQuantityIn(vs ...alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldIn(FieldMeteredQuantity, vs...)) +} + +// MeteredQuantityNotIn applies the NotIn predicate on the "metered_quantity" field. +func MeteredQuantityNotIn(vs ...alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldNotIn(FieldMeteredQuantity, vs...)) +} + +// MeteredQuantityGT applies the GT predicate on the "metered_quantity" field. +func MeteredQuantityGT(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldGT(FieldMeteredQuantity, v)) +} + +// MeteredQuantityGTE applies the GTE predicate on the "metered_quantity" field. +func MeteredQuantityGTE(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldGTE(FieldMeteredQuantity, v)) +} + +// MeteredQuantityLT applies the LT predicate on the "metered_quantity" field. +func MeteredQuantityLT(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldLT(FieldMeteredQuantity, v)) +} + +// MeteredQuantityLTE applies the LTE predicate on the "metered_quantity" field. +func MeteredQuantityLTE(v alpacadecimal.Decimal) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldLTE(FieldMeteredQuantity, v)) +} + +// MeteredQuantityIsNil applies the IsNil predicate on the "metered_quantity" field. +func MeteredQuantityIsNil() predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldIsNull(FieldMeteredQuantity)) +} + +// MeteredQuantityNotNil applies the NotNil predicate on the "metered_quantity" field. +func MeteredQuantityNotNil() predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldNotNull(FieldMeteredQuantity)) +} + +// UnitConfigIsNil applies the IsNil predicate on the "unit_config" field. +func UnitConfigIsNil() predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldIsNull(FieldUnitConfig)) +} + +// UnitConfigNotNil applies the NotNil predicate on the "unit_config" field. +func UnitConfigNotNil() predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.FieldNotNull(FieldUnitConfig)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.BillingInvoiceUsageBasedLineConfig) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.BillingInvoiceUsageBasedLineConfig) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.BillingInvoiceUsageBasedLineConfig) predicate.BillingInvoiceUsageBasedLineConfig { + return predicate.BillingInvoiceUsageBasedLineConfig(sql.NotPredicates(p)) +} diff --git a/ent/db/billinginvoiceusagebasedlineconfig_create.go b/ent/db/billinginvoiceusagebasedlineconfig_create.go new file mode 100644 index 0000000000000000000000000000000000000000..8fb0de9736a2895a3aafafd353ef33ac2f61c247 --- /dev/null +++ b/ent/db/billinginvoiceusagebasedlineconfig_create.go @@ -0,0 +1,943 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + + "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/billinginvoiceusagebasedlineconfig" + "github.com/openmeterio/openmeter/openmeter/productcatalog" +) + +// BillingInvoiceUsageBasedLineConfigCreate is the builder for creating a BillingInvoiceUsageBasedLineConfig entity. +type BillingInvoiceUsageBasedLineConfigCreate struct { + config + mutation *BillingInvoiceUsageBasedLineConfigMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *BillingInvoiceUsageBasedLineConfigCreate) SetNamespace(v string) *BillingInvoiceUsageBasedLineConfigCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetPriceType sets the "price_type" field. +func (_c *BillingInvoiceUsageBasedLineConfigCreate) SetPriceType(v productcatalog.PriceType) *BillingInvoiceUsageBasedLineConfigCreate { + _c.mutation.SetPriceType(v) + return _c +} + +// SetFeatureKey sets the "feature_key" field. +func (_c *BillingInvoiceUsageBasedLineConfigCreate) SetFeatureKey(v string) *BillingInvoiceUsageBasedLineConfigCreate { + _c.mutation.SetFeatureKey(v) + return _c +} + +// SetNillableFeatureKey sets the "feature_key" field if the given value is not nil. +func (_c *BillingInvoiceUsageBasedLineConfigCreate) SetNillableFeatureKey(v *string) *BillingInvoiceUsageBasedLineConfigCreate { + if v != nil { + _c.SetFeatureKey(*v) + } + return _c +} + +// SetPrice sets the "price" field. +func (_c *BillingInvoiceUsageBasedLineConfigCreate) SetPrice(v *productcatalog.Price) *BillingInvoiceUsageBasedLineConfigCreate { + _c.mutation.SetPrice(v) + return _c +} + +// SetPreLinePeriodQuantity sets the "pre_line_period_quantity" field. +func (_c *BillingInvoiceUsageBasedLineConfigCreate) SetPreLinePeriodQuantity(v alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigCreate { + _c.mutation.SetPreLinePeriodQuantity(v) + return _c +} + +// SetNillablePreLinePeriodQuantity sets the "pre_line_period_quantity" field if the given value is not nil. +func (_c *BillingInvoiceUsageBasedLineConfigCreate) SetNillablePreLinePeriodQuantity(v *alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigCreate { + if v != nil { + _c.SetPreLinePeriodQuantity(*v) + } + return _c +} + +// SetMeteredPreLinePeriodQuantity sets the "metered_pre_line_period_quantity" field. +func (_c *BillingInvoiceUsageBasedLineConfigCreate) SetMeteredPreLinePeriodQuantity(v alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigCreate { + _c.mutation.SetMeteredPreLinePeriodQuantity(v) + return _c +} + +// SetNillableMeteredPreLinePeriodQuantity sets the "metered_pre_line_period_quantity" field if the given value is not nil. +func (_c *BillingInvoiceUsageBasedLineConfigCreate) SetNillableMeteredPreLinePeriodQuantity(v *alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigCreate { + if v != nil { + _c.SetMeteredPreLinePeriodQuantity(*v) + } + return _c +} + +// SetMeteredQuantity sets the "metered_quantity" field. +func (_c *BillingInvoiceUsageBasedLineConfigCreate) SetMeteredQuantity(v alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigCreate { + _c.mutation.SetMeteredQuantity(v) + return _c +} + +// SetNillableMeteredQuantity sets the "metered_quantity" field if the given value is not nil. +func (_c *BillingInvoiceUsageBasedLineConfigCreate) SetNillableMeteredQuantity(v *alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigCreate { + if v != nil { + _c.SetMeteredQuantity(*v) + } + return _c +} + +// SetUnitConfig sets the "unit_config" field. +func (_c *BillingInvoiceUsageBasedLineConfigCreate) SetUnitConfig(v *productcatalog.UnitConfig) *BillingInvoiceUsageBasedLineConfigCreate { + _c.mutation.SetUnitConfig(v) + return _c +} + +// SetID sets the "id" field. +func (_c *BillingInvoiceUsageBasedLineConfigCreate) SetID(v string) *BillingInvoiceUsageBasedLineConfigCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *BillingInvoiceUsageBasedLineConfigCreate) SetNillableID(v *string) *BillingInvoiceUsageBasedLineConfigCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// Mutation returns the BillingInvoiceUsageBasedLineConfigMutation object of the builder. +func (_c *BillingInvoiceUsageBasedLineConfigCreate) Mutation() *BillingInvoiceUsageBasedLineConfigMutation { + return _c.mutation +} + +// Save creates the BillingInvoiceUsageBasedLineConfig in the database. +func (_c *BillingInvoiceUsageBasedLineConfigCreate) Save(ctx context.Context) (*BillingInvoiceUsageBasedLineConfig, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *BillingInvoiceUsageBasedLineConfigCreate) SaveX(ctx context.Context) *BillingInvoiceUsageBasedLineConfig { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingInvoiceUsageBasedLineConfigCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingInvoiceUsageBasedLineConfigCreate) 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 *BillingInvoiceUsageBasedLineConfigCreate) defaults() { + if _, ok := _c.mutation.ID(); !ok { + v := billinginvoiceusagebasedlineconfig.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *BillingInvoiceUsageBasedLineConfigCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "BillingInvoiceUsageBasedLineConfig.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := billinginvoiceusagebasedlineconfig.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceUsageBasedLineConfig.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.PriceType(); !ok { + return &ValidationError{Name: "price_type", err: errors.New(`db: missing required field "BillingInvoiceUsageBasedLineConfig.price_type"`)} + } + if v, ok := _c.mutation.PriceType(); ok { + if err := billinginvoiceusagebasedlineconfig.PriceTypeValidator(v); err != nil { + return &ValidationError{Name: "price_type", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceUsageBasedLineConfig.price_type": %w`, err)} + } + } + if _, ok := _c.mutation.Price(); !ok { + return &ValidationError{Name: "price", err: errors.New(`db: missing required field "BillingInvoiceUsageBasedLineConfig.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 "BillingInvoiceUsageBasedLineConfig.price": %w`, err)} + } + } + if v, ok := _c.mutation.UnitConfig(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "unit_config", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceUsageBasedLineConfig.unit_config": %w`, err)} + } + } + return nil +} + +func (_c *BillingInvoiceUsageBasedLineConfigCreate) sqlSave(ctx context.Context) (*BillingInvoiceUsageBasedLineConfig, 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 BillingInvoiceUsageBasedLineConfig.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *BillingInvoiceUsageBasedLineConfigCreate) createSpec() (*BillingInvoiceUsageBasedLineConfig, *sqlgraph.CreateSpec, error) { + var ( + _node = &BillingInvoiceUsageBasedLineConfig{config: _c.config} + _spec = sqlgraph.NewCreateSpec(billinginvoiceusagebasedlineconfig.Table, sqlgraph.NewFieldSpec(billinginvoiceusagebasedlineconfig.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(billinginvoiceusagebasedlineconfig.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.PriceType(); ok { + _spec.SetField(billinginvoiceusagebasedlineconfig.FieldPriceType, field.TypeEnum, value) + _node.PriceType = value + } + if value, ok := _c.mutation.FeatureKey(); ok { + _spec.SetField(billinginvoiceusagebasedlineconfig.FieldFeatureKey, field.TypeString, value) + _node.FeatureKey = &value + } + if value, ok := _c.mutation.Price(); ok { + vv, err := billinginvoiceusagebasedlineconfig.ValueScanner.Price.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(billinginvoiceusagebasedlineconfig.FieldPrice, field.TypeString, vv) + _node.Price = value + } + if value, ok := _c.mutation.PreLinePeriodQuantity(); ok { + _spec.SetField(billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity, field.TypeOther, value) + _node.PreLinePeriodQuantity = &value + } + if value, ok := _c.mutation.MeteredPreLinePeriodQuantity(); ok { + _spec.SetField(billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity, field.TypeOther, value) + _node.MeteredPreLinePeriodQuantity = &value + } + if value, ok := _c.mutation.MeteredQuantity(); ok { + _spec.SetField(billinginvoiceusagebasedlineconfig.FieldMeteredQuantity, field.TypeOther, value) + _node.MeteredQuantity = &value + } + if value, ok := _c.mutation.UnitConfig(); ok { + vv, err := billinginvoiceusagebasedlineconfig.ValueScanner.UnitConfig.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(billinginvoiceusagebasedlineconfig.FieldUnitConfig, field.TypeString, vv) + _node.UnitConfig = value + } + return _node, _spec, nil +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.BillingInvoiceUsageBasedLineConfig.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.BillingInvoiceUsageBasedLineConfigUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *BillingInvoiceUsageBasedLineConfigCreate) OnConflict(opts ...sql.ConflictOption) *BillingInvoiceUsageBasedLineConfigUpsertOne { + _c.conflict = opts + return &BillingInvoiceUsageBasedLineConfigUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingInvoiceUsageBasedLineConfig.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingInvoiceUsageBasedLineConfigCreate) OnConflictColumns(columns ...string) *BillingInvoiceUsageBasedLineConfigUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingInvoiceUsageBasedLineConfigUpsertOne{ + create: _c, + } +} + +type ( + // BillingInvoiceUsageBasedLineConfigUpsertOne is the builder for "upsert"-ing + // one BillingInvoiceUsageBasedLineConfig node. + BillingInvoiceUsageBasedLineConfigUpsertOne struct { + create *BillingInvoiceUsageBasedLineConfigCreate + } + + // BillingInvoiceUsageBasedLineConfigUpsert is the "OnConflict" setter. + BillingInvoiceUsageBasedLineConfigUpsert struct { + *sql.UpdateSet + } +) + +// SetPriceType sets the "price_type" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsert) SetPriceType(v productcatalog.PriceType) *BillingInvoiceUsageBasedLineConfigUpsert { + u.Set(billinginvoiceusagebasedlineconfig.FieldPriceType, v) + return u +} + +// UpdatePriceType sets the "price_type" field to the value that was provided on create. +func (u *BillingInvoiceUsageBasedLineConfigUpsert) UpdatePriceType() *BillingInvoiceUsageBasedLineConfigUpsert { + u.SetExcluded(billinginvoiceusagebasedlineconfig.FieldPriceType) + return u +} + +// SetPrice sets the "price" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsert) SetPrice(v *productcatalog.Price) *BillingInvoiceUsageBasedLineConfigUpsert { + u.Set(billinginvoiceusagebasedlineconfig.FieldPrice, v) + return u +} + +// UpdatePrice sets the "price" field to the value that was provided on create. +func (u *BillingInvoiceUsageBasedLineConfigUpsert) UpdatePrice() *BillingInvoiceUsageBasedLineConfigUpsert { + u.SetExcluded(billinginvoiceusagebasedlineconfig.FieldPrice) + return u +} + +// SetPreLinePeriodQuantity sets the "pre_line_period_quantity" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsert) SetPreLinePeriodQuantity(v alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpsert { + u.Set(billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity, v) + return u +} + +// UpdatePreLinePeriodQuantity sets the "pre_line_period_quantity" field to the value that was provided on create. +func (u *BillingInvoiceUsageBasedLineConfigUpsert) UpdatePreLinePeriodQuantity() *BillingInvoiceUsageBasedLineConfigUpsert { + u.SetExcluded(billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity) + return u +} + +// ClearPreLinePeriodQuantity clears the value of the "pre_line_period_quantity" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsert) ClearPreLinePeriodQuantity() *BillingInvoiceUsageBasedLineConfigUpsert { + u.SetNull(billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity) + return u +} + +// SetMeteredPreLinePeriodQuantity sets the "metered_pre_line_period_quantity" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsert) SetMeteredPreLinePeriodQuantity(v alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpsert { + u.Set(billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity, v) + return u +} + +// UpdateMeteredPreLinePeriodQuantity sets the "metered_pre_line_period_quantity" field to the value that was provided on create. +func (u *BillingInvoiceUsageBasedLineConfigUpsert) UpdateMeteredPreLinePeriodQuantity() *BillingInvoiceUsageBasedLineConfigUpsert { + u.SetExcluded(billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity) + return u +} + +// ClearMeteredPreLinePeriodQuantity clears the value of the "metered_pre_line_period_quantity" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsert) ClearMeteredPreLinePeriodQuantity() *BillingInvoiceUsageBasedLineConfigUpsert { + u.SetNull(billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity) + return u +} + +// SetMeteredQuantity sets the "metered_quantity" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsert) SetMeteredQuantity(v alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpsert { + u.Set(billinginvoiceusagebasedlineconfig.FieldMeteredQuantity, v) + return u +} + +// UpdateMeteredQuantity sets the "metered_quantity" field to the value that was provided on create. +func (u *BillingInvoiceUsageBasedLineConfigUpsert) UpdateMeteredQuantity() *BillingInvoiceUsageBasedLineConfigUpsert { + u.SetExcluded(billinginvoiceusagebasedlineconfig.FieldMeteredQuantity) + return u +} + +// ClearMeteredQuantity clears the value of the "metered_quantity" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsert) ClearMeteredQuantity() *BillingInvoiceUsageBasedLineConfigUpsert { + u.SetNull(billinginvoiceusagebasedlineconfig.FieldMeteredQuantity) + return u +} + +// SetUnitConfig sets the "unit_config" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsert) SetUnitConfig(v *productcatalog.UnitConfig) *BillingInvoiceUsageBasedLineConfigUpsert { + u.Set(billinginvoiceusagebasedlineconfig.FieldUnitConfig, v) + return u +} + +// UpdateUnitConfig sets the "unit_config" field to the value that was provided on create. +func (u *BillingInvoiceUsageBasedLineConfigUpsert) UpdateUnitConfig() *BillingInvoiceUsageBasedLineConfigUpsert { + u.SetExcluded(billinginvoiceusagebasedlineconfig.FieldUnitConfig) + return u +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsert) ClearUnitConfig() *BillingInvoiceUsageBasedLineConfigUpsert { + u.SetNull(billinginvoiceusagebasedlineconfig.FieldUnitConfig) + 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.BillingInvoiceUsageBasedLineConfig.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(billinginvoiceusagebasedlineconfig.FieldID) +// }), +// ). +// Exec(ctx) +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) UpdateNewValues() *BillingInvoiceUsageBasedLineConfigUpsertOne { + 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(billinginvoiceusagebasedlineconfig.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(billinginvoiceusagebasedlineconfig.FieldNamespace) + } + if _, exists := u.create.mutation.FeatureKey(); exists { + s.SetIgnore(billinginvoiceusagebasedlineconfig.FieldFeatureKey) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingInvoiceUsageBasedLineConfig.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) Ignore() *BillingInvoiceUsageBasedLineConfigUpsertOne { + 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 *BillingInvoiceUsageBasedLineConfigUpsertOne) DoNothing() *BillingInvoiceUsageBasedLineConfigUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingInvoiceUsageBasedLineConfigCreate.OnConflict +// documentation for more info. +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) Update(set func(*BillingInvoiceUsageBasedLineConfigUpsert)) *BillingInvoiceUsageBasedLineConfigUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingInvoiceUsageBasedLineConfigUpsert{UpdateSet: update}) + })) + return u +} + +// SetPriceType sets the "price_type" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) SetPriceType(v productcatalog.PriceType) *BillingInvoiceUsageBasedLineConfigUpsertOne { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.SetPriceType(v) + }) +} + +// UpdatePriceType sets the "price_type" field to the value that was provided on create. +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) UpdatePriceType() *BillingInvoiceUsageBasedLineConfigUpsertOne { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.UpdatePriceType() + }) +} + +// SetPrice sets the "price" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) SetPrice(v *productcatalog.Price) *BillingInvoiceUsageBasedLineConfigUpsertOne { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.SetPrice(v) + }) +} + +// UpdatePrice sets the "price" field to the value that was provided on create. +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) UpdatePrice() *BillingInvoiceUsageBasedLineConfigUpsertOne { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.UpdatePrice() + }) +} + +// SetPreLinePeriodQuantity sets the "pre_line_period_quantity" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) SetPreLinePeriodQuantity(v alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpsertOne { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.SetPreLinePeriodQuantity(v) + }) +} + +// UpdatePreLinePeriodQuantity sets the "pre_line_period_quantity" field to the value that was provided on create. +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) UpdatePreLinePeriodQuantity() *BillingInvoiceUsageBasedLineConfigUpsertOne { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.UpdatePreLinePeriodQuantity() + }) +} + +// ClearPreLinePeriodQuantity clears the value of the "pre_line_period_quantity" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) ClearPreLinePeriodQuantity() *BillingInvoiceUsageBasedLineConfigUpsertOne { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.ClearPreLinePeriodQuantity() + }) +} + +// SetMeteredPreLinePeriodQuantity sets the "metered_pre_line_period_quantity" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) SetMeteredPreLinePeriodQuantity(v alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpsertOne { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.SetMeteredPreLinePeriodQuantity(v) + }) +} + +// UpdateMeteredPreLinePeriodQuantity sets the "metered_pre_line_period_quantity" field to the value that was provided on create. +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) UpdateMeteredPreLinePeriodQuantity() *BillingInvoiceUsageBasedLineConfigUpsertOne { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.UpdateMeteredPreLinePeriodQuantity() + }) +} + +// ClearMeteredPreLinePeriodQuantity clears the value of the "metered_pre_line_period_quantity" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) ClearMeteredPreLinePeriodQuantity() *BillingInvoiceUsageBasedLineConfigUpsertOne { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.ClearMeteredPreLinePeriodQuantity() + }) +} + +// SetMeteredQuantity sets the "metered_quantity" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) SetMeteredQuantity(v alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpsertOne { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.SetMeteredQuantity(v) + }) +} + +// UpdateMeteredQuantity sets the "metered_quantity" field to the value that was provided on create. +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) UpdateMeteredQuantity() *BillingInvoiceUsageBasedLineConfigUpsertOne { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.UpdateMeteredQuantity() + }) +} + +// ClearMeteredQuantity clears the value of the "metered_quantity" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) ClearMeteredQuantity() *BillingInvoiceUsageBasedLineConfigUpsertOne { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.ClearMeteredQuantity() + }) +} + +// SetUnitConfig sets the "unit_config" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) SetUnitConfig(v *productcatalog.UnitConfig) *BillingInvoiceUsageBasedLineConfigUpsertOne { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.SetUnitConfig(v) + }) +} + +// UpdateUnitConfig sets the "unit_config" field to the value that was provided on create. +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) UpdateUnitConfig() *BillingInvoiceUsageBasedLineConfigUpsertOne { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.UpdateUnitConfig() + }) +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) ClearUnitConfig() *BillingInvoiceUsageBasedLineConfigUpsertOne { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.ClearUnitConfig() + }) +} + +// Exec executes the query. +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingInvoiceUsageBasedLineConfigCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingInvoiceUsageBasedLineConfigUpsertOne) 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 *BillingInvoiceUsageBasedLineConfigUpsertOne) 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: BillingInvoiceUsageBasedLineConfigUpsertOne.ID is not supported by MySQL driver. Use BillingInvoiceUsageBasedLineConfigUpsertOne.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 *BillingInvoiceUsageBasedLineConfigUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// BillingInvoiceUsageBasedLineConfigCreateBulk is the builder for creating many BillingInvoiceUsageBasedLineConfig entities in bulk. +type BillingInvoiceUsageBasedLineConfigCreateBulk struct { + config + err error + builders []*BillingInvoiceUsageBasedLineConfigCreate + conflict []sql.ConflictOption +} + +// Save creates the BillingInvoiceUsageBasedLineConfig entities in the database. +func (_c *BillingInvoiceUsageBasedLineConfigCreateBulk) Save(ctx context.Context) ([]*BillingInvoiceUsageBasedLineConfig, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*BillingInvoiceUsageBasedLineConfig, 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.(*BillingInvoiceUsageBasedLineConfigMutation) + 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 *BillingInvoiceUsageBasedLineConfigCreateBulk) SaveX(ctx context.Context) []*BillingInvoiceUsageBasedLineConfig { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingInvoiceUsageBasedLineConfigCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingInvoiceUsageBasedLineConfigCreateBulk) 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.BillingInvoiceUsageBasedLineConfig.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.BillingInvoiceUsageBasedLineConfigUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *BillingInvoiceUsageBasedLineConfigCreateBulk) OnConflict(opts ...sql.ConflictOption) *BillingInvoiceUsageBasedLineConfigUpsertBulk { + _c.conflict = opts + return &BillingInvoiceUsageBasedLineConfigUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingInvoiceUsageBasedLineConfig.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingInvoiceUsageBasedLineConfigCreateBulk) OnConflictColumns(columns ...string) *BillingInvoiceUsageBasedLineConfigUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingInvoiceUsageBasedLineConfigUpsertBulk{ + create: _c, + } +} + +// BillingInvoiceUsageBasedLineConfigUpsertBulk is the builder for "upsert"-ing +// a bulk of BillingInvoiceUsageBasedLineConfig nodes. +type BillingInvoiceUsageBasedLineConfigUpsertBulk struct { + create *BillingInvoiceUsageBasedLineConfigCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.BillingInvoiceUsageBasedLineConfig.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(billinginvoiceusagebasedlineconfig.FieldID) +// }), +// ). +// Exec(ctx) +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) UpdateNewValues() *BillingInvoiceUsageBasedLineConfigUpsertBulk { + 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(billinginvoiceusagebasedlineconfig.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(billinginvoiceusagebasedlineconfig.FieldNamespace) + } + if _, exists := b.mutation.FeatureKey(); exists { + s.SetIgnore(billinginvoiceusagebasedlineconfig.FieldFeatureKey) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingInvoiceUsageBasedLineConfig.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) Ignore() *BillingInvoiceUsageBasedLineConfigUpsertBulk { + 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 *BillingInvoiceUsageBasedLineConfigUpsertBulk) DoNothing() *BillingInvoiceUsageBasedLineConfigUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingInvoiceUsageBasedLineConfigCreateBulk.OnConflict +// documentation for more info. +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) Update(set func(*BillingInvoiceUsageBasedLineConfigUpsert)) *BillingInvoiceUsageBasedLineConfigUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingInvoiceUsageBasedLineConfigUpsert{UpdateSet: update}) + })) + return u +} + +// SetPriceType sets the "price_type" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) SetPriceType(v productcatalog.PriceType) *BillingInvoiceUsageBasedLineConfigUpsertBulk { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.SetPriceType(v) + }) +} + +// UpdatePriceType sets the "price_type" field to the value that was provided on create. +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) UpdatePriceType() *BillingInvoiceUsageBasedLineConfigUpsertBulk { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.UpdatePriceType() + }) +} + +// SetPrice sets the "price" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) SetPrice(v *productcatalog.Price) *BillingInvoiceUsageBasedLineConfigUpsertBulk { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.SetPrice(v) + }) +} + +// UpdatePrice sets the "price" field to the value that was provided on create. +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) UpdatePrice() *BillingInvoiceUsageBasedLineConfigUpsertBulk { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.UpdatePrice() + }) +} + +// SetPreLinePeriodQuantity sets the "pre_line_period_quantity" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) SetPreLinePeriodQuantity(v alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpsertBulk { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.SetPreLinePeriodQuantity(v) + }) +} + +// UpdatePreLinePeriodQuantity sets the "pre_line_period_quantity" field to the value that was provided on create. +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) UpdatePreLinePeriodQuantity() *BillingInvoiceUsageBasedLineConfigUpsertBulk { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.UpdatePreLinePeriodQuantity() + }) +} + +// ClearPreLinePeriodQuantity clears the value of the "pre_line_period_quantity" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) ClearPreLinePeriodQuantity() *BillingInvoiceUsageBasedLineConfigUpsertBulk { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.ClearPreLinePeriodQuantity() + }) +} + +// SetMeteredPreLinePeriodQuantity sets the "metered_pre_line_period_quantity" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) SetMeteredPreLinePeriodQuantity(v alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpsertBulk { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.SetMeteredPreLinePeriodQuantity(v) + }) +} + +// UpdateMeteredPreLinePeriodQuantity sets the "metered_pre_line_period_quantity" field to the value that was provided on create. +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) UpdateMeteredPreLinePeriodQuantity() *BillingInvoiceUsageBasedLineConfigUpsertBulk { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.UpdateMeteredPreLinePeriodQuantity() + }) +} + +// ClearMeteredPreLinePeriodQuantity clears the value of the "metered_pre_line_period_quantity" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) ClearMeteredPreLinePeriodQuantity() *BillingInvoiceUsageBasedLineConfigUpsertBulk { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.ClearMeteredPreLinePeriodQuantity() + }) +} + +// SetMeteredQuantity sets the "metered_quantity" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) SetMeteredQuantity(v alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpsertBulk { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.SetMeteredQuantity(v) + }) +} + +// UpdateMeteredQuantity sets the "metered_quantity" field to the value that was provided on create. +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) UpdateMeteredQuantity() *BillingInvoiceUsageBasedLineConfigUpsertBulk { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.UpdateMeteredQuantity() + }) +} + +// ClearMeteredQuantity clears the value of the "metered_quantity" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) ClearMeteredQuantity() *BillingInvoiceUsageBasedLineConfigUpsertBulk { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.ClearMeteredQuantity() + }) +} + +// SetUnitConfig sets the "unit_config" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) SetUnitConfig(v *productcatalog.UnitConfig) *BillingInvoiceUsageBasedLineConfigUpsertBulk { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.SetUnitConfig(v) + }) +} + +// UpdateUnitConfig sets the "unit_config" field to the value that was provided on create. +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) UpdateUnitConfig() *BillingInvoiceUsageBasedLineConfigUpsertBulk { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.UpdateUnitConfig() + }) +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) ClearUnitConfig() *BillingInvoiceUsageBasedLineConfigUpsertBulk { + return u.Update(func(s *BillingInvoiceUsageBasedLineConfigUpsert) { + s.ClearUnitConfig() + }) +} + +// Exec executes the query. +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) 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 BillingInvoiceUsageBasedLineConfigCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingInvoiceUsageBasedLineConfigCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingInvoiceUsageBasedLineConfigUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billinginvoiceusagebasedlineconfig_delete.go b/ent/db/billinginvoiceusagebasedlineconfig_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..2d559994235f096341f5a1437d43af1374553264 --- /dev/null +++ b/ent/db/billinginvoiceusagebasedlineconfig_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/billinginvoiceusagebasedlineconfig" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingInvoiceUsageBasedLineConfigDelete is the builder for deleting a BillingInvoiceUsageBasedLineConfig entity. +type BillingInvoiceUsageBasedLineConfigDelete struct { + config + hooks []Hook + mutation *BillingInvoiceUsageBasedLineConfigMutation +} + +// Where appends a list predicates to the BillingInvoiceUsageBasedLineConfigDelete builder. +func (_d *BillingInvoiceUsageBasedLineConfigDelete) Where(ps ...predicate.BillingInvoiceUsageBasedLineConfig) *BillingInvoiceUsageBasedLineConfigDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *BillingInvoiceUsageBasedLineConfigDelete) 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 *BillingInvoiceUsageBasedLineConfigDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *BillingInvoiceUsageBasedLineConfigDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(billinginvoiceusagebasedlineconfig.Table, sqlgraph.NewFieldSpec(billinginvoiceusagebasedlineconfig.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 +} + +// BillingInvoiceUsageBasedLineConfigDeleteOne is the builder for deleting a single BillingInvoiceUsageBasedLineConfig entity. +type BillingInvoiceUsageBasedLineConfigDeleteOne struct { + _d *BillingInvoiceUsageBasedLineConfigDelete +} + +// Where appends a list predicates to the BillingInvoiceUsageBasedLineConfigDelete builder. +func (_d *BillingInvoiceUsageBasedLineConfigDeleteOne) Where(ps ...predicate.BillingInvoiceUsageBasedLineConfig) *BillingInvoiceUsageBasedLineConfigDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *BillingInvoiceUsageBasedLineConfigDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{billinginvoiceusagebasedlineconfig.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *BillingInvoiceUsageBasedLineConfigDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billinginvoiceusagebasedlineconfig_query.go b/ent/db/billinginvoiceusagebasedlineconfig_query.go new file mode 100644 index 0000000000000000000000000000000000000000..56657400e757cf7f3ebd07830383d587f158f048 --- /dev/null +++ b/ent/db/billinginvoiceusagebasedlineconfig_query.go @@ -0,0 +1,564 @@ +// 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/billinginvoiceusagebasedlineconfig" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingInvoiceUsageBasedLineConfigQuery is the builder for querying BillingInvoiceUsageBasedLineConfig entities. +type BillingInvoiceUsageBasedLineConfigQuery struct { + config + ctx *QueryContext + order []billinginvoiceusagebasedlineconfig.OrderOption + inters []Interceptor + predicates []predicate.BillingInvoiceUsageBasedLineConfig + 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 BillingInvoiceUsageBasedLineConfigQuery builder. +func (_q *BillingInvoiceUsageBasedLineConfigQuery) Where(ps ...predicate.BillingInvoiceUsageBasedLineConfig) *BillingInvoiceUsageBasedLineConfigQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *BillingInvoiceUsageBasedLineConfigQuery) Limit(limit int) *BillingInvoiceUsageBasedLineConfigQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *BillingInvoiceUsageBasedLineConfigQuery) Offset(offset int) *BillingInvoiceUsageBasedLineConfigQuery { + _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 *BillingInvoiceUsageBasedLineConfigQuery) Unique(unique bool) *BillingInvoiceUsageBasedLineConfigQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *BillingInvoiceUsageBasedLineConfigQuery) Order(o ...billinginvoiceusagebasedlineconfig.OrderOption) *BillingInvoiceUsageBasedLineConfigQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first BillingInvoiceUsageBasedLineConfig entity from the query. +// Returns a *NotFoundError when no BillingInvoiceUsageBasedLineConfig was found. +func (_q *BillingInvoiceUsageBasedLineConfigQuery) First(ctx context.Context) (*BillingInvoiceUsageBasedLineConfig, 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{billinginvoiceusagebasedlineconfig.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *BillingInvoiceUsageBasedLineConfigQuery) FirstX(ctx context.Context) *BillingInvoiceUsageBasedLineConfig { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first BillingInvoiceUsageBasedLineConfig ID from the query. +// Returns a *NotFoundError when no BillingInvoiceUsageBasedLineConfig ID was found. +func (_q *BillingInvoiceUsageBasedLineConfigQuery) 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{billinginvoiceusagebasedlineconfig.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *BillingInvoiceUsageBasedLineConfigQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single BillingInvoiceUsageBasedLineConfig entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one BillingInvoiceUsageBasedLineConfig entity is found. +// Returns a *NotFoundError when no BillingInvoiceUsageBasedLineConfig entities are found. +func (_q *BillingInvoiceUsageBasedLineConfigQuery) Only(ctx context.Context) (*BillingInvoiceUsageBasedLineConfig, 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{billinginvoiceusagebasedlineconfig.Label} + default: + return nil, &NotSingularError{billinginvoiceusagebasedlineconfig.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *BillingInvoiceUsageBasedLineConfigQuery) OnlyX(ctx context.Context) *BillingInvoiceUsageBasedLineConfig { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only BillingInvoiceUsageBasedLineConfig ID in the query. +// Returns a *NotSingularError when more than one BillingInvoiceUsageBasedLineConfig ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *BillingInvoiceUsageBasedLineConfigQuery) 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{billinginvoiceusagebasedlineconfig.Label} + default: + err = &NotSingularError{billinginvoiceusagebasedlineconfig.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *BillingInvoiceUsageBasedLineConfigQuery) 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 BillingInvoiceUsageBasedLineConfigs. +func (_q *BillingInvoiceUsageBasedLineConfigQuery) All(ctx context.Context) ([]*BillingInvoiceUsageBasedLineConfig, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*BillingInvoiceUsageBasedLineConfig, *BillingInvoiceUsageBasedLineConfigQuery]() + return withInterceptors[[]*BillingInvoiceUsageBasedLineConfig](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *BillingInvoiceUsageBasedLineConfigQuery) AllX(ctx context.Context) []*BillingInvoiceUsageBasedLineConfig { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of BillingInvoiceUsageBasedLineConfig IDs. +func (_q *BillingInvoiceUsageBasedLineConfigQuery) 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(billinginvoiceusagebasedlineconfig.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *BillingInvoiceUsageBasedLineConfigQuery) 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 *BillingInvoiceUsageBasedLineConfigQuery) 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[*BillingInvoiceUsageBasedLineConfigQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *BillingInvoiceUsageBasedLineConfigQuery) 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 *BillingInvoiceUsageBasedLineConfigQuery) 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 *BillingInvoiceUsageBasedLineConfigQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the BillingInvoiceUsageBasedLineConfigQuery 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 *BillingInvoiceUsageBasedLineConfigQuery) Clone() *BillingInvoiceUsageBasedLineConfigQuery { + if _q == nil { + return nil + } + return &BillingInvoiceUsageBasedLineConfigQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]billinginvoiceusagebasedlineconfig.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.BillingInvoiceUsageBasedLineConfig{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// 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.BillingInvoiceUsageBasedLineConfig.Query(). +// GroupBy(billinginvoiceusagebasedlineconfig.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *BillingInvoiceUsageBasedLineConfigQuery) GroupBy(field string, fields ...string) *BillingInvoiceUsageBasedLineConfigGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &BillingInvoiceUsageBasedLineConfigGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = billinginvoiceusagebasedlineconfig.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.BillingInvoiceUsageBasedLineConfig.Query(). +// Select(billinginvoiceusagebasedlineconfig.FieldNamespace). +// Scan(ctx, &v) +func (_q *BillingInvoiceUsageBasedLineConfigQuery) Select(fields ...string) *BillingInvoiceUsageBasedLineConfigSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &BillingInvoiceUsageBasedLineConfigSelect{BillingInvoiceUsageBasedLineConfigQuery: _q} + sbuild.label = billinginvoiceusagebasedlineconfig.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a BillingInvoiceUsageBasedLineConfigSelect configured with the given aggregations. +func (_q *BillingInvoiceUsageBasedLineConfigQuery) Aggregate(fns ...AggregateFunc) *BillingInvoiceUsageBasedLineConfigSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *BillingInvoiceUsageBasedLineConfigQuery) 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 !billinginvoiceusagebasedlineconfig.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 *BillingInvoiceUsageBasedLineConfigQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BillingInvoiceUsageBasedLineConfig, error) { + var ( + nodes = []*BillingInvoiceUsageBasedLineConfig{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*BillingInvoiceUsageBasedLineConfig).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &BillingInvoiceUsageBasedLineConfig{config: _q.config} + nodes = append(nodes, node) + 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 + } + return nodes, nil +} + +func (_q *BillingInvoiceUsageBasedLineConfigQuery) 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 *BillingInvoiceUsageBasedLineConfigQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(billinginvoiceusagebasedlineconfig.Table, billinginvoiceusagebasedlineconfig.Columns, sqlgraph.NewFieldSpec(billinginvoiceusagebasedlineconfig.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, billinginvoiceusagebasedlineconfig.FieldID) + for i := range fields { + if fields[i] != billinginvoiceusagebasedlineconfig.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 *BillingInvoiceUsageBasedLineConfigQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(billinginvoiceusagebasedlineconfig.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = billinginvoiceusagebasedlineconfig.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 *BillingInvoiceUsageBasedLineConfigQuery) ForUpdate(opts ...sql.LockOption) *BillingInvoiceUsageBasedLineConfigQuery { + 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 *BillingInvoiceUsageBasedLineConfigQuery) ForShare(opts ...sql.LockOption) *BillingInvoiceUsageBasedLineConfigQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// BillingInvoiceUsageBasedLineConfigGroupBy is the group-by builder for BillingInvoiceUsageBasedLineConfig entities. +type BillingInvoiceUsageBasedLineConfigGroupBy struct { + selector + build *BillingInvoiceUsageBasedLineConfigQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *BillingInvoiceUsageBasedLineConfigGroupBy) Aggregate(fns ...AggregateFunc) *BillingInvoiceUsageBasedLineConfigGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *BillingInvoiceUsageBasedLineConfigGroupBy) 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[*BillingInvoiceUsageBasedLineConfigQuery, *BillingInvoiceUsageBasedLineConfigGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *BillingInvoiceUsageBasedLineConfigGroupBy) sqlScan(ctx context.Context, root *BillingInvoiceUsageBasedLineConfigQuery, 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) +} + +// BillingInvoiceUsageBasedLineConfigSelect is the builder for selecting fields of BillingInvoiceUsageBasedLineConfig entities. +type BillingInvoiceUsageBasedLineConfigSelect struct { + *BillingInvoiceUsageBasedLineConfigQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *BillingInvoiceUsageBasedLineConfigSelect) Aggregate(fns ...AggregateFunc) *BillingInvoiceUsageBasedLineConfigSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *BillingInvoiceUsageBasedLineConfigSelect) 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[*BillingInvoiceUsageBasedLineConfigQuery, *BillingInvoiceUsageBasedLineConfigSelect](ctx, _s.BillingInvoiceUsageBasedLineConfigQuery, _s, _s.inters, v) +} + +func (_s *BillingInvoiceUsageBasedLineConfigSelect) sqlScan(ctx context.Context, root *BillingInvoiceUsageBasedLineConfigQuery, 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/ent/db/billinginvoiceusagebasedlineconfig_update.go b/ent/db/billinginvoiceusagebasedlineconfig_update.go new file mode 100644 index 0000000000000000000000000000000000000000..6a138ba7551b91933a83feaf4a2a25cca1e48ce6 --- /dev/null +++ b/ent/db/billinginvoiceusagebasedlineconfig_update.go @@ -0,0 +1,489 @@ +// 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/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceusagebasedlineconfig" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/productcatalog" +) + +// BillingInvoiceUsageBasedLineConfigUpdate is the builder for updating BillingInvoiceUsageBasedLineConfig entities. +type BillingInvoiceUsageBasedLineConfigUpdate struct { + config + hooks []Hook + mutation *BillingInvoiceUsageBasedLineConfigMutation +} + +// Where appends a list predicates to the BillingInvoiceUsageBasedLineConfigUpdate builder. +func (_u *BillingInvoiceUsageBasedLineConfigUpdate) Where(ps ...predicate.BillingInvoiceUsageBasedLineConfig) *BillingInvoiceUsageBasedLineConfigUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetPriceType sets the "price_type" field. +func (_u *BillingInvoiceUsageBasedLineConfigUpdate) SetPriceType(v productcatalog.PriceType) *BillingInvoiceUsageBasedLineConfigUpdate { + _u.mutation.SetPriceType(v) + return _u +} + +// SetNillablePriceType sets the "price_type" field if the given value is not nil. +func (_u *BillingInvoiceUsageBasedLineConfigUpdate) SetNillablePriceType(v *productcatalog.PriceType) *BillingInvoiceUsageBasedLineConfigUpdate { + if v != nil { + _u.SetPriceType(*v) + } + return _u +} + +// SetPrice sets the "price" field. +func (_u *BillingInvoiceUsageBasedLineConfigUpdate) SetPrice(v *productcatalog.Price) *BillingInvoiceUsageBasedLineConfigUpdate { + _u.mutation.SetPrice(v) + return _u +} + +// SetPreLinePeriodQuantity sets the "pre_line_period_quantity" field. +func (_u *BillingInvoiceUsageBasedLineConfigUpdate) SetPreLinePeriodQuantity(v alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpdate { + _u.mutation.SetPreLinePeriodQuantity(v) + return _u +} + +// SetNillablePreLinePeriodQuantity sets the "pre_line_period_quantity" field if the given value is not nil. +func (_u *BillingInvoiceUsageBasedLineConfigUpdate) SetNillablePreLinePeriodQuantity(v *alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpdate { + if v != nil { + _u.SetPreLinePeriodQuantity(*v) + } + return _u +} + +// ClearPreLinePeriodQuantity clears the value of the "pre_line_period_quantity" field. +func (_u *BillingInvoiceUsageBasedLineConfigUpdate) ClearPreLinePeriodQuantity() *BillingInvoiceUsageBasedLineConfigUpdate { + _u.mutation.ClearPreLinePeriodQuantity() + return _u +} + +// SetMeteredPreLinePeriodQuantity sets the "metered_pre_line_period_quantity" field. +func (_u *BillingInvoiceUsageBasedLineConfigUpdate) SetMeteredPreLinePeriodQuantity(v alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpdate { + _u.mutation.SetMeteredPreLinePeriodQuantity(v) + return _u +} + +// SetNillableMeteredPreLinePeriodQuantity sets the "metered_pre_line_period_quantity" field if the given value is not nil. +func (_u *BillingInvoiceUsageBasedLineConfigUpdate) SetNillableMeteredPreLinePeriodQuantity(v *alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpdate { + if v != nil { + _u.SetMeteredPreLinePeriodQuantity(*v) + } + return _u +} + +// ClearMeteredPreLinePeriodQuantity clears the value of the "metered_pre_line_period_quantity" field. +func (_u *BillingInvoiceUsageBasedLineConfigUpdate) ClearMeteredPreLinePeriodQuantity() *BillingInvoiceUsageBasedLineConfigUpdate { + _u.mutation.ClearMeteredPreLinePeriodQuantity() + return _u +} + +// SetMeteredQuantity sets the "metered_quantity" field. +func (_u *BillingInvoiceUsageBasedLineConfigUpdate) SetMeteredQuantity(v alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpdate { + _u.mutation.SetMeteredQuantity(v) + return _u +} + +// SetNillableMeteredQuantity sets the "metered_quantity" field if the given value is not nil. +func (_u *BillingInvoiceUsageBasedLineConfigUpdate) SetNillableMeteredQuantity(v *alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpdate { + if v != nil { + _u.SetMeteredQuantity(*v) + } + return _u +} + +// ClearMeteredQuantity clears the value of the "metered_quantity" field. +func (_u *BillingInvoiceUsageBasedLineConfigUpdate) ClearMeteredQuantity() *BillingInvoiceUsageBasedLineConfigUpdate { + _u.mutation.ClearMeteredQuantity() + return _u +} + +// SetUnitConfig sets the "unit_config" field. +func (_u *BillingInvoiceUsageBasedLineConfigUpdate) SetUnitConfig(v *productcatalog.UnitConfig) *BillingInvoiceUsageBasedLineConfigUpdate { + _u.mutation.SetUnitConfig(v) + return _u +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (_u *BillingInvoiceUsageBasedLineConfigUpdate) ClearUnitConfig() *BillingInvoiceUsageBasedLineConfigUpdate { + _u.mutation.ClearUnitConfig() + return _u +} + +// Mutation returns the BillingInvoiceUsageBasedLineConfigMutation object of the builder. +func (_u *BillingInvoiceUsageBasedLineConfigUpdate) Mutation() *BillingInvoiceUsageBasedLineConfigMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *BillingInvoiceUsageBasedLineConfigUpdate) 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 *BillingInvoiceUsageBasedLineConfigUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *BillingInvoiceUsageBasedLineConfigUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingInvoiceUsageBasedLineConfigUpdate) 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 *BillingInvoiceUsageBasedLineConfigUpdate) check() error { + if v, ok := _u.mutation.PriceType(); ok { + if err := billinginvoiceusagebasedlineconfig.PriceTypeValidator(v); err != nil { + return &ValidationError{Name: "price_type", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceUsageBasedLineConfig.price_type": %w`, err)} + } + } + if v, ok := _u.mutation.Price(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "price", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceUsageBasedLineConfig.price": %w`, err)} + } + } + if v, ok := _u.mutation.UnitConfig(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "unit_config", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceUsageBasedLineConfig.unit_config": %w`, err)} + } + } + return nil +} + +func (_u *BillingInvoiceUsageBasedLineConfigUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(billinginvoiceusagebasedlineconfig.Table, billinginvoiceusagebasedlineconfig.Columns, sqlgraph.NewFieldSpec(billinginvoiceusagebasedlineconfig.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.PriceType(); ok { + _spec.SetField(billinginvoiceusagebasedlineconfig.FieldPriceType, field.TypeEnum, value) + } + if _u.mutation.FeatureKeyCleared() { + _spec.ClearField(billinginvoiceusagebasedlineconfig.FieldFeatureKey, field.TypeString) + } + if value, ok := _u.mutation.Price(); ok { + vv, err := billinginvoiceusagebasedlineconfig.ValueScanner.Price.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(billinginvoiceusagebasedlineconfig.FieldPrice, field.TypeString, vv) + } + if value, ok := _u.mutation.PreLinePeriodQuantity(); ok { + _spec.SetField(billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity, field.TypeOther, value) + } + if _u.mutation.PreLinePeriodQuantityCleared() { + _spec.ClearField(billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity, field.TypeOther) + } + if value, ok := _u.mutation.MeteredPreLinePeriodQuantity(); ok { + _spec.SetField(billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity, field.TypeOther, value) + } + if _u.mutation.MeteredPreLinePeriodQuantityCleared() { + _spec.ClearField(billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity, field.TypeOther) + } + if value, ok := _u.mutation.MeteredQuantity(); ok { + _spec.SetField(billinginvoiceusagebasedlineconfig.FieldMeteredQuantity, field.TypeOther, value) + } + if _u.mutation.MeteredQuantityCleared() { + _spec.ClearField(billinginvoiceusagebasedlineconfig.FieldMeteredQuantity, field.TypeOther) + } + if value, ok := _u.mutation.UnitConfig(); ok { + vv, err := billinginvoiceusagebasedlineconfig.ValueScanner.UnitConfig.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(billinginvoiceusagebasedlineconfig.FieldUnitConfig, field.TypeString, vv) + } + if _u.mutation.UnitConfigCleared() { + _spec.ClearField(billinginvoiceusagebasedlineconfig.FieldUnitConfig, field.TypeString) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{billinginvoiceusagebasedlineconfig.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// BillingInvoiceUsageBasedLineConfigUpdateOne is the builder for updating a single BillingInvoiceUsageBasedLineConfig entity. +type BillingInvoiceUsageBasedLineConfigUpdateOne struct { + config + fields []string + hooks []Hook + mutation *BillingInvoiceUsageBasedLineConfigMutation +} + +// SetPriceType sets the "price_type" field. +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) SetPriceType(v productcatalog.PriceType) *BillingInvoiceUsageBasedLineConfigUpdateOne { + _u.mutation.SetPriceType(v) + return _u +} + +// SetNillablePriceType sets the "price_type" field if the given value is not nil. +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) SetNillablePriceType(v *productcatalog.PriceType) *BillingInvoiceUsageBasedLineConfigUpdateOne { + if v != nil { + _u.SetPriceType(*v) + } + return _u +} + +// SetPrice sets the "price" field. +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) SetPrice(v *productcatalog.Price) *BillingInvoiceUsageBasedLineConfigUpdateOne { + _u.mutation.SetPrice(v) + return _u +} + +// SetPreLinePeriodQuantity sets the "pre_line_period_quantity" field. +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) SetPreLinePeriodQuantity(v alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpdateOne { + _u.mutation.SetPreLinePeriodQuantity(v) + return _u +} + +// SetNillablePreLinePeriodQuantity sets the "pre_line_period_quantity" field if the given value is not nil. +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) SetNillablePreLinePeriodQuantity(v *alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpdateOne { + if v != nil { + _u.SetPreLinePeriodQuantity(*v) + } + return _u +} + +// ClearPreLinePeriodQuantity clears the value of the "pre_line_period_quantity" field. +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) ClearPreLinePeriodQuantity() *BillingInvoiceUsageBasedLineConfigUpdateOne { + _u.mutation.ClearPreLinePeriodQuantity() + return _u +} + +// SetMeteredPreLinePeriodQuantity sets the "metered_pre_line_period_quantity" field. +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) SetMeteredPreLinePeriodQuantity(v alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpdateOne { + _u.mutation.SetMeteredPreLinePeriodQuantity(v) + return _u +} + +// SetNillableMeteredPreLinePeriodQuantity sets the "metered_pre_line_period_quantity" field if the given value is not nil. +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) SetNillableMeteredPreLinePeriodQuantity(v *alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpdateOne { + if v != nil { + _u.SetMeteredPreLinePeriodQuantity(*v) + } + return _u +} + +// ClearMeteredPreLinePeriodQuantity clears the value of the "metered_pre_line_period_quantity" field. +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) ClearMeteredPreLinePeriodQuantity() *BillingInvoiceUsageBasedLineConfigUpdateOne { + _u.mutation.ClearMeteredPreLinePeriodQuantity() + return _u +} + +// SetMeteredQuantity sets the "metered_quantity" field. +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) SetMeteredQuantity(v alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpdateOne { + _u.mutation.SetMeteredQuantity(v) + return _u +} + +// SetNillableMeteredQuantity sets the "metered_quantity" field if the given value is not nil. +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) SetNillableMeteredQuantity(v *alpacadecimal.Decimal) *BillingInvoiceUsageBasedLineConfigUpdateOne { + if v != nil { + _u.SetMeteredQuantity(*v) + } + return _u +} + +// ClearMeteredQuantity clears the value of the "metered_quantity" field. +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) ClearMeteredQuantity() *BillingInvoiceUsageBasedLineConfigUpdateOne { + _u.mutation.ClearMeteredQuantity() + return _u +} + +// SetUnitConfig sets the "unit_config" field. +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) SetUnitConfig(v *productcatalog.UnitConfig) *BillingInvoiceUsageBasedLineConfigUpdateOne { + _u.mutation.SetUnitConfig(v) + return _u +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) ClearUnitConfig() *BillingInvoiceUsageBasedLineConfigUpdateOne { + _u.mutation.ClearUnitConfig() + return _u +} + +// Mutation returns the BillingInvoiceUsageBasedLineConfigMutation object of the builder. +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) Mutation() *BillingInvoiceUsageBasedLineConfigMutation { + return _u.mutation +} + +// Where appends a list predicates to the BillingInvoiceUsageBasedLineConfigUpdate builder. +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) Where(ps ...predicate.BillingInvoiceUsageBasedLineConfig) *BillingInvoiceUsageBasedLineConfigUpdateOne { + _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 *BillingInvoiceUsageBasedLineConfigUpdateOne) Select(field string, fields ...string) *BillingInvoiceUsageBasedLineConfigUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated BillingInvoiceUsageBasedLineConfig entity. +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) Save(ctx context.Context) (*BillingInvoiceUsageBasedLineConfig, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) SaveX(ctx context.Context) *BillingInvoiceUsageBasedLineConfig { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) 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 *BillingInvoiceUsageBasedLineConfigUpdateOne) check() error { + if v, ok := _u.mutation.PriceType(); ok { + if err := billinginvoiceusagebasedlineconfig.PriceTypeValidator(v); err != nil { + return &ValidationError{Name: "price_type", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceUsageBasedLineConfig.price_type": %w`, err)} + } + } + if v, ok := _u.mutation.Price(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "price", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceUsageBasedLineConfig.price": %w`, err)} + } + } + if v, ok := _u.mutation.UnitConfig(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "unit_config", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceUsageBasedLineConfig.unit_config": %w`, err)} + } + } + return nil +} + +func (_u *BillingInvoiceUsageBasedLineConfigUpdateOne) sqlSave(ctx context.Context) (_node *BillingInvoiceUsageBasedLineConfig, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(billinginvoiceusagebasedlineconfig.Table, billinginvoiceusagebasedlineconfig.Columns, sqlgraph.NewFieldSpec(billinginvoiceusagebasedlineconfig.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "BillingInvoiceUsageBasedLineConfig.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, billinginvoiceusagebasedlineconfig.FieldID) + for _, f := range fields { + if !billinginvoiceusagebasedlineconfig.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != billinginvoiceusagebasedlineconfig.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.PriceType(); ok { + _spec.SetField(billinginvoiceusagebasedlineconfig.FieldPriceType, field.TypeEnum, value) + } + if _u.mutation.FeatureKeyCleared() { + _spec.ClearField(billinginvoiceusagebasedlineconfig.FieldFeatureKey, field.TypeString) + } + if value, ok := _u.mutation.Price(); ok { + vv, err := billinginvoiceusagebasedlineconfig.ValueScanner.Price.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(billinginvoiceusagebasedlineconfig.FieldPrice, field.TypeString, vv) + } + if value, ok := _u.mutation.PreLinePeriodQuantity(); ok { + _spec.SetField(billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity, field.TypeOther, value) + } + if _u.mutation.PreLinePeriodQuantityCleared() { + _spec.ClearField(billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity, field.TypeOther) + } + if value, ok := _u.mutation.MeteredPreLinePeriodQuantity(); ok { + _spec.SetField(billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity, field.TypeOther, value) + } + if _u.mutation.MeteredPreLinePeriodQuantityCleared() { + _spec.ClearField(billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity, field.TypeOther) + } + if value, ok := _u.mutation.MeteredQuantity(); ok { + _spec.SetField(billinginvoiceusagebasedlineconfig.FieldMeteredQuantity, field.TypeOther, value) + } + if _u.mutation.MeteredQuantityCleared() { + _spec.ClearField(billinginvoiceusagebasedlineconfig.FieldMeteredQuantity, field.TypeOther) + } + if value, ok := _u.mutation.UnitConfig(); ok { + vv, err := billinginvoiceusagebasedlineconfig.ValueScanner.UnitConfig.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(billinginvoiceusagebasedlineconfig.FieldUnitConfig, field.TypeString, vv) + } + if _u.mutation.UnitConfigCleared() { + _spec.ClearField(billinginvoiceusagebasedlineconfig.FieldUnitConfig, field.TypeString) + } + _node = &BillingInvoiceUsageBasedLineConfig{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{billinginvoiceusagebasedlineconfig.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/ent/db/billinginvoicevalidationissue.go b/ent/db/billinginvoicevalidationissue.go new file mode 100644 index 0000000000000000000000000000000000000000..617694eded80700ab000280ced78afa16a851c6c --- /dev/null +++ b/ent/db/billinginvoicevalidationissue.go @@ -0,0 +1,255 @@ +// 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/billing" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicevalidationissue" +) + +// BillingInvoiceValidationIssue is the model entity for the BillingInvoiceValidationIssue schema. +type BillingInvoiceValidationIssue 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"` + // InvoiceID holds the value of the "invoice_id" field. + InvoiceID string `json:"invoice_id,omitempty"` + // Severity holds the value of the "severity" field. + Severity billing.ValidationIssueSeverity `json:"severity,omitempty"` + // Code holds the value of the "code" field. + Code *string `json:"code,omitempty"` + // Message holds the value of the "message" field. + Message string `json:"message,omitempty"` + // Path holds the value of the "path" field. + Path *string `json:"path,omitempty"` + // Component holds the value of the "component" field. + Component string `json:"component,omitempty"` + // DedupeHash holds the value of the "dedupe_hash" field. + DedupeHash []byte `json:"dedupe_hash,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the BillingInvoiceValidationIssueQuery when eager-loading is set. + Edges BillingInvoiceValidationIssueEdges `json:"edges"` + selectValues sql.SelectValues +} + +// BillingInvoiceValidationIssueEdges holds the relations/edges for other nodes in the graph. +type BillingInvoiceValidationIssueEdges struct { + // BillingInvoice holds the value of the billing_invoice edge. + BillingInvoice *BillingInvoice `json:"billing_invoice,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// BillingInvoiceOrErr returns the BillingInvoice value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e BillingInvoiceValidationIssueEdges) BillingInvoiceOrErr() (*BillingInvoice, error) { + if e.BillingInvoice != nil { + return e.BillingInvoice, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: billinginvoice.Label} + } + return nil, &NotLoadedError{edge: "billing_invoice"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*BillingInvoiceValidationIssue) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case billinginvoicevalidationissue.FieldDedupeHash: + values[i] = new([]byte) + case billinginvoicevalidationissue.FieldID, billinginvoicevalidationissue.FieldNamespace, billinginvoicevalidationissue.FieldInvoiceID, billinginvoicevalidationissue.FieldSeverity, billinginvoicevalidationissue.FieldCode, billinginvoicevalidationissue.FieldMessage, billinginvoicevalidationissue.FieldPath, billinginvoicevalidationissue.FieldComponent: + values[i] = new(sql.NullString) + case billinginvoicevalidationissue.FieldCreatedAt, billinginvoicevalidationissue.FieldUpdatedAt, billinginvoicevalidationissue.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 BillingInvoiceValidationIssue fields. +func (_m *BillingInvoiceValidationIssue) 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 billinginvoicevalidationissue.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 billinginvoicevalidationissue.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 billinginvoicevalidationissue.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 billinginvoicevalidationissue.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 billinginvoicevalidationissue.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 billinginvoicevalidationissue.FieldInvoiceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field invoice_id", values[i]) + } else if value.Valid { + _m.InvoiceID = value.String + } + case billinginvoicevalidationissue.FieldSeverity: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field severity", values[i]) + } else if value.Valid { + _m.Severity = billing.ValidationIssueSeverity(value.String) + } + case billinginvoicevalidationissue.FieldCode: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field code", values[i]) + } else if value.Valid { + _m.Code = new(string) + *_m.Code = value.String + } + case billinginvoicevalidationissue.FieldMessage: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field message", values[i]) + } else if value.Valid { + _m.Message = value.String + } + case billinginvoicevalidationissue.FieldPath: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field path", values[i]) + } else if value.Valid { + _m.Path = new(string) + *_m.Path = value.String + } + case billinginvoicevalidationissue.FieldComponent: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field component", values[i]) + } else if value.Valid { + _m.Component = value.String + } + case billinginvoicevalidationissue.FieldDedupeHash: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field dedupe_hash", values[i]) + } else if value != nil { + _m.DedupeHash = *value + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the BillingInvoiceValidationIssue. +// This includes values selected through modifiers, order, etc. +func (_m *BillingInvoiceValidationIssue) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryBillingInvoice queries the "billing_invoice" edge of the BillingInvoiceValidationIssue entity. +func (_m *BillingInvoiceValidationIssue) QueryBillingInvoice() *BillingInvoiceQuery { + return NewBillingInvoiceValidationIssueClient(_m.config).QueryBillingInvoice(_m) +} + +// Update returns a builder for updating this BillingInvoiceValidationIssue. +// Note that you need to call BillingInvoiceValidationIssue.Unwrap() before calling this method if this BillingInvoiceValidationIssue +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *BillingInvoiceValidationIssue) Update() *BillingInvoiceValidationIssueUpdateOne { + return NewBillingInvoiceValidationIssueClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the BillingInvoiceValidationIssue 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 *BillingInvoiceValidationIssue) Unwrap() *BillingInvoiceValidationIssue { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: BillingInvoiceValidationIssue is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *BillingInvoiceValidationIssue) String() string { + var builder strings.Builder + builder.WriteString("BillingInvoiceValidationIssue(") + 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("invoice_id=") + builder.WriteString(_m.InvoiceID) + builder.WriteString(", ") + builder.WriteString("severity=") + builder.WriteString(fmt.Sprintf("%v", _m.Severity)) + builder.WriteString(", ") + if v := _m.Code; v != nil { + builder.WriteString("code=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("message=") + builder.WriteString(_m.Message) + builder.WriteString(", ") + if v := _m.Path; v != nil { + builder.WriteString("path=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("component=") + builder.WriteString(_m.Component) + builder.WriteString(", ") + builder.WriteString("dedupe_hash=") + builder.WriteString(fmt.Sprintf("%v", _m.DedupeHash)) + builder.WriteByte(')') + return builder.String() +} + +// BillingInvoiceValidationIssues is a parsable slice of BillingInvoiceValidationIssue. +type BillingInvoiceValidationIssues []*BillingInvoiceValidationIssue diff --git a/ent/db/billinginvoicevalidationissue/billinginvoicevalidationissue.go b/ent/db/billinginvoicevalidationissue/billinginvoicevalidationissue.go new file mode 100644 index 0000000000000000000000000000000000000000..3c9e2cab1f09534b99567996b30e1e47a78bc451 --- /dev/null +++ b/ent/db/billinginvoicevalidationissue/billinginvoicevalidationissue.go @@ -0,0 +1,179 @@ +// Code generated by ent, DO NOT EDIT. + +package billinginvoicevalidationissue + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/billing" +) + +const ( + // Label holds the string label denoting the billinginvoicevalidationissue type in the database. + Label = "billing_invoice_validation_issue" + // 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" + // FieldInvoiceID holds the string denoting the invoice_id field in the database. + FieldInvoiceID = "invoice_id" + // FieldSeverity holds the string denoting the severity field in the database. + FieldSeverity = "severity" + // FieldCode holds the string denoting the code field in the database. + FieldCode = "code" + // FieldMessage holds the string denoting the message field in the database. + FieldMessage = "message" + // FieldPath holds the string denoting the path field in the database. + FieldPath = "path" + // FieldComponent holds the string denoting the component field in the database. + FieldComponent = "component" + // FieldDedupeHash holds the string denoting the dedupe_hash field in the database. + FieldDedupeHash = "dedupe_hash" + // EdgeBillingInvoice holds the string denoting the billing_invoice edge name in mutations. + EdgeBillingInvoice = "billing_invoice" + // Table holds the table name of the billinginvoicevalidationissue in the database. + Table = "billing_invoice_validation_issues" + // BillingInvoiceTable is the table that holds the billing_invoice relation/edge. + BillingInvoiceTable = "billing_invoice_validation_issues" + // BillingInvoiceInverseTable is the table name for the BillingInvoice entity. + // It exists in this package in order to avoid circular dependency with the "billinginvoice" package. + BillingInvoiceInverseTable = "billing_invoices" + // BillingInvoiceColumn is the table column denoting the billing_invoice relation/edge. + BillingInvoiceColumn = "invoice_id" +) + +// Columns holds all SQL columns for billinginvoicevalidationissue fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldInvoiceID, + FieldSeverity, + FieldCode, + FieldMessage, + FieldPath, + FieldComponent, + FieldDedupeHash, +} + +// 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 + // InvoiceIDValidator is a validator for the "invoice_id" field. It is called by the builders before save. + InvoiceIDValidator func(string) error + // MessageValidator is a validator for the "message" field. It is called by the builders before save. + MessageValidator func(string) error + // DedupeHashValidator is a validator for the "dedupe_hash" field. It is called by the builders before save. + DedupeHashValidator func([]byte) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// SeverityValidator is a validator for the "severity" field enum values. It is called by the builders before save. +func SeverityValidator(s billing.ValidationIssueSeverity) error { + switch s { + case "critical", "warning": + return nil + default: + return fmt.Errorf("billinginvoicevalidationissue: invalid enum value for severity field: %q", s) + } +} + +// OrderOption defines the ordering options for the BillingInvoiceValidationIssue 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() +} + +// ByInvoiceID orders the results by the invoice_id field. +func ByInvoiceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoiceID, opts...).ToFunc() +} + +// BySeverity orders the results by the severity field. +func BySeverity(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSeverity, opts...).ToFunc() +} + +// ByCode orders the results by the code field. +func ByCode(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCode, opts...).ToFunc() +} + +// ByMessage orders the results by the message field. +func ByMessage(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMessage, opts...).ToFunc() +} + +// ByPath orders the results by the path field. +func ByPath(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPath, opts...).ToFunc() +} + +// ByComponent orders the results by the component field. +func ByComponent(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldComponent, opts...).ToFunc() +} + +// ByBillingInvoiceField orders the results by billing_invoice field. +func ByBillingInvoiceField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBillingInvoiceStep(), sql.OrderByField(field, opts...)) + } +} +func newBillingInvoiceStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BillingInvoiceInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, BillingInvoiceTable, BillingInvoiceColumn), + ) +} diff --git a/ent/db/billinginvoicevalidationissue/where.go b/ent/db/billinginvoicevalidationissue/where.go new file mode 100644 index 0000000000000000000000000000000000000000..b1e7e7d83392f63b503fcd3b1f4975d0635c5233 --- /dev/null +++ b/ent/db/billinginvoicevalidationissue/where.go @@ -0,0 +1,765 @@ +// Code generated by ent, DO NOT EDIT. + +package billinginvoicevalidationissue + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(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.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(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.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(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.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEQ(FieldDeletedAt, v)) +} + +// InvoiceID applies equality check predicate on the "invoice_id" field. It's identical to InvoiceIDEQ. +func InvoiceID(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEQ(FieldInvoiceID, v)) +} + +// Code applies equality check predicate on the "code" field. It's identical to CodeEQ. +func Code(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEQ(FieldCode, v)) +} + +// Message applies equality check predicate on the "message" field. It's identical to MessageEQ. +func Message(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEQ(FieldMessage, v)) +} + +// Path applies equality check predicate on the "path" field. It's identical to PathEQ. +func Path(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEQ(FieldPath, v)) +} + +// Component applies equality check predicate on the "component" field. It's identical to ComponentEQ. +func Component(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEQ(FieldComponent, v)) +} + +// DedupeHash applies equality check predicate on the "dedupe_hash" field. It's identical to DedupeHashEQ. +func DedupeHash(v []byte) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEQ(FieldDedupeHash, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNotNull(FieldDeletedAt)) +} + +// InvoiceIDEQ applies the EQ predicate on the "invoice_id" field. +func InvoiceIDEQ(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEQ(FieldInvoiceID, v)) +} + +// InvoiceIDNEQ applies the NEQ predicate on the "invoice_id" field. +func InvoiceIDNEQ(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNEQ(FieldInvoiceID, v)) +} + +// InvoiceIDIn applies the In predicate on the "invoice_id" field. +func InvoiceIDIn(vs ...string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldIn(FieldInvoiceID, vs...)) +} + +// InvoiceIDNotIn applies the NotIn predicate on the "invoice_id" field. +func InvoiceIDNotIn(vs ...string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNotIn(FieldInvoiceID, vs...)) +} + +// InvoiceIDGT applies the GT predicate on the "invoice_id" field. +func InvoiceIDGT(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGT(FieldInvoiceID, v)) +} + +// InvoiceIDGTE applies the GTE predicate on the "invoice_id" field. +func InvoiceIDGTE(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGTE(FieldInvoiceID, v)) +} + +// InvoiceIDLT applies the LT predicate on the "invoice_id" field. +func InvoiceIDLT(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLT(FieldInvoiceID, v)) +} + +// InvoiceIDLTE applies the LTE predicate on the "invoice_id" field. +func InvoiceIDLTE(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLTE(FieldInvoiceID, v)) +} + +// InvoiceIDContains applies the Contains predicate on the "invoice_id" field. +func InvoiceIDContains(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldContains(FieldInvoiceID, v)) +} + +// InvoiceIDHasPrefix applies the HasPrefix predicate on the "invoice_id" field. +func InvoiceIDHasPrefix(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldHasPrefix(FieldInvoiceID, v)) +} + +// InvoiceIDHasSuffix applies the HasSuffix predicate on the "invoice_id" field. +func InvoiceIDHasSuffix(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldHasSuffix(FieldInvoiceID, v)) +} + +// InvoiceIDEqualFold applies the EqualFold predicate on the "invoice_id" field. +func InvoiceIDEqualFold(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEqualFold(FieldInvoiceID, v)) +} + +// InvoiceIDContainsFold applies the ContainsFold predicate on the "invoice_id" field. +func InvoiceIDContainsFold(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldContainsFold(FieldInvoiceID, v)) +} + +// SeverityEQ applies the EQ predicate on the "severity" field. +func SeverityEQ(v billing.ValidationIssueSeverity) predicate.BillingInvoiceValidationIssue { + vc := v + return predicate.BillingInvoiceValidationIssue(sql.FieldEQ(FieldSeverity, vc)) +} + +// SeverityNEQ applies the NEQ predicate on the "severity" field. +func SeverityNEQ(v billing.ValidationIssueSeverity) predicate.BillingInvoiceValidationIssue { + vc := v + return predicate.BillingInvoiceValidationIssue(sql.FieldNEQ(FieldSeverity, vc)) +} + +// SeverityIn applies the In predicate on the "severity" field. +func SeverityIn(vs ...billing.ValidationIssueSeverity) predicate.BillingInvoiceValidationIssue { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingInvoiceValidationIssue(sql.FieldIn(FieldSeverity, v...)) +} + +// SeverityNotIn applies the NotIn predicate on the "severity" field. +func SeverityNotIn(vs ...billing.ValidationIssueSeverity) predicate.BillingInvoiceValidationIssue { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingInvoiceValidationIssue(sql.FieldNotIn(FieldSeverity, v...)) +} + +// CodeEQ applies the EQ predicate on the "code" field. +func CodeEQ(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEQ(FieldCode, v)) +} + +// CodeNEQ applies the NEQ predicate on the "code" field. +func CodeNEQ(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNEQ(FieldCode, v)) +} + +// CodeIn applies the In predicate on the "code" field. +func CodeIn(vs ...string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldIn(FieldCode, vs...)) +} + +// CodeNotIn applies the NotIn predicate on the "code" field. +func CodeNotIn(vs ...string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNotIn(FieldCode, vs...)) +} + +// CodeGT applies the GT predicate on the "code" field. +func CodeGT(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGT(FieldCode, v)) +} + +// CodeGTE applies the GTE predicate on the "code" field. +func CodeGTE(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGTE(FieldCode, v)) +} + +// CodeLT applies the LT predicate on the "code" field. +func CodeLT(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLT(FieldCode, v)) +} + +// CodeLTE applies the LTE predicate on the "code" field. +func CodeLTE(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLTE(FieldCode, v)) +} + +// CodeContains applies the Contains predicate on the "code" field. +func CodeContains(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldContains(FieldCode, v)) +} + +// CodeHasPrefix applies the HasPrefix predicate on the "code" field. +func CodeHasPrefix(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldHasPrefix(FieldCode, v)) +} + +// CodeHasSuffix applies the HasSuffix predicate on the "code" field. +func CodeHasSuffix(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldHasSuffix(FieldCode, v)) +} + +// CodeIsNil applies the IsNil predicate on the "code" field. +func CodeIsNil() predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldIsNull(FieldCode)) +} + +// CodeNotNil applies the NotNil predicate on the "code" field. +func CodeNotNil() predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNotNull(FieldCode)) +} + +// CodeEqualFold applies the EqualFold predicate on the "code" field. +func CodeEqualFold(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEqualFold(FieldCode, v)) +} + +// CodeContainsFold applies the ContainsFold predicate on the "code" field. +func CodeContainsFold(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldContainsFold(FieldCode, v)) +} + +// MessageEQ applies the EQ predicate on the "message" field. +func MessageEQ(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEQ(FieldMessage, v)) +} + +// MessageNEQ applies the NEQ predicate on the "message" field. +func MessageNEQ(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNEQ(FieldMessage, v)) +} + +// MessageIn applies the In predicate on the "message" field. +func MessageIn(vs ...string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldIn(FieldMessage, vs...)) +} + +// MessageNotIn applies the NotIn predicate on the "message" field. +func MessageNotIn(vs ...string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNotIn(FieldMessage, vs...)) +} + +// MessageGT applies the GT predicate on the "message" field. +func MessageGT(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGT(FieldMessage, v)) +} + +// MessageGTE applies the GTE predicate on the "message" field. +func MessageGTE(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGTE(FieldMessage, v)) +} + +// MessageLT applies the LT predicate on the "message" field. +func MessageLT(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLT(FieldMessage, v)) +} + +// MessageLTE applies the LTE predicate on the "message" field. +func MessageLTE(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLTE(FieldMessage, v)) +} + +// MessageContains applies the Contains predicate on the "message" field. +func MessageContains(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldContains(FieldMessage, v)) +} + +// MessageHasPrefix applies the HasPrefix predicate on the "message" field. +func MessageHasPrefix(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldHasPrefix(FieldMessage, v)) +} + +// MessageHasSuffix applies the HasSuffix predicate on the "message" field. +func MessageHasSuffix(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldHasSuffix(FieldMessage, v)) +} + +// MessageEqualFold applies the EqualFold predicate on the "message" field. +func MessageEqualFold(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEqualFold(FieldMessage, v)) +} + +// MessageContainsFold applies the ContainsFold predicate on the "message" field. +func MessageContainsFold(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldContainsFold(FieldMessage, v)) +} + +// PathEQ applies the EQ predicate on the "path" field. +func PathEQ(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEQ(FieldPath, v)) +} + +// PathNEQ applies the NEQ predicate on the "path" field. +func PathNEQ(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNEQ(FieldPath, v)) +} + +// PathIn applies the In predicate on the "path" field. +func PathIn(vs ...string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldIn(FieldPath, vs...)) +} + +// PathNotIn applies the NotIn predicate on the "path" field. +func PathNotIn(vs ...string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNotIn(FieldPath, vs...)) +} + +// PathGT applies the GT predicate on the "path" field. +func PathGT(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGT(FieldPath, v)) +} + +// PathGTE applies the GTE predicate on the "path" field. +func PathGTE(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGTE(FieldPath, v)) +} + +// PathLT applies the LT predicate on the "path" field. +func PathLT(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLT(FieldPath, v)) +} + +// PathLTE applies the LTE predicate on the "path" field. +func PathLTE(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLTE(FieldPath, v)) +} + +// PathContains applies the Contains predicate on the "path" field. +func PathContains(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldContains(FieldPath, v)) +} + +// PathHasPrefix applies the HasPrefix predicate on the "path" field. +func PathHasPrefix(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldHasPrefix(FieldPath, v)) +} + +// PathHasSuffix applies the HasSuffix predicate on the "path" field. +func PathHasSuffix(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldHasSuffix(FieldPath, v)) +} + +// PathIsNil applies the IsNil predicate on the "path" field. +func PathIsNil() predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldIsNull(FieldPath)) +} + +// PathNotNil applies the NotNil predicate on the "path" field. +func PathNotNil() predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNotNull(FieldPath)) +} + +// PathEqualFold applies the EqualFold predicate on the "path" field. +func PathEqualFold(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEqualFold(FieldPath, v)) +} + +// PathContainsFold applies the ContainsFold predicate on the "path" field. +func PathContainsFold(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldContainsFold(FieldPath, v)) +} + +// ComponentEQ applies the EQ predicate on the "component" field. +func ComponentEQ(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEQ(FieldComponent, v)) +} + +// ComponentNEQ applies the NEQ predicate on the "component" field. +func ComponentNEQ(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNEQ(FieldComponent, v)) +} + +// ComponentIn applies the In predicate on the "component" field. +func ComponentIn(vs ...string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldIn(FieldComponent, vs...)) +} + +// ComponentNotIn applies the NotIn predicate on the "component" field. +func ComponentNotIn(vs ...string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNotIn(FieldComponent, vs...)) +} + +// ComponentGT applies the GT predicate on the "component" field. +func ComponentGT(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGT(FieldComponent, v)) +} + +// ComponentGTE applies the GTE predicate on the "component" field. +func ComponentGTE(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGTE(FieldComponent, v)) +} + +// ComponentLT applies the LT predicate on the "component" field. +func ComponentLT(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLT(FieldComponent, v)) +} + +// ComponentLTE applies the LTE predicate on the "component" field. +func ComponentLTE(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLTE(FieldComponent, v)) +} + +// ComponentContains applies the Contains predicate on the "component" field. +func ComponentContains(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldContains(FieldComponent, v)) +} + +// ComponentHasPrefix applies the HasPrefix predicate on the "component" field. +func ComponentHasPrefix(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldHasPrefix(FieldComponent, v)) +} + +// ComponentHasSuffix applies the HasSuffix predicate on the "component" field. +func ComponentHasSuffix(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldHasSuffix(FieldComponent, v)) +} + +// ComponentEqualFold applies the EqualFold predicate on the "component" field. +func ComponentEqualFold(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEqualFold(FieldComponent, v)) +} + +// ComponentContainsFold applies the ContainsFold predicate on the "component" field. +func ComponentContainsFold(v string) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldContainsFold(FieldComponent, v)) +} + +// DedupeHashEQ applies the EQ predicate on the "dedupe_hash" field. +func DedupeHashEQ(v []byte) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldEQ(FieldDedupeHash, v)) +} + +// DedupeHashNEQ applies the NEQ predicate on the "dedupe_hash" field. +func DedupeHashNEQ(v []byte) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNEQ(FieldDedupeHash, v)) +} + +// DedupeHashIn applies the In predicate on the "dedupe_hash" field. +func DedupeHashIn(vs ...[]byte) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldIn(FieldDedupeHash, vs...)) +} + +// DedupeHashNotIn applies the NotIn predicate on the "dedupe_hash" field. +func DedupeHashNotIn(vs ...[]byte) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldNotIn(FieldDedupeHash, vs...)) +} + +// DedupeHashGT applies the GT predicate on the "dedupe_hash" field. +func DedupeHashGT(v []byte) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGT(FieldDedupeHash, v)) +} + +// DedupeHashGTE applies the GTE predicate on the "dedupe_hash" field. +func DedupeHashGTE(v []byte) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldGTE(FieldDedupeHash, v)) +} + +// DedupeHashLT applies the LT predicate on the "dedupe_hash" field. +func DedupeHashLT(v []byte) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLT(FieldDedupeHash, v)) +} + +// DedupeHashLTE applies the LTE predicate on the "dedupe_hash" field. +func DedupeHashLTE(v []byte) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.FieldLTE(FieldDedupeHash, v)) +} + +// HasBillingInvoice applies the HasEdge predicate on the "billing_invoice" edge. +func HasBillingInvoice() predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, BillingInvoiceTable, BillingInvoiceColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBillingInvoiceWith applies the HasEdge predicate on the "billing_invoice" edge with a given conditions (other predicates). +func HasBillingInvoiceWith(preds ...predicate.BillingInvoice) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(func(s *sql.Selector) { + step := newBillingInvoiceStep() + 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.BillingInvoiceValidationIssue) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.BillingInvoiceValidationIssue) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.BillingInvoiceValidationIssue) predicate.BillingInvoiceValidationIssue { + return predicate.BillingInvoiceValidationIssue(sql.NotPredicates(p)) +} diff --git a/ent/db/billinginvoicevalidationissue_create.go b/ent/db/billinginvoicevalidationissue_create.go new file mode 100644 index 0000000000000000000000000000000000000000..86e880e6bda4bd0b022aa65bbc5191093b4e043e --- /dev/null +++ b/ent/db/billinginvoicevalidationissue_create.go @@ -0,0 +1,1123 @@ +// 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/billing" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicevalidationissue" +) + +// BillingInvoiceValidationIssueCreate is the builder for creating a BillingInvoiceValidationIssue entity. +type BillingInvoiceValidationIssueCreate struct { + config + mutation *BillingInvoiceValidationIssueMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *BillingInvoiceValidationIssueCreate) SetNamespace(v string) *BillingInvoiceValidationIssueCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *BillingInvoiceValidationIssueCreate) SetCreatedAt(v time.Time) *BillingInvoiceValidationIssueCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *BillingInvoiceValidationIssueCreate) SetNillableCreatedAt(v *time.Time) *BillingInvoiceValidationIssueCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *BillingInvoiceValidationIssueCreate) SetUpdatedAt(v time.Time) *BillingInvoiceValidationIssueCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *BillingInvoiceValidationIssueCreate) SetNillableUpdatedAt(v *time.Time) *BillingInvoiceValidationIssueCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *BillingInvoiceValidationIssueCreate) SetDeletedAt(v time.Time) *BillingInvoiceValidationIssueCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *BillingInvoiceValidationIssueCreate) SetNillableDeletedAt(v *time.Time) *BillingInvoiceValidationIssueCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetInvoiceID sets the "invoice_id" field. +func (_c *BillingInvoiceValidationIssueCreate) SetInvoiceID(v string) *BillingInvoiceValidationIssueCreate { + _c.mutation.SetInvoiceID(v) + return _c +} + +// SetSeverity sets the "severity" field. +func (_c *BillingInvoiceValidationIssueCreate) SetSeverity(v billing.ValidationIssueSeverity) *BillingInvoiceValidationIssueCreate { + _c.mutation.SetSeverity(v) + return _c +} + +// SetCode sets the "code" field. +func (_c *BillingInvoiceValidationIssueCreate) SetCode(v string) *BillingInvoiceValidationIssueCreate { + _c.mutation.SetCode(v) + return _c +} + +// SetNillableCode sets the "code" field if the given value is not nil. +func (_c *BillingInvoiceValidationIssueCreate) SetNillableCode(v *string) *BillingInvoiceValidationIssueCreate { + if v != nil { + _c.SetCode(*v) + } + return _c +} + +// SetMessage sets the "message" field. +func (_c *BillingInvoiceValidationIssueCreate) SetMessage(v string) *BillingInvoiceValidationIssueCreate { + _c.mutation.SetMessage(v) + return _c +} + +// SetPath sets the "path" field. +func (_c *BillingInvoiceValidationIssueCreate) SetPath(v string) *BillingInvoiceValidationIssueCreate { + _c.mutation.SetPath(v) + return _c +} + +// SetNillablePath sets the "path" field if the given value is not nil. +func (_c *BillingInvoiceValidationIssueCreate) SetNillablePath(v *string) *BillingInvoiceValidationIssueCreate { + if v != nil { + _c.SetPath(*v) + } + return _c +} + +// SetComponent sets the "component" field. +func (_c *BillingInvoiceValidationIssueCreate) SetComponent(v string) *BillingInvoiceValidationIssueCreate { + _c.mutation.SetComponent(v) + return _c +} + +// SetDedupeHash sets the "dedupe_hash" field. +func (_c *BillingInvoiceValidationIssueCreate) SetDedupeHash(v []byte) *BillingInvoiceValidationIssueCreate { + _c.mutation.SetDedupeHash(v) + return _c +} + +// SetID sets the "id" field. +func (_c *BillingInvoiceValidationIssueCreate) SetID(v string) *BillingInvoiceValidationIssueCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *BillingInvoiceValidationIssueCreate) SetNillableID(v *string) *BillingInvoiceValidationIssueCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetBillingInvoiceID sets the "billing_invoice" edge to the BillingInvoice entity by ID. +func (_c *BillingInvoiceValidationIssueCreate) SetBillingInvoiceID(id string) *BillingInvoiceValidationIssueCreate { + _c.mutation.SetBillingInvoiceID(id) + return _c +} + +// SetBillingInvoice sets the "billing_invoice" edge to the BillingInvoice entity. +func (_c *BillingInvoiceValidationIssueCreate) SetBillingInvoice(v *BillingInvoice) *BillingInvoiceValidationIssueCreate { + return _c.SetBillingInvoiceID(v.ID) +} + +// Mutation returns the BillingInvoiceValidationIssueMutation object of the builder. +func (_c *BillingInvoiceValidationIssueCreate) Mutation() *BillingInvoiceValidationIssueMutation { + return _c.mutation +} + +// Save creates the BillingInvoiceValidationIssue in the database. +func (_c *BillingInvoiceValidationIssueCreate) Save(ctx context.Context) (*BillingInvoiceValidationIssue, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *BillingInvoiceValidationIssueCreate) SaveX(ctx context.Context) *BillingInvoiceValidationIssue { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingInvoiceValidationIssueCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingInvoiceValidationIssueCreate) 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 *BillingInvoiceValidationIssueCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := billinginvoicevalidationissue.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := billinginvoicevalidationissue.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := billinginvoicevalidationissue.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *BillingInvoiceValidationIssueCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "BillingInvoiceValidationIssue.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := billinginvoicevalidationissue.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceValidationIssue.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "BillingInvoiceValidationIssue.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "BillingInvoiceValidationIssue.updated_at"`)} + } + if _, ok := _c.mutation.InvoiceID(); !ok { + return &ValidationError{Name: "invoice_id", err: errors.New(`db: missing required field "BillingInvoiceValidationIssue.invoice_id"`)} + } + if v, ok := _c.mutation.InvoiceID(); ok { + if err := billinginvoicevalidationissue.InvoiceIDValidator(v); err != nil { + return &ValidationError{Name: "invoice_id", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceValidationIssue.invoice_id": %w`, err)} + } + } + if _, ok := _c.mutation.Severity(); !ok { + return &ValidationError{Name: "severity", err: errors.New(`db: missing required field "BillingInvoiceValidationIssue.severity"`)} + } + if v, ok := _c.mutation.Severity(); ok { + if err := billinginvoicevalidationissue.SeverityValidator(v); err != nil { + return &ValidationError{Name: "severity", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceValidationIssue.severity": %w`, err)} + } + } + if _, ok := _c.mutation.Message(); !ok { + return &ValidationError{Name: "message", err: errors.New(`db: missing required field "BillingInvoiceValidationIssue.message"`)} + } + if v, ok := _c.mutation.Message(); ok { + if err := billinginvoicevalidationissue.MessageValidator(v); err != nil { + return &ValidationError{Name: "message", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceValidationIssue.message": %w`, err)} + } + } + if _, ok := _c.mutation.Component(); !ok { + return &ValidationError{Name: "component", err: errors.New(`db: missing required field "BillingInvoiceValidationIssue.component"`)} + } + if _, ok := _c.mutation.DedupeHash(); !ok { + return &ValidationError{Name: "dedupe_hash", err: errors.New(`db: missing required field "BillingInvoiceValidationIssue.dedupe_hash"`)} + } + if v, ok := _c.mutation.DedupeHash(); ok { + if err := billinginvoicevalidationissue.DedupeHashValidator(v); err != nil { + return &ValidationError{Name: "dedupe_hash", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceValidationIssue.dedupe_hash": %w`, err)} + } + } + if len(_c.mutation.BillingInvoiceIDs()) == 0 { + return &ValidationError{Name: "billing_invoice", err: errors.New(`db: missing required edge "BillingInvoiceValidationIssue.billing_invoice"`)} + } + return nil +} + +func (_c *BillingInvoiceValidationIssueCreate) sqlSave(ctx context.Context) (*BillingInvoiceValidationIssue, 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 BillingInvoiceValidationIssue.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *BillingInvoiceValidationIssueCreate) createSpec() (*BillingInvoiceValidationIssue, *sqlgraph.CreateSpec) { + var ( + _node = &BillingInvoiceValidationIssue{config: _c.config} + _spec = sqlgraph.NewCreateSpec(billinginvoicevalidationissue.Table, sqlgraph.NewFieldSpec(billinginvoicevalidationissue.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(billinginvoicevalidationissue.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Severity(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldSeverity, field.TypeEnum, value) + _node.Severity = value + } + if value, ok := _c.mutation.Code(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldCode, field.TypeString, value) + _node.Code = &value + } + if value, ok := _c.mutation.Message(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldMessage, field.TypeString, value) + _node.Message = value + } + if value, ok := _c.mutation.Path(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldPath, field.TypeString, value) + _node.Path = &value + } + if value, ok := _c.mutation.Component(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldComponent, field.TypeString, value) + _node.Component = value + } + if value, ok := _c.mutation.DedupeHash(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldDedupeHash, field.TypeBytes, value) + _node.DedupeHash = value + } + if nodes := _c.mutation.BillingInvoiceIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicevalidationissue.BillingInvoiceTable, + Columns: []string{billinginvoicevalidationissue.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.InvoiceID = 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.BillingInvoiceValidationIssue.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.BillingInvoiceValidationIssueUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *BillingInvoiceValidationIssueCreate) OnConflict(opts ...sql.ConflictOption) *BillingInvoiceValidationIssueUpsertOne { + _c.conflict = opts + return &BillingInvoiceValidationIssueUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingInvoiceValidationIssue.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingInvoiceValidationIssueCreate) OnConflictColumns(columns ...string) *BillingInvoiceValidationIssueUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingInvoiceValidationIssueUpsertOne{ + create: _c, + } +} + +type ( + // BillingInvoiceValidationIssueUpsertOne is the builder for "upsert"-ing + // one BillingInvoiceValidationIssue node. + BillingInvoiceValidationIssueUpsertOne struct { + create *BillingInvoiceValidationIssueCreate + } + + // BillingInvoiceValidationIssueUpsert is the "OnConflict" setter. + BillingInvoiceValidationIssueUpsert struct { + *sql.UpdateSet + } +) + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingInvoiceValidationIssueUpsert) SetUpdatedAt(v time.Time) *BillingInvoiceValidationIssueUpsert { + u.Set(billinginvoicevalidationissue.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsert) UpdateUpdatedAt() *BillingInvoiceValidationIssueUpsert { + u.SetExcluded(billinginvoicevalidationissue.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingInvoiceValidationIssueUpsert) SetDeletedAt(v time.Time) *BillingInvoiceValidationIssueUpsert { + u.Set(billinginvoicevalidationissue.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsert) UpdateDeletedAt() *BillingInvoiceValidationIssueUpsert { + u.SetExcluded(billinginvoicevalidationissue.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingInvoiceValidationIssueUpsert) ClearDeletedAt() *BillingInvoiceValidationIssueUpsert { + u.SetNull(billinginvoicevalidationissue.FieldDeletedAt) + return u +} + +// SetInvoiceID sets the "invoice_id" field. +func (u *BillingInvoiceValidationIssueUpsert) SetInvoiceID(v string) *BillingInvoiceValidationIssueUpsert { + u.Set(billinginvoicevalidationissue.FieldInvoiceID, v) + return u +} + +// UpdateInvoiceID sets the "invoice_id" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsert) UpdateInvoiceID() *BillingInvoiceValidationIssueUpsert { + u.SetExcluded(billinginvoicevalidationissue.FieldInvoiceID) + return u +} + +// SetSeverity sets the "severity" field. +func (u *BillingInvoiceValidationIssueUpsert) SetSeverity(v billing.ValidationIssueSeverity) *BillingInvoiceValidationIssueUpsert { + u.Set(billinginvoicevalidationissue.FieldSeverity, v) + return u +} + +// UpdateSeverity sets the "severity" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsert) UpdateSeverity() *BillingInvoiceValidationIssueUpsert { + u.SetExcluded(billinginvoicevalidationissue.FieldSeverity) + return u +} + +// SetCode sets the "code" field. +func (u *BillingInvoiceValidationIssueUpsert) SetCode(v string) *BillingInvoiceValidationIssueUpsert { + u.Set(billinginvoicevalidationissue.FieldCode, v) + return u +} + +// UpdateCode sets the "code" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsert) UpdateCode() *BillingInvoiceValidationIssueUpsert { + u.SetExcluded(billinginvoicevalidationissue.FieldCode) + return u +} + +// ClearCode clears the value of the "code" field. +func (u *BillingInvoiceValidationIssueUpsert) ClearCode() *BillingInvoiceValidationIssueUpsert { + u.SetNull(billinginvoicevalidationissue.FieldCode) + return u +} + +// SetMessage sets the "message" field. +func (u *BillingInvoiceValidationIssueUpsert) SetMessage(v string) *BillingInvoiceValidationIssueUpsert { + u.Set(billinginvoicevalidationissue.FieldMessage, v) + return u +} + +// UpdateMessage sets the "message" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsert) UpdateMessage() *BillingInvoiceValidationIssueUpsert { + u.SetExcluded(billinginvoicevalidationissue.FieldMessage) + return u +} + +// SetPath sets the "path" field. +func (u *BillingInvoiceValidationIssueUpsert) SetPath(v string) *BillingInvoiceValidationIssueUpsert { + u.Set(billinginvoicevalidationissue.FieldPath, v) + return u +} + +// UpdatePath sets the "path" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsert) UpdatePath() *BillingInvoiceValidationIssueUpsert { + u.SetExcluded(billinginvoicevalidationissue.FieldPath) + return u +} + +// ClearPath clears the value of the "path" field. +func (u *BillingInvoiceValidationIssueUpsert) ClearPath() *BillingInvoiceValidationIssueUpsert { + u.SetNull(billinginvoicevalidationissue.FieldPath) + return u +} + +// SetComponent sets the "component" field. +func (u *BillingInvoiceValidationIssueUpsert) SetComponent(v string) *BillingInvoiceValidationIssueUpsert { + u.Set(billinginvoicevalidationissue.FieldComponent, v) + return u +} + +// UpdateComponent sets the "component" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsert) UpdateComponent() *BillingInvoiceValidationIssueUpsert { + u.SetExcluded(billinginvoicevalidationissue.FieldComponent) + return u +} + +// SetDedupeHash sets the "dedupe_hash" field. +func (u *BillingInvoiceValidationIssueUpsert) SetDedupeHash(v []byte) *BillingInvoiceValidationIssueUpsert { + u.Set(billinginvoicevalidationissue.FieldDedupeHash, v) + return u +} + +// UpdateDedupeHash sets the "dedupe_hash" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsert) UpdateDedupeHash() *BillingInvoiceValidationIssueUpsert { + u.SetExcluded(billinginvoicevalidationissue.FieldDedupeHash) + 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.BillingInvoiceValidationIssue.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(billinginvoicevalidationissue.FieldID) +// }), +// ). +// Exec(ctx) +func (u *BillingInvoiceValidationIssueUpsertOne) UpdateNewValues() *BillingInvoiceValidationIssueUpsertOne { + 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(billinginvoicevalidationissue.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(billinginvoicevalidationissue.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(billinginvoicevalidationissue.FieldCreatedAt) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingInvoiceValidationIssue.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingInvoiceValidationIssueUpsertOne) Ignore() *BillingInvoiceValidationIssueUpsertOne { + 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 *BillingInvoiceValidationIssueUpsertOne) DoNothing() *BillingInvoiceValidationIssueUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingInvoiceValidationIssueCreate.OnConflict +// documentation for more info. +func (u *BillingInvoiceValidationIssueUpsertOne) Update(set func(*BillingInvoiceValidationIssueUpsert)) *BillingInvoiceValidationIssueUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingInvoiceValidationIssueUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingInvoiceValidationIssueUpsertOne) SetUpdatedAt(v time.Time) *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsertOne) UpdateUpdatedAt() *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingInvoiceValidationIssueUpsertOne) SetDeletedAt(v time.Time) *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsertOne) UpdateDeletedAt() *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingInvoiceValidationIssueUpsertOne) ClearDeletedAt() *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.ClearDeletedAt() + }) +} + +// SetInvoiceID sets the "invoice_id" field. +func (u *BillingInvoiceValidationIssueUpsertOne) SetInvoiceID(v string) *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.SetInvoiceID(v) + }) +} + +// UpdateInvoiceID sets the "invoice_id" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsertOne) UpdateInvoiceID() *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.UpdateInvoiceID() + }) +} + +// SetSeverity sets the "severity" field. +func (u *BillingInvoiceValidationIssueUpsertOne) SetSeverity(v billing.ValidationIssueSeverity) *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.SetSeverity(v) + }) +} + +// UpdateSeverity sets the "severity" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsertOne) UpdateSeverity() *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.UpdateSeverity() + }) +} + +// SetCode sets the "code" field. +func (u *BillingInvoiceValidationIssueUpsertOne) SetCode(v string) *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.SetCode(v) + }) +} + +// UpdateCode sets the "code" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsertOne) UpdateCode() *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.UpdateCode() + }) +} + +// ClearCode clears the value of the "code" field. +func (u *BillingInvoiceValidationIssueUpsertOne) ClearCode() *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.ClearCode() + }) +} + +// SetMessage sets the "message" field. +func (u *BillingInvoiceValidationIssueUpsertOne) SetMessage(v string) *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.SetMessage(v) + }) +} + +// UpdateMessage sets the "message" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsertOne) UpdateMessage() *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.UpdateMessage() + }) +} + +// SetPath sets the "path" field. +func (u *BillingInvoiceValidationIssueUpsertOne) SetPath(v string) *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.SetPath(v) + }) +} + +// UpdatePath sets the "path" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsertOne) UpdatePath() *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.UpdatePath() + }) +} + +// ClearPath clears the value of the "path" field. +func (u *BillingInvoiceValidationIssueUpsertOne) ClearPath() *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.ClearPath() + }) +} + +// SetComponent sets the "component" field. +func (u *BillingInvoiceValidationIssueUpsertOne) SetComponent(v string) *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.SetComponent(v) + }) +} + +// UpdateComponent sets the "component" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsertOne) UpdateComponent() *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.UpdateComponent() + }) +} + +// SetDedupeHash sets the "dedupe_hash" field. +func (u *BillingInvoiceValidationIssueUpsertOne) SetDedupeHash(v []byte) *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.SetDedupeHash(v) + }) +} + +// UpdateDedupeHash sets the "dedupe_hash" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsertOne) UpdateDedupeHash() *BillingInvoiceValidationIssueUpsertOne { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.UpdateDedupeHash() + }) +} + +// Exec executes the query. +func (u *BillingInvoiceValidationIssueUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingInvoiceValidationIssueCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingInvoiceValidationIssueUpsertOne) 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 *BillingInvoiceValidationIssueUpsertOne) 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: BillingInvoiceValidationIssueUpsertOne.ID is not supported by MySQL driver. Use BillingInvoiceValidationIssueUpsertOne.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 *BillingInvoiceValidationIssueUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// BillingInvoiceValidationIssueCreateBulk is the builder for creating many BillingInvoiceValidationIssue entities in bulk. +type BillingInvoiceValidationIssueCreateBulk struct { + config + err error + builders []*BillingInvoiceValidationIssueCreate + conflict []sql.ConflictOption +} + +// Save creates the BillingInvoiceValidationIssue entities in the database. +func (_c *BillingInvoiceValidationIssueCreateBulk) Save(ctx context.Context) ([]*BillingInvoiceValidationIssue, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*BillingInvoiceValidationIssue, 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.(*BillingInvoiceValidationIssueMutation) + 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 *BillingInvoiceValidationIssueCreateBulk) SaveX(ctx context.Context) []*BillingInvoiceValidationIssue { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingInvoiceValidationIssueCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingInvoiceValidationIssueCreateBulk) 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.BillingInvoiceValidationIssue.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.BillingInvoiceValidationIssueUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *BillingInvoiceValidationIssueCreateBulk) OnConflict(opts ...sql.ConflictOption) *BillingInvoiceValidationIssueUpsertBulk { + _c.conflict = opts + return &BillingInvoiceValidationIssueUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingInvoiceValidationIssue.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingInvoiceValidationIssueCreateBulk) OnConflictColumns(columns ...string) *BillingInvoiceValidationIssueUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingInvoiceValidationIssueUpsertBulk{ + create: _c, + } +} + +// BillingInvoiceValidationIssueUpsertBulk is the builder for "upsert"-ing +// a bulk of BillingInvoiceValidationIssue nodes. +type BillingInvoiceValidationIssueUpsertBulk struct { + create *BillingInvoiceValidationIssueCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.BillingInvoiceValidationIssue.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(billinginvoicevalidationissue.FieldID) +// }), +// ). +// Exec(ctx) +func (u *BillingInvoiceValidationIssueUpsertBulk) UpdateNewValues() *BillingInvoiceValidationIssueUpsertBulk { + 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(billinginvoicevalidationissue.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(billinginvoicevalidationissue.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(billinginvoicevalidationissue.FieldCreatedAt) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingInvoiceValidationIssue.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingInvoiceValidationIssueUpsertBulk) Ignore() *BillingInvoiceValidationIssueUpsertBulk { + 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 *BillingInvoiceValidationIssueUpsertBulk) DoNothing() *BillingInvoiceValidationIssueUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingInvoiceValidationIssueCreateBulk.OnConflict +// documentation for more info. +func (u *BillingInvoiceValidationIssueUpsertBulk) Update(set func(*BillingInvoiceValidationIssueUpsert)) *BillingInvoiceValidationIssueUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingInvoiceValidationIssueUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingInvoiceValidationIssueUpsertBulk) SetUpdatedAt(v time.Time) *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsertBulk) UpdateUpdatedAt() *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingInvoiceValidationIssueUpsertBulk) SetDeletedAt(v time.Time) *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsertBulk) UpdateDeletedAt() *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingInvoiceValidationIssueUpsertBulk) ClearDeletedAt() *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.ClearDeletedAt() + }) +} + +// SetInvoiceID sets the "invoice_id" field. +func (u *BillingInvoiceValidationIssueUpsertBulk) SetInvoiceID(v string) *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.SetInvoiceID(v) + }) +} + +// UpdateInvoiceID sets the "invoice_id" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsertBulk) UpdateInvoiceID() *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.UpdateInvoiceID() + }) +} + +// SetSeverity sets the "severity" field. +func (u *BillingInvoiceValidationIssueUpsertBulk) SetSeverity(v billing.ValidationIssueSeverity) *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.SetSeverity(v) + }) +} + +// UpdateSeverity sets the "severity" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsertBulk) UpdateSeverity() *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.UpdateSeverity() + }) +} + +// SetCode sets the "code" field. +func (u *BillingInvoiceValidationIssueUpsertBulk) SetCode(v string) *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.SetCode(v) + }) +} + +// UpdateCode sets the "code" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsertBulk) UpdateCode() *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.UpdateCode() + }) +} + +// ClearCode clears the value of the "code" field. +func (u *BillingInvoiceValidationIssueUpsertBulk) ClearCode() *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.ClearCode() + }) +} + +// SetMessage sets the "message" field. +func (u *BillingInvoiceValidationIssueUpsertBulk) SetMessage(v string) *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.SetMessage(v) + }) +} + +// UpdateMessage sets the "message" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsertBulk) UpdateMessage() *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.UpdateMessage() + }) +} + +// SetPath sets the "path" field. +func (u *BillingInvoiceValidationIssueUpsertBulk) SetPath(v string) *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.SetPath(v) + }) +} + +// UpdatePath sets the "path" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsertBulk) UpdatePath() *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.UpdatePath() + }) +} + +// ClearPath clears the value of the "path" field. +func (u *BillingInvoiceValidationIssueUpsertBulk) ClearPath() *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.ClearPath() + }) +} + +// SetComponent sets the "component" field. +func (u *BillingInvoiceValidationIssueUpsertBulk) SetComponent(v string) *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.SetComponent(v) + }) +} + +// UpdateComponent sets the "component" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsertBulk) UpdateComponent() *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.UpdateComponent() + }) +} + +// SetDedupeHash sets the "dedupe_hash" field. +func (u *BillingInvoiceValidationIssueUpsertBulk) SetDedupeHash(v []byte) *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.SetDedupeHash(v) + }) +} + +// UpdateDedupeHash sets the "dedupe_hash" field to the value that was provided on create. +func (u *BillingInvoiceValidationIssueUpsertBulk) UpdateDedupeHash() *BillingInvoiceValidationIssueUpsertBulk { + return u.Update(func(s *BillingInvoiceValidationIssueUpsert) { + s.UpdateDedupeHash() + }) +} + +// Exec executes the query. +func (u *BillingInvoiceValidationIssueUpsertBulk) 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 BillingInvoiceValidationIssueCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingInvoiceValidationIssueCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingInvoiceValidationIssueUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billinginvoicevalidationissue_delete.go b/ent/db/billinginvoicevalidationissue_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..cac87a24efc3fbefb0ab57962a6652bad7e32eed --- /dev/null +++ b/ent/db/billinginvoicevalidationissue_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/billinginvoicevalidationissue" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingInvoiceValidationIssueDelete is the builder for deleting a BillingInvoiceValidationIssue entity. +type BillingInvoiceValidationIssueDelete struct { + config + hooks []Hook + mutation *BillingInvoiceValidationIssueMutation +} + +// Where appends a list predicates to the BillingInvoiceValidationIssueDelete builder. +func (_d *BillingInvoiceValidationIssueDelete) Where(ps ...predicate.BillingInvoiceValidationIssue) *BillingInvoiceValidationIssueDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *BillingInvoiceValidationIssueDelete) 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 *BillingInvoiceValidationIssueDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *BillingInvoiceValidationIssueDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(billinginvoicevalidationissue.Table, sqlgraph.NewFieldSpec(billinginvoicevalidationissue.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 +} + +// BillingInvoiceValidationIssueDeleteOne is the builder for deleting a single BillingInvoiceValidationIssue entity. +type BillingInvoiceValidationIssueDeleteOne struct { + _d *BillingInvoiceValidationIssueDelete +} + +// Where appends a list predicates to the BillingInvoiceValidationIssueDelete builder. +func (_d *BillingInvoiceValidationIssueDeleteOne) Where(ps ...predicate.BillingInvoiceValidationIssue) *BillingInvoiceValidationIssueDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *BillingInvoiceValidationIssueDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{billinginvoicevalidationissue.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *BillingInvoiceValidationIssueDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billinginvoicevalidationissue_query.go b/ent/db/billinginvoicevalidationissue_query.go new file mode 100644 index 0000000000000000000000000000000000000000..ee66da2566598c4a5da8df6fa4c098994a9da8b5 --- /dev/null +++ b/ent/db/billinginvoicevalidationissue_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/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicevalidationissue" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingInvoiceValidationIssueQuery is the builder for querying BillingInvoiceValidationIssue entities. +type BillingInvoiceValidationIssueQuery struct { + config + ctx *QueryContext + order []billinginvoicevalidationissue.OrderOption + inters []Interceptor + predicates []predicate.BillingInvoiceValidationIssue + withBillingInvoice *BillingInvoiceQuery + 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 BillingInvoiceValidationIssueQuery builder. +func (_q *BillingInvoiceValidationIssueQuery) Where(ps ...predicate.BillingInvoiceValidationIssue) *BillingInvoiceValidationIssueQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *BillingInvoiceValidationIssueQuery) Limit(limit int) *BillingInvoiceValidationIssueQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *BillingInvoiceValidationIssueQuery) Offset(offset int) *BillingInvoiceValidationIssueQuery { + _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 *BillingInvoiceValidationIssueQuery) Unique(unique bool) *BillingInvoiceValidationIssueQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *BillingInvoiceValidationIssueQuery) Order(o ...billinginvoicevalidationissue.OrderOption) *BillingInvoiceValidationIssueQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryBillingInvoice chains the current query on the "billing_invoice" edge. +func (_q *BillingInvoiceValidationIssueQuery) QueryBillingInvoice() *BillingInvoiceQuery { + query := (&BillingInvoiceClient{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(billinginvoicevalidationissue.Table, billinginvoicevalidationissue.FieldID, selector), + sqlgraph.To(billinginvoice.Table, billinginvoice.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoicevalidationissue.BillingInvoiceTable, billinginvoicevalidationissue.BillingInvoiceColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first BillingInvoiceValidationIssue entity from the query. +// Returns a *NotFoundError when no BillingInvoiceValidationIssue was found. +func (_q *BillingInvoiceValidationIssueQuery) First(ctx context.Context) (*BillingInvoiceValidationIssue, 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{billinginvoicevalidationissue.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *BillingInvoiceValidationIssueQuery) FirstX(ctx context.Context) *BillingInvoiceValidationIssue { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first BillingInvoiceValidationIssue ID from the query. +// Returns a *NotFoundError when no BillingInvoiceValidationIssue ID was found. +func (_q *BillingInvoiceValidationIssueQuery) 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{billinginvoicevalidationissue.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *BillingInvoiceValidationIssueQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single BillingInvoiceValidationIssue entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one BillingInvoiceValidationIssue entity is found. +// Returns a *NotFoundError when no BillingInvoiceValidationIssue entities are found. +func (_q *BillingInvoiceValidationIssueQuery) Only(ctx context.Context) (*BillingInvoiceValidationIssue, 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{billinginvoicevalidationissue.Label} + default: + return nil, &NotSingularError{billinginvoicevalidationissue.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *BillingInvoiceValidationIssueQuery) OnlyX(ctx context.Context) *BillingInvoiceValidationIssue { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only BillingInvoiceValidationIssue ID in the query. +// Returns a *NotSingularError when more than one BillingInvoiceValidationIssue ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *BillingInvoiceValidationIssueQuery) 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{billinginvoicevalidationissue.Label} + default: + err = &NotSingularError{billinginvoicevalidationissue.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *BillingInvoiceValidationIssueQuery) 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 BillingInvoiceValidationIssues. +func (_q *BillingInvoiceValidationIssueQuery) All(ctx context.Context) ([]*BillingInvoiceValidationIssue, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*BillingInvoiceValidationIssue, *BillingInvoiceValidationIssueQuery]() + return withInterceptors[[]*BillingInvoiceValidationIssue](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *BillingInvoiceValidationIssueQuery) AllX(ctx context.Context) []*BillingInvoiceValidationIssue { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of BillingInvoiceValidationIssue IDs. +func (_q *BillingInvoiceValidationIssueQuery) 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(billinginvoicevalidationissue.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *BillingInvoiceValidationIssueQuery) 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 *BillingInvoiceValidationIssueQuery) 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[*BillingInvoiceValidationIssueQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *BillingInvoiceValidationIssueQuery) 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 *BillingInvoiceValidationIssueQuery) 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 *BillingInvoiceValidationIssueQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the BillingInvoiceValidationIssueQuery 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 *BillingInvoiceValidationIssueQuery) Clone() *BillingInvoiceValidationIssueQuery { + if _q == nil { + return nil + } + return &BillingInvoiceValidationIssueQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]billinginvoicevalidationissue.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.BillingInvoiceValidationIssue{}, _q.predicates...), + withBillingInvoice: _q.withBillingInvoice.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithBillingInvoice tells the query-builder to eager-load the nodes that are connected to +// the "billing_invoice" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *BillingInvoiceValidationIssueQuery) WithBillingInvoice(opts ...func(*BillingInvoiceQuery)) *BillingInvoiceValidationIssueQuery { + query := (&BillingInvoiceClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingInvoice = 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.BillingInvoiceValidationIssue.Query(). +// GroupBy(billinginvoicevalidationissue.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *BillingInvoiceValidationIssueQuery) GroupBy(field string, fields ...string) *BillingInvoiceValidationIssueGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &BillingInvoiceValidationIssueGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = billinginvoicevalidationissue.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.BillingInvoiceValidationIssue.Query(). +// Select(billinginvoicevalidationissue.FieldNamespace). +// Scan(ctx, &v) +func (_q *BillingInvoiceValidationIssueQuery) Select(fields ...string) *BillingInvoiceValidationIssueSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &BillingInvoiceValidationIssueSelect{BillingInvoiceValidationIssueQuery: _q} + sbuild.label = billinginvoicevalidationissue.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a BillingInvoiceValidationIssueSelect configured with the given aggregations. +func (_q *BillingInvoiceValidationIssueQuery) Aggregate(fns ...AggregateFunc) *BillingInvoiceValidationIssueSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *BillingInvoiceValidationIssueQuery) 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 !billinginvoicevalidationissue.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 *BillingInvoiceValidationIssueQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BillingInvoiceValidationIssue, error) { + var ( + nodes = []*BillingInvoiceValidationIssue{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withBillingInvoice != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*BillingInvoiceValidationIssue).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &BillingInvoiceValidationIssue{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.withBillingInvoice; query != nil { + if err := _q.loadBillingInvoice(ctx, query, nodes, nil, + func(n *BillingInvoiceValidationIssue, e *BillingInvoice) { n.Edges.BillingInvoice = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *BillingInvoiceValidationIssueQuery) loadBillingInvoice(ctx context.Context, query *BillingInvoiceQuery, nodes []*BillingInvoiceValidationIssue, init func(*BillingInvoiceValidationIssue), assign func(*BillingInvoiceValidationIssue, *BillingInvoice)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*BillingInvoiceValidationIssue) + for i := range nodes { + fk := nodes[i].InvoiceID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(billinginvoice.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 "invoice_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *BillingInvoiceValidationIssueQuery) 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 *BillingInvoiceValidationIssueQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(billinginvoicevalidationissue.Table, billinginvoicevalidationissue.Columns, sqlgraph.NewFieldSpec(billinginvoicevalidationissue.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, billinginvoicevalidationissue.FieldID) + for i := range fields { + if fields[i] != billinginvoicevalidationissue.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withBillingInvoice != nil { + _spec.Node.AddColumnOnce(billinginvoicevalidationissue.FieldInvoiceID) + } + } + 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 *BillingInvoiceValidationIssueQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(billinginvoicevalidationissue.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = billinginvoicevalidationissue.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 *BillingInvoiceValidationIssueQuery) ForUpdate(opts ...sql.LockOption) *BillingInvoiceValidationIssueQuery { + 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 *BillingInvoiceValidationIssueQuery) ForShare(opts ...sql.LockOption) *BillingInvoiceValidationIssueQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// BillingInvoiceValidationIssueGroupBy is the group-by builder for BillingInvoiceValidationIssue entities. +type BillingInvoiceValidationIssueGroupBy struct { + selector + build *BillingInvoiceValidationIssueQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *BillingInvoiceValidationIssueGroupBy) Aggregate(fns ...AggregateFunc) *BillingInvoiceValidationIssueGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *BillingInvoiceValidationIssueGroupBy) 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[*BillingInvoiceValidationIssueQuery, *BillingInvoiceValidationIssueGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *BillingInvoiceValidationIssueGroupBy) sqlScan(ctx context.Context, root *BillingInvoiceValidationIssueQuery, 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) +} + +// BillingInvoiceValidationIssueSelect is the builder for selecting fields of BillingInvoiceValidationIssue entities. +type BillingInvoiceValidationIssueSelect struct { + *BillingInvoiceValidationIssueQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *BillingInvoiceValidationIssueSelect) Aggregate(fns ...AggregateFunc) *BillingInvoiceValidationIssueSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *BillingInvoiceValidationIssueSelect) 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[*BillingInvoiceValidationIssueQuery, *BillingInvoiceValidationIssueSelect](ctx, _s.BillingInvoiceValidationIssueQuery, _s, _s.inters, v) +} + +func (_s *BillingInvoiceValidationIssueSelect) sqlScan(ctx context.Context, root *BillingInvoiceValidationIssueQuery, 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/ent/db/billinginvoicevalidationissue_update.go b/ent/db/billinginvoicevalidationissue_update.go new file mode 100644 index 0000000000000000000000000000000000000000..0f8a83b43486c663ddaf93128c92931cbc194861 --- /dev/null +++ b/ent/db/billinginvoicevalidationissue_update.go @@ -0,0 +1,672 @@ +// 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/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicevalidationissue" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingInvoiceValidationIssueUpdate is the builder for updating BillingInvoiceValidationIssue entities. +type BillingInvoiceValidationIssueUpdate struct { + config + hooks []Hook + mutation *BillingInvoiceValidationIssueMutation +} + +// Where appends a list predicates to the BillingInvoiceValidationIssueUpdate builder. +func (_u *BillingInvoiceValidationIssueUpdate) Where(ps ...predicate.BillingInvoiceValidationIssue) *BillingInvoiceValidationIssueUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *BillingInvoiceValidationIssueUpdate) SetUpdatedAt(v time.Time) *BillingInvoiceValidationIssueUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *BillingInvoiceValidationIssueUpdate) SetDeletedAt(v time.Time) *BillingInvoiceValidationIssueUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *BillingInvoiceValidationIssueUpdate) SetNillableDeletedAt(v *time.Time) *BillingInvoiceValidationIssueUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *BillingInvoiceValidationIssueUpdate) ClearDeletedAt() *BillingInvoiceValidationIssueUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetInvoiceID sets the "invoice_id" field. +func (_u *BillingInvoiceValidationIssueUpdate) SetInvoiceID(v string) *BillingInvoiceValidationIssueUpdate { + _u.mutation.SetInvoiceID(v) + return _u +} + +// SetNillableInvoiceID sets the "invoice_id" field if the given value is not nil. +func (_u *BillingInvoiceValidationIssueUpdate) SetNillableInvoiceID(v *string) *BillingInvoiceValidationIssueUpdate { + if v != nil { + _u.SetInvoiceID(*v) + } + return _u +} + +// SetSeverity sets the "severity" field. +func (_u *BillingInvoiceValidationIssueUpdate) SetSeverity(v billing.ValidationIssueSeverity) *BillingInvoiceValidationIssueUpdate { + _u.mutation.SetSeverity(v) + return _u +} + +// SetNillableSeverity sets the "severity" field if the given value is not nil. +func (_u *BillingInvoiceValidationIssueUpdate) SetNillableSeverity(v *billing.ValidationIssueSeverity) *BillingInvoiceValidationIssueUpdate { + if v != nil { + _u.SetSeverity(*v) + } + return _u +} + +// SetCode sets the "code" field. +func (_u *BillingInvoiceValidationIssueUpdate) SetCode(v string) *BillingInvoiceValidationIssueUpdate { + _u.mutation.SetCode(v) + return _u +} + +// SetNillableCode sets the "code" field if the given value is not nil. +func (_u *BillingInvoiceValidationIssueUpdate) SetNillableCode(v *string) *BillingInvoiceValidationIssueUpdate { + if v != nil { + _u.SetCode(*v) + } + return _u +} + +// ClearCode clears the value of the "code" field. +func (_u *BillingInvoiceValidationIssueUpdate) ClearCode() *BillingInvoiceValidationIssueUpdate { + _u.mutation.ClearCode() + return _u +} + +// SetMessage sets the "message" field. +func (_u *BillingInvoiceValidationIssueUpdate) SetMessage(v string) *BillingInvoiceValidationIssueUpdate { + _u.mutation.SetMessage(v) + return _u +} + +// SetNillableMessage sets the "message" field if the given value is not nil. +func (_u *BillingInvoiceValidationIssueUpdate) SetNillableMessage(v *string) *BillingInvoiceValidationIssueUpdate { + if v != nil { + _u.SetMessage(*v) + } + return _u +} + +// SetPath sets the "path" field. +func (_u *BillingInvoiceValidationIssueUpdate) SetPath(v string) *BillingInvoiceValidationIssueUpdate { + _u.mutation.SetPath(v) + return _u +} + +// SetNillablePath sets the "path" field if the given value is not nil. +func (_u *BillingInvoiceValidationIssueUpdate) SetNillablePath(v *string) *BillingInvoiceValidationIssueUpdate { + if v != nil { + _u.SetPath(*v) + } + return _u +} + +// ClearPath clears the value of the "path" field. +func (_u *BillingInvoiceValidationIssueUpdate) ClearPath() *BillingInvoiceValidationIssueUpdate { + _u.mutation.ClearPath() + return _u +} + +// SetComponent sets the "component" field. +func (_u *BillingInvoiceValidationIssueUpdate) SetComponent(v string) *BillingInvoiceValidationIssueUpdate { + _u.mutation.SetComponent(v) + return _u +} + +// SetNillableComponent sets the "component" field if the given value is not nil. +func (_u *BillingInvoiceValidationIssueUpdate) SetNillableComponent(v *string) *BillingInvoiceValidationIssueUpdate { + if v != nil { + _u.SetComponent(*v) + } + return _u +} + +// SetDedupeHash sets the "dedupe_hash" field. +func (_u *BillingInvoiceValidationIssueUpdate) SetDedupeHash(v []byte) *BillingInvoiceValidationIssueUpdate { + _u.mutation.SetDedupeHash(v) + return _u +} + +// SetBillingInvoiceID sets the "billing_invoice" edge to the BillingInvoice entity by ID. +func (_u *BillingInvoiceValidationIssueUpdate) SetBillingInvoiceID(id string) *BillingInvoiceValidationIssueUpdate { + _u.mutation.SetBillingInvoiceID(id) + return _u +} + +// SetBillingInvoice sets the "billing_invoice" edge to the BillingInvoice entity. +func (_u *BillingInvoiceValidationIssueUpdate) SetBillingInvoice(v *BillingInvoice) *BillingInvoiceValidationIssueUpdate { + return _u.SetBillingInvoiceID(v.ID) +} + +// Mutation returns the BillingInvoiceValidationIssueMutation object of the builder. +func (_u *BillingInvoiceValidationIssueUpdate) Mutation() *BillingInvoiceValidationIssueMutation { + return _u.mutation +} + +// ClearBillingInvoice clears the "billing_invoice" edge to the BillingInvoice entity. +func (_u *BillingInvoiceValidationIssueUpdate) ClearBillingInvoice() *BillingInvoiceValidationIssueUpdate { + _u.mutation.ClearBillingInvoice() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *BillingInvoiceValidationIssueUpdate) 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 *BillingInvoiceValidationIssueUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *BillingInvoiceValidationIssueUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingInvoiceValidationIssueUpdate) 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 *BillingInvoiceValidationIssueUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := billinginvoicevalidationissue.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *BillingInvoiceValidationIssueUpdate) check() error { + if v, ok := _u.mutation.InvoiceID(); ok { + if err := billinginvoicevalidationissue.InvoiceIDValidator(v); err != nil { + return &ValidationError{Name: "invoice_id", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceValidationIssue.invoice_id": %w`, err)} + } + } + if v, ok := _u.mutation.Severity(); ok { + if err := billinginvoicevalidationissue.SeverityValidator(v); err != nil { + return &ValidationError{Name: "severity", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceValidationIssue.severity": %w`, err)} + } + } + if v, ok := _u.mutation.Message(); ok { + if err := billinginvoicevalidationissue.MessageValidator(v); err != nil { + return &ValidationError{Name: "message", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceValidationIssue.message": %w`, err)} + } + } + if v, ok := _u.mutation.DedupeHash(); ok { + if err := billinginvoicevalidationissue.DedupeHashValidator(v); err != nil { + return &ValidationError{Name: "dedupe_hash", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceValidationIssue.dedupe_hash": %w`, err)} + } + } + if _u.mutation.BillingInvoiceCleared() && len(_u.mutation.BillingInvoiceIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "BillingInvoiceValidationIssue.billing_invoice"`) + } + return nil +} + +func (_u *BillingInvoiceValidationIssueUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(billinginvoicevalidationissue.Table, billinginvoicevalidationissue.Columns, sqlgraph.NewFieldSpec(billinginvoicevalidationissue.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(billinginvoicevalidationissue.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(billinginvoicevalidationissue.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Severity(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldSeverity, field.TypeEnum, value) + } + if value, ok := _u.mutation.Code(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldCode, field.TypeString, value) + } + if _u.mutation.CodeCleared() { + _spec.ClearField(billinginvoicevalidationissue.FieldCode, field.TypeString) + } + if value, ok := _u.mutation.Message(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldMessage, field.TypeString, value) + } + if value, ok := _u.mutation.Path(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldPath, field.TypeString, value) + } + if _u.mutation.PathCleared() { + _spec.ClearField(billinginvoicevalidationissue.FieldPath, field.TypeString) + } + if value, ok := _u.mutation.Component(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldComponent, field.TypeString, value) + } + if value, ok := _u.mutation.DedupeHash(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldDedupeHash, field.TypeBytes, value) + } + if _u.mutation.BillingInvoiceCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicevalidationissue.BillingInvoiceTable, + Columns: []string{billinginvoicevalidationissue.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingInvoiceIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicevalidationissue.BillingInvoiceTable, + Columns: []string{billinginvoicevalidationissue.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.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{billinginvoicevalidationissue.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// BillingInvoiceValidationIssueUpdateOne is the builder for updating a single BillingInvoiceValidationIssue entity. +type BillingInvoiceValidationIssueUpdateOne struct { + config + fields []string + hooks []Hook + mutation *BillingInvoiceValidationIssueMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *BillingInvoiceValidationIssueUpdateOne) SetUpdatedAt(v time.Time) *BillingInvoiceValidationIssueUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *BillingInvoiceValidationIssueUpdateOne) SetDeletedAt(v time.Time) *BillingInvoiceValidationIssueUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *BillingInvoiceValidationIssueUpdateOne) SetNillableDeletedAt(v *time.Time) *BillingInvoiceValidationIssueUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *BillingInvoiceValidationIssueUpdateOne) ClearDeletedAt() *BillingInvoiceValidationIssueUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetInvoiceID sets the "invoice_id" field. +func (_u *BillingInvoiceValidationIssueUpdateOne) SetInvoiceID(v string) *BillingInvoiceValidationIssueUpdateOne { + _u.mutation.SetInvoiceID(v) + return _u +} + +// SetNillableInvoiceID sets the "invoice_id" field if the given value is not nil. +func (_u *BillingInvoiceValidationIssueUpdateOne) SetNillableInvoiceID(v *string) *BillingInvoiceValidationIssueUpdateOne { + if v != nil { + _u.SetInvoiceID(*v) + } + return _u +} + +// SetSeverity sets the "severity" field. +func (_u *BillingInvoiceValidationIssueUpdateOne) SetSeverity(v billing.ValidationIssueSeverity) *BillingInvoiceValidationIssueUpdateOne { + _u.mutation.SetSeverity(v) + return _u +} + +// SetNillableSeverity sets the "severity" field if the given value is not nil. +func (_u *BillingInvoiceValidationIssueUpdateOne) SetNillableSeverity(v *billing.ValidationIssueSeverity) *BillingInvoiceValidationIssueUpdateOne { + if v != nil { + _u.SetSeverity(*v) + } + return _u +} + +// SetCode sets the "code" field. +func (_u *BillingInvoiceValidationIssueUpdateOne) SetCode(v string) *BillingInvoiceValidationIssueUpdateOne { + _u.mutation.SetCode(v) + return _u +} + +// SetNillableCode sets the "code" field if the given value is not nil. +func (_u *BillingInvoiceValidationIssueUpdateOne) SetNillableCode(v *string) *BillingInvoiceValidationIssueUpdateOne { + if v != nil { + _u.SetCode(*v) + } + return _u +} + +// ClearCode clears the value of the "code" field. +func (_u *BillingInvoiceValidationIssueUpdateOne) ClearCode() *BillingInvoiceValidationIssueUpdateOne { + _u.mutation.ClearCode() + return _u +} + +// SetMessage sets the "message" field. +func (_u *BillingInvoiceValidationIssueUpdateOne) SetMessage(v string) *BillingInvoiceValidationIssueUpdateOne { + _u.mutation.SetMessage(v) + return _u +} + +// SetNillableMessage sets the "message" field if the given value is not nil. +func (_u *BillingInvoiceValidationIssueUpdateOne) SetNillableMessage(v *string) *BillingInvoiceValidationIssueUpdateOne { + if v != nil { + _u.SetMessage(*v) + } + return _u +} + +// SetPath sets the "path" field. +func (_u *BillingInvoiceValidationIssueUpdateOne) SetPath(v string) *BillingInvoiceValidationIssueUpdateOne { + _u.mutation.SetPath(v) + return _u +} + +// SetNillablePath sets the "path" field if the given value is not nil. +func (_u *BillingInvoiceValidationIssueUpdateOne) SetNillablePath(v *string) *BillingInvoiceValidationIssueUpdateOne { + if v != nil { + _u.SetPath(*v) + } + return _u +} + +// ClearPath clears the value of the "path" field. +func (_u *BillingInvoiceValidationIssueUpdateOne) ClearPath() *BillingInvoiceValidationIssueUpdateOne { + _u.mutation.ClearPath() + return _u +} + +// SetComponent sets the "component" field. +func (_u *BillingInvoiceValidationIssueUpdateOne) SetComponent(v string) *BillingInvoiceValidationIssueUpdateOne { + _u.mutation.SetComponent(v) + return _u +} + +// SetNillableComponent sets the "component" field if the given value is not nil. +func (_u *BillingInvoiceValidationIssueUpdateOne) SetNillableComponent(v *string) *BillingInvoiceValidationIssueUpdateOne { + if v != nil { + _u.SetComponent(*v) + } + return _u +} + +// SetDedupeHash sets the "dedupe_hash" field. +func (_u *BillingInvoiceValidationIssueUpdateOne) SetDedupeHash(v []byte) *BillingInvoiceValidationIssueUpdateOne { + _u.mutation.SetDedupeHash(v) + return _u +} + +// SetBillingInvoiceID sets the "billing_invoice" edge to the BillingInvoice entity by ID. +func (_u *BillingInvoiceValidationIssueUpdateOne) SetBillingInvoiceID(id string) *BillingInvoiceValidationIssueUpdateOne { + _u.mutation.SetBillingInvoiceID(id) + return _u +} + +// SetBillingInvoice sets the "billing_invoice" edge to the BillingInvoice entity. +func (_u *BillingInvoiceValidationIssueUpdateOne) SetBillingInvoice(v *BillingInvoice) *BillingInvoiceValidationIssueUpdateOne { + return _u.SetBillingInvoiceID(v.ID) +} + +// Mutation returns the BillingInvoiceValidationIssueMutation object of the builder. +func (_u *BillingInvoiceValidationIssueUpdateOne) Mutation() *BillingInvoiceValidationIssueMutation { + return _u.mutation +} + +// ClearBillingInvoice clears the "billing_invoice" edge to the BillingInvoice entity. +func (_u *BillingInvoiceValidationIssueUpdateOne) ClearBillingInvoice() *BillingInvoiceValidationIssueUpdateOne { + _u.mutation.ClearBillingInvoice() + return _u +} + +// Where appends a list predicates to the BillingInvoiceValidationIssueUpdate builder. +func (_u *BillingInvoiceValidationIssueUpdateOne) Where(ps ...predicate.BillingInvoiceValidationIssue) *BillingInvoiceValidationIssueUpdateOne { + _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 *BillingInvoiceValidationIssueUpdateOne) Select(field string, fields ...string) *BillingInvoiceValidationIssueUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated BillingInvoiceValidationIssue entity. +func (_u *BillingInvoiceValidationIssueUpdateOne) Save(ctx context.Context) (*BillingInvoiceValidationIssue, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *BillingInvoiceValidationIssueUpdateOne) SaveX(ctx context.Context) *BillingInvoiceValidationIssue { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *BillingInvoiceValidationIssueUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingInvoiceValidationIssueUpdateOne) 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 *BillingInvoiceValidationIssueUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := billinginvoicevalidationissue.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *BillingInvoiceValidationIssueUpdateOne) check() error { + if v, ok := _u.mutation.InvoiceID(); ok { + if err := billinginvoicevalidationissue.InvoiceIDValidator(v); err != nil { + return &ValidationError{Name: "invoice_id", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceValidationIssue.invoice_id": %w`, err)} + } + } + if v, ok := _u.mutation.Severity(); ok { + if err := billinginvoicevalidationissue.SeverityValidator(v); err != nil { + return &ValidationError{Name: "severity", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceValidationIssue.severity": %w`, err)} + } + } + if v, ok := _u.mutation.Message(); ok { + if err := billinginvoicevalidationissue.MessageValidator(v); err != nil { + return &ValidationError{Name: "message", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceValidationIssue.message": %w`, err)} + } + } + if v, ok := _u.mutation.DedupeHash(); ok { + if err := billinginvoicevalidationissue.DedupeHashValidator(v); err != nil { + return &ValidationError{Name: "dedupe_hash", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceValidationIssue.dedupe_hash": %w`, err)} + } + } + if _u.mutation.BillingInvoiceCleared() && len(_u.mutation.BillingInvoiceIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "BillingInvoiceValidationIssue.billing_invoice"`) + } + return nil +} + +func (_u *BillingInvoiceValidationIssueUpdateOne) sqlSave(ctx context.Context) (_node *BillingInvoiceValidationIssue, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(billinginvoicevalidationissue.Table, billinginvoicevalidationissue.Columns, sqlgraph.NewFieldSpec(billinginvoicevalidationissue.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "BillingInvoiceValidationIssue.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, billinginvoicevalidationissue.FieldID) + for _, f := range fields { + if !billinginvoicevalidationissue.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != billinginvoicevalidationissue.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(billinginvoicevalidationissue.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(billinginvoicevalidationissue.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Severity(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldSeverity, field.TypeEnum, value) + } + if value, ok := _u.mutation.Code(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldCode, field.TypeString, value) + } + if _u.mutation.CodeCleared() { + _spec.ClearField(billinginvoicevalidationissue.FieldCode, field.TypeString) + } + if value, ok := _u.mutation.Message(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldMessage, field.TypeString, value) + } + if value, ok := _u.mutation.Path(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldPath, field.TypeString, value) + } + if _u.mutation.PathCleared() { + _spec.ClearField(billinginvoicevalidationissue.FieldPath, field.TypeString) + } + if value, ok := _u.mutation.Component(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldComponent, field.TypeString, value) + } + if value, ok := _u.mutation.DedupeHash(); ok { + _spec.SetField(billinginvoicevalidationissue.FieldDedupeHash, field.TypeBytes, value) + } + if _u.mutation.BillingInvoiceCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicevalidationissue.BillingInvoiceTable, + Columns: []string{billinginvoicevalidationissue.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingInvoiceIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billinginvoicevalidationissue.BillingInvoiceTable, + Columns: []string{billinginvoicevalidationissue.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &BillingInvoiceValidationIssue{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{billinginvoicevalidationissue.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/ent/db/billinginvoicewriteschemalevel.go b/ent/db/billinginvoicewriteschemalevel.go new file mode 100644 index 0000000000000000000000000000000000000000..29d407157e9951bd1d21afe00128e3edd27c4ac6 --- /dev/null +++ b/ent/db/billinginvoicewriteschemalevel.go @@ -0,0 +1,103 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicewriteschemalevel" +) + +// BillingInvoiceWriteSchemaLevel is the model entity for the BillingInvoiceWriteSchemaLevel schema. +type BillingInvoiceWriteSchemaLevel struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // SchemaLevel holds the value of the "schema_level" field. + SchemaLevel int `json:"schema_level,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*BillingInvoiceWriteSchemaLevel) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case billinginvoicewriteschemalevel.FieldSchemaLevel: + values[i] = new(sql.NullInt64) + case billinginvoicewriteschemalevel.FieldID: + values[i] = new(sql.NullString) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the BillingInvoiceWriteSchemaLevel fields. +func (_m *BillingInvoiceWriteSchemaLevel) 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 billinginvoicewriteschemalevel.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 billinginvoicewriteschemalevel.FieldSchemaLevel: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field schema_level", values[i]) + } else if value.Valid { + _m.SchemaLevel = int(value.Int64) + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the BillingInvoiceWriteSchemaLevel. +// This includes values selected through modifiers, order, etc. +func (_m *BillingInvoiceWriteSchemaLevel) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this BillingInvoiceWriteSchemaLevel. +// Note that you need to call BillingInvoiceWriteSchemaLevel.Unwrap() before calling this method if this BillingInvoiceWriteSchemaLevel +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *BillingInvoiceWriteSchemaLevel) Update() *BillingInvoiceWriteSchemaLevelUpdateOne { + return NewBillingInvoiceWriteSchemaLevelClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the BillingInvoiceWriteSchemaLevel 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 *BillingInvoiceWriteSchemaLevel) Unwrap() *BillingInvoiceWriteSchemaLevel { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: BillingInvoiceWriteSchemaLevel is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *BillingInvoiceWriteSchemaLevel) String() string { + var builder strings.Builder + builder.WriteString("BillingInvoiceWriteSchemaLevel(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("schema_level=") + builder.WriteString(fmt.Sprintf("%v", _m.SchemaLevel)) + builder.WriteByte(')') + return builder.String() +} + +// BillingInvoiceWriteSchemaLevels is a parsable slice of BillingInvoiceWriteSchemaLevel. +type BillingInvoiceWriteSchemaLevels []*BillingInvoiceWriteSchemaLevel diff --git a/ent/db/billinginvoicewriteschemalevel/billinginvoicewriteschemalevel.go b/ent/db/billinginvoicewriteschemalevel/billinginvoicewriteschemalevel.go new file mode 100644 index 0000000000000000000000000000000000000000..b9ed3ace3970ad33d8436f8faa1dede6f690fe0e --- /dev/null +++ b/ent/db/billinginvoicewriteschemalevel/billinginvoicewriteschemalevel.go @@ -0,0 +1,52 @@ +// Code generated by ent, DO NOT EDIT. + +package billinginvoicewriteschemalevel + +import ( + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the billinginvoicewriteschemalevel type in the database. + Label = "billing_invoice_write_schema_level" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldSchemaLevel holds the string denoting the schema_level field in the database. + FieldSchemaLevel = "schema_level" + // Table holds the table name of the billinginvoicewriteschemalevel in the database. + Table = "billing_invoice_write_schema_levels" +) + +// Columns holds all SQL columns for billinginvoicewriteschemalevel fields. +var Columns = []string{ + FieldID, + FieldSchemaLevel, +} + +// 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 ( + // IDValidator is a validator for the "id" field. It is called by the builders before save. + IDValidator func(string) error +) + +// OrderOption defines the ordering options for the BillingInvoiceWriteSchemaLevel 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() +} + +// BySchemaLevel orders the results by the schema_level field. +func BySchemaLevel(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSchemaLevel, opts...).ToFunc() +} diff --git a/ent/db/billinginvoicewriteschemalevel/where.go b/ent/db/billinginvoicewriteschemalevel/where.go new file mode 100644 index 0000000000000000000000000000000000000000..89593e72c64fcad8f7d4eb5106470ee948bef437 --- /dev/null +++ b/ent/db/billinginvoicewriteschemalevel/where.go @@ -0,0 +1,123 @@ +// Code generated by ent, DO NOT EDIT. + +package billinginvoicewriteschemalevel + +import ( + "entgo.io/ent/dialect/sql" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.FieldContainsFold(FieldID, id)) +} + +// SchemaLevel applies equality check predicate on the "schema_level" field. It's identical to SchemaLevelEQ. +func SchemaLevel(v int) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.FieldEQ(FieldSchemaLevel, v)) +} + +// SchemaLevelEQ applies the EQ predicate on the "schema_level" field. +func SchemaLevelEQ(v int) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.FieldEQ(FieldSchemaLevel, v)) +} + +// SchemaLevelNEQ applies the NEQ predicate on the "schema_level" field. +func SchemaLevelNEQ(v int) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.FieldNEQ(FieldSchemaLevel, v)) +} + +// SchemaLevelIn applies the In predicate on the "schema_level" field. +func SchemaLevelIn(vs ...int) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.FieldIn(FieldSchemaLevel, vs...)) +} + +// SchemaLevelNotIn applies the NotIn predicate on the "schema_level" field. +func SchemaLevelNotIn(vs ...int) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.FieldNotIn(FieldSchemaLevel, vs...)) +} + +// SchemaLevelGT applies the GT predicate on the "schema_level" field. +func SchemaLevelGT(v int) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.FieldGT(FieldSchemaLevel, v)) +} + +// SchemaLevelGTE applies the GTE predicate on the "schema_level" field. +func SchemaLevelGTE(v int) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.FieldGTE(FieldSchemaLevel, v)) +} + +// SchemaLevelLT applies the LT predicate on the "schema_level" field. +func SchemaLevelLT(v int) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.FieldLT(FieldSchemaLevel, v)) +} + +// SchemaLevelLTE applies the LTE predicate on the "schema_level" field. +func SchemaLevelLTE(v int) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.FieldLTE(FieldSchemaLevel, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.BillingInvoiceWriteSchemaLevel) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.BillingInvoiceWriteSchemaLevel) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.BillingInvoiceWriteSchemaLevel) predicate.BillingInvoiceWriteSchemaLevel { + return predicate.BillingInvoiceWriteSchemaLevel(sql.NotPredicates(p)) +} diff --git a/ent/db/billinginvoicewriteschemalevel_create.go b/ent/db/billinginvoicewriteschemalevel_create.go new file mode 100644 index 0000000000000000000000000000000000000000..b15939783952bbf6114e8ae3a969dde9d4368505 --- /dev/null +++ b/ent/db/billinginvoicewriteschemalevel_create.go @@ -0,0 +1,514 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + + "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/billinginvoicewriteschemalevel" +) + +// BillingInvoiceWriteSchemaLevelCreate is the builder for creating a BillingInvoiceWriteSchemaLevel entity. +type BillingInvoiceWriteSchemaLevelCreate struct { + config + mutation *BillingInvoiceWriteSchemaLevelMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetSchemaLevel sets the "schema_level" field. +func (_c *BillingInvoiceWriteSchemaLevelCreate) SetSchemaLevel(v int) *BillingInvoiceWriteSchemaLevelCreate { + _c.mutation.SetSchemaLevel(v) + return _c +} + +// SetID sets the "id" field. +func (_c *BillingInvoiceWriteSchemaLevelCreate) SetID(v string) *BillingInvoiceWriteSchemaLevelCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the BillingInvoiceWriteSchemaLevelMutation object of the builder. +func (_c *BillingInvoiceWriteSchemaLevelCreate) Mutation() *BillingInvoiceWriteSchemaLevelMutation { + return _c.mutation +} + +// Save creates the BillingInvoiceWriteSchemaLevel in the database. +func (_c *BillingInvoiceWriteSchemaLevelCreate) Save(ctx context.Context) (*BillingInvoiceWriteSchemaLevel, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *BillingInvoiceWriteSchemaLevelCreate) SaveX(ctx context.Context) *BillingInvoiceWriteSchemaLevel { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingInvoiceWriteSchemaLevelCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingInvoiceWriteSchemaLevelCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *BillingInvoiceWriteSchemaLevelCreate) check() error { + if _, ok := _c.mutation.SchemaLevel(); !ok { + return &ValidationError{Name: "schema_level", err: errors.New(`db: missing required field "BillingInvoiceWriteSchemaLevel.schema_level"`)} + } + if v, ok := _c.mutation.ID(); ok { + if err := billinginvoicewriteschemalevel.IDValidator(v); err != nil { + return &ValidationError{Name: "id", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceWriteSchemaLevel.id": %w`, err)} + } + } + return nil +} + +func (_c *BillingInvoiceWriteSchemaLevelCreate) sqlSave(ctx context.Context) (*BillingInvoiceWriteSchemaLevel, 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 BillingInvoiceWriteSchemaLevel.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *BillingInvoiceWriteSchemaLevelCreate) createSpec() (*BillingInvoiceWriteSchemaLevel, *sqlgraph.CreateSpec) { + var ( + _node = &BillingInvoiceWriteSchemaLevel{config: _c.config} + _spec = sqlgraph.NewCreateSpec(billinginvoicewriteschemalevel.Table, sqlgraph.NewFieldSpec(billinginvoicewriteschemalevel.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.SchemaLevel(); ok { + _spec.SetField(billinginvoicewriteschemalevel.FieldSchemaLevel, field.TypeInt, value) + _node.SchemaLevel = value + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.BillingInvoiceWriteSchemaLevel.Create(). +// SetSchemaLevel(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.BillingInvoiceWriteSchemaLevelUpsert) { +// SetSchemaLevel(v+v). +// }). +// Exec(ctx) +func (_c *BillingInvoiceWriteSchemaLevelCreate) OnConflict(opts ...sql.ConflictOption) *BillingInvoiceWriteSchemaLevelUpsertOne { + _c.conflict = opts + return &BillingInvoiceWriteSchemaLevelUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingInvoiceWriteSchemaLevel.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingInvoiceWriteSchemaLevelCreate) OnConflictColumns(columns ...string) *BillingInvoiceWriteSchemaLevelUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingInvoiceWriteSchemaLevelUpsertOne{ + create: _c, + } +} + +type ( + // BillingInvoiceWriteSchemaLevelUpsertOne is the builder for "upsert"-ing + // one BillingInvoiceWriteSchemaLevel node. + BillingInvoiceWriteSchemaLevelUpsertOne struct { + create *BillingInvoiceWriteSchemaLevelCreate + } + + // BillingInvoiceWriteSchemaLevelUpsert is the "OnConflict" setter. + BillingInvoiceWriteSchemaLevelUpsert struct { + *sql.UpdateSet + } +) + +// SetSchemaLevel sets the "schema_level" field. +func (u *BillingInvoiceWriteSchemaLevelUpsert) SetSchemaLevel(v int) *BillingInvoiceWriteSchemaLevelUpsert { + u.Set(billinginvoicewriteschemalevel.FieldSchemaLevel, v) + return u +} + +// UpdateSchemaLevel sets the "schema_level" field to the value that was provided on create. +func (u *BillingInvoiceWriteSchemaLevelUpsert) UpdateSchemaLevel() *BillingInvoiceWriteSchemaLevelUpsert { + u.SetExcluded(billinginvoicewriteschemalevel.FieldSchemaLevel) + return u +} + +// AddSchemaLevel adds v to the "schema_level" field. +func (u *BillingInvoiceWriteSchemaLevelUpsert) AddSchemaLevel(v int) *BillingInvoiceWriteSchemaLevelUpsert { + u.Add(billinginvoicewriteschemalevel.FieldSchemaLevel, v) + 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.BillingInvoiceWriteSchemaLevel.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(billinginvoicewriteschemalevel.FieldID) +// }), +// ). +// Exec(ctx) +func (u *BillingInvoiceWriteSchemaLevelUpsertOne) UpdateNewValues() *BillingInvoiceWriteSchemaLevelUpsertOne { + 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(billinginvoicewriteschemalevel.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingInvoiceWriteSchemaLevel.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingInvoiceWriteSchemaLevelUpsertOne) Ignore() *BillingInvoiceWriteSchemaLevelUpsertOne { + 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 *BillingInvoiceWriteSchemaLevelUpsertOne) DoNothing() *BillingInvoiceWriteSchemaLevelUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingInvoiceWriteSchemaLevelCreate.OnConflict +// documentation for more info. +func (u *BillingInvoiceWriteSchemaLevelUpsertOne) Update(set func(*BillingInvoiceWriteSchemaLevelUpsert)) *BillingInvoiceWriteSchemaLevelUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingInvoiceWriteSchemaLevelUpsert{UpdateSet: update}) + })) + return u +} + +// SetSchemaLevel sets the "schema_level" field. +func (u *BillingInvoiceWriteSchemaLevelUpsertOne) SetSchemaLevel(v int) *BillingInvoiceWriteSchemaLevelUpsertOne { + return u.Update(func(s *BillingInvoiceWriteSchemaLevelUpsert) { + s.SetSchemaLevel(v) + }) +} + +// AddSchemaLevel adds v to the "schema_level" field. +func (u *BillingInvoiceWriteSchemaLevelUpsertOne) AddSchemaLevel(v int) *BillingInvoiceWriteSchemaLevelUpsertOne { + return u.Update(func(s *BillingInvoiceWriteSchemaLevelUpsert) { + s.AddSchemaLevel(v) + }) +} + +// UpdateSchemaLevel sets the "schema_level" field to the value that was provided on create. +func (u *BillingInvoiceWriteSchemaLevelUpsertOne) UpdateSchemaLevel() *BillingInvoiceWriteSchemaLevelUpsertOne { + return u.Update(func(s *BillingInvoiceWriteSchemaLevelUpsert) { + s.UpdateSchemaLevel() + }) +} + +// Exec executes the query. +func (u *BillingInvoiceWriteSchemaLevelUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingInvoiceWriteSchemaLevelCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingInvoiceWriteSchemaLevelUpsertOne) 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 *BillingInvoiceWriteSchemaLevelUpsertOne) 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: BillingInvoiceWriteSchemaLevelUpsertOne.ID is not supported by MySQL driver. Use BillingInvoiceWriteSchemaLevelUpsertOne.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 *BillingInvoiceWriteSchemaLevelUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// BillingInvoiceWriteSchemaLevelCreateBulk is the builder for creating many BillingInvoiceWriteSchemaLevel entities in bulk. +type BillingInvoiceWriteSchemaLevelCreateBulk struct { + config + err error + builders []*BillingInvoiceWriteSchemaLevelCreate + conflict []sql.ConflictOption +} + +// Save creates the BillingInvoiceWriteSchemaLevel entities in the database. +func (_c *BillingInvoiceWriteSchemaLevelCreateBulk) Save(ctx context.Context) ([]*BillingInvoiceWriteSchemaLevel, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*BillingInvoiceWriteSchemaLevel, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*BillingInvoiceWriteSchemaLevelMutation) + 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 *BillingInvoiceWriteSchemaLevelCreateBulk) SaveX(ctx context.Context) []*BillingInvoiceWriteSchemaLevel { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingInvoiceWriteSchemaLevelCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingInvoiceWriteSchemaLevelCreateBulk) 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.BillingInvoiceWriteSchemaLevel.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.BillingInvoiceWriteSchemaLevelUpsert) { +// SetSchemaLevel(v+v). +// }). +// Exec(ctx) +func (_c *BillingInvoiceWriteSchemaLevelCreateBulk) OnConflict(opts ...sql.ConflictOption) *BillingInvoiceWriteSchemaLevelUpsertBulk { + _c.conflict = opts + return &BillingInvoiceWriteSchemaLevelUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingInvoiceWriteSchemaLevel.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingInvoiceWriteSchemaLevelCreateBulk) OnConflictColumns(columns ...string) *BillingInvoiceWriteSchemaLevelUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingInvoiceWriteSchemaLevelUpsertBulk{ + create: _c, + } +} + +// BillingInvoiceWriteSchemaLevelUpsertBulk is the builder for "upsert"-ing +// a bulk of BillingInvoiceWriteSchemaLevel nodes. +type BillingInvoiceWriteSchemaLevelUpsertBulk struct { + create *BillingInvoiceWriteSchemaLevelCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.BillingInvoiceWriteSchemaLevel.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(billinginvoicewriteschemalevel.FieldID) +// }), +// ). +// Exec(ctx) +func (u *BillingInvoiceWriteSchemaLevelUpsertBulk) UpdateNewValues() *BillingInvoiceWriteSchemaLevelUpsertBulk { + 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(billinginvoicewriteschemalevel.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingInvoiceWriteSchemaLevel.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingInvoiceWriteSchemaLevelUpsertBulk) Ignore() *BillingInvoiceWriteSchemaLevelUpsertBulk { + 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 *BillingInvoiceWriteSchemaLevelUpsertBulk) DoNothing() *BillingInvoiceWriteSchemaLevelUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingInvoiceWriteSchemaLevelCreateBulk.OnConflict +// documentation for more info. +func (u *BillingInvoiceWriteSchemaLevelUpsertBulk) Update(set func(*BillingInvoiceWriteSchemaLevelUpsert)) *BillingInvoiceWriteSchemaLevelUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingInvoiceWriteSchemaLevelUpsert{UpdateSet: update}) + })) + return u +} + +// SetSchemaLevel sets the "schema_level" field. +func (u *BillingInvoiceWriteSchemaLevelUpsertBulk) SetSchemaLevel(v int) *BillingInvoiceWriteSchemaLevelUpsertBulk { + return u.Update(func(s *BillingInvoiceWriteSchemaLevelUpsert) { + s.SetSchemaLevel(v) + }) +} + +// AddSchemaLevel adds v to the "schema_level" field. +func (u *BillingInvoiceWriteSchemaLevelUpsertBulk) AddSchemaLevel(v int) *BillingInvoiceWriteSchemaLevelUpsertBulk { + return u.Update(func(s *BillingInvoiceWriteSchemaLevelUpsert) { + s.AddSchemaLevel(v) + }) +} + +// UpdateSchemaLevel sets the "schema_level" field to the value that was provided on create. +func (u *BillingInvoiceWriteSchemaLevelUpsertBulk) UpdateSchemaLevel() *BillingInvoiceWriteSchemaLevelUpsertBulk { + return u.Update(func(s *BillingInvoiceWriteSchemaLevelUpsert) { + s.UpdateSchemaLevel() + }) +} + +// Exec executes the query. +func (u *BillingInvoiceWriteSchemaLevelUpsertBulk) 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 BillingInvoiceWriteSchemaLevelCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingInvoiceWriteSchemaLevelCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingInvoiceWriteSchemaLevelUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billinginvoicewriteschemalevel_delete.go b/ent/db/billinginvoicewriteschemalevel_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..8273d5c79e0934ab56b4631bfd70129f00f13e7c --- /dev/null +++ b/ent/db/billinginvoicewriteschemalevel_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/billinginvoicewriteschemalevel" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingInvoiceWriteSchemaLevelDelete is the builder for deleting a BillingInvoiceWriteSchemaLevel entity. +type BillingInvoiceWriteSchemaLevelDelete struct { + config + hooks []Hook + mutation *BillingInvoiceWriteSchemaLevelMutation +} + +// Where appends a list predicates to the BillingInvoiceWriteSchemaLevelDelete builder. +func (_d *BillingInvoiceWriteSchemaLevelDelete) Where(ps ...predicate.BillingInvoiceWriteSchemaLevel) *BillingInvoiceWriteSchemaLevelDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *BillingInvoiceWriteSchemaLevelDelete) 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 *BillingInvoiceWriteSchemaLevelDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *BillingInvoiceWriteSchemaLevelDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(billinginvoicewriteschemalevel.Table, sqlgraph.NewFieldSpec(billinginvoicewriteschemalevel.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 +} + +// BillingInvoiceWriteSchemaLevelDeleteOne is the builder for deleting a single BillingInvoiceWriteSchemaLevel entity. +type BillingInvoiceWriteSchemaLevelDeleteOne struct { + _d *BillingInvoiceWriteSchemaLevelDelete +} + +// Where appends a list predicates to the BillingInvoiceWriteSchemaLevelDelete builder. +func (_d *BillingInvoiceWriteSchemaLevelDeleteOne) Where(ps ...predicate.BillingInvoiceWriteSchemaLevel) *BillingInvoiceWriteSchemaLevelDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *BillingInvoiceWriteSchemaLevelDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{billinginvoicewriteschemalevel.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *BillingInvoiceWriteSchemaLevelDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billinginvoicewriteschemalevel_query.go b/ent/db/billinginvoicewriteschemalevel_query.go new file mode 100644 index 0000000000000000000000000000000000000000..38a0a2c56a55f61c2fd1b1221f6d959bd1a11a97 --- /dev/null +++ b/ent/db/billinginvoicewriteschemalevel_query.go @@ -0,0 +1,564 @@ +// 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/billinginvoicewriteschemalevel" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingInvoiceWriteSchemaLevelQuery is the builder for querying BillingInvoiceWriteSchemaLevel entities. +type BillingInvoiceWriteSchemaLevelQuery struct { + config + ctx *QueryContext + order []billinginvoicewriteschemalevel.OrderOption + inters []Interceptor + predicates []predicate.BillingInvoiceWriteSchemaLevel + 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 BillingInvoiceWriteSchemaLevelQuery builder. +func (_q *BillingInvoiceWriteSchemaLevelQuery) Where(ps ...predicate.BillingInvoiceWriteSchemaLevel) *BillingInvoiceWriteSchemaLevelQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *BillingInvoiceWriteSchemaLevelQuery) Limit(limit int) *BillingInvoiceWriteSchemaLevelQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *BillingInvoiceWriteSchemaLevelQuery) Offset(offset int) *BillingInvoiceWriteSchemaLevelQuery { + _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 *BillingInvoiceWriteSchemaLevelQuery) Unique(unique bool) *BillingInvoiceWriteSchemaLevelQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *BillingInvoiceWriteSchemaLevelQuery) Order(o ...billinginvoicewriteschemalevel.OrderOption) *BillingInvoiceWriteSchemaLevelQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first BillingInvoiceWriteSchemaLevel entity from the query. +// Returns a *NotFoundError when no BillingInvoiceWriteSchemaLevel was found. +func (_q *BillingInvoiceWriteSchemaLevelQuery) First(ctx context.Context) (*BillingInvoiceWriteSchemaLevel, 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{billinginvoicewriteschemalevel.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *BillingInvoiceWriteSchemaLevelQuery) FirstX(ctx context.Context) *BillingInvoiceWriteSchemaLevel { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first BillingInvoiceWriteSchemaLevel ID from the query. +// Returns a *NotFoundError when no BillingInvoiceWriteSchemaLevel ID was found. +func (_q *BillingInvoiceWriteSchemaLevelQuery) 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{billinginvoicewriteschemalevel.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *BillingInvoiceWriteSchemaLevelQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single BillingInvoiceWriteSchemaLevel entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one BillingInvoiceWriteSchemaLevel entity is found. +// Returns a *NotFoundError when no BillingInvoiceWriteSchemaLevel entities are found. +func (_q *BillingInvoiceWriteSchemaLevelQuery) Only(ctx context.Context) (*BillingInvoiceWriteSchemaLevel, 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{billinginvoicewriteschemalevel.Label} + default: + return nil, &NotSingularError{billinginvoicewriteschemalevel.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *BillingInvoiceWriteSchemaLevelQuery) OnlyX(ctx context.Context) *BillingInvoiceWriteSchemaLevel { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only BillingInvoiceWriteSchemaLevel ID in the query. +// Returns a *NotSingularError when more than one BillingInvoiceWriteSchemaLevel ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *BillingInvoiceWriteSchemaLevelQuery) 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{billinginvoicewriteschemalevel.Label} + default: + err = &NotSingularError{billinginvoicewriteschemalevel.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *BillingInvoiceWriteSchemaLevelQuery) 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 BillingInvoiceWriteSchemaLevels. +func (_q *BillingInvoiceWriteSchemaLevelQuery) All(ctx context.Context) ([]*BillingInvoiceWriteSchemaLevel, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*BillingInvoiceWriteSchemaLevel, *BillingInvoiceWriteSchemaLevelQuery]() + return withInterceptors[[]*BillingInvoiceWriteSchemaLevel](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *BillingInvoiceWriteSchemaLevelQuery) AllX(ctx context.Context) []*BillingInvoiceWriteSchemaLevel { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of BillingInvoiceWriteSchemaLevel IDs. +func (_q *BillingInvoiceWriteSchemaLevelQuery) 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(billinginvoicewriteschemalevel.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *BillingInvoiceWriteSchemaLevelQuery) 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 *BillingInvoiceWriteSchemaLevelQuery) 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[*BillingInvoiceWriteSchemaLevelQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *BillingInvoiceWriteSchemaLevelQuery) 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 *BillingInvoiceWriteSchemaLevelQuery) 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 *BillingInvoiceWriteSchemaLevelQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the BillingInvoiceWriteSchemaLevelQuery 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 *BillingInvoiceWriteSchemaLevelQuery) Clone() *BillingInvoiceWriteSchemaLevelQuery { + if _q == nil { + return nil + } + return &BillingInvoiceWriteSchemaLevelQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]billinginvoicewriteschemalevel.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.BillingInvoiceWriteSchemaLevel{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// 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 { +// SchemaLevel int `json:"schema_level,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.BillingInvoiceWriteSchemaLevel.Query(). +// GroupBy(billinginvoicewriteschemalevel.FieldSchemaLevel). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *BillingInvoiceWriteSchemaLevelQuery) GroupBy(field string, fields ...string) *BillingInvoiceWriteSchemaLevelGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &BillingInvoiceWriteSchemaLevelGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = billinginvoicewriteschemalevel.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 { +// SchemaLevel int `json:"schema_level,omitempty"` +// } +// +// client.BillingInvoiceWriteSchemaLevel.Query(). +// Select(billinginvoicewriteschemalevel.FieldSchemaLevel). +// Scan(ctx, &v) +func (_q *BillingInvoiceWriteSchemaLevelQuery) Select(fields ...string) *BillingInvoiceWriteSchemaLevelSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &BillingInvoiceWriteSchemaLevelSelect{BillingInvoiceWriteSchemaLevelQuery: _q} + sbuild.label = billinginvoicewriteschemalevel.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a BillingInvoiceWriteSchemaLevelSelect configured with the given aggregations. +func (_q *BillingInvoiceWriteSchemaLevelQuery) Aggregate(fns ...AggregateFunc) *BillingInvoiceWriteSchemaLevelSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *BillingInvoiceWriteSchemaLevelQuery) 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 !billinginvoicewriteschemalevel.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 *BillingInvoiceWriteSchemaLevelQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BillingInvoiceWriteSchemaLevel, error) { + var ( + nodes = []*BillingInvoiceWriteSchemaLevel{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*BillingInvoiceWriteSchemaLevel).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &BillingInvoiceWriteSchemaLevel{config: _q.config} + nodes = append(nodes, node) + 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 + } + return nodes, nil +} + +func (_q *BillingInvoiceWriteSchemaLevelQuery) 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 *BillingInvoiceWriteSchemaLevelQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(billinginvoicewriteschemalevel.Table, billinginvoicewriteschemalevel.Columns, sqlgraph.NewFieldSpec(billinginvoicewriteschemalevel.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, billinginvoicewriteschemalevel.FieldID) + for i := range fields { + if fields[i] != billinginvoicewriteschemalevel.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 *BillingInvoiceWriteSchemaLevelQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(billinginvoicewriteschemalevel.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = billinginvoicewriteschemalevel.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 *BillingInvoiceWriteSchemaLevelQuery) ForUpdate(opts ...sql.LockOption) *BillingInvoiceWriteSchemaLevelQuery { + 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 *BillingInvoiceWriteSchemaLevelQuery) ForShare(opts ...sql.LockOption) *BillingInvoiceWriteSchemaLevelQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// BillingInvoiceWriteSchemaLevelGroupBy is the group-by builder for BillingInvoiceWriteSchemaLevel entities. +type BillingInvoiceWriteSchemaLevelGroupBy struct { + selector + build *BillingInvoiceWriteSchemaLevelQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *BillingInvoiceWriteSchemaLevelGroupBy) Aggregate(fns ...AggregateFunc) *BillingInvoiceWriteSchemaLevelGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *BillingInvoiceWriteSchemaLevelGroupBy) 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[*BillingInvoiceWriteSchemaLevelQuery, *BillingInvoiceWriteSchemaLevelGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *BillingInvoiceWriteSchemaLevelGroupBy) sqlScan(ctx context.Context, root *BillingInvoiceWriteSchemaLevelQuery, 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) +} + +// BillingInvoiceWriteSchemaLevelSelect is the builder for selecting fields of BillingInvoiceWriteSchemaLevel entities. +type BillingInvoiceWriteSchemaLevelSelect struct { + *BillingInvoiceWriteSchemaLevelQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *BillingInvoiceWriteSchemaLevelSelect) Aggregate(fns ...AggregateFunc) *BillingInvoiceWriteSchemaLevelSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *BillingInvoiceWriteSchemaLevelSelect) 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[*BillingInvoiceWriteSchemaLevelQuery, *BillingInvoiceWriteSchemaLevelSelect](ctx, _s.BillingInvoiceWriteSchemaLevelQuery, _s, _s.inters, v) +} + +func (_s *BillingInvoiceWriteSchemaLevelSelect) sqlScan(ctx context.Context, root *BillingInvoiceWriteSchemaLevelQuery, 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/ent/db/billinginvoicewriteschemalevel_update.go b/ent/db/billinginvoicewriteschemalevel_update.go new file mode 100644 index 0000000000000000000000000000000000000000..66a9bd48079d2bedfd418540a162b12600dbf097 --- /dev/null +++ b/ent/db/billinginvoicewriteschemalevel_update.go @@ -0,0 +1,229 @@ +// 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/billinginvoicewriteschemalevel" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingInvoiceWriteSchemaLevelUpdate is the builder for updating BillingInvoiceWriteSchemaLevel entities. +type BillingInvoiceWriteSchemaLevelUpdate struct { + config + hooks []Hook + mutation *BillingInvoiceWriteSchemaLevelMutation +} + +// Where appends a list predicates to the BillingInvoiceWriteSchemaLevelUpdate builder. +func (_u *BillingInvoiceWriteSchemaLevelUpdate) Where(ps ...predicate.BillingInvoiceWriteSchemaLevel) *BillingInvoiceWriteSchemaLevelUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetSchemaLevel sets the "schema_level" field. +func (_u *BillingInvoiceWriteSchemaLevelUpdate) SetSchemaLevel(v int) *BillingInvoiceWriteSchemaLevelUpdate { + _u.mutation.ResetSchemaLevel() + _u.mutation.SetSchemaLevel(v) + return _u +} + +// SetNillableSchemaLevel sets the "schema_level" field if the given value is not nil. +func (_u *BillingInvoiceWriteSchemaLevelUpdate) SetNillableSchemaLevel(v *int) *BillingInvoiceWriteSchemaLevelUpdate { + if v != nil { + _u.SetSchemaLevel(*v) + } + return _u +} + +// AddSchemaLevel adds value to the "schema_level" field. +func (_u *BillingInvoiceWriteSchemaLevelUpdate) AddSchemaLevel(v int) *BillingInvoiceWriteSchemaLevelUpdate { + _u.mutation.AddSchemaLevel(v) + return _u +} + +// Mutation returns the BillingInvoiceWriteSchemaLevelMutation object of the builder. +func (_u *BillingInvoiceWriteSchemaLevelUpdate) Mutation() *BillingInvoiceWriteSchemaLevelMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *BillingInvoiceWriteSchemaLevelUpdate) 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 *BillingInvoiceWriteSchemaLevelUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *BillingInvoiceWriteSchemaLevelUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingInvoiceWriteSchemaLevelUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *BillingInvoiceWriteSchemaLevelUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(billinginvoicewriteschemalevel.Table, billinginvoicewriteschemalevel.Columns, sqlgraph.NewFieldSpec(billinginvoicewriteschemalevel.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.SchemaLevel(); ok { + _spec.SetField(billinginvoicewriteschemalevel.FieldSchemaLevel, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedSchemaLevel(); ok { + _spec.AddField(billinginvoicewriteschemalevel.FieldSchemaLevel, field.TypeInt, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{billinginvoicewriteschemalevel.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// BillingInvoiceWriteSchemaLevelUpdateOne is the builder for updating a single BillingInvoiceWriteSchemaLevel entity. +type BillingInvoiceWriteSchemaLevelUpdateOne struct { + config + fields []string + hooks []Hook + mutation *BillingInvoiceWriteSchemaLevelMutation +} + +// SetSchemaLevel sets the "schema_level" field. +func (_u *BillingInvoiceWriteSchemaLevelUpdateOne) SetSchemaLevel(v int) *BillingInvoiceWriteSchemaLevelUpdateOne { + _u.mutation.ResetSchemaLevel() + _u.mutation.SetSchemaLevel(v) + return _u +} + +// SetNillableSchemaLevel sets the "schema_level" field if the given value is not nil. +func (_u *BillingInvoiceWriteSchemaLevelUpdateOne) SetNillableSchemaLevel(v *int) *BillingInvoiceWriteSchemaLevelUpdateOne { + if v != nil { + _u.SetSchemaLevel(*v) + } + return _u +} + +// AddSchemaLevel adds value to the "schema_level" field. +func (_u *BillingInvoiceWriteSchemaLevelUpdateOne) AddSchemaLevel(v int) *BillingInvoiceWriteSchemaLevelUpdateOne { + _u.mutation.AddSchemaLevel(v) + return _u +} + +// Mutation returns the BillingInvoiceWriteSchemaLevelMutation object of the builder. +func (_u *BillingInvoiceWriteSchemaLevelUpdateOne) Mutation() *BillingInvoiceWriteSchemaLevelMutation { + return _u.mutation +} + +// Where appends a list predicates to the BillingInvoiceWriteSchemaLevelUpdate builder. +func (_u *BillingInvoiceWriteSchemaLevelUpdateOne) Where(ps ...predicate.BillingInvoiceWriteSchemaLevel) *BillingInvoiceWriteSchemaLevelUpdateOne { + _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 *BillingInvoiceWriteSchemaLevelUpdateOne) Select(field string, fields ...string) *BillingInvoiceWriteSchemaLevelUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated BillingInvoiceWriteSchemaLevel entity. +func (_u *BillingInvoiceWriteSchemaLevelUpdateOne) Save(ctx context.Context) (*BillingInvoiceWriteSchemaLevel, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *BillingInvoiceWriteSchemaLevelUpdateOne) SaveX(ctx context.Context) *BillingInvoiceWriteSchemaLevel { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *BillingInvoiceWriteSchemaLevelUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingInvoiceWriteSchemaLevelUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *BillingInvoiceWriteSchemaLevelUpdateOne) sqlSave(ctx context.Context) (_node *BillingInvoiceWriteSchemaLevel, err error) { + _spec := sqlgraph.NewUpdateSpec(billinginvoicewriteschemalevel.Table, billinginvoicewriteschemalevel.Columns, sqlgraph.NewFieldSpec(billinginvoicewriteschemalevel.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "BillingInvoiceWriteSchemaLevel.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, billinginvoicewriteschemalevel.FieldID) + for _, f := range fields { + if !billinginvoicewriteschemalevel.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != billinginvoicewriteschemalevel.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.SchemaLevel(); ok { + _spec.SetField(billinginvoicewriteschemalevel.FieldSchemaLevel, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedSchemaLevel(); ok { + _spec.AddField(billinginvoicewriteschemalevel.FieldSchemaLevel, field.TypeInt, value) + } + _node = &BillingInvoiceWriteSchemaLevel{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{billinginvoicewriteschemalevel.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/ent/db/billingprofile.go b/ent/db/billingprofile.go new file mode 100644 index 0000000000000000000000000000000000000000..3dafec499d5a3cda86cef71aec268760a051271f --- /dev/null +++ b/ent/db/billingprofile.go @@ -0,0 +1,478 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + dbapp "github.com/openmeterio/openmeter/openmeter/ent/db/app" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingprofile" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingworkflowconfig" + "github.com/openmeterio/openmeter/pkg/models" +) + +// BillingProfile is the model entity for the BillingProfile schema. +type BillingProfile 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"` + // Metadata holds the value of the "metadata" field. + Metadata map[string]string `json:"metadata,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"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Description holds the value of the "description" field. + Description *string `json:"description,omitempty"` + // SupplierAddressCountry holds the value of the "supplier_address_country" field. + SupplierAddressCountry *models.CountryCode `json:"supplier_address_country,omitempty"` + // SupplierAddressPostalCode holds the value of the "supplier_address_postal_code" field. + SupplierAddressPostalCode *string `json:"supplier_address_postal_code,omitempty"` + // SupplierAddressState holds the value of the "supplier_address_state" field. + SupplierAddressState *string `json:"supplier_address_state,omitempty"` + // SupplierAddressCity holds the value of the "supplier_address_city" field. + SupplierAddressCity *string `json:"supplier_address_city,omitempty"` + // SupplierAddressLine1 holds the value of the "supplier_address_line1" field. + SupplierAddressLine1 *string `json:"supplier_address_line1,omitempty"` + // SupplierAddressLine2 holds the value of the "supplier_address_line2" field. + SupplierAddressLine2 *string `json:"supplier_address_line2,omitempty"` + // SupplierAddressPhoneNumber holds the value of the "supplier_address_phone_number" field. + SupplierAddressPhoneNumber *string `json:"supplier_address_phone_number,omitempty"` + // TaxAppID holds the value of the "tax_app_id" field. + TaxAppID string `json:"tax_app_id,omitempty"` + // InvoicingAppID holds the value of the "invoicing_app_id" field. + InvoicingAppID string `json:"invoicing_app_id,omitempty"` + // PaymentAppID holds the value of the "payment_app_id" field. + PaymentAppID string `json:"payment_app_id,omitempty"` + // WorkflowConfigID holds the value of the "workflow_config_id" field. + WorkflowConfigID string `json:"workflow_config_id,omitempty"` + // Default holds the value of the "default" field. + Default bool `json:"default,omitempty"` + // SupplierName holds the value of the "supplier_name" field. + SupplierName string `json:"supplier_name,omitempty"` + // SupplierTaxCode holds the value of the "supplier_tax_code" field. + SupplierTaxCode *string `json:"supplier_tax_code,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the BillingProfileQuery when eager-loading is set. + Edges BillingProfileEdges `json:"edges"` + selectValues sql.SelectValues +} + +// BillingProfileEdges holds the relations/edges for other nodes in the graph. +type BillingProfileEdges struct { + // BillingInvoices holds the value of the billing_invoices edge. + BillingInvoices []*BillingInvoice `json:"billing_invoices,omitempty"` + // BillingCustomerOverride holds the value of the billing_customer_override edge. + BillingCustomerOverride []*BillingCustomerOverride `json:"billing_customer_override,omitempty"` + // WorkflowConfig holds the value of the workflow_config edge. + WorkflowConfig *BillingWorkflowConfig `json:"workflow_config,omitempty"` + // TaxApp holds the value of the tax_app edge. + TaxApp *App `json:"tax_app,omitempty"` + // InvoicingApp holds the value of the invoicing_app edge. + InvoicingApp *App `json:"invoicing_app,omitempty"` + // PaymentApp holds the value of the payment_app edge. + PaymentApp *App `json:"payment_app,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [6]bool +} + +// BillingInvoicesOrErr returns the BillingInvoices value or an error if the edge +// was not loaded in eager-loading. +func (e BillingProfileEdges) BillingInvoicesOrErr() ([]*BillingInvoice, error) { + if e.loadedTypes[0] { + return e.BillingInvoices, nil + } + return nil, &NotLoadedError{edge: "billing_invoices"} +} + +// BillingCustomerOverrideOrErr returns the BillingCustomerOverride value or an error if the edge +// was not loaded in eager-loading. +func (e BillingProfileEdges) BillingCustomerOverrideOrErr() ([]*BillingCustomerOverride, error) { + if e.loadedTypes[1] { + return e.BillingCustomerOverride, nil + } + return nil, &NotLoadedError{edge: "billing_customer_override"} +} + +// WorkflowConfigOrErr returns the WorkflowConfig value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e BillingProfileEdges) WorkflowConfigOrErr() (*BillingWorkflowConfig, error) { + if e.WorkflowConfig != nil { + return e.WorkflowConfig, nil + } else if e.loadedTypes[2] { + return nil, &NotFoundError{label: billingworkflowconfig.Label} + } + return nil, &NotLoadedError{edge: "workflow_config"} +} + +// TaxAppOrErr returns the TaxApp value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e BillingProfileEdges) TaxAppOrErr() (*App, error) { + if e.TaxApp != nil { + return e.TaxApp, nil + } else if e.loadedTypes[3] { + return nil, &NotFoundError{label: dbapp.Label} + } + return nil, &NotLoadedError{edge: "tax_app"} +} + +// InvoicingAppOrErr returns the InvoicingApp value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e BillingProfileEdges) InvoicingAppOrErr() (*App, error) { + if e.InvoicingApp != nil { + return e.InvoicingApp, nil + } else if e.loadedTypes[4] { + return nil, &NotFoundError{label: dbapp.Label} + } + return nil, &NotLoadedError{edge: "invoicing_app"} +} + +// PaymentAppOrErr returns the PaymentApp value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e BillingProfileEdges) PaymentAppOrErr() (*App, error) { + if e.PaymentApp != nil { + return e.PaymentApp, nil + } else if e.loadedTypes[5] { + return nil, &NotFoundError{label: dbapp.Label} + } + return nil, &NotLoadedError{edge: "payment_app"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*BillingProfile) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case billingprofile.FieldMetadata: + values[i] = new([]byte) + case billingprofile.FieldDefault: + values[i] = new(sql.NullBool) + case billingprofile.FieldID, billingprofile.FieldNamespace, billingprofile.FieldName, billingprofile.FieldDescription, billingprofile.FieldSupplierAddressCountry, billingprofile.FieldSupplierAddressPostalCode, billingprofile.FieldSupplierAddressState, billingprofile.FieldSupplierAddressCity, billingprofile.FieldSupplierAddressLine1, billingprofile.FieldSupplierAddressLine2, billingprofile.FieldSupplierAddressPhoneNumber, billingprofile.FieldTaxAppID, billingprofile.FieldInvoicingAppID, billingprofile.FieldPaymentAppID, billingprofile.FieldWorkflowConfigID, billingprofile.FieldSupplierName, billingprofile.FieldSupplierTaxCode: + values[i] = new(sql.NullString) + case billingprofile.FieldCreatedAt, billingprofile.FieldUpdatedAt, billingprofile.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 BillingProfile fields. +func (_m *BillingProfile) 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 billingprofile.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 billingprofile.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 billingprofile.FieldMetadata: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field metadata", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Metadata); err != nil { + return fmt.Errorf("unmarshal field metadata: %w", err) + } + } + case billingprofile.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 billingprofile.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 billingprofile.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 billingprofile.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case billingprofile.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + _m.Description = new(string) + *_m.Description = value.String + } + case billingprofile.FieldSupplierAddressCountry: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field supplier_address_country", values[i]) + } else if value.Valid { + _m.SupplierAddressCountry = new(models.CountryCode) + *_m.SupplierAddressCountry = models.CountryCode(value.String) + } + case billingprofile.FieldSupplierAddressPostalCode: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field supplier_address_postal_code", values[i]) + } else if value.Valid { + _m.SupplierAddressPostalCode = new(string) + *_m.SupplierAddressPostalCode = value.String + } + case billingprofile.FieldSupplierAddressState: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field supplier_address_state", values[i]) + } else if value.Valid { + _m.SupplierAddressState = new(string) + *_m.SupplierAddressState = value.String + } + case billingprofile.FieldSupplierAddressCity: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field supplier_address_city", values[i]) + } else if value.Valid { + _m.SupplierAddressCity = new(string) + *_m.SupplierAddressCity = value.String + } + case billingprofile.FieldSupplierAddressLine1: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field supplier_address_line1", values[i]) + } else if value.Valid { + _m.SupplierAddressLine1 = new(string) + *_m.SupplierAddressLine1 = value.String + } + case billingprofile.FieldSupplierAddressLine2: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field supplier_address_line2", values[i]) + } else if value.Valid { + _m.SupplierAddressLine2 = new(string) + *_m.SupplierAddressLine2 = value.String + } + case billingprofile.FieldSupplierAddressPhoneNumber: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field supplier_address_phone_number", values[i]) + } else if value.Valid { + _m.SupplierAddressPhoneNumber = new(string) + *_m.SupplierAddressPhoneNumber = value.String + } + case billingprofile.FieldTaxAppID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field tax_app_id", values[i]) + } else if value.Valid { + _m.TaxAppID = value.String + } + case billingprofile.FieldInvoicingAppID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field invoicing_app_id", values[i]) + } else if value.Valid { + _m.InvoicingAppID = value.String + } + case billingprofile.FieldPaymentAppID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field payment_app_id", values[i]) + } else if value.Valid { + _m.PaymentAppID = value.String + } + case billingprofile.FieldWorkflowConfigID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field workflow_config_id", values[i]) + } else if value.Valid { + _m.WorkflowConfigID = value.String + } + case billingprofile.FieldDefault: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field default", values[i]) + } else if value.Valid { + _m.Default = value.Bool + } + case billingprofile.FieldSupplierName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field supplier_name", values[i]) + } else if value.Valid { + _m.SupplierName = value.String + } + case billingprofile.FieldSupplierTaxCode: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field supplier_tax_code", values[i]) + } else if value.Valid { + _m.SupplierTaxCode = new(string) + *_m.SupplierTaxCode = 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 BillingProfile. +// This includes values selected through modifiers, order, etc. +func (_m *BillingProfile) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryBillingInvoices queries the "billing_invoices" edge of the BillingProfile entity. +func (_m *BillingProfile) QueryBillingInvoices() *BillingInvoiceQuery { + return NewBillingProfileClient(_m.config).QueryBillingInvoices(_m) +} + +// QueryBillingCustomerOverride queries the "billing_customer_override" edge of the BillingProfile entity. +func (_m *BillingProfile) QueryBillingCustomerOverride() *BillingCustomerOverrideQuery { + return NewBillingProfileClient(_m.config).QueryBillingCustomerOverride(_m) +} + +// QueryWorkflowConfig queries the "workflow_config" edge of the BillingProfile entity. +func (_m *BillingProfile) QueryWorkflowConfig() *BillingWorkflowConfigQuery { + return NewBillingProfileClient(_m.config).QueryWorkflowConfig(_m) +} + +// QueryTaxApp queries the "tax_app" edge of the BillingProfile entity. +func (_m *BillingProfile) QueryTaxApp() *AppQuery { + return NewBillingProfileClient(_m.config).QueryTaxApp(_m) +} + +// QueryInvoicingApp queries the "invoicing_app" edge of the BillingProfile entity. +func (_m *BillingProfile) QueryInvoicingApp() *AppQuery { + return NewBillingProfileClient(_m.config).QueryInvoicingApp(_m) +} + +// QueryPaymentApp queries the "payment_app" edge of the BillingProfile entity. +func (_m *BillingProfile) QueryPaymentApp() *AppQuery { + return NewBillingProfileClient(_m.config).QueryPaymentApp(_m) +} + +// Update returns a builder for updating this BillingProfile. +// Note that you need to call BillingProfile.Unwrap() before calling this method if this BillingProfile +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *BillingProfile) Update() *BillingProfileUpdateOne { + return NewBillingProfileClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the BillingProfile 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 *BillingProfile) Unwrap() *BillingProfile { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: BillingProfile is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *BillingProfile) String() string { + var builder strings.Builder + builder.WriteString("BillingProfile(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("metadata=") + builder.WriteString(fmt.Sprintf("%v", _m.Metadata)) + 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("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + if v := _m.Description; v != nil { + builder.WriteString("description=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SupplierAddressCountry; v != nil { + builder.WriteString("supplier_address_country=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.SupplierAddressPostalCode; v != nil { + builder.WriteString("supplier_address_postal_code=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SupplierAddressState; v != nil { + builder.WriteString("supplier_address_state=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SupplierAddressCity; v != nil { + builder.WriteString("supplier_address_city=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SupplierAddressLine1; v != nil { + builder.WriteString("supplier_address_line1=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SupplierAddressLine2; v != nil { + builder.WriteString("supplier_address_line2=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SupplierAddressPhoneNumber; v != nil { + builder.WriteString("supplier_address_phone_number=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("tax_app_id=") + builder.WriteString(_m.TaxAppID) + builder.WriteString(", ") + builder.WriteString("invoicing_app_id=") + builder.WriteString(_m.InvoicingAppID) + builder.WriteString(", ") + builder.WriteString("payment_app_id=") + builder.WriteString(_m.PaymentAppID) + builder.WriteString(", ") + builder.WriteString("workflow_config_id=") + builder.WriteString(_m.WorkflowConfigID) + builder.WriteString(", ") + builder.WriteString("default=") + builder.WriteString(fmt.Sprintf("%v", _m.Default)) + builder.WriteString(", ") + builder.WriteString("supplier_name=") + builder.WriteString(_m.SupplierName) + builder.WriteString(", ") + if v := _m.SupplierTaxCode; v != nil { + builder.WriteString("supplier_tax_code=") + builder.WriteString(*v) + } + builder.WriteByte(')') + return builder.String() +} + +// BillingProfiles is a parsable slice of BillingProfile. +type BillingProfiles []*BillingProfile diff --git a/ent/db/billingprofile/billingprofile.go b/ent/db/billingprofile/billingprofile.go new file mode 100644 index 0000000000000000000000000000000000000000..a6b48752a1f0299cee3bb7168165e4ffef2da8f6 --- /dev/null +++ b/ent/db/billingprofile/billingprofile.go @@ -0,0 +1,378 @@ +// Code generated by ent, DO NOT EDIT. + +package billingprofile + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the billingprofile type in the database. + Label = "billing_profile" + // 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" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // 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" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // FieldSupplierAddressCountry holds the string denoting the supplier_address_country field in the database. + FieldSupplierAddressCountry = "supplier_address_country" + // FieldSupplierAddressPostalCode holds the string denoting the supplier_address_postal_code field in the database. + FieldSupplierAddressPostalCode = "supplier_address_postal_code" + // FieldSupplierAddressState holds the string denoting the supplier_address_state field in the database. + FieldSupplierAddressState = "supplier_address_state" + // FieldSupplierAddressCity holds the string denoting the supplier_address_city field in the database. + FieldSupplierAddressCity = "supplier_address_city" + // FieldSupplierAddressLine1 holds the string denoting the supplier_address_line1 field in the database. + FieldSupplierAddressLine1 = "supplier_address_line1" + // FieldSupplierAddressLine2 holds the string denoting the supplier_address_line2 field in the database. + FieldSupplierAddressLine2 = "supplier_address_line2" + // FieldSupplierAddressPhoneNumber holds the string denoting the supplier_address_phone_number field in the database. + FieldSupplierAddressPhoneNumber = "supplier_address_phone_number" + // FieldTaxAppID holds the string denoting the tax_app_id field in the database. + FieldTaxAppID = "tax_app_id" + // FieldInvoicingAppID holds the string denoting the invoicing_app_id field in the database. + FieldInvoicingAppID = "invoicing_app_id" + // FieldPaymentAppID holds the string denoting the payment_app_id field in the database. + FieldPaymentAppID = "payment_app_id" + // FieldWorkflowConfigID holds the string denoting the workflow_config_id field in the database. + FieldWorkflowConfigID = "workflow_config_id" + // FieldDefault holds the string denoting the default field in the database. + FieldDefault = "default" + // FieldSupplierName holds the string denoting the supplier_name field in the database. + FieldSupplierName = "supplier_name" + // FieldSupplierTaxCode holds the string denoting the supplier_tax_code field in the database. + FieldSupplierTaxCode = "supplier_tax_code" + // EdgeBillingInvoices holds the string denoting the billing_invoices edge name in mutations. + EdgeBillingInvoices = "billing_invoices" + // EdgeBillingCustomerOverride holds the string denoting the billing_customer_override edge name in mutations. + EdgeBillingCustomerOverride = "billing_customer_override" + // EdgeWorkflowConfig holds the string denoting the workflow_config edge name in mutations. + EdgeWorkflowConfig = "workflow_config" + // EdgeTaxApp holds the string denoting the tax_app edge name in mutations. + EdgeTaxApp = "tax_app" + // EdgeInvoicingApp holds the string denoting the invoicing_app edge name in mutations. + EdgeInvoicingApp = "invoicing_app" + // EdgePaymentApp holds the string denoting the payment_app edge name in mutations. + EdgePaymentApp = "payment_app" + // Table holds the table name of the billingprofile in the database. + Table = "billing_profiles" + // BillingInvoicesTable is the table that holds the billing_invoices relation/edge. + BillingInvoicesTable = "billing_invoices" + // BillingInvoicesInverseTable is the table name for the BillingInvoice entity. + // It exists in this package in order to avoid circular dependency with the "billinginvoice" package. + BillingInvoicesInverseTable = "billing_invoices" + // BillingInvoicesColumn is the table column denoting the billing_invoices relation/edge. + BillingInvoicesColumn = "source_billing_profile_id" + // BillingCustomerOverrideTable is the table that holds the billing_customer_override relation/edge. + BillingCustomerOverrideTable = "billing_customer_overrides" + // BillingCustomerOverrideInverseTable is the table name for the BillingCustomerOverride entity. + // It exists in this package in order to avoid circular dependency with the "billingcustomeroverride" package. + BillingCustomerOverrideInverseTable = "billing_customer_overrides" + // BillingCustomerOverrideColumn is the table column denoting the billing_customer_override relation/edge. + BillingCustomerOverrideColumn = "billing_profile_id" + // WorkflowConfigTable is the table that holds the workflow_config relation/edge. + WorkflowConfigTable = "billing_profiles" + // WorkflowConfigInverseTable is the table name for the BillingWorkflowConfig entity. + // It exists in this package in order to avoid circular dependency with the "billingworkflowconfig" package. + WorkflowConfigInverseTable = "billing_workflow_configs" + // WorkflowConfigColumn is the table column denoting the workflow_config relation/edge. + WorkflowConfigColumn = "workflow_config_id" + // TaxAppTable is the table that holds the tax_app relation/edge. + TaxAppTable = "billing_profiles" + // TaxAppInverseTable is the table name for the App entity. + // It exists in this package in order to avoid circular dependency with the "dbapp" package. + TaxAppInverseTable = "apps" + // TaxAppColumn is the table column denoting the tax_app relation/edge. + TaxAppColumn = "tax_app_id" + // InvoicingAppTable is the table that holds the invoicing_app relation/edge. + InvoicingAppTable = "billing_profiles" + // InvoicingAppInverseTable is the table name for the App entity. + // It exists in this package in order to avoid circular dependency with the "dbapp" package. + InvoicingAppInverseTable = "apps" + // InvoicingAppColumn is the table column denoting the invoicing_app relation/edge. + InvoicingAppColumn = "invoicing_app_id" + // PaymentAppTable is the table that holds the payment_app relation/edge. + PaymentAppTable = "billing_profiles" + // PaymentAppInverseTable is the table name for the App entity. + // It exists in this package in order to avoid circular dependency with the "dbapp" package. + PaymentAppInverseTable = "apps" + // PaymentAppColumn is the table column denoting the payment_app relation/edge. + PaymentAppColumn = "payment_app_id" +) + +// Columns holds all SQL columns for billingprofile fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldMetadata, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldName, + FieldDescription, + FieldSupplierAddressCountry, + FieldSupplierAddressPostalCode, + FieldSupplierAddressState, + FieldSupplierAddressCity, + FieldSupplierAddressLine1, + FieldSupplierAddressLine2, + FieldSupplierAddressPhoneNumber, + FieldTaxAppID, + FieldInvoicingAppID, + FieldPaymentAppID, + FieldWorkflowConfigID, + FieldDefault, + FieldSupplierName, + FieldSupplierTaxCode, +} + +// 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 + // SupplierAddressCountryValidator is a validator for the "supplier_address_country" field. It is called by the builders before save. + SupplierAddressCountryValidator func(string) error + // WorkflowConfigIDValidator is a validator for the "workflow_config_id" field. It is called by the builders before save. + WorkflowConfigIDValidator func(string) error + // DefaultDefault holds the default value on creation for the "default" field. + DefaultDefault bool + // SupplierNameValidator is a validator for the "supplier_name" field. It is called by the builders before save. + SupplierNameValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// OrderOption defines the ordering options for the BillingProfile 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() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, opts...).ToFunc() +} + +// BySupplierAddressCountry orders the results by the supplier_address_country field. +func BySupplierAddressCountry(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSupplierAddressCountry, opts...).ToFunc() +} + +// BySupplierAddressPostalCode orders the results by the supplier_address_postal_code field. +func BySupplierAddressPostalCode(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSupplierAddressPostalCode, opts...).ToFunc() +} + +// BySupplierAddressState orders the results by the supplier_address_state field. +func BySupplierAddressState(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSupplierAddressState, opts...).ToFunc() +} + +// BySupplierAddressCity orders the results by the supplier_address_city field. +func BySupplierAddressCity(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSupplierAddressCity, opts...).ToFunc() +} + +// BySupplierAddressLine1 orders the results by the supplier_address_line1 field. +func BySupplierAddressLine1(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSupplierAddressLine1, opts...).ToFunc() +} + +// BySupplierAddressLine2 orders the results by the supplier_address_line2 field. +func BySupplierAddressLine2(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSupplierAddressLine2, opts...).ToFunc() +} + +// BySupplierAddressPhoneNumber orders the results by the supplier_address_phone_number field. +func BySupplierAddressPhoneNumber(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSupplierAddressPhoneNumber, opts...).ToFunc() +} + +// ByTaxAppID orders the results by the tax_app_id field. +func ByTaxAppID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxAppID, opts...).ToFunc() +} + +// ByInvoicingAppID orders the results by the invoicing_app_id field. +func ByInvoicingAppID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoicingAppID, opts...).ToFunc() +} + +// ByPaymentAppID orders the results by the payment_app_id field. +func ByPaymentAppID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPaymentAppID, opts...).ToFunc() +} + +// ByWorkflowConfigID orders the results by the workflow_config_id field. +func ByWorkflowConfigID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldWorkflowConfigID, opts...).ToFunc() +} + +// ByDefault orders the results by the default field. +func ByDefault(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDefault, opts...).ToFunc() +} + +// BySupplierName orders the results by the supplier_name field. +func BySupplierName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSupplierName, opts...).ToFunc() +} + +// BySupplierTaxCode orders the results by the supplier_tax_code field. +func BySupplierTaxCode(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSupplierTaxCode, opts...).ToFunc() +} + +// ByBillingInvoicesCount orders the results by billing_invoices count. +func ByBillingInvoicesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newBillingInvoicesStep(), opts...) + } +} + +// ByBillingInvoices orders the results by billing_invoices terms. +func ByBillingInvoices(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBillingInvoicesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByBillingCustomerOverrideCount orders the results by billing_customer_override count. +func ByBillingCustomerOverrideCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newBillingCustomerOverrideStep(), opts...) + } +} + +// ByBillingCustomerOverride orders the results by billing_customer_override terms. +func ByBillingCustomerOverride(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBillingCustomerOverrideStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByWorkflowConfigField orders the results by workflow_config field. +func ByWorkflowConfigField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newWorkflowConfigStep(), sql.OrderByField(field, opts...)) + } +} + +// ByTaxAppField orders the results by tax_app field. +func ByTaxAppField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTaxAppStep(), sql.OrderByField(field, opts...)) + } +} + +// ByInvoicingAppField orders the results by invoicing_app field. +func ByInvoicingAppField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newInvoicingAppStep(), sql.OrderByField(field, opts...)) + } +} + +// ByPaymentAppField orders the results by payment_app field. +func ByPaymentAppField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newPaymentAppStep(), sql.OrderByField(field, opts...)) + } +} +func newBillingInvoicesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BillingInvoicesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, BillingInvoicesTable, BillingInvoicesColumn), + ) +} +func newBillingCustomerOverrideStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BillingCustomerOverrideInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, BillingCustomerOverrideTable, BillingCustomerOverrideColumn), + ) +} +func newWorkflowConfigStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(WorkflowConfigInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, WorkflowConfigTable, WorkflowConfigColumn), + ) +} +func newTaxAppStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TaxAppInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, TaxAppTable, TaxAppColumn), + ) +} +func newInvoicingAppStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(InvoicingAppInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, InvoicingAppTable, InvoicingAppColumn), + ) +} +func newPaymentAppStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(PaymentAppInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, PaymentAppTable, PaymentAppColumn), + ) +} diff --git a/ent/db/billingprofile/where.go b/ent/db/billingprofile/where.go new file mode 100644 index 0000000000000000000000000000000000000000..b315f8defcbf47fab983e7dccad445d36fa1e22d --- /dev/null +++ b/ent/db/billingprofile/where.go @@ -0,0 +1,1620 @@ +// Code generated by ent, DO NOT EDIT. + +package billingprofile + +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/pkg/models" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.BillingProfile { + return predicate.BillingProfile(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.BillingProfile { + return predicate.BillingProfile(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.BillingProfile { + return predicate.BillingProfile(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.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldName, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldDescription, v)) +} + +// SupplierAddressCountry applies equality check predicate on the "supplier_address_country" field. It's identical to SupplierAddressCountryEQ. +func SupplierAddressCountry(v models.CountryCode) predicate.BillingProfile { + vc := string(v) + return predicate.BillingProfile(sql.FieldEQ(FieldSupplierAddressCountry, vc)) +} + +// SupplierAddressPostalCode applies equality check predicate on the "supplier_address_postal_code" field. It's identical to SupplierAddressPostalCodeEQ. +func SupplierAddressPostalCode(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldSupplierAddressPostalCode, v)) +} + +// SupplierAddressState applies equality check predicate on the "supplier_address_state" field. It's identical to SupplierAddressStateEQ. +func SupplierAddressState(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldSupplierAddressState, v)) +} + +// SupplierAddressCity applies equality check predicate on the "supplier_address_city" field. It's identical to SupplierAddressCityEQ. +func SupplierAddressCity(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldSupplierAddressCity, v)) +} + +// SupplierAddressLine1 applies equality check predicate on the "supplier_address_line1" field. It's identical to SupplierAddressLine1EQ. +func SupplierAddressLine1(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldSupplierAddressLine1, v)) +} + +// SupplierAddressLine2 applies equality check predicate on the "supplier_address_line2" field. It's identical to SupplierAddressLine2EQ. +func SupplierAddressLine2(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldSupplierAddressLine2, v)) +} + +// SupplierAddressPhoneNumber applies equality check predicate on the "supplier_address_phone_number" field. It's identical to SupplierAddressPhoneNumberEQ. +func SupplierAddressPhoneNumber(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldSupplierAddressPhoneNumber, v)) +} + +// TaxAppID applies equality check predicate on the "tax_app_id" field. It's identical to TaxAppIDEQ. +func TaxAppID(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldTaxAppID, v)) +} + +// InvoicingAppID applies equality check predicate on the "invoicing_app_id" field. It's identical to InvoicingAppIDEQ. +func InvoicingAppID(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldInvoicingAppID, v)) +} + +// PaymentAppID applies equality check predicate on the "payment_app_id" field. It's identical to PaymentAppIDEQ. +func PaymentAppID(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldPaymentAppID, v)) +} + +// WorkflowConfigID applies equality check predicate on the "workflow_config_id" field. It's identical to WorkflowConfigIDEQ. +func WorkflowConfigID(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldWorkflowConfigID, v)) +} + +// Default applies equality check predicate on the "default" field. It's identical to DefaultEQ. +func Default(v bool) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldDefault, v)) +} + +// SupplierName applies equality check predicate on the "supplier_name" field. It's identical to SupplierNameEQ. +func SupplierName(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldSupplierName, v)) +} + +// SupplierTaxCode applies equality check predicate on the "supplier_tax_code" field. It's identical to SupplierTaxCodeEQ. +func SupplierTaxCode(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldSupplierTaxCode, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContainsFold(FieldNamespace, v)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotNull(FieldMetadata)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotNull(FieldDeletedAt)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContainsFold(FieldName, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContainsFold(FieldDescription, v)) +} + +// SupplierAddressCountryEQ applies the EQ predicate on the "supplier_address_country" field. +func SupplierAddressCountryEQ(v models.CountryCode) predicate.BillingProfile { + vc := string(v) + return predicate.BillingProfile(sql.FieldEQ(FieldSupplierAddressCountry, vc)) +} + +// SupplierAddressCountryNEQ applies the NEQ predicate on the "supplier_address_country" field. +func SupplierAddressCountryNEQ(v models.CountryCode) predicate.BillingProfile { + vc := string(v) + return predicate.BillingProfile(sql.FieldNEQ(FieldSupplierAddressCountry, vc)) +} + +// SupplierAddressCountryIn applies the In predicate on the "supplier_address_country" field. +func SupplierAddressCountryIn(vs ...models.CountryCode) predicate.BillingProfile { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.BillingProfile(sql.FieldIn(FieldSupplierAddressCountry, v...)) +} + +// SupplierAddressCountryNotIn applies the NotIn predicate on the "supplier_address_country" field. +func SupplierAddressCountryNotIn(vs ...models.CountryCode) predicate.BillingProfile { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.BillingProfile(sql.FieldNotIn(FieldSupplierAddressCountry, v...)) +} + +// SupplierAddressCountryGT applies the GT predicate on the "supplier_address_country" field. +func SupplierAddressCountryGT(v models.CountryCode) predicate.BillingProfile { + vc := string(v) + return predicate.BillingProfile(sql.FieldGT(FieldSupplierAddressCountry, vc)) +} + +// SupplierAddressCountryGTE applies the GTE predicate on the "supplier_address_country" field. +func SupplierAddressCountryGTE(v models.CountryCode) predicate.BillingProfile { + vc := string(v) + return predicate.BillingProfile(sql.FieldGTE(FieldSupplierAddressCountry, vc)) +} + +// SupplierAddressCountryLT applies the LT predicate on the "supplier_address_country" field. +func SupplierAddressCountryLT(v models.CountryCode) predicate.BillingProfile { + vc := string(v) + return predicate.BillingProfile(sql.FieldLT(FieldSupplierAddressCountry, vc)) +} + +// SupplierAddressCountryLTE applies the LTE predicate on the "supplier_address_country" field. +func SupplierAddressCountryLTE(v models.CountryCode) predicate.BillingProfile { + vc := string(v) + return predicate.BillingProfile(sql.FieldLTE(FieldSupplierAddressCountry, vc)) +} + +// SupplierAddressCountryContains applies the Contains predicate on the "supplier_address_country" field. +func SupplierAddressCountryContains(v models.CountryCode) predicate.BillingProfile { + vc := string(v) + return predicate.BillingProfile(sql.FieldContains(FieldSupplierAddressCountry, vc)) +} + +// SupplierAddressCountryHasPrefix applies the HasPrefix predicate on the "supplier_address_country" field. +func SupplierAddressCountryHasPrefix(v models.CountryCode) predicate.BillingProfile { + vc := string(v) + return predicate.BillingProfile(sql.FieldHasPrefix(FieldSupplierAddressCountry, vc)) +} + +// SupplierAddressCountryHasSuffix applies the HasSuffix predicate on the "supplier_address_country" field. +func SupplierAddressCountryHasSuffix(v models.CountryCode) predicate.BillingProfile { + vc := string(v) + return predicate.BillingProfile(sql.FieldHasSuffix(FieldSupplierAddressCountry, vc)) +} + +// SupplierAddressCountryIsNil applies the IsNil predicate on the "supplier_address_country" field. +func SupplierAddressCountryIsNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIsNull(FieldSupplierAddressCountry)) +} + +// SupplierAddressCountryNotNil applies the NotNil predicate on the "supplier_address_country" field. +func SupplierAddressCountryNotNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotNull(FieldSupplierAddressCountry)) +} + +// SupplierAddressCountryEqualFold applies the EqualFold predicate on the "supplier_address_country" field. +func SupplierAddressCountryEqualFold(v models.CountryCode) predicate.BillingProfile { + vc := string(v) + return predicate.BillingProfile(sql.FieldEqualFold(FieldSupplierAddressCountry, vc)) +} + +// SupplierAddressCountryContainsFold applies the ContainsFold predicate on the "supplier_address_country" field. +func SupplierAddressCountryContainsFold(v models.CountryCode) predicate.BillingProfile { + vc := string(v) + return predicate.BillingProfile(sql.FieldContainsFold(FieldSupplierAddressCountry, vc)) +} + +// SupplierAddressPostalCodeEQ applies the EQ predicate on the "supplier_address_postal_code" field. +func SupplierAddressPostalCodeEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldSupplierAddressPostalCode, v)) +} + +// SupplierAddressPostalCodeNEQ applies the NEQ predicate on the "supplier_address_postal_code" field. +func SupplierAddressPostalCodeNEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNEQ(FieldSupplierAddressPostalCode, v)) +} + +// SupplierAddressPostalCodeIn applies the In predicate on the "supplier_address_postal_code" field. +func SupplierAddressPostalCodeIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIn(FieldSupplierAddressPostalCode, vs...)) +} + +// SupplierAddressPostalCodeNotIn applies the NotIn predicate on the "supplier_address_postal_code" field. +func SupplierAddressPostalCodeNotIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotIn(FieldSupplierAddressPostalCode, vs...)) +} + +// SupplierAddressPostalCodeGT applies the GT predicate on the "supplier_address_postal_code" field. +func SupplierAddressPostalCodeGT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGT(FieldSupplierAddressPostalCode, v)) +} + +// SupplierAddressPostalCodeGTE applies the GTE predicate on the "supplier_address_postal_code" field. +func SupplierAddressPostalCodeGTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGTE(FieldSupplierAddressPostalCode, v)) +} + +// SupplierAddressPostalCodeLT applies the LT predicate on the "supplier_address_postal_code" field. +func SupplierAddressPostalCodeLT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLT(FieldSupplierAddressPostalCode, v)) +} + +// SupplierAddressPostalCodeLTE applies the LTE predicate on the "supplier_address_postal_code" field. +func SupplierAddressPostalCodeLTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLTE(FieldSupplierAddressPostalCode, v)) +} + +// SupplierAddressPostalCodeContains applies the Contains predicate on the "supplier_address_postal_code" field. +func SupplierAddressPostalCodeContains(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContains(FieldSupplierAddressPostalCode, v)) +} + +// SupplierAddressPostalCodeHasPrefix applies the HasPrefix predicate on the "supplier_address_postal_code" field. +func SupplierAddressPostalCodeHasPrefix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasPrefix(FieldSupplierAddressPostalCode, v)) +} + +// SupplierAddressPostalCodeHasSuffix applies the HasSuffix predicate on the "supplier_address_postal_code" field. +func SupplierAddressPostalCodeHasSuffix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasSuffix(FieldSupplierAddressPostalCode, v)) +} + +// SupplierAddressPostalCodeIsNil applies the IsNil predicate on the "supplier_address_postal_code" field. +func SupplierAddressPostalCodeIsNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIsNull(FieldSupplierAddressPostalCode)) +} + +// SupplierAddressPostalCodeNotNil applies the NotNil predicate on the "supplier_address_postal_code" field. +func SupplierAddressPostalCodeNotNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotNull(FieldSupplierAddressPostalCode)) +} + +// SupplierAddressPostalCodeEqualFold applies the EqualFold predicate on the "supplier_address_postal_code" field. +func SupplierAddressPostalCodeEqualFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEqualFold(FieldSupplierAddressPostalCode, v)) +} + +// SupplierAddressPostalCodeContainsFold applies the ContainsFold predicate on the "supplier_address_postal_code" field. +func SupplierAddressPostalCodeContainsFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContainsFold(FieldSupplierAddressPostalCode, v)) +} + +// SupplierAddressStateEQ applies the EQ predicate on the "supplier_address_state" field. +func SupplierAddressStateEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldSupplierAddressState, v)) +} + +// SupplierAddressStateNEQ applies the NEQ predicate on the "supplier_address_state" field. +func SupplierAddressStateNEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNEQ(FieldSupplierAddressState, v)) +} + +// SupplierAddressStateIn applies the In predicate on the "supplier_address_state" field. +func SupplierAddressStateIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIn(FieldSupplierAddressState, vs...)) +} + +// SupplierAddressStateNotIn applies the NotIn predicate on the "supplier_address_state" field. +func SupplierAddressStateNotIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotIn(FieldSupplierAddressState, vs...)) +} + +// SupplierAddressStateGT applies the GT predicate on the "supplier_address_state" field. +func SupplierAddressStateGT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGT(FieldSupplierAddressState, v)) +} + +// SupplierAddressStateGTE applies the GTE predicate on the "supplier_address_state" field. +func SupplierAddressStateGTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGTE(FieldSupplierAddressState, v)) +} + +// SupplierAddressStateLT applies the LT predicate on the "supplier_address_state" field. +func SupplierAddressStateLT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLT(FieldSupplierAddressState, v)) +} + +// SupplierAddressStateLTE applies the LTE predicate on the "supplier_address_state" field. +func SupplierAddressStateLTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLTE(FieldSupplierAddressState, v)) +} + +// SupplierAddressStateContains applies the Contains predicate on the "supplier_address_state" field. +func SupplierAddressStateContains(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContains(FieldSupplierAddressState, v)) +} + +// SupplierAddressStateHasPrefix applies the HasPrefix predicate on the "supplier_address_state" field. +func SupplierAddressStateHasPrefix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasPrefix(FieldSupplierAddressState, v)) +} + +// SupplierAddressStateHasSuffix applies the HasSuffix predicate on the "supplier_address_state" field. +func SupplierAddressStateHasSuffix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasSuffix(FieldSupplierAddressState, v)) +} + +// SupplierAddressStateIsNil applies the IsNil predicate on the "supplier_address_state" field. +func SupplierAddressStateIsNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIsNull(FieldSupplierAddressState)) +} + +// SupplierAddressStateNotNil applies the NotNil predicate on the "supplier_address_state" field. +func SupplierAddressStateNotNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotNull(FieldSupplierAddressState)) +} + +// SupplierAddressStateEqualFold applies the EqualFold predicate on the "supplier_address_state" field. +func SupplierAddressStateEqualFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEqualFold(FieldSupplierAddressState, v)) +} + +// SupplierAddressStateContainsFold applies the ContainsFold predicate on the "supplier_address_state" field. +func SupplierAddressStateContainsFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContainsFold(FieldSupplierAddressState, v)) +} + +// SupplierAddressCityEQ applies the EQ predicate on the "supplier_address_city" field. +func SupplierAddressCityEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldSupplierAddressCity, v)) +} + +// SupplierAddressCityNEQ applies the NEQ predicate on the "supplier_address_city" field. +func SupplierAddressCityNEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNEQ(FieldSupplierAddressCity, v)) +} + +// SupplierAddressCityIn applies the In predicate on the "supplier_address_city" field. +func SupplierAddressCityIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIn(FieldSupplierAddressCity, vs...)) +} + +// SupplierAddressCityNotIn applies the NotIn predicate on the "supplier_address_city" field. +func SupplierAddressCityNotIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotIn(FieldSupplierAddressCity, vs...)) +} + +// SupplierAddressCityGT applies the GT predicate on the "supplier_address_city" field. +func SupplierAddressCityGT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGT(FieldSupplierAddressCity, v)) +} + +// SupplierAddressCityGTE applies the GTE predicate on the "supplier_address_city" field. +func SupplierAddressCityGTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGTE(FieldSupplierAddressCity, v)) +} + +// SupplierAddressCityLT applies the LT predicate on the "supplier_address_city" field. +func SupplierAddressCityLT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLT(FieldSupplierAddressCity, v)) +} + +// SupplierAddressCityLTE applies the LTE predicate on the "supplier_address_city" field. +func SupplierAddressCityLTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLTE(FieldSupplierAddressCity, v)) +} + +// SupplierAddressCityContains applies the Contains predicate on the "supplier_address_city" field. +func SupplierAddressCityContains(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContains(FieldSupplierAddressCity, v)) +} + +// SupplierAddressCityHasPrefix applies the HasPrefix predicate on the "supplier_address_city" field. +func SupplierAddressCityHasPrefix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasPrefix(FieldSupplierAddressCity, v)) +} + +// SupplierAddressCityHasSuffix applies the HasSuffix predicate on the "supplier_address_city" field. +func SupplierAddressCityHasSuffix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasSuffix(FieldSupplierAddressCity, v)) +} + +// SupplierAddressCityIsNil applies the IsNil predicate on the "supplier_address_city" field. +func SupplierAddressCityIsNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIsNull(FieldSupplierAddressCity)) +} + +// SupplierAddressCityNotNil applies the NotNil predicate on the "supplier_address_city" field. +func SupplierAddressCityNotNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotNull(FieldSupplierAddressCity)) +} + +// SupplierAddressCityEqualFold applies the EqualFold predicate on the "supplier_address_city" field. +func SupplierAddressCityEqualFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEqualFold(FieldSupplierAddressCity, v)) +} + +// SupplierAddressCityContainsFold applies the ContainsFold predicate on the "supplier_address_city" field. +func SupplierAddressCityContainsFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContainsFold(FieldSupplierAddressCity, v)) +} + +// SupplierAddressLine1EQ applies the EQ predicate on the "supplier_address_line1" field. +func SupplierAddressLine1EQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldSupplierAddressLine1, v)) +} + +// SupplierAddressLine1NEQ applies the NEQ predicate on the "supplier_address_line1" field. +func SupplierAddressLine1NEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNEQ(FieldSupplierAddressLine1, v)) +} + +// SupplierAddressLine1In applies the In predicate on the "supplier_address_line1" field. +func SupplierAddressLine1In(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIn(FieldSupplierAddressLine1, vs...)) +} + +// SupplierAddressLine1NotIn applies the NotIn predicate on the "supplier_address_line1" field. +func SupplierAddressLine1NotIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotIn(FieldSupplierAddressLine1, vs...)) +} + +// SupplierAddressLine1GT applies the GT predicate on the "supplier_address_line1" field. +func SupplierAddressLine1GT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGT(FieldSupplierAddressLine1, v)) +} + +// SupplierAddressLine1GTE applies the GTE predicate on the "supplier_address_line1" field. +func SupplierAddressLine1GTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGTE(FieldSupplierAddressLine1, v)) +} + +// SupplierAddressLine1LT applies the LT predicate on the "supplier_address_line1" field. +func SupplierAddressLine1LT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLT(FieldSupplierAddressLine1, v)) +} + +// SupplierAddressLine1LTE applies the LTE predicate on the "supplier_address_line1" field. +func SupplierAddressLine1LTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLTE(FieldSupplierAddressLine1, v)) +} + +// SupplierAddressLine1Contains applies the Contains predicate on the "supplier_address_line1" field. +func SupplierAddressLine1Contains(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContains(FieldSupplierAddressLine1, v)) +} + +// SupplierAddressLine1HasPrefix applies the HasPrefix predicate on the "supplier_address_line1" field. +func SupplierAddressLine1HasPrefix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasPrefix(FieldSupplierAddressLine1, v)) +} + +// SupplierAddressLine1HasSuffix applies the HasSuffix predicate on the "supplier_address_line1" field. +func SupplierAddressLine1HasSuffix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasSuffix(FieldSupplierAddressLine1, v)) +} + +// SupplierAddressLine1IsNil applies the IsNil predicate on the "supplier_address_line1" field. +func SupplierAddressLine1IsNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIsNull(FieldSupplierAddressLine1)) +} + +// SupplierAddressLine1NotNil applies the NotNil predicate on the "supplier_address_line1" field. +func SupplierAddressLine1NotNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotNull(FieldSupplierAddressLine1)) +} + +// SupplierAddressLine1EqualFold applies the EqualFold predicate on the "supplier_address_line1" field. +func SupplierAddressLine1EqualFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEqualFold(FieldSupplierAddressLine1, v)) +} + +// SupplierAddressLine1ContainsFold applies the ContainsFold predicate on the "supplier_address_line1" field. +func SupplierAddressLine1ContainsFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContainsFold(FieldSupplierAddressLine1, v)) +} + +// SupplierAddressLine2EQ applies the EQ predicate on the "supplier_address_line2" field. +func SupplierAddressLine2EQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldSupplierAddressLine2, v)) +} + +// SupplierAddressLine2NEQ applies the NEQ predicate on the "supplier_address_line2" field. +func SupplierAddressLine2NEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNEQ(FieldSupplierAddressLine2, v)) +} + +// SupplierAddressLine2In applies the In predicate on the "supplier_address_line2" field. +func SupplierAddressLine2In(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIn(FieldSupplierAddressLine2, vs...)) +} + +// SupplierAddressLine2NotIn applies the NotIn predicate on the "supplier_address_line2" field. +func SupplierAddressLine2NotIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotIn(FieldSupplierAddressLine2, vs...)) +} + +// SupplierAddressLine2GT applies the GT predicate on the "supplier_address_line2" field. +func SupplierAddressLine2GT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGT(FieldSupplierAddressLine2, v)) +} + +// SupplierAddressLine2GTE applies the GTE predicate on the "supplier_address_line2" field. +func SupplierAddressLine2GTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGTE(FieldSupplierAddressLine2, v)) +} + +// SupplierAddressLine2LT applies the LT predicate on the "supplier_address_line2" field. +func SupplierAddressLine2LT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLT(FieldSupplierAddressLine2, v)) +} + +// SupplierAddressLine2LTE applies the LTE predicate on the "supplier_address_line2" field. +func SupplierAddressLine2LTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLTE(FieldSupplierAddressLine2, v)) +} + +// SupplierAddressLine2Contains applies the Contains predicate on the "supplier_address_line2" field. +func SupplierAddressLine2Contains(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContains(FieldSupplierAddressLine2, v)) +} + +// SupplierAddressLine2HasPrefix applies the HasPrefix predicate on the "supplier_address_line2" field. +func SupplierAddressLine2HasPrefix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasPrefix(FieldSupplierAddressLine2, v)) +} + +// SupplierAddressLine2HasSuffix applies the HasSuffix predicate on the "supplier_address_line2" field. +func SupplierAddressLine2HasSuffix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasSuffix(FieldSupplierAddressLine2, v)) +} + +// SupplierAddressLine2IsNil applies the IsNil predicate on the "supplier_address_line2" field. +func SupplierAddressLine2IsNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIsNull(FieldSupplierAddressLine2)) +} + +// SupplierAddressLine2NotNil applies the NotNil predicate on the "supplier_address_line2" field. +func SupplierAddressLine2NotNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotNull(FieldSupplierAddressLine2)) +} + +// SupplierAddressLine2EqualFold applies the EqualFold predicate on the "supplier_address_line2" field. +func SupplierAddressLine2EqualFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEqualFold(FieldSupplierAddressLine2, v)) +} + +// SupplierAddressLine2ContainsFold applies the ContainsFold predicate on the "supplier_address_line2" field. +func SupplierAddressLine2ContainsFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContainsFold(FieldSupplierAddressLine2, v)) +} + +// SupplierAddressPhoneNumberEQ applies the EQ predicate on the "supplier_address_phone_number" field. +func SupplierAddressPhoneNumberEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldSupplierAddressPhoneNumber, v)) +} + +// SupplierAddressPhoneNumberNEQ applies the NEQ predicate on the "supplier_address_phone_number" field. +func SupplierAddressPhoneNumberNEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNEQ(FieldSupplierAddressPhoneNumber, v)) +} + +// SupplierAddressPhoneNumberIn applies the In predicate on the "supplier_address_phone_number" field. +func SupplierAddressPhoneNumberIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIn(FieldSupplierAddressPhoneNumber, vs...)) +} + +// SupplierAddressPhoneNumberNotIn applies the NotIn predicate on the "supplier_address_phone_number" field. +func SupplierAddressPhoneNumberNotIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotIn(FieldSupplierAddressPhoneNumber, vs...)) +} + +// SupplierAddressPhoneNumberGT applies the GT predicate on the "supplier_address_phone_number" field. +func SupplierAddressPhoneNumberGT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGT(FieldSupplierAddressPhoneNumber, v)) +} + +// SupplierAddressPhoneNumberGTE applies the GTE predicate on the "supplier_address_phone_number" field. +func SupplierAddressPhoneNumberGTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGTE(FieldSupplierAddressPhoneNumber, v)) +} + +// SupplierAddressPhoneNumberLT applies the LT predicate on the "supplier_address_phone_number" field. +func SupplierAddressPhoneNumberLT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLT(FieldSupplierAddressPhoneNumber, v)) +} + +// SupplierAddressPhoneNumberLTE applies the LTE predicate on the "supplier_address_phone_number" field. +func SupplierAddressPhoneNumberLTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLTE(FieldSupplierAddressPhoneNumber, v)) +} + +// SupplierAddressPhoneNumberContains applies the Contains predicate on the "supplier_address_phone_number" field. +func SupplierAddressPhoneNumberContains(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContains(FieldSupplierAddressPhoneNumber, v)) +} + +// SupplierAddressPhoneNumberHasPrefix applies the HasPrefix predicate on the "supplier_address_phone_number" field. +func SupplierAddressPhoneNumberHasPrefix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasPrefix(FieldSupplierAddressPhoneNumber, v)) +} + +// SupplierAddressPhoneNumberHasSuffix applies the HasSuffix predicate on the "supplier_address_phone_number" field. +func SupplierAddressPhoneNumberHasSuffix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasSuffix(FieldSupplierAddressPhoneNumber, v)) +} + +// SupplierAddressPhoneNumberIsNil applies the IsNil predicate on the "supplier_address_phone_number" field. +func SupplierAddressPhoneNumberIsNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIsNull(FieldSupplierAddressPhoneNumber)) +} + +// SupplierAddressPhoneNumberNotNil applies the NotNil predicate on the "supplier_address_phone_number" field. +func SupplierAddressPhoneNumberNotNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotNull(FieldSupplierAddressPhoneNumber)) +} + +// SupplierAddressPhoneNumberEqualFold applies the EqualFold predicate on the "supplier_address_phone_number" field. +func SupplierAddressPhoneNumberEqualFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEqualFold(FieldSupplierAddressPhoneNumber, v)) +} + +// SupplierAddressPhoneNumberContainsFold applies the ContainsFold predicate on the "supplier_address_phone_number" field. +func SupplierAddressPhoneNumberContainsFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContainsFold(FieldSupplierAddressPhoneNumber, v)) +} + +// TaxAppIDEQ applies the EQ predicate on the "tax_app_id" field. +func TaxAppIDEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldTaxAppID, v)) +} + +// TaxAppIDNEQ applies the NEQ predicate on the "tax_app_id" field. +func TaxAppIDNEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNEQ(FieldTaxAppID, v)) +} + +// TaxAppIDIn applies the In predicate on the "tax_app_id" field. +func TaxAppIDIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIn(FieldTaxAppID, vs...)) +} + +// TaxAppIDNotIn applies the NotIn predicate on the "tax_app_id" field. +func TaxAppIDNotIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotIn(FieldTaxAppID, vs...)) +} + +// TaxAppIDGT applies the GT predicate on the "tax_app_id" field. +func TaxAppIDGT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGT(FieldTaxAppID, v)) +} + +// TaxAppIDGTE applies the GTE predicate on the "tax_app_id" field. +func TaxAppIDGTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGTE(FieldTaxAppID, v)) +} + +// TaxAppIDLT applies the LT predicate on the "tax_app_id" field. +func TaxAppIDLT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLT(FieldTaxAppID, v)) +} + +// TaxAppIDLTE applies the LTE predicate on the "tax_app_id" field. +func TaxAppIDLTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLTE(FieldTaxAppID, v)) +} + +// TaxAppIDContains applies the Contains predicate on the "tax_app_id" field. +func TaxAppIDContains(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContains(FieldTaxAppID, v)) +} + +// TaxAppIDHasPrefix applies the HasPrefix predicate on the "tax_app_id" field. +func TaxAppIDHasPrefix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasPrefix(FieldTaxAppID, v)) +} + +// TaxAppIDHasSuffix applies the HasSuffix predicate on the "tax_app_id" field. +func TaxAppIDHasSuffix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasSuffix(FieldTaxAppID, v)) +} + +// TaxAppIDEqualFold applies the EqualFold predicate on the "tax_app_id" field. +func TaxAppIDEqualFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEqualFold(FieldTaxAppID, v)) +} + +// TaxAppIDContainsFold applies the ContainsFold predicate on the "tax_app_id" field. +func TaxAppIDContainsFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContainsFold(FieldTaxAppID, v)) +} + +// InvoicingAppIDEQ applies the EQ predicate on the "invoicing_app_id" field. +func InvoicingAppIDEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldInvoicingAppID, v)) +} + +// InvoicingAppIDNEQ applies the NEQ predicate on the "invoicing_app_id" field. +func InvoicingAppIDNEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNEQ(FieldInvoicingAppID, v)) +} + +// InvoicingAppIDIn applies the In predicate on the "invoicing_app_id" field. +func InvoicingAppIDIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIn(FieldInvoicingAppID, vs...)) +} + +// InvoicingAppIDNotIn applies the NotIn predicate on the "invoicing_app_id" field. +func InvoicingAppIDNotIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotIn(FieldInvoicingAppID, vs...)) +} + +// InvoicingAppIDGT applies the GT predicate on the "invoicing_app_id" field. +func InvoicingAppIDGT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGT(FieldInvoicingAppID, v)) +} + +// InvoicingAppIDGTE applies the GTE predicate on the "invoicing_app_id" field. +func InvoicingAppIDGTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGTE(FieldInvoicingAppID, v)) +} + +// InvoicingAppIDLT applies the LT predicate on the "invoicing_app_id" field. +func InvoicingAppIDLT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLT(FieldInvoicingAppID, v)) +} + +// InvoicingAppIDLTE applies the LTE predicate on the "invoicing_app_id" field. +func InvoicingAppIDLTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLTE(FieldInvoicingAppID, v)) +} + +// InvoicingAppIDContains applies the Contains predicate on the "invoicing_app_id" field. +func InvoicingAppIDContains(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContains(FieldInvoicingAppID, v)) +} + +// InvoicingAppIDHasPrefix applies the HasPrefix predicate on the "invoicing_app_id" field. +func InvoicingAppIDHasPrefix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasPrefix(FieldInvoicingAppID, v)) +} + +// InvoicingAppIDHasSuffix applies the HasSuffix predicate on the "invoicing_app_id" field. +func InvoicingAppIDHasSuffix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasSuffix(FieldInvoicingAppID, v)) +} + +// InvoicingAppIDEqualFold applies the EqualFold predicate on the "invoicing_app_id" field. +func InvoicingAppIDEqualFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEqualFold(FieldInvoicingAppID, v)) +} + +// InvoicingAppIDContainsFold applies the ContainsFold predicate on the "invoicing_app_id" field. +func InvoicingAppIDContainsFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContainsFold(FieldInvoicingAppID, v)) +} + +// PaymentAppIDEQ applies the EQ predicate on the "payment_app_id" field. +func PaymentAppIDEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldPaymentAppID, v)) +} + +// PaymentAppIDNEQ applies the NEQ predicate on the "payment_app_id" field. +func PaymentAppIDNEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNEQ(FieldPaymentAppID, v)) +} + +// PaymentAppIDIn applies the In predicate on the "payment_app_id" field. +func PaymentAppIDIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIn(FieldPaymentAppID, vs...)) +} + +// PaymentAppIDNotIn applies the NotIn predicate on the "payment_app_id" field. +func PaymentAppIDNotIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotIn(FieldPaymentAppID, vs...)) +} + +// PaymentAppIDGT applies the GT predicate on the "payment_app_id" field. +func PaymentAppIDGT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGT(FieldPaymentAppID, v)) +} + +// PaymentAppIDGTE applies the GTE predicate on the "payment_app_id" field. +func PaymentAppIDGTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGTE(FieldPaymentAppID, v)) +} + +// PaymentAppIDLT applies the LT predicate on the "payment_app_id" field. +func PaymentAppIDLT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLT(FieldPaymentAppID, v)) +} + +// PaymentAppIDLTE applies the LTE predicate on the "payment_app_id" field. +func PaymentAppIDLTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLTE(FieldPaymentAppID, v)) +} + +// PaymentAppIDContains applies the Contains predicate on the "payment_app_id" field. +func PaymentAppIDContains(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContains(FieldPaymentAppID, v)) +} + +// PaymentAppIDHasPrefix applies the HasPrefix predicate on the "payment_app_id" field. +func PaymentAppIDHasPrefix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasPrefix(FieldPaymentAppID, v)) +} + +// PaymentAppIDHasSuffix applies the HasSuffix predicate on the "payment_app_id" field. +func PaymentAppIDHasSuffix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasSuffix(FieldPaymentAppID, v)) +} + +// PaymentAppIDEqualFold applies the EqualFold predicate on the "payment_app_id" field. +func PaymentAppIDEqualFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEqualFold(FieldPaymentAppID, v)) +} + +// PaymentAppIDContainsFold applies the ContainsFold predicate on the "payment_app_id" field. +func PaymentAppIDContainsFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContainsFold(FieldPaymentAppID, v)) +} + +// WorkflowConfigIDEQ applies the EQ predicate on the "workflow_config_id" field. +func WorkflowConfigIDEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldWorkflowConfigID, v)) +} + +// WorkflowConfigIDNEQ applies the NEQ predicate on the "workflow_config_id" field. +func WorkflowConfigIDNEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNEQ(FieldWorkflowConfigID, v)) +} + +// WorkflowConfigIDIn applies the In predicate on the "workflow_config_id" field. +func WorkflowConfigIDIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIn(FieldWorkflowConfigID, vs...)) +} + +// WorkflowConfigIDNotIn applies the NotIn predicate on the "workflow_config_id" field. +func WorkflowConfigIDNotIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotIn(FieldWorkflowConfigID, vs...)) +} + +// WorkflowConfigIDGT applies the GT predicate on the "workflow_config_id" field. +func WorkflowConfigIDGT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGT(FieldWorkflowConfigID, v)) +} + +// WorkflowConfigIDGTE applies the GTE predicate on the "workflow_config_id" field. +func WorkflowConfigIDGTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGTE(FieldWorkflowConfigID, v)) +} + +// WorkflowConfigIDLT applies the LT predicate on the "workflow_config_id" field. +func WorkflowConfigIDLT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLT(FieldWorkflowConfigID, v)) +} + +// WorkflowConfigIDLTE applies the LTE predicate on the "workflow_config_id" field. +func WorkflowConfigIDLTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLTE(FieldWorkflowConfigID, v)) +} + +// WorkflowConfigIDContains applies the Contains predicate on the "workflow_config_id" field. +func WorkflowConfigIDContains(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContains(FieldWorkflowConfigID, v)) +} + +// WorkflowConfigIDHasPrefix applies the HasPrefix predicate on the "workflow_config_id" field. +func WorkflowConfigIDHasPrefix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasPrefix(FieldWorkflowConfigID, v)) +} + +// WorkflowConfigIDHasSuffix applies the HasSuffix predicate on the "workflow_config_id" field. +func WorkflowConfigIDHasSuffix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasSuffix(FieldWorkflowConfigID, v)) +} + +// WorkflowConfigIDEqualFold applies the EqualFold predicate on the "workflow_config_id" field. +func WorkflowConfigIDEqualFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEqualFold(FieldWorkflowConfigID, v)) +} + +// WorkflowConfigIDContainsFold applies the ContainsFold predicate on the "workflow_config_id" field. +func WorkflowConfigIDContainsFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContainsFold(FieldWorkflowConfigID, v)) +} + +// DefaultEQ applies the EQ predicate on the "default" field. +func DefaultEQ(v bool) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldDefault, v)) +} + +// DefaultNEQ applies the NEQ predicate on the "default" field. +func DefaultNEQ(v bool) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNEQ(FieldDefault, v)) +} + +// SupplierNameEQ applies the EQ predicate on the "supplier_name" field. +func SupplierNameEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldSupplierName, v)) +} + +// SupplierNameNEQ applies the NEQ predicate on the "supplier_name" field. +func SupplierNameNEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNEQ(FieldSupplierName, v)) +} + +// SupplierNameIn applies the In predicate on the "supplier_name" field. +func SupplierNameIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIn(FieldSupplierName, vs...)) +} + +// SupplierNameNotIn applies the NotIn predicate on the "supplier_name" field. +func SupplierNameNotIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotIn(FieldSupplierName, vs...)) +} + +// SupplierNameGT applies the GT predicate on the "supplier_name" field. +func SupplierNameGT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGT(FieldSupplierName, v)) +} + +// SupplierNameGTE applies the GTE predicate on the "supplier_name" field. +func SupplierNameGTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGTE(FieldSupplierName, v)) +} + +// SupplierNameLT applies the LT predicate on the "supplier_name" field. +func SupplierNameLT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLT(FieldSupplierName, v)) +} + +// SupplierNameLTE applies the LTE predicate on the "supplier_name" field. +func SupplierNameLTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLTE(FieldSupplierName, v)) +} + +// SupplierNameContains applies the Contains predicate on the "supplier_name" field. +func SupplierNameContains(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContains(FieldSupplierName, v)) +} + +// SupplierNameHasPrefix applies the HasPrefix predicate on the "supplier_name" field. +func SupplierNameHasPrefix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasPrefix(FieldSupplierName, v)) +} + +// SupplierNameHasSuffix applies the HasSuffix predicate on the "supplier_name" field. +func SupplierNameHasSuffix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasSuffix(FieldSupplierName, v)) +} + +// SupplierNameEqualFold applies the EqualFold predicate on the "supplier_name" field. +func SupplierNameEqualFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEqualFold(FieldSupplierName, v)) +} + +// SupplierNameContainsFold applies the ContainsFold predicate on the "supplier_name" field. +func SupplierNameContainsFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContainsFold(FieldSupplierName, v)) +} + +// SupplierTaxCodeEQ applies the EQ predicate on the "supplier_tax_code" field. +func SupplierTaxCodeEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEQ(FieldSupplierTaxCode, v)) +} + +// SupplierTaxCodeNEQ applies the NEQ predicate on the "supplier_tax_code" field. +func SupplierTaxCodeNEQ(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNEQ(FieldSupplierTaxCode, v)) +} + +// SupplierTaxCodeIn applies the In predicate on the "supplier_tax_code" field. +func SupplierTaxCodeIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIn(FieldSupplierTaxCode, vs...)) +} + +// SupplierTaxCodeNotIn applies the NotIn predicate on the "supplier_tax_code" field. +func SupplierTaxCodeNotIn(vs ...string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotIn(FieldSupplierTaxCode, vs...)) +} + +// SupplierTaxCodeGT applies the GT predicate on the "supplier_tax_code" field. +func SupplierTaxCodeGT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGT(FieldSupplierTaxCode, v)) +} + +// SupplierTaxCodeGTE applies the GTE predicate on the "supplier_tax_code" field. +func SupplierTaxCodeGTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldGTE(FieldSupplierTaxCode, v)) +} + +// SupplierTaxCodeLT applies the LT predicate on the "supplier_tax_code" field. +func SupplierTaxCodeLT(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLT(FieldSupplierTaxCode, v)) +} + +// SupplierTaxCodeLTE applies the LTE predicate on the "supplier_tax_code" field. +func SupplierTaxCodeLTE(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldLTE(FieldSupplierTaxCode, v)) +} + +// SupplierTaxCodeContains applies the Contains predicate on the "supplier_tax_code" field. +func SupplierTaxCodeContains(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContains(FieldSupplierTaxCode, v)) +} + +// SupplierTaxCodeHasPrefix applies the HasPrefix predicate on the "supplier_tax_code" field. +func SupplierTaxCodeHasPrefix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasPrefix(FieldSupplierTaxCode, v)) +} + +// SupplierTaxCodeHasSuffix applies the HasSuffix predicate on the "supplier_tax_code" field. +func SupplierTaxCodeHasSuffix(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldHasSuffix(FieldSupplierTaxCode, v)) +} + +// SupplierTaxCodeIsNil applies the IsNil predicate on the "supplier_tax_code" field. +func SupplierTaxCodeIsNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldIsNull(FieldSupplierTaxCode)) +} + +// SupplierTaxCodeNotNil applies the NotNil predicate on the "supplier_tax_code" field. +func SupplierTaxCodeNotNil() predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldNotNull(FieldSupplierTaxCode)) +} + +// SupplierTaxCodeEqualFold applies the EqualFold predicate on the "supplier_tax_code" field. +func SupplierTaxCodeEqualFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldEqualFold(FieldSupplierTaxCode, v)) +} + +// SupplierTaxCodeContainsFold applies the ContainsFold predicate on the "supplier_tax_code" field. +func SupplierTaxCodeContainsFold(v string) predicate.BillingProfile { + return predicate.BillingProfile(sql.FieldContainsFold(FieldSupplierTaxCode, v)) +} + +// HasBillingInvoices applies the HasEdge predicate on the "billing_invoices" edge. +func HasBillingInvoices() predicate.BillingProfile { + return predicate.BillingProfile(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, BillingInvoicesTable, BillingInvoicesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBillingInvoicesWith applies the HasEdge predicate on the "billing_invoices" edge with a given conditions (other predicates). +func HasBillingInvoicesWith(preds ...predicate.BillingInvoice) predicate.BillingProfile { + return predicate.BillingProfile(func(s *sql.Selector) { + step := newBillingInvoicesStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasBillingCustomerOverride applies the HasEdge predicate on the "billing_customer_override" edge. +func HasBillingCustomerOverride() predicate.BillingProfile { + return predicate.BillingProfile(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, BillingCustomerOverrideTable, BillingCustomerOverrideColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBillingCustomerOverrideWith applies the HasEdge predicate on the "billing_customer_override" edge with a given conditions (other predicates). +func HasBillingCustomerOverrideWith(preds ...predicate.BillingCustomerOverride) predicate.BillingProfile { + return predicate.BillingProfile(func(s *sql.Selector) { + step := newBillingCustomerOverrideStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasWorkflowConfig applies the HasEdge predicate on the "workflow_config" edge. +func HasWorkflowConfig() predicate.BillingProfile { + return predicate.BillingProfile(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, WorkflowConfigTable, WorkflowConfigColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasWorkflowConfigWith applies the HasEdge predicate on the "workflow_config" edge with a given conditions (other predicates). +func HasWorkflowConfigWith(preds ...predicate.BillingWorkflowConfig) predicate.BillingProfile { + return predicate.BillingProfile(func(s *sql.Selector) { + step := newWorkflowConfigStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasTaxApp applies the HasEdge predicate on the "tax_app" edge. +func HasTaxApp() predicate.BillingProfile { + return predicate.BillingProfile(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, TaxAppTable, TaxAppColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTaxAppWith applies the HasEdge predicate on the "tax_app" edge with a given conditions (other predicates). +func HasTaxAppWith(preds ...predicate.App) predicate.BillingProfile { + return predicate.BillingProfile(func(s *sql.Selector) { + step := newTaxAppStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasInvoicingApp applies the HasEdge predicate on the "invoicing_app" edge. +func HasInvoicingApp() predicate.BillingProfile { + return predicate.BillingProfile(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, InvoicingAppTable, InvoicingAppColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasInvoicingAppWith applies the HasEdge predicate on the "invoicing_app" edge with a given conditions (other predicates). +func HasInvoicingAppWith(preds ...predicate.App) predicate.BillingProfile { + return predicate.BillingProfile(func(s *sql.Selector) { + step := newInvoicingAppStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasPaymentApp applies the HasEdge predicate on the "payment_app" edge. +func HasPaymentApp() predicate.BillingProfile { + return predicate.BillingProfile(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, PaymentAppTable, PaymentAppColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasPaymentAppWith applies the HasEdge predicate on the "payment_app" edge with a given conditions (other predicates). +func HasPaymentAppWith(preds ...predicate.App) predicate.BillingProfile { + return predicate.BillingProfile(func(s *sql.Selector) { + step := newPaymentAppStep() + 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.BillingProfile) predicate.BillingProfile { + return predicate.BillingProfile(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.BillingProfile) predicate.BillingProfile { + return predicate.BillingProfile(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.BillingProfile) predicate.BillingProfile { + return predicate.BillingProfile(sql.NotPredicates(p)) +} diff --git a/ent/db/billingprofile_create.go b/ent/db/billingprofile_create.go new file mode 100644 index 0000000000000000000000000000000000000000..8fa5e8e560794e8846854f3f35fe0851dcf313ef --- /dev/null +++ b/ent/db/billingprofile_create.go @@ -0,0 +1,1872 @@ +// 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" + dbapp "github.com/openmeterio/openmeter/openmeter/ent/db/app" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingcustomeroverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingprofile" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingworkflowconfig" + "github.com/openmeterio/openmeter/pkg/models" +) + +// BillingProfileCreate is the builder for creating a BillingProfile entity. +type BillingProfileCreate struct { + config + mutation *BillingProfileMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *BillingProfileCreate) SetNamespace(v string) *BillingProfileCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetMetadata sets the "metadata" field. +func (_c *BillingProfileCreate) SetMetadata(v map[string]string) *BillingProfileCreate { + _c.mutation.SetMetadata(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *BillingProfileCreate) SetCreatedAt(v time.Time) *BillingProfileCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *BillingProfileCreate) SetNillableCreatedAt(v *time.Time) *BillingProfileCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *BillingProfileCreate) SetUpdatedAt(v time.Time) *BillingProfileCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *BillingProfileCreate) SetNillableUpdatedAt(v *time.Time) *BillingProfileCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *BillingProfileCreate) SetDeletedAt(v time.Time) *BillingProfileCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *BillingProfileCreate) SetNillableDeletedAt(v *time.Time) *BillingProfileCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetName sets the "name" field. +func (_c *BillingProfileCreate) SetName(v string) *BillingProfileCreate { + _c.mutation.SetName(v) + return _c +} + +// SetDescription sets the "description" field. +func (_c *BillingProfileCreate) SetDescription(v string) *BillingProfileCreate { + _c.mutation.SetDescription(v) + return _c +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_c *BillingProfileCreate) SetNillableDescription(v *string) *BillingProfileCreate { + if v != nil { + _c.SetDescription(*v) + } + return _c +} + +// SetSupplierAddressCountry sets the "supplier_address_country" field. +func (_c *BillingProfileCreate) SetSupplierAddressCountry(v models.CountryCode) *BillingProfileCreate { + _c.mutation.SetSupplierAddressCountry(v) + return _c +} + +// SetNillableSupplierAddressCountry sets the "supplier_address_country" field if the given value is not nil. +func (_c *BillingProfileCreate) SetNillableSupplierAddressCountry(v *models.CountryCode) *BillingProfileCreate { + if v != nil { + _c.SetSupplierAddressCountry(*v) + } + return _c +} + +// SetSupplierAddressPostalCode sets the "supplier_address_postal_code" field. +func (_c *BillingProfileCreate) SetSupplierAddressPostalCode(v string) *BillingProfileCreate { + _c.mutation.SetSupplierAddressPostalCode(v) + return _c +} + +// SetNillableSupplierAddressPostalCode sets the "supplier_address_postal_code" field if the given value is not nil. +func (_c *BillingProfileCreate) SetNillableSupplierAddressPostalCode(v *string) *BillingProfileCreate { + if v != nil { + _c.SetSupplierAddressPostalCode(*v) + } + return _c +} + +// SetSupplierAddressState sets the "supplier_address_state" field. +func (_c *BillingProfileCreate) SetSupplierAddressState(v string) *BillingProfileCreate { + _c.mutation.SetSupplierAddressState(v) + return _c +} + +// SetNillableSupplierAddressState sets the "supplier_address_state" field if the given value is not nil. +func (_c *BillingProfileCreate) SetNillableSupplierAddressState(v *string) *BillingProfileCreate { + if v != nil { + _c.SetSupplierAddressState(*v) + } + return _c +} + +// SetSupplierAddressCity sets the "supplier_address_city" field. +func (_c *BillingProfileCreate) SetSupplierAddressCity(v string) *BillingProfileCreate { + _c.mutation.SetSupplierAddressCity(v) + return _c +} + +// SetNillableSupplierAddressCity sets the "supplier_address_city" field if the given value is not nil. +func (_c *BillingProfileCreate) SetNillableSupplierAddressCity(v *string) *BillingProfileCreate { + if v != nil { + _c.SetSupplierAddressCity(*v) + } + return _c +} + +// SetSupplierAddressLine1 sets the "supplier_address_line1" field. +func (_c *BillingProfileCreate) SetSupplierAddressLine1(v string) *BillingProfileCreate { + _c.mutation.SetSupplierAddressLine1(v) + return _c +} + +// SetNillableSupplierAddressLine1 sets the "supplier_address_line1" field if the given value is not nil. +func (_c *BillingProfileCreate) SetNillableSupplierAddressLine1(v *string) *BillingProfileCreate { + if v != nil { + _c.SetSupplierAddressLine1(*v) + } + return _c +} + +// SetSupplierAddressLine2 sets the "supplier_address_line2" field. +func (_c *BillingProfileCreate) SetSupplierAddressLine2(v string) *BillingProfileCreate { + _c.mutation.SetSupplierAddressLine2(v) + return _c +} + +// SetNillableSupplierAddressLine2 sets the "supplier_address_line2" field if the given value is not nil. +func (_c *BillingProfileCreate) SetNillableSupplierAddressLine2(v *string) *BillingProfileCreate { + if v != nil { + _c.SetSupplierAddressLine2(*v) + } + return _c +} + +// SetSupplierAddressPhoneNumber sets the "supplier_address_phone_number" field. +func (_c *BillingProfileCreate) SetSupplierAddressPhoneNumber(v string) *BillingProfileCreate { + _c.mutation.SetSupplierAddressPhoneNumber(v) + return _c +} + +// SetNillableSupplierAddressPhoneNumber sets the "supplier_address_phone_number" field if the given value is not nil. +func (_c *BillingProfileCreate) SetNillableSupplierAddressPhoneNumber(v *string) *BillingProfileCreate { + if v != nil { + _c.SetSupplierAddressPhoneNumber(*v) + } + return _c +} + +// SetTaxAppID sets the "tax_app_id" field. +func (_c *BillingProfileCreate) SetTaxAppID(v string) *BillingProfileCreate { + _c.mutation.SetTaxAppID(v) + return _c +} + +// SetInvoicingAppID sets the "invoicing_app_id" field. +func (_c *BillingProfileCreate) SetInvoicingAppID(v string) *BillingProfileCreate { + _c.mutation.SetInvoicingAppID(v) + return _c +} + +// SetPaymentAppID sets the "payment_app_id" field. +func (_c *BillingProfileCreate) SetPaymentAppID(v string) *BillingProfileCreate { + _c.mutation.SetPaymentAppID(v) + return _c +} + +// SetWorkflowConfigID sets the "workflow_config_id" field. +func (_c *BillingProfileCreate) SetWorkflowConfigID(v string) *BillingProfileCreate { + _c.mutation.SetWorkflowConfigID(v) + return _c +} + +// SetDefault sets the "default" field. +func (_c *BillingProfileCreate) SetDefault(v bool) *BillingProfileCreate { + _c.mutation.SetDefault(v) + return _c +} + +// SetNillableDefault sets the "default" field if the given value is not nil. +func (_c *BillingProfileCreate) SetNillableDefault(v *bool) *BillingProfileCreate { + if v != nil { + _c.SetDefault(*v) + } + return _c +} + +// SetSupplierName sets the "supplier_name" field. +func (_c *BillingProfileCreate) SetSupplierName(v string) *BillingProfileCreate { + _c.mutation.SetSupplierName(v) + return _c +} + +// SetSupplierTaxCode sets the "supplier_tax_code" field. +func (_c *BillingProfileCreate) SetSupplierTaxCode(v string) *BillingProfileCreate { + _c.mutation.SetSupplierTaxCode(v) + return _c +} + +// SetNillableSupplierTaxCode sets the "supplier_tax_code" field if the given value is not nil. +func (_c *BillingProfileCreate) SetNillableSupplierTaxCode(v *string) *BillingProfileCreate { + if v != nil { + _c.SetSupplierTaxCode(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *BillingProfileCreate) SetID(v string) *BillingProfileCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *BillingProfileCreate) SetNillableID(v *string) *BillingProfileCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// AddBillingInvoiceIDs adds the "billing_invoices" edge to the BillingInvoice entity by IDs. +func (_c *BillingProfileCreate) AddBillingInvoiceIDs(ids ...string) *BillingProfileCreate { + _c.mutation.AddBillingInvoiceIDs(ids...) + return _c +} + +// AddBillingInvoices adds the "billing_invoices" edges to the BillingInvoice entity. +func (_c *BillingProfileCreate) AddBillingInvoices(v ...*BillingInvoice) *BillingProfileCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddBillingInvoiceIDs(ids...) +} + +// AddBillingCustomerOverrideIDs adds the "billing_customer_override" edge to the BillingCustomerOverride entity by IDs. +func (_c *BillingProfileCreate) AddBillingCustomerOverrideIDs(ids ...string) *BillingProfileCreate { + _c.mutation.AddBillingCustomerOverrideIDs(ids...) + return _c +} + +// AddBillingCustomerOverride adds the "billing_customer_override" edges to the BillingCustomerOverride entity. +func (_c *BillingProfileCreate) AddBillingCustomerOverride(v ...*BillingCustomerOverride) *BillingProfileCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddBillingCustomerOverrideIDs(ids...) +} + +// SetWorkflowConfig sets the "workflow_config" edge to the BillingWorkflowConfig entity. +func (_c *BillingProfileCreate) SetWorkflowConfig(v *BillingWorkflowConfig) *BillingProfileCreate { + return _c.SetWorkflowConfigID(v.ID) +} + +// SetTaxApp sets the "tax_app" edge to the App entity. +func (_c *BillingProfileCreate) SetTaxApp(v *App) *BillingProfileCreate { + return _c.SetTaxAppID(v.ID) +} + +// SetInvoicingApp sets the "invoicing_app" edge to the App entity. +func (_c *BillingProfileCreate) SetInvoicingApp(v *App) *BillingProfileCreate { + return _c.SetInvoicingAppID(v.ID) +} + +// SetPaymentApp sets the "payment_app" edge to the App entity. +func (_c *BillingProfileCreate) SetPaymentApp(v *App) *BillingProfileCreate { + return _c.SetPaymentAppID(v.ID) +} + +// Mutation returns the BillingProfileMutation object of the builder. +func (_c *BillingProfileCreate) Mutation() *BillingProfileMutation { + return _c.mutation +} + +// Save creates the BillingProfile in the database. +func (_c *BillingProfileCreate) Save(ctx context.Context) (*BillingProfile, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *BillingProfileCreate) SaveX(ctx context.Context) *BillingProfile { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingProfileCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingProfileCreate) 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 *BillingProfileCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := billingprofile.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := billingprofile.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.Default(); !ok { + v := billingprofile.DefaultDefault + _c.mutation.SetDefault(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := billingprofile.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *BillingProfileCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "BillingProfile.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := billingprofile.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "BillingProfile.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "BillingProfile.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "BillingProfile.updated_at"`)} + } + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "BillingProfile.name"`)} + } + if v, ok := _c.mutation.SupplierAddressCountry(); ok { + if err := billingprofile.SupplierAddressCountryValidator(string(v)); err != nil { + return &ValidationError{Name: "supplier_address_country", err: fmt.Errorf(`db: validator failed for field "BillingProfile.supplier_address_country": %w`, err)} + } + } + if _, ok := _c.mutation.TaxAppID(); !ok { + return &ValidationError{Name: "tax_app_id", err: errors.New(`db: missing required field "BillingProfile.tax_app_id"`)} + } + if _, ok := _c.mutation.InvoicingAppID(); !ok { + return &ValidationError{Name: "invoicing_app_id", err: errors.New(`db: missing required field "BillingProfile.invoicing_app_id"`)} + } + if _, ok := _c.mutation.PaymentAppID(); !ok { + return &ValidationError{Name: "payment_app_id", err: errors.New(`db: missing required field "BillingProfile.payment_app_id"`)} + } + if _, ok := _c.mutation.WorkflowConfigID(); !ok { + return &ValidationError{Name: "workflow_config_id", err: errors.New(`db: missing required field "BillingProfile.workflow_config_id"`)} + } + if v, ok := _c.mutation.WorkflowConfigID(); ok { + if err := billingprofile.WorkflowConfigIDValidator(v); err != nil { + return &ValidationError{Name: "workflow_config_id", err: fmt.Errorf(`db: validator failed for field "BillingProfile.workflow_config_id": %w`, err)} + } + } + if _, ok := _c.mutation.Default(); !ok { + return &ValidationError{Name: "default", err: errors.New(`db: missing required field "BillingProfile.default"`)} + } + if _, ok := _c.mutation.SupplierName(); !ok { + return &ValidationError{Name: "supplier_name", err: errors.New(`db: missing required field "BillingProfile.supplier_name"`)} + } + if v, ok := _c.mutation.SupplierName(); ok { + if err := billingprofile.SupplierNameValidator(v); err != nil { + return &ValidationError{Name: "supplier_name", err: fmt.Errorf(`db: validator failed for field "BillingProfile.supplier_name": %w`, err)} + } + } + if len(_c.mutation.WorkflowConfigIDs()) == 0 { + return &ValidationError{Name: "workflow_config", err: errors.New(`db: missing required edge "BillingProfile.workflow_config"`)} + } + if len(_c.mutation.TaxAppIDs()) == 0 { + return &ValidationError{Name: "tax_app", err: errors.New(`db: missing required edge "BillingProfile.tax_app"`)} + } + if len(_c.mutation.InvoicingAppIDs()) == 0 { + return &ValidationError{Name: "invoicing_app", err: errors.New(`db: missing required edge "BillingProfile.invoicing_app"`)} + } + if len(_c.mutation.PaymentAppIDs()) == 0 { + return &ValidationError{Name: "payment_app", err: errors.New(`db: missing required edge "BillingProfile.payment_app"`)} + } + return nil +} + +func (_c *BillingProfileCreate) sqlSave(ctx context.Context) (*BillingProfile, 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 BillingProfile.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *BillingProfileCreate) createSpec() (*BillingProfile, *sqlgraph.CreateSpec) { + var ( + _node = &BillingProfile{config: _c.config} + _spec = sqlgraph.NewCreateSpec(billingprofile.Table, sqlgraph.NewFieldSpec(billingprofile.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(billingprofile.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Metadata(); ok { + _spec.SetField(billingprofile.FieldMetadata, field.TypeJSON, value) + _node.Metadata = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(billingprofile.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(billingprofile.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(billingprofile.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(billingprofile.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Description(); ok { + _spec.SetField(billingprofile.FieldDescription, field.TypeString, value) + _node.Description = &value + } + if value, ok := _c.mutation.SupplierAddressCountry(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressCountry, field.TypeString, value) + _node.SupplierAddressCountry = &value + } + if value, ok := _c.mutation.SupplierAddressPostalCode(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressPostalCode, field.TypeString, value) + _node.SupplierAddressPostalCode = &value + } + if value, ok := _c.mutation.SupplierAddressState(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressState, field.TypeString, value) + _node.SupplierAddressState = &value + } + if value, ok := _c.mutation.SupplierAddressCity(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressCity, field.TypeString, value) + _node.SupplierAddressCity = &value + } + if value, ok := _c.mutation.SupplierAddressLine1(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressLine1, field.TypeString, value) + _node.SupplierAddressLine1 = &value + } + if value, ok := _c.mutation.SupplierAddressLine2(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressLine2, field.TypeString, value) + _node.SupplierAddressLine2 = &value + } + if value, ok := _c.mutation.SupplierAddressPhoneNumber(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressPhoneNumber, field.TypeString, value) + _node.SupplierAddressPhoneNumber = &value + } + if value, ok := _c.mutation.Default(); ok { + _spec.SetField(billingprofile.FieldDefault, field.TypeBool, value) + _node.Default = value + } + if value, ok := _c.mutation.SupplierName(); ok { + _spec.SetField(billingprofile.FieldSupplierName, field.TypeString, value) + _node.SupplierName = value + } + if value, ok := _c.mutation.SupplierTaxCode(); ok { + _spec.SetField(billingprofile.FieldSupplierTaxCode, field.TypeString, value) + _node.SupplierTaxCode = &value + } + if nodes := _c.mutation.BillingInvoicesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingprofile.BillingInvoicesTable, + Columns: []string{billingprofile.BillingInvoicesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.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.BillingCustomerOverrideIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingprofile.BillingCustomerOverrideTable, + Columns: []string{billingprofile.BillingCustomerOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingcustomeroverride.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.WorkflowConfigIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: billingprofile.WorkflowConfigTable, + Columns: []string{billingprofile.WorkflowConfigColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingworkflowconfig.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.WorkflowConfigID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.TaxAppIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingprofile.TaxAppTable, + Columns: []string{billingprofile.TaxAppColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbapp.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.TaxAppID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.InvoicingAppIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingprofile.InvoicingAppTable, + Columns: []string{billingprofile.InvoicingAppColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbapp.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.InvoicingAppID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.PaymentAppIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingprofile.PaymentAppTable, + Columns: []string{billingprofile.PaymentAppColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbapp.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.PaymentAppID = 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.BillingProfile.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.BillingProfileUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *BillingProfileCreate) OnConflict(opts ...sql.ConflictOption) *BillingProfileUpsertOne { + _c.conflict = opts + return &BillingProfileUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingProfile.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingProfileCreate) OnConflictColumns(columns ...string) *BillingProfileUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingProfileUpsertOne{ + create: _c, + } +} + +type ( + // BillingProfileUpsertOne is the builder for "upsert"-ing + // one BillingProfile node. + BillingProfileUpsertOne struct { + create *BillingProfileCreate + } + + // BillingProfileUpsert is the "OnConflict" setter. + BillingProfileUpsert struct { + *sql.UpdateSet + } +) + +// SetMetadata sets the "metadata" field. +func (u *BillingProfileUpsert) SetMetadata(v map[string]string) *BillingProfileUpsert { + u.Set(billingprofile.FieldMetadata, v) + return u +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *BillingProfileUpsert) UpdateMetadata() *BillingProfileUpsert { + u.SetExcluded(billingprofile.FieldMetadata) + return u +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *BillingProfileUpsert) ClearMetadata() *BillingProfileUpsert { + u.SetNull(billingprofile.FieldMetadata) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingProfileUpsert) SetUpdatedAt(v time.Time) *BillingProfileUpsert { + u.Set(billingprofile.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingProfileUpsert) UpdateUpdatedAt() *BillingProfileUpsert { + u.SetExcluded(billingprofile.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingProfileUpsert) SetDeletedAt(v time.Time) *BillingProfileUpsert { + u.Set(billingprofile.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingProfileUpsert) UpdateDeletedAt() *BillingProfileUpsert { + u.SetExcluded(billingprofile.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingProfileUpsert) ClearDeletedAt() *BillingProfileUpsert { + u.SetNull(billingprofile.FieldDeletedAt) + return u +} + +// SetName sets the "name" field. +func (u *BillingProfileUpsert) SetName(v string) *BillingProfileUpsert { + u.Set(billingprofile.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *BillingProfileUpsert) UpdateName() *BillingProfileUpsert { + u.SetExcluded(billingprofile.FieldName) + return u +} + +// SetDescription sets the "description" field. +func (u *BillingProfileUpsert) SetDescription(v string) *BillingProfileUpsert { + u.Set(billingprofile.FieldDescription, v) + return u +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *BillingProfileUpsert) UpdateDescription() *BillingProfileUpsert { + u.SetExcluded(billingprofile.FieldDescription) + return u +} + +// ClearDescription clears the value of the "description" field. +func (u *BillingProfileUpsert) ClearDescription() *BillingProfileUpsert { + u.SetNull(billingprofile.FieldDescription) + return u +} + +// SetSupplierAddressCountry sets the "supplier_address_country" field. +func (u *BillingProfileUpsert) SetSupplierAddressCountry(v models.CountryCode) *BillingProfileUpsert { + u.Set(billingprofile.FieldSupplierAddressCountry, v) + return u +} + +// UpdateSupplierAddressCountry sets the "supplier_address_country" field to the value that was provided on create. +func (u *BillingProfileUpsert) UpdateSupplierAddressCountry() *BillingProfileUpsert { + u.SetExcluded(billingprofile.FieldSupplierAddressCountry) + return u +} + +// ClearSupplierAddressCountry clears the value of the "supplier_address_country" field. +func (u *BillingProfileUpsert) ClearSupplierAddressCountry() *BillingProfileUpsert { + u.SetNull(billingprofile.FieldSupplierAddressCountry) + return u +} + +// SetSupplierAddressPostalCode sets the "supplier_address_postal_code" field. +func (u *BillingProfileUpsert) SetSupplierAddressPostalCode(v string) *BillingProfileUpsert { + u.Set(billingprofile.FieldSupplierAddressPostalCode, v) + return u +} + +// UpdateSupplierAddressPostalCode sets the "supplier_address_postal_code" field to the value that was provided on create. +func (u *BillingProfileUpsert) UpdateSupplierAddressPostalCode() *BillingProfileUpsert { + u.SetExcluded(billingprofile.FieldSupplierAddressPostalCode) + return u +} + +// ClearSupplierAddressPostalCode clears the value of the "supplier_address_postal_code" field. +func (u *BillingProfileUpsert) ClearSupplierAddressPostalCode() *BillingProfileUpsert { + u.SetNull(billingprofile.FieldSupplierAddressPostalCode) + return u +} + +// SetSupplierAddressState sets the "supplier_address_state" field. +func (u *BillingProfileUpsert) SetSupplierAddressState(v string) *BillingProfileUpsert { + u.Set(billingprofile.FieldSupplierAddressState, v) + return u +} + +// UpdateSupplierAddressState sets the "supplier_address_state" field to the value that was provided on create. +func (u *BillingProfileUpsert) UpdateSupplierAddressState() *BillingProfileUpsert { + u.SetExcluded(billingprofile.FieldSupplierAddressState) + return u +} + +// ClearSupplierAddressState clears the value of the "supplier_address_state" field. +func (u *BillingProfileUpsert) ClearSupplierAddressState() *BillingProfileUpsert { + u.SetNull(billingprofile.FieldSupplierAddressState) + return u +} + +// SetSupplierAddressCity sets the "supplier_address_city" field. +func (u *BillingProfileUpsert) SetSupplierAddressCity(v string) *BillingProfileUpsert { + u.Set(billingprofile.FieldSupplierAddressCity, v) + return u +} + +// UpdateSupplierAddressCity sets the "supplier_address_city" field to the value that was provided on create. +func (u *BillingProfileUpsert) UpdateSupplierAddressCity() *BillingProfileUpsert { + u.SetExcluded(billingprofile.FieldSupplierAddressCity) + return u +} + +// ClearSupplierAddressCity clears the value of the "supplier_address_city" field. +func (u *BillingProfileUpsert) ClearSupplierAddressCity() *BillingProfileUpsert { + u.SetNull(billingprofile.FieldSupplierAddressCity) + return u +} + +// SetSupplierAddressLine1 sets the "supplier_address_line1" field. +func (u *BillingProfileUpsert) SetSupplierAddressLine1(v string) *BillingProfileUpsert { + u.Set(billingprofile.FieldSupplierAddressLine1, v) + return u +} + +// UpdateSupplierAddressLine1 sets the "supplier_address_line1" field to the value that was provided on create. +func (u *BillingProfileUpsert) UpdateSupplierAddressLine1() *BillingProfileUpsert { + u.SetExcluded(billingprofile.FieldSupplierAddressLine1) + return u +} + +// ClearSupplierAddressLine1 clears the value of the "supplier_address_line1" field. +func (u *BillingProfileUpsert) ClearSupplierAddressLine1() *BillingProfileUpsert { + u.SetNull(billingprofile.FieldSupplierAddressLine1) + return u +} + +// SetSupplierAddressLine2 sets the "supplier_address_line2" field. +func (u *BillingProfileUpsert) SetSupplierAddressLine2(v string) *BillingProfileUpsert { + u.Set(billingprofile.FieldSupplierAddressLine2, v) + return u +} + +// UpdateSupplierAddressLine2 sets the "supplier_address_line2" field to the value that was provided on create. +func (u *BillingProfileUpsert) UpdateSupplierAddressLine2() *BillingProfileUpsert { + u.SetExcluded(billingprofile.FieldSupplierAddressLine2) + return u +} + +// ClearSupplierAddressLine2 clears the value of the "supplier_address_line2" field. +func (u *BillingProfileUpsert) ClearSupplierAddressLine2() *BillingProfileUpsert { + u.SetNull(billingprofile.FieldSupplierAddressLine2) + return u +} + +// SetSupplierAddressPhoneNumber sets the "supplier_address_phone_number" field. +func (u *BillingProfileUpsert) SetSupplierAddressPhoneNumber(v string) *BillingProfileUpsert { + u.Set(billingprofile.FieldSupplierAddressPhoneNumber, v) + return u +} + +// UpdateSupplierAddressPhoneNumber sets the "supplier_address_phone_number" field to the value that was provided on create. +func (u *BillingProfileUpsert) UpdateSupplierAddressPhoneNumber() *BillingProfileUpsert { + u.SetExcluded(billingprofile.FieldSupplierAddressPhoneNumber) + return u +} + +// ClearSupplierAddressPhoneNumber clears the value of the "supplier_address_phone_number" field. +func (u *BillingProfileUpsert) ClearSupplierAddressPhoneNumber() *BillingProfileUpsert { + u.SetNull(billingprofile.FieldSupplierAddressPhoneNumber) + return u +} + +// SetWorkflowConfigID sets the "workflow_config_id" field. +func (u *BillingProfileUpsert) SetWorkflowConfigID(v string) *BillingProfileUpsert { + u.Set(billingprofile.FieldWorkflowConfigID, v) + return u +} + +// UpdateWorkflowConfigID sets the "workflow_config_id" field to the value that was provided on create. +func (u *BillingProfileUpsert) UpdateWorkflowConfigID() *BillingProfileUpsert { + u.SetExcluded(billingprofile.FieldWorkflowConfigID) + return u +} + +// SetDefault sets the "default" field. +func (u *BillingProfileUpsert) SetDefault(v bool) *BillingProfileUpsert { + u.Set(billingprofile.FieldDefault, v) + return u +} + +// UpdateDefault sets the "default" field to the value that was provided on create. +func (u *BillingProfileUpsert) UpdateDefault() *BillingProfileUpsert { + u.SetExcluded(billingprofile.FieldDefault) + return u +} + +// SetSupplierName sets the "supplier_name" field. +func (u *BillingProfileUpsert) SetSupplierName(v string) *BillingProfileUpsert { + u.Set(billingprofile.FieldSupplierName, v) + return u +} + +// UpdateSupplierName sets the "supplier_name" field to the value that was provided on create. +func (u *BillingProfileUpsert) UpdateSupplierName() *BillingProfileUpsert { + u.SetExcluded(billingprofile.FieldSupplierName) + return u +} + +// SetSupplierTaxCode sets the "supplier_tax_code" field. +func (u *BillingProfileUpsert) SetSupplierTaxCode(v string) *BillingProfileUpsert { + u.Set(billingprofile.FieldSupplierTaxCode, v) + return u +} + +// UpdateSupplierTaxCode sets the "supplier_tax_code" field to the value that was provided on create. +func (u *BillingProfileUpsert) UpdateSupplierTaxCode() *BillingProfileUpsert { + u.SetExcluded(billingprofile.FieldSupplierTaxCode) + return u +} + +// ClearSupplierTaxCode clears the value of the "supplier_tax_code" field. +func (u *BillingProfileUpsert) ClearSupplierTaxCode() *BillingProfileUpsert { + u.SetNull(billingprofile.FieldSupplierTaxCode) + 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.BillingProfile.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(billingprofile.FieldID) +// }), +// ). +// Exec(ctx) +func (u *BillingProfileUpsertOne) UpdateNewValues() *BillingProfileUpsertOne { + 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(billingprofile.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(billingprofile.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(billingprofile.FieldCreatedAt) + } + if _, exists := u.create.mutation.TaxAppID(); exists { + s.SetIgnore(billingprofile.FieldTaxAppID) + } + if _, exists := u.create.mutation.InvoicingAppID(); exists { + s.SetIgnore(billingprofile.FieldInvoicingAppID) + } + if _, exists := u.create.mutation.PaymentAppID(); exists { + s.SetIgnore(billingprofile.FieldPaymentAppID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingProfile.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingProfileUpsertOne) Ignore() *BillingProfileUpsertOne { + 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 *BillingProfileUpsertOne) DoNothing() *BillingProfileUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingProfileCreate.OnConflict +// documentation for more info. +func (u *BillingProfileUpsertOne) Update(set func(*BillingProfileUpsert)) *BillingProfileUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingProfileUpsert{UpdateSet: update}) + })) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *BillingProfileUpsertOne) SetMetadata(v map[string]string) *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *BillingProfileUpsertOne) UpdateMetadata() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *BillingProfileUpsertOne) ClearMetadata() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingProfileUpsertOne) SetUpdatedAt(v time.Time) *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingProfileUpsertOne) UpdateUpdatedAt() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingProfileUpsertOne) SetDeletedAt(v time.Time) *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingProfileUpsertOne) UpdateDeletedAt() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingProfileUpsertOne) ClearDeletedAt() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *BillingProfileUpsertOne) SetName(v string) *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *BillingProfileUpsertOne) UpdateName() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *BillingProfileUpsertOne) SetDescription(v string) *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *BillingProfileUpsertOne) UpdateDescription() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *BillingProfileUpsertOne) ClearDescription() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearDescription() + }) +} + +// SetSupplierAddressCountry sets the "supplier_address_country" field. +func (u *BillingProfileUpsertOne) SetSupplierAddressCountry(v models.CountryCode) *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.SetSupplierAddressCountry(v) + }) +} + +// UpdateSupplierAddressCountry sets the "supplier_address_country" field to the value that was provided on create. +func (u *BillingProfileUpsertOne) UpdateSupplierAddressCountry() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateSupplierAddressCountry() + }) +} + +// ClearSupplierAddressCountry clears the value of the "supplier_address_country" field. +func (u *BillingProfileUpsertOne) ClearSupplierAddressCountry() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearSupplierAddressCountry() + }) +} + +// SetSupplierAddressPostalCode sets the "supplier_address_postal_code" field. +func (u *BillingProfileUpsertOne) SetSupplierAddressPostalCode(v string) *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.SetSupplierAddressPostalCode(v) + }) +} + +// UpdateSupplierAddressPostalCode sets the "supplier_address_postal_code" field to the value that was provided on create. +func (u *BillingProfileUpsertOne) UpdateSupplierAddressPostalCode() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateSupplierAddressPostalCode() + }) +} + +// ClearSupplierAddressPostalCode clears the value of the "supplier_address_postal_code" field. +func (u *BillingProfileUpsertOne) ClearSupplierAddressPostalCode() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearSupplierAddressPostalCode() + }) +} + +// SetSupplierAddressState sets the "supplier_address_state" field. +func (u *BillingProfileUpsertOne) SetSupplierAddressState(v string) *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.SetSupplierAddressState(v) + }) +} + +// UpdateSupplierAddressState sets the "supplier_address_state" field to the value that was provided on create. +func (u *BillingProfileUpsertOne) UpdateSupplierAddressState() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateSupplierAddressState() + }) +} + +// ClearSupplierAddressState clears the value of the "supplier_address_state" field. +func (u *BillingProfileUpsertOne) ClearSupplierAddressState() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearSupplierAddressState() + }) +} + +// SetSupplierAddressCity sets the "supplier_address_city" field. +func (u *BillingProfileUpsertOne) SetSupplierAddressCity(v string) *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.SetSupplierAddressCity(v) + }) +} + +// UpdateSupplierAddressCity sets the "supplier_address_city" field to the value that was provided on create. +func (u *BillingProfileUpsertOne) UpdateSupplierAddressCity() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateSupplierAddressCity() + }) +} + +// ClearSupplierAddressCity clears the value of the "supplier_address_city" field. +func (u *BillingProfileUpsertOne) ClearSupplierAddressCity() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearSupplierAddressCity() + }) +} + +// SetSupplierAddressLine1 sets the "supplier_address_line1" field. +func (u *BillingProfileUpsertOne) SetSupplierAddressLine1(v string) *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.SetSupplierAddressLine1(v) + }) +} + +// UpdateSupplierAddressLine1 sets the "supplier_address_line1" field to the value that was provided on create. +func (u *BillingProfileUpsertOne) UpdateSupplierAddressLine1() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateSupplierAddressLine1() + }) +} + +// ClearSupplierAddressLine1 clears the value of the "supplier_address_line1" field. +func (u *BillingProfileUpsertOne) ClearSupplierAddressLine1() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearSupplierAddressLine1() + }) +} + +// SetSupplierAddressLine2 sets the "supplier_address_line2" field. +func (u *BillingProfileUpsertOne) SetSupplierAddressLine2(v string) *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.SetSupplierAddressLine2(v) + }) +} + +// UpdateSupplierAddressLine2 sets the "supplier_address_line2" field to the value that was provided on create. +func (u *BillingProfileUpsertOne) UpdateSupplierAddressLine2() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateSupplierAddressLine2() + }) +} + +// ClearSupplierAddressLine2 clears the value of the "supplier_address_line2" field. +func (u *BillingProfileUpsertOne) ClearSupplierAddressLine2() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearSupplierAddressLine2() + }) +} + +// SetSupplierAddressPhoneNumber sets the "supplier_address_phone_number" field. +func (u *BillingProfileUpsertOne) SetSupplierAddressPhoneNumber(v string) *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.SetSupplierAddressPhoneNumber(v) + }) +} + +// UpdateSupplierAddressPhoneNumber sets the "supplier_address_phone_number" field to the value that was provided on create. +func (u *BillingProfileUpsertOne) UpdateSupplierAddressPhoneNumber() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateSupplierAddressPhoneNumber() + }) +} + +// ClearSupplierAddressPhoneNumber clears the value of the "supplier_address_phone_number" field. +func (u *BillingProfileUpsertOne) ClearSupplierAddressPhoneNumber() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearSupplierAddressPhoneNumber() + }) +} + +// SetWorkflowConfigID sets the "workflow_config_id" field. +func (u *BillingProfileUpsertOne) SetWorkflowConfigID(v string) *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.SetWorkflowConfigID(v) + }) +} + +// UpdateWorkflowConfigID sets the "workflow_config_id" field to the value that was provided on create. +func (u *BillingProfileUpsertOne) UpdateWorkflowConfigID() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateWorkflowConfigID() + }) +} + +// SetDefault sets the "default" field. +func (u *BillingProfileUpsertOne) SetDefault(v bool) *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.SetDefault(v) + }) +} + +// UpdateDefault sets the "default" field to the value that was provided on create. +func (u *BillingProfileUpsertOne) UpdateDefault() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateDefault() + }) +} + +// SetSupplierName sets the "supplier_name" field. +func (u *BillingProfileUpsertOne) SetSupplierName(v string) *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.SetSupplierName(v) + }) +} + +// UpdateSupplierName sets the "supplier_name" field to the value that was provided on create. +func (u *BillingProfileUpsertOne) UpdateSupplierName() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateSupplierName() + }) +} + +// SetSupplierTaxCode sets the "supplier_tax_code" field. +func (u *BillingProfileUpsertOne) SetSupplierTaxCode(v string) *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.SetSupplierTaxCode(v) + }) +} + +// UpdateSupplierTaxCode sets the "supplier_tax_code" field to the value that was provided on create. +func (u *BillingProfileUpsertOne) UpdateSupplierTaxCode() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateSupplierTaxCode() + }) +} + +// ClearSupplierTaxCode clears the value of the "supplier_tax_code" field. +func (u *BillingProfileUpsertOne) ClearSupplierTaxCode() *BillingProfileUpsertOne { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearSupplierTaxCode() + }) +} + +// Exec executes the query. +func (u *BillingProfileUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingProfileCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingProfileUpsertOne) 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 *BillingProfileUpsertOne) 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: BillingProfileUpsertOne.ID is not supported by MySQL driver. Use BillingProfileUpsertOne.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 *BillingProfileUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// BillingProfileCreateBulk is the builder for creating many BillingProfile entities in bulk. +type BillingProfileCreateBulk struct { + config + err error + builders []*BillingProfileCreate + conflict []sql.ConflictOption +} + +// Save creates the BillingProfile entities in the database. +func (_c *BillingProfileCreateBulk) Save(ctx context.Context) ([]*BillingProfile, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*BillingProfile, 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.(*BillingProfileMutation) + 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 *BillingProfileCreateBulk) SaveX(ctx context.Context) []*BillingProfile { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingProfileCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingProfileCreateBulk) 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.BillingProfile.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.BillingProfileUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *BillingProfileCreateBulk) OnConflict(opts ...sql.ConflictOption) *BillingProfileUpsertBulk { + _c.conflict = opts + return &BillingProfileUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingProfile.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingProfileCreateBulk) OnConflictColumns(columns ...string) *BillingProfileUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingProfileUpsertBulk{ + create: _c, + } +} + +// BillingProfileUpsertBulk is the builder for "upsert"-ing +// a bulk of BillingProfile nodes. +type BillingProfileUpsertBulk struct { + create *BillingProfileCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.BillingProfile.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(billingprofile.FieldID) +// }), +// ). +// Exec(ctx) +func (u *BillingProfileUpsertBulk) UpdateNewValues() *BillingProfileUpsertBulk { + 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(billingprofile.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(billingprofile.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(billingprofile.FieldCreatedAt) + } + if _, exists := b.mutation.TaxAppID(); exists { + s.SetIgnore(billingprofile.FieldTaxAppID) + } + if _, exists := b.mutation.InvoicingAppID(); exists { + s.SetIgnore(billingprofile.FieldInvoicingAppID) + } + if _, exists := b.mutation.PaymentAppID(); exists { + s.SetIgnore(billingprofile.FieldPaymentAppID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingProfile.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingProfileUpsertBulk) Ignore() *BillingProfileUpsertBulk { + 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 *BillingProfileUpsertBulk) DoNothing() *BillingProfileUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingProfileCreateBulk.OnConflict +// documentation for more info. +func (u *BillingProfileUpsertBulk) Update(set func(*BillingProfileUpsert)) *BillingProfileUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingProfileUpsert{UpdateSet: update}) + })) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *BillingProfileUpsertBulk) SetMetadata(v map[string]string) *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *BillingProfileUpsertBulk) UpdateMetadata() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *BillingProfileUpsertBulk) ClearMetadata() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingProfileUpsertBulk) SetUpdatedAt(v time.Time) *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingProfileUpsertBulk) UpdateUpdatedAt() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingProfileUpsertBulk) SetDeletedAt(v time.Time) *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingProfileUpsertBulk) UpdateDeletedAt() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingProfileUpsertBulk) ClearDeletedAt() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *BillingProfileUpsertBulk) SetName(v string) *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *BillingProfileUpsertBulk) UpdateName() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *BillingProfileUpsertBulk) SetDescription(v string) *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *BillingProfileUpsertBulk) UpdateDescription() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *BillingProfileUpsertBulk) ClearDescription() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearDescription() + }) +} + +// SetSupplierAddressCountry sets the "supplier_address_country" field. +func (u *BillingProfileUpsertBulk) SetSupplierAddressCountry(v models.CountryCode) *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.SetSupplierAddressCountry(v) + }) +} + +// UpdateSupplierAddressCountry sets the "supplier_address_country" field to the value that was provided on create. +func (u *BillingProfileUpsertBulk) UpdateSupplierAddressCountry() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateSupplierAddressCountry() + }) +} + +// ClearSupplierAddressCountry clears the value of the "supplier_address_country" field. +func (u *BillingProfileUpsertBulk) ClearSupplierAddressCountry() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearSupplierAddressCountry() + }) +} + +// SetSupplierAddressPostalCode sets the "supplier_address_postal_code" field. +func (u *BillingProfileUpsertBulk) SetSupplierAddressPostalCode(v string) *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.SetSupplierAddressPostalCode(v) + }) +} + +// UpdateSupplierAddressPostalCode sets the "supplier_address_postal_code" field to the value that was provided on create. +func (u *BillingProfileUpsertBulk) UpdateSupplierAddressPostalCode() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateSupplierAddressPostalCode() + }) +} + +// ClearSupplierAddressPostalCode clears the value of the "supplier_address_postal_code" field. +func (u *BillingProfileUpsertBulk) ClearSupplierAddressPostalCode() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearSupplierAddressPostalCode() + }) +} + +// SetSupplierAddressState sets the "supplier_address_state" field. +func (u *BillingProfileUpsertBulk) SetSupplierAddressState(v string) *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.SetSupplierAddressState(v) + }) +} + +// UpdateSupplierAddressState sets the "supplier_address_state" field to the value that was provided on create. +func (u *BillingProfileUpsertBulk) UpdateSupplierAddressState() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateSupplierAddressState() + }) +} + +// ClearSupplierAddressState clears the value of the "supplier_address_state" field. +func (u *BillingProfileUpsertBulk) ClearSupplierAddressState() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearSupplierAddressState() + }) +} + +// SetSupplierAddressCity sets the "supplier_address_city" field. +func (u *BillingProfileUpsertBulk) SetSupplierAddressCity(v string) *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.SetSupplierAddressCity(v) + }) +} + +// UpdateSupplierAddressCity sets the "supplier_address_city" field to the value that was provided on create. +func (u *BillingProfileUpsertBulk) UpdateSupplierAddressCity() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateSupplierAddressCity() + }) +} + +// ClearSupplierAddressCity clears the value of the "supplier_address_city" field. +func (u *BillingProfileUpsertBulk) ClearSupplierAddressCity() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearSupplierAddressCity() + }) +} + +// SetSupplierAddressLine1 sets the "supplier_address_line1" field. +func (u *BillingProfileUpsertBulk) SetSupplierAddressLine1(v string) *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.SetSupplierAddressLine1(v) + }) +} + +// UpdateSupplierAddressLine1 sets the "supplier_address_line1" field to the value that was provided on create. +func (u *BillingProfileUpsertBulk) UpdateSupplierAddressLine1() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateSupplierAddressLine1() + }) +} + +// ClearSupplierAddressLine1 clears the value of the "supplier_address_line1" field. +func (u *BillingProfileUpsertBulk) ClearSupplierAddressLine1() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearSupplierAddressLine1() + }) +} + +// SetSupplierAddressLine2 sets the "supplier_address_line2" field. +func (u *BillingProfileUpsertBulk) SetSupplierAddressLine2(v string) *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.SetSupplierAddressLine2(v) + }) +} + +// UpdateSupplierAddressLine2 sets the "supplier_address_line2" field to the value that was provided on create. +func (u *BillingProfileUpsertBulk) UpdateSupplierAddressLine2() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateSupplierAddressLine2() + }) +} + +// ClearSupplierAddressLine2 clears the value of the "supplier_address_line2" field. +func (u *BillingProfileUpsertBulk) ClearSupplierAddressLine2() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearSupplierAddressLine2() + }) +} + +// SetSupplierAddressPhoneNumber sets the "supplier_address_phone_number" field. +func (u *BillingProfileUpsertBulk) SetSupplierAddressPhoneNumber(v string) *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.SetSupplierAddressPhoneNumber(v) + }) +} + +// UpdateSupplierAddressPhoneNumber sets the "supplier_address_phone_number" field to the value that was provided on create. +func (u *BillingProfileUpsertBulk) UpdateSupplierAddressPhoneNumber() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateSupplierAddressPhoneNumber() + }) +} + +// ClearSupplierAddressPhoneNumber clears the value of the "supplier_address_phone_number" field. +func (u *BillingProfileUpsertBulk) ClearSupplierAddressPhoneNumber() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearSupplierAddressPhoneNumber() + }) +} + +// SetWorkflowConfigID sets the "workflow_config_id" field. +func (u *BillingProfileUpsertBulk) SetWorkflowConfigID(v string) *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.SetWorkflowConfigID(v) + }) +} + +// UpdateWorkflowConfigID sets the "workflow_config_id" field to the value that was provided on create. +func (u *BillingProfileUpsertBulk) UpdateWorkflowConfigID() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateWorkflowConfigID() + }) +} + +// SetDefault sets the "default" field. +func (u *BillingProfileUpsertBulk) SetDefault(v bool) *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.SetDefault(v) + }) +} + +// UpdateDefault sets the "default" field to the value that was provided on create. +func (u *BillingProfileUpsertBulk) UpdateDefault() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateDefault() + }) +} + +// SetSupplierName sets the "supplier_name" field. +func (u *BillingProfileUpsertBulk) SetSupplierName(v string) *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.SetSupplierName(v) + }) +} + +// UpdateSupplierName sets the "supplier_name" field to the value that was provided on create. +func (u *BillingProfileUpsertBulk) UpdateSupplierName() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateSupplierName() + }) +} + +// SetSupplierTaxCode sets the "supplier_tax_code" field. +func (u *BillingProfileUpsertBulk) SetSupplierTaxCode(v string) *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.SetSupplierTaxCode(v) + }) +} + +// UpdateSupplierTaxCode sets the "supplier_tax_code" field to the value that was provided on create. +func (u *BillingProfileUpsertBulk) UpdateSupplierTaxCode() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.UpdateSupplierTaxCode() + }) +} + +// ClearSupplierTaxCode clears the value of the "supplier_tax_code" field. +func (u *BillingProfileUpsertBulk) ClearSupplierTaxCode() *BillingProfileUpsertBulk { + return u.Update(func(s *BillingProfileUpsert) { + s.ClearSupplierTaxCode() + }) +} + +// Exec executes the query. +func (u *BillingProfileUpsertBulk) 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 BillingProfileCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingProfileCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingProfileUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billingprofile_delete.go b/ent/db/billingprofile_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..1d9bdb3bfec2b715902abb5a8722fe6a8a8db2cd --- /dev/null +++ b/ent/db/billingprofile_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/billingprofile" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingProfileDelete is the builder for deleting a BillingProfile entity. +type BillingProfileDelete struct { + config + hooks []Hook + mutation *BillingProfileMutation +} + +// Where appends a list predicates to the BillingProfileDelete builder. +func (_d *BillingProfileDelete) Where(ps ...predicate.BillingProfile) *BillingProfileDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *BillingProfileDelete) 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 *BillingProfileDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *BillingProfileDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(billingprofile.Table, sqlgraph.NewFieldSpec(billingprofile.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 +} + +// BillingProfileDeleteOne is the builder for deleting a single BillingProfile entity. +type BillingProfileDeleteOne struct { + _d *BillingProfileDelete +} + +// Where appends a list predicates to the BillingProfileDelete builder. +func (_d *BillingProfileDeleteOne) Where(ps ...predicate.BillingProfile) *BillingProfileDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *BillingProfileDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{billingprofile.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *BillingProfileDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billingprofile_query.go b/ent/db/billingprofile_query.go new file mode 100644 index 0000000000000000000000000000000000000000..85d64c1ebc00f45b37664e191b34cc8fb85b0eed --- /dev/null +++ b/ent/db/billingprofile_query.go @@ -0,0 +1,1022 @@ +// 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" + dbapp "github.com/openmeterio/openmeter/openmeter/ent/db/app" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingcustomeroverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingprofile" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingworkflowconfig" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingProfileQuery is the builder for querying BillingProfile entities. +type BillingProfileQuery struct { + config + ctx *QueryContext + order []billingprofile.OrderOption + inters []Interceptor + predicates []predicate.BillingProfile + withBillingInvoices *BillingInvoiceQuery + withBillingCustomerOverride *BillingCustomerOverrideQuery + withWorkflowConfig *BillingWorkflowConfigQuery + withTaxApp *AppQuery + withInvoicingApp *AppQuery + withPaymentApp *AppQuery + 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 BillingProfileQuery builder. +func (_q *BillingProfileQuery) Where(ps ...predicate.BillingProfile) *BillingProfileQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *BillingProfileQuery) Limit(limit int) *BillingProfileQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *BillingProfileQuery) Offset(offset int) *BillingProfileQuery { + _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 *BillingProfileQuery) Unique(unique bool) *BillingProfileQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *BillingProfileQuery) Order(o ...billingprofile.OrderOption) *BillingProfileQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryBillingInvoices chains the current query on the "billing_invoices" edge. +func (_q *BillingProfileQuery) QueryBillingInvoices() *BillingInvoiceQuery { + query := (&BillingInvoiceClient{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(billingprofile.Table, billingprofile.FieldID, selector), + sqlgraph.To(billinginvoice.Table, billinginvoice.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, billingprofile.BillingInvoicesTable, billingprofile.BillingInvoicesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryBillingCustomerOverride chains the current query on the "billing_customer_override" edge. +func (_q *BillingProfileQuery) QueryBillingCustomerOverride() *BillingCustomerOverrideQuery { + query := (&BillingCustomerOverrideClient{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(billingprofile.Table, billingprofile.FieldID, selector), + sqlgraph.To(billingcustomeroverride.Table, billingcustomeroverride.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, billingprofile.BillingCustomerOverrideTable, billingprofile.BillingCustomerOverrideColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryWorkflowConfig chains the current query on the "workflow_config" edge. +func (_q *BillingProfileQuery) QueryWorkflowConfig() *BillingWorkflowConfigQuery { + query := (&BillingWorkflowConfigClient{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(billingprofile.Table, billingprofile.FieldID, selector), + sqlgraph.To(billingworkflowconfig.Table, billingworkflowconfig.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, billingprofile.WorkflowConfigTable, billingprofile.WorkflowConfigColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryTaxApp chains the current query on the "tax_app" edge. +func (_q *BillingProfileQuery) QueryTaxApp() *AppQuery { + query := (&AppClient{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(billingprofile.Table, billingprofile.FieldID, selector), + sqlgraph.To(dbapp.Table, dbapp.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billingprofile.TaxAppTable, billingprofile.TaxAppColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryInvoicingApp chains the current query on the "invoicing_app" edge. +func (_q *BillingProfileQuery) QueryInvoicingApp() *AppQuery { + query := (&AppClient{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(billingprofile.Table, billingprofile.FieldID, selector), + sqlgraph.To(dbapp.Table, dbapp.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billingprofile.InvoicingAppTable, billingprofile.InvoicingAppColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryPaymentApp chains the current query on the "payment_app" edge. +func (_q *BillingProfileQuery) QueryPaymentApp() *AppQuery { + query := (&AppClient{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(billingprofile.Table, billingprofile.FieldID, selector), + sqlgraph.To(dbapp.Table, dbapp.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billingprofile.PaymentAppTable, billingprofile.PaymentAppColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first BillingProfile entity from the query. +// Returns a *NotFoundError when no BillingProfile was found. +func (_q *BillingProfileQuery) First(ctx context.Context) (*BillingProfile, 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{billingprofile.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *BillingProfileQuery) FirstX(ctx context.Context) *BillingProfile { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first BillingProfile ID from the query. +// Returns a *NotFoundError when no BillingProfile ID was found. +func (_q *BillingProfileQuery) 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{billingprofile.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *BillingProfileQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single BillingProfile entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one BillingProfile entity is found. +// Returns a *NotFoundError when no BillingProfile entities are found. +func (_q *BillingProfileQuery) Only(ctx context.Context) (*BillingProfile, 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{billingprofile.Label} + default: + return nil, &NotSingularError{billingprofile.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *BillingProfileQuery) OnlyX(ctx context.Context) *BillingProfile { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only BillingProfile ID in the query. +// Returns a *NotSingularError when more than one BillingProfile ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *BillingProfileQuery) 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{billingprofile.Label} + default: + err = &NotSingularError{billingprofile.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *BillingProfileQuery) 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 BillingProfiles. +func (_q *BillingProfileQuery) All(ctx context.Context) ([]*BillingProfile, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*BillingProfile, *BillingProfileQuery]() + return withInterceptors[[]*BillingProfile](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *BillingProfileQuery) AllX(ctx context.Context) []*BillingProfile { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of BillingProfile IDs. +func (_q *BillingProfileQuery) 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(billingprofile.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *BillingProfileQuery) 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 *BillingProfileQuery) 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[*BillingProfileQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *BillingProfileQuery) 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 *BillingProfileQuery) 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 *BillingProfileQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the BillingProfileQuery 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 *BillingProfileQuery) Clone() *BillingProfileQuery { + if _q == nil { + return nil + } + return &BillingProfileQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]billingprofile.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.BillingProfile{}, _q.predicates...), + withBillingInvoices: _q.withBillingInvoices.Clone(), + withBillingCustomerOverride: _q.withBillingCustomerOverride.Clone(), + withWorkflowConfig: _q.withWorkflowConfig.Clone(), + withTaxApp: _q.withTaxApp.Clone(), + withInvoicingApp: _q.withInvoicingApp.Clone(), + withPaymentApp: _q.withPaymentApp.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithBillingInvoices tells the query-builder to eager-load the nodes that are connected to +// the "billing_invoices" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *BillingProfileQuery) WithBillingInvoices(opts ...func(*BillingInvoiceQuery)) *BillingProfileQuery { + query := (&BillingInvoiceClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingInvoices = query + return _q +} + +// WithBillingCustomerOverride tells the query-builder to eager-load the nodes that are connected to +// the "billing_customer_override" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *BillingProfileQuery) WithBillingCustomerOverride(opts ...func(*BillingCustomerOverrideQuery)) *BillingProfileQuery { + query := (&BillingCustomerOverrideClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingCustomerOverride = query + return _q +} + +// WithWorkflowConfig tells the query-builder to eager-load the nodes that are connected to +// the "workflow_config" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *BillingProfileQuery) WithWorkflowConfig(opts ...func(*BillingWorkflowConfigQuery)) *BillingProfileQuery { + query := (&BillingWorkflowConfigClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withWorkflowConfig = query + return _q +} + +// WithTaxApp tells the query-builder to eager-load the nodes that are connected to +// the "tax_app" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *BillingProfileQuery) WithTaxApp(opts ...func(*AppQuery)) *BillingProfileQuery { + query := (&AppClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withTaxApp = query + return _q +} + +// WithInvoicingApp tells the query-builder to eager-load the nodes that are connected to +// the "invoicing_app" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *BillingProfileQuery) WithInvoicingApp(opts ...func(*AppQuery)) *BillingProfileQuery { + query := (&AppClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withInvoicingApp = query + return _q +} + +// WithPaymentApp tells the query-builder to eager-load the nodes that are connected to +// the "payment_app" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *BillingProfileQuery) WithPaymentApp(opts ...func(*AppQuery)) *BillingProfileQuery { + query := (&AppClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withPaymentApp = 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.BillingProfile.Query(). +// GroupBy(billingprofile.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *BillingProfileQuery) GroupBy(field string, fields ...string) *BillingProfileGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &BillingProfileGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = billingprofile.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.BillingProfile.Query(). +// Select(billingprofile.FieldNamespace). +// Scan(ctx, &v) +func (_q *BillingProfileQuery) Select(fields ...string) *BillingProfileSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &BillingProfileSelect{BillingProfileQuery: _q} + sbuild.label = billingprofile.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a BillingProfileSelect configured with the given aggregations. +func (_q *BillingProfileQuery) Aggregate(fns ...AggregateFunc) *BillingProfileSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *BillingProfileQuery) 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 !billingprofile.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 *BillingProfileQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BillingProfile, error) { + var ( + nodes = []*BillingProfile{} + _spec = _q.querySpec() + loadedTypes = [6]bool{ + _q.withBillingInvoices != nil, + _q.withBillingCustomerOverride != nil, + _q.withWorkflowConfig != nil, + _q.withTaxApp != nil, + _q.withInvoicingApp != nil, + _q.withPaymentApp != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*BillingProfile).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &BillingProfile{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.withBillingInvoices; query != nil { + if err := _q.loadBillingInvoices(ctx, query, nodes, + func(n *BillingProfile) { n.Edges.BillingInvoices = []*BillingInvoice{} }, + func(n *BillingProfile, e *BillingInvoice) { + n.Edges.BillingInvoices = append(n.Edges.BillingInvoices, e) + }); err != nil { + return nil, err + } + } + if query := _q.withBillingCustomerOverride; query != nil { + if err := _q.loadBillingCustomerOverride(ctx, query, nodes, + func(n *BillingProfile) { n.Edges.BillingCustomerOverride = []*BillingCustomerOverride{} }, + func(n *BillingProfile, e *BillingCustomerOverride) { + n.Edges.BillingCustomerOverride = append(n.Edges.BillingCustomerOverride, e) + }); err != nil { + return nil, err + } + } + if query := _q.withWorkflowConfig; query != nil { + if err := _q.loadWorkflowConfig(ctx, query, nodes, nil, + func(n *BillingProfile, e *BillingWorkflowConfig) { n.Edges.WorkflowConfig = e }); err != nil { + return nil, err + } + } + if query := _q.withTaxApp; query != nil { + if err := _q.loadTaxApp(ctx, query, nodes, nil, + func(n *BillingProfile, e *App) { n.Edges.TaxApp = e }); err != nil { + return nil, err + } + } + if query := _q.withInvoicingApp; query != nil { + if err := _q.loadInvoicingApp(ctx, query, nodes, nil, + func(n *BillingProfile, e *App) { n.Edges.InvoicingApp = e }); err != nil { + return nil, err + } + } + if query := _q.withPaymentApp; query != nil { + if err := _q.loadPaymentApp(ctx, query, nodes, nil, + func(n *BillingProfile, e *App) { n.Edges.PaymentApp = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *BillingProfileQuery) loadBillingInvoices(ctx context.Context, query *BillingInvoiceQuery, nodes []*BillingProfile, init func(*BillingProfile), assign func(*BillingProfile, *BillingInvoice)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*BillingProfile) + 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(billinginvoice.FieldSourceBillingProfileID) + } + query.Where(predicate.BillingInvoice(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(billingprofile.BillingInvoicesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.SourceBillingProfileID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "source_billing_profile_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *BillingProfileQuery) loadBillingCustomerOverride(ctx context.Context, query *BillingCustomerOverrideQuery, nodes []*BillingProfile, init func(*BillingProfile), assign func(*BillingProfile, *BillingCustomerOverride)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*BillingProfile) + 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(billingcustomeroverride.FieldBillingProfileID) + } + query.Where(predicate.BillingCustomerOverride(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(billingprofile.BillingCustomerOverrideColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.BillingProfileID + if fk == nil { + return fmt.Errorf(`foreign-key "billing_profile_id" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "billing_profile_id" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *BillingProfileQuery) loadWorkflowConfig(ctx context.Context, query *BillingWorkflowConfigQuery, nodes []*BillingProfile, init func(*BillingProfile), assign func(*BillingProfile, *BillingWorkflowConfig)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*BillingProfile) + for i := range nodes { + fk := nodes[i].WorkflowConfigID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(billingworkflowconfig.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 "workflow_config_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *BillingProfileQuery) loadTaxApp(ctx context.Context, query *AppQuery, nodes []*BillingProfile, init func(*BillingProfile), assign func(*BillingProfile, *App)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*BillingProfile) + for i := range nodes { + fk := nodes[i].TaxAppID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(dbapp.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 "tax_app_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *BillingProfileQuery) loadInvoicingApp(ctx context.Context, query *AppQuery, nodes []*BillingProfile, init func(*BillingProfile), assign func(*BillingProfile, *App)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*BillingProfile) + for i := range nodes { + fk := nodes[i].InvoicingAppID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(dbapp.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 "invoicing_app_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *BillingProfileQuery) loadPaymentApp(ctx context.Context, query *AppQuery, nodes []*BillingProfile, init func(*BillingProfile), assign func(*BillingProfile, *App)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*BillingProfile) + for i := range nodes { + fk := nodes[i].PaymentAppID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(dbapp.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 "payment_app_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *BillingProfileQuery) 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 *BillingProfileQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(billingprofile.Table, billingprofile.Columns, sqlgraph.NewFieldSpec(billingprofile.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, billingprofile.FieldID) + for i := range fields { + if fields[i] != billingprofile.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withWorkflowConfig != nil { + _spec.Node.AddColumnOnce(billingprofile.FieldWorkflowConfigID) + } + if _q.withTaxApp != nil { + _spec.Node.AddColumnOnce(billingprofile.FieldTaxAppID) + } + if _q.withInvoicingApp != nil { + _spec.Node.AddColumnOnce(billingprofile.FieldInvoicingAppID) + } + if _q.withPaymentApp != nil { + _spec.Node.AddColumnOnce(billingprofile.FieldPaymentAppID) + } + } + 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 *BillingProfileQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(billingprofile.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = billingprofile.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 *BillingProfileQuery) ForUpdate(opts ...sql.LockOption) *BillingProfileQuery { + 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 *BillingProfileQuery) ForShare(opts ...sql.LockOption) *BillingProfileQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// BillingProfileGroupBy is the group-by builder for BillingProfile entities. +type BillingProfileGroupBy struct { + selector + build *BillingProfileQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *BillingProfileGroupBy) Aggregate(fns ...AggregateFunc) *BillingProfileGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *BillingProfileGroupBy) 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[*BillingProfileQuery, *BillingProfileGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *BillingProfileGroupBy) sqlScan(ctx context.Context, root *BillingProfileQuery, 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) +} + +// BillingProfileSelect is the builder for selecting fields of BillingProfile entities. +type BillingProfileSelect struct { + *BillingProfileQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *BillingProfileSelect) Aggregate(fns ...AggregateFunc) *BillingProfileSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *BillingProfileSelect) 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[*BillingProfileQuery, *BillingProfileSelect](ctx, _s.BillingProfileQuery, _s, _s.inters, v) +} + +func (_s *BillingProfileSelect) sqlScan(ctx context.Context, root *BillingProfileQuery, 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/ent/db/billingprofile_update.go b/ent/db/billingprofile_update.go new file mode 100644 index 0000000000000000000000000000000000000000..93c82b68b6b83e31213fa98be3a2455764d5ec89 --- /dev/null +++ b/ent/db/billingprofile_update.go @@ -0,0 +1,1376 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/billingcustomeroverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingprofile" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingworkflowconfig" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/models" +) + +// BillingProfileUpdate is the builder for updating BillingProfile entities. +type BillingProfileUpdate struct { + config + hooks []Hook + mutation *BillingProfileMutation +} + +// Where appends a list predicates to the BillingProfileUpdate builder. +func (_u *BillingProfileUpdate) Where(ps ...predicate.BillingProfile) *BillingProfileUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *BillingProfileUpdate) SetMetadata(v map[string]string) *BillingProfileUpdate { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *BillingProfileUpdate) ClearMetadata() *BillingProfileUpdate { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *BillingProfileUpdate) SetUpdatedAt(v time.Time) *BillingProfileUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *BillingProfileUpdate) SetDeletedAt(v time.Time) *BillingProfileUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *BillingProfileUpdate) SetNillableDeletedAt(v *time.Time) *BillingProfileUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *BillingProfileUpdate) ClearDeletedAt() *BillingProfileUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *BillingProfileUpdate) SetName(v string) *BillingProfileUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *BillingProfileUpdate) SetNillableName(v *string) *BillingProfileUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *BillingProfileUpdate) SetDescription(v string) *BillingProfileUpdate { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *BillingProfileUpdate) SetNillableDescription(v *string) *BillingProfileUpdate { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *BillingProfileUpdate) ClearDescription() *BillingProfileUpdate { + _u.mutation.ClearDescription() + return _u +} + +// SetSupplierAddressCountry sets the "supplier_address_country" field. +func (_u *BillingProfileUpdate) SetSupplierAddressCountry(v models.CountryCode) *BillingProfileUpdate { + _u.mutation.SetSupplierAddressCountry(v) + return _u +} + +// SetNillableSupplierAddressCountry sets the "supplier_address_country" field if the given value is not nil. +func (_u *BillingProfileUpdate) SetNillableSupplierAddressCountry(v *models.CountryCode) *BillingProfileUpdate { + if v != nil { + _u.SetSupplierAddressCountry(*v) + } + return _u +} + +// ClearSupplierAddressCountry clears the value of the "supplier_address_country" field. +func (_u *BillingProfileUpdate) ClearSupplierAddressCountry() *BillingProfileUpdate { + _u.mutation.ClearSupplierAddressCountry() + return _u +} + +// SetSupplierAddressPostalCode sets the "supplier_address_postal_code" field. +func (_u *BillingProfileUpdate) SetSupplierAddressPostalCode(v string) *BillingProfileUpdate { + _u.mutation.SetSupplierAddressPostalCode(v) + return _u +} + +// SetNillableSupplierAddressPostalCode sets the "supplier_address_postal_code" field if the given value is not nil. +func (_u *BillingProfileUpdate) SetNillableSupplierAddressPostalCode(v *string) *BillingProfileUpdate { + if v != nil { + _u.SetSupplierAddressPostalCode(*v) + } + return _u +} + +// ClearSupplierAddressPostalCode clears the value of the "supplier_address_postal_code" field. +func (_u *BillingProfileUpdate) ClearSupplierAddressPostalCode() *BillingProfileUpdate { + _u.mutation.ClearSupplierAddressPostalCode() + return _u +} + +// SetSupplierAddressState sets the "supplier_address_state" field. +func (_u *BillingProfileUpdate) SetSupplierAddressState(v string) *BillingProfileUpdate { + _u.mutation.SetSupplierAddressState(v) + return _u +} + +// SetNillableSupplierAddressState sets the "supplier_address_state" field if the given value is not nil. +func (_u *BillingProfileUpdate) SetNillableSupplierAddressState(v *string) *BillingProfileUpdate { + if v != nil { + _u.SetSupplierAddressState(*v) + } + return _u +} + +// ClearSupplierAddressState clears the value of the "supplier_address_state" field. +func (_u *BillingProfileUpdate) ClearSupplierAddressState() *BillingProfileUpdate { + _u.mutation.ClearSupplierAddressState() + return _u +} + +// SetSupplierAddressCity sets the "supplier_address_city" field. +func (_u *BillingProfileUpdate) SetSupplierAddressCity(v string) *BillingProfileUpdate { + _u.mutation.SetSupplierAddressCity(v) + return _u +} + +// SetNillableSupplierAddressCity sets the "supplier_address_city" field if the given value is not nil. +func (_u *BillingProfileUpdate) SetNillableSupplierAddressCity(v *string) *BillingProfileUpdate { + if v != nil { + _u.SetSupplierAddressCity(*v) + } + return _u +} + +// ClearSupplierAddressCity clears the value of the "supplier_address_city" field. +func (_u *BillingProfileUpdate) ClearSupplierAddressCity() *BillingProfileUpdate { + _u.mutation.ClearSupplierAddressCity() + return _u +} + +// SetSupplierAddressLine1 sets the "supplier_address_line1" field. +func (_u *BillingProfileUpdate) SetSupplierAddressLine1(v string) *BillingProfileUpdate { + _u.mutation.SetSupplierAddressLine1(v) + return _u +} + +// SetNillableSupplierAddressLine1 sets the "supplier_address_line1" field if the given value is not nil. +func (_u *BillingProfileUpdate) SetNillableSupplierAddressLine1(v *string) *BillingProfileUpdate { + if v != nil { + _u.SetSupplierAddressLine1(*v) + } + return _u +} + +// ClearSupplierAddressLine1 clears the value of the "supplier_address_line1" field. +func (_u *BillingProfileUpdate) ClearSupplierAddressLine1() *BillingProfileUpdate { + _u.mutation.ClearSupplierAddressLine1() + return _u +} + +// SetSupplierAddressLine2 sets the "supplier_address_line2" field. +func (_u *BillingProfileUpdate) SetSupplierAddressLine2(v string) *BillingProfileUpdate { + _u.mutation.SetSupplierAddressLine2(v) + return _u +} + +// SetNillableSupplierAddressLine2 sets the "supplier_address_line2" field if the given value is not nil. +func (_u *BillingProfileUpdate) SetNillableSupplierAddressLine2(v *string) *BillingProfileUpdate { + if v != nil { + _u.SetSupplierAddressLine2(*v) + } + return _u +} + +// ClearSupplierAddressLine2 clears the value of the "supplier_address_line2" field. +func (_u *BillingProfileUpdate) ClearSupplierAddressLine2() *BillingProfileUpdate { + _u.mutation.ClearSupplierAddressLine2() + return _u +} + +// SetSupplierAddressPhoneNumber sets the "supplier_address_phone_number" field. +func (_u *BillingProfileUpdate) SetSupplierAddressPhoneNumber(v string) *BillingProfileUpdate { + _u.mutation.SetSupplierAddressPhoneNumber(v) + return _u +} + +// SetNillableSupplierAddressPhoneNumber sets the "supplier_address_phone_number" field if the given value is not nil. +func (_u *BillingProfileUpdate) SetNillableSupplierAddressPhoneNumber(v *string) *BillingProfileUpdate { + if v != nil { + _u.SetSupplierAddressPhoneNumber(*v) + } + return _u +} + +// ClearSupplierAddressPhoneNumber clears the value of the "supplier_address_phone_number" field. +func (_u *BillingProfileUpdate) ClearSupplierAddressPhoneNumber() *BillingProfileUpdate { + _u.mutation.ClearSupplierAddressPhoneNumber() + return _u +} + +// SetWorkflowConfigID sets the "workflow_config_id" field. +func (_u *BillingProfileUpdate) SetWorkflowConfigID(v string) *BillingProfileUpdate { + _u.mutation.SetWorkflowConfigID(v) + return _u +} + +// SetNillableWorkflowConfigID sets the "workflow_config_id" field if the given value is not nil. +func (_u *BillingProfileUpdate) SetNillableWorkflowConfigID(v *string) *BillingProfileUpdate { + if v != nil { + _u.SetWorkflowConfigID(*v) + } + return _u +} + +// SetDefault sets the "default" field. +func (_u *BillingProfileUpdate) SetDefault(v bool) *BillingProfileUpdate { + _u.mutation.SetDefault(v) + return _u +} + +// SetNillableDefault sets the "default" field if the given value is not nil. +func (_u *BillingProfileUpdate) SetNillableDefault(v *bool) *BillingProfileUpdate { + if v != nil { + _u.SetDefault(*v) + } + return _u +} + +// SetSupplierName sets the "supplier_name" field. +func (_u *BillingProfileUpdate) SetSupplierName(v string) *BillingProfileUpdate { + _u.mutation.SetSupplierName(v) + return _u +} + +// SetNillableSupplierName sets the "supplier_name" field if the given value is not nil. +func (_u *BillingProfileUpdate) SetNillableSupplierName(v *string) *BillingProfileUpdate { + if v != nil { + _u.SetSupplierName(*v) + } + return _u +} + +// SetSupplierTaxCode sets the "supplier_tax_code" field. +func (_u *BillingProfileUpdate) SetSupplierTaxCode(v string) *BillingProfileUpdate { + _u.mutation.SetSupplierTaxCode(v) + return _u +} + +// SetNillableSupplierTaxCode sets the "supplier_tax_code" field if the given value is not nil. +func (_u *BillingProfileUpdate) SetNillableSupplierTaxCode(v *string) *BillingProfileUpdate { + if v != nil { + _u.SetSupplierTaxCode(*v) + } + return _u +} + +// ClearSupplierTaxCode clears the value of the "supplier_tax_code" field. +func (_u *BillingProfileUpdate) ClearSupplierTaxCode() *BillingProfileUpdate { + _u.mutation.ClearSupplierTaxCode() + return _u +} + +// AddBillingInvoiceIDs adds the "billing_invoices" edge to the BillingInvoice entity by IDs. +func (_u *BillingProfileUpdate) AddBillingInvoiceIDs(ids ...string) *BillingProfileUpdate { + _u.mutation.AddBillingInvoiceIDs(ids...) + return _u +} + +// AddBillingInvoices adds the "billing_invoices" edges to the BillingInvoice entity. +func (_u *BillingProfileUpdate) AddBillingInvoices(v ...*BillingInvoice) *BillingProfileUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddBillingInvoiceIDs(ids...) +} + +// AddBillingCustomerOverrideIDs adds the "billing_customer_override" edge to the BillingCustomerOverride entity by IDs. +func (_u *BillingProfileUpdate) AddBillingCustomerOverrideIDs(ids ...string) *BillingProfileUpdate { + _u.mutation.AddBillingCustomerOverrideIDs(ids...) + return _u +} + +// AddBillingCustomerOverride adds the "billing_customer_override" edges to the BillingCustomerOverride entity. +func (_u *BillingProfileUpdate) AddBillingCustomerOverride(v ...*BillingCustomerOverride) *BillingProfileUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddBillingCustomerOverrideIDs(ids...) +} + +// SetWorkflowConfig sets the "workflow_config" edge to the BillingWorkflowConfig entity. +func (_u *BillingProfileUpdate) SetWorkflowConfig(v *BillingWorkflowConfig) *BillingProfileUpdate { + return _u.SetWorkflowConfigID(v.ID) +} + +// Mutation returns the BillingProfileMutation object of the builder. +func (_u *BillingProfileUpdate) Mutation() *BillingProfileMutation { + return _u.mutation +} + +// ClearBillingInvoices clears all "billing_invoices" edges to the BillingInvoice entity. +func (_u *BillingProfileUpdate) ClearBillingInvoices() *BillingProfileUpdate { + _u.mutation.ClearBillingInvoices() + return _u +} + +// RemoveBillingInvoiceIDs removes the "billing_invoices" edge to BillingInvoice entities by IDs. +func (_u *BillingProfileUpdate) RemoveBillingInvoiceIDs(ids ...string) *BillingProfileUpdate { + _u.mutation.RemoveBillingInvoiceIDs(ids...) + return _u +} + +// RemoveBillingInvoices removes "billing_invoices" edges to BillingInvoice entities. +func (_u *BillingProfileUpdate) RemoveBillingInvoices(v ...*BillingInvoice) *BillingProfileUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveBillingInvoiceIDs(ids...) +} + +// ClearBillingCustomerOverride clears all "billing_customer_override" edges to the BillingCustomerOverride entity. +func (_u *BillingProfileUpdate) ClearBillingCustomerOverride() *BillingProfileUpdate { + _u.mutation.ClearBillingCustomerOverride() + return _u +} + +// RemoveBillingCustomerOverrideIDs removes the "billing_customer_override" edge to BillingCustomerOverride entities by IDs. +func (_u *BillingProfileUpdate) RemoveBillingCustomerOverrideIDs(ids ...string) *BillingProfileUpdate { + _u.mutation.RemoveBillingCustomerOverrideIDs(ids...) + return _u +} + +// RemoveBillingCustomerOverride removes "billing_customer_override" edges to BillingCustomerOverride entities. +func (_u *BillingProfileUpdate) RemoveBillingCustomerOverride(v ...*BillingCustomerOverride) *BillingProfileUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveBillingCustomerOverrideIDs(ids...) +} + +// ClearWorkflowConfig clears the "workflow_config" edge to the BillingWorkflowConfig entity. +func (_u *BillingProfileUpdate) ClearWorkflowConfig() *BillingProfileUpdate { + _u.mutation.ClearWorkflowConfig() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *BillingProfileUpdate) 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 *BillingProfileUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *BillingProfileUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingProfileUpdate) 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 *BillingProfileUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := billingprofile.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *BillingProfileUpdate) check() error { + if v, ok := _u.mutation.SupplierAddressCountry(); ok { + if err := billingprofile.SupplierAddressCountryValidator(string(v)); err != nil { + return &ValidationError{Name: "supplier_address_country", err: fmt.Errorf(`db: validator failed for field "BillingProfile.supplier_address_country": %w`, err)} + } + } + if v, ok := _u.mutation.WorkflowConfigID(); ok { + if err := billingprofile.WorkflowConfigIDValidator(v); err != nil { + return &ValidationError{Name: "workflow_config_id", err: fmt.Errorf(`db: validator failed for field "BillingProfile.workflow_config_id": %w`, err)} + } + } + if v, ok := _u.mutation.SupplierName(); ok { + if err := billingprofile.SupplierNameValidator(v); err != nil { + return &ValidationError{Name: "supplier_name", err: fmt.Errorf(`db: validator failed for field "BillingProfile.supplier_name": %w`, err)} + } + } + if _u.mutation.WorkflowConfigCleared() && len(_u.mutation.WorkflowConfigIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "BillingProfile.workflow_config"`) + } + if _u.mutation.TaxAppCleared() && len(_u.mutation.TaxAppIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "BillingProfile.tax_app"`) + } + if _u.mutation.InvoicingAppCleared() && len(_u.mutation.InvoicingAppIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "BillingProfile.invoicing_app"`) + } + if _u.mutation.PaymentAppCleared() && len(_u.mutation.PaymentAppIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "BillingProfile.payment_app"`) + } + return nil +} + +func (_u *BillingProfileUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(billingprofile.Table, billingprofile.Columns, sqlgraph.NewFieldSpec(billingprofile.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.Metadata(); ok { + _spec.SetField(billingprofile.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(billingprofile.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(billingprofile.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(billingprofile.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(billingprofile.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(billingprofile.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(billingprofile.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(billingprofile.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.SupplierAddressCountry(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressCountry, field.TypeString, value) + } + if _u.mutation.SupplierAddressCountryCleared() { + _spec.ClearField(billingprofile.FieldSupplierAddressCountry, field.TypeString) + } + if value, ok := _u.mutation.SupplierAddressPostalCode(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressPostalCode, field.TypeString, value) + } + if _u.mutation.SupplierAddressPostalCodeCleared() { + _spec.ClearField(billingprofile.FieldSupplierAddressPostalCode, field.TypeString) + } + if value, ok := _u.mutation.SupplierAddressState(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressState, field.TypeString, value) + } + if _u.mutation.SupplierAddressStateCleared() { + _spec.ClearField(billingprofile.FieldSupplierAddressState, field.TypeString) + } + if value, ok := _u.mutation.SupplierAddressCity(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressCity, field.TypeString, value) + } + if _u.mutation.SupplierAddressCityCleared() { + _spec.ClearField(billingprofile.FieldSupplierAddressCity, field.TypeString) + } + if value, ok := _u.mutation.SupplierAddressLine1(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressLine1, field.TypeString, value) + } + if _u.mutation.SupplierAddressLine1Cleared() { + _spec.ClearField(billingprofile.FieldSupplierAddressLine1, field.TypeString) + } + if value, ok := _u.mutation.SupplierAddressLine2(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressLine2, field.TypeString, value) + } + if _u.mutation.SupplierAddressLine2Cleared() { + _spec.ClearField(billingprofile.FieldSupplierAddressLine2, field.TypeString) + } + if value, ok := _u.mutation.SupplierAddressPhoneNumber(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressPhoneNumber, field.TypeString, value) + } + if _u.mutation.SupplierAddressPhoneNumberCleared() { + _spec.ClearField(billingprofile.FieldSupplierAddressPhoneNumber, field.TypeString) + } + if value, ok := _u.mutation.Default(); ok { + _spec.SetField(billingprofile.FieldDefault, field.TypeBool, value) + } + if value, ok := _u.mutation.SupplierName(); ok { + _spec.SetField(billingprofile.FieldSupplierName, field.TypeString, value) + } + if value, ok := _u.mutation.SupplierTaxCode(); ok { + _spec.SetField(billingprofile.FieldSupplierTaxCode, field.TypeString, value) + } + if _u.mutation.SupplierTaxCodeCleared() { + _spec.ClearField(billingprofile.FieldSupplierTaxCode, field.TypeString) + } + if _u.mutation.BillingInvoicesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingprofile.BillingInvoicesTable, + Columns: []string{billingprofile.BillingInvoicesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedBillingInvoicesIDs(); len(nodes) > 0 && !_u.mutation.BillingInvoicesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingprofile.BillingInvoicesTable, + Columns: []string{billingprofile.BillingInvoicesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.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.BillingInvoicesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingprofile.BillingInvoicesTable, + Columns: []string{billingprofile.BillingInvoicesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.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.BillingCustomerOverrideCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingprofile.BillingCustomerOverrideTable, + Columns: []string{billingprofile.BillingCustomerOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingcustomeroverride.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedBillingCustomerOverrideIDs(); len(nodes) > 0 && !_u.mutation.BillingCustomerOverrideCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingprofile.BillingCustomerOverrideTable, + Columns: []string{billingprofile.BillingCustomerOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingcustomeroverride.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.BillingCustomerOverrideIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingprofile.BillingCustomerOverrideTable, + Columns: []string{billingprofile.BillingCustomerOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingcustomeroverride.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.WorkflowConfigCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: billingprofile.WorkflowConfigTable, + Columns: []string{billingprofile.WorkflowConfigColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingworkflowconfig.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.WorkflowConfigIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: billingprofile.WorkflowConfigTable, + Columns: []string{billingprofile.WorkflowConfigColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingworkflowconfig.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{billingprofile.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// BillingProfileUpdateOne is the builder for updating a single BillingProfile entity. +type BillingProfileUpdateOne struct { + config + fields []string + hooks []Hook + mutation *BillingProfileMutation +} + +// SetMetadata sets the "metadata" field. +func (_u *BillingProfileUpdateOne) SetMetadata(v map[string]string) *BillingProfileUpdateOne { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *BillingProfileUpdateOne) ClearMetadata() *BillingProfileUpdateOne { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *BillingProfileUpdateOne) SetUpdatedAt(v time.Time) *BillingProfileUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *BillingProfileUpdateOne) SetDeletedAt(v time.Time) *BillingProfileUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *BillingProfileUpdateOne) SetNillableDeletedAt(v *time.Time) *BillingProfileUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *BillingProfileUpdateOne) ClearDeletedAt() *BillingProfileUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *BillingProfileUpdateOne) SetName(v string) *BillingProfileUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *BillingProfileUpdateOne) SetNillableName(v *string) *BillingProfileUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *BillingProfileUpdateOne) SetDescription(v string) *BillingProfileUpdateOne { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *BillingProfileUpdateOne) SetNillableDescription(v *string) *BillingProfileUpdateOne { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *BillingProfileUpdateOne) ClearDescription() *BillingProfileUpdateOne { + _u.mutation.ClearDescription() + return _u +} + +// SetSupplierAddressCountry sets the "supplier_address_country" field. +func (_u *BillingProfileUpdateOne) SetSupplierAddressCountry(v models.CountryCode) *BillingProfileUpdateOne { + _u.mutation.SetSupplierAddressCountry(v) + return _u +} + +// SetNillableSupplierAddressCountry sets the "supplier_address_country" field if the given value is not nil. +func (_u *BillingProfileUpdateOne) SetNillableSupplierAddressCountry(v *models.CountryCode) *BillingProfileUpdateOne { + if v != nil { + _u.SetSupplierAddressCountry(*v) + } + return _u +} + +// ClearSupplierAddressCountry clears the value of the "supplier_address_country" field. +func (_u *BillingProfileUpdateOne) ClearSupplierAddressCountry() *BillingProfileUpdateOne { + _u.mutation.ClearSupplierAddressCountry() + return _u +} + +// SetSupplierAddressPostalCode sets the "supplier_address_postal_code" field. +func (_u *BillingProfileUpdateOne) SetSupplierAddressPostalCode(v string) *BillingProfileUpdateOne { + _u.mutation.SetSupplierAddressPostalCode(v) + return _u +} + +// SetNillableSupplierAddressPostalCode sets the "supplier_address_postal_code" field if the given value is not nil. +func (_u *BillingProfileUpdateOne) SetNillableSupplierAddressPostalCode(v *string) *BillingProfileUpdateOne { + if v != nil { + _u.SetSupplierAddressPostalCode(*v) + } + return _u +} + +// ClearSupplierAddressPostalCode clears the value of the "supplier_address_postal_code" field. +func (_u *BillingProfileUpdateOne) ClearSupplierAddressPostalCode() *BillingProfileUpdateOne { + _u.mutation.ClearSupplierAddressPostalCode() + return _u +} + +// SetSupplierAddressState sets the "supplier_address_state" field. +func (_u *BillingProfileUpdateOne) SetSupplierAddressState(v string) *BillingProfileUpdateOne { + _u.mutation.SetSupplierAddressState(v) + return _u +} + +// SetNillableSupplierAddressState sets the "supplier_address_state" field if the given value is not nil. +func (_u *BillingProfileUpdateOne) SetNillableSupplierAddressState(v *string) *BillingProfileUpdateOne { + if v != nil { + _u.SetSupplierAddressState(*v) + } + return _u +} + +// ClearSupplierAddressState clears the value of the "supplier_address_state" field. +func (_u *BillingProfileUpdateOne) ClearSupplierAddressState() *BillingProfileUpdateOne { + _u.mutation.ClearSupplierAddressState() + return _u +} + +// SetSupplierAddressCity sets the "supplier_address_city" field. +func (_u *BillingProfileUpdateOne) SetSupplierAddressCity(v string) *BillingProfileUpdateOne { + _u.mutation.SetSupplierAddressCity(v) + return _u +} + +// SetNillableSupplierAddressCity sets the "supplier_address_city" field if the given value is not nil. +func (_u *BillingProfileUpdateOne) SetNillableSupplierAddressCity(v *string) *BillingProfileUpdateOne { + if v != nil { + _u.SetSupplierAddressCity(*v) + } + return _u +} + +// ClearSupplierAddressCity clears the value of the "supplier_address_city" field. +func (_u *BillingProfileUpdateOne) ClearSupplierAddressCity() *BillingProfileUpdateOne { + _u.mutation.ClearSupplierAddressCity() + return _u +} + +// SetSupplierAddressLine1 sets the "supplier_address_line1" field. +func (_u *BillingProfileUpdateOne) SetSupplierAddressLine1(v string) *BillingProfileUpdateOne { + _u.mutation.SetSupplierAddressLine1(v) + return _u +} + +// SetNillableSupplierAddressLine1 sets the "supplier_address_line1" field if the given value is not nil. +func (_u *BillingProfileUpdateOne) SetNillableSupplierAddressLine1(v *string) *BillingProfileUpdateOne { + if v != nil { + _u.SetSupplierAddressLine1(*v) + } + return _u +} + +// ClearSupplierAddressLine1 clears the value of the "supplier_address_line1" field. +func (_u *BillingProfileUpdateOne) ClearSupplierAddressLine1() *BillingProfileUpdateOne { + _u.mutation.ClearSupplierAddressLine1() + return _u +} + +// SetSupplierAddressLine2 sets the "supplier_address_line2" field. +func (_u *BillingProfileUpdateOne) SetSupplierAddressLine2(v string) *BillingProfileUpdateOne { + _u.mutation.SetSupplierAddressLine2(v) + return _u +} + +// SetNillableSupplierAddressLine2 sets the "supplier_address_line2" field if the given value is not nil. +func (_u *BillingProfileUpdateOne) SetNillableSupplierAddressLine2(v *string) *BillingProfileUpdateOne { + if v != nil { + _u.SetSupplierAddressLine2(*v) + } + return _u +} + +// ClearSupplierAddressLine2 clears the value of the "supplier_address_line2" field. +func (_u *BillingProfileUpdateOne) ClearSupplierAddressLine2() *BillingProfileUpdateOne { + _u.mutation.ClearSupplierAddressLine2() + return _u +} + +// SetSupplierAddressPhoneNumber sets the "supplier_address_phone_number" field. +func (_u *BillingProfileUpdateOne) SetSupplierAddressPhoneNumber(v string) *BillingProfileUpdateOne { + _u.mutation.SetSupplierAddressPhoneNumber(v) + return _u +} + +// SetNillableSupplierAddressPhoneNumber sets the "supplier_address_phone_number" field if the given value is not nil. +func (_u *BillingProfileUpdateOne) SetNillableSupplierAddressPhoneNumber(v *string) *BillingProfileUpdateOne { + if v != nil { + _u.SetSupplierAddressPhoneNumber(*v) + } + return _u +} + +// ClearSupplierAddressPhoneNumber clears the value of the "supplier_address_phone_number" field. +func (_u *BillingProfileUpdateOne) ClearSupplierAddressPhoneNumber() *BillingProfileUpdateOne { + _u.mutation.ClearSupplierAddressPhoneNumber() + return _u +} + +// SetWorkflowConfigID sets the "workflow_config_id" field. +func (_u *BillingProfileUpdateOne) SetWorkflowConfigID(v string) *BillingProfileUpdateOne { + _u.mutation.SetWorkflowConfigID(v) + return _u +} + +// SetNillableWorkflowConfigID sets the "workflow_config_id" field if the given value is not nil. +func (_u *BillingProfileUpdateOne) SetNillableWorkflowConfigID(v *string) *BillingProfileUpdateOne { + if v != nil { + _u.SetWorkflowConfigID(*v) + } + return _u +} + +// SetDefault sets the "default" field. +func (_u *BillingProfileUpdateOne) SetDefault(v bool) *BillingProfileUpdateOne { + _u.mutation.SetDefault(v) + return _u +} + +// SetNillableDefault sets the "default" field if the given value is not nil. +func (_u *BillingProfileUpdateOne) SetNillableDefault(v *bool) *BillingProfileUpdateOne { + if v != nil { + _u.SetDefault(*v) + } + return _u +} + +// SetSupplierName sets the "supplier_name" field. +func (_u *BillingProfileUpdateOne) SetSupplierName(v string) *BillingProfileUpdateOne { + _u.mutation.SetSupplierName(v) + return _u +} + +// SetNillableSupplierName sets the "supplier_name" field if the given value is not nil. +func (_u *BillingProfileUpdateOne) SetNillableSupplierName(v *string) *BillingProfileUpdateOne { + if v != nil { + _u.SetSupplierName(*v) + } + return _u +} + +// SetSupplierTaxCode sets the "supplier_tax_code" field. +func (_u *BillingProfileUpdateOne) SetSupplierTaxCode(v string) *BillingProfileUpdateOne { + _u.mutation.SetSupplierTaxCode(v) + return _u +} + +// SetNillableSupplierTaxCode sets the "supplier_tax_code" field if the given value is not nil. +func (_u *BillingProfileUpdateOne) SetNillableSupplierTaxCode(v *string) *BillingProfileUpdateOne { + if v != nil { + _u.SetSupplierTaxCode(*v) + } + return _u +} + +// ClearSupplierTaxCode clears the value of the "supplier_tax_code" field. +func (_u *BillingProfileUpdateOne) ClearSupplierTaxCode() *BillingProfileUpdateOne { + _u.mutation.ClearSupplierTaxCode() + return _u +} + +// AddBillingInvoiceIDs adds the "billing_invoices" edge to the BillingInvoice entity by IDs. +func (_u *BillingProfileUpdateOne) AddBillingInvoiceIDs(ids ...string) *BillingProfileUpdateOne { + _u.mutation.AddBillingInvoiceIDs(ids...) + return _u +} + +// AddBillingInvoices adds the "billing_invoices" edges to the BillingInvoice entity. +func (_u *BillingProfileUpdateOne) AddBillingInvoices(v ...*BillingInvoice) *BillingProfileUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddBillingInvoiceIDs(ids...) +} + +// AddBillingCustomerOverrideIDs adds the "billing_customer_override" edge to the BillingCustomerOverride entity by IDs. +func (_u *BillingProfileUpdateOne) AddBillingCustomerOverrideIDs(ids ...string) *BillingProfileUpdateOne { + _u.mutation.AddBillingCustomerOverrideIDs(ids...) + return _u +} + +// AddBillingCustomerOverride adds the "billing_customer_override" edges to the BillingCustomerOverride entity. +func (_u *BillingProfileUpdateOne) AddBillingCustomerOverride(v ...*BillingCustomerOverride) *BillingProfileUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddBillingCustomerOverrideIDs(ids...) +} + +// SetWorkflowConfig sets the "workflow_config" edge to the BillingWorkflowConfig entity. +func (_u *BillingProfileUpdateOne) SetWorkflowConfig(v *BillingWorkflowConfig) *BillingProfileUpdateOne { + return _u.SetWorkflowConfigID(v.ID) +} + +// Mutation returns the BillingProfileMutation object of the builder. +func (_u *BillingProfileUpdateOne) Mutation() *BillingProfileMutation { + return _u.mutation +} + +// ClearBillingInvoices clears all "billing_invoices" edges to the BillingInvoice entity. +func (_u *BillingProfileUpdateOne) ClearBillingInvoices() *BillingProfileUpdateOne { + _u.mutation.ClearBillingInvoices() + return _u +} + +// RemoveBillingInvoiceIDs removes the "billing_invoices" edge to BillingInvoice entities by IDs. +func (_u *BillingProfileUpdateOne) RemoveBillingInvoiceIDs(ids ...string) *BillingProfileUpdateOne { + _u.mutation.RemoveBillingInvoiceIDs(ids...) + return _u +} + +// RemoveBillingInvoices removes "billing_invoices" edges to BillingInvoice entities. +func (_u *BillingProfileUpdateOne) RemoveBillingInvoices(v ...*BillingInvoice) *BillingProfileUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveBillingInvoiceIDs(ids...) +} + +// ClearBillingCustomerOverride clears all "billing_customer_override" edges to the BillingCustomerOverride entity. +func (_u *BillingProfileUpdateOne) ClearBillingCustomerOverride() *BillingProfileUpdateOne { + _u.mutation.ClearBillingCustomerOverride() + return _u +} + +// RemoveBillingCustomerOverrideIDs removes the "billing_customer_override" edge to BillingCustomerOverride entities by IDs. +func (_u *BillingProfileUpdateOne) RemoveBillingCustomerOverrideIDs(ids ...string) *BillingProfileUpdateOne { + _u.mutation.RemoveBillingCustomerOverrideIDs(ids...) + return _u +} + +// RemoveBillingCustomerOverride removes "billing_customer_override" edges to BillingCustomerOverride entities. +func (_u *BillingProfileUpdateOne) RemoveBillingCustomerOverride(v ...*BillingCustomerOverride) *BillingProfileUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveBillingCustomerOverrideIDs(ids...) +} + +// ClearWorkflowConfig clears the "workflow_config" edge to the BillingWorkflowConfig entity. +func (_u *BillingProfileUpdateOne) ClearWorkflowConfig() *BillingProfileUpdateOne { + _u.mutation.ClearWorkflowConfig() + return _u +} + +// Where appends a list predicates to the BillingProfileUpdate builder. +func (_u *BillingProfileUpdateOne) Where(ps ...predicate.BillingProfile) *BillingProfileUpdateOne { + _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 *BillingProfileUpdateOne) Select(field string, fields ...string) *BillingProfileUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated BillingProfile entity. +func (_u *BillingProfileUpdateOne) Save(ctx context.Context) (*BillingProfile, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *BillingProfileUpdateOne) SaveX(ctx context.Context) *BillingProfile { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *BillingProfileUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingProfileUpdateOne) 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 *BillingProfileUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := billingprofile.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *BillingProfileUpdateOne) check() error { + if v, ok := _u.mutation.SupplierAddressCountry(); ok { + if err := billingprofile.SupplierAddressCountryValidator(string(v)); err != nil { + return &ValidationError{Name: "supplier_address_country", err: fmt.Errorf(`db: validator failed for field "BillingProfile.supplier_address_country": %w`, err)} + } + } + if v, ok := _u.mutation.WorkflowConfigID(); ok { + if err := billingprofile.WorkflowConfigIDValidator(v); err != nil { + return &ValidationError{Name: "workflow_config_id", err: fmt.Errorf(`db: validator failed for field "BillingProfile.workflow_config_id": %w`, err)} + } + } + if v, ok := _u.mutation.SupplierName(); ok { + if err := billingprofile.SupplierNameValidator(v); err != nil { + return &ValidationError{Name: "supplier_name", err: fmt.Errorf(`db: validator failed for field "BillingProfile.supplier_name": %w`, err)} + } + } + if _u.mutation.WorkflowConfigCleared() && len(_u.mutation.WorkflowConfigIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "BillingProfile.workflow_config"`) + } + if _u.mutation.TaxAppCleared() && len(_u.mutation.TaxAppIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "BillingProfile.tax_app"`) + } + if _u.mutation.InvoicingAppCleared() && len(_u.mutation.InvoicingAppIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "BillingProfile.invoicing_app"`) + } + if _u.mutation.PaymentAppCleared() && len(_u.mutation.PaymentAppIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "BillingProfile.payment_app"`) + } + return nil +} + +func (_u *BillingProfileUpdateOne) sqlSave(ctx context.Context) (_node *BillingProfile, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(billingprofile.Table, billingprofile.Columns, sqlgraph.NewFieldSpec(billingprofile.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "BillingProfile.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, billingprofile.FieldID) + for _, f := range fields { + if !billingprofile.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != billingprofile.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.Metadata(); ok { + _spec.SetField(billingprofile.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(billingprofile.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(billingprofile.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(billingprofile.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(billingprofile.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(billingprofile.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(billingprofile.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(billingprofile.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.SupplierAddressCountry(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressCountry, field.TypeString, value) + } + if _u.mutation.SupplierAddressCountryCleared() { + _spec.ClearField(billingprofile.FieldSupplierAddressCountry, field.TypeString) + } + if value, ok := _u.mutation.SupplierAddressPostalCode(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressPostalCode, field.TypeString, value) + } + if _u.mutation.SupplierAddressPostalCodeCleared() { + _spec.ClearField(billingprofile.FieldSupplierAddressPostalCode, field.TypeString) + } + if value, ok := _u.mutation.SupplierAddressState(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressState, field.TypeString, value) + } + if _u.mutation.SupplierAddressStateCleared() { + _spec.ClearField(billingprofile.FieldSupplierAddressState, field.TypeString) + } + if value, ok := _u.mutation.SupplierAddressCity(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressCity, field.TypeString, value) + } + if _u.mutation.SupplierAddressCityCleared() { + _spec.ClearField(billingprofile.FieldSupplierAddressCity, field.TypeString) + } + if value, ok := _u.mutation.SupplierAddressLine1(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressLine1, field.TypeString, value) + } + if _u.mutation.SupplierAddressLine1Cleared() { + _spec.ClearField(billingprofile.FieldSupplierAddressLine1, field.TypeString) + } + if value, ok := _u.mutation.SupplierAddressLine2(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressLine2, field.TypeString, value) + } + if _u.mutation.SupplierAddressLine2Cleared() { + _spec.ClearField(billingprofile.FieldSupplierAddressLine2, field.TypeString) + } + if value, ok := _u.mutation.SupplierAddressPhoneNumber(); ok { + _spec.SetField(billingprofile.FieldSupplierAddressPhoneNumber, field.TypeString, value) + } + if _u.mutation.SupplierAddressPhoneNumberCleared() { + _spec.ClearField(billingprofile.FieldSupplierAddressPhoneNumber, field.TypeString) + } + if value, ok := _u.mutation.Default(); ok { + _spec.SetField(billingprofile.FieldDefault, field.TypeBool, value) + } + if value, ok := _u.mutation.SupplierName(); ok { + _spec.SetField(billingprofile.FieldSupplierName, field.TypeString, value) + } + if value, ok := _u.mutation.SupplierTaxCode(); ok { + _spec.SetField(billingprofile.FieldSupplierTaxCode, field.TypeString, value) + } + if _u.mutation.SupplierTaxCodeCleared() { + _spec.ClearField(billingprofile.FieldSupplierTaxCode, field.TypeString) + } + if _u.mutation.BillingInvoicesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingprofile.BillingInvoicesTable, + Columns: []string{billingprofile.BillingInvoicesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedBillingInvoicesIDs(); len(nodes) > 0 && !_u.mutation.BillingInvoicesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingprofile.BillingInvoicesTable, + Columns: []string{billingprofile.BillingInvoicesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.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.BillingInvoicesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingprofile.BillingInvoicesTable, + Columns: []string{billingprofile.BillingInvoicesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.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.BillingCustomerOverrideCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingprofile.BillingCustomerOverrideTable, + Columns: []string{billingprofile.BillingCustomerOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingcustomeroverride.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedBillingCustomerOverrideIDs(); len(nodes) > 0 && !_u.mutation.BillingCustomerOverrideCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingprofile.BillingCustomerOverrideTable, + Columns: []string{billingprofile.BillingCustomerOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingcustomeroverride.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.BillingCustomerOverrideIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingprofile.BillingCustomerOverrideTable, + Columns: []string{billingprofile.BillingCustomerOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingcustomeroverride.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.WorkflowConfigCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: billingprofile.WorkflowConfigTable, + Columns: []string{billingprofile.WorkflowConfigColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingworkflowconfig.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.WorkflowConfigIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: billingprofile.WorkflowConfigTable, + Columns: []string{billingprofile.WorkflowConfigColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingworkflowconfig.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &BillingProfile{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{billingprofile.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/ent/db/billingsequencenumbers.go b/ent/db/billingsequencenumbers.go new file mode 100644 index 0000000000000000000000000000000000000000..661af153f9d96fe163e0ee1807af7506b43241b7 --- /dev/null +++ b/ent/db/billingsequencenumbers.go @@ -0,0 +1,128 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingsequencenumbers" +) + +// BillingSequenceNumbers is the model entity for the BillingSequenceNumbers schema. +type BillingSequenceNumbers struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Namespace holds the value of the "namespace" field. + Namespace string `json:"namespace,omitempty"` + // Scope holds the value of the "scope" field. + Scope string `json:"scope,omitempty"` + // Last holds the value of the "last" field. + Last alpacadecimal.Decimal `json:"last,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*BillingSequenceNumbers) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case billingsequencenumbers.FieldLast: + values[i] = new(alpacadecimal.Decimal) + case billingsequencenumbers.FieldID: + values[i] = new(sql.NullInt64) + case billingsequencenumbers.FieldNamespace, billingsequencenumbers.FieldScope: + values[i] = new(sql.NullString) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the BillingSequenceNumbers fields. +func (_m *BillingSequenceNumbers) 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 billingsequencenumbers.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int(value.Int64) + case billingsequencenumbers.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 billingsequencenumbers.FieldScope: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field scope", values[i]) + } else if value.Valid { + _m.Scope = value.String + } + case billingsequencenumbers.FieldLast: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field last", values[i]) + } else if value != nil { + _m.Last = *value + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the BillingSequenceNumbers. +// This includes values selected through modifiers, order, etc. +func (_m *BillingSequenceNumbers) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this BillingSequenceNumbers. +// Note that you need to call BillingSequenceNumbers.Unwrap() before calling this method if this BillingSequenceNumbers +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *BillingSequenceNumbers) Update() *BillingSequenceNumbersUpdateOne { + return NewBillingSequenceNumbersClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the BillingSequenceNumbers 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 *BillingSequenceNumbers) Unwrap() *BillingSequenceNumbers { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: BillingSequenceNumbers is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *BillingSequenceNumbers) String() string { + var builder strings.Builder + builder.WriteString("BillingSequenceNumbers(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("scope=") + builder.WriteString(_m.Scope) + builder.WriteString(", ") + builder.WriteString("last=") + builder.WriteString(fmt.Sprintf("%v", _m.Last)) + builder.WriteByte(')') + return builder.String() +} + +// BillingSequenceNumbersSlice is a parsable slice of BillingSequenceNumbers. +type BillingSequenceNumbersSlice []*BillingSequenceNumbers diff --git a/ent/db/billingsequencenumbers/billingsequencenumbers.go b/ent/db/billingsequencenumbers/billingsequencenumbers.go new file mode 100644 index 0000000000000000000000000000000000000000..4caa32fa28becfb3abc7c6ec1137a8129a3ec454 --- /dev/null +++ b/ent/db/billingsequencenumbers/billingsequencenumbers.go @@ -0,0 +1,68 @@ +// Code generated by ent, DO NOT EDIT. + +package billingsequencenumbers + +import ( + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the billingsequencenumbers type in the database. + Label = "billing_sequence_numbers" + // 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" + // FieldScope holds the string denoting the scope field in the database. + FieldScope = "scope" + // FieldLast holds the string denoting the last field in the database. + FieldLast = "last" + // Table holds the table name of the billingsequencenumbers in the database. + Table = "billing_sequence_numbers" +) + +// Columns holds all SQL columns for billingsequencenumbers fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldScope, + FieldLast, +} + +// 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 +) + +// OrderOption defines the ordering options for the BillingSequenceNumbers 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() +} + +// ByScope orders the results by the scope field. +func ByScope(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldScope, opts...).ToFunc() +} + +// ByLast orders the results by the last field. +func ByLast(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLast, opts...).ToFunc() +} diff --git a/ent/db/billingsequencenumbers/where.go b/ent/db/billingsequencenumbers/where.go new file mode 100644 index 0000000000000000000000000000000000000000..2d5099b6a7e189a61261088ff0e88081b5206daa --- /dev/null +++ b/ent/db/billingsequencenumbers/where.go @@ -0,0 +1,254 @@ +// Code generated by ent, DO NOT EDIT. + +package billingsequencenumbers + +import ( + "entgo.io/ent/dialect/sql" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldLTE(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldEQ(FieldNamespace, v)) +} + +// Scope applies equality check predicate on the "scope" field. It's identical to ScopeEQ. +func Scope(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldEQ(FieldScope, v)) +} + +// Last applies equality check predicate on the "last" field. It's identical to LastEQ. +func Last(v alpacadecimal.Decimal) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldEQ(FieldLast, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldContainsFold(FieldNamespace, v)) +} + +// ScopeEQ applies the EQ predicate on the "scope" field. +func ScopeEQ(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldEQ(FieldScope, v)) +} + +// ScopeNEQ applies the NEQ predicate on the "scope" field. +func ScopeNEQ(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldNEQ(FieldScope, v)) +} + +// ScopeIn applies the In predicate on the "scope" field. +func ScopeIn(vs ...string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldIn(FieldScope, vs...)) +} + +// ScopeNotIn applies the NotIn predicate on the "scope" field. +func ScopeNotIn(vs ...string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldNotIn(FieldScope, vs...)) +} + +// ScopeGT applies the GT predicate on the "scope" field. +func ScopeGT(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldGT(FieldScope, v)) +} + +// ScopeGTE applies the GTE predicate on the "scope" field. +func ScopeGTE(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldGTE(FieldScope, v)) +} + +// ScopeLT applies the LT predicate on the "scope" field. +func ScopeLT(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldLT(FieldScope, v)) +} + +// ScopeLTE applies the LTE predicate on the "scope" field. +func ScopeLTE(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldLTE(FieldScope, v)) +} + +// ScopeContains applies the Contains predicate on the "scope" field. +func ScopeContains(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldContains(FieldScope, v)) +} + +// ScopeHasPrefix applies the HasPrefix predicate on the "scope" field. +func ScopeHasPrefix(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldHasPrefix(FieldScope, v)) +} + +// ScopeHasSuffix applies the HasSuffix predicate on the "scope" field. +func ScopeHasSuffix(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldHasSuffix(FieldScope, v)) +} + +// ScopeEqualFold applies the EqualFold predicate on the "scope" field. +func ScopeEqualFold(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldEqualFold(FieldScope, v)) +} + +// ScopeContainsFold applies the ContainsFold predicate on the "scope" field. +func ScopeContainsFold(v string) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldContainsFold(FieldScope, v)) +} + +// LastEQ applies the EQ predicate on the "last" field. +func LastEQ(v alpacadecimal.Decimal) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldEQ(FieldLast, v)) +} + +// LastNEQ applies the NEQ predicate on the "last" field. +func LastNEQ(v alpacadecimal.Decimal) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldNEQ(FieldLast, v)) +} + +// LastIn applies the In predicate on the "last" field. +func LastIn(vs ...alpacadecimal.Decimal) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldIn(FieldLast, vs...)) +} + +// LastNotIn applies the NotIn predicate on the "last" field. +func LastNotIn(vs ...alpacadecimal.Decimal) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldNotIn(FieldLast, vs...)) +} + +// LastGT applies the GT predicate on the "last" field. +func LastGT(v alpacadecimal.Decimal) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldGT(FieldLast, v)) +} + +// LastGTE applies the GTE predicate on the "last" field. +func LastGTE(v alpacadecimal.Decimal) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldGTE(FieldLast, v)) +} + +// LastLT applies the LT predicate on the "last" field. +func LastLT(v alpacadecimal.Decimal) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldLT(FieldLast, v)) +} + +// LastLTE applies the LTE predicate on the "last" field. +func LastLTE(v alpacadecimal.Decimal) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.FieldLTE(FieldLast, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.BillingSequenceNumbers) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.BillingSequenceNumbers) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.BillingSequenceNumbers) predicate.BillingSequenceNumbers { + return predicate.BillingSequenceNumbers(sql.NotPredicates(p)) +} diff --git a/ent/db/billingsequencenumbers_create.go b/ent/db/billingsequencenumbers_create.go new file mode 100644 index 0000000000000000000000000000000000000000..31184cca4480c2b215981731e326b1b0743c7085 --- /dev/null +++ b/ent/db/billingsequencenumbers_create.go @@ -0,0 +1,538 @@ +// 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/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingsequencenumbers" +) + +// BillingSequenceNumbersCreate is the builder for creating a BillingSequenceNumbers entity. +type BillingSequenceNumbersCreate struct { + config + mutation *BillingSequenceNumbersMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *BillingSequenceNumbersCreate) SetNamespace(v string) *BillingSequenceNumbersCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetScope sets the "scope" field. +func (_c *BillingSequenceNumbersCreate) SetScope(v string) *BillingSequenceNumbersCreate { + _c.mutation.SetScope(v) + return _c +} + +// SetLast sets the "last" field. +func (_c *BillingSequenceNumbersCreate) SetLast(v alpacadecimal.Decimal) *BillingSequenceNumbersCreate { + _c.mutation.SetLast(v) + return _c +} + +// Mutation returns the BillingSequenceNumbersMutation object of the builder. +func (_c *BillingSequenceNumbersCreate) Mutation() *BillingSequenceNumbersMutation { + return _c.mutation +} + +// Save creates the BillingSequenceNumbers in the database. +func (_c *BillingSequenceNumbersCreate) Save(ctx context.Context) (*BillingSequenceNumbers, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *BillingSequenceNumbersCreate) SaveX(ctx context.Context) *BillingSequenceNumbers { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingSequenceNumbersCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingSequenceNumbersCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *BillingSequenceNumbersCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "BillingSequenceNumbers.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := billingsequencenumbers.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "BillingSequenceNumbers.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.Scope(); !ok { + return &ValidationError{Name: "scope", err: errors.New(`db: missing required field "BillingSequenceNumbers.scope"`)} + } + if _, ok := _c.mutation.Last(); !ok { + return &ValidationError{Name: "last", err: errors.New(`db: missing required field "BillingSequenceNumbers.last"`)} + } + return nil +} + +func (_c *BillingSequenceNumbersCreate) sqlSave(ctx context.Context) (*BillingSequenceNumbers, 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 + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *BillingSequenceNumbersCreate) createSpec() (*BillingSequenceNumbers, *sqlgraph.CreateSpec) { + var ( + _node = &BillingSequenceNumbers{config: _c.config} + _spec = sqlgraph.NewCreateSpec(billingsequencenumbers.Table, sqlgraph.NewFieldSpec(billingsequencenumbers.FieldID, field.TypeInt)) + ) + _spec.OnConflict = _c.conflict + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(billingsequencenumbers.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Scope(); ok { + _spec.SetField(billingsequencenumbers.FieldScope, field.TypeString, value) + _node.Scope = value + } + if value, ok := _c.mutation.Last(); ok { + _spec.SetField(billingsequencenumbers.FieldLast, field.TypeOther, value) + _node.Last = value + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.BillingSequenceNumbers.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.BillingSequenceNumbersUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *BillingSequenceNumbersCreate) OnConflict(opts ...sql.ConflictOption) *BillingSequenceNumbersUpsertOne { + _c.conflict = opts + return &BillingSequenceNumbersUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingSequenceNumbers.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingSequenceNumbersCreate) OnConflictColumns(columns ...string) *BillingSequenceNumbersUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingSequenceNumbersUpsertOne{ + create: _c, + } +} + +type ( + // BillingSequenceNumbersUpsertOne is the builder for "upsert"-ing + // one BillingSequenceNumbers node. + BillingSequenceNumbersUpsertOne struct { + create *BillingSequenceNumbersCreate + } + + // BillingSequenceNumbersUpsert is the "OnConflict" setter. + BillingSequenceNumbersUpsert struct { + *sql.UpdateSet + } +) + +// SetScope sets the "scope" field. +func (u *BillingSequenceNumbersUpsert) SetScope(v string) *BillingSequenceNumbersUpsert { + u.Set(billingsequencenumbers.FieldScope, v) + return u +} + +// UpdateScope sets the "scope" field to the value that was provided on create. +func (u *BillingSequenceNumbersUpsert) UpdateScope() *BillingSequenceNumbersUpsert { + u.SetExcluded(billingsequencenumbers.FieldScope) + return u +} + +// SetLast sets the "last" field. +func (u *BillingSequenceNumbersUpsert) SetLast(v alpacadecimal.Decimal) *BillingSequenceNumbersUpsert { + u.Set(billingsequencenumbers.FieldLast, v) + return u +} + +// UpdateLast sets the "last" field to the value that was provided on create. +func (u *BillingSequenceNumbersUpsert) UpdateLast() *BillingSequenceNumbersUpsert { + u.SetExcluded(billingsequencenumbers.FieldLast) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create. +// Using this option is equivalent to using: +// +// client.BillingSequenceNumbers.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *BillingSequenceNumbersUpsertOne) UpdateNewValues() *BillingSequenceNumbersUpsertOne { + 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.Namespace(); exists { + s.SetIgnore(billingsequencenumbers.FieldNamespace) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingSequenceNumbers.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingSequenceNumbersUpsertOne) Ignore() *BillingSequenceNumbersUpsertOne { + 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 *BillingSequenceNumbersUpsertOne) DoNothing() *BillingSequenceNumbersUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingSequenceNumbersCreate.OnConflict +// documentation for more info. +func (u *BillingSequenceNumbersUpsertOne) Update(set func(*BillingSequenceNumbersUpsert)) *BillingSequenceNumbersUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingSequenceNumbersUpsert{UpdateSet: update}) + })) + return u +} + +// SetScope sets the "scope" field. +func (u *BillingSequenceNumbersUpsertOne) SetScope(v string) *BillingSequenceNumbersUpsertOne { + return u.Update(func(s *BillingSequenceNumbersUpsert) { + s.SetScope(v) + }) +} + +// UpdateScope sets the "scope" field to the value that was provided on create. +func (u *BillingSequenceNumbersUpsertOne) UpdateScope() *BillingSequenceNumbersUpsertOne { + return u.Update(func(s *BillingSequenceNumbersUpsert) { + s.UpdateScope() + }) +} + +// SetLast sets the "last" field. +func (u *BillingSequenceNumbersUpsertOne) SetLast(v alpacadecimal.Decimal) *BillingSequenceNumbersUpsertOne { + return u.Update(func(s *BillingSequenceNumbersUpsert) { + s.SetLast(v) + }) +} + +// UpdateLast sets the "last" field to the value that was provided on create. +func (u *BillingSequenceNumbersUpsertOne) UpdateLast() *BillingSequenceNumbersUpsertOne { + return u.Update(func(s *BillingSequenceNumbersUpsert) { + s.UpdateLast() + }) +} + +// Exec executes the query. +func (u *BillingSequenceNumbersUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingSequenceNumbersCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingSequenceNumbersUpsertOne) 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 *BillingSequenceNumbersUpsertOne) ID(ctx context.Context) (id int, err error) { + 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 *BillingSequenceNumbersUpsertOne) IDX(ctx context.Context) int { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// BillingSequenceNumbersCreateBulk is the builder for creating many BillingSequenceNumbers entities in bulk. +type BillingSequenceNumbersCreateBulk struct { + config + err error + builders []*BillingSequenceNumbersCreate + conflict []sql.ConflictOption +} + +// Save creates the BillingSequenceNumbers entities in the database. +func (_c *BillingSequenceNumbersCreateBulk) Save(ctx context.Context) ([]*BillingSequenceNumbers, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*BillingSequenceNumbers, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*BillingSequenceNumbersMutation) + 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 + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + 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 *BillingSequenceNumbersCreateBulk) SaveX(ctx context.Context) []*BillingSequenceNumbers { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingSequenceNumbersCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingSequenceNumbersCreateBulk) 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.BillingSequenceNumbers.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.BillingSequenceNumbersUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *BillingSequenceNumbersCreateBulk) OnConflict(opts ...sql.ConflictOption) *BillingSequenceNumbersUpsertBulk { + _c.conflict = opts + return &BillingSequenceNumbersUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingSequenceNumbers.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingSequenceNumbersCreateBulk) OnConflictColumns(columns ...string) *BillingSequenceNumbersUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingSequenceNumbersUpsertBulk{ + create: _c, + } +} + +// BillingSequenceNumbersUpsertBulk is the builder for "upsert"-ing +// a bulk of BillingSequenceNumbers nodes. +type BillingSequenceNumbersUpsertBulk struct { + create *BillingSequenceNumbersCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.BillingSequenceNumbers.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *BillingSequenceNumbersUpsertBulk) UpdateNewValues() *BillingSequenceNumbersUpsertBulk { + 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.Namespace(); exists { + s.SetIgnore(billingsequencenumbers.FieldNamespace) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingSequenceNumbers.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingSequenceNumbersUpsertBulk) Ignore() *BillingSequenceNumbersUpsertBulk { + 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 *BillingSequenceNumbersUpsertBulk) DoNothing() *BillingSequenceNumbersUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingSequenceNumbersCreateBulk.OnConflict +// documentation for more info. +func (u *BillingSequenceNumbersUpsertBulk) Update(set func(*BillingSequenceNumbersUpsert)) *BillingSequenceNumbersUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingSequenceNumbersUpsert{UpdateSet: update}) + })) + return u +} + +// SetScope sets the "scope" field. +func (u *BillingSequenceNumbersUpsertBulk) SetScope(v string) *BillingSequenceNumbersUpsertBulk { + return u.Update(func(s *BillingSequenceNumbersUpsert) { + s.SetScope(v) + }) +} + +// UpdateScope sets the "scope" field to the value that was provided on create. +func (u *BillingSequenceNumbersUpsertBulk) UpdateScope() *BillingSequenceNumbersUpsertBulk { + return u.Update(func(s *BillingSequenceNumbersUpsert) { + s.UpdateScope() + }) +} + +// SetLast sets the "last" field. +func (u *BillingSequenceNumbersUpsertBulk) SetLast(v alpacadecimal.Decimal) *BillingSequenceNumbersUpsertBulk { + return u.Update(func(s *BillingSequenceNumbersUpsert) { + s.SetLast(v) + }) +} + +// UpdateLast sets the "last" field to the value that was provided on create. +func (u *BillingSequenceNumbersUpsertBulk) UpdateLast() *BillingSequenceNumbersUpsertBulk { + return u.Update(func(s *BillingSequenceNumbersUpsert) { + s.UpdateLast() + }) +} + +// Exec executes the query. +func (u *BillingSequenceNumbersUpsertBulk) 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 BillingSequenceNumbersCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingSequenceNumbersCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingSequenceNumbersUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billingsequencenumbers_delete.go b/ent/db/billingsequencenumbers_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..c8ccbe0d40957a6e0bad8a48686d3ff0036b933c --- /dev/null +++ b/ent/db/billingsequencenumbers_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/billingsequencenumbers" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingSequenceNumbersDelete is the builder for deleting a BillingSequenceNumbers entity. +type BillingSequenceNumbersDelete struct { + config + hooks []Hook + mutation *BillingSequenceNumbersMutation +} + +// Where appends a list predicates to the BillingSequenceNumbersDelete builder. +func (_d *BillingSequenceNumbersDelete) Where(ps ...predicate.BillingSequenceNumbers) *BillingSequenceNumbersDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *BillingSequenceNumbersDelete) 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 *BillingSequenceNumbersDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *BillingSequenceNumbersDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(billingsequencenumbers.Table, sqlgraph.NewFieldSpec(billingsequencenumbers.FieldID, field.TypeInt)) + 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 +} + +// BillingSequenceNumbersDeleteOne is the builder for deleting a single BillingSequenceNumbers entity. +type BillingSequenceNumbersDeleteOne struct { + _d *BillingSequenceNumbersDelete +} + +// Where appends a list predicates to the BillingSequenceNumbersDelete builder. +func (_d *BillingSequenceNumbersDeleteOne) Where(ps ...predicate.BillingSequenceNumbers) *BillingSequenceNumbersDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *BillingSequenceNumbersDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{billingsequencenumbers.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *BillingSequenceNumbersDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billingsequencenumbers_query.go b/ent/db/billingsequencenumbers_query.go new file mode 100644 index 0000000000000000000000000000000000000000..534fd7a94269100890a83c3daf68b4e5202f6b91 --- /dev/null +++ b/ent/db/billingsequencenumbers_query.go @@ -0,0 +1,564 @@ +// 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/billingsequencenumbers" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingSequenceNumbersQuery is the builder for querying BillingSequenceNumbers entities. +type BillingSequenceNumbersQuery struct { + config + ctx *QueryContext + order []billingsequencenumbers.OrderOption + inters []Interceptor + predicates []predicate.BillingSequenceNumbers + 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 BillingSequenceNumbersQuery builder. +func (_q *BillingSequenceNumbersQuery) Where(ps ...predicate.BillingSequenceNumbers) *BillingSequenceNumbersQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *BillingSequenceNumbersQuery) Limit(limit int) *BillingSequenceNumbersQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *BillingSequenceNumbersQuery) Offset(offset int) *BillingSequenceNumbersQuery { + _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 *BillingSequenceNumbersQuery) Unique(unique bool) *BillingSequenceNumbersQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *BillingSequenceNumbersQuery) Order(o ...billingsequencenumbers.OrderOption) *BillingSequenceNumbersQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first BillingSequenceNumbers entity from the query. +// Returns a *NotFoundError when no BillingSequenceNumbers was found. +func (_q *BillingSequenceNumbersQuery) First(ctx context.Context) (*BillingSequenceNumbers, 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{billingsequencenumbers.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *BillingSequenceNumbersQuery) FirstX(ctx context.Context) *BillingSequenceNumbers { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first BillingSequenceNumbers ID from the query. +// Returns a *NotFoundError when no BillingSequenceNumbers ID was found. +func (_q *BillingSequenceNumbersQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{billingsequencenumbers.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *BillingSequenceNumbersQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single BillingSequenceNumbers entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one BillingSequenceNumbers entity is found. +// Returns a *NotFoundError when no BillingSequenceNumbers entities are found. +func (_q *BillingSequenceNumbersQuery) Only(ctx context.Context) (*BillingSequenceNumbers, 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{billingsequencenumbers.Label} + default: + return nil, &NotSingularError{billingsequencenumbers.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *BillingSequenceNumbersQuery) OnlyX(ctx context.Context) *BillingSequenceNumbers { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only BillingSequenceNumbers ID in the query. +// Returns a *NotSingularError when more than one BillingSequenceNumbers ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *BillingSequenceNumbersQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + 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{billingsequencenumbers.Label} + default: + err = &NotSingularError{billingsequencenumbers.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *BillingSequenceNumbersQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of BillingSequenceNumbersSlice. +func (_q *BillingSequenceNumbersQuery) All(ctx context.Context) ([]*BillingSequenceNumbers, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*BillingSequenceNumbers, *BillingSequenceNumbersQuery]() + return withInterceptors[[]*BillingSequenceNumbers](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *BillingSequenceNumbersQuery) AllX(ctx context.Context) []*BillingSequenceNumbers { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of BillingSequenceNumbers IDs. +func (_q *BillingSequenceNumbersQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(billingsequencenumbers.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *BillingSequenceNumbersQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *BillingSequenceNumbersQuery) 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[*BillingSequenceNumbersQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *BillingSequenceNumbersQuery) 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 *BillingSequenceNumbersQuery) 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 *BillingSequenceNumbersQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the BillingSequenceNumbersQuery 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 *BillingSequenceNumbersQuery) Clone() *BillingSequenceNumbersQuery { + if _q == nil { + return nil + } + return &BillingSequenceNumbersQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]billingsequencenumbers.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.BillingSequenceNumbers{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// 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.BillingSequenceNumbers.Query(). +// GroupBy(billingsequencenumbers.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *BillingSequenceNumbersQuery) GroupBy(field string, fields ...string) *BillingSequenceNumbersGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &BillingSequenceNumbersGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = billingsequencenumbers.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.BillingSequenceNumbers.Query(). +// Select(billingsequencenumbers.FieldNamespace). +// Scan(ctx, &v) +func (_q *BillingSequenceNumbersQuery) Select(fields ...string) *BillingSequenceNumbersSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &BillingSequenceNumbersSelect{BillingSequenceNumbersQuery: _q} + sbuild.label = billingsequencenumbers.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a BillingSequenceNumbersSelect configured with the given aggregations. +func (_q *BillingSequenceNumbersQuery) Aggregate(fns ...AggregateFunc) *BillingSequenceNumbersSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *BillingSequenceNumbersQuery) 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 !billingsequencenumbers.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 *BillingSequenceNumbersQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BillingSequenceNumbers, error) { + var ( + nodes = []*BillingSequenceNumbers{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*BillingSequenceNumbers).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &BillingSequenceNumbers{config: _q.config} + nodes = append(nodes, node) + 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 + } + return nodes, nil +} + +func (_q *BillingSequenceNumbersQuery) 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 *BillingSequenceNumbersQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(billingsequencenumbers.Table, billingsequencenumbers.Columns, sqlgraph.NewFieldSpec(billingsequencenumbers.FieldID, field.TypeInt)) + _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, billingsequencenumbers.FieldID) + for i := range fields { + if fields[i] != billingsequencenumbers.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 *BillingSequenceNumbersQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(billingsequencenumbers.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = billingsequencenumbers.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 *BillingSequenceNumbersQuery) ForUpdate(opts ...sql.LockOption) *BillingSequenceNumbersQuery { + 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 *BillingSequenceNumbersQuery) ForShare(opts ...sql.LockOption) *BillingSequenceNumbersQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// BillingSequenceNumbersGroupBy is the group-by builder for BillingSequenceNumbers entities. +type BillingSequenceNumbersGroupBy struct { + selector + build *BillingSequenceNumbersQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *BillingSequenceNumbersGroupBy) Aggregate(fns ...AggregateFunc) *BillingSequenceNumbersGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *BillingSequenceNumbersGroupBy) 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[*BillingSequenceNumbersQuery, *BillingSequenceNumbersGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *BillingSequenceNumbersGroupBy) sqlScan(ctx context.Context, root *BillingSequenceNumbersQuery, 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) +} + +// BillingSequenceNumbersSelect is the builder for selecting fields of BillingSequenceNumbers entities. +type BillingSequenceNumbersSelect struct { + *BillingSequenceNumbersQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *BillingSequenceNumbersSelect) Aggregate(fns ...AggregateFunc) *BillingSequenceNumbersSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *BillingSequenceNumbersSelect) 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[*BillingSequenceNumbersQuery, *BillingSequenceNumbersSelect](ctx, _s.BillingSequenceNumbersQuery, _s, _s.inters, v) +} + +func (_s *BillingSequenceNumbersSelect) sqlScan(ctx context.Context, root *BillingSequenceNumbersQuery, 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/ent/db/billingsequencenumbers_update.go b/ent/db/billingsequencenumbers_update.go new file mode 100644 index 0000000000000000000000000000000000000000..5cf18c9cb24aae6af100ee5a6f96845cd5a9be79 --- /dev/null +++ b/ent/db/billingsequencenumbers_update.go @@ -0,0 +1,244 @@ +// 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/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingsequencenumbers" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingSequenceNumbersUpdate is the builder for updating BillingSequenceNumbers entities. +type BillingSequenceNumbersUpdate struct { + config + hooks []Hook + mutation *BillingSequenceNumbersMutation +} + +// Where appends a list predicates to the BillingSequenceNumbersUpdate builder. +func (_u *BillingSequenceNumbersUpdate) Where(ps ...predicate.BillingSequenceNumbers) *BillingSequenceNumbersUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetScope sets the "scope" field. +func (_u *BillingSequenceNumbersUpdate) SetScope(v string) *BillingSequenceNumbersUpdate { + _u.mutation.SetScope(v) + return _u +} + +// SetNillableScope sets the "scope" field if the given value is not nil. +func (_u *BillingSequenceNumbersUpdate) SetNillableScope(v *string) *BillingSequenceNumbersUpdate { + if v != nil { + _u.SetScope(*v) + } + return _u +} + +// SetLast sets the "last" field. +func (_u *BillingSequenceNumbersUpdate) SetLast(v alpacadecimal.Decimal) *BillingSequenceNumbersUpdate { + _u.mutation.SetLast(v) + return _u +} + +// SetNillableLast sets the "last" field if the given value is not nil. +func (_u *BillingSequenceNumbersUpdate) SetNillableLast(v *alpacadecimal.Decimal) *BillingSequenceNumbersUpdate { + if v != nil { + _u.SetLast(*v) + } + return _u +} + +// Mutation returns the BillingSequenceNumbersMutation object of the builder. +func (_u *BillingSequenceNumbersUpdate) Mutation() *BillingSequenceNumbersMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *BillingSequenceNumbersUpdate) 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 *BillingSequenceNumbersUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *BillingSequenceNumbersUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingSequenceNumbersUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *BillingSequenceNumbersUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(billingsequencenumbers.Table, billingsequencenumbers.Columns, sqlgraph.NewFieldSpec(billingsequencenumbers.FieldID, field.TypeInt)) + 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.Scope(); ok { + _spec.SetField(billingsequencenumbers.FieldScope, field.TypeString, value) + } + if value, ok := _u.mutation.Last(); ok { + _spec.SetField(billingsequencenumbers.FieldLast, field.TypeOther, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{billingsequencenumbers.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// BillingSequenceNumbersUpdateOne is the builder for updating a single BillingSequenceNumbers entity. +type BillingSequenceNumbersUpdateOne struct { + config + fields []string + hooks []Hook + mutation *BillingSequenceNumbersMutation +} + +// SetScope sets the "scope" field. +func (_u *BillingSequenceNumbersUpdateOne) SetScope(v string) *BillingSequenceNumbersUpdateOne { + _u.mutation.SetScope(v) + return _u +} + +// SetNillableScope sets the "scope" field if the given value is not nil. +func (_u *BillingSequenceNumbersUpdateOne) SetNillableScope(v *string) *BillingSequenceNumbersUpdateOne { + if v != nil { + _u.SetScope(*v) + } + return _u +} + +// SetLast sets the "last" field. +func (_u *BillingSequenceNumbersUpdateOne) SetLast(v alpacadecimal.Decimal) *BillingSequenceNumbersUpdateOne { + _u.mutation.SetLast(v) + return _u +} + +// SetNillableLast sets the "last" field if the given value is not nil. +func (_u *BillingSequenceNumbersUpdateOne) SetNillableLast(v *alpacadecimal.Decimal) *BillingSequenceNumbersUpdateOne { + if v != nil { + _u.SetLast(*v) + } + return _u +} + +// Mutation returns the BillingSequenceNumbersMutation object of the builder. +func (_u *BillingSequenceNumbersUpdateOne) Mutation() *BillingSequenceNumbersMutation { + return _u.mutation +} + +// Where appends a list predicates to the BillingSequenceNumbersUpdate builder. +func (_u *BillingSequenceNumbersUpdateOne) Where(ps ...predicate.BillingSequenceNumbers) *BillingSequenceNumbersUpdateOne { + _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 *BillingSequenceNumbersUpdateOne) Select(field string, fields ...string) *BillingSequenceNumbersUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated BillingSequenceNumbers entity. +func (_u *BillingSequenceNumbersUpdateOne) Save(ctx context.Context) (*BillingSequenceNumbers, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *BillingSequenceNumbersUpdateOne) SaveX(ctx context.Context) *BillingSequenceNumbers { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *BillingSequenceNumbersUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingSequenceNumbersUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *BillingSequenceNumbersUpdateOne) sqlSave(ctx context.Context) (_node *BillingSequenceNumbers, err error) { + _spec := sqlgraph.NewUpdateSpec(billingsequencenumbers.Table, billingsequencenumbers.Columns, sqlgraph.NewFieldSpec(billingsequencenumbers.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "BillingSequenceNumbers.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, billingsequencenumbers.FieldID) + for _, f := range fields { + if !billingsequencenumbers.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != billingsequencenumbers.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.Scope(); ok { + _spec.SetField(billingsequencenumbers.FieldScope, field.TypeString, value) + } + if value, ok := _u.mutation.Last(); ok { + _spec.SetField(billingsequencenumbers.FieldLast, field.TypeOther, value) + } + _node = &BillingSequenceNumbers{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{billingsequencenumbers.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/ent/db/billingstandardinvoicedetailedline.go b/ent/db/billingstandardinvoicedetailedline.go new file mode 100644 index 0000000000000000000000000000000000000000..c72818a374d6754db3c7529e0e006ed94583909c --- /dev/null +++ b/ent/db/billingstandardinvoicedetailedline.go @@ -0,0 +1,511 @@ +// 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/models/creditsapplied" + "github.com/openmeterio/openmeter/openmeter/billing/models/stddetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingstandardinvoicedetailedline" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// BillingStandardInvoiceDetailedLine is the model entity for the BillingStandardInvoiceDetailedLine schema. +type BillingStandardInvoiceDetailedLine struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // Currency holds the value of the "currency" field. + Currency currencyx.Code `json:"currency,omitempty"` + // ServicePeriodStart holds the value of the "service_period_start" field. + ServicePeriodStart time.Time `json:"service_period_start,omitempty"` + // ServicePeriodEnd holds the value of the "service_period_end" field. + ServicePeriodEnd time.Time `json:"service_period_end,omitempty"` + // Quantity holds the value of the "quantity" field. + Quantity alpacadecimal.Decimal `json:"quantity,omitempty"` + // InvoicingAppExternalID holds the value of the "invoicing_app_external_id" field. + InvoicingAppExternalID *string `json:"invoicing_app_external_id,omitempty"` + // ChildUniqueReferenceID holds the value of the "child_unique_reference_id" field. + ChildUniqueReferenceID string `json:"child_unique_reference_id,omitempty"` + // PerUnitAmount holds the value of the "per_unit_amount" field. + PerUnitAmount alpacadecimal.Decimal `json:"per_unit_amount,omitempty"` + // Category holds the value of the "category" field. + Category stddetailedline.Category `json:"category,omitempty"` + // PaymentTerm holds the value of the "payment_term" field. + PaymentTerm productcatalog.PaymentTermType `json:"payment_term,omitempty"` + // Index holds the value of the "index" field. + Index *int `json:"index,omitempty"` + // CreditsApplied holds the value of the "credits_applied" field. + CreditsApplied *creditsapplied.CreditsApplied `json:"credits_applied,omitempty"` + // Annotations holds the value of the "annotations" field. + // + // Deprecated: Field "annotations" was marked as deprecated in the schema. + Annotations models.Annotations `json:"annotations,omitempty"` + // Namespace holds the value of the "namespace" field. + Namespace string `json:"namespace,omitempty"` + // Metadata holds the value of the "metadata" field. + // + // Deprecated: Field "metadata" was marked as deprecated in the schema. + Metadata map[string]string `json:"metadata,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"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Description holds the value of the "description" field. + Description *string `json:"description,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"` + // InvoiceID holds the value of the "invoice_id" field. + InvoiceID string `json:"invoice_id,omitempty"` + // ParentLineID holds the value of the "parent_line_id" field. + ParentLineID string `json:"parent_line_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the BillingStandardInvoiceDetailedLineQuery when eager-loading is set. + Edges BillingStandardInvoiceDetailedLineEdges `json:"edges"` + selectValues sql.SelectValues +} + +// BillingStandardInvoiceDetailedLineEdges holds the relations/edges for other nodes in the graph. +type BillingStandardInvoiceDetailedLineEdges struct { + // BillingInvoice holds the value of the billing_invoice edge. + BillingInvoice *BillingInvoice `json:"billing_invoice,omitempty"` + // BillingInvoiceLine holds the value of the billing_invoice_line edge. + BillingInvoiceLine *BillingInvoiceLine `json:"billing_invoice_line,omitempty"` + // AmountDiscounts holds the value of the amount_discounts edge. + AmountDiscounts []*BillingStandardInvoiceDetailedLineAmountDiscount `json:"amount_discounts,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [3]bool +} + +// BillingInvoiceOrErr returns the BillingInvoice value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e BillingStandardInvoiceDetailedLineEdges) BillingInvoiceOrErr() (*BillingInvoice, error) { + if e.BillingInvoice != nil { + return e.BillingInvoice, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: billinginvoice.Label} + } + return nil, &NotLoadedError{edge: "billing_invoice"} +} + +// BillingInvoiceLineOrErr returns the BillingInvoiceLine value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e BillingStandardInvoiceDetailedLineEdges) BillingInvoiceLineOrErr() (*BillingInvoiceLine, error) { + if e.BillingInvoiceLine != nil { + return e.BillingInvoiceLine, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: billinginvoiceline.Label} + } + return nil, &NotLoadedError{edge: "billing_invoice_line"} +} + +// AmountDiscountsOrErr returns the AmountDiscounts value or an error if the edge +// was not loaded in eager-loading. +func (e BillingStandardInvoiceDetailedLineEdges) AmountDiscountsOrErr() ([]*BillingStandardInvoiceDetailedLineAmountDiscount, error) { + if e.loadedTypes[2] { + return e.AmountDiscounts, nil + } + return nil, &NotLoadedError{edge: "amount_discounts"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*BillingStandardInvoiceDetailedLine) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case billingstandardinvoicedetailedline.FieldCreditsApplied, billingstandardinvoicedetailedline.FieldAnnotations, billingstandardinvoicedetailedline.FieldMetadata: + values[i] = new([]byte) + case billingstandardinvoicedetailedline.FieldQuantity, billingstandardinvoicedetailedline.FieldPerUnitAmount, billingstandardinvoicedetailedline.FieldAmount, billingstandardinvoicedetailedline.FieldTaxesTotal, billingstandardinvoicedetailedline.FieldTaxesInclusiveTotal, billingstandardinvoicedetailedline.FieldTaxesExclusiveTotal, billingstandardinvoicedetailedline.FieldChargesTotal, billingstandardinvoicedetailedline.FieldDiscountsTotal, billingstandardinvoicedetailedline.FieldCreditsTotal, billingstandardinvoicedetailedline.FieldTotal: + values[i] = new(alpacadecimal.Decimal) + case billingstandardinvoicedetailedline.FieldIndex: + values[i] = new(sql.NullInt64) + case billingstandardinvoicedetailedline.FieldID, billingstandardinvoicedetailedline.FieldCurrency, billingstandardinvoicedetailedline.FieldInvoicingAppExternalID, billingstandardinvoicedetailedline.FieldChildUniqueReferenceID, billingstandardinvoicedetailedline.FieldCategory, billingstandardinvoicedetailedline.FieldPaymentTerm, billingstandardinvoicedetailedline.FieldNamespace, billingstandardinvoicedetailedline.FieldName, billingstandardinvoicedetailedline.FieldDescription, billingstandardinvoicedetailedline.FieldInvoiceID, billingstandardinvoicedetailedline.FieldParentLineID: + values[i] = new(sql.NullString) + case billingstandardinvoicedetailedline.FieldServicePeriodStart, billingstandardinvoicedetailedline.FieldServicePeriodEnd, billingstandardinvoicedetailedline.FieldCreatedAt, billingstandardinvoicedetailedline.FieldUpdatedAt, billingstandardinvoicedetailedline.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 BillingStandardInvoiceDetailedLine fields. +func (_m *BillingStandardInvoiceDetailedLine) 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 billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.FieldCurrency: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field currency", values[i]) + } else if value.Valid { + _m.Currency = currencyx.Code(value.String) + } + case billingstandardinvoicedetailedline.FieldServicePeriodStart: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field service_period_start", values[i]) + } else if value.Valid { + _m.ServicePeriodStart = value.Time + } + case billingstandardinvoicedetailedline.FieldServicePeriodEnd: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field service_period_end", values[i]) + } else if value.Valid { + _m.ServicePeriodEnd = value.Time + } + case billingstandardinvoicedetailedline.FieldQuantity: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field quantity", values[i]) + } else if value != nil { + _m.Quantity = *value + } + case billingstandardinvoicedetailedline.FieldInvoicingAppExternalID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field invoicing_app_external_id", values[i]) + } else if value.Valid { + _m.InvoicingAppExternalID = new(string) + *_m.InvoicingAppExternalID = value.String + } + case billingstandardinvoicedetailedline.FieldChildUniqueReferenceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field child_unique_reference_id", values[i]) + } else if value.Valid { + _m.ChildUniqueReferenceID = value.String + } + case billingstandardinvoicedetailedline.FieldPerUnitAmount: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field per_unit_amount", values[i]) + } else if value != nil { + _m.PerUnitAmount = *value + } + case billingstandardinvoicedetailedline.FieldCategory: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field category", values[i]) + } else if value.Valid { + _m.Category = stddetailedline.Category(value.String) + } + case billingstandardinvoicedetailedline.FieldPaymentTerm: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field payment_term", values[i]) + } else if value.Valid { + _m.PaymentTerm = productcatalog.PaymentTermType(value.String) + } + case billingstandardinvoicedetailedline.FieldIndex: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field index", values[i]) + } else if value.Valid { + _m.Index = new(int) + *_m.Index = int(value.Int64) + } + case billingstandardinvoicedetailedline.FieldCreditsApplied: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field credits_applied", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.CreditsApplied); err != nil { + return fmt.Errorf("unmarshal field credits_applied: %w", err) + } + } + case billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.FieldMetadata: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field metadata", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Metadata); err != nil { + return fmt.Errorf("unmarshal field metadata: %w", err) + } + } + case billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case billingstandardinvoicedetailedline.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + _m.Description = new(string) + *_m.Description = value.String + } + case billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.FieldInvoiceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field invoice_id", values[i]) + } else if value.Valid { + _m.InvoiceID = value.String + } + case billingstandardinvoicedetailedline.FieldParentLineID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field parent_line_id", values[i]) + } else if value.Valid { + _m.ParentLineID = 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 BillingStandardInvoiceDetailedLine. +// This includes values selected through modifiers, order, etc. +func (_m *BillingStandardInvoiceDetailedLine) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryBillingInvoice queries the "billing_invoice" edge of the BillingStandardInvoiceDetailedLine entity. +func (_m *BillingStandardInvoiceDetailedLine) QueryBillingInvoice() *BillingInvoiceQuery { + return NewBillingStandardInvoiceDetailedLineClient(_m.config).QueryBillingInvoice(_m) +} + +// QueryBillingInvoiceLine queries the "billing_invoice_line" edge of the BillingStandardInvoiceDetailedLine entity. +func (_m *BillingStandardInvoiceDetailedLine) QueryBillingInvoiceLine() *BillingInvoiceLineQuery { + return NewBillingStandardInvoiceDetailedLineClient(_m.config).QueryBillingInvoiceLine(_m) +} + +// QueryAmountDiscounts queries the "amount_discounts" edge of the BillingStandardInvoiceDetailedLine entity. +func (_m *BillingStandardInvoiceDetailedLine) QueryAmountDiscounts() *BillingStandardInvoiceDetailedLineAmountDiscountQuery { + return NewBillingStandardInvoiceDetailedLineClient(_m.config).QueryAmountDiscounts(_m) +} + +// Update returns a builder for updating this BillingStandardInvoiceDetailedLine. +// Note that you need to call BillingStandardInvoiceDetailedLine.Unwrap() before calling this method if this BillingStandardInvoiceDetailedLine +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *BillingStandardInvoiceDetailedLine) Update() *BillingStandardInvoiceDetailedLineUpdateOne { + return NewBillingStandardInvoiceDetailedLineClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLine) Unwrap() *BillingStandardInvoiceDetailedLine { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: BillingStandardInvoiceDetailedLine is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *BillingStandardInvoiceDetailedLine) String() string { + var builder strings.Builder + builder.WriteString("BillingStandardInvoiceDetailedLine(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("currency=") + builder.WriteString(fmt.Sprintf("%v", _m.Currency)) + builder.WriteString(", ") + builder.WriteString("service_period_start=") + builder.WriteString(_m.ServicePeriodStart.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("service_period_end=") + builder.WriteString(_m.ServicePeriodEnd.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("quantity=") + builder.WriteString(fmt.Sprintf("%v", _m.Quantity)) + builder.WriteString(", ") + if v := _m.InvoicingAppExternalID; v != nil { + builder.WriteString("invoicing_app_external_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("child_unique_reference_id=") + builder.WriteString(_m.ChildUniqueReferenceID) + builder.WriteString(", ") + builder.WriteString("per_unit_amount=") + builder.WriteString(fmt.Sprintf("%v", _m.PerUnitAmount)) + builder.WriteString(", ") + builder.WriteString("category=") + builder.WriteString(fmt.Sprintf("%v", _m.Category)) + builder.WriteString(", ") + builder.WriteString("payment_term=") + builder.WriteString(fmt.Sprintf("%v", _m.PaymentTerm)) + builder.WriteString(", ") + if v := _m.Index; v != nil { + builder.WriteString("index=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + builder.WriteString("credits_applied=") + builder.WriteString(fmt.Sprintf("%v", _m.CreditsApplied)) + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + builder.WriteString(", ") + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("metadata=") + builder.WriteString(fmt.Sprintf("%v", _m.Metadata)) + 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("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + if v := _m.Description; v != nil { + builder.WriteString("description=") + builder.WriteString(*v) + } + 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("invoice_id=") + builder.WriteString(_m.InvoiceID) + builder.WriteString(", ") + builder.WriteString("parent_line_id=") + builder.WriteString(_m.ParentLineID) + builder.WriteByte(')') + return builder.String() +} + +// BillingStandardInvoiceDetailedLines is a parsable slice of BillingStandardInvoiceDetailedLine. +type BillingStandardInvoiceDetailedLines []*BillingStandardInvoiceDetailedLine diff --git a/ent/db/billingstandardinvoicedetailedline/billingstandardinvoicedetailedline.go b/ent/db/billingstandardinvoicedetailedline/billingstandardinvoicedetailedline.go new file mode 100644 index 0000000000000000000000000000000000000000..0ea48650b5602f2ad19c13c2c1dc742ae8e34961 --- /dev/null +++ b/ent/db/billingstandardinvoicedetailedline/billingstandardinvoicedetailedline.go @@ -0,0 +1,382 @@ +// Code generated by ent, DO NOT EDIT. + +package billingstandardinvoicedetailedline + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/billing/models/stddetailedline" + "github.com/openmeterio/openmeter/openmeter/productcatalog" +) + +const ( + // Label holds the string label denoting the billingstandardinvoicedetailedline type in the database. + Label = "billing_standard_invoice_detailed_line" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldCurrency holds the string denoting the currency field in the database. + FieldCurrency = "currency" + // FieldServicePeriodStart holds the string denoting the service_period_start field in the database. + FieldServicePeriodStart = "service_period_start" + // FieldServicePeriodEnd holds the string denoting the service_period_end field in the database. + FieldServicePeriodEnd = "service_period_end" + // FieldQuantity holds the string denoting the quantity field in the database. + FieldQuantity = "quantity" + // FieldInvoicingAppExternalID holds the string denoting the invoicing_app_external_id field in the database. + FieldInvoicingAppExternalID = "invoicing_app_external_id" + // FieldChildUniqueReferenceID holds the string denoting the child_unique_reference_id field in the database. + FieldChildUniqueReferenceID = "child_unique_reference_id" + // FieldPerUnitAmount holds the string denoting the per_unit_amount field in the database. + FieldPerUnitAmount = "per_unit_amount" + // FieldCategory holds the string denoting the category field in the database. + FieldCategory = "category" + // FieldPaymentTerm holds the string denoting the payment_term field in the database. + FieldPaymentTerm = "payment_term" + // FieldIndex holds the string denoting the index field in the database. + FieldIndex = "index" + // FieldCreditsApplied holds the string denoting the credits_applied field in the database. + FieldCreditsApplied = "credits_applied" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // FieldNamespace holds the string denoting the namespace field in the database. + FieldNamespace = "namespace" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // 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" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // 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" + // FieldInvoiceID holds the string denoting the invoice_id field in the database. + FieldInvoiceID = "invoice_id" + // FieldParentLineID holds the string denoting the parent_line_id field in the database. + FieldParentLineID = "parent_line_id" + // EdgeBillingInvoice holds the string denoting the billing_invoice edge name in mutations. + EdgeBillingInvoice = "billing_invoice" + // EdgeBillingInvoiceLine holds the string denoting the billing_invoice_line edge name in mutations. + EdgeBillingInvoiceLine = "billing_invoice_line" + // EdgeAmountDiscounts holds the string denoting the amount_discounts edge name in mutations. + EdgeAmountDiscounts = "amount_discounts" + // Table holds the table name of the billingstandardinvoicedetailedline in the database. + Table = "billing_standard_invoice_detailed_lines" + // BillingInvoiceTable is the table that holds the billing_invoice relation/edge. + BillingInvoiceTable = "billing_standard_invoice_detailed_lines" + // BillingInvoiceInverseTable is the table name for the BillingInvoice entity. + // It exists in this package in order to avoid circular dependency with the "billinginvoice" package. + BillingInvoiceInverseTable = "billing_invoices" + // BillingInvoiceColumn is the table column denoting the billing_invoice relation/edge. + BillingInvoiceColumn = "invoice_id" + // BillingInvoiceLineTable is the table that holds the billing_invoice_line relation/edge. + BillingInvoiceLineTable = "billing_standard_invoice_detailed_lines" + // BillingInvoiceLineInverseTable is the table name for the BillingInvoiceLine entity. + // It exists in this package in order to avoid circular dependency with the "billinginvoiceline" package. + BillingInvoiceLineInverseTable = "billing_invoice_lines" + // BillingInvoiceLineColumn is the table column denoting the billing_invoice_line relation/edge. + BillingInvoiceLineColumn = "parent_line_id" + // AmountDiscountsTable is the table that holds the amount_discounts relation/edge. + AmountDiscountsTable = "billing_standard_invoice_detailed_line_amount_discounts" + // AmountDiscountsInverseTable is the table name for the BillingStandardInvoiceDetailedLineAmountDiscount entity. + // It exists in this package in order to avoid circular dependency with the "billingstandardinvoicedetailedlineamountdiscount" package. + AmountDiscountsInverseTable = "billing_standard_invoice_detailed_line_amount_discounts" + // AmountDiscountsColumn is the table column denoting the amount_discounts relation/edge. + AmountDiscountsColumn = "line_id" +) + +// Columns holds all SQL columns for billingstandardinvoicedetailedline fields. +var Columns = []string{ + FieldID, + FieldCurrency, + FieldServicePeriodStart, + FieldServicePeriodEnd, + FieldQuantity, + FieldInvoicingAppExternalID, + FieldChildUniqueReferenceID, + FieldPerUnitAmount, + FieldCategory, + FieldPaymentTerm, + FieldIndex, + FieldCreditsApplied, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldName, + FieldDescription, + FieldAmount, + FieldTaxesTotal, + FieldTaxesInclusiveTotal, + FieldTaxesExclusiveTotal, + FieldChargesTotal, + FieldDiscountsTotal, + FieldCreditsTotal, + FieldTotal, + FieldInvoiceID, + FieldParentLineID, +} + +// 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 + } + } + for _, f := range [...]string{FieldAnnotations, FieldMetadata} { + if column == f { + return true + } + } + return false +} + +var ( + // CurrencyValidator is a validator for the "currency" field. It is called by the builders before save. + CurrencyValidator func(string) error + // ChildUniqueReferenceIDValidator is a validator for the "child_unique_reference_id" field. It is called by the builders before save. + ChildUniqueReferenceIDValidator 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 +) + +const DefaultCategory stddetailedline.Category = "regular" + +// CategoryValidator is a validator for the "category" field enum values. It is called by the builders before save. +func CategoryValidator(c stddetailedline.Category) error { + switch c { + case "regular", "commitment": + return nil + default: + return fmt.Errorf("billingstandardinvoicedetailedline: invalid enum value for category field: %q", c) + } +} + +const DefaultPaymentTerm productcatalog.PaymentTermType = "in_advance" + +// PaymentTermValidator is a validator for the "payment_term" field enum values. It is called by the builders before save. +func PaymentTermValidator(pt productcatalog.PaymentTermType) error { + switch pt { + case "in_advance", "in_arrears": + return nil + default: + return fmt.Errorf("billingstandardinvoicedetailedline: invalid enum value for payment_term field: %q", pt) + } +} + +// OrderOption defines the ordering options for the BillingStandardInvoiceDetailedLine 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() +} + +// ByCurrency orders the results by the currency field. +func ByCurrency(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCurrency, opts...).ToFunc() +} + +// ByServicePeriodStart orders the results by the service_period_start field. +func ByServicePeriodStart(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldServicePeriodStart, opts...).ToFunc() +} + +// ByServicePeriodEnd orders the results by the service_period_end field. +func ByServicePeriodEnd(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldServicePeriodEnd, opts...).ToFunc() +} + +// ByQuantity orders the results by the quantity field. +func ByQuantity(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldQuantity, opts...).ToFunc() +} + +// ByInvoicingAppExternalID orders the results by the invoicing_app_external_id field. +func ByInvoicingAppExternalID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoicingAppExternalID, opts...).ToFunc() +} + +// ByChildUniqueReferenceID orders the results by the child_unique_reference_id field. +func ByChildUniqueReferenceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChildUniqueReferenceID, opts...).ToFunc() +} + +// ByPerUnitAmount orders the results by the per_unit_amount field. +func ByPerUnitAmount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPerUnitAmount, opts...).ToFunc() +} + +// ByCategory orders the results by the category field. +func ByCategory(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCategory, opts...).ToFunc() +} + +// ByPaymentTerm orders the results by the payment_term field. +func ByPaymentTerm(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPaymentTerm, opts...).ToFunc() +} + +// ByIndex orders the results by the index field. +func ByIndex(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIndex, 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() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, 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() +} + +// ByInvoiceID orders the results by the invoice_id field. +func ByInvoiceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoiceID, opts...).ToFunc() +} + +// ByParentLineID orders the results by the parent_line_id field. +func ByParentLineID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldParentLineID, opts...).ToFunc() +} + +// ByBillingInvoiceField orders the results by billing_invoice field. +func ByBillingInvoiceField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBillingInvoiceStep(), sql.OrderByField(field, opts...)) + } +} + +// ByBillingInvoiceLineField orders the results by billing_invoice_line field. +func ByBillingInvoiceLineField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBillingInvoiceLineStep(), sql.OrderByField(field, opts...)) + } +} + +// ByAmountDiscountsCount orders the results by amount_discounts count. +func ByAmountDiscountsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newAmountDiscountsStep(), opts...) + } +} + +// ByAmountDiscounts orders the results by amount_discounts terms. +func ByAmountDiscounts(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newAmountDiscountsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newBillingInvoiceStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BillingInvoiceInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, BillingInvoiceTable, BillingInvoiceColumn), + ) +} +func newBillingInvoiceLineStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BillingInvoiceLineInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, BillingInvoiceLineTable, BillingInvoiceLineColumn), + ) +} +func newAmountDiscountsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(AmountDiscountsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, AmountDiscountsTable, AmountDiscountsColumn), + ) +} diff --git a/ent/db/billingstandardinvoicedetailedline/where.go b/ent/db/billingstandardinvoicedetailedline/where.go new file mode 100644 index 0000000000000000000000000000000000000000..e751f4be34ef424aa888b1383830041381827b20 --- /dev/null +++ b/ent/db/billingstandardinvoicedetailedline/where.go @@ -0,0 +1,1584 @@ +// Code generated by ent, DO NOT EDIT. + +package billingstandardinvoicedetailedline + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/billing/models/stddetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldContainsFold(FieldID, id)) +} + +// Currency applies equality check predicate on the "currency" field. It's identical to CurrencyEQ. +func Currency(v currencyx.Code) predicate.BillingStandardInvoiceDetailedLine { + vc := string(v) + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldCurrency, vc)) +} + +// ServicePeriodStart applies equality check predicate on the "service_period_start" field. It's identical to ServicePeriodStartEQ. +func ServicePeriodStart(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldServicePeriodStart, v)) +} + +// ServicePeriodEnd applies equality check predicate on the "service_period_end" field. It's identical to ServicePeriodEndEQ. +func ServicePeriodEnd(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldServicePeriodEnd, v)) +} + +// Quantity applies equality check predicate on the "quantity" field. It's identical to QuantityEQ. +func Quantity(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldQuantity, v)) +} + +// InvoicingAppExternalID applies equality check predicate on the "invoicing_app_external_id" field. It's identical to InvoicingAppExternalIDEQ. +func InvoicingAppExternalID(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldInvoicingAppExternalID, v)) +} + +// ChildUniqueReferenceID applies equality check predicate on the "child_unique_reference_id" field. It's identical to ChildUniqueReferenceIDEQ. +func ChildUniqueReferenceID(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldChildUniqueReferenceID, v)) +} + +// PerUnitAmount applies equality check predicate on the "per_unit_amount" field. It's identical to PerUnitAmountEQ. +func PerUnitAmount(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldPerUnitAmount, v)) +} + +// Index applies equality check predicate on the "index" field. It's identical to IndexEQ. +func Index(v int) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldIndex, v)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(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.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(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.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(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.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldName, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldDescription, v)) +} + +// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ. +func Amount(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(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.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(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.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(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.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(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.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(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.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(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.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldCreditsTotal, v)) +} + +// Total applies equality check predicate on the "total" field. It's identical to TotalEQ. +func Total(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldTotal, v)) +} + +// InvoiceID applies equality check predicate on the "invoice_id" field. It's identical to InvoiceIDEQ. +func InvoiceID(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldInvoiceID, v)) +} + +// ParentLineID applies equality check predicate on the "parent_line_id" field. It's identical to ParentLineIDEQ. +func ParentLineID(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldParentLineID, v)) +} + +// CurrencyEQ applies the EQ predicate on the "currency" field. +func CurrencyEQ(v currencyx.Code) predicate.BillingStandardInvoiceDetailedLine { + vc := string(v) + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldCurrency, vc)) +} + +// CurrencyNEQ applies the NEQ predicate on the "currency" field. +func CurrencyNEQ(v currencyx.Code) predicate.BillingStandardInvoiceDetailedLine { + vc := string(v) + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldCurrency, vc)) +} + +// CurrencyIn applies the In predicate on the "currency" field. +func CurrencyIn(vs ...currencyx.Code) predicate.BillingStandardInvoiceDetailedLine { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldCurrency, v...)) +} + +// CurrencyNotIn applies the NotIn predicate on the "currency" field. +func CurrencyNotIn(vs ...currencyx.Code) predicate.BillingStandardInvoiceDetailedLine { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldCurrency, v...)) +} + +// CurrencyGT applies the GT predicate on the "currency" field. +func CurrencyGT(v currencyx.Code) predicate.BillingStandardInvoiceDetailedLine { + vc := string(v) + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldCurrency, vc)) +} + +// CurrencyGTE applies the GTE predicate on the "currency" field. +func CurrencyGTE(v currencyx.Code) predicate.BillingStandardInvoiceDetailedLine { + vc := string(v) + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldCurrency, vc)) +} + +// CurrencyLT applies the LT predicate on the "currency" field. +func CurrencyLT(v currencyx.Code) predicate.BillingStandardInvoiceDetailedLine { + vc := string(v) + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldCurrency, vc)) +} + +// CurrencyLTE applies the LTE predicate on the "currency" field. +func CurrencyLTE(v currencyx.Code) predicate.BillingStandardInvoiceDetailedLine { + vc := string(v) + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldCurrency, vc)) +} + +// CurrencyContains applies the Contains predicate on the "currency" field. +func CurrencyContains(v currencyx.Code) predicate.BillingStandardInvoiceDetailedLine { + vc := string(v) + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldContains(FieldCurrency, vc)) +} + +// CurrencyHasPrefix applies the HasPrefix predicate on the "currency" field. +func CurrencyHasPrefix(v currencyx.Code) predicate.BillingStandardInvoiceDetailedLine { + vc := string(v) + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldHasPrefix(FieldCurrency, vc)) +} + +// CurrencyHasSuffix applies the HasSuffix predicate on the "currency" field. +func CurrencyHasSuffix(v currencyx.Code) predicate.BillingStandardInvoiceDetailedLine { + vc := string(v) + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldHasSuffix(FieldCurrency, vc)) +} + +// CurrencyEqualFold applies the EqualFold predicate on the "currency" field. +func CurrencyEqualFold(v currencyx.Code) predicate.BillingStandardInvoiceDetailedLine { + vc := string(v) + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEqualFold(FieldCurrency, vc)) +} + +// CurrencyContainsFold applies the ContainsFold predicate on the "currency" field. +func CurrencyContainsFold(v currencyx.Code) predicate.BillingStandardInvoiceDetailedLine { + vc := string(v) + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldContainsFold(FieldCurrency, vc)) +} + +// ServicePeriodStartEQ applies the EQ predicate on the "service_period_start" field. +func ServicePeriodStartEQ(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldServicePeriodStart, v)) +} + +// ServicePeriodStartNEQ applies the NEQ predicate on the "service_period_start" field. +func ServicePeriodStartNEQ(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldServicePeriodStart, v)) +} + +// ServicePeriodStartIn applies the In predicate on the "service_period_start" field. +func ServicePeriodStartIn(vs ...time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldServicePeriodStart, vs...)) +} + +// ServicePeriodStartNotIn applies the NotIn predicate on the "service_period_start" field. +func ServicePeriodStartNotIn(vs ...time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldServicePeriodStart, vs...)) +} + +// ServicePeriodStartGT applies the GT predicate on the "service_period_start" field. +func ServicePeriodStartGT(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldServicePeriodStart, v)) +} + +// ServicePeriodStartGTE applies the GTE predicate on the "service_period_start" field. +func ServicePeriodStartGTE(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldServicePeriodStart, v)) +} + +// ServicePeriodStartLT applies the LT predicate on the "service_period_start" field. +func ServicePeriodStartLT(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldServicePeriodStart, v)) +} + +// ServicePeriodStartLTE applies the LTE predicate on the "service_period_start" field. +func ServicePeriodStartLTE(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldServicePeriodStart, v)) +} + +// ServicePeriodEndEQ applies the EQ predicate on the "service_period_end" field. +func ServicePeriodEndEQ(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldServicePeriodEnd, v)) +} + +// ServicePeriodEndNEQ applies the NEQ predicate on the "service_period_end" field. +func ServicePeriodEndNEQ(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldServicePeriodEnd, v)) +} + +// ServicePeriodEndIn applies the In predicate on the "service_period_end" field. +func ServicePeriodEndIn(vs ...time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldServicePeriodEnd, vs...)) +} + +// ServicePeriodEndNotIn applies the NotIn predicate on the "service_period_end" field. +func ServicePeriodEndNotIn(vs ...time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldServicePeriodEnd, vs...)) +} + +// ServicePeriodEndGT applies the GT predicate on the "service_period_end" field. +func ServicePeriodEndGT(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldServicePeriodEnd, v)) +} + +// ServicePeriodEndGTE applies the GTE predicate on the "service_period_end" field. +func ServicePeriodEndGTE(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldServicePeriodEnd, v)) +} + +// ServicePeriodEndLT applies the LT predicate on the "service_period_end" field. +func ServicePeriodEndLT(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldServicePeriodEnd, v)) +} + +// ServicePeriodEndLTE applies the LTE predicate on the "service_period_end" field. +func ServicePeriodEndLTE(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldServicePeriodEnd, v)) +} + +// QuantityEQ applies the EQ predicate on the "quantity" field. +func QuantityEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldQuantity, v)) +} + +// QuantityNEQ applies the NEQ predicate on the "quantity" field. +func QuantityNEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldQuantity, v)) +} + +// QuantityIn applies the In predicate on the "quantity" field. +func QuantityIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldQuantity, vs...)) +} + +// QuantityNotIn applies the NotIn predicate on the "quantity" field. +func QuantityNotIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldQuantity, vs...)) +} + +// QuantityGT applies the GT predicate on the "quantity" field. +func QuantityGT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldQuantity, v)) +} + +// QuantityGTE applies the GTE predicate on the "quantity" field. +func QuantityGTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldQuantity, v)) +} + +// QuantityLT applies the LT predicate on the "quantity" field. +func QuantityLT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldQuantity, v)) +} + +// QuantityLTE applies the LTE predicate on the "quantity" field. +func QuantityLTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldQuantity, v)) +} + +// InvoicingAppExternalIDEQ applies the EQ predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDEQ(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDNEQ applies the NEQ predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDNEQ(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDIn applies the In predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDIn(vs ...string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldInvoicingAppExternalID, vs...)) +} + +// InvoicingAppExternalIDNotIn applies the NotIn predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDNotIn(vs ...string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldInvoicingAppExternalID, vs...)) +} + +// InvoicingAppExternalIDGT applies the GT predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDGT(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDGTE applies the GTE predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDGTE(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDLT applies the LT predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDLT(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDLTE applies the LTE predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDLTE(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDContains applies the Contains predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDContains(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldContains(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDHasPrefix applies the HasPrefix predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDHasPrefix(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldHasPrefix(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDHasSuffix applies the HasSuffix predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDHasSuffix(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldHasSuffix(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDIsNil applies the IsNil predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDIsNil() predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIsNull(FieldInvoicingAppExternalID)) +} + +// InvoicingAppExternalIDNotNil applies the NotNil predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDNotNil() predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotNull(FieldInvoicingAppExternalID)) +} + +// InvoicingAppExternalIDEqualFold applies the EqualFold predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDEqualFold(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEqualFold(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDContainsFold applies the ContainsFold predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDContainsFold(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldContainsFold(FieldInvoicingAppExternalID, v)) +} + +// ChildUniqueReferenceIDEQ applies the EQ predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDEQ(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDNEQ applies the NEQ predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDNEQ(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDIn applies the In predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDIn(vs ...string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldChildUniqueReferenceID, vs...)) +} + +// ChildUniqueReferenceIDNotIn applies the NotIn predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDNotIn(vs ...string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldChildUniqueReferenceID, vs...)) +} + +// ChildUniqueReferenceIDGT applies the GT predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDGT(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDGTE applies the GTE predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDGTE(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDLT applies the LT predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDLT(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDLTE applies the LTE predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDLTE(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDContains applies the Contains predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDContains(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldContains(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDHasPrefix applies the HasPrefix predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDHasPrefix(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldHasPrefix(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDHasSuffix applies the HasSuffix predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDHasSuffix(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldHasSuffix(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDEqualFold applies the EqualFold predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDEqualFold(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEqualFold(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDContainsFold applies the ContainsFold predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDContainsFold(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldContainsFold(FieldChildUniqueReferenceID, v)) +} + +// PerUnitAmountEQ applies the EQ predicate on the "per_unit_amount" field. +func PerUnitAmountEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldPerUnitAmount, v)) +} + +// PerUnitAmountNEQ applies the NEQ predicate on the "per_unit_amount" field. +func PerUnitAmountNEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldPerUnitAmount, v)) +} + +// PerUnitAmountIn applies the In predicate on the "per_unit_amount" field. +func PerUnitAmountIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldPerUnitAmount, vs...)) +} + +// PerUnitAmountNotIn applies the NotIn predicate on the "per_unit_amount" field. +func PerUnitAmountNotIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldPerUnitAmount, vs...)) +} + +// PerUnitAmountGT applies the GT predicate on the "per_unit_amount" field. +func PerUnitAmountGT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldPerUnitAmount, v)) +} + +// PerUnitAmountGTE applies the GTE predicate on the "per_unit_amount" field. +func PerUnitAmountGTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldPerUnitAmount, v)) +} + +// PerUnitAmountLT applies the LT predicate on the "per_unit_amount" field. +func PerUnitAmountLT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldPerUnitAmount, v)) +} + +// PerUnitAmountLTE applies the LTE predicate on the "per_unit_amount" field. +func PerUnitAmountLTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldPerUnitAmount, v)) +} + +// CategoryEQ applies the EQ predicate on the "category" field. +func CategoryEQ(v stddetailedline.Category) predicate.BillingStandardInvoiceDetailedLine { + vc := v + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldCategory, vc)) +} + +// CategoryNEQ applies the NEQ predicate on the "category" field. +func CategoryNEQ(v stddetailedline.Category) predicate.BillingStandardInvoiceDetailedLine { + vc := v + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldCategory, vc)) +} + +// CategoryIn applies the In predicate on the "category" field. +func CategoryIn(vs ...stddetailedline.Category) predicate.BillingStandardInvoiceDetailedLine { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldCategory, v...)) +} + +// CategoryNotIn applies the NotIn predicate on the "category" field. +func CategoryNotIn(vs ...stddetailedline.Category) predicate.BillingStandardInvoiceDetailedLine { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldCategory, v...)) +} + +// PaymentTermEQ applies the EQ predicate on the "payment_term" field. +func PaymentTermEQ(v productcatalog.PaymentTermType) predicate.BillingStandardInvoiceDetailedLine { + vc := v + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldPaymentTerm, vc)) +} + +// PaymentTermNEQ applies the NEQ predicate on the "payment_term" field. +func PaymentTermNEQ(v productcatalog.PaymentTermType) predicate.BillingStandardInvoiceDetailedLine { + vc := v + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldPaymentTerm, vc)) +} + +// PaymentTermIn applies the In predicate on the "payment_term" field. +func PaymentTermIn(vs ...productcatalog.PaymentTermType) predicate.BillingStandardInvoiceDetailedLine { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldPaymentTerm, v...)) +} + +// PaymentTermNotIn applies the NotIn predicate on the "payment_term" field. +func PaymentTermNotIn(vs ...productcatalog.PaymentTermType) predicate.BillingStandardInvoiceDetailedLine { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldPaymentTerm, v...)) +} + +// IndexEQ applies the EQ predicate on the "index" field. +func IndexEQ(v int) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldIndex, v)) +} + +// IndexNEQ applies the NEQ predicate on the "index" field. +func IndexNEQ(v int) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldIndex, v)) +} + +// IndexIn applies the In predicate on the "index" field. +func IndexIn(vs ...int) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldIndex, vs...)) +} + +// IndexNotIn applies the NotIn predicate on the "index" field. +func IndexNotIn(vs ...int) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldIndex, vs...)) +} + +// IndexGT applies the GT predicate on the "index" field. +func IndexGT(v int) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldIndex, v)) +} + +// IndexGTE applies the GTE predicate on the "index" field. +func IndexGTE(v int) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldIndex, v)) +} + +// IndexLT applies the LT predicate on the "index" field. +func IndexLT(v int) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldIndex, v)) +} + +// IndexLTE applies the LTE predicate on the "index" field. +func IndexLTE(v int) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldIndex, v)) +} + +// IndexIsNil applies the IsNil predicate on the "index" field. +func IndexIsNil() predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIsNull(FieldIndex)) +} + +// IndexNotNil applies the NotNil predicate on the "index" field. +func IndexNotNil() predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotNull(FieldIndex)) +} + +// CreditsAppliedIsNil applies the IsNil predicate on the "credits_applied" field. +func CreditsAppliedIsNil() predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIsNull(FieldCreditsApplied)) +} + +// CreditsAppliedNotNil applies the NotNil predicate on the "credits_applied" field. +func CreditsAppliedNotNil() predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotNull(FieldCreditsApplied)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotNull(FieldAnnotations)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldContainsFold(FieldNamespace, v)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotNull(FieldMetadata)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotNull(FieldDeletedAt)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldContainsFold(FieldName, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldContainsFold(FieldDescription, v)) +} + +// AmountEQ applies the EQ predicate on the "amount" field. +func AmountEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldAmount, v)) +} + +// AmountNEQ applies the NEQ predicate on the "amount" field. +func AmountNEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldAmount, v)) +} + +// AmountIn applies the In predicate on the "amount" field. +func AmountIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldAmount, vs...)) +} + +// AmountNotIn applies the NotIn predicate on the "amount" field. +func AmountNotIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldAmount, vs...)) +} + +// AmountGT applies the GT predicate on the "amount" field. +func AmountGT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldAmount, v)) +} + +// AmountGTE applies the GTE predicate on the "amount" field. +func AmountGTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldAmount, v)) +} + +// AmountLT applies the LT predicate on the "amount" field. +func AmountLT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldAmount, v)) +} + +// AmountLTE applies the LTE predicate on the "amount" field. +func AmountLTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldAmount, v)) +} + +// TaxesTotalEQ applies the EQ predicate on the "taxes_total" field. +func TaxesTotalEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldTaxesTotal, v)) +} + +// TaxesTotalNEQ applies the NEQ predicate on the "taxes_total" field. +func TaxesTotalNEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldTaxesTotal, v)) +} + +// TaxesTotalIn applies the In predicate on the "taxes_total" field. +func TaxesTotalIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldTaxesTotal, vs...)) +} + +// TaxesTotalNotIn applies the NotIn predicate on the "taxes_total" field. +func TaxesTotalNotIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldTaxesTotal, vs...)) +} + +// TaxesTotalGT applies the GT predicate on the "taxes_total" field. +func TaxesTotalGT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldTaxesTotal, v)) +} + +// TaxesTotalGTE applies the GTE predicate on the "taxes_total" field. +func TaxesTotalGTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldTaxesTotal, v)) +} + +// TaxesTotalLT applies the LT predicate on the "taxes_total" field. +func TaxesTotalLT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldTaxesTotal, v)) +} + +// TaxesTotalLTE applies the LTE predicate on the "taxes_total" field. +func TaxesTotalLTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldTaxesTotal, v)) +} + +// TaxesInclusiveTotalEQ applies the EQ predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalNEQ applies the NEQ predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalNEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalIn applies the In predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldTaxesInclusiveTotal, vs...)) +} + +// TaxesInclusiveTotalNotIn applies the NotIn predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalNotIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldTaxesInclusiveTotal, vs...)) +} + +// TaxesInclusiveTotalGT applies the GT predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalGT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalGTE applies the GTE predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalGTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalLT applies the LT predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalLT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalLTE applies the LTE predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalLTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldTaxesInclusiveTotal, v)) +} + +// TaxesExclusiveTotalEQ applies the EQ predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalNEQ applies the NEQ predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalNEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalIn applies the In predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldTaxesExclusiveTotal, vs...)) +} + +// TaxesExclusiveTotalNotIn applies the NotIn predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalNotIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldTaxesExclusiveTotal, vs...)) +} + +// TaxesExclusiveTotalGT applies the GT predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalGT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalGTE applies the GTE predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalGTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalLT applies the LT predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalLT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalLTE applies the LTE predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalLTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldTaxesExclusiveTotal, v)) +} + +// ChargesTotalEQ applies the EQ predicate on the "charges_total" field. +func ChargesTotalEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldChargesTotal, v)) +} + +// ChargesTotalNEQ applies the NEQ predicate on the "charges_total" field. +func ChargesTotalNEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldChargesTotal, v)) +} + +// ChargesTotalIn applies the In predicate on the "charges_total" field. +func ChargesTotalIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldChargesTotal, vs...)) +} + +// ChargesTotalNotIn applies the NotIn predicate on the "charges_total" field. +func ChargesTotalNotIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldChargesTotal, vs...)) +} + +// ChargesTotalGT applies the GT predicate on the "charges_total" field. +func ChargesTotalGT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldChargesTotal, v)) +} + +// ChargesTotalGTE applies the GTE predicate on the "charges_total" field. +func ChargesTotalGTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldChargesTotal, v)) +} + +// ChargesTotalLT applies the LT predicate on the "charges_total" field. +func ChargesTotalLT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldChargesTotal, v)) +} + +// ChargesTotalLTE applies the LTE predicate on the "charges_total" field. +func ChargesTotalLTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldChargesTotal, v)) +} + +// DiscountsTotalEQ applies the EQ predicate on the "discounts_total" field. +func DiscountsTotalEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldDiscountsTotal, v)) +} + +// DiscountsTotalNEQ applies the NEQ predicate on the "discounts_total" field. +func DiscountsTotalNEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldDiscountsTotal, v)) +} + +// DiscountsTotalIn applies the In predicate on the "discounts_total" field. +func DiscountsTotalIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldDiscountsTotal, vs...)) +} + +// DiscountsTotalNotIn applies the NotIn predicate on the "discounts_total" field. +func DiscountsTotalNotIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldDiscountsTotal, vs...)) +} + +// DiscountsTotalGT applies the GT predicate on the "discounts_total" field. +func DiscountsTotalGT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldDiscountsTotal, v)) +} + +// DiscountsTotalGTE applies the GTE predicate on the "discounts_total" field. +func DiscountsTotalGTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldDiscountsTotal, v)) +} + +// DiscountsTotalLT applies the LT predicate on the "discounts_total" field. +func DiscountsTotalLT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldDiscountsTotal, v)) +} + +// DiscountsTotalLTE applies the LTE predicate on the "discounts_total" field. +func DiscountsTotalLTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldDiscountsTotal, v)) +} + +// CreditsTotalEQ applies the EQ predicate on the "credits_total" field. +func CreditsTotalEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldCreditsTotal, v)) +} + +// CreditsTotalNEQ applies the NEQ predicate on the "credits_total" field. +func CreditsTotalNEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldCreditsTotal, v)) +} + +// CreditsTotalIn applies the In predicate on the "credits_total" field. +func CreditsTotalIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldCreditsTotal, vs...)) +} + +// CreditsTotalNotIn applies the NotIn predicate on the "credits_total" field. +func CreditsTotalNotIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldCreditsTotal, vs...)) +} + +// CreditsTotalGT applies the GT predicate on the "credits_total" field. +func CreditsTotalGT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldCreditsTotal, v)) +} + +// CreditsTotalGTE applies the GTE predicate on the "credits_total" field. +func CreditsTotalGTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldCreditsTotal, v)) +} + +// CreditsTotalLT applies the LT predicate on the "credits_total" field. +func CreditsTotalLT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldCreditsTotal, v)) +} + +// CreditsTotalLTE applies the LTE predicate on the "credits_total" field. +func CreditsTotalLTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldCreditsTotal, v)) +} + +// TotalEQ applies the EQ predicate on the "total" field. +func TotalEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldTotal, v)) +} + +// TotalNEQ applies the NEQ predicate on the "total" field. +func TotalNEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldTotal, v)) +} + +// TotalIn applies the In predicate on the "total" field. +func TotalIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldTotal, vs...)) +} + +// TotalNotIn applies the NotIn predicate on the "total" field. +func TotalNotIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldTotal, vs...)) +} + +// TotalGT applies the GT predicate on the "total" field. +func TotalGT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldTotal, v)) +} + +// TotalGTE applies the GTE predicate on the "total" field. +func TotalGTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldTotal, v)) +} + +// TotalLT applies the LT predicate on the "total" field. +func TotalLT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldTotal, v)) +} + +// TotalLTE applies the LTE predicate on the "total" field. +func TotalLTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldTotal, v)) +} + +// InvoiceIDEQ applies the EQ predicate on the "invoice_id" field. +func InvoiceIDEQ(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldInvoiceID, v)) +} + +// InvoiceIDNEQ applies the NEQ predicate on the "invoice_id" field. +func InvoiceIDNEQ(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldInvoiceID, v)) +} + +// InvoiceIDIn applies the In predicate on the "invoice_id" field. +func InvoiceIDIn(vs ...string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldInvoiceID, vs...)) +} + +// InvoiceIDNotIn applies the NotIn predicate on the "invoice_id" field. +func InvoiceIDNotIn(vs ...string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldInvoiceID, vs...)) +} + +// InvoiceIDGT applies the GT predicate on the "invoice_id" field. +func InvoiceIDGT(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldInvoiceID, v)) +} + +// InvoiceIDGTE applies the GTE predicate on the "invoice_id" field. +func InvoiceIDGTE(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldInvoiceID, v)) +} + +// InvoiceIDLT applies the LT predicate on the "invoice_id" field. +func InvoiceIDLT(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldInvoiceID, v)) +} + +// InvoiceIDLTE applies the LTE predicate on the "invoice_id" field. +func InvoiceIDLTE(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldInvoiceID, v)) +} + +// InvoiceIDContains applies the Contains predicate on the "invoice_id" field. +func InvoiceIDContains(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldContains(FieldInvoiceID, v)) +} + +// InvoiceIDHasPrefix applies the HasPrefix predicate on the "invoice_id" field. +func InvoiceIDHasPrefix(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldHasPrefix(FieldInvoiceID, v)) +} + +// InvoiceIDHasSuffix applies the HasSuffix predicate on the "invoice_id" field. +func InvoiceIDHasSuffix(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldHasSuffix(FieldInvoiceID, v)) +} + +// InvoiceIDEqualFold applies the EqualFold predicate on the "invoice_id" field. +func InvoiceIDEqualFold(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEqualFold(FieldInvoiceID, v)) +} + +// InvoiceIDContainsFold applies the ContainsFold predicate on the "invoice_id" field. +func InvoiceIDContainsFold(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldContainsFold(FieldInvoiceID, v)) +} + +// ParentLineIDEQ applies the EQ predicate on the "parent_line_id" field. +func ParentLineIDEQ(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEQ(FieldParentLineID, v)) +} + +// ParentLineIDNEQ applies the NEQ predicate on the "parent_line_id" field. +func ParentLineIDNEQ(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNEQ(FieldParentLineID, v)) +} + +// ParentLineIDIn applies the In predicate on the "parent_line_id" field. +func ParentLineIDIn(vs ...string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldIn(FieldParentLineID, vs...)) +} + +// ParentLineIDNotIn applies the NotIn predicate on the "parent_line_id" field. +func ParentLineIDNotIn(vs ...string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldNotIn(FieldParentLineID, vs...)) +} + +// ParentLineIDGT applies the GT predicate on the "parent_line_id" field. +func ParentLineIDGT(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGT(FieldParentLineID, v)) +} + +// ParentLineIDGTE applies the GTE predicate on the "parent_line_id" field. +func ParentLineIDGTE(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldGTE(FieldParentLineID, v)) +} + +// ParentLineIDLT applies the LT predicate on the "parent_line_id" field. +func ParentLineIDLT(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLT(FieldParentLineID, v)) +} + +// ParentLineIDLTE applies the LTE predicate on the "parent_line_id" field. +func ParentLineIDLTE(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldLTE(FieldParentLineID, v)) +} + +// ParentLineIDContains applies the Contains predicate on the "parent_line_id" field. +func ParentLineIDContains(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldContains(FieldParentLineID, v)) +} + +// ParentLineIDHasPrefix applies the HasPrefix predicate on the "parent_line_id" field. +func ParentLineIDHasPrefix(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldHasPrefix(FieldParentLineID, v)) +} + +// ParentLineIDHasSuffix applies the HasSuffix predicate on the "parent_line_id" field. +func ParentLineIDHasSuffix(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldHasSuffix(FieldParentLineID, v)) +} + +// ParentLineIDEqualFold applies the EqualFold predicate on the "parent_line_id" field. +func ParentLineIDEqualFold(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldEqualFold(FieldParentLineID, v)) +} + +// ParentLineIDContainsFold applies the ContainsFold predicate on the "parent_line_id" field. +func ParentLineIDContainsFold(v string) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.FieldContainsFold(FieldParentLineID, v)) +} + +// HasBillingInvoice applies the HasEdge predicate on the "billing_invoice" edge. +func HasBillingInvoice() predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, BillingInvoiceTable, BillingInvoiceColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBillingInvoiceWith applies the HasEdge predicate on the "billing_invoice" edge with a given conditions (other predicates). +func HasBillingInvoiceWith(preds ...predicate.BillingInvoice) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(func(s *sql.Selector) { + step := newBillingInvoiceStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasBillingInvoiceLine applies the HasEdge predicate on the "billing_invoice_line" edge. +func HasBillingInvoiceLine() predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, BillingInvoiceLineTable, BillingInvoiceLineColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBillingInvoiceLineWith applies the HasEdge predicate on the "billing_invoice_line" edge with a given conditions (other predicates). +func HasBillingInvoiceLineWith(preds ...predicate.BillingInvoiceLine) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(func(s *sql.Selector) { + step := newBillingInvoiceLineStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasAmountDiscounts applies the HasEdge predicate on the "amount_discounts" edge. +func HasAmountDiscounts() predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, AmountDiscountsTable, AmountDiscountsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasAmountDiscountsWith applies the HasEdge predicate on the "amount_discounts" edge with a given conditions (other predicates). +func HasAmountDiscountsWith(preds ...predicate.BillingStandardInvoiceDetailedLineAmountDiscount) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(func(s *sql.Selector) { + step := newAmountDiscountsStep() + 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.BillingStandardInvoiceDetailedLine) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.BillingStandardInvoiceDetailedLine) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.BillingStandardInvoiceDetailedLine) predicate.BillingStandardInvoiceDetailedLine { + return predicate.BillingStandardInvoiceDetailedLine(sql.NotPredicates(p)) +} diff --git a/ent/db/billingstandardinvoicedetailedline_create.go b/ent/db/billingstandardinvoicedetailedline_create.go new file mode 100644 index 0000000000000000000000000000000000000000..7a3381b7c262dad2d68411ca9a28d5bceaf71bf9 --- /dev/null +++ b/ent/db/billingstandardinvoicedetailedline_create.go @@ -0,0 +1,2233 @@ +// 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/models/creditsapplied" + "github.com/openmeterio/openmeter/openmeter/billing/models/stddetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingstandardinvoicedetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingstandardinvoicedetailedlineamountdiscount" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// BillingStandardInvoiceDetailedLineCreate is the builder for creating a BillingStandardInvoiceDetailedLine entity. +type BillingStandardInvoiceDetailedLineCreate struct { + config + mutation *BillingStandardInvoiceDetailedLineMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetCurrency sets the "currency" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetCurrency(v currencyx.Code) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetCurrency(v) + return _c +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetServicePeriodStart(v time.Time) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetServicePeriodStart(v) + return _c +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetServicePeriodEnd(v time.Time) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetServicePeriodEnd(v) + return _c +} + +// SetQuantity sets the "quantity" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetQuantity(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetQuantity(v) + return _c +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetInvoicingAppExternalID(v string) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetInvoicingAppExternalID(v) + return _c +} + +// SetNillableInvoicingAppExternalID sets the "invoicing_app_external_id" field if the given value is not nil. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetNillableInvoicingAppExternalID(v *string) *BillingStandardInvoiceDetailedLineCreate { + if v != nil { + _c.SetInvoicingAppExternalID(*v) + } + return _c +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetChildUniqueReferenceID(v string) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetChildUniqueReferenceID(v) + return _c +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetPerUnitAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetPerUnitAmount(v) + return _c +} + +// SetCategory sets the "category" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetCategory(v stddetailedline.Category) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetCategory(v) + return _c +} + +// SetNillableCategory sets the "category" field if the given value is not nil. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetNillableCategory(v *stddetailedline.Category) *BillingStandardInvoiceDetailedLineCreate { + if v != nil { + _c.SetCategory(*v) + } + return _c +} + +// SetPaymentTerm sets the "payment_term" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetPaymentTerm(v productcatalog.PaymentTermType) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetPaymentTerm(v) + return _c +} + +// SetNillablePaymentTerm sets the "payment_term" field if the given value is not nil. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetNillablePaymentTerm(v *productcatalog.PaymentTermType) *BillingStandardInvoiceDetailedLineCreate { + if v != nil { + _c.SetPaymentTerm(*v) + } + return _c +} + +// SetIndex sets the "index" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetIndex(v int) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetIndex(v) + return _c +} + +// SetNillableIndex sets the "index" field if the given value is not nil. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetNillableIndex(v *int) *BillingStandardInvoiceDetailedLineCreate { + if v != nil { + _c.SetIndex(*v) + } + return _c +} + +// SetCreditsApplied sets the "credits_applied" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetCreditsApplied(v *creditsapplied.CreditsApplied) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetCreditsApplied(v) + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetAnnotations(v models.Annotations) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetNamespace sets the "namespace" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetNamespace(v string) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetMetadata sets the "metadata" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetMetadata(v map[string]string) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetMetadata(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetCreatedAt(v time.Time) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetNillableCreatedAt(v *time.Time) *BillingStandardInvoiceDetailedLineCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetUpdatedAt(v time.Time) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetNillableUpdatedAt(v *time.Time) *BillingStandardInvoiceDetailedLineCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetDeletedAt(v time.Time) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetNillableDeletedAt(v *time.Time) *BillingStandardInvoiceDetailedLineCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetName sets the "name" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetName(v string) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetName(v) + return _c +} + +// SetDescription sets the "description" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetDescription(v string) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetDescription(v) + return _c +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetNillableDescription(v *string) *BillingStandardInvoiceDetailedLineCreate { + if v != nil { + _c.SetDescription(*v) + } + return _c +} + +// SetAmount sets the "amount" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetTaxesTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetTaxesTotal(v) + return _c +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetTaxesInclusiveTotal(v) + return _c +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetTaxesExclusiveTotal(v) + return _c +} + +// SetChargesTotal sets the "charges_total" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetChargesTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetChargesTotal(v) + return _c +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetDiscountsTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetDiscountsTotal(v) + return _c +} + +// SetCreditsTotal sets the "credits_total" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetCreditsTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetCreditsTotal(v) + return _c +} + +// SetTotal sets the "total" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetTotal(v) + return _c +} + +// SetInvoiceID sets the "invoice_id" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetInvoiceID(v string) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetInvoiceID(v) + return _c +} + +// SetParentLineID sets the "parent_line_id" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetParentLineID(v string) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetParentLineID(v) + return _c +} + +// SetID sets the "id" field. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetID(v string) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetNillableID(v *string) *BillingStandardInvoiceDetailedLineCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetBillingInvoiceID sets the "billing_invoice" edge to the BillingInvoice entity by ID. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetBillingInvoiceID(id string) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetBillingInvoiceID(id) + return _c +} + +// SetBillingInvoice sets the "billing_invoice" edge to the BillingInvoice entity. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetBillingInvoice(v *BillingInvoice) *BillingStandardInvoiceDetailedLineCreate { + return _c.SetBillingInvoiceID(v.ID) +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetBillingInvoiceLineID(id string) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.SetBillingInvoiceLineID(id) + return _c +} + +// SetBillingInvoiceLine sets the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_c *BillingStandardInvoiceDetailedLineCreate) SetBillingInvoiceLine(v *BillingInvoiceLine) *BillingStandardInvoiceDetailedLineCreate { + return _c.SetBillingInvoiceLineID(v.ID) +} + +// AddAmountDiscountIDs adds the "amount_discounts" edge to the BillingStandardInvoiceDetailedLineAmountDiscount entity by IDs. +func (_c *BillingStandardInvoiceDetailedLineCreate) AddAmountDiscountIDs(ids ...string) *BillingStandardInvoiceDetailedLineCreate { + _c.mutation.AddAmountDiscountIDs(ids...) + return _c +} + +// AddAmountDiscounts adds the "amount_discounts" edges to the BillingStandardInvoiceDetailedLineAmountDiscount entity. +func (_c *BillingStandardInvoiceDetailedLineCreate) AddAmountDiscounts(v ...*BillingStandardInvoiceDetailedLineAmountDiscount) *BillingStandardInvoiceDetailedLineCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddAmountDiscountIDs(ids...) +} + +// Mutation returns the BillingStandardInvoiceDetailedLineMutation object of the builder. +func (_c *BillingStandardInvoiceDetailedLineCreate) Mutation() *BillingStandardInvoiceDetailedLineMutation { + return _c.mutation +} + +// Save creates the BillingStandardInvoiceDetailedLine in the database. +func (_c *BillingStandardInvoiceDetailedLineCreate) Save(ctx context.Context) (*BillingStandardInvoiceDetailedLine, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *BillingStandardInvoiceDetailedLineCreate) SaveX(ctx context.Context) *BillingStandardInvoiceDetailedLine { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingStandardInvoiceDetailedLineCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingStandardInvoiceDetailedLineCreate) 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 *BillingStandardInvoiceDetailedLineCreate) defaults() { + if _, ok := _c.mutation.Category(); !ok { + v := billingstandardinvoicedetailedline.DefaultCategory + _c.mutation.SetCategory(v) + } + if _, ok := _c.mutation.PaymentTerm(); !ok { + v := billingstandardinvoicedetailedline.DefaultPaymentTerm + _c.mutation.SetPaymentTerm(v) + } + if _, ok := _c.mutation.CreatedAt(); !ok { + v := billingstandardinvoicedetailedline.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := billingstandardinvoicedetailedline.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := billingstandardinvoicedetailedline.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *BillingStandardInvoiceDetailedLineCreate) check() error { + if _, ok := _c.mutation.Currency(); !ok { + return &ValidationError{Name: "currency", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.currency"`)} + } + if v, ok := _c.mutation.Currency(); ok { + if err := billingstandardinvoicedetailedline.CurrencyValidator(string(v)); err != nil { + return &ValidationError{Name: "currency", err: fmt.Errorf(`db: validator failed for field "BillingStandardInvoiceDetailedLine.currency": %w`, err)} + } + } + if _, ok := _c.mutation.ServicePeriodStart(); !ok { + return &ValidationError{Name: "service_period_start", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.service_period_start"`)} + } + if _, ok := _c.mutation.ServicePeriodEnd(); !ok { + return &ValidationError{Name: "service_period_end", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.service_period_end"`)} + } + if _, ok := _c.mutation.Quantity(); !ok { + return &ValidationError{Name: "quantity", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.quantity"`)} + } + if _, ok := _c.mutation.ChildUniqueReferenceID(); !ok { + return &ValidationError{Name: "child_unique_reference_id", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.child_unique_reference_id"`)} + } + if v, ok := _c.mutation.ChildUniqueReferenceID(); ok { + if err := billingstandardinvoicedetailedline.ChildUniqueReferenceIDValidator(v); err != nil { + return &ValidationError{Name: "child_unique_reference_id", err: fmt.Errorf(`db: validator failed for field "BillingStandardInvoiceDetailedLine.child_unique_reference_id": %w`, err)} + } + } + if _, ok := _c.mutation.PerUnitAmount(); !ok { + return &ValidationError{Name: "per_unit_amount", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.per_unit_amount"`)} + } + if _, ok := _c.mutation.Category(); !ok { + return &ValidationError{Name: "category", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.category"`)} + } + if v, ok := _c.mutation.Category(); ok { + if err := billingstandardinvoicedetailedline.CategoryValidator(v); err != nil { + return &ValidationError{Name: "category", err: fmt.Errorf(`db: validator failed for field "BillingStandardInvoiceDetailedLine.category": %w`, err)} + } + } + if _, ok := _c.mutation.PaymentTerm(); !ok { + return &ValidationError{Name: "payment_term", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.payment_term"`)} + } + if v, ok := _c.mutation.PaymentTerm(); ok { + if err := billingstandardinvoicedetailedline.PaymentTermValidator(v); err != nil { + return &ValidationError{Name: "payment_term", err: fmt.Errorf(`db: validator failed for field "BillingStandardInvoiceDetailedLine.payment_term": %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 "BillingStandardInvoiceDetailedLine.credits_applied": %w`, err)} + } + } + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := billingstandardinvoicedetailedline.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "BillingStandardInvoiceDetailedLine.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.updated_at"`)} + } + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.name"`)} + } + if _, ok := _c.mutation.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.amount"`)} + } + if _, ok := _c.mutation.TaxesTotal(); !ok { + return &ValidationError{Name: "taxes_total", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.taxes_total"`)} + } + if _, ok := _c.mutation.TaxesInclusiveTotal(); !ok { + return &ValidationError{Name: "taxes_inclusive_total", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.taxes_inclusive_total"`)} + } + if _, ok := _c.mutation.TaxesExclusiveTotal(); !ok { + return &ValidationError{Name: "taxes_exclusive_total", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.taxes_exclusive_total"`)} + } + if _, ok := _c.mutation.ChargesTotal(); !ok { + return &ValidationError{Name: "charges_total", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.charges_total"`)} + } + if _, ok := _c.mutation.DiscountsTotal(); !ok { + return &ValidationError{Name: "discounts_total", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.discounts_total"`)} + } + if _, ok := _c.mutation.CreditsTotal(); !ok { + return &ValidationError{Name: "credits_total", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.credits_total"`)} + } + if _, ok := _c.mutation.Total(); !ok { + return &ValidationError{Name: "total", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.total"`)} + } + if _, ok := _c.mutation.InvoiceID(); !ok { + return &ValidationError{Name: "invoice_id", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.invoice_id"`)} + } + if _, ok := _c.mutation.ParentLineID(); !ok { + return &ValidationError{Name: "parent_line_id", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLine.parent_line_id"`)} + } + if len(_c.mutation.BillingInvoiceIDs()) == 0 { + return &ValidationError{Name: "billing_invoice", err: errors.New(`db: missing required edge "BillingStandardInvoiceDetailedLine.billing_invoice"`)} + } + if len(_c.mutation.BillingInvoiceLineIDs()) == 0 { + return &ValidationError{Name: "billing_invoice_line", err: errors.New(`db: missing required edge "BillingStandardInvoiceDetailedLine.billing_invoice_line"`)} + } + return nil +} + +func (_c *BillingStandardInvoiceDetailedLineCreate) sqlSave(ctx context.Context) (*BillingStandardInvoiceDetailedLine, 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 BillingStandardInvoiceDetailedLine.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *BillingStandardInvoiceDetailedLineCreate) createSpec() (*BillingStandardInvoiceDetailedLine, *sqlgraph.CreateSpec) { + var ( + _node = &BillingStandardInvoiceDetailedLine{config: _c.config} + _spec = sqlgraph.NewCreateSpec(billingstandardinvoicedetailedline.Table, sqlgraph.NewFieldSpec(billingstandardinvoicedetailedline.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.Currency(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldCurrency, field.TypeString, value) + _node.Currency = value + } + if value, ok := _c.mutation.ServicePeriodStart(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldServicePeriodStart, field.TypeTime, value) + _node.ServicePeriodStart = value + } + if value, ok := _c.mutation.ServicePeriodEnd(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldServicePeriodEnd, field.TypeTime, value) + _node.ServicePeriodEnd = value + } + if value, ok := _c.mutation.Quantity(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldQuantity, field.TypeOther, value) + _node.Quantity = value + } + if value, ok := _c.mutation.InvoicingAppExternalID(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldInvoicingAppExternalID, field.TypeString, value) + _node.InvoicingAppExternalID = &value + } + if value, ok := _c.mutation.ChildUniqueReferenceID(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldChildUniqueReferenceID, field.TypeString, value) + _node.ChildUniqueReferenceID = value + } + if value, ok := _c.mutation.PerUnitAmount(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldPerUnitAmount, field.TypeOther, value) + _node.PerUnitAmount = value + } + if value, ok := _c.mutation.Category(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldCategory, field.TypeEnum, value) + _node.Category = value + } + if value, ok := _c.mutation.PaymentTerm(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldPaymentTerm, field.TypeEnum, value) + _node.PaymentTerm = value + } + if value, ok := _c.mutation.Index(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldIndex, field.TypeInt, value) + _node.Index = &value + } + if value, ok := _c.mutation.CreditsApplied(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldCreditsApplied, field.TypeJSON, value) + _node.CreditsApplied = value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Metadata(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldMetadata, field.TypeJSON, value) + _node.Metadata = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Description(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldDescription, field.TypeString, value) + _node.Description = &value + } + if value, ok := _c.mutation.Amount(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldAmount, field.TypeOther, value) + _node.Amount = value + } + if value, ok := _c.mutation.TaxesTotal(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldTaxesTotal, field.TypeOther, value) + _node.TaxesTotal = value + } + if value, ok := _c.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldTaxesInclusiveTotal, field.TypeOther, value) + _node.TaxesInclusiveTotal = value + } + if value, ok := _c.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldTaxesExclusiveTotal, field.TypeOther, value) + _node.TaxesExclusiveTotal = value + } + if value, ok := _c.mutation.ChargesTotal(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldChargesTotal, field.TypeOther, value) + _node.ChargesTotal = value + } + if value, ok := _c.mutation.DiscountsTotal(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldDiscountsTotal, field.TypeOther, value) + _node.DiscountsTotal = value + } + if value, ok := _c.mutation.CreditsTotal(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldCreditsTotal, field.TypeOther, value) + _node.CreditsTotal = value + } + if value, ok := _c.mutation.Total(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldTotal, field.TypeOther, value) + _node.Total = value + } + if nodes := _c.mutation.BillingInvoiceIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingstandardinvoicedetailedline.BillingInvoiceTable, + Columns: []string{billingstandardinvoicedetailedline.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.InvoiceID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.BillingInvoiceLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingstandardinvoicedetailedline.BillingInvoiceLineTable, + Columns: []string{billingstandardinvoicedetailedline.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.ParentLineID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.AmountDiscountsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingstandardinvoicedetailedline.AmountDiscountsTable, + Columns: []string{billingstandardinvoicedetailedline.AmountDiscountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingstandardinvoicedetailedlineamountdiscount.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.BillingStandardInvoiceDetailedLine.Create(). +// SetCurrency(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.BillingStandardInvoiceDetailedLineUpsert) { +// SetCurrency(v+v). +// }). +// Exec(ctx) +func (_c *BillingStandardInvoiceDetailedLineCreate) OnConflict(opts ...sql.ConflictOption) *BillingStandardInvoiceDetailedLineUpsertOne { + _c.conflict = opts + return &BillingStandardInvoiceDetailedLineUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingStandardInvoiceDetailedLine.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingStandardInvoiceDetailedLineCreate) OnConflictColumns(columns ...string) *BillingStandardInvoiceDetailedLineUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingStandardInvoiceDetailedLineUpsertOne{ + create: _c, + } +} + +type ( + // BillingStandardInvoiceDetailedLineUpsertOne is the builder for "upsert"-ing + // one BillingStandardInvoiceDetailedLine node. + BillingStandardInvoiceDetailedLineUpsertOne struct { + create *BillingStandardInvoiceDetailedLineCreate + } + + // BillingStandardInvoiceDetailedLineUpsert is the "OnConflict" setter. + BillingStandardInvoiceDetailedLineUpsert struct { + *sql.UpdateSet + } +) + +// SetServicePeriodStart sets the "service_period_start" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetServicePeriodStart(v time.Time) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldServicePeriodStart, v) + return u +} + +// UpdateServicePeriodStart sets the "service_period_start" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateServicePeriodStart() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldServicePeriodStart) + return u +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetServicePeriodEnd(v time.Time) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldServicePeriodEnd, v) + return u +} + +// UpdateServicePeriodEnd sets the "service_period_end" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateServicePeriodEnd() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldServicePeriodEnd) + return u +} + +// SetQuantity sets the "quantity" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetQuantity(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldQuantity, v) + return u +} + +// UpdateQuantity sets the "quantity" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateQuantity() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldQuantity) + return u +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetInvoicingAppExternalID(v string) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldInvoicingAppExternalID, v) + return u +} + +// UpdateInvoicingAppExternalID sets the "invoicing_app_external_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateInvoicingAppExternalID() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldInvoicingAppExternalID) + return u +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) ClearInvoicingAppExternalID() *BillingStandardInvoiceDetailedLineUpsert { + u.SetNull(billingstandardinvoicedetailedline.FieldInvoicingAppExternalID) + return u +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetChildUniqueReferenceID(v string) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldChildUniqueReferenceID, v) + return u +} + +// UpdateChildUniqueReferenceID sets the "child_unique_reference_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateChildUniqueReferenceID() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldChildUniqueReferenceID) + return u +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetPerUnitAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldPerUnitAmount, v) + return u +} + +// UpdatePerUnitAmount sets the "per_unit_amount" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdatePerUnitAmount() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldPerUnitAmount) + return u +} + +// SetCategory sets the "category" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetCategory(v stddetailedline.Category) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldCategory, v) + return u +} + +// UpdateCategory sets the "category" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateCategory() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldCategory) + return u +} + +// SetPaymentTerm sets the "payment_term" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetPaymentTerm(v productcatalog.PaymentTermType) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldPaymentTerm, v) + return u +} + +// UpdatePaymentTerm sets the "payment_term" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdatePaymentTerm() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldPaymentTerm) + return u +} + +// SetIndex sets the "index" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetIndex(v int) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldIndex, v) + return u +} + +// UpdateIndex sets the "index" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateIndex() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldIndex) + return u +} + +// AddIndex adds v to the "index" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) AddIndex(v int) *BillingStandardInvoiceDetailedLineUpsert { + u.Add(billingstandardinvoicedetailedline.FieldIndex, v) + return u +} + +// ClearIndex clears the value of the "index" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) ClearIndex() *BillingStandardInvoiceDetailedLineUpsert { + u.SetNull(billingstandardinvoicedetailedline.FieldIndex) + return u +} + +// SetCreditsApplied sets the "credits_applied" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetCreditsApplied(v *creditsapplied.CreditsApplied) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldCreditsApplied, v) + return u +} + +// UpdateCreditsApplied sets the "credits_applied" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateCreditsApplied() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldCreditsApplied) + return u +} + +// ClearCreditsApplied clears the value of the "credits_applied" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) ClearCreditsApplied() *BillingStandardInvoiceDetailedLineUpsert { + u.SetNull(billingstandardinvoicedetailedline.FieldCreditsApplied) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetAnnotations(v models.Annotations) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateAnnotations() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) ClearAnnotations() *BillingStandardInvoiceDetailedLineUpsert { + u.SetNull(billingstandardinvoicedetailedline.FieldAnnotations) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetMetadata(v map[string]string) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldMetadata, v) + return u +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateMetadata() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldMetadata) + return u +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) ClearMetadata() *BillingStandardInvoiceDetailedLineUpsert { + u.SetNull(billingstandardinvoicedetailedline.FieldMetadata) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetUpdatedAt(v time.Time) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateUpdatedAt() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetDeletedAt(v time.Time) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateDeletedAt() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) ClearDeletedAt() *BillingStandardInvoiceDetailedLineUpsert { + u.SetNull(billingstandardinvoicedetailedline.FieldDeletedAt) + return u +} + +// SetName sets the "name" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetName(v string) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateName() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldName) + return u +} + +// SetDescription sets the "description" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetDescription(v string) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldDescription, v) + return u +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateDescription() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldDescription) + return u +} + +// ClearDescription clears the value of the "description" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) ClearDescription() *BillingStandardInvoiceDetailedLineUpsert { + u.SetNull(billingstandardinvoicedetailedline.FieldDescription) + return u +} + +// SetAmount sets the "amount" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldAmount, v) + return u +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateAmount() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldAmount) + return u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetTaxesTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldTaxesTotal, v) + return u +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateTaxesTotal() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldTaxesTotal) + return u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldTaxesInclusiveTotal, v) + return u +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateTaxesInclusiveTotal() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldTaxesInclusiveTotal) + return u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldTaxesExclusiveTotal, v) + return u +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateTaxesExclusiveTotal() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldTaxesExclusiveTotal) + return u +} + +// SetChargesTotal sets the "charges_total" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetChargesTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldChargesTotal, v) + return u +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateChargesTotal() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldChargesTotal) + return u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetDiscountsTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldDiscountsTotal, v) + return u +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateDiscountsTotal() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldDiscountsTotal) + return u +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetCreditsTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldCreditsTotal, v) + return u +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateCreditsTotal() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldCreditsTotal) + return u +} + +// SetTotal sets the "total" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldTotal, v) + return u +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateTotal() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldTotal) + return u +} + +// SetInvoiceID sets the "invoice_id" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetInvoiceID(v string) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldInvoiceID, v) + return u +} + +// UpdateInvoiceID sets the "invoice_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateInvoiceID() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldInvoiceID) + return u +} + +// SetParentLineID sets the "parent_line_id" field. +func (u *BillingStandardInvoiceDetailedLineUpsert) SetParentLineID(v string) *BillingStandardInvoiceDetailedLineUpsert { + u.Set(billingstandardinvoicedetailedline.FieldParentLineID, v) + return u +} + +// UpdateParentLineID sets the "parent_line_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsert) UpdateParentLineID() *BillingStandardInvoiceDetailedLineUpsert { + u.SetExcluded(billingstandardinvoicedetailedline.FieldParentLineID) + 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.BillingStandardInvoiceDetailedLine.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(billingstandardinvoicedetailedline.FieldID) +// }), +// ). +// Exec(ctx) +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateNewValues() *BillingStandardInvoiceDetailedLineUpsertOne { + 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(billingstandardinvoicedetailedline.FieldID) + } + if _, exists := u.create.mutation.Currency(); exists { + s.SetIgnore(billingstandardinvoicedetailedline.FieldCurrency) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(billingstandardinvoicedetailedline.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(billingstandardinvoicedetailedline.FieldCreatedAt) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingStandardInvoiceDetailedLine.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingStandardInvoiceDetailedLineUpsertOne) Ignore() *BillingStandardInvoiceDetailedLineUpsertOne { + 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 *BillingStandardInvoiceDetailedLineUpsertOne) DoNothing() *BillingStandardInvoiceDetailedLineUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingStandardInvoiceDetailedLineCreate.OnConflict +// documentation for more info. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) Update(set func(*BillingStandardInvoiceDetailedLineUpsert)) *BillingStandardInvoiceDetailedLineUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingStandardInvoiceDetailedLineUpsert{UpdateSet: update}) + })) + return u +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetServicePeriodStart(v time.Time) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetServicePeriodStart(v) + }) +} + +// UpdateServicePeriodStart sets the "service_period_start" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateServicePeriodStart() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateServicePeriodStart() + }) +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetServicePeriodEnd(v time.Time) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetServicePeriodEnd(v) + }) +} + +// UpdateServicePeriodEnd sets the "service_period_end" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateServicePeriodEnd() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateServicePeriodEnd() + }) +} + +// SetQuantity sets the "quantity" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetQuantity(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetQuantity(v) + }) +} + +// UpdateQuantity sets the "quantity" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateQuantity() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateQuantity() + }) +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetInvoicingAppExternalID(v string) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetInvoicingAppExternalID(v) + }) +} + +// UpdateInvoicingAppExternalID sets the "invoicing_app_external_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateInvoicingAppExternalID() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateInvoicingAppExternalID() + }) +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) ClearInvoicingAppExternalID() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.ClearInvoicingAppExternalID() + }) +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetChildUniqueReferenceID(v string) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetChildUniqueReferenceID(v) + }) +} + +// UpdateChildUniqueReferenceID sets the "child_unique_reference_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateChildUniqueReferenceID() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateChildUniqueReferenceID() + }) +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetPerUnitAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetPerUnitAmount(v) + }) +} + +// UpdatePerUnitAmount sets the "per_unit_amount" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdatePerUnitAmount() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdatePerUnitAmount() + }) +} + +// SetCategory sets the "category" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetCategory(v stddetailedline.Category) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetCategory(v) + }) +} + +// UpdateCategory sets the "category" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateCategory() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateCategory() + }) +} + +// SetPaymentTerm sets the "payment_term" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetPaymentTerm(v productcatalog.PaymentTermType) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetPaymentTerm(v) + }) +} + +// UpdatePaymentTerm sets the "payment_term" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdatePaymentTerm() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdatePaymentTerm() + }) +} + +// SetIndex sets the "index" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetIndex(v int) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetIndex(v) + }) +} + +// AddIndex adds v to the "index" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) AddIndex(v int) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.AddIndex(v) + }) +} + +// UpdateIndex sets the "index" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateIndex() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateIndex() + }) +} + +// ClearIndex clears the value of the "index" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) ClearIndex() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.ClearIndex() + }) +} + +// SetCreditsApplied sets the "credits_applied" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetCreditsApplied(v *creditsapplied.CreditsApplied) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetCreditsApplied(v) + }) +} + +// UpdateCreditsApplied sets the "credits_applied" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateCreditsApplied() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateCreditsApplied() + }) +} + +// ClearCreditsApplied clears the value of the "credits_applied" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) ClearCreditsApplied() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.ClearCreditsApplied() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetAnnotations(v models.Annotations) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateAnnotations() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) ClearAnnotations() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.ClearAnnotations() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetMetadata(v map[string]string) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateMetadata() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) ClearMetadata() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetUpdatedAt(v time.Time) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateUpdatedAt() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetDeletedAt(v time.Time) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateDeletedAt() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) ClearDeletedAt() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetName(v string) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateName() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetDescription(v string) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateDescription() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) ClearDescription() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.ClearDescription() + }) +} + +// SetAmount sets the "amount" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateAmount() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateAmount() + }) +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetTaxesTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetTaxesTotal(v) + }) +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateTaxesTotal() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateTaxesTotal() + }) +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetTaxesInclusiveTotal(v) + }) +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateTaxesInclusiveTotal() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateTaxesInclusiveTotal() + }) +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetTaxesExclusiveTotal(v) + }) +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateTaxesExclusiveTotal() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateTaxesExclusiveTotal() + }) +} + +// SetChargesTotal sets the "charges_total" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetChargesTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetChargesTotal(v) + }) +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateChargesTotal() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateChargesTotal() + }) +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetDiscountsTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetDiscountsTotal(v) + }) +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateDiscountsTotal() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateDiscountsTotal() + }) +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetCreditsTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetCreditsTotal(v) + }) +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateCreditsTotal() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateCreditsTotal() + }) +} + +// SetTotal sets the "total" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetTotal(v) + }) +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateTotal() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateTotal() + }) +} + +// SetInvoiceID sets the "invoice_id" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetInvoiceID(v string) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetInvoiceID(v) + }) +} + +// UpdateInvoiceID sets the "invoice_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateInvoiceID() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateInvoiceID() + }) +} + +// SetParentLineID sets the "parent_line_id" field. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) SetParentLineID(v string) *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetParentLineID(v) + }) +} + +// UpdateParentLineID sets the "parent_line_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) UpdateParentLineID() *BillingStandardInvoiceDetailedLineUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateParentLineID() + }) +} + +// Exec executes the query. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingStandardInvoiceDetailedLineCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingStandardInvoiceDetailedLineUpsertOne) 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 *BillingStandardInvoiceDetailedLineUpsertOne) 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: BillingStandardInvoiceDetailedLineUpsertOne.ID is not supported by MySQL driver. Use BillingStandardInvoiceDetailedLineUpsertOne.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 *BillingStandardInvoiceDetailedLineUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// BillingStandardInvoiceDetailedLineCreateBulk is the builder for creating many BillingStandardInvoiceDetailedLine entities in bulk. +type BillingStandardInvoiceDetailedLineCreateBulk struct { + config + err error + builders []*BillingStandardInvoiceDetailedLineCreate + conflict []sql.ConflictOption +} + +// Save creates the BillingStandardInvoiceDetailedLine entities in the database. +func (_c *BillingStandardInvoiceDetailedLineCreateBulk) Save(ctx context.Context) ([]*BillingStandardInvoiceDetailedLine, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*BillingStandardInvoiceDetailedLine, 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.(*BillingStandardInvoiceDetailedLineMutation) + 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 *BillingStandardInvoiceDetailedLineCreateBulk) SaveX(ctx context.Context) []*BillingStandardInvoiceDetailedLine { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingStandardInvoiceDetailedLineCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingStandardInvoiceDetailedLineCreateBulk) 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.BillingStandardInvoiceDetailedLine.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.BillingStandardInvoiceDetailedLineUpsert) { +// SetCurrency(v+v). +// }). +// Exec(ctx) +func (_c *BillingStandardInvoiceDetailedLineCreateBulk) OnConflict(opts ...sql.ConflictOption) *BillingStandardInvoiceDetailedLineUpsertBulk { + _c.conflict = opts + return &BillingStandardInvoiceDetailedLineUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingStandardInvoiceDetailedLine.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingStandardInvoiceDetailedLineCreateBulk) OnConflictColumns(columns ...string) *BillingStandardInvoiceDetailedLineUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingStandardInvoiceDetailedLineUpsertBulk{ + create: _c, + } +} + +// BillingStandardInvoiceDetailedLineUpsertBulk is the builder for "upsert"-ing +// a bulk of BillingStandardInvoiceDetailedLine nodes. +type BillingStandardInvoiceDetailedLineUpsertBulk struct { + create *BillingStandardInvoiceDetailedLineCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.BillingStandardInvoiceDetailedLine.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(billingstandardinvoicedetailedline.FieldID) +// }), +// ). +// Exec(ctx) +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateNewValues() *BillingStandardInvoiceDetailedLineUpsertBulk { + 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(billingstandardinvoicedetailedline.FieldID) + } + if _, exists := b.mutation.Currency(); exists { + s.SetIgnore(billingstandardinvoicedetailedline.FieldCurrency) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(billingstandardinvoicedetailedline.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(billingstandardinvoicedetailedline.FieldCreatedAt) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingStandardInvoiceDetailedLine.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) Ignore() *BillingStandardInvoiceDetailedLineUpsertBulk { + 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 *BillingStandardInvoiceDetailedLineUpsertBulk) DoNothing() *BillingStandardInvoiceDetailedLineUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingStandardInvoiceDetailedLineCreateBulk.OnConflict +// documentation for more info. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) Update(set func(*BillingStandardInvoiceDetailedLineUpsert)) *BillingStandardInvoiceDetailedLineUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingStandardInvoiceDetailedLineUpsert{UpdateSet: update}) + })) + return u +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetServicePeriodStart(v time.Time) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetServicePeriodStart(v) + }) +} + +// UpdateServicePeriodStart sets the "service_period_start" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateServicePeriodStart() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateServicePeriodStart() + }) +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetServicePeriodEnd(v time.Time) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetServicePeriodEnd(v) + }) +} + +// UpdateServicePeriodEnd sets the "service_period_end" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateServicePeriodEnd() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateServicePeriodEnd() + }) +} + +// SetQuantity sets the "quantity" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetQuantity(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetQuantity(v) + }) +} + +// UpdateQuantity sets the "quantity" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateQuantity() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateQuantity() + }) +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetInvoicingAppExternalID(v string) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetInvoicingAppExternalID(v) + }) +} + +// UpdateInvoicingAppExternalID sets the "invoicing_app_external_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateInvoicingAppExternalID() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateInvoicingAppExternalID() + }) +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) ClearInvoicingAppExternalID() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.ClearInvoicingAppExternalID() + }) +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetChildUniqueReferenceID(v string) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetChildUniqueReferenceID(v) + }) +} + +// UpdateChildUniqueReferenceID sets the "child_unique_reference_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateChildUniqueReferenceID() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateChildUniqueReferenceID() + }) +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetPerUnitAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetPerUnitAmount(v) + }) +} + +// UpdatePerUnitAmount sets the "per_unit_amount" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdatePerUnitAmount() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdatePerUnitAmount() + }) +} + +// SetCategory sets the "category" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetCategory(v stddetailedline.Category) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetCategory(v) + }) +} + +// UpdateCategory sets the "category" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateCategory() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateCategory() + }) +} + +// SetPaymentTerm sets the "payment_term" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetPaymentTerm(v productcatalog.PaymentTermType) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetPaymentTerm(v) + }) +} + +// UpdatePaymentTerm sets the "payment_term" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdatePaymentTerm() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdatePaymentTerm() + }) +} + +// SetIndex sets the "index" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetIndex(v int) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetIndex(v) + }) +} + +// AddIndex adds v to the "index" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) AddIndex(v int) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.AddIndex(v) + }) +} + +// UpdateIndex sets the "index" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateIndex() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateIndex() + }) +} + +// ClearIndex clears the value of the "index" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) ClearIndex() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.ClearIndex() + }) +} + +// SetCreditsApplied sets the "credits_applied" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetCreditsApplied(v *creditsapplied.CreditsApplied) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetCreditsApplied(v) + }) +} + +// UpdateCreditsApplied sets the "credits_applied" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateCreditsApplied() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateCreditsApplied() + }) +} + +// ClearCreditsApplied clears the value of the "credits_applied" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) ClearCreditsApplied() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.ClearCreditsApplied() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetAnnotations(v models.Annotations) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateAnnotations() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) ClearAnnotations() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.ClearAnnotations() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetMetadata(v map[string]string) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateMetadata() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) ClearMetadata() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetUpdatedAt(v time.Time) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateUpdatedAt() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetDeletedAt(v time.Time) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateDeletedAt() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) ClearDeletedAt() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetName(v string) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateName() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetDescription(v string) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateDescription() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) ClearDescription() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.ClearDescription() + }) +} + +// SetAmount sets the "amount" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateAmount() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateAmount() + }) +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetTaxesTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetTaxesTotal(v) + }) +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateTaxesTotal() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateTaxesTotal() + }) +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetTaxesInclusiveTotal(v) + }) +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateTaxesInclusiveTotal() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateTaxesInclusiveTotal() + }) +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetTaxesExclusiveTotal(v) + }) +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateTaxesExclusiveTotal() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateTaxesExclusiveTotal() + }) +} + +// SetChargesTotal sets the "charges_total" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetChargesTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetChargesTotal(v) + }) +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateChargesTotal() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateChargesTotal() + }) +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetDiscountsTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetDiscountsTotal(v) + }) +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateDiscountsTotal() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateDiscountsTotal() + }) +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetCreditsTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetCreditsTotal(v) + }) +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateCreditsTotal() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateCreditsTotal() + }) +} + +// SetTotal sets the "total" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetTotal(v) + }) +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateTotal() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateTotal() + }) +} + +// SetInvoiceID sets the "invoice_id" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetInvoiceID(v string) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetInvoiceID(v) + }) +} + +// UpdateInvoiceID sets the "invoice_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateInvoiceID() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateInvoiceID() + }) +} + +// SetParentLineID sets the "parent_line_id" field. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) SetParentLineID(v string) *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.SetParentLineID(v) + }) +} + +// UpdateParentLineID sets the "parent_line_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) UpdateParentLineID() *BillingStandardInvoiceDetailedLineUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineUpsert) { + s.UpdateParentLineID() + }) +} + +// Exec executes the query. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) 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 BillingStandardInvoiceDetailedLineCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingStandardInvoiceDetailedLineCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingStandardInvoiceDetailedLineUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billingstandardinvoicedetailedline_delete.go b/ent/db/billingstandardinvoicedetailedline_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..162ccc5f3de45aaf0c1abcc1446ec2c01236963d --- /dev/null +++ b/ent/db/billingstandardinvoicedetailedline_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/billingstandardinvoicedetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingStandardInvoiceDetailedLineDelete is the builder for deleting a BillingStandardInvoiceDetailedLine entity. +type BillingStandardInvoiceDetailedLineDelete struct { + config + hooks []Hook + mutation *BillingStandardInvoiceDetailedLineMutation +} + +// Where appends a list predicates to the BillingStandardInvoiceDetailedLineDelete builder. +func (_d *BillingStandardInvoiceDetailedLineDelete) Where(ps ...predicate.BillingStandardInvoiceDetailedLine) *BillingStandardInvoiceDetailedLineDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *BillingStandardInvoiceDetailedLineDelete) 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 *BillingStandardInvoiceDetailedLineDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *BillingStandardInvoiceDetailedLineDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(billingstandardinvoicedetailedline.Table, sqlgraph.NewFieldSpec(billingstandardinvoicedetailedline.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 +} + +// BillingStandardInvoiceDetailedLineDeleteOne is the builder for deleting a single BillingStandardInvoiceDetailedLine entity. +type BillingStandardInvoiceDetailedLineDeleteOne struct { + _d *BillingStandardInvoiceDetailedLineDelete +} + +// Where appends a list predicates to the BillingStandardInvoiceDetailedLineDelete builder. +func (_d *BillingStandardInvoiceDetailedLineDeleteOne) Where(ps ...predicate.BillingStandardInvoiceDetailedLine) *BillingStandardInvoiceDetailedLineDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *BillingStandardInvoiceDetailedLineDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{billingstandardinvoicedetailedline.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *BillingStandardInvoiceDetailedLineDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billingstandardinvoicedetailedline_query.go b/ent/db/billingstandardinvoicedetailedline_query.go new file mode 100644 index 0000000000000000000000000000000000000000..3fe5b4291a31c6011d058dc09f14404350280060 --- /dev/null +++ b/ent/db/billingstandardinvoicedetailedline_query.go @@ -0,0 +1,797 @@ +// 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/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingstandardinvoicedetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingstandardinvoicedetailedlineamountdiscount" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingStandardInvoiceDetailedLineQuery is the builder for querying BillingStandardInvoiceDetailedLine entities. +type BillingStandardInvoiceDetailedLineQuery struct { + config + ctx *QueryContext + order []billingstandardinvoicedetailedline.OrderOption + inters []Interceptor + predicates []predicate.BillingStandardInvoiceDetailedLine + withBillingInvoice *BillingInvoiceQuery + withBillingInvoiceLine *BillingInvoiceLineQuery + withAmountDiscounts *BillingStandardInvoiceDetailedLineAmountDiscountQuery + 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 BillingStandardInvoiceDetailedLineQuery builder. +func (_q *BillingStandardInvoiceDetailedLineQuery) Where(ps ...predicate.BillingStandardInvoiceDetailedLine) *BillingStandardInvoiceDetailedLineQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *BillingStandardInvoiceDetailedLineQuery) Limit(limit int) *BillingStandardInvoiceDetailedLineQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *BillingStandardInvoiceDetailedLineQuery) Offset(offset int) *BillingStandardInvoiceDetailedLineQuery { + _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 *BillingStandardInvoiceDetailedLineQuery) Unique(unique bool) *BillingStandardInvoiceDetailedLineQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *BillingStandardInvoiceDetailedLineQuery) Order(o ...billingstandardinvoicedetailedline.OrderOption) *BillingStandardInvoiceDetailedLineQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryBillingInvoice chains the current query on the "billing_invoice" edge. +func (_q *BillingStandardInvoiceDetailedLineQuery) QueryBillingInvoice() *BillingInvoiceQuery { + query := (&BillingInvoiceClient{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(billingstandardinvoicedetailedline.Table, billingstandardinvoicedetailedline.FieldID, selector), + sqlgraph.To(billinginvoice.Table, billinginvoice.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billingstandardinvoicedetailedline.BillingInvoiceTable, billingstandardinvoicedetailedline.BillingInvoiceColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryBillingInvoiceLine chains the current query on the "billing_invoice_line" edge. +func (_q *BillingStandardInvoiceDetailedLineQuery) QueryBillingInvoiceLine() *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{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(billingstandardinvoicedetailedline.Table, billingstandardinvoicedetailedline.FieldID, selector), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billingstandardinvoicedetailedline.BillingInvoiceLineTable, billingstandardinvoicedetailedline.BillingInvoiceLineColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryAmountDiscounts chains the current query on the "amount_discounts" edge. +func (_q *BillingStandardInvoiceDetailedLineQuery) QueryAmountDiscounts() *BillingStandardInvoiceDetailedLineAmountDiscountQuery { + query := (&BillingStandardInvoiceDetailedLineAmountDiscountClient{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(billingstandardinvoicedetailedline.Table, billingstandardinvoicedetailedline.FieldID, selector), + sqlgraph.To(billingstandardinvoicedetailedlineamountdiscount.Table, billingstandardinvoicedetailedlineamountdiscount.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, billingstandardinvoicedetailedline.AmountDiscountsTable, billingstandardinvoicedetailedline.AmountDiscountsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first BillingStandardInvoiceDetailedLine entity from the query. +// Returns a *NotFoundError when no BillingStandardInvoiceDetailedLine was found. +func (_q *BillingStandardInvoiceDetailedLineQuery) First(ctx context.Context) (*BillingStandardInvoiceDetailedLine, 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{billingstandardinvoicedetailedline.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *BillingStandardInvoiceDetailedLineQuery) FirstX(ctx context.Context) *BillingStandardInvoiceDetailedLine { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first BillingStandardInvoiceDetailedLine ID from the query. +// Returns a *NotFoundError when no BillingStandardInvoiceDetailedLine ID was found. +func (_q *BillingStandardInvoiceDetailedLineQuery) 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{billingstandardinvoicedetailedline.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *BillingStandardInvoiceDetailedLineQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single BillingStandardInvoiceDetailedLine entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one BillingStandardInvoiceDetailedLine entity is found. +// Returns a *NotFoundError when no BillingStandardInvoiceDetailedLine entities are found. +func (_q *BillingStandardInvoiceDetailedLineQuery) Only(ctx context.Context) (*BillingStandardInvoiceDetailedLine, 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{billingstandardinvoicedetailedline.Label} + default: + return nil, &NotSingularError{billingstandardinvoicedetailedline.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *BillingStandardInvoiceDetailedLineQuery) OnlyX(ctx context.Context) *BillingStandardInvoiceDetailedLine { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only BillingStandardInvoiceDetailedLine ID in the query. +// Returns a *NotSingularError when more than one BillingStandardInvoiceDetailedLine ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *BillingStandardInvoiceDetailedLineQuery) 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{billingstandardinvoicedetailedline.Label} + default: + err = &NotSingularError{billingstandardinvoicedetailedline.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *BillingStandardInvoiceDetailedLineQuery) 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 BillingStandardInvoiceDetailedLines. +func (_q *BillingStandardInvoiceDetailedLineQuery) All(ctx context.Context) ([]*BillingStandardInvoiceDetailedLine, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*BillingStandardInvoiceDetailedLine, *BillingStandardInvoiceDetailedLineQuery]() + return withInterceptors[[]*BillingStandardInvoiceDetailedLine](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *BillingStandardInvoiceDetailedLineQuery) AllX(ctx context.Context) []*BillingStandardInvoiceDetailedLine { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of BillingStandardInvoiceDetailedLine IDs. +func (_q *BillingStandardInvoiceDetailedLineQuery) 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(billingstandardinvoicedetailedline.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *BillingStandardInvoiceDetailedLineQuery) 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 *BillingStandardInvoiceDetailedLineQuery) 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[*BillingStandardInvoiceDetailedLineQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *BillingStandardInvoiceDetailedLineQuery) 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 *BillingStandardInvoiceDetailedLineQuery) 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 *BillingStandardInvoiceDetailedLineQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the BillingStandardInvoiceDetailedLineQuery 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 *BillingStandardInvoiceDetailedLineQuery) Clone() *BillingStandardInvoiceDetailedLineQuery { + if _q == nil { + return nil + } + return &BillingStandardInvoiceDetailedLineQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]billingstandardinvoicedetailedline.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.BillingStandardInvoiceDetailedLine{}, _q.predicates...), + withBillingInvoice: _q.withBillingInvoice.Clone(), + withBillingInvoiceLine: _q.withBillingInvoiceLine.Clone(), + withAmountDiscounts: _q.withAmountDiscounts.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithBillingInvoice tells the query-builder to eager-load the nodes that are connected to +// the "billing_invoice" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *BillingStandardInvoiceDetailedLineQuery) WithBillingInvoice(opts ...func(*BillingInvoiceQuery)) *BillingStandardInvoiceDetailedLineQuery { + query := (&BillingInvoiceClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingInvoice = query + return _q +} + +// WithBillingInvoiceLine tells the query-builder to eager-load the nodes that are connected to +// the "billing_invoice_line" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *BillingStandardInvoiceDetailedLineQuery) WithBillingInvoiceLine(opts ...func(*BillingInvoiceLineQuery)) *BillingStandardInvoiceDetailedLineQuery { + query := (&BillingInvoiceLineClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingInvoiceLine = query + return _q +} + +// WithAmountDiscounts tells the query-builder to eager-load the nodes that are connected to +// the "amount_discounts" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *BillingStandardInvoiceDetailedLineQuery) WithAmountDiscounts(opts ...func(*BillingStandardInvoiceDetailedLineAmountDiscountQuery)) *BillingStandardInvoiceDetailedLineQuery { + query := (&BillingStandardInvoiceDetailedLineAmountDiscountClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withAmountDiscounts = 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 { +// Currency currencyx.Code `json:"currency,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.BillingStandardInvoiceDetailedLine.Query(). +// GroupBy(billingstandardinvoicedetailedline.FieldCurrency). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *BillingStandardInvoiceDetailedLineQuery) GroupBy(field string, fields ...string) *BillingStandardInvoiceDetailedLineGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &BillingStandardInvoiceDetailedLineGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = billingstandardinvoicedetailedline.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 { +// Currency currencyx.Code `json:"currency,omitempty"` +// } +// +// client.BillingStandardInvoiceDetailedLine.Query(). +// Select(billingstandardinvoicedetailedline.FieldCurrency). +// Scan(ctx, &v) +func (_q *BillingStandardInvoiceDetailedLineQuery) Select(fields ...string) *BillingStandardInvoiceDetailedLineSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &BillingStandardInvoiceDetailedLineSelect{BillingStandardInvoiceDetailedLineQuery: _q} + sbuild.label = billingstandardinvoicedetailedline.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a BillingStandardInvoiceDetailedLineSelect configured with the given aggregations. +func (_q *BillingStandardInvoiceDetailedLineQuery) Aggregate(fns ...AggregateFunc) *BillingStandardInvoiceDetailedLineSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *BillingStandardInvoiceDetailedLineQuery) 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 !billingstandardinvoicedetailedline.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 *BillingStandardInvoiceDetailedLineQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BillingStandardInvoiceDetailedLine, error) { + var ( + nodes = []*BillingStandardInvoiceDetailedLine{} + _spec = _q.querySpec() + loadedTypes = [3]bool{ + _q.withBillingInvoice != nil, + _q.withBillingInvoiceLine != nil, + _q.withAmountDiscounts != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*BillingStandardInvoiceDetailedLine).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &BillingStandardInvoiceDetailedLine{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.withBillingInvoice; query != nil { + if err := _q.loadBillingInvoice(ctx, query, nodes, nil, + func(n *BillingStandardInvoiceDetailedLine, e *BillingInvoice) { n.Edges.BillingInvoice = e }); err != nil { + return nil, err + } + } + if query := _q.withBillingInvoiceLine; query != nil { + if err := _q.loadBillingInvoiceLine(ctx, query, nodes, nil, + func(n *BillingStandardInvoiceDetailedLine, e *BillingInvoiceLine) { n.Edges.BillingInvoiceLine = e }); err != nil { + return nil, err + } + } + if query := _q.withAmountDiscounts; query != nil { + if err := _q.loadAmountDiscounts(ctx, query, nodes, + func(n *BillingStandardInvoiceDetailedLine) { + n.Edges.AmountDiscounts = []*BillingStandardInvoiceDetailedLineAmountDiscount{} + }, + func(n *BillingStandardInvoiceDetailedLine, e *BillingStandardInvoiceDetailedLineAmountDiscount) { + n.Edges.AmountDiscounts = append(n.Edges.AmountDiscounts, e) + }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *BillingStandardInvoiceDetailedLineQuery) loadBillingInvoice(ctx context.Context, query *BillingInvoiceQuery, nodes []*BillingStandardInvoiceDetailedLine, init func(*BillingStandardInvoiceDetailedLine), assign func(*BillingStandardInvoiceDetailedLine, *BillingInvoice)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*BillingStandardInvoiceDetailedLine) + for i := range nodes { + fk := nodes[i].InvoiceID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(billinginvoice.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 "invoice_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *BillingStandardInvoiceDetailedLineQuery) loadBillingInvoiceLine(ctx context.Context, query *BillingInvoiceLineQuery, nodes []*BillingStandardInvoiceDetailedLine, init func(*BillingStandardInvoiceDetailedLine), assign func(*BillingStandardInvoiceDetailedLine, *BillingInvoiceLine)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*BillingStandardInvoiceDetailedLine) + for i := range nodes { + fk := nodes[i].ParentLineID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(billinginvoiceline.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 "parent_line_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *BillingStandardInvoiceDetailedLineQuery) loadAmountDiscounts(ctx context.Context, query *BillingStandardInvoiceDetailedLineAmountDiscountQuery, nodes []*BillingStandardInvoiceDetailedLine, init func(*BillingStandardInvoiceDetailedLine), assign func(*BillingStandardInvoiceDetailedLine, *BillingStandardInvoiceDetailedLineAmountDiscount)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*BillingStandardInvoiceDetailedLine) + 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(billingstandardinvoicedetailedlineamountdiscount.FieldLineID) + } + query.Where(predicate.BillingStandardInvoiceDetailedLineAmountDiscount(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(billingstandardinvoicedetailedline.AmountDiscountsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.LineID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "line_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *BillingStandardInvoiceDetailedLineQuery) 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 *BillingStandardInvoiceDetailedLineQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(billingstandardinvoicedetailedline.Table, billingstandardinvoicedetailedline.Columns, sqlgraph.NewFieldSpec(billingstandardinvoicedetailedline.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, billingstandardinvoicedetailedline.FieldID) + for i := range fields { + if fields[i] != billingstandardinvoicedetailedline.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withBillingInvoice != nil { + _spec.Node.AddColumnOnce(billingstandardinvoicedetailedline.FieldInvoiceID) + } + if _q.withBillingInvoiceLine != nil { + _spec.Node.AddColumnOnce(billingstandardinvoicedetailedline.FieldParentLineID) + } + } + 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 *BillingStandardInvoiceDetailedLineQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(billingstandardinvoicedetailedline.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = billingstandardinvoicedetailedline.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 *BillingStandardInvoiceDetailedLineQuery) ForUpdate(opts ...sql.LockOption) *BillingStandardInvoiceDetailedLineQuery { + 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 *BillingStandardInvoiceDetailedLineQuery) ForShare(opts ...sql.LockOption) *BillingStandardInvoiceDetailedLineQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// BillingStandardInvoiceDetailedLineGroupBy is the group-by builder for BillingStandardInvoiceDetailedLine entities. +type BillingStandardInvoiceDetailedLineGroupBy struct { + selector + build *BillingStandardInvoiceDetailedLineQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *BillingStandardInvoiceDetailedLineGroupBy) Aggregate(fns ...AggregateFunc) *BillingStandardInvoiceDetailedLineGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *BillingStandardInvoiceDetailedLineGroupBy) 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[*BillingStandardInvoiceDetailedLineQuery, *BillingStandardInvoiceDetailedLineGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *BillingStandardInvoiceDetailedLineGroupBy) sqlScan(ctx context.Context, root *BillingStandardInvoiceDetailedLineQuery, 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) +} + +// BillingStandardInvoiceDetailedLineSelect is the builder for selecting fields of BillingStandardInvoiceDetailedLine entities. +type BillingStandardInvoiceDetailedLineSelect struct { + *BillingStandardInvoiceDetailedLineQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *BillingStandardInvoiceDetailedLineSelect) Aggregate(fns ...AggregateFunc) *BillingStandardInvoiceDetailedLineSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *BillingStandardInvoiceDetailedLineSelect) 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[*BillingStandardInvoiceDetailedLineQuery, *BillingStandardInvoiceDetailedLineSelect](ctx, _s.BillingStandardInvoiceDetailedLineQuery, _s, _s.inters, v) +} + +func (_s *BillingStandardInvoiceDetailedLineSelect) sqlScan(ctx context.Context, root *BillingStandardInvoiceDetailedLineQuery, 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/ent/db/billingstandardinvoicedetailedline_update.go b/ent/db/billingstandardinvoicedetailedline_update.go new file mode 100644 index 0000000000000000000000000000000000000000..0ad1f8cd9b561c42381dc72ec6e30963c70bb8b5 --- /dev/null +++ b/ent/db/billingstandardinvoicedetailedline_update.go @@ -0,0 +1,1570 @@ +// 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/models/creditsapplied" + "github.com/openmeterio/openmeter/openmeter/billing/models/stddetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingstandardinvoicedetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingstandardinvoicedetailedlineamountdiscount" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/models" +) + +// BillingStandardInvoiceDetailedLineUpdate is the builder for updating BillingStandardInvoiceDetailedLine entities. +type BillingStandardInvoiceDetailedLineUpdate struct { + config + hooks []Hook + mutation *BillingStandardInvoiceDetailedLineMutation +} + +// Where appends a list predicates to the BillingStandardInvoiceDetailedLineUpdate builder. +func (_u *BillingStandardInvoiceDetailedLineUpdate) Where(ps ...predicate.BillingStandardInvoiceDetailedLine) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetServicePeriodStart(v time.Time) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetServicePeriodStart(v) + return _u +} + +// SetNillableServicePeriodStart sets the "service_period_start" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillableServicePeriodStart(v *time.Time) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetServicePeriodStart(*v) + } + return _u +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetServicePeriodEnd(v time.Time) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetServicePeriodEnd(v) + return _u +} + +// SetNillableServicePeriodEnd sets the "service_period_end" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillableServicePeriodEnd(v *time.Time) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetServicePeriodEnd(*v) + } + return _u +} + +// SetQuantity sets the "quantity" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetQuantity(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetQuantity(v) + return _u +} + +// SetNillableQuantity sets the "quantity" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillableQuantity(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetQuantity(*v) + } + return _u +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetInvoicingAppExternalID(v string) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetInvoicingAppExternalID(v) + return _u +} + +// SetNillableInvoicingAppExternalID sets the "invoicing_app_external_id" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillableInvoicingAppExternalID(v *string) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetInvoicingAppExternalID(*v) + } + return _u +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) ClearInvoicingAppExternalID() *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.ClearInvoicingAppExternalID() + return _u +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetChildUniqueReferenceID(v string) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetChildUniqueReferenceID(v) + return _u +} + +// SetNillableChildUniqueReferenceID sets the "child_unique_reference_id" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillableChildUniqueReferenceID(v *string) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetChildUniqueReferenceID(*v) + } + return _u +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetPerUnitAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetPerUnitAmount(v) + return _u +} + +// SetNillablePerUnitAmount sets the "per_unit_amount" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillablePerUnitAmount(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetPerUnitAmount(*v) + } + return _u +} + +// SetCategory sets the "category" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetCategory(v stddetailedline.Category) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetCategory(v) + return _u +} + +// SetNillableCategory sets the "category" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillableCategory(v *stddetailedline.Category) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetCategory(*v) + } + return _u +} + +// SetPaymentTerm sets the "payment_term" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetPaymentTerm(v productcatalog.PaymentTermType) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetPaymentTerm(v) + return _u +} + +// SetNillablePaymentTerm sets the "payment_term" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillablePaymentTerm(v *productcatalog.PaymentTermType) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetPaymentTerm(*v) + } + return _u +} + +// SetIndex sets the "index" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetIndex(v int) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.ResetIndex() + _u.mutation.SetIndex(v) + return _u +} + +// SetNillableIndex sets the "index" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillableIndex(v *int) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetIndex(*v) + } + return _u +} + +// AddIndex adds value to the "index" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) AddIndex(v int) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.AddIndex(v) + return _u +} + +// ClearIndex clears the value of the "index" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) ClearIndex() *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.ClearIndex() + return _u +} + +// SetCreditsApplied sets the "credits_applied" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetCreditsApplied(v *creditsapplied.CreditsApplied) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetCreditsApplied(v) + return _u +} + +// ClearCreditsApplied clears the value of the "credits_applied" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) ClearCreditsApplied() *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.ClearCreditsApplied() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetAnnotations(v models.Annotations) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) ClearAnnotations() *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetMetadata(v map[string]string) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) ClearMetadata() *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetUpdatedAt(v time.Time) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetDeletedAt(v time.Time) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillableDeletedAt(v *time.Time) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) ClearDeletedAt() *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetName(v string) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillableName(v *string) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetDescription(v string) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillableDescription(v *string) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) ClearDescription() *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.ClearDescription() + return _u +} + +// SetAmount sets the "amount" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillableAmount(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetTaxesTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetTaxesTotal(v) + return _u +} + +// SetNillableTaxesTotal sets the "taxes_total" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillableTaxesTotal(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetTaxesTotal(*v) + } + return _u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetTaxesInclusiveTotal(v) + return _u +} + +// SetNillableTaxesInclusiveTotal sets the "taxes_inclusive_total" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillableTaxesInclusiveTotal(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetTaxesInclusiveTotal(*v) + } + return _u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetTaxesExclusiveTotal(v) + return _u +} + +// SetNillableTaxesExclusiveTotal sets the "taxes_exclusive_total" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillableTaxesExclusiveTotal(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetTaxesExclusiveTotal(*v) + } + return _u +} + +// SetChargesTotal sets the "charges_total" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetChargesTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetChargesTotal(v) + return _u +} + +// SetNillableChargesTotal sets the "charges_total" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillableChargesTotal(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetChargesTotal(*v) + } + return _u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetDiscountsTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetDiscountsTotal(v) + return _u +} + +// SetNillableDiscountsTotal sets the "discounts_total" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillableDiscountsTotal(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetDiscountsTotal(*v) + } + return _u +} + +// SetCreditsTotal sets the "credits_total" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetCreditsTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetCreditsTotal(v) + return _u +} + +// SetNillableCreditsTotal sets the "credits_total" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillableCreditsTotal(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetCreditsTotal(*v) + } + return _u +} + +// SetTotal sets the "total" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetTotal(v) + return _u +} + +// SetNillableTotal sets the "total" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillableTotal(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetTotal(*v) + } + return _u +} + +// SetInvoiceID sets the "invoice_id" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetInvoiceID(v string) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetInvoiceID(v) + return _u +} + +// SetNillableInvoiceID sets the "invoice_id" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillableInvoiceID(v *string) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetInvoiceID(*v) + } + return _u +} + +// SetParentLineID sets the "parent_line_id" field. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetParentLineID(v string) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetParentLineID(v) + return _u +} + +// SetNillableParentLineID sets the "parent_line_id" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetNillableParentLineID(v *string) *BillingStandardInvoiceDetailedLineUpdate { + if v != nil { + _u.SetParentLineID(*v) + } + return _u +} + +// SetBillingInvoiceID sets the "billing_invoice" edge to the BillingInvoice entity by ID. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetBillingInvoiceID(id string) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetBillingInvoiceID(id) + return _u +} + +// SetBillingInvoice sets the "billing_invoice" edge to the BillingInvoice entity. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetBillingInvoice(v *BillingInvoice) *BillingStandardInvoiceDetailedLineUpdate { + return _u.SetBillingInvoiceID(v.ID) +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetBillingInvoiceLineID(id string) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.SetBillingInvoiceLineID(id) + return _u +} + +// SetBillingInvoiceLine sets the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *BillingStandardInvoiceDetailedLineUpdate) SetBillingInvoiceLine(v *BillingInvoiceLine) *BillingStandardInvoiceDetailedLineUpdate { + return _u.SetBillingInvoiceLineID(v.ID) +} + +// AddAmountDiscountIDs adds the "amount_discounts" edge to the BillingStandardInvoiceDetailedLineAmountDiscount entity by IDs. +func (_u *BillingStandardInvoiceDetailedLineUpdate) AddAmountDiscountIDs(ids ...string) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.AddAmountDiscountIDs(ids...) + return _u +} + +// AddAmountDiscounts adds the "amount_discounts" edges to the BillingStandardInvoiceDetailedLineAmountDiscount entity. +func (_u *BillingStandardInvoiceDetailedLineUpdate) AddAmountDiscounts(v ...*BillingStandardInvoiceDetailedLineAmountDiscount) *BillingStandardInvoiceDetailedLineUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddAmountDiscountIDs(ids...) +} + +// Mutation returns the BillingStandardInvoiceDetailedLineMutation object of the builder. +func (_u *BillingStandardInvoiceDetailedLineUpdate) Mutation() *BillingStandardInvoiceDetailedLineMutation { + return _u.mutation +} + +// ClearBillingInvoice clears the "billing_invoice" edge to the BillingInvoice entity. +func (_u *BillingStandardInvoiceDetailedLineUpdate) ClearBillingInvoice() *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.ClearBillingInvoice() + return _u +} + +// ClearBillingInvoiceLine clears the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *BillingStandardInvoiceDetailedLineUpdate) ClearBillingInvoiceLine() *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.ClearBillingInvoiceLine() + return _u +} + +// ClearAmountDiscounts clears all "amount_discounts" edges to the BillingStandardInvoiceDetailedLineAmountDiscount entity. +func (_u *BillingStandardInvoiceDetailedLineUpdate) ClearAmountDiscounts() *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.ClearAmountDiscounts() + return _u +} + +// RemoveAmountDiscountIDs removes the "amount_discounts" edge to BillingStandardInvoiceDetailedLineAmountDiscount entities by IDs. +func (_u *BillingStandardInvoiceDetailedLineUpdate) RemoveAmountDiscountIDs(ids ...string) *BillingStandardInvoiceDetailedLineUpdate { + _u.mutation.RemoveAmountDiscountIDs(ids...) + return _u +} + +// RemoveAmountDiscounts removes "amount_discounts" edges to BillingStandardInvoiceDetailedLineAmountDiscount entities. +func (_u *BillingStandardInvoiceDetailedLineUpdate) RemoveAmountDiscounts(v ...*BillingStandardInvoiceDetailedLineAmountDiscount) *BillingStandardInvoiceDetailedLineUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveAmountDiscountIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *BillingStandardInvoiceDetailedLineUpdate) 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 *BillingStandardInvoiceDetailedLineUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *BillingStandardInvoiceDetailedLineUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingStandardInvoiceDetailedLineUpdate) 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 *BillingStandardInvoiceDetailedLineUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := billingstandardinvoicedetailedline.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *BillingStandardInvoiceDetailedLineUpdate) check() error { + if v, ok := _u.mutation.ChildUniqueReferenceID(); ok { + if err := billingstandardinvoicedetailedline.ChildUniqueReferenceIDValidator(v); err != nil { + return &ValidationError{Name: "child_unique_reference_id", err: fmt.Errorf(`db: validator failed for field "BillingStandardInvoiceDetailedLine.child_unique_reference_id": %w`, err)} + } + } + if v, ok := _u.mutation.Category(); ok { + if err := billingstandardinvoicedetailedline.CategoryValidator(v); err != nil { + return &ValidationError{Name: "category", err: fmt.Errorf(`db: validator failed for field "BillingStandardInvoiceDetailedLine.category": %w`, err)} + } + } + if v, ok := _u.mutation.PaymentTerm(); ok { + if err := billingstandardinvoicedetailedline.PaymentTermValidator(v); err != nil { + return &ValidationError{Name: "payment_term", err: fmt.Errorf(`db: validator failed for field "BillingStandardInvoiceDetailedLine.payment_term": %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 "BillingStandardInvoiceDetailedLine.credits_applied": %w`, err)} + } + } + if _u.mutation.BillingInvoiceCleared() && len(_u.mutation.BillingInvoiceIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "BillingStandardInvoiceDetailedLine.billing_invoice"`) + } + if _u.mutation.BillingInvoiceLineCleared() && len(_u.mutation.BillingInvoiceLineIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "BillingStandardInvoiceDetailedLine.billing_invoice_line"`) + } + return nil +} + +func (_u *BillingStandardInvoiceDetailedLineUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(billingstandardinvoicedetailedline.Table, billingstandardinvoicedetailedline.Columns, sqlgraph.NewFieldSpec(billingstandardinvoicedetailedline.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.ServicePeriodStart(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldServicePeriodStart, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodEnd(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldServicePeriodEnd, field.TypeTime, value) + } + if value, ok := _u.mutation.Quantity(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldQuantity, field.TypeOther, value) + } + if value, ok := _u.mutation.InvoicingAppExternalID(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldInvoicingAppExternalID, field.TypeString, value) + } + if _u.mutation.InvoicingAppExternalIDCleared() { + _spec.ClearField(billingstandardinvoicedetailedline.FieldInvoicingAppExternalID, field.TypeString) + } + if value, ok := _u.mutation.ChildUniqueReferenceID(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldChildUniqueReferenceID, field.TypeString, value) + } + if value, ok := _u.mutation.PerUnitAmount(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldPerUnitAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.Category(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldCategory, field.TypeEnum, value) + } + if value, ok := _u.mutation.PaymentTerm(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldPaymentTerm, field.TypeEnum, value) + } + if value, ok := _u.mutation.Index(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldIndex, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedIndex(); ok { + _spec.AddField(billingstandardinvoicedetailedline.FieldIndex, field.TypeInt, value) + } + if _u.mutation.IndexCleared() { + _spec.ClearField(billingstandardinvoicedetailedline.FieldIndex, field.TypeInt) + } + if value, ok := _u.mutation.CreditsApplied(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldCreditsApplied, field.TypeJSON, value) + } + if _u.mutation.CreditsAppliedCleared() { + _spec.ClearField(billingstandardinvoicedetailedline.FieldCreditsApplied, field.TypeJSON) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(billingstandardinvoicedetailedline.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(billingstandardinvoicedetailedline.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(billingstandardinvoicedetailedline.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(billingstandardinvoicedetailedline.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesTotal(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldTaxesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldTaxesInclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldTaxesExclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.ChargesTotal(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldChargesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.DiscountsTotal(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldDiscountsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.CreditsTotal(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldCreditsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.Total(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldTotal, field.TypeOther, value) + } + if _u.mutation.BillingInvoiceCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingstandardinvoicedetailedline.BillingInvoiceTable, + Columns: []string{billingstandardinvoicedetailedline.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingInvoiceIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingstandardinvoicedetailedline.BillingInvoiceTable, + Columns: []string{billingstandardinvoicedetailedline.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.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.BillingInvoiceLineCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingstandardinvoicedetailedline.BillingInvoiceLineTable, + Columns: []string{billingstandardinvoicedetailedline.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingInvoiceLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingstandardinvoicedetailedline.BillingInvoiceLineTable, + Columns: []string{billingstandardinvoicedetailedline.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.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.AmountDiscountsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingstandardinvoicedetailedline.AmountDiscountsTable, + Columns: []string{billingstandardinvoicedetailedline.AmountDiscountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingstandardinvoicedetailedlineamountdiscount.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedAmountDiscountsIDs(); len(nodes) > 0 && !_u.mutation.AmountDiscountsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingstandardinvoicedetailedline.AmountDiscountsTable, + Columns: []string{billingstandardinvoicedetailedline.AmountDiscountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingstandardinvoicedetailedlineamountdiscount.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.AmountDiscountsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingstandardinvoicedetailedline.AmountDiscountsTable, + Columns: []string{billingstandardinvoicedetailedline.AmountDiscountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingstandardinvoicedetailedlineamountdiscount.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{billingstandardinvoicedetailedline.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// BillingStandardInvoiceDetailedLineUpdateOne is the builder for updating a single BillingStandardInvoiceDetailedLine entity. +type BillingStandardInvoiceDetailedLineUpdateOne struct { + config + fields []string + hooks []Hook + mutation *BillingStandardInvoiceDetailedLineMutation +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetServicePeriodStart(v time.Time) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetServicePeriodStart(v) + return _u +} + +// SetNillableServicePeriodStart sets the "service_period_start" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillableServicePeriodStart(v *time.Time) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetServicePeriodStart(*v) + } + return _u +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetServicePeriodEnd(v time.Time) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetServicePeriodEnd(v) + return _u +} + +// SetNillableServicePeriodEnd sets the "service_period_end" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillableServicePeriodEnd(v *time.Time) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetServicePeriodEnd(*v) + } + return _u +} + +// SetQuantity sets the "quantity" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetQuantity(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetQuantity(v) + return _u +} + +// SetNillableQuantity sets the "quantity" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillableQuantity(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetQuantity(*v) + } + return _u +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetInvoicingAppExternalID(v string) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetInvoicingAppExternalID(v) + return _u +} + +// SetNillableInvoicingAppExternalID sets the "invoicing_app_external_id" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillableInvoicingAppExternalID(v *string) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetInvoicingAppExternalID(*v) + } + return _u +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) ClearInvoicingAppExternalID() *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.ClearInvoicingAppExternalID() + return _u +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetChildUniqueReferenceID(v string) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetChildUniqueReferenceID(v) + return _u +} + +// SetNillableChildUniqueReferenceID sets the "child_unique_reference_id" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillableChildUniqueReferenceID(v *string) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetChildUniqueReferenceID(*v) + } + return _u +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetPerUnitAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetPerUnitAmount(v) + return _u +} + +// SetNillablePerUnitAmount sets the "per_unit_amount" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillablePerUnitAmount(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetPerUnitAmount(*v) + } + return _u +} + +// SetCategory sets the "category" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetCategory(v stddetailedline.Category) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetCategory(v) + return _u +} + +// SetNillableCategory sets the "category" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillableCategory(v *stddetailedline.Category) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetCategory(*v) + } + return _u +} + +// SetPaymentTerm sets the "payment_term" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetPaymentTerm(v productcatalog.PaymentTermType) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetPaymentTerm(v) + return _u +} + +// SetNillablePaymentTerm sets the "payment_term" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillablePaymentTerm(v *productcatalog.PaymentTermType) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetPaymentTerm(*v) + } + return _u +} + +// SetIndex sets the "index" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetIndex(v int) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.ResetIndex() + _u.mutation.SetIndex(v) + return _u +} + +// SetNillableIndex sets the "index" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillableIndex(v *int) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetIndex(*v) + } + return _u +} + +// AddIndex adds value to the "index" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) AddIndex(v int) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.AddIndex(v) + return _u +} + +// ClearIndex clears the value of the "index" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) ClearIndex() *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.ClearIndex() + return _u +} + +// SetCreditsApplied sets the "credits_applied" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetCreditsApplied(v *creditsapplied.CreditsApplied) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetCreditsApplied(v) + return _u +} + +// ClearCreditsApplied clears the value of the "credits_applied" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) ClearCreditsApplied() *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.ClearCreditsApplied() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetAnnotations(v models.Annotations) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) ClearAnnotations() *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetMetadata(v map[string]string) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) ClearMetadata() *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetUpdatedAt(v time.Time) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetDeletedAt(v time.Time) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillableDeletedAt(v *time.Time) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) ClearDeletedAt() *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetName(v string) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillableName(v *string) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetDescription(v string) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillableDescription(v *string) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) ClearDescription() *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.ClearDescription() + return _u +} + +// SetAmount sets the "amount" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillableAmount(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetTaxesTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetTaxesTotal(v) + return _u +} + +// SetNillableTaxesTotal sets the "taxes_total" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillableTaxesTotal(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetTaxesTotal(*v) + } + return _u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetTaxesInclusiveTotal(v) + return _u +} + +// SetNillableTaxesInclusiveTotal sets the "taxes_inclusive_total" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillableTaxesInclusiveTotal(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetTaxesInclusiveTotal(*v) + } + return _u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetTaxesExclusiveTotal(v) + return _u +} + +// SetNillableTaxesExclusiveTotal sets the "taxes_exclusive_total" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillableTaxesExclusiveTotal(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetTaxesExclusiveTotal(*v) + } + return _u +} + +// SetChargesTotal sets the "charges_total" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetChargesTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetChargesTotal(v) + return _u +} + +// SetNillableChargesTotal sets the "charges_total" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillableChargesTotal(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetChargesTotal(*v) + } + return _u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetDiscountsTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetDiscountsTotal(v) + return _u +} + +// SetNillableDiscountsTotal sets the "discounts_total" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillableDiscountsTotal(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetDiscountsTotal(*v) + } + return _u +} + +// SetCreditsTotal sets the "credits_total" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetCreditsTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetCreditsTotal(v) + return _u +} + +// SetNillableCreditsTotal sets the "credits_total" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillableCreditsTotal(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetCreditsTotal(*v) + } + return _u +} + +// SetTotal sets the "total" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetTotal(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetTotal(v) + return _u +} + +// SetNillableTotal sets the "total" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillableTotal(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetTotal(*v) + } + return _u +} + +// SetInvoiceID sets the "invoice_id" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetInvoiceID(v string) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetInvoiceID(v) + return _u +} + +// SetNillableInvoiceID sets the "invoice_id" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillableInvoiceID(v *string) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetInvoiceID(*v) + } + return _u +} + +// SetParentLineID sets the "parent_line_id" field. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetParentLineID(v string) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetParentLineID(v) + return _u +} + +// SetNillableParentLineID sets the "parent_line_id" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetNillableParentLineID(v *string) *BillingStandardInvoiceDetailedLineUpdateOne { + if v != nil { + _u.SetParentLineID(*v) + } + return _u +} + +// SetBillingInvoiceID sets the "billing_invoice" edge to the BillingInvoice entity by ID. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetBillingInvoiceID(id string) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetBillingInvoiceID(id) + return _u +} + +// SetBillingInvoice sets the "billing_invoice" edge to the BillingInvoice entity. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetBillingInvoice(v *BillingInvoice) *BillingStandardInvoiceDetailedLineUpdateOne { + return _u.SetBillingInvoiceID(v.ID) +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetBillingInvoiceLineID(id string) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.SetBillingInvoiceLineID(id) + return _u +} + +// SetBillingInvoiceLine sets the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SetBillingInvoiceLine(v *BillingInvoiceLine) *BillingStandardInvoiceDetailedLineUpdateOne { + return _u.SetBillingInvoiceLineID(v.ID) +} + +// AddAmountDiscountIDs adds the "amount_discounts" edge to the BillingStandardInvoiceDetailedLineAmountDiscount entity by IDs. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) AddAmountDiscountIDs(ids ...string) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.AddAmountDiscountIDs(ids...) + return _u +} + +// AddAmountDiscounts adds the "amount_discounts" edges to the BillingStandardInvoiceDetailedLineAmountDiscount entity. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) AddAmountDiscounts(v ...*BillingStandardInvoiceDetailedLineAmountDiscount) *BillingStandardInvoiceDetailedLineUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddAmountDiscountIDs(ids...) +} + +// Mutation returns the BillingStandardInvoiceDetailedLineMutation object of the builder. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) Mutation() *BillingStandardInvoiceDetailedLineMutation { + return _u.mutation +} + +// ClearBillingInvoice clears the "billing_invoice" edge to the BillingInvoice entity. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) ClearBillingInvoice() *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.ClearBillingInvoice() + return _u +} + +// ClearBillingInvoiceLine clears the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) ClearBillingInvoiceLine() *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.ClearBillingInvoiceLine() + return _u +} + +// ClearAmountDiscounts clears all "amount_discounts" edges to the BillingStandardInvoiceDetailedLineAmountDiscount entity. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) ClearAmountDiscounts() *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.ClearAmountDiscounts() + return _u +} + +// RemoveAmountDiscountIDs removes the "amount_discounts" edge to BillingStandardInvoiceDetailedLineAmountDiscount entities by IDs. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) RemoveAmountDiscountIDs(ids ...string) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.mutation.RemoveAmountDiscountIDs(ids...) + return _u +} + +// RemoveAmountDiscounts removes "amount_discounts" edges to BillingStandardInvoiceDetailedLineAmountDiscount entities. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) RemoveAmountDiscounts(v ...*BillingStandardInvoiceDetailedLineAmountDiscount) *BillingStandardInvoiceDetailedLineUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveAmountDiscountIDs(ids...) +} + +// Where appends a list predicates to the BillingStandardInvoiceDetailedLineUpdate builder. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) Where(ps ...predicate.BillingStandardInvoiceDetailedLine) *BillingStandardInvoiceDetailedLineUpdateOne { + _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 *BillingStandardInvoiceDetailedLineUpdateOne) Select(field string, fields ...string) *BillingStandardInvoiceDetailedLineUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated BillingStandardInvoiceDetailedLine entity. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) Save(ctx context.Context) (*BillingStandardInvoiceDetailedLine, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) SaveX(ctx context.Context) *BillingStandardInvoiceDetailedLine { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) 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 *BillingStandardInvoiceDetailedLineUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := billingstandardinvoicedetailedline.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) check() error { + if v, ok := _u.mutation.ChildUniqueReferenceID(); ok { + if err := billingstandardinvoicedetailedline.ChildUniqueReferenceIDValidator(v); err != nil { + return &ValidationError{Name: "child_unique_reference_id", err: fmt.Errorf(`db: validator failed for field "BillingStandardInvoiceDetailedLine.child_unique_reference_id": %w`, err)} + } + } + if v, ok := _u.mutation.Category(); ok { + if err := billingstandardinvoicedetailedline.CategoryValidator(v); err != nil { + return &ValidationError{Name: "category", err: fmt.Errorf(`db: validator failed for field "BillingStandardInvoiceDetailedLine.category": %w`, err)} + } + } + if v, ok := _u.mutation.PaymentTerm(); ok { + if err := billingstandardinvoicedetailedline.PaymentTermValidator(v); err != nil { + return &ValidationError{Name: "payment_term", err: fmt.Errorf(`db: validator failed for field "BillingStandardInvoiceDetailedLine.payment_term": %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 "BillingStandardInvoiceDetailedLine.credits_applied": %w`, err)} + } + } + if _u.mutation.BillingInvoiceCleared() && len(_u.mutation.BillingInvoiceIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "BillingStandardInvoiceDetailedLine.billing_invoice"`) + } + if _u.mutation.BillingInvoiceLineCleared() && len(_u.mutation.BillingInvoiceLineIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "BillingStandardInvoiceDetailedLine.billing_invoice_line"`) + } + return nil +} + +func (_u *BillingStandardInvoiceDetailedLineUpdateOne) sqlSave(ctx context.Context) (_node *BillingStandardInvoiceDetailedLine, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(billingstandardinvoicedetailedline.Table, billingstandardinvoicedetailedline.Columns, sqlgraph.NewFieldSpec(billingstandardinvoicedetailedline.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "BillingStandardInvoiceDetailedLine.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, billingstandardinvoicedetailedline.FieldID) + for _, f := range fields { + if !billingstandardinvoicedetailedline.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != billingstandardinvoicedetailedline.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.ServicePeriodStart(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldServicePeriodStart, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodEnd(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldServicePeriodEnd, field.TypeTime, value) + } + if value, ok := _u.mutation.Quantity(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldQuantity, field.TypeOther, value) + } + if value, ok := _u.mutation.InvoicingAppExternalID(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldInvoicingAppExternalID, field.TypeString, value) + } + if _u.mutation.InvoicingAppExternalIDCleared() { + _spec.ClearField(billingstandardinvoicedetailedline.FieldInvoicingAppExternalID, field.TypeString) + } + if value, ok := _u.mutation.ChildUniqueReferenceID(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldChildUniqueReferenceID, field.TypeString, value) + } + if value, ok := _u.mutation.PerUnitAmount(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldPerUnitAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.Category(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldCategory, field.TypeEnum, value) + } + if value, ok := _u.mutation.PaymentTerm(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldPaymentTerm, field.TypeEnum, value) + } + if value, ok := _u.mutation.Index(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldIndex, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedIndex(); ok { + _spec.AddField(billingstandardinvoicedetailedline.FieldIndex, field.TypeInt, value) + } + if _u.mutation.IndexCleared() { + _spec.ClearField(billingstandardinvoicedetailedline.FieldIndex, field.TypeInt) + } + if value, ok := _u.mutation.CreditsApplied(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldCreditsApplied, field.TypeJSON, value) + } + if _u.mutation.CreditsAppliedCleared() { + _spec.ClearField(billingstandardinvoicedetailedline.FieldCreditsApplied, field.TypeJSON) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(billingstandardinvoicedetailedline.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(billingstandardinvoicedetailedline.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(billingstandardinvoicedetailedline.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(billingstandardinvoicedetailedline.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesTotal(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldTaxesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldTaxesInclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldTaxesExclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.ChargesTotal(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldChargesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.DiscountsTotal(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldDiscountsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.CreditsTotal(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldCreditsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.Total(); ok { + _spec.SetField(billingstandardinvoicedetailedline.FieldTotal, field.TypeOther, value) + } + if _u.mutation.BillingInvoiceCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingstandardinvoicedetailedline.BillingInvoiceTable, + Columns: []string{billingstandardinvoicedetailedline.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingInvoiceIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingstandardinvoicedetailedline.BillingInvoiceTable, + Columns: []string{billingstandardinvoicedetailedline.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.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.BillingInvoiceLineCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingstandardinvoicedetailedline.BillingInvoiceLineTable, + Columns: []string{billingstandardinvoicedetailedline.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingInvoiceLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingstandardinvoicedetailedline.BillingInvoiceLineTable, + Columns: []string{billingstandardinvoicedetailedline.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.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.AmountDiscountsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingstandardinvoicedetailedline.AmountDiscountsTable, + Columns: []string{billingstandardinvoicedetailedline.AmountDiscountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingstandardinvoicedetailedlineamountdiscount.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedAmountDiscountsIDs(); len(nodes) > 0 && !_u.mutation.AmountDiscountsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingstandardinvoicedetailedline.AmountDiscountsTable, + Columns: []string{billingstandardinvoicedetailedline.AmountDiscountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingstandardinvoicedetailedlineamountdiscount.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.AmountDiscountsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: billingstandardinvoicedetailedline.AmountDiscountsTable, + Columns: []string{billingstandardinvoicedetailedline.AmountDiscountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingstandardinvoicedetailedlineamountdiscount.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &BillingStandardInvoiceDetailedLine{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{billingstandardinvoicedetailedline.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/ent/db/billingstandardinvoicedetailedlineamountdiscount.go b/ent/db/billingstandardinvoicedetailedlineamountdiscount.go new file mode 100644 index 0000000000000000000000000000000000000000..e1ef0fd419abd45ace99c6db12e3b193fcf122ab --- /dev/null +++ b/ent/db/billingstandardinvoicedetailedlineamountdiscount.go @@ -0,0 +1,279 @@ +// 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" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingstandardinvoicedetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingstandardinvoicedetailedlineamountdiscount" +) + +// BillingStandardInvoiceDetailedLineAmountDiscount is the model entity for the BillingStandardInvoiceDetailedLineAmountDiscount schema. +type BillingStandardInvoiceDetailedLineAmountDiscount 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"` + // InvoicingAppExternalID holds the value of the "invoicing_app_external_id" field. + InvoicingAppExternalID *string `json:"invoicing_app_external_id,omitempty"` + // LineID holds the value of the "line_id" field. + LineID string `json:"line_id,omitempty"` + // ChildUniqueReferenceID holds the value of the "child_unique_reference_id" field. + ChildUniqueReferenceID *string `json:"child_unique_reference_id,omitempty"` + // Description holds the value of the "description" field. + Description *string `json:"description,omitempty"` + // Reason holds the value of the "reason" field. + Reason billing.DiscountReasonType `json:"reason,omitempty"` + // Amount holds the value of the "amount" field. + Amount alpacadecimal.Decimal `json:"amount,omitempty"` + // RoundingAmount holds the value of the "rounding_amount" field. + RoundingAmount *alpacadecimal.Decimal `json:"rounding_amount,omitempty"` + // SourceDiscount holds the value of the "source_discount" field. + SourceDiscount *billing.DiscountReason `json:"source_discount,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the BillingStandardInvoiceDetailedLineAmountDiscountQuery when eager-loading is set. + Edges BillingStandardInvoiceDetailedLineAmountDiscountEdges `json:"edges"` + selectValues sql.SelectValues +} + +// BillingStandardInvoiceDetailedLineAmountDiscountEdges holds the relations/edges for other nodes in the graph. +type BillingStandardInvoiceDetailedLineAmountDiscountEdges struct { + // DetailedLine holds the value of the detailed_line edge. + DetailedLine *BillingStandardInvoiceDetailedLine `json:"detailed_line,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// DetailedLineOrErr returns the DetailedLine value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e BillingStandardInvoiceDetailedLineAmountDiscountEdges) DetailedLineOrErr() (*BillingStandardInvoiceDetailedLine, error) { + if e.DetailedLine != nil { + return e.DetailedLine, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: billingstandardinvoicedetailedline.Label} + } + return nil, &NotLoadedError{edge: "detailed_line"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*BillingStandardInvoiceDetailedLineAmountDiscount) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount: + values[i] = &sql.NullScanner{S: new(alpacadecimal.Decimal)} + case billingstandardinvoicedetailedlineamountdiscount.FieldAmount: + values[i] = new(alpacadecimal.Decimal) + case billingstandardinvoicedetailedlineamountdiscount.FieldID, billingstandardinvoicedetailedlineamountdiscount.FieldNamespace, billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID, billingstandardinvoicedetailedlineamountdiscount.FieldLineID, billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID, billingstandardinvoicedetailedlineamountdiscount.FieldDescription, billingstandardinvoicedetailedlineamountdiscount.FieldReason: + values[i] = new(sql.NullString) + case billingstandardinvoicedetailedlineamountdiscount.FieldCreatedAt, billingstandardinvoicedetailedlineamountdiscount.FieldUpdatedAt, billingstandardinvoicedetailedlineamountdiscount.FieldDeletedAt: + values[i] = new(sql.NullTime) + case billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount: + values[i] = billingstandardinvoicedetailedlineamountdiscount.ValueScanner.SourceDiscount.ScanValue() + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the BillingStandardInvoiceDetailedLineAmountDiscount fields. +func (_m *BillingStandardInvoiceDetailedLineAmountDiscount) 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 billingstandardinvoicedetailedlineamountdiscount.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 billingstandardinvoicedetailedlineamountdiscount.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 billingstandardinvoicedetailedlineamountdiscount.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 billingstandardinvoicedetailedlineamountdiscount.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 billingstandardinvoicedetailedlineamountdiscount.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 billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field invoicing_app_external_id", values[i]) + } else if value.Valid { + _m.InvoicingAppExternalID = new(string) + *_m.InvoicingAppExternalID = value.String + } + case billingstandardinvoicedetailedlineamountdiscount.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 billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field child_unique_reference_id", values[i]) + } else if value.Valid { + _m.ChildUniqueReferenceID = new(string) + *_m.ChildUniqueReferenceID = value.String + } + case billingstandardinvoicedetailedlineamountdiscount.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + _m.Description = new(string) + *_m.Description = value.String + } + case billingstandardinvoicedetailedlineamountdiscount.FieldReason: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field reason", values[i]) + } else if value.Valid { + _m.Reason = billing.DiscountReasonType(value.String) + } + case billingstandardinvoicedetailedlineamountdiscount.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 billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field rounding_amount", values[i]) + } else if value.Valid { + _m.RoundingAmount = new(alpacadecimal.Decimal) + *_m.RoundingAmount = *value.S.(*alpacadecimal.Decimal) + } + case billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount: + if value, err := billingstandardinvoicedetailedlineamountdiscount.ValueScanner.SourceDiscount.FromValue(values[i]); err != nil { + return err + } else { + _m.SourceDiscount = value + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the BillingStandardInvoiceDetailedLineAmountDiscount. +// This includes values selected through modifiers, order, etc. +func (_m *BillingStandardInvoiceDetailedLineAmountDiscount) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryDetailedLine queries the "detailed_line" edge of the BillingStandardInvoiceDetailedLineAmountDiscount entity. +func (_m *BillingStandardInvoiceDetailedLineAmountDiscount) QueryDetailedLine() *BillingStandardInvoiceDetailedLineQuery { + return NewBillingStandardInvoiceDetailedLineAmountDiscountClient(_m.config).QueryDetailedLine(_m) +} + +// Update returns a builder for updating this BillingStandardInvoiceDetailedLineAmountDiscount. +// Note that you need to call BillingStandardInvoiceDetailedLineAmountDiscount.Unwrap() before calling this method if this BillingStandardInvoiceDetailedLineAmountDiscount +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *BillingStandardInvoiceDetailedLineAmountDiscount) Update() *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + return NewBillingStandardInvoiceDetailedLineAmountDiscountClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the BillingStandardInvoiceDetailedLineAmountDiscount 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 *BillingStandardInvoiceDetailedLineAmountDiscount) Unwrap() *BillingStandardInvoiceDetailedLineAmountDiscount { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: BillingStandardInvoiceDetailedLineAmountDiscount is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *BillingStandardInvoiceDetailedLineAmountDiscount) String() string { + var builder strings.Builder + builder.WriteString("BillingStandardInvoiceDetailedLineAmountDiscount(") + 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(", ") + if v := _m.InvoicingAppExternalID; v != nil { + builder.WriteString("invoicing_app_external_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("line_id=") + builder.WriteString(_m.LineID) + builder.WriteString(", ") + if v := _m.ChildUniqueReferenceID; v != nil { + builder.WriteString("child_unique_reference_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.Description; v != nil { + builder.WriteString("description=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("reason=") + builder.WriteString(fmt.Sprintf("%v", _m.Reason)) + builder.WriteString(", ") + builder.WriteString("amount=") + builder.WriteString(fmt.Sprintf("%v", _m.Amount)) + builder.WriteString(", ") + if v := _m.RoundingAmount; v != nil { + builder.WriteString("rounding_amount=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.SourceDiscount; v != nil { + builder.WriteString("source_discount=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteByte(')') + return builder.String() +} + +// BillingStandardInvoiceDetailedLineAmountDiscounts is a parsable slice of BillingStandardInvoiceDetailedLineAmountDiscount. +type BillingStandardInvoiceDetailedLineAmountDiscounts []*BillingStandardInvoiceDetailedLineAmountDiscount diff --git a/ent/db/billingstandardinvoicedetailedlineamountdiscount/billingstandardinvoicedetailedlineamountdiscount.go b/ent/db/billingstandardinvoicedetailedlineamountdiscount/billingstandardinvoicedetailedlineamountdiscount.go new file mode 100644 index 0000000000000000000000000000000000000000..136de40e5195773072a449a6c0c58b49977f9e73 --- /dev/null +++ b/ent/db/billingstandardinvoicedetailedlineamountdiscount/billingstandardinvoicedetailedlineamountdiscount.go @@ -0,0 +1,191 @@ +// Code generated by ent, DO NOT EDIT. + +package billingstandardinvoicedetailedlineamountdiscount + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/billing" +) + +const ( + // Label holds the string label denoting the billingstandardinvoicedetailedlineamountdiscount type in the database. + Label = "billing_standard_invoice_detailed_line_amount_discount" + // 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" + // FieldInvoicingAppExternalID holds the string denoting the invoicing_app_external_id field in the database. + FieldInvoicingAppExternalID = "invoicing_app_external_id" + // FieldLineID holds the string denoting the line_id field in the database. + FieldLineID = "line_id" + // FieldChildUniqueReferenceID holds the string denoting the child_unique_reference_id field in the database. + FieldChildUniqueReferenceID = "child_unique_reference_id" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // FieldReason holds the string denoting the reason field in the database. + FieldReason = "reason" + // FieldAmount holds the string denoting the amount field in the database. + FieldAmount = "amount" + // FieldRoundingAmount holds the string denoting the rounding_amount field in the database. + FieldRoundingAmount = "rounding_amount" + // FieldSourceDiscount holds the string denoting the source_discount field in the database. + FieldSourceDiscount = "source_discount" + // EdgeDetailedLine holds the string denoting the detailed_line edge name in mutations. + EdgeDetailedLine = "detailed_line" + // Table holds the table name of the billingstandardinvoicedetailedlineamountdiscount in the database. + Table = "billing_standard_invoice_detailed_line_amount_discounts" + // DetailedLineTable is the table that holds the detailed_line relation/edge. + DetailedLineTable = "billing_standard_invoice_detailed_line_amount_discounts" + // DetailedLineInverseTable is the table name for the BillingStandardInvoiceDetailedLine entity. + // It exists in this package in order to avoid circular dependency with the "billingstandardinvoicedetailedline" package. + DetailedLineInverseTable = "billing_standard_invoice_detailed_lines" + // DetailedLineColumn is the table column denoting the detailed_line relation/edge. + DetailedLineColumn = "line_id" +) + +// Columns holds all SQL columns for billingstandardinvoicedetailedlineamountdiscount fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldInvoicingAppExternalID, + FieldLineID, + FieldChildUniqueReferenceID, + FieldDescription, + FieldReason, + FieldAmount, + FieldRoundingAmount, + FieldSourceDiscount, +} + +// 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 + // ValueScanner of all BillingStandardInvoiceDetailedLineAmountDiscount fields. + ValueScanner struct { + SourceDiscount field.TypeValueScanner[*billing.DiscountReason] + } +) + +// ReasonValidator is a validator for the "reason" field enum values. It is called by the builders before save. +func ReasonValidator(r billing.DiscountReasonType) error { + switch r { + case "maximum_spend", "ratecard_percentage", "ratecard_usage": + return nil + default: + return fmt.Errorf("billingstandardinvoicedetailedlineamountdiscount: invalid enum value for reason field: %q", r) + } +} + +// OrderOption defines the ordering options for the BillingStandardInvoiceDetailedLineAmountDiscount 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() +} + +// ByInvoicingAppExternalID orders the results by the invoicing_app_external_id field. +func ByInvoicingAppExternalID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoicingAppExternalID, opts...).ToFunc() +} + +// ByLineID orders the results by the line_id field. +func ByLineID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLineID, opts...).ToFunc() +} + +// ByChildUniqueReferenceID orders the results by the child_unique_reference_id field. +func ByChildUniqueReferenceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChildUniqueReferenceID, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, opts...).ToFunc() +} + +// ByReason orders the results by the reason field. +func ByReason(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldReason, opts...).ToFunc() +} + +// ByAmount orders the results by the amount field. +func ByAmount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAmount, opts...).ToFunc() +} + +// ByRoundingAmount orders the results by the rounding_amount field. +func ByRoundingAmount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRoundingAmount, opts...).ToFunc() +} + +// BySourceDiscount orders the results by the source_discount field. +func BySourceDiscount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSourceDiscount, opts...).ToFunc() +} + +// ByDetailedLineField orders the results by detailed_line field. +func ByDetailedLineField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newDetailedLineStep(), sql.OrderByField(field, opts...)) + } +} +func newDetailedLineStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(DetailedLineInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, DetailedLineTable, DetailedLineColumn), + ) +} diff --git a/ent/db/billingstandardinvoicedetailedlineamountdiscount/where.go b/ent/db/billingstandardinvoicedetailedlineamountdiscount/where.go new file mode 100644 index 0000000000000000000000000000000000000000..3042bcc5dee6f13e85a10aaae90ae2649f7de7ad --- /dev/null +++ b/ent/db/billingstandardinvoicedetailedlineamountdiscount/where.go @@ -0,0 +1,771 @@ +// Code generated by ent, DO NOT EDIT. + +package billingstandardinvoicedetailedlineamountdiscount + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(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.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(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.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(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.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEQ(FieldDeletedAt, v)) +} + +// InvoicingAppExternalID applies equality check predicate on the "invoicing_app_external_id" field. It's identical to InvoicingAppExternalIDEQ. +func InvoicingAppExternalID(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEQ(FieldInvoicingAppExternalID, v)) +} + +// LineID applies equality check predicate on the "line_id" field. It's identical to LineIDEQ. +func LineID(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEQ(FieldLineID, v)) +} + +// ChildUniqueReferenceID applies equality check predicate on the "child_unique_reference_id" field. It's identical to ChildUniqueReferenceIDEQ. +func ChildUniqueReferenceID(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEQ(FieldChildUniqueReferenceID, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEQ(FieldDescription, v)) +} + +// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ. +func Amount(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEQ(FieldAmount, v)) +} + +// RoundingAmount applies equality check predicate on the "rounding_amount" field. It's identical to RoundingAmountEQ. +func RoundingAmount(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEQ(FieldRoundingAmount, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNotNull(FieldDeletedAt)) +} + +// InvoicingAppExternalIDEQ applies the EQ predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDEQ(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEQ(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDNEQ applies the NEQ predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDNEQ(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNEQ(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDIn applies the In predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDIn(vs ...string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldIn(FieldInvoicingAppExternalID, vs...)) +} + +// InvoicingAppExternalIDNotIn applies the NotIn predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDNotIn(vs ...string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNotIn(FieldInvoicingAppExternalID, vs...)) +} + +// InvoicingAppExternalIDGT applies the GT predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDGT(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGT(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDGTE applies the GTE predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDGTE(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGTE(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDLT applies the LT predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDLT(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLT(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDLTE applies the LTE predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDLTE(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLTE(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDContains applies the Contains predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDContains(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldContains(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDHasPrefix applies the HasPrefix predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDHasPrefix(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldHasPrefix(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDHasSuffix applies the HasSuffix predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDHasSuffix(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldHasSuffix(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDIsNil applies the IsNil predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDIsNil() predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldIsNull(FieldInvoicingAppExternalID)) +} + +// InvoicingAppExternalIDNotNil applies the NotNil predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDNotNil() predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNotNull(FieldInvoicingAppExternalID)) +} + +// InvoicingAppExternalIDEqualFold applies the EqualFold predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDEqualFold(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEqualFold(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDContainsFold applies the ContainsFold predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDContainsFold(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldContainsFold(FieldInvoicingAppExternalID, v)) +} + +// LineIDEQ applies the EQ predicate on the "line_id" field. +func LineIDEQ(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEQ(FieldLineID, v)) +} + +// LineIDNEQ applies the NEQ predicate on the "line_id" field. +func LineIDNEQ(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNEQ(FieldLineID, v)) +} + +// LineIDIn applies the In predicate on the "line_id" field. +func LineIDIn(vs ...string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldIn(FieldLineID, vs...)) +} + +// LineIDNotIn applies the NotIn predicate on the "line_id" field. +func LineIDNotIn(vs ...string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNotIn(FieldLineID, vs...)) +} + +// LineIDGT applies the GT predicate on the "line_id" field. +func LineIDGT(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGT(FieldLineID, v)) +} + +// LineIDGTE applies the GTE predicate on the "line_id" field. +func LineIDGTE(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGTE(FieldLineID, v)) +} + +// LineIDLT applies the LT predicate on the "line_id" field. +func LineIDLT(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLT(FieldLineID, v)) +} + +// LineIDLTE applies the LTE predicate on the "line_id" field. +func LineIDLTE(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLTE(FieldLineID, v)) +} + +// LineIDContains applies the Contains predicate on the "line_id" field. +func LineIDContains(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldContains(FieldLineID, v)) +} + +// LineIDHasPrefix applies the HasPrefix predicate on the "line_id" field. +func LineIDHasPrefix(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldHasPrefix(FieldLineID, v)) +} + +// LineIDHasSuffix applies the HasSuffix predicate on the "line_id" field. +func LineIDHasSuffix(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldHasSuffix(FieldLineID, v)) +} + +// LineIDEqualFold applies the EqualFold predicate on the "line_id" field. +func LineIDEqualFold(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEqualFold(FieldLineID, v)) +} + +// LineIDContainsFold applies the ContainsFold predicate on the "line_id" field. +func LineIDContainsFold(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldContainsFold(FieldLineID, v)) +} + +// ChildUniqueReferenceIDEQ applies the EQ predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDEQ(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEQ(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDNEQ applies the NEQ predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDNEQ(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNEQ(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDIn applies the In predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDIn(vs ...string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldIn(FieldChildUniqueReferenceID, vs...)) +} + +// ChildUniqueReferenceIDNotIn applies the NotIn predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDNotIn(vs ...string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNotIn(FieldChildUniqueReferenceID, vs...)) +} + +// ChildUniqueReferenceIDGT applies the GT predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDGT(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGT(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDGTE applies the GTE predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDGTE(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGTE(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDLT applies the LT predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDLT(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLT(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDLTE applies the LTE predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDLTE(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLTE(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDContains applies the Contains predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDContains(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldContains(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDHasPrefix applies the HasPrefix predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDHasPrefix(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldHasPrefix(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDHasSuffix applies the HasSuffix predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDHasSuffix(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldHasSuffix(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDIsNil applies the IsNil predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDIsNil() predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldIsNull(FieldChildUniqueReferenceID)) +} + +// ChildUniqueReferenceIDNotNil applies the NotNil predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDNotNil() predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNotNull(FieldChildUniqueReferenceID)) +} + +// ChildUniqueReferenceIDEqualFold applies the EqualFold predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDEqualFold(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEqualFold(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDContainsFold applies the ContainsFold predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDContainsFold(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldContainsFold(FieldChildUniqueReferenceID, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldContainsFold(FieldDescription, v)) +} + +// ReasonEQ applies the EQ predicate on the "reason" field. +func ReasonEQ(v billing.DiscountReasonType) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + vc := v + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEQ(FieldReason, vc)) +} + +// ReasonNEQ applies the NEQ predicate on the "reason" field. +func ReasonNEQ(v billing.DiscountReasonType) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + vc := v + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNEQ(FieldReason, vc)) +} + +// ReasonIn applies the In predicate on the "reason" field. +func ReasonIn(vs ...billing.DiscountReasonType) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldIn(FieldReason, v...)) +} + +// ReasonNotIn applies the NotIn predicate on the "reason" field. +func ReasonNotIn(vs ...billing.DiscountReasonType) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNotIn(FieldReason, v...)) +} + +// AmountEQ applies the EQ predicate on the "amount" field. +func AmountEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEQ(FieldAmount, v)) +} + +// AmountNEQ applies the NEQ predicate on the "amount" field. +func AmountNEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNEQ(FieldAmount, v)) +} + +// AmountIn applies the In predicate on the "amount" field. +func AmountIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldIn(FieldAmount, vs...)) +} + +// AmountNotIn applies the NotIn predicate on the "amount" field. +func AmountNotIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNotIn(FieldAmount, vs...)) +} + +// AmountGT applies the GT predicate on the "amount" field. +func AmountGT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGT(FieldAmount, v)) +} + +// AmountGTE applies the GTE predicate on the "amount" field. +func AmountGTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGTE(FieldAmount, v)) +} + +// AmountLT applies the LT predicate on the "amount" field. +func AmountLT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLT(FieldAmount, v)) +} + +// AmountLTE applies the LTE predicate on the "amount" field. +func AmountLTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLTE(FieldAmount, v)) +} + +// RoundingAmountEQ applies the EQ predicate on the "rounding_amount" field. +func RoundingAmountEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldEQ(FieldRoundingAmount, v)) +} + +// RoundingAmountNEQ applies the NEQ predicate on the "rounding_amount" field. +func RoundingAmountNEQ(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNEQ(FieldRoundingAmount, v)) +} + +// RoundingAmountIn applies the In predicate on the "rounding_amount" field. +func RoundingAmountIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldIn(FieldRoundingAmount, vs...)) +} + +// RoundingAmountNotIn applies the NotIn predicate on the "rounding_amount" field. +func RoundingAmountNotIn(vs ...alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNotIn(FieldRoundingAmount, vs...)) +} + +// RoundingAmountGT applies the GT predicate on the "rounding_amount" field. +func RoundingAmountGT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGT(FieldRoundingAmount, v)) +} + +// RoundingAmountGTE applies the GTE predicate on the "rounding_amount" field. +func RoundingAmountGTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldGTE(FieldRoundingAmount, v)) +} + +// RoundingAmountLT applies the LT predicate on the "rounding_amount" field. +func RoundingAmountLT(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLT(FieldRoundingAmount, v)) +} + +// RoundingAmountLTE applies the LTE predicate on the "rounding_amount" field. +func RoundingAmountLTE(v alpacadecimal.Decimal) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldLTE(FieldRoundingAmount, v)) +} + +// RoundingAmountIsNil applies the IsNil predicate on the "rounding_amount" field. +func RoundingAmountIsNil() predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldIsNull(FieldRoundingAmount)) +} + +// RoundingAmountNotNil applies the NotNil predicate on the "rounding_amount" field. +func RoundingAmountNotNil() predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNotNull(FieldRoundingAmount)) +} + +// SourceDiscountIsNil applies the IsNil predicate on the "source_discount" field. +func SourceDiscountIsNil() predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldIsNull(FieldSourceDiscount)) +} + +// SourceDiscountNotNil applies the NotNil predicate on the "source_discount" field. +func SourceDiscountNotNil() predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.FieldNotNull(FieldSourceDiscount)) +} + +// HasDetailedLine applies the HasEdge predicate on the "detailed_line" edge. +func HasDetailedLine() predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, DetailedLineTable, DetailedLineColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasDetailedLineWith applies the HasEdge predicate on the "detailed_line" edge with a given conditions (other predicates). +func HasDetailedLineWith(preds ...predicate.BillingStandardInvoiceDetailedLine) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(func(s *sql.Selector) { + step := newDetailedLineStep() + 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.BillingStandardInvoiceDetailedLineAmountDiscount) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.BillingStandardInvoiceDetailedLineAmountDiscount) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.BillingStandardInvoiceDetailedLineAmountDiscount) predicate.BillingStandardInvoiceDetailedLineAmountDiscount { + return predicate.BillingStandardInvoiceDetailedLineAmountDiscount(sql.NotPredicates(p)) +} diff --git a/ent/db/billingstandardinvoicedetailedlineamountdiscount_create.go b/ent/db/billingstandardinvoicedetailedlineamountdiscount_create.go new file mode 100644 index 0000000000000000000000000000000000000000..6017b876b9ee544ba88518effccb0a32007a0233 --- /dev/null +++ b/ent/db/billingstandardinvoicedetailedlineamountdiscount_create.go @@ -0,0 +1,1244 @@ +// 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" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingstandardinvoicedetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingstandardinvoicedetailedlineamountdiscount" +) + +// BillingStandardInvoiceDetailedLineAmountDiscountCreate is the builder for creating a BillingStandardInvoiceDetailedLineAmountDiscount entity. +type BillingStandardInvoiceDetailedLineAmountDiscountCreate struct { + config + mutation *BillingStandardInvoiceDetailedLineAmountDiscountMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetNamespace(v string) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetCreatedAt(v time.Time) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetNillableCreatedAt(v *time.Time) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetUpdatedAt(v time.Time) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetNillableUpdatedAt(v *time.Time) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetDeletedAt(v time.Time) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetNillableDeletedAt(v *time.Time) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetInvoicingAppExternalID(v string) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + _c.mutation.SetInvoicingAppExternalID(v) + return _c +} + +// SetNillableInvoicingAppExternalID sets the "invoicing_app_external_id" field if the given value is not nil. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetNillableInvoicingAppExternalID(v *string) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + if v != nil { + _c.SetInvoicingAppExternalID(*v) + } + return _c +} + +// SetLineID sets the "line_id" field. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetLineID(v string) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + _c.mutation.SetLineID(v) + return _c +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetChildUniqueReferenceID(v string) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + _c.mutation.SetChildUniqueReferenceID(v) + return _c +} + +// SetNillableChildUniqueReferenceID sets the "child_unique_reference_id" field if the given value is not nil. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetNillableChildUniqueReferenceID(v *string) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + if v != nil { + _c.SetChildUniqueReferenceID(*v) + } + return _c +} + +// SetDescription sets the "description" field. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetDescription(v string) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + _c.mutation.SetDescription(v) + return _c +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetNillableDescription(v *string) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + if v != nil { + _c.SetDescription(*v) + } + return _c +} + +// SetReason sets the "reason" field. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetReason(v billing.DiscountReasonType) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + _c.mutation.SetReason(v) + return _c +} + +// SetAmount sets the "amount" field. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetRoundingAmount sets the "rounding_amount" field. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetRoundingAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + _c.mutation.SetRoundingAmount(v) + return _c +} + +// SetNillableRoundingAmount sets the "rounding_amount" field if the given value is not nil. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetNillableRoundingAmount(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + if v != nil { + _c.SetRoundingAmount(*v) + } + return _c +} + +// SetSourceDiscount sets the "source_discount" field. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetSourceDiscount(v *billing.DiscountReason) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + _c.mutation.SetSourceDiscount(v) + return _c +} + +// SetID sets the "id" field. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetID(v string) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetNillableID(v *string) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetDetailedLineID sets the "detailed_line" edge to the BillingStandardInvoiceDetailedLine entity by ID. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetDetailedLineID(id string) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + _c.mutation.SetDetailedLineID(id) + return _c +} + +// SetDetailedLine sets the "detailed_line" edge to the BillingStandardInvoiceDetailedLine entity. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SetDetailedLine(v *BillingStandardInvoiceDetailedLine) *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + return _c.SetDetailedLineID(v.ID) +} + +// Mutation returns the BillingStandardInvoiceDetailedLineAmountDiscountMutation object of the builder. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) Mutation() *BillingStandardInvoiceDetailedLineAmountDiscountMutation { + return _c.mutation +} + +// Save creates the BillingStandardInvoiceDetailedLineAmountDiscount in the database. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) Save(ctx context.Context) (*BillingStandardInvoiceDetailedLineAmountDiscount, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) SaveX(ctx context.Context) *BillingStandardInvoiceDetailedLineAmountDiscount { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) 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 *BillingStandardInvoiceDetailedLineAmountDiscountCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := billingstandardinvoicedetailedlineamountdiscount.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := billingstandardinvoicedetailedlineamountdiscount.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := billingstandardinvoicedetailedlineamountdiscount.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLineAmountDiscount.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := billingstandardinvoicedetailedlineamountdiscount.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "BillingStandardInvoiceDetailedLineAmountDiscount.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLineAmountDiscount.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLineAmountDiscount.updated_at"`)} + } + if _, ok := _c.mutation.LineID(); !ok { + return &ValidationError{Name: "line_id", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLineAmountDiscount.line_id"`)} + } + if _, ok := _c.mutation.Reason(); !ok { + return &ValidationError{Name: "reason", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLineAmountDiscount.reason"`)} + } + if v, ok := _c.mutation.Reason(); ok { + if err := billingstandardinvoicedetailedlineamountdiscount.ReasonValidator(v); err != nil { + return &ValidationError{Name: "reason", err: fmt.Errorf(`db: validator failed for field "BillingStandardInvoiceDetailedLineAmountDiscount.reason": %w`, err)} + } + } + if _, ok := _c.mutation.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`db: missing required field "BillingStandardInvoiceDetailedLineAmountDiscount.amount"`)} + } + if v, ok := _c.mutation.SourceDiscount(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "source_discount", err: fmt.Errorf(`db: validator failed for field "BillingStandardInvoiceDetailedLineAmountDiscount.source_discount": %w`, err)} + } + } + if len(_c.mutation.DetailedLineIDs()) == 0 { + return &ValidationError{Name: "detailed_line", err: errors.New(`db: missing required edge "BillingStandardInvoiceDetailedLineAmountDiscount.detailed_line"`)} + } + return nil +} + +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) sqlSave(ctx context.Context) (*BillingStandardInvoiceDetailedLineAmountDiscount, 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 BillingStandardInvoiceDetailedLineAmountDiscount.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) createSpec() (*BillingStandardInvoiceDetailedLineAmountDiscount, *sqlgraph.CreateSpec, error) { + var ( + _node = &BillingStandardInvoiceDetailedLineAmountDiscount{config: _c.config} + _spec = sqlgraph.NewCreateSpec(billingstandardinvoicedetailedlineamountdiscount.Table, sqlgraph.NewFieldSpec(billingstandardinvoicedetailedlineamountdiscount.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(billingstandardinvoicedetailedlineamountdiscount.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.InvoicingAppExternalID(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID, field.TypeString, value) + _node.InvoicingAppExternalID = &value + } + if value, ok := _c.mutation.ChildUniqueReferenceID(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID, field.TypeString, value) + _node.ChildUniqueReferenceID = &value + } + if value, ok := _c.mutation.Description(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldDescription, field.TypeString, value) + _node.Description = &value + } + if value, ok := _c.mutation.Reason(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldReason, field.TypeEnum, value) + _node.Reason = value + } + if value, ok := _c.mutation.Amount(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldAmount, field.TypeOther, value) + _node.Amount = value + } + if value, ok := _c.mutation.RoundingAmount(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount, field.TypeOther, value) + _node.RoundingAmount = &value + } + if value, ok := _c.mutation.SourceDiscount(); ok { + vv, err := billingstandardinvoicedetailedlineamountdiscount.ValueScanner.SourceDiscount.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount, field.TypeString, vv) + _node.SourceDiscount = value + } + if nodes := _c.mutation.DetailedLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingstandardinvoicedetailedlineamountdiscount.DetailedLineTable, + Columns: []string{billingstandardinvoicedetailedlineamountdiscount.DetailedLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingstandardinvoicedetailedline.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.LineID = nodes[0] + _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.BillingStandardInvoiceDetailedLineAmountDiscount.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.BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) OnConflict(opts ...sql.ConflictOption) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + _c.conflict = opts + return &BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingStandardInvoiceDetailedLineAmountDiscount.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreate) OnConflictColumns(columns ...string) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne{ + create: _c, + } +} + +type ( + // BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne is the builder for "upsert"-ing + // one BillingStandardInvoiceDetailedLineAmountDiscount node. + BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne struct { + create *BillingStandardInvoiceDetailedLineAmountDiscountCreate + } + + // BillingStandardInvoiceDetailedLineAmountDiscountUpsert is the "OnConflict" setter. + BillingStandardInvoiceDetailedLineAmountDiscountUpsert struct { + *sql.UpdateSet + } +) + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) SetUpdatedAt(v time.Time) *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.Set(billingstandardinvoicedetailedlineamountdiscount.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) UpdateUpdatedAt() *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.SetExcluded(billingstandardinvoicedetailedlineamountdiscount.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) SetDeletedAt(v time.Time) *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.Set(billingstandardinvoicedetailedlineamountdiscount.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) UpdateDeletedAt() *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.SetExcluded(billingstandardinvoicedetailedlineamountdiscount.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) ClearDeletedAt() *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.SetNull(billingstandardinvoicedetailedlineamountdiscount.FieldDeletedAt) + return u +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) SetInvoicingAppExternalID(v string) *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.Set(billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID, v) + return u +} + +// UpdateInvoicingAppExternalID sets the "invoicing_app_external_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) UpdateInvoicingAppExternalID() *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.SetExcluded(billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID) + return u +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) ClearInvoicingAppExternalID() *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.SetNull(billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID) + return u +} + +// SetLineID sets the "line_id" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) SetLineID(v string) *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.Set(billingstandardinvoicedetailedlineamountdiscount.FieldLineID, v) + return u +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) UpdateLineID() *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.SetExcluded(billingstandardinvoicedetailedlineamountdiscount.FieldLineID) + return u +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) SetChildUniqueReferenceID(v string) *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.Set(billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID, v) + return u +} + +// UpdateChildUniqueReferenceID sets the "child_unique_reference_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) UpdateChildUniqueReferenceID() *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.SetExcluded(billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID) + return u +} + +// ClearChildUniqueReferenceID clears the value of the "child_unique_reference_id" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) ClearChildUniqueReferenceID() *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.SetNull(billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID) + return u +} + +// SetDescription sets the "description" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) SetDescription(v string) *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.Set(billingstandardinvoicedetailedlineamountdiscount.FieldDescription, v) + return u +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) UpdateDescription() *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.SetExcluded(billingstandardinvoicedetailedlineamountdiscount.FieldDescription) + return u +} + +// ClearDescription clears the value of the "description" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) ClearDescription() *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.SetNull(billingstandardinvoicedetailedlineamountdiscount.FieldDescription) + return u +} + +// SetReason sets the "reason" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) SetReason(v billing.DiscountReasonType) *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.Set(billingstandardinvoicedetailedlineamountdiscount.FieldReason, v) + return u +} + +// UpdateReason sets the "reason" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) UpdateReason() *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.SetExcluded(billingstandardinvoicedetailedlineamountdiscount.FieldReason) + return u +} + +// SetAmount sets the "amount" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) SetAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.Set(billingstandardinvoicedetailedlineamountdiscount.FieldAmount, v) + return u +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) UpdateAmount() *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.SetExcluded(billingstandardinvoicedetailedlineamountdiscount.FieldAmount) + return u +} + +// SetRoundingAmount sets the "rounding_amount" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) SetRoundingAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.Set(billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount, v) + return u +} + +// UpdateRoundingAmount sets the "rounding_amount" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) UpdateRoundingAmount() *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.SetExcluded(billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount) + return u +} + +// ClearRoundingAmount clears the value of the "rounding_amount" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) ClearRoundingAmount() *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.SetNull(billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount) + return u +} + +// SetSourceDiscount sets the "source_discount" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) SetSourceDiscount(v *billing.DiscountReason) *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.Set(billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount, v) + return u +} + +// UpdateSourceDiscount sets the "source_discount" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) UpdateSourceDiscount() *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.SetExcluded(billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount) + return u +} + +// ClearSourceDiscount clears the value of the "source_discount" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) ClearSourceDiscount() *BillingStandardInvoiceDetailedLineAmountDiscountUpsert { + u.SetNull(billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount) + 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.BillingStandardInvoiceDetailedLineAmountDiscount.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(billingstandardinvoicedetailedlineamountdiscount.FieldID) +// }), +// ). +// Exec(ctx) +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) UpdateNewValues() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + 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(billingstandardinvoicedetailedlineamountdiscount.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(billingstandardinvoicedetailedlineamountdiscount.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(billingstandardinvoicedetailedlineamountdiscount.FieldCreatedAt) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingStandardInvoiceDetailedLineAmountDiscount.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) Ignore() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + 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 *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) DoNothing() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingStandardInvoiceDetailedLineAmountDiscountCreate.OnConflict +// documentation for more info. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) Update(set func(*BillingStandardInvoiceDetailedLineAmountDiscountUpsert)) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingStandardInvoiceDetailedLineAmountDiscountUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) SetUpdatedAt(v time.Time) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) UpdateUpdatedAt() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) SetDeletedAt(v time.Time) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) UpdateDeletedAt() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) ClearDeletedAt() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.ClearDeletedAt() + }) +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) SetInvoicingAppExternalID(v string) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.SetInvoicingAppExternalID(v) + }) +} + +// UpdateInvoicingAppExternalID sets the "invoicing_app_external_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) UpdateInvoicingAppExternalID() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.UpdateInvoicingAppExternalID() + }) +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) ClearInvoicingAppExternalID() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.ClearInvoicingAppExternalID() + }) +} + +// SetLineID sets the "line_id" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) SetLineID(v string) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.SetLineID(v) + }) +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) UpdateLineID() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.UpdateLineID() + }) +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) SetChildUniqueReferenceID(v string) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.SetChildUniqueReferenceID(v) + }) +} + +// UpdateChildUniqueReferenceID sets the "child_unique_reference_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) UpdateChildUniqueReferenceID() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.UpdateChildUniqueReferenceID() + }) +} + +// ClearChildUniqueReferenceID clears the value of the "child_unique_reference_id" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) ClearChildUniqueReferenceID() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.ClearChildUniqueReferenceID() + }) +} + +// SetDescription sets the "description" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) SetDescription(v string) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) UpdateDescription() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) ClearDescription() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.ClearDescription() + }) +} + +// SetReason sets the "reason" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) SetReason(v billing.DiscountReasonType) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.SetReason(v) + }) +} + +// UpdateReason sets the "reason" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) UpdateReason() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.UpdateReason() + }) +} + +// SetAmount sets the "amount" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) SetAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) UpdateAmount() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.UpdateAmount() + }) +} + +// SetRoundingAmount sets the "rounding_amount" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) SetRoundingAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.SetRoundingAmount(v) + }) +} + +// UpdateRoundingAmount sets the "rounding_amount" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) UpdateRoundingAmount() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.UpdateRoundingAmount() + }) +} + +// ClearRoundingAmount clears the value of the "rounding_amount" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) ClearRoundingAmount() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.ClearRoundingAmount() + }) +} + +// SetSourceDiscount sets the "source_discount" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) SetSourceDiscount(v *billing.DiscountReason) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.SetSourceDiscount(v) + }) +} + +// UpdateSourceDiscount sets the "source_discount" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) UpdateSourceDiscount() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.UpdateSourceDiscount() + }) +} + +// ClearSourceDiscount clears the value of the "source_discount" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) ClearSourceDiscount() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.ClearSourceDiscount() + }) +} + +// Exec executes the query. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingStandardInvoiceDetailedLineAmountDiscountCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) 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 *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) 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: BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne.ID is not supported by MySQL driver. Use BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne.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 *BillingStandardInvoiceDetailedLineAmountDiscountUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// BillingStandardInvoiceDetailedLineAmountDiscountCreateBulk is the builder for creating many BillingStandardInvoiceDetailedLineAmountDiscount entities in bulk. +type BillingStandardInvoiceDetailedLineAmountDiscountCreateBulk struct { + config + err error + builders []*BillingStandardInvoiceDetailedLineAmountDiscountCreate + conflict []sql.ConflictOption +} + +// Save creates the BillingStandardInvoiceDetailedLineAmountDiscount entities in the database. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreateBulk) Save(ctx context.Context) ([]*BillingStandardInvoiceDetailedLineAmountDiscount, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*BillingStandardInvoiceDetailedLineAmountDiscount, 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.(*BillingStandardInvoiceDetailedLineAmountDiscountMutation) + 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 *BillingStandardInvoiceDetailedLineAmountDiscountCreateBulk) SaveX(ctx context.Context) []*BillingStandardInvoiceDetailedLineAmountDiscount { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreateBulk) 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.BillingStandardInvoiceDetailedLineAmountDiscount.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.BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreateBulk) OnConflict(opts ...sql.ConflictOption) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + _c.conflict = opts + return &BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingStandardInvoiceDetailedLineAmountDiscount.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingStandardInvoiceDetailedLineAmountDiscountCreateBulk) OnConflictColumns(columns ...string) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk{ + create: _c, + } +} + +// BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk is the builder for "upsert"-ing +// a bulk of BillingStandardInvoiceDetailedLineAmountDiscount nodes. +type BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk struct { + create *BillingStandardInvoiceDetailedLineAmountDiscountCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.BillingStandardInvoiceDetailedLineAmountDiscount.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(billingstandardinvoicedetailedlineamountdiscount.FieldID) +// }), +// ). +// Exec(ctx) +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) UpdateNewValues() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + 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(billingstandardinvoicedetailedlineamountdiscount.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(billingstandardinvoicedetailedlineamountdiscount.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(billingstandardinvoicedetailedlineamountdiscount.FieldCreatedAt) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingStandardInvoiceDetailedLineAmountDiscount.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) Ignore() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + 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 *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) DoNothing() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingStandardInvoiceDetailedLineAmountDiscountCreateBulk.OnConflict +// documentation for more info. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) Update(set func(*BillingStandardInvoiceDetailedLineAmountDiscountUpsert)) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingStandardInvoiceDetailedLineAmountDiscountUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) SetUpdatedAt(v time.Time) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) UpdateUpdatedAt() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) SetDeletedAt(v time.Time) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) UpdateDeletedAt() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) ClearDeletedAt() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.ClearDeletedAt() + }) +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) SetInvoicingAppExternalID(v string) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.SetInvoicingAppExternalID(v) + }) +} + +// UpdateInvoicingAppExternalID sets the "invoicing_app_external_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) UpdateInvoicingAppExternalID() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.UpdateInvoicingAppExternalID() + }) +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) ClearInvoicingAppExternalID() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.ClearInvoicingAppExternalID() + }) +} + +// SetLineID sets the "line_id" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) SetLineID(v string) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.SetLineID(v) + }) +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) UpdateLineID() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.UpdateLineID() + }) +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) SetChildUniqueReferenceID(v string) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.SetChildUniqueReferenceID(v) + }) +} + +// UpdateChildUniqueReferenceID sets the "child_unique_reference_id" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) UpdateChildUniqueReferenceID() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.UpdateChildUniqueReferenceID() + }) +} + +// ClearChildUniqueReferenceID clears the value of the "child_unique_reference_id" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) ClearChildUniqueReferenceID() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.ClearChildUniqueReferenceID() + }) +} + +// SetDescription sets the "description" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) SetDescription(v string) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) UpdateDescription() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) ClearDescription() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.ClearDescription() + }) +} + +// SetReason sets the "reason" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) SetReason(v billing.DiscountReasonType) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.SetReason(v) + }) +} + +// UpdateReason sets the "reason" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) UpdateReason() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.UpdateReason() + }) +} + +// SetAmount sets the "amount" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) SetAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) UpdateAmount() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.UpdateAmount() + }) +} + +// SetRoundingAmount sets the "rounding_amount" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) SetRoundingAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.SetRoundingAmount(v) + }) +} + +// UpdateRoundingAmount sets the "rounding_amount" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) UpdateRoundingAmount() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.UpdateRoundingAmount() + }) +} + +// ClearRoundingAmount clears the value of the "rounding_amount" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) ClearRoundingAmount() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.ClearRoundingAmount() + }) +} + +// SetSourceDiscount sets the "source_discount" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) SetSourceDiscount(v *billing.DiscountReason) *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.SetSourceDiscount(v) + }) +} + +// UpdateSourceDiscount sets the "source_discount" field to the value that was provided on create. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) UpdateSourceDiscount() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.UpdateSourceDiscount() + }) +} + +// ClearSourceDiscount clears the value of the "source_discount" field. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) ClearSourceDiscount() *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk { + return u.Update(func(s *BillingStandardInvoiceDetailedLineAmountDiscountUpsert) { + s.ClearSourceDiscount() + }) +} + +// Exec executes the query. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) 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 BillingStandardInvoiceDetailedLineAmountDiscountCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingStandardInvoiceDetailedLineAmountDiscountCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingStandardInvoiceDetailedLineAmountDiscountUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billingstandardinvoicedetailedlineamountdiscount_delete.go b/ent/db/billingstandardinvoicedetailedlineamountdiscount_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..ef66e28f2a87092ebc8a6722d4172b73181e02a7 --- /dev/null +++ b/ent/db/billingstandardinvoicedetailedlineamountdiscount_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/billingstandardinvoicedetailedlineamountdiscount" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingStandardInvoiceDetailedLineAmountDiscountDelete is the builder for deleting a BillingStandardInvoiceDetailedLineAmountDiscount entity. +type BillingStandardInvoiceDetailedLineAmountDiscountDelete struct { + config + hooks []Hook + mutation *BillingStandardInvoiceDetailedLineAmountDiscountMutation +} + +// Where appends a list predicates to the BillingStandardInvoiceDetailedLineAmountDiscountDelete builder. +func (_d *BillingStandardInvoiceDetailedLineAmountDiscountDelete) Where(ps ...predicate.BillingStandardInvoiceDetailedLineAmountDiscount) *BillingStandardInvoiceDetailedLineAmountDiscountDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *BillingStandardInvoiceDetailedLineAmountDiscountDelete) 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 *BillingStandardInvoiceDetailedLineAmountDiscountDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *BillingStandardInvoiceDetailedLineAmountDiscountDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(billingstandardinvoicedetailedlineamountdiscount.Table, sqlgraph.NewFieldSpec(billingstandardinvoicedetailedlineamountdiscount.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 +} + +// BillingStandardInvoiceDetailedLineAmountDiscountDeleteOne is the builder for deleting a single BillingStandardInvoiceDetailedLineAmountDiscount entity. +type BillingStandardInvoiceDetailedLineAmountDiscountDeleteOne struct { + _d *BillingStandardInvoiceDetailedLineAmountDiscountDelete +} + +// Where appends a list predicates to the BillingStandardInvoiceDetailedLineAmountDiscountDelete builder. +func (_d *BillingStandardInvoiceDetailedLineAmountDiscountDeleteOne) Where(ps ...predicate.BillingStandardInvoiceDetailedLineAmountDiscount) *BillingStandardInvoiceDetailedLineAmountDiscountDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *BillingStandardInvoiceDetailedLineAmountDiscountDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{billingstandardinvoicedetailedlineamountdiscount.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *BillingStandardInvoiceDetailedLineAmountDiscountDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billingstandardinvoicedetailedlineamountdiscount_query.go b/ent/db/billingstandardinvoicedetailedlineamountdiscount_query.go new file mode 100644 index 0000000000000000000000000000000000000000..943a853de77b2732648abe7672f4d1e878fcca1e --- /dev/null +++ b/ent/db/billingstandardinvoicedetailedlineamountdiscount_query.go @@ -0,0 +1,645 @@ +// 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/billingstandardinvoicedetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingstandardinvoicedetailedlineamountdiscount" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingStandardInvoiceDetailedLineAmountDiscountQuery is the builder for querying BillingStandardInvoiceDetailedLineAmountDiscount entities. +type BillingStandardInvoiceDetailedLineAmountDiscountQuery struct { + config + ctx *QueryContext + order []billingstandardinvoicedetailedlineamountdiscount.OrderOption + inters []Interceptor + predicates []predicate.BillingStandardInvoiceDetailedLineAmountDiscount + withDetailedLine *BillingStandardInvoiceDetailedLineQuery + 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 BillingStandardInvoiceDetailedLineAmountDiscountQuery builder. +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) Where(ps ...predicate.BillingStandardInvoiceDetailedLineAmountDiscount) *BillingStandardInvoiceDetailedLineAmountDiscountQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) Limit(limit int) *BillingStandardInvoiceDetailedLineAmountDiscountQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) Offset(offset int) *BillingStandardInvoiceDetailedLineAmountDiscountQuery { + _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 *BillingStandardInvoiceDetailedLineAmountDiscountQuery) Unique(unique bool) *BillingStandardInvoiceDetailedLineAmountDiscountQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) Order(o ...billingstandardinvoicedetailedlineamountdiscount.OrderOption) *BillingStandardInvoiceDetailedLineAmountDiscountQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryDetailedLine chains the current query on the "detailed_line" edge. +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) QueryDetailedLine() *BillingStandardInvoiceDetailedLineQuery { + query := (&BillingStandardInvoiceDetailedLineClient{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(billingstandardinvoicedetailedlineamountdiscount.Table, billingstandardinvoicedetailedlineamountdiscount.FieldID, selector), + sqlgraph.To(billingstandardinvoicedetailedline.Table, billingstandardinvoicedetailedline.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billingstandardinvoicedetailedlineamountdiscount.DetailedLineTable, billingstandardinvoicedetailedlineamountdiscount.DetailedLineColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first BillingStandardInvoiceDetailedLineAmountDiscount entity from the query. +// Returns a *NotFoundError when no BillingStandardInvoiceDetailedLineAmountDiscount was found. +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) First(ctx context.Context) (*BillingStandardInvoiceDetailedLineAmountDiscount, 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{billingstandardinvoicedetailedlineamountdiscount.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) FirstX(ctx context.Context) *BillingStandardInvoiceDetailedLineAmountDiscount { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first BillingStandardInvoiceDetailedLineAmountDiscount ID from the query. +// Returns a *NotFoundError when no BillingStandardInvoiceDetailedLineAmountDiscount ID was found. +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) 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{billingstandardinvoicedetailedlineamountdiscount.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single BillingStandardInvoiceDetailedLineAmountDiscount entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one BillingStandardInvoiceDetailedLineAmountDiscount entity is found. +// Returns a *NotFoundError when no BillingStandardInvoiceDetailedLineAmountDiscount entities are found. +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) Only(ctx context.Context) (*BillingStandardInvoiceDetailedLineAmountDiscount, 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{billingstandardinvoicedetailedlineamountdiscount.Label} + default: + return nil, &NotSingularError{billingstandardinvoicedetailedlineamountdiscount.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) OnlyX(ctx context.Context) *BillingStandardInvoiceDetailedLineAmountDiscount { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only BillingStandardInvoiceDetailedLineAmountDiscount ID in the query. +// Returns a *NotSingularError when more than one BillingStandardInvoiceDetailedLineAmountDiscount ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) 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{billingstandardinvoicedetailedlineamountdiscount.Label} + default: + err = &NotSingularError{billingstandardinvoicedetailedlineamountdiscount.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) 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 BillingStandardInvoiceDetailedLineAmountDiscounts. +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) All(ctx context.Context) ([]*BillingStandardInvoiceDetailedLineAmountDiscount, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*BillingStandardInvoiceDetailedLineAmountDiscount, *BillingStandardInvoiceDetailedLineAmountDiscountQuery]() + return withInterceptors[[]*BillingStandardInvoiceDetailedLineAmountDiscount](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) AllX(ctx context.Context) []*BillingStandardInvoiceDetailedLineAmountDiscount { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of BillingStandardInvoiceDetailedLineAmountDiscount IDs. +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) 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(billingstandardinvoicedetailedlineamountdiscount.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) 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 *BillingStandardInvoiceDetailedLineAmountDiscountQuery) 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[*BillingStandardInvoiceDetailedLineAmountDiscountQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) 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 *BillingStandardInvoiceDetailedLineAmountDiscountQuery) 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 *BillingStandardInvoiceDetailedLineAmountDiscountQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the BillingStandardInvoiceDetailedLineAmountDiscountQuery 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 *BillingStandardInvoiceDetailedLineAmountDiscountQuery) Clone() *BillingStandardInvoiceDetailedLineAmountDiscountQuery { + if _q == nil { + return nil + } + return &BillingStandardInvoiceDetailedLineAmountDiscountQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]billingstandardinvoicedetailedlineamountdiscount.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.BillingStandardInvoiceDetailedLineAmountDiscount{}, _q.predicates...), + withDetailedLine: _q.withDetailedLine.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithDetailedLine tells the query-builder to eager-load the nodes that are connected to +// the "detailed_line" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) WithDetailedLine(opts ...func(*BillingStandardInvoiceDetailedLineQuery)) *BillingStandardInvoiceDetailedLineAmountDiscountQuery { + query := (&BillingStandardInvoiceDetailedLineClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withDetailedLine = 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.BillingStandardInvoiceDetailedLineAmountDiscount.Query(). +// GroupBy(billingstandardinvoicedetailedlineamountdiscount.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) GroupBy(field string, fields ...string) *BillingStandardInvoiceDetailedLineAmountDiscountGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &BillingStandardInvoiceDetailedLineAmountDiscountGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = billingstandardinvoicedetailedlineamountdiscount.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.BillingStandardInvoiceDetailedLineAmountDiscount.Query(). +// Select(billingstandardinvoicedetailedlineamountdiscount.FieldNamespace). +// Scan(ctx, &v) +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) Select(fields ...string) *BillingStandardInvoiceDetailedLineAmountDiscountSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &BillingStandardInvoiceDetailedLineAmountDiscountSelect{BillingStandardInvoiceDetailedLineAmountDiscountQuery: _q} + sbuild.label = billingstandardinvoicedetailedlineamountdiscount.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a BillingStandardInvoiceDetailedLineAmountDiscountSelect configured with the given aggregations. +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) Aggregate(fns ...AggregateFunc) *BillingStandardInvoiceDetailedLineAmountDiscountSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) 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 !billingstandardinvoicedetailedlineamountdiscount.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 *BillingStandardInvoiceDetailedLineAmountDiscountQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BillingStandardInvoiceDetailedLineAmountDiscount, error) { + var ( + nodes = []*BillingStandardInvoiceDetailedLineAmountDiscount{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withDetailedLine != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*BillingStandardInvoiceDetailedLineAmountDiscount).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &BillingStandardInvoiceDetailedLineAmountDiscount{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.withDetailedLine; query != nil { + if err := _q.loadDetailedLine(ctx, query, nodes, nil, + func(n *BillingStandardInvoiceDetailedLineAmountDiscount, e *BillingStandardInvoiceDetailedLine) { + n.Edges.DetailedLine = e + }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) loadDetailedLine(ctx context.Context, query *BillingStandardInvoiceDetailedLineQuery, nodes []*BillingStandardInvoiceDetailedLineAmountDiscount, init func(*BillingStandardInvoiceDetailedLineAmountDiscount), assign func(*BillingStandardInvoiceDetailedLineAmountDiscount, *BillingStandardInvoiceDetailedLine)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*BillingStandardInvoiceDetailedLineAmountDiscount) + for i := range nodes { + fk := nodes[i].LineID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(billingstandardinvoicedetailedline.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 "line_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *BillingStandardInvoiceDetailedLineAmountDiscountQuery) 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 *BillingStandardInvoiceDetailedLineAmountDiscountQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(billingstandardinvoicedetailedlineamountdiscount.Table, billingstandardinvoicedetailedlineamountdiscount.Columns, sqlgraph.NewFieldSpec(billingstandardinvoicedetailedlineamountdiscount.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, billingstandardinvoicedetailedlineamountdiscount.FieldID) + for i := range fields { + if fields[i] != billingstandardinvoicedetailedlineamountdiscount.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withDetailedLine != nil { + _spec.Node.AddColumnOnce(billingstandardinvoicedetailedlineamountdiscount.FieldLineID) + } + } + 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 *BillingStandardInvoiceDetailedLineAmountDiscountQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(billingstandardinvoicedetailedlineamountdiscount.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = billingstandardinvoicedetailedlineamountdiscount.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 *BillingStandardInvoiceDetailedLineAmountDiscountQuery) ForUpdate(opts ...sql.LockOption) *BillingStandardInvoiceDetailedLineAmountDiscountQuery { + 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 *BillingStandardInvoiceDetailedLineAmountDiscountQuery) ForShare(opts ...sql.LockOption) *BillingStandardInvoiceDetailedLineAmountDiscountQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// BillingStandardInvoiceDetailedLineAmountDiscountGroupBy is the group-by builder for BillingStandardInvoiceDetailedLineAmountDiscount entities. +type BillingStandardInvoiceDetailedLineAmountDiscountGroupBy struct { + selector + build *BillingStandardInvoiceDetailedLineAmountDiscountQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *BillingStandardInvoiceDetailedLineAmountDiscountGroupBy) Aggregate(fns ...AggregateFunc) *BillingStandardInvoiceDetailedLineAmountDiscountGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *BillingStandardInvoiceDetailedLineAmountDiscountGroupBy) 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[*BillingStandardInvoiceDetailedLineAmountDiscountQuery, *BillingStandardInvoiceDetailedLineAmountDiscountGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *BillingStandardInvoiceDetailedLineAmountDiscountGroupBy) sqlScan(ctx context.Context, root *BillingStandardInvoiceDetailedLineAmountDiscountQuery, 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) +} + +// BillingStandardInvoiceDetailedLineAmountDiscountSelect is the builder for selecting fields of BillingStandardInvoiceDetailedLineAmountDiscount entities. +type BillingStandardInvoiceDetailedLineAmountDiscountSelect struct { + *BillingStandardInvoiceDetailedLineAmountDiscountQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *BillingStandardInvoiceDetailedLineAmountDiscountSelect) Aggregate(fns ...AggregateFunc) *BillingStandardInvoiceDetailedLineAmountDiscountSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *BillingStandardInvoiceDetailedLineAmountDiscountSelect) 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[*BillingStandardInvoiceDetailedLineAmountDiscountQuery, *BillingStandardInvoiceDetailedLineAmountDiscountSelect](ctx, _s.BillingStandardInvoiceDetailedLineAmountDiscountQuery, _s, _s.inters, v) +} + +func (_s *BillingStandardInvoiceDetailedLineAmountDiscountSelect) sqlScan(ctx context.Context, root *BillingStandardInvoiceDetailedLineAmountDiscountQuery, 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/ent/db/billingstandardinvoicedetailedlineamountdiscount_update.go b/ent/db/billingstandardinvoicedetailedlineamountdiscount_update.go new file mode 100644 index 0000000000000000000000000000000000000000..ce918931ecfc872d614a3f43f31bc5a73b58ae72 --- /dev/null +++ b/ent/db/billingstandardinvoicedetailedlineamountdiscount_update.go @@ -0,0 +1,749 @@ +// 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" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingstandardinvoicedetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingstandardinvoicedetailedlineamountdiscount" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingStandardInvoiceDetailedLineAmountDiscountUpdate is the builder for updating BillingStandardInvoiceDetailedLineAmountDiscount entities. +type BillingStandardInvoiceDetailedLineAmountDiscountUpdate struct { + config + hooks []Hook + mutation *BillingStandardInvoiceDetailedLineAmountDiscountMutation +} + +// Where appends a list predicates to the BillingStandardInvoiceDetailedLineAmountDiscountUpdate builder. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) Where(ps ...predicate.BillingStandardInvoiceDetailedLineAmountDiscount) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SetUpdatedAt(v time.Time) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SetDeletedAt(v time.Time) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SetNillableDeletedAt(v *time.Time) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) ClearDeletedAt() *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SetInvoicingAppExternalID(v string) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + _u.mutation.SetInvoicingAppExternalID(v) + return _u +} + +// SetNillableInvoicingAppExternalID sets the "invoicing_app_external_id" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SetNillableInvoicingAppExternalID(v *string) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + if v != nil { + _u.SetInvoicingAppExternalID(*v) + } + return _u +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) ClearInvoicingAppExternalID() *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + _u.mutation.ClearInvoicingAppExternalID() + return _u +} + +// SetLineID sets the "line_id" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SetLineID(v string) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + _u.mutation.SetLineID(v) + return _u +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SetNillableLineID(v *string) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + if v != nil { + _u.SetLineID(*v) + } + return _u +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SetChildUniqueReferenceID(v string) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + _u.mutation.SetChildUniqueReferenceID(v) + return _u +} + +// SetNillableChildUniqueReferenceID sets the "child_unique_reference_id" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SetNillableChildUniqueReferenceID(v *string) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + if v != nil { + _u.SetChildUniqueReferenceID(*v) + } + return _u +} + +// ClearChildUniqueReferenceID clears the value of the "child_unique_reference_id" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) ClearChildUniqueReferenceID() *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + _u.mutation.ClearChildUniqueReferenceID() + return _u +} + +// SetDescription sets the "description" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SetDescription(v string) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SetNillableDescription(v *string) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) ClearDescription() *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + _u.mutation.ClearDescription() + return _u +} + +// SetReason sets the "reason" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SetReason(v billing.DiscountReasonType) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + _u.mutation.SetReason(v) + return _u +} + +// SetNillableReason sets the "reason" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SetNillableReason(v *billing.DiscountReasonType) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + if v != nil { + _u.SetReason(*v) + } + return _u +} + +// SetAmount sets the "amount" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SetAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SetNillableAmount(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetRoundingAmount sets the "rounding_amount" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SetRoundingAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + _u.mutation.SetRoundingAmount(v) + return _u +} + +// SetNillableRoundingAmount sets the "rounding_amount" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SetNillableRoundingAmount(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + if v != nil { + _u.SetRoundingAmount(*v) + } + return _u +} + +// ClearRoundingAmount clears the value of the "rounding_amount" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) ClearRoundingAmount() *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + _u.mutation.ClearRoundingAmount() + return _u +} + +// SetSourceDiscount sets the "source_discount" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SetSourceDiscount(v *billing.DiscountReason) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + _u.mutation.SetSourceDiscount(v) + return _u +} + +// ClearSourceDiscount clears the value of the "source_discount" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) ClearSourceDiscount() *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + _u.mutation.ClearSourceDiscount() + return _u +} + +// SetDetailedLineID sets the "detailed_line" edge to the BillingStandardInvoiceDetailedLine entity by ID. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SetDetailedLineID(id string) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + _u.mutation.SetDetailedLineID(id) + return _u +} + +// SetDetailedLine sets the "detailed_line" edge to the BillingStandardInvoiceDetailedLine entity. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SetDetailedLine(v *BillingStandardInvoiceDetailedLine) *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + return _u.SetDetailedLineID(v.ID) +} + +// Mutation returns the BillingStandardInvoiceDetailedLineAmountDiscountMutation object of the builder. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) Mutation() *BillingStandardInvoiceDetailedLineAmountDiscountMutation { + return _u.mutation +} + +// ClearDetailedLine clears the "detailed_line" edge to the BillingStandardInvoiceDetailedLine entity. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) ClearDetailedLine() *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + _u.mutation.ClearDetailedLine() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) 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 *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) 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 *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := billingstandardinvoicedetailedlineamountdiscount.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) check() error { + if v, ok := _u.mutation.Reason(); ok { + if err := billingstandardinvoicedetailedlineamountdiscount.ReasonValidator(v); err != nil { + return &ValidationError{Name: "reason", err: fmt.Errorf(`db: validator failed for field "BillingStandardInvoiceDetailedLineAmountDiscount.reason": %w`, err)} + } + } + if v, ok := _u.mutation.SourceDiscount(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "source_discount", err: fmt.Errorf(`db: validator failed for field "BillingStandardInvoiceDetailedLineAmountDiscount.source_discount": %w`, err)} + } + } + if _u.mutation.DetailedLineCleared() && len(_u.mutation.DetailedLineIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "BillingStandardInvoiceDetailedLineAmountDiscount.detailed_line"`) + } + return nil +} + +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(billingstandardinvoicedetailedlineamountdiscount.Table, billingstandardinvoicedetailedlineamountdiscount.Columns, sqlgraph.NewFieldSpec(billingstandardinvoicedetailedlineamountdiscount.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(billingstandardinvoicedetailedlineamountdiscount.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(billingstandardinvoicedetailedlineamountdiscount.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.InvoicingAppExternalID(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID, field.TypeString, value) + } + if _u.mutation.InvoicingAppExternalIDCleared() { + _spec.ClearField(billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID, field.TypeString) + } + if value, ok := _u.mutation.ChildUniqueReferenceID(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID, field.TypeString, value) + } + if _u.mutation.ChildUniqueReferenceIDCleared() { + _spec.ClearField(billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID, field.TypeString) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(billingstandardinvoicedetailedlineamountdiscount.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.Reason(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldReason, field.TypeEnum, value) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.RoundingAmount(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount, field.TypeOther, value) + } + if _u.mutation.RoundingAmountCleared() { + _spec.ClearField(billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount, field.TypeOther) + } + if value, ok := _u.mutation.SourceDiscount(); ok { + vv, err := billingstandardinvoicedetailedlineamountdiscount.ValueScanner.SourceDiscount.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount, field.TypeString, vv) + } + if _u.mutation.SourceDiscountCleared() { + _spec.ClearField(billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount, field.TypeString) + } + if _u.mutation.DetailedLineCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingstandardinvoicedetailedlineamountdiscount.DetailedLineTable, + Columns: []string{billingstandardinvoicedetailedlineamountdiscount.DetailedLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingstandardinvoicedetailedline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.DetailedLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingstandardinvoicedetailedlineamountdiscount.DetailedLineTable, + Columns: []string{billingstandardinvoicedetailedlineamountdiscount.DetailedLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingstandardinvoicedetailedline.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{billingstandardinvoicedetailedlineamountdiscount.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne is the builder for updating a single BillingStandardInvoiceDetailedLineAmountDiscount entity. +type BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne struct { + config + fields []string + hooks []Hook + mutation *BillingStandardInvoiceDetailedLineAmountDiscountMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SetUpdatedAt(v time.Time) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SetDeletedAt(v time.Time) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SetNillableDeletedAt(v *time.Time) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) ClearDeletedAt() *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SetInvoicingAppExternalID(v string) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + _u.mutation.SetInvoicingAppExternalID(v) + return _u +} + +// SetNillableInvoicingAppExternalID sets the "invoicing_app_external_id" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SetNillableInvoicingAppExternalID(v *string) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + if v != nil { + _u.SetInvoicingAppExternalID(*v) + } + return _u +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) ClearInvoicingAppExternalID() *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + _u.mutation.ClearInvoicingAppExternalID() + return _u +} + +// SetLineID sets the "line_id" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SetLineID(v string) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + _u.mutation.SetLineID(v) + return _u +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SetNillableLineID(v *string) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + if v != nil { + _u.SetLineID(*v) + } + return _u +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SetChildUniqueReferenceID(v string) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + _u.mutation.SetChildUniqueReferenceID(v) + return _u +} + +// SetNillableChildUniqueReferenceID sets the "child_unique_reference_id" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SetNillableChildUniqueReferenceID(v *string) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + if v != nil { + _u.SetChildUniqueReferenceID(*v) + } + return _u +} + +// ClearChildUniqueReferenceID clears the value of the "child_unique_reference_id" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) ClearChildUniqueReferenceID() *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + _u.mutation.ClearChildUniqueReferenceID() + return _u +} + +// SetDescription sets the "description" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SetDescription(v string) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SetNillableDescription(v *string) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) ClearDescription() *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + _u.mutation.ClearDescription() + return _u +} + +// SetReason sets the "reason" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SetReason(v billing.DiscountReasonType) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + _u.mutation.SetReason(v) + return _u +} + +// SetNillableReason sets the "reason" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SetNillableReason(v *billing.DiscountReasonType) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + if v != nil { + _u.SetReason(*v) + } + return _u +} + +// SetAmount sets the "amount" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SetAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SetNillableAmount(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetRoundingAmount sets the "rounding_amount" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SetRoundingAmount(v alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + _u.mutation.SetRoundingAmount(v) + return _u +} + +// SetNillableRoundingAmount sets the "rounding_amount" field if the given value is not nil. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SetNillableRoundingAmount(v *alpacadecimal.Decimal) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + if v != nil { + _u.SetRoundingAmount(*v) + } + return _u +} + +// ClearRoundingAmount clears the value of the "rounding_amount" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) ClearRoundingAmount() *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + _u.mutation.ClearRoundingAmount() + return _u +} + +// SetSourceDiscount sets the "source_discount" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SetSourceDiscount(v *billing.DiscountReason) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + _u.mutation.SetSourceDiscount(v) + return _u +} + +// ClearSourceDiscount clears the value of the "source_discount" field. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) ClearSourceDiscount() *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + _u.mutation.ClearSourceDiscount() + return _u +} + +// SetDetailedLineID sets the "detailed_line" edge to the BillingStandardInvoiceDetailedLine entity by ID. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SetDetailedLineID(id string) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + _u.mutation.SetDetailedLineID(id) + return _u +} + +// SetDetailedLine sets the "detailed_line" edge to the BillingStandardInvoiceDetailedLine entity. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SetDetailedLine(v *BillingStandardInvoiceDetailedLine) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + return _u.SetDetailedLineID(v.ID) +} + +// Mutation returns the BillingStandardInvoiceDetailedLineAmountDiscountMutation object of the builder. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) Mutation() *BillingStandardInvoiceDetailedLineAmountDiscountMutation { + return _u.mutation +} + +// ClearDetailedLine clears the "detailed_line" edge to the BillingStandardInvoiceDetailedLine entity. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) ClearDetailedLine() *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + _u.mutation.ClearDetailedLine() + return _u +} + +// Where appends a list predicates to the BillingStandardInvoiceDetailedLineAmountDiscountUpdate builder. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) Where(ps ...predicate.BillingStandardInvoiceDetailedLineAmountDiscount) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + _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 *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) Select(field string, fields ...string) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated BillingStandardInvoiceDetailedLineAmountDiscount entity. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) Save(ctx context.Context) (*BillingStandardInvoiceDetailedLineAmountDiscount, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) SaveX(ctx context.Context) *BillingStandardInvoiceDetailedLineAmountDiscount { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) 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 *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := billingstandardinvoicedetailedlineamountdiscount.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) check() error { + if v, ok := _u.mutation.Reason(); ok { + if err := billingstandardinvoicedetailedlineamountdiscount.ReasonValidator(v); err != nil { + return &ValidationError{Name: "reason", err: fmt.Errorf(`db: validator failed for field "BillingStandardInvoiceDetailedLineAmountDiscount.reason": %w`, err)} + } + } + if v, ok := _u.mutation.SourceDiscount(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "source_discount", err: fmt.Errorf(`db: validator failed for field "BillingStandardInvoiceDetailedLineAmountDiscount.source_discount": %w`, err)} + } + } + if _u.mutation.DetailedLineCleared() && len(_u.mutation.DetailedLineIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "BillingStandardInvoiceDetailedLineAmountDiscount.detailed_line"`) + } + return nil +} + +func (_u *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne) sqlSave(ctx context.Context) (_node *BillingStandardInvoiceDetailedLineAmountDiscount, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(billingstandardinvoicedetailedlineamountdiscount.Table, billingstandardinvoicedetailedlineamountdiscount.Columns, sqlgraph.NewFieldSpec(billingstandardinvoicedetailedlineamountdiscount.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "BillingStandardInvoiceDetailedLineAmountDiscount.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, billingstandardinvoicedetailedlineamountdiscount.FieldID) + for _, f := range fields { + if !billingstandardinvoicedetailedlineamountdiscount.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != billingstandardinvoicedetailedlineamountdiscount.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(billingstandardinvoicedetailedlineamountdiscount.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(billingstandardinvoicedetailedlineamountdiscount.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.InvoicingAppExternalID(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID, field.TypeString, value) + } + if _u.mutation.InvoicingAppExternalIDCleared() { + _spec.ClearField(billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID, field.TypeString) + } + if value, ok := _u.mutation.ChildUniqueReferenceID(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID, field.TypeString, value) + } + if _u.mutation.ChildUniqueReferenceIDCleared() { + _spec.ClearField(billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID, field.TypeString) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(billingstandardinvoicedetailedlineamountdiscount.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.Reason(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldReason, field.TypeEnum, value) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.RoundingAmount(); ok { + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount, field.TypeOther, value) + } + if _u.mutation.RoundingAmountCleared() { + _spec.ClearField(billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount, field.TypeOther) + } + if value, ok := _u.mutation.SourceDiscount(); ok { + vv, err := billingstandardinvoicedetailedlineamountdiscount.ValueScanner.SourceDiscount.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount, field.TypeString, vv) + } + if _u.mutation.SourceDiscountCleared() { + _spec.ClearField(billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount, field.TypeString) + } + if _u.mutation.DetailedLineCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingstandardinvoicedetailedlineamountdiscount.DetailedLineTable, + Columns: []string{billingstandardinvoicedetailedlineamountdiscount.DetailedLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingstandardinvoicedetailedline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.DetailedLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingstandardinvoicedetailedlineamountdiscount.DetailedLineTable, + Columns: []string{billingstandardinvoicedetailedlineamountdiscount.DetailedLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingstandardinvoicedetailedline.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &BillingStandardInvoiceDetailedLineAmountDiscount{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{billingstandardinvoicedetailedlineamountdiscount.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/ent/db/billingworkflowconfig.go b/ent/db/billingworkflowconfig.go new file mode 100644 index 0000000000000000000000000000000000000000..992e3238e83034e8f5939245598cd159479d64e6 --- /dev/null +++ b/ent/db/billingworkflowconfig.go @@ -0,0 +1,379 @@ +// 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/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingprofile" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingworkflowconfig" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/datetime" +) + +// BillingWorkflowConfig is the model entity for the BillingWorkflowConfig schema. +type BillingWorkflowConfig 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"` + // TaxCodeID holds the value of the "tax_code_id" field. + TaxCodeID *string `json:"tax_code_id,omitempty"` + // TaxBehavior holds the value of the "tax_behavior" field. + TaxBehavior *productcatalog.TaxBehavior `json:"tax_behavior,omitempty"` + // CollectionAlignment holds the value of the "collection_alignment" field. + CollectionAlignment billing.AlignmentKind `json:"collection_alignment,omitempty"` + // AnchoredAlignmentDetail holds the value of the "anchored_alignment_detail" field. + AnchoredAlignmentDetail *billing.AnchoredAlignmentDetail `json:"anchored_alignment_detail,omitempty"` + // LineCollectionPeriod holds the value of the "line_collection_period" field. + LineCollectionPeriod datetime.ISODurationString `json:"line_collection_period,omitempty"` + // InvoiceAutoAdvance holds the value of the "invoice_auto_advance" field. + InvoiceAutoAdvance bool `json:"invoice_auto_advance,omitempty"` + // InvoiceDraftPeriod holds the value of the "invoice_draft_period" field. + InvoiceDraftPeriod datetime.ISODurationString `json:"invoice_draft_period,omitempty"` + // InvoiceDueAfter holds the value of the "invoice_due_after" field. + InvoiceDueAfter datetime.ISODurationString `json:"invoice_due_after,omitempty"` + // InvoiceCollectionMethod holds the value of the "invoice_collection_method" field. + InvoiceCollectionMethod billing.CollectionMethod `json:"invoice_collection_method,omitempty"` + // InvoiceProgressiveBilling holds the value of the "invoice_progressive_billing" field. + InvoiceProgressiveBilling bool `json:"invoice_progressive_billing,omitempty"` + // SubscriptionEndProrationMode holds the value of the "subscription_end_proration_mode" field. + SubscriptionEndProrationMode billing.SubscriptionEndProrationMode `json:"subscription_end_proration_mode,omitempty"` + // InvoiceDefaultTaxSettings holds the value of the "invoice_default_tax_settings" field. + InvoiceDefaultTaxSettings productcatalog.TaxConfig `json:"invoice_default_tax_settings,omitempty"` + // TaxEnabled holds the value of the "tax_enabled" field. + TaxEnabled bool `json:"tax_enabled,omitempty"` + // TaxEnforced holds the value of the "tax_enforced" field. + TaxEnforced bool `json:"tax_enforced,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the BillingWorkflowConfigQuery when eager-loading is set. + Edges BillingWorkflowConfigEdges `json:"edges"` + selectValues sql.SelectValues +} + +// BillingWorkflowConfigEdges holds the relations/edges for other nodes in the graph. +type BillingWorkflowConfigEdges struct { + // BillingInvoices holds the value of the billing_invoices edge. + BillingInvoices *BillingInvoice `json:"billing_invoices,omitempty"` + // BillingProfile holds the value of the billing_profile edge. + BillingProfile *BillingProfile `json:"billing_profile,omitempty"` + // TaxCode holds the value of the tax_code edge. + TaxCode *TaxCode `json:"tax_code,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [3]bool +} + +// BillingInvoicesOrErr returns the BillingInvoices value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e BillingWorkflowConfigEdges) BillingInvoicesOrErr() (*BillingInvoice, error) { + if e.BillingInvoices != nil { + return e.BillingInvoices, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: billinginvoice.Label} + } + return nil, &NotLoadedError{edge: "billing_invoices"} +} + +// BillingProfileOrErr returns the BillingProfile value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e BillingWorkflowConfigEdges) BillingProfileOrErr() (*BillingProfile, error) { + if e.BillingProfile != nil { + return e.BillingProfile, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: billingprofile.Label} + } + return nil, &NotLoadedError{edge: "billing_profile"} +} + +// TaxCodeOrErr returns the TaxCode value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e BillingWorkflowConfigEdges) TaxCodeOrErr() (*TaxCode, error) { + if e.TaxCode != nil { + return e.TaxCode, nil + } else if e.loadedTypes[2] { + return nil, &NotFoundError{label: dbtaxcode.Label} + } + return nil, &NotLoadedError{edge: "tax_code"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*BillingWorkflowConfig) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case billingworkflowconfig.FieldAnchoredAlignmentDetail, billingworkflowconfig.FieldInvoiceDefaultTaxSettings: + values[i] = new([]byte) + case billingworkflowconfig.FieldInvoiceAutoAdvance, billingworkflowconfig.FieldInvoiceProgressiveBilling, billingworkflowconfig.FieldTaxEnabled, billingworkflowconfig.FieldTaxEnforced: + values[i] = new(sql.NullBool) + case billingworkflowconfig.FieldID, billingworkflowconfig.FieldNamespace, billingworkflowconfig.FieldTaxCodeID, billingworkflowconfig.FieldTaxBehavior, billingworkflowconfig.FieldCollectionAlignment, billingworkflowconfig.FieldLineCollectionPeriod, billingworkflowconfig.FieldInvoiceDraftPeriod, billingworkflowconfig.FieldInvoiceDueAfter, billingworkflowconfig.FieldInvoiceCollectionMethod, billingworkflowconfig.FieldSubscriptionEndProrationMode: + values[i] = new(sql.NullString) + case billingworkflowconfig.FieldCreatedAt, billingworkflowconfig.FieldUpdatedAt, billingworkflowconfig.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 BillingWorkflowConfig fields. +func (_m *BillingWorkflowConfig) 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 billingworkflowconfig.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 billingworkflowconfig.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 billingworkflowconfig.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 billingworkflowconfig.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 billingworkflowconfig.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 billingworkflowconfig.FieldTaxCodeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field tax_code_id", values[i]) + } else if value.Valid { + _m.TaxCodeID = new(string) + *_m.TaxCodeID = value.String + } + case billingworkflowconfig.FieldTaxBehavior: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field tax_behavior", values[i]) + } else if value.Valid { + _m.TaxBehavior = new(productcatalog.TaxBehavior) + *_m.TaxBehavior = productcatalog.TaxBehavior(value.String) + } + case billingworkflowconfig.FieldCollectionAlignment: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field collection_alignment", values[i]) + } else if value.Valid { + _m.CollectionAlignment = billing.AlignmentKind(value.String) + } + case billingworkflowconfig.FieldAnchoredAlignmentDetail: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field anchored_alignment_detail", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.AnchoredAlignmentDetail); err != nil { + return fmt.Errorf("unmarshal field anchored_alignment_detail: %w", err) + } + } + case billingworkflowconfig.FieldLineCollectionPeriod: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field line_collection_period", values[i]) + } else if value.Valid { + _m.LineCollectionPeriod = datetime.ISODurationString(value.String) + } + case billingworkflowconfig.FieldInvoiceAutoAdvance: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field invoice_auto_advance", values[i]) + } else if value.Valid { + _m.InvoiceAutoAdvance = value.Bool + } + case billingworkflowconfig.FieldInvoiceDraftPeriod: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field invoice_draft_period", values[i]) + } else if value.Valid { + _m.InvoiceDraftPeriod = datetime.ISODurationString(value.String) + } + case billingworkflowconfig.FieldInvoiceDueAfter: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field invoice_due_after", values[i]) + } else if value.Valid { + _m.InvoiceDueAfter = datetime.ISODurationString(value.String) + } + case billingworkflowconfig.FieldInvoiceCollectionMethod: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field invoice_collection_method", values[i]) + } else if value.Valid { + _m.InvoiceCollectionMethod = billing.CollectionMethod(value.String) + } + case billingworkflowconfig.FieldInvoiceProgressiveBilling: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field invoice_progressive_billing", values[i]) + } else if value.Valid { + _m.InvoiceProgressiveBilling = value.Bool + } + case billingworkflowconfig.FieldSubscriptionEndProrationMode: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field subscription_end_proration_mode", values[i]) + } else if value.Valid { + _m.SubscriptionEndProrationMode = billing.SubscriptionEndProrationMode(value.String) + } + case billingworkflowconfig.FieldInvoiceDefaultTaxSettings: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field invoice_default_tax_settings", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.InvoiceDefaultTaxSettings); err != nil { + return fmt.Errorf("unmarshal field invoice_default_tax_settings: %w", err) + } + } + case billingworkflowconfig.FieldTaxEnabled: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field tax_enabled", values[i]) + } else if value.Valid { + _m.TaxEnabled = value.Bool + } + case billingworkflowconfig.FieldTaxEnforced: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field tax_enforced", values[i]) + } else if value.Valid { + _m.TaxEnforced = value.Bool + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the BillingWorkflowConfig. +// This includes values selected through modifiers, order, etc. +func (_m *BillingWorkflowConfig) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryBillingInvoices queries the "billing_invoices" edge of the BillingWorkflowConfig entity. +func (_m *BillingWorkflowConfig) QueryBillingInvoices() *BillingInvoiceQuery { + return NewBillingWorkflowConfigClient(_m.config).QueryBillingInvoices(_m) +} + +// QueryBillingProfile queries the "billing_profile" edge of the BillingWorkflowConfig entity. +func (_m *BillingWorkflowConfig) QueryBillingProfile() *BillingProfileQuery { + return NewBillingWorkflowConfigClient(_m.config).QueryBillingProfile(_m) +} + +// QueryTaxCode queries the "tax_code" edge of the BillingWorkflowConfig entity. +func (_m *BillingWorkflowConfig) QueryTaxCode() *TaxCodeQuery { + return NewBillingWorkflowConfigClient(_m.config).QueryTaxCode(_m) +} + +// Update returns a builder for updating this BillingWorkflowConfig. +// Note that you need to call BillingWorkflowConfig.Unwrap() before calling this method if this BillingWorkflowConfig +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *BillingWorkflowConfig) Update() *BillingWorkflowConfigUpdateOne { + return NewBillingWorkflowConfigClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the BillingWorkflowConfig 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 *BillingWorkflowConfig) Unwrap() *BillingWorkflowConfig { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: BillingWorkflowConfig is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *BillingWorkflowConfig) String() string { + var builder strings.Builder + builder.WriteString("BillingWorkflowConfig(") + 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(", ") + if v := _m.TaxCodeID; v != nil { + builder.WriteString("tax_code_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.TaxBehavior; v != nil { + builder.WriteString("tax_behavior=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + builder.WriteString("collection_alignment=") + builder.WriteString(fmt.Sprintf("%v", _m.CollectionAlignment)) + builder.WriteString(", ") + builder.WriteString("anchored_alignment_detail=") + builder.WriteString(fmt.Sprintf("%v", _m.AnchoredAlignmentDetail)) + builder.WriteString(", ") + builder.WriteString("line_collection_period=") + builder.WriteString(fmt.Sprintf("%v", _m.LineCollectionPeriod)) + builder.WriteString(", ") + builder.WriteString("invoice_auto_advance=") + builder.WriteString(fmt.Sprintf("%v", _m.InvoiceAutoAdvance)) + builder.WriteString(", ") + builder.WriteString("invoice_draft_period=") + builder.WriteString(fmt.Sprintf("%v", _m.InvoiceDraftPeriod)) + builder.WriteString(", ") + builder.WriteString("invoice_due_after=") + builder.WriteString(fmt.Sprintf("%v", _m.InvoiceDueAfter)) + builder.WriteString(", ") + builder.WriteString("invoice_collection_method=") + builder.WriteString(fmt.Sprintf("%v", _m.InvoiceCollectionMethod)) + builder.WriteString(", ") + builder.WriteString("invoice_progressive_billing=") + builder.WriteString(fmt.Sprintf("%v", _m.InvoiceProgressiveBilling)) + builder.WriteString(", ") + builder.WriteString("subscription_end_proration_mode=") + builder.WriteString(fmt.Sprintf("%v", _m.SubscriptionEndProrationMode)) + builder.WriteString(", ") + builder.WriteString("invoice_default_tax_settings=") + builder.WriteString(fmt.Sprintf("%v", _m.InvoiceDefaultTaxSettings)) + builder.WriteString(", ") + builder.WriteString("tax_enabled=") + builder.WriteString(fmt.Sprintf("%v", _m.TaxEnabled)) + builder.WriteString(", ") + builder.WriteString("tax_enforced=") + builder.WriteString(fmt.Sprintf("%v", _m.TaxEnforced)) + builder.WriteByte(')') + return builder.String() +} + +// BillingWorkflowConfigs is a parsable slice of BillingWorkflowConfig. +type BillingWorkflowConfigs []*BillingWorkflowConfig diff --git a/ent/db/billingworkflowconfig/billingworkflowconfig.go b/ent/db/billingworkflowconfig/billingworkflowconfig.go new file mode 100644 index 0000000000000000000000000000000000000000..bc8c62db527638fd9ed8584f3a1221b3ce9557e4 --- /dev/null +++ b/ent/db/billingworkflowconfig/billingworkflowconfig.go @@ -0,0 +1,307 @@ +// Code generated by ent, DO NOT EDIT. + +package billingworkflowconfig + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/productcatalog" +) + +const ( + // Label holds the string label denoting the billingworkflowconfig type in the database. + Label = "billing_workflow_config" + // 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" + // FieldTaxCodeID holds the string denoting the tax_code_id field in the database. + FieldTaxCodeID = "tax_code_id" + // FieldTaxBehavior holds the string denoting the tax_behavior field in the database. + FieldTaxBehavior = "tax_behavior" + // FieldCollectionAlignment holds the string denoting the collection_alignment field in the database. + FieldCollectionAlignment = "collection_alignment" + // FieldAnchoredAlignmentDetail holds the string denoting the anchored_alignment_detail field in the database. + FieldAnchoredAlignmentDetail = "anchored_alignment_detail" + // FieldLineCollectionPeriod holds the string denoting the line_collection_period field in the database. + FieldLineCollectionPeriod = "line_collection_period" + // FieldInvoiceAutoAdvance holds the string denoting the invoice_auto_advance field in the database. + FieldInvoiceAutoAdvance = "invoice_auto_advance" + // FieldInvoiceDraftPeriod holds the string denoting the invoice_draft_period field in the database. + FieldInvoiceDraftPeriod = "invoice_draft_period" + // FieldInvoiceDueAfter holds the string denoting the invoice_due_after field in the database. + FieldInvoiceDueAfter = "invoice_due_after" + // FieldInvoiceCollectionMethod holds the string denoting the invoice_collection_method field in the database. + FieldInvoiceCollectionMethod = "invoice_collection_method" + // FieldInvoiceProgressiveBilling holds the string denoting the invoice_progressive_billing field in the database. + FieldInvoiceProgressiveBilling = "invoice_progressive_billing" + // FieldSubscriptionEndProrationMode holds the string denoting the subscription_end_proration_mode field in the database. + FieldSubscriptionEndProrationMode = "subscription_end_proration_mode" + // FieldInvoiceDefaultTaxSettings holds the string denoting the invoice_default_tax_settings field in the database. + FieldInvoiceDefaultTaxSettings = "invoice_default_tax_settings" + // FieldTaxEnabled holds the string denoting the tax_enabled field in the database. + FieldTaxEnabled = "tax_enabled" + // FieldTaxEnforced holds the string denoting the tax_enforced field in the database. + FieldTaxEnforced = "tax_enforced" + // EdgeBillingInvoices holds the string denoting the billing_invoices edge name in mutations. + EdgeBillingInvoices = "billing_invoices" + // EdgeBillingProfile holds the string denoting the billing_profile edge name in mutations. + EdgeBillingProfile = "billing_profile" + // EdgeTaxCode holds the string denoting the tax_code edge name in mutations. + EdgeTaxCode = "tax_code" + // Table holds the table name of the billingworkflowconfig in the database. + Table = "billing_workflow_configs" + // BillingInvoicesTable is the table that holds the billing_invoices relation/edge. + BillingInvoicesTable = "billing_invoices" + // BillingInvoicesInverseTable is the table name for the BillingInvoice entity. + // It exists in this package in order to avoid circular dependency with the "billinginvoice" package. + BillingInvoicesInverseTable = "billing_invoices" + // BillingInvoicesColumn is the table column denoting the billing_invoices relation/edge. + BillingInvoicesColumn = "workflow_config_id" + // BillingProfileTable is the table that holds the billing_profile relation/edge. + BillingProfileTable = "billing_profiles" + // BillingProfileInverseTable is the table name for the BillingProfile entity. + // It exists in this package in order to avoid circular dependency with the "billingprofile" package. + BillingProfileInverseTable = "billing_profiles" + // BillingProfileColumn is the table column denoting the billing_profile relation/edge. + BillingProfileColumn = "workflow_config_id" + // TaxCodeTable is the table that holds the tax_code relation/edge. + TaxCodeTable = "billing_workflow_configs" + // TaxCodeInverseTable is the table name for the TaxCode entity. + // It exists in this package in order to avoid circular dependency with the "dbtaxcode" package. + TaxCodeInverseTable = "tax_codes" + // TaxCodeColumn is the table column denoting the tax_code relation/edge. + TaxCodeColumn = "tax_code_id" +) + +// Columns holds all SQL columns for billingworkflowconfig fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldTaxCodeID, + FieldTaxBehavior, + FieldCollectionAlignment, + FieldAnchoredAlignmentDetail, + FieldLineCollectionPeriod, + FieldInvoiceAutoAdvance, + FieldInvoiceDraftPeriod, + FieldInvoiceDueAfter, + FieldInvoiceCollectionMethod, + FieldInvoiceProgressiveBilling, + FieldSubscriptionEndProrationMode, + FieldInvoiceDefaultTaxSettings, + FieldTaxEnabled, + FieldTaxEnforced, +} + +// 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 + // DefaultTaxEnabled holds the default value on creation for the "tax_enabled" field. + DefaultTaxEnabled bool + // DefaultTaxEnforced holds the default value on creation for the "tax_enforced" field. + DefaultTaxEnforced bool + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// TaxBehaviorValidator is a validator for the "tax_behavior" field enum values. It is called by the builders before save. +func TaxBehaviorValidator(tb productcatalog.TaxBehavior) error { + switch tb { + case "inclusive", "exclusive": + return nil + default: + return fmt.Errorf("billingworkflowconfig: invalid enum value for tax_behavior field: %q", tb) + } +} + +// CollectionAlignmentValidator is a validator for the "collection_alignment" field enum values. It is called by the builders before save. +func CollectionAlignmentValidator(ca billing.AlignmentKind) error { + switch ca { + case "subscription", "anchored": + return nil + default: + return fmt.Errorf("billingworkflowconfig: invalid enum value for collection_alignment field: %q", ca) + } +} + +// InvoiceCollectionMethodValidator is a validator for the "invoice_collection_method" field enum values. It is called by the builders before save. +func InvoiceCollectionMethodValidator(icm billing.CollectionMethod) error { + switch icm { + case "charge_automatically", "send_invoice": + return nil + default: + return fmt.Errorf("billingworkflowconfig: invalid enum value for invoice_collection_method field: %q", icm) + } +} + +const DefaultSubscriptionEndProrationMode billing.SubscriptionEndProrationMode = "bill_actual_period" + +// SubscriptionEndProrationModeValidator is a validator for the "subscription_end_proration_mode" field enum values. It is called by the builders before save. +func SubscriptionEndProrationModeValidator(sepm billing.SubscriptionEndProrationMode) error { + switch sepm { + case "bill_full_period", "bill_actual_period": + return nil + default: + return fmt.Errorf("billingworkflowconfig: invalid enum value for subscription_end_proration_mode field: %q", sepm) + } +} + +// OrderOption defines the ordering options for the BillingWorkflowConfig 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() +} + +// ByTaxCodeID orders the results by the tax_code_id field. +func ByTaxCodeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxCodeID, opts...).ToFunc() +} + +// ByTaxBehavior orders the results by the tax_behavior field. +func ByTaxBehavior(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxBehavior, opts...).ToFunc() +} + +// ByCollectionAlignment orders the results by the collection_alignment field. +func ByCollectionAlignment(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCollectionAlignment, opts...).ToFunc() +} + +// ByLineCollectionPeriod orders the results by the line_collection_period field. +func ByLineCollectionPeriod(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLineCollectionPeriod, opts...).ToFunc() +} + +// ByInvoiceAutoAdvance orders the results by the invoice_auto_advance field. +func ByInvoiceAutoAdvance(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoiceAutoAdvance, opts...).ToFunc() +} + +// ByInvoiceDraftPeriod orders the results by the invoice_draft_period field. +func ByInvoiceDraftPeriod(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoiceDraftPeriod, opts...).ToFunc() +} + +// ByInvoiceDueAfter orders the results by the invoice_due_after field. +func ByInvoiceDueAfter(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoiceDueAfter, opts...).ToFunc() +} + +// ByInvoiceCollectionMethod orders the results by the invoice_collection_method field. +func ByInvoiceCollectionMethod(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoiceCollectionMethod, opts...).ToFunc() +} + +// ByInvoiceProgressiveBilling orders the results by the invoice_progressive_billing field. +func ByInvoiceProgressiveBilling(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoiceProgressiveBilling, opts...).ToFunc() +} + +// BySubscriptionEndProrationMode orders the results by the subscription_end_proration_mode field. +func BySubscriptionEndProrationMode(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSubscriptionEndProrationMode, opts...).ToFunc() +} + +// ByTaxEnabled orders the results by the tax_enabled field. +func ByTaxEnabled(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxEnabled, opts...).ToFunc() +} + +// ByTaxEnforced orders the results by the tax_enforced field. +func ByTaxEnforced(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxEnforced, opts...).ToFunc() +} + +// ByBillingInvoicesField orders the results by billing_invoices field. +func ByBillingInvoicesField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBillingInvoicesStep(), sql.OrderByField(field, opts...)) + } +} + +// ByBillingProfileField orders the results by billing_profile field. +func ByBillingProfileField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBillingProfileStep(), sql.OrderByField(field, opts...)) + } +} + +// ByTaxCodeField orders the results by tax_code field. +func ByTaxCodeField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTaxCodeStep(), sql.OrderByField(field, opts...)) + } +} +func newBillingInvoicesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BillingInvoicesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, BillingInvoicesTable, BillingInvoicesColumn), + ) +} +func newBillingProfileStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BillingProfileInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, BillingProfileTable, BillingProfileColumn), + ) +} +func newTaxCodeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TaxCodeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, TaxCodeTable, TaxCodeColumn), + ) +} diff --git a/ent/db/billingworkflowconfig/where.go b/ent/db/billingworkflowconfig/where.go new file mode 100644 index 0000000000000000000000000000000000000000..d0619a421802e54f40f1dc7a3b4450779b6e58a9 --- /dev/null +++ b/ent/db/billingworkflowconfig/where.go @@ -0,0 +1,928 @@ +// Code generated by ent, DO NOT EDIT. + +package billingworkflowconfig + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/datetime" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(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.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(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.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(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.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldDeletedAt, v)) +} + +// TaxCodeID applies equality check predicate on the "tax_code_id" field. It's identical to TaxCodeIDEQ. +func TaxCodeID(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldTaxCodeID, v)) +} + +// LineCollectionPeriod applies equality check predicate on the "line_collection_period" field. It's identical to LineCollectionPeriodEQ. +func LineCollectionPeriod(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldLineCollectionPeriod, vc)) +} + +// InvoiceAutoAdvance applies equality check predicate on the "invoice_auto_advance" field. It's identical to InvoiceAutoAdvanceEQ. +func InvoiceAutoAdvance(v bool) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldInvoiceAutoAdvance, v)) +} + +// InvoiceDraftPeriod applies equality check predicate on the "invoice_draft_period" field. It's identical to InvoiceDraftPeriodEQ. +func InvoiceDraftPeriod(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldInvoiceDraftPeriod, vc)) +} + +// InvoiceDueAfter applies equality check predicate on the "invoice_due_after" field. It's identical to InvoiceDueAfterEQ. +func InvoiceDueAfter(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldInvoiceDueAfter, vc)) +} + +// InvoiceProgressiveBilling applies equality check predicate on the "invoice_progressive_billing" field. It's identical to InvoiceProgressiveBillingEQ. +func InvoiceProgressiveBilling(v bool) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldInvoiceProgressiveBilling, v)) +} + +// TaxEnabled applies equality check predicate on the "tax_enabled" field. It's identical to TaxEnabledEQ. +func TaxEnabled(v bool) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldTaxEnabled, v)) +} + +// TaxEnforced applies equality check predicate on the "tax_enforced" field. It's identical to TaxEnforcedEQ. +func TaxEnforced(v bool) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldTaxEnforced, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNotNull(FieldDeletedAt)) +} + +// TaxCodeIDEQ applies the EQ predicate on the "tax_code_id" field. +func TaxCodeIDEQ(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldTaxCodeID, v)) +} + +// TaxCodeIDNEQ applies the NEQ predicate on the "tax_code_id" field. +func TaxCodeIDNEQ(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNEQ(FieldTaxCodeID, v)) +} + +// TaxCodeIDIn applies the In predicate on the "tax_code_id" field. +func TaxCodeIDIn(vs ...string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldIn(FieldTaxCodeID, vs...)) +} + +// TaxCodeIDNotIn applies the NotIn predicate on the "tax_code_id" field. +func TaxCodeIDNotIn(vs ...string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNotIn(FieldTaxCodeID, vs...)) +} + +// TaxCodeIDGT applies the GT predicate on the "tax_code_id" field. +func TaxCodeIDGT(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldGT(FieldTaxCodeID, v)) +} + +// TaxCodeIDGTE applies the GTE predicate on the "tax_code_id" field. +func TaxCodeIDGTE(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldGTE(FieldTaxCodeID, v)) +} + +// TaxCodeIDLT applies the LT predicate on the "tax_code_id" field. +func TaxCodeIDLT(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldLT(FieldTaxCodeID, v)) +} + +// TaxCodeIDLTE applies the LTE predicate on the "tax_code_id" field. +func TaxCodeIDLTE(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldLTE(FieldTaxCodeID, v)) +} + +// TaxCodeIDContains applies the Contains predicate on the "tax_code_id" field. +func TaxCodeIDContains(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldContains(FieldTaxCodeID, v)) +} + +// TaxCodeIDHasPrefix applies the HasPrefix predicate on the "tax_code_id" field. +func TaxCodeIDHasPrefix(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldHasPrefix(FieldTaxCodeID, v)) +} + +// TaxCodeIDHasSuffix applies the HasSuffix predicate on the "tax_code_id" field. +func TaxCodeIDHasSuffix(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldHasSuffix(FieldTaxCodeID, v)) +} + +// TaxCodeIDIsNil applies the IsNil predicate on the "tax_code_id" field. +func TaxCodeIDIsNil() predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldIsNull(FieldTaxCodeID)) +} + +// TaxCodeIDNotNil applies the NotNil predicate on the "tax_code_id" field. +func TaxCodeIDNotNil() predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNotNull(FieldTaxCodeID)) +} + +// TaxCodeIDEqualFold applies the EqualFold predicate on the "tax_code_id" field. +func TaxCodeIDEqualFold(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldEqualFold(FieldTaxCodeID, v)) +} + +// TaxCodeIDContainsFold applies the ContainsFold predicate on the "tax_code_id" field. +func TaxCodeIDContainsFold(v string) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldContainsFold(FieldTaxCodeID, v)) +} + +// TaxBehaviorEQ applies the EQ predicate on the "tax_behavior" field. +func TaxBehaviorEQ(v productcatalog.TaxBehavior) predicate.BillingWorkflowConfig { + vc := v + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldTaxBehavior, vc)) +} + +// TaxBehaviorNEQ applies the NEQ predicate on the "tax_behavior" field. +func TaxBehaviorNEQ(v productcatalog.TaxBehavior) predicate.BillingWorkflowConfig { + vc := v + return predicate.BillingWorkflowConfig(sql.FieldNEQ(FieldTaxBehavior, vc)) +} + +// TaxBehaviorIn applies the In predicate on the "tax_behavior" field. +func TaxBehaviorIn(vs ...productcatalog.TaxBehavior) predicate.BillingWorkflowConfig { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingWorkflowConfig(sql.FieldIn(FieldTaxBehavior, v...)) +} + +// TaxBehaviorNotIn applies the NotIn predicate on the "tax_behavior" field. +func TaxBehaviorNotIn(vs ...productcatalog.TaxBehavior) predicate.BillingWorkflowConfig { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingWorkflowConfig(sql.FieldNotIn(FieldTaxBehavior, v...)) +} + +// TaxBehaviorIsNil applies the IsNil predicate on the "tax_behavior" field. +func TaxBehaviorIsNil() predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldIsNull(FieldTaxBehavior)) +} + +// TaxBehaviorNotNil applies the NotNil predicate on the "tax_behavior" field. +func TaxBehaviorNotNil() predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNotNull(FieldTaxBehavior)) +} + +// CollectionAlignmentEQ applies the EQ predicate on the "collection_alignment" field. +func CollectionAlignmentEQ(v billing.AlignmentKind) predicate.BillingWorkflowConfig { + vc := v + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldCollectionAlignment, vc)) +} + +// CollectionAlignmentNEQ applies the NEQ predicate on the "collection_alignment" field. +func CollectionAlignmentNEQ(v billing.AlignmentKind) predicate.BillingWorkflowConfig { + vc := v + return predicate.BillingWorkflowConfig(sql.FieldNEQ(FieldCollectionAlignment, vc)) +} + +// CollectionAlignmentIn applies the In predicate on the "collection_alignment" field. +func CollectionAlignmentIn(vs ...billing.AlignmentKind) predicate.BillingWorkflowConfig { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingWorkflowConfig(sql.FieldIn(FieldCollectionAlignment, v...)) +} + +// CollectionAlignmentNotIn applies the NotIn predicate on the "collection_alignment" field. +func CollectionAlignmentNotIn(vs ...billing.AlignmentKind) predicate.BillingWorkflowConfig { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingWorkflowConfig(sql.FieldNotIn(FieldCollectionAlignment, v...)) +} + +// AnchoredAlignmentDetailIsNil applies the IsNil predicate on the "anchored_alignment_detail" field. +func AnchoredAlignmentDetailIsNil() predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldIsNull(FieldAnchoredAlignmentDetail)) +} + +// AnchoredAlignmentDetailNotNil applies the NotNil predicate on the "anchored_alignment_detail" field. +func AnchoredAlignmentDetailNotNil() predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNotNull(FieldAnchoredAlignmentDetail)) +} + +// LineCollectionPeriodEQ applies the EQ predicate on the "line_collection_period" field. +func LineCollectionPeriodEQ(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldLineCollectionPeriod, vc)) +} + +// LineCollectionPeriodNEQ applies the NEQ predicate on the "line_collection_period" field. +func LineCollectionPeriodNEQ(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldNEQ(FieldLineCollectionPeriod, vc)) +} + +// LineCollectionPeriodIn applies the In predicate on the "line_collection_period" field. +func LineCollectionPeriodIn(vs ...datetime.ISODurationString) predicate.BillingWorkflowConfig { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.BillingWorkflowConfig(sql.FieldIn(FieldLineCollectionPeriod, v...)) +} + +// LineCollectionPeriodNotIn applies the NotIn predicate on the "line_collection_period" field. +func LineCollectionPeriodNotIn(vs ...datetime.ISODurationString) predicate.BillingWorkflowConfig { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.BillingWorkflowConfig(sql.FieldNotIn(FieldLineCollectionPeriod, v...)) +} + +// LineCollectionPeriodGT applies the GT predicate on the "line_collection_period" field. +func LineCollectionPeriodGT(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldGT(FieldLineCollectionPeriod, vc)) +} + +// LineCollectionPeriodGTE applies the GTE predicate on the "line_collection_period" field. +func LineCollectionPeriodGTE(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldGTE(FieldLineCollectionPeriod, vc)) +} + +// LineCollectionPeriodLT applies the LT predicate on the "line_collection_period" field. +func LineCollectionPeriodLT(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldLT(FieldLineCollectionPeriod, vc)) +} + +// LineCollectionPeriodLTE applies the LTE predicate on the "line_collection_period" field. +func LineCollectionPeriodLTE(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldLTE(FieldLineCollectionPeriod, vc)) +} + +// LineCollectionPeriodContains applies the Contains predicate on the "line_collection_period" field. +func LineCollectionPeriodContains(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldContains(FieldLineCollectionPeriod, vc)) +} + +// LineCollectionPeriodHasPrefix applies the HasPrefix predicate on the "line_collection_period" field. +func LineCollectionPeriodHasPrefix(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldHasPrefix(FieldLineCollectionPeriod, vc)) +} + +// LineCollectionPeriodHasSuffix applies the HasSuffix predicate on the "line_collection_period" field. +func LineCollectionPeriodHasSuffix(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldHasSuffix(FieldLineCollectionPeriod, vc)) +} + +// LineCollectionPeriodEqualFold applies the EqualFold predicate on the "line_collection_period" field. +func LineCollectionPeriodEqualFold(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldEqualFold(FieldLineCollectionPeriod, vc)) +} + +// LineCollectionPeriodContainsFold applies the ContainsFold predicate on the "line_collection_period" field. +func LineCollectionPeriodContainsFold(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldContainsFold(FieldLineCollectionPeriod, vc)) +} + +// InvoiceAutoAdvanceEQ applies the EQ predicate on the "invoice_auto_advance" field. +func InvoiceAutoAdvanceEQ(v bool) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldInvoiceAutoAdvance, v)) +} + +// InvoiceAutoAdvanceNEQ applies the NEQ predicate on the "invoice_auto_advance" field. +func InvoiceAutoAdvanceNEQ(v bool) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNEQ(FieldInvoiceAutoAdvance, v)) +} + +// InvoiceDraftPeriodEQ applies the EQ predicate on the "invoice_draft_period" field. +func InvoiceDraftPeriodEQ(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldInvoiceDraftPeriod, vc)) +} + +// InvoiceDraftPeriodNEQ applies the NEQ predicate on the "invoice_draft_period" field. +func InvoiceDraftPeriodNEQ(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldNEQ(FieldInvoiceDraftPeriod, vc)) +} + +// InvoiceDraftPeriodIn applies the In predicate on the "invoice_draft_period" field. +func InvoiceDraftPeriodIn(vs ...datetime.ISODurationString) predicate.BillingWorkflowConfig { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.BillingWorkflowConfig(sql.FieldIn(FieldInvoiceDraftPeriod, v...)) +} + +// InvoiceDraftPeriodNotIn applies the NotIn predicate on the "invoice_draft_period" field. +func InvoiceDraftPeriodNotIn(vs ...datetime.ISODurationString) predicate.BillingWorkflowConfig { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.BillingWorkflowConfig(sql.FieldNotIn(FieldInvoiceDraftPeriod, v...)) +} + +// InvoiceDraftPeriodGT applies the GT predicate on the "invoice_draft_period" field. +func InvoiceDraftPeriodGT(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldGT(FieldInvoiceDraftPeriod, vc)) +} + +// InvoiceDraftPeriodGTE applies the GTE predicate on the "invoice_draft_period" field. +func InvoiceDraftPeriodGTE(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldGTE(FieldInvoiceDraftPeriod, vc)) +} + +// InvoiceDraftPeriodLT applies the LT predicate on the "invoice_draft_period" field. +func InvoiceDraftPeriodLT(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldLT(FieldInvoiceDraftPeriod, vc)) +} + +// InvoiceDraftPeriodLTE applies the LTE predicate on the "invoice_draft_period" field. +func InvoiceDraftPeriodLTE(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldLTE(FieldInvoiceDraftPeriod, vc)) +} + +// InvoiceDraftPeriodContains applies the Contains predicate on the "invoice_draft_period" field. +func InvoiceDraftPeriodContains(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldContains(FieldInvoiceDraftPeriod, vc)) +} + +// InvoiceDraftPeriodHasPrefix applies the HasPrefix predicate on the "invoice_draft_period" field. +func InvoiceDraftPeriodHasPrefix(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldHasPrefix(FieldInvoiceDraftPeriod, vc)) +} + +// InvoiceDraftPeriodHasSuffix applies the HasSuffix predicate on the "invoice_draft_period" field. +func InvoiceDraftPeriodHasSuffix(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldHasSuffix(FieldInvoiceDraftPeriod, vc)) +} + +// InvoiceDraftPeriodEqualFold applies the EqualFold predicate on the "invoice_draft_period" field. +func InvoiceDraftPeriodEqualFold(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldEqualFold(FieldInvoiceDraftPeriod, vc)) +} + +// InvoiceDraftPeriodContainsFold applies the ContainsFold predicate on the "invoice_draft_period" field. +func InvoiceDraftPeriodContainsFold(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldContainsFold(FieldInvoiceDraftPeriod, vc)) +} + +// InvoiceDueAfterEQ applies the EQ predicate on the "invoice_due_after" field. +func InvoiceDueAfterEQ(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldInvoiceDueAfter, vc)) +} + +// InvoiceDueAfterNEQ applies the NEQ predicate on the "invoice_due_after" field. +func InvoiceDueAfterNEQ(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldNEQ(FieldInvoiceDueAfter, vc)) +} + +// InvoiceDueAfterIn applies the In predicate on the "invoice_due_after" field. +func InvoiceDueAfterIn(vs ...datetime.ISODurationString) predicate.BillingWorkflowConfig { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.BillingWorkflowConfig(sql.FieldIn(FieldInvoiceDueAfter, v...)) +} + +// InvoiceDueAfterNotIn applies the NotIn predicate on the "invoice_due_after" field. +func InvoiceDueAfterNotIn(vs ...datetime.ISODurationString) predicate.BillingWorkflowConfig { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.BillingWorkflowConfig(sql.FieldNotIn(FieldInvoiceDueAfter, v...)) +} + +// InvoiceDueAfterGT applies the GT predicate on the "invoice_due_after" field. +func InvoiceDueAfterGT(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldGT(FieldInvoiceDueAfter, vc)) +} + +// InvoiceDueAfterGTE applies the GTE predicate on the "invoice_due_after" field. +func InvoiceDueAfterGTE(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldGTE(FieldInvoiceDueAfter, vc)) +} + +// InvoiceDueAfterLT applies the LT predicate on the "invoice_due_after" field. +func InvoiceDueAfterLT(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldLT(FieldInvoiceDueAfter, vc)) +} + +// InvoiceDueAfterLTE applies the LTE predicate on the "invoice_due_after" field. +func InvoiceDueAfterLTE(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldLTE(FieldInvoiceDueAfter, vc)) +} + +// InvoiceDueAfterContains applies the Contains predicate on the "invoice_due_after" field. +func InvoiceDueAfterContains(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldContains(FieldInvoiceDueAfter, vc)) +} + +// InvoiceDueAfterHasPrefix applies the HasPrefix predicate on the "invoice_due_after" field. +func InvoiceDueAfterHasPrefix(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldHasPrefix(FieldInvoiceDueAfter, vc)) +} + +// InvoiceDueAfterHasSuffix applies the HasSuffix predicate on the "invoice_due_after" field. +func InvoiceDueAfterHasSuffix(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldHasSuffix(FieldInvoiceDueAfter, vc)) +} + +// InvoiceDueAfterEqualFold applies the EqualFold predicate on the "invoice_due_after" field. +func InvoiceDueAfterEqualFold(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldEqualFold(FieldInvoiceDueAfter, vc)) +} + +// InvoiceDueAfterContainsFold applies the ContainsFold predicate on the "invoice_due_after" field. +func InvoiceDueAfterContainsFold(v datetime.ISODurationString) predicate.BillingWorkflowConfig { + vc := string(v) + return predicate.BillingWorkflowConfig(sql.FieldContainsFold(FieldInvoiceDueAfter, vc)) +} + +// InvoiceCollectionMethodEQ applies the EQ predicate on the "invoice_collection_method" field. +func InvoiceCollectionMethodEQ(v billing.CollectionMethod) predicate.BillingWorkflowConfig { + vc := v + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldInvoiceCollectionMethod, vc)) +} + +// InvoiceCollectionMethodNEQ applies the NEQ predicate on the "invoice_collection_method" field. +func InvoiceCollectionMethodNEQ(v billing.CollectionMethod) predicate.BillingWorkflowConfig { + vc := v + return predicate.BillingWorkflowConfig(sql.FieldNEQ(FieldInvoiceCollectionMethod, vc)) +} + +// InvoiceCollectionMethodIn applies the In predicate on the "invoice_collection_method" field. +func InvoiceCollectionMethodIn(vs ...billing.CollectionMethod) predicate.BillingWorkflowConfig { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingWorkflowConfig(sql.FieldIn(FieldInvoiceCollectionMethod, v...)) +} + +// InvoiceCollectionMethodNotIn applies the NotIn predicate on the "invoice_collection_method" field. +func InvoiceCollectionMethodNotIn(vs ...billing.CollectionMethod) predicate.BillingWorkflowConfig { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingWorkflowConfig(sql.FieldNotIn(FieldInvoiceCollectionMethod, v...)) +} + +// InvoiceProgressiveBillingEQ applies the EQ predicate on the "invoice_progressive_billing" field. +func InvoiceProgressiveBillingEQ(v bool) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldInvoiceProgressiveBilling, v)) +} + +// InvoiceProgressiveBillingNEQ applies the NEQ predicate on the "invoice_progressive_billing" field. +func InvoiceProgressiveBillingNEQ(v bool) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNEQ(FieldInvoiceProgressiveBilling, v)) +} + +// SubscriptionEndProrationModeEQ applies the EQ predicate on the "subscription_end_proration_mode" field. +func SubscriptionEndProrationModeEQ(v billing.SubscriptionEndProrationMode) predicate.BillingWorkflowConfig { + vc := v + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldSubscriptionEndProrationMode, vc)) +} + +// SubscriptionEndProrationModeNEQ applies the NEQ predicate on the "subscription_end_proration_mode" field. +func SubscriptionEndProrationModeNEQ(v billing.SubscriptionEndProrationMode) predicate.BillingWorkflowConfig { + vc := v + return predicate.BillingWorkflowConfig(sql.FieldNEQ(FieldSubscriptionEndProrationMode, vc)) +} + +// SubscriptionEndProrationModeIn applies the In predicate on the "subscription_end_proration_mode" field. +func SubscriptionEndProrationModeIn(vs ...billing.SubscriptionEndProrationMode) predicate.BillingWorkflowConfig { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingWorkflowConfig(sql.FieldIn(FieldSubscriptionEndProrationMode, v...)) +} + +// SubscriptionEndProrationModeNotIn applies the NotIn predicate on the "subscription_end_proration_mode" field. +func SubscriptionEndProrationModeNotIn(vs ...billing.SubscriptionEndProrationMode) predicate.BillingWorkflowConfig { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingWorkflowConfig(sql.FieldNotIn(FieldSubscriptionEndProrationMode, v...)) +} + +// InvoiceDefaultTaxSettingsIsNil applies the IsNil predicate on the "invoice_default_tax_settings" field. +func InvoiceDefaultTaxSettingsIsNil() predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldIsNull(FieldInvoiceDefaultTaxSettings)) +} + +// InvoiceDefaultTaxSettingsNotNil applies the NotNil predicate on the "invoice_default_tax_settings" field. +func InvoiceDefaultTaxSettingsNotNil() predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNotNull(FieldInvoiceDefaultTaxSettings)) +} + +// TaxEnabledEQ applies the EQ predicate on the "tax_enabled" field. +func TaxEnabledEQ(v bool) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldTaxEnabled, v)) +} + +// TaxEnabledNEQ applies the NEQ predicate on the "tax_enabled" field. +func TaxEnabledNEQ(v bool) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNEQ(FieldTaxEnabled, v)) +} + +// TaxEnforcedEQ applies the EQ predicate on the "tax_enforced" field. +func TaxEnforcedEQ(v bool) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldEQ(FieldTaxEnforced, v)) +} + +// TaxEnforcedNEQ applies the NEQ predicate on the "tax_enforced" field. +func TaxEnforcedNEQ(v bool) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.FieldNEQ(FieldTaxEnforced, v)) +} + +// HasBillingInvoices applies the HasEdge predicate on the "billing_invoices" edge. +func HasBillingInvoices() predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, BillingInvoicesTable, BillingInvoicesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBillingInvoicesWith applies the HasEdge predicate on the "billing_invoices" edge with a given conditions (other predicates). +func HasBillingInvoicesWith(preds ...predicate.BillingInvoice) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(func(s *sql.Selector) { + step := newBillingInvoicesStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasBillingProfile applies the HasEdge predicate on the "billing_profile" edge. +func HasBillingProfile() predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, BillingProfileTable, BillingProfileColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBillingProfileWith applies the HasEdge predicate on the "billing_profile" edge with a given conditions (other predicates). +func HasBillingProfileWith(preds ...predicate.BillingProfile) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(func(s *sql.Selector) { + step := newBillingProfileStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasTaxCode applies the HasEdge predicate on the "tax_code" edge. +func HasTaxCode() predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, TaxCodeTable, TaxCodeColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTaxCodeWith applies the HasEdge predicate on the "tax_code" edge with a given conditions (other predicates). +func HasTaxCodeWith(preds ...predicate.TaxCode) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(func(s *sql.Selector) { + step := newTaxCodeStep() + 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.BillingWorkflowConfig) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.BillingWorkflowConfig) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.BillingWorkflowConfig) predicate.BillingWorkflowConfig { + return predicate.BillingWorkflowConfig(sql.NotPredicates(p)) +} diff --git a/ent/db/billingworkflowconfig_create.go b/ent/db/billingworkflowconfig_create.go new file mode 100644 index 0000000000000000000000000000000000000000..82c59f130346cdba631c9ca4c52f3e47e878335f --- /dev/null +++ b/ent/db/billingworkflowconfig_create.go @@ -0,0 +1,1647 @@ +// 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/billing" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingprofile" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingworkflowconfig" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/datetime" +) + +// BillingWorkflowConfigCreate is the builder for creating a BillingWorkflowConfig entity. +type BillingWorkflowConfigCreate struct { + config + mutation *BillingWorkflowConfigMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *BillingWorkflowConfigCreate) SetNamespace(v string) *BillingWorkflowConfigCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *BillingWorkflowConfigCreate) SetCreatedAt(v time.Time) *BillingWorkflowConfigCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *BillingWorkflowConfigCreate) SetNillableCreatedAt(v *time.Time) *BillingWorkflowConfigCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *BillingWorkflowConfigCreate) SetUpdatedAt(v time.Time) *BillingWorkflowConfigCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *BillingWorkflowConfigCreate) SetNillableUpdatedAt(v *time.Time) *BillingWorkflowConfigCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *BillingWorkflowConfigCreate) SetDeletedAt(v time.Time) *BillingWorkflowConfigCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *BillingWorkflowConfigCreate) SetNillableDeletedAt(v *time.Time) *BillingWorkflowConfigCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (_c *BillingWorkflowConfigCreate) SetTaxCodeID(v string) *BillingWorkflowConfigCreate { + _c.mutation.SetTaxCodeID(v) + return _c +} + +// SetNillableTaxCodeID sets the "tax_code_id" field if the given value is not nil. +func (_c *BillingWorkflowConfigCreate) SetNillableTaxCodeID(v *string) *BillingWorkflowConfigCreate { + if v != nil { + _c.SetTaxCodeID(*v) + } + return _c +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (_c *BillingWorkflowConfigCreate) SetTaxBehavior(v productcatalog.TaxBehavior) *BillingWorkflowConfigCreate { + _c.mutation.SetTaxBehavior(v) + return _c +} + +// SetNillableTaxBehavior sets the "tax_behavior" field if the given value is not nil. +func (_c *BillingWorkflowConfigCreate) SetNillableTaxBehavior(v *productcatalog.TaxBehavior) *BillingWorkflowConfigCreate { + if v != nil { + _c.SetTaxBehavior(*v) + } + return _c +} + +// SetCollectionAlignment sets the "collection_alignment" field. +func (_c *BillingWorkflowConfigCreate) SetCollectionAlignment(v billing.AlignmentKind) *BillingWorkflowConfigCreate { + _c.mutation.SetCollectionAlignment(v) + return _c +} + +// SetAnchoredAlignmentDetail sets the "anchored_alignment_detail" field. +func (_c *BillingWorkflowConfigCreate) SetAnchoredAlignmentDetail(v *billing.AnchoredAlignmentDetail) *BillingWorkflowConfigCreate { + _c.mutation.SetAnchoredAlignmentDetail(v) + return _c +} + +// SetLineCollectionPeriod sets the "line_collection_period" field. +func (_c *BillingWorkflowConfigCreate) SetLineCollectionPeriod(v datetime.ISODurationString) *BillingWorkflowConfigCreate { + _c.mutation.SetLineCollectionPeriod(v) + return _c +} + +// SetInvoiceAutoAdvance sets the "invoice_auto_advance" field. +func (_c *BillingWorkflowConfigCreate) SetInvoiceAutoAdvance(v bool) *BillingWorkflowConfigCreate { + _c.mutation.SetInvoiceAutoAdvance(v) + return _c +} + +// SetInvoiceDraftPeriod sets the "invoice_draft_period" field. +func (_c *BillingWorkflowConfigCreate) SetInvoiceDraftPeriod(v datetime.ISODurationString) *BillingWorkflowConfigCreate { + _c.mutation.SetInvoiceDraftPeriod(v) + return _c +} + +// SetInvoiceDueAfter sets the "invoice_due_after" field. +func (_c *BillingWorkflowConfigCreate) SetInvoiceDueAfter(v datetime.ISODurationString) *BillingWorkflowConfigCreate { + _c.mutation.SetInvoiceDueAfter(v) + return _c +} + +// SetInvoiceCollectionMethod sets the "invoice_collection_method" field. +func (_c *BillingWorkflowConfigCreate) SetInvoiceCollectionMethod(v billing.CollectionMethod) *BillingWorkflowConfigCreate { + _c.mutation.SetInvoiceCollectionMethod(v) + return _c +} + +// SetInvoiceProgressiveBilling sets the "invoice_progressive_billing" field. +func (_c *BillingWorkflowConfigCreate) SetInvoiceProgressiveBilling(v bool) *BillingWorkflowConfigCreate { + _c.mutation.SetInvoiceProgressiveBilling(v) + return _c +} + +// SetSubscriptionEndProrationMode sets the "subscription_end_proration_mode" field. +func (_c *BillingWorkflowConfigCreate) SetSubscriptionEndProrationMode(v billing.SubscriptionEndProrationMode) *BillingWorkflowConfigCreate { + _c.mutation.SetSubscriptionEndProrationMode(v) + return _c +} + +// SetNillableSubscriptionEndProrationMode sets the "subscription_end_proration_mode" field if the given value is not nil. +func (_c *BillingWorkflowConfigCreate) SetNillableSubscriptionEndProrationMode(v *billing.SubscriptionEndProrationMode) *BillingWorkflowConfigCreate { + if v != nil { + _c.SetSubscriptionEndProrationMode(*v) + } + return _c +} + +// SetInvoiceDefaultTaxSettings sets the "invoice_default_tax_settings" field. +func (_c *BillingWorkflowConfigCreate) SetInvoiceDefaultTaxSettings(v productcatalog.TaxConfig) *BillingWorkflowConfigCreate { + _c.mutation.SetInvoiceDefaultTaxSettings(v) + return _c +} + +// SetNillableInvoiceDefaultTaxSettings sets the "invoice_default_tax_settings" field if the given value is not nil. +func (_c *BillingWorkflowConfigCreate) SetNillableInvoiceDefaultTaxSettings(v *productcatalog.TaxConfig) *BillingWorkflowConfigCreate { + if v != nil { + _c.SetInvoiceDefaultTaxSettings(*v) + } + return _c +} + +// SetTaxEnabled sets the "tax_enabled" field. +func (_c *BillingWorkflowConfigCreate) SetTaxEnabled(v bool) *BillingWorkflowConfigCreate { + _c.mutation.SetTaxEnabled(v) + return _c +} + +// SetNillableTaxEnabled sets the "tax_enabled" field if the given value is not nil. +func (_c *BillingWorkflowConfigCreate) SetNillableTaxEnabled(v *bool) *BillingWorkflowConfigCreate { + if v != nil { + _c.SetTaxEnabled(*v) + } + return _c +} + +// SetTaxEnforced sets the "tax_enforced" field. +func (_c *BillingWorkflowConfigCreate) SetTaxEnforced(v bool) *BillingWorkflowConfigCreate { + _c.mutation.SetTaxEnforced(v) + return _c +} + +// SetNillableTaxEnforced sets the "tax_enforced" field if the given value is not nil. +func (_c *BillingWorkflowConfigCreate) SetNillableTaxEnforced(v *bool) *BillingWorkflowConfigCreate { + if v != nil { + _c.SetTaxEnforced(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *BillingWorkflowConfigCreate) SetID(v string) *BillingWorkflowConfigCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *BillingWorkflowConfigCreate) SetNillableID(v *string) *BillingWorkflowConfigCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetBillingInvoicesID sets the "billing_invoices" edge to the BillingInvoice entity by ID. +func (_c *BillingWorkflowConfigCreate) SetBillingInvoicesID(id string) *BillingWorkflowConfigCreate { + _c.mutation.SetBillingInvoicesID(id) + return _c +} + +// SetNillableBillingInvoicesID sets the "billing_invoices" edge to the BillingInvoice entity by ID if the given value is not nil. +func (_c *BillingWorkflowConfigCreate) SetNillableBillingInvoicesID(id *string) *BillingWorkflowConfigCreate { + if id != nil { + _c = _c.SetBillingInvoicesID(*id) + } + return _c +} + +// SetBillingInvoices sets the "billing_invoices" edge to the BillingInvoice entity. +func (_c *BillingWorkflowConfigCreate) SetBillingInvoices(v *BillingInvoice) *BillingWorkflowConfigCreate { + return _c.SetBillingInvoicesID(v.ID) +} + +// SetBillingProfileID sets the "billing_profile" edge to the BillingProfile entity by ID. +func (_c *BillingWorkflowConfigCreate) SetBillingProfileID(id string) *BillingWorkflowConfigCreate { + _c.mutation.SetBillingProfileID(id) + return _c +} + +// SetNillableBillingProfileID sets the "billing_profile" edge to the BillingProfile entity by ID if the given value is not nil. +func (_c *BillingWorkflowConfigCreate) SetNillableBillingProfileID(id *string) *BillingWorkflowConfigCreate { + if id != nil { + _c = _c.SetBillingProfileID(*id) + } + return _c +} + +// SetBillingProfile sets the "billing_profile" edge to the BillingProfile entity. +func (_c *BillingWorkflowConfigCreate) SetBillingProfile(v *BillingProfile) *BillingWorkflowConfigCreate { + return _c.SetBillingProfileID(v.ID) +} + +// SetTaxCode sets the "tax_code" edge to the TaxCode entity. +func (_c *BillingWorkflowConfigCreate) SetTaxCode(v *TaxCode) *BillingWorkflowConfigCreate { + return _c.SetTaxCodeID(v.ID) +} + +// Mutation returns the BillingWorkflowConfigMutation object of the builder. +func (_c *BillingWorkflowConfigCreate) Mutation() *BillingWorkflowConfigMutation { + return _c.mutation +} + +// Save creates the BillingWorkflowConfig in the database. +func (_c *BillingWorkflowConfigCreate) Save(ctx context.Context) (*BillingWorkflowConfig, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *BillingWorkflowConfigCreate) SaveX(ctx context.Context) *BillingWorkflowConfig { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingWorkflowConfigCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingWorkflowConfigCreate) 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 *BillingWorkflowConfigCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := billingworkflowconfig.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := billingworkflowconfig.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.SubscriptionEndProrationMode(); !ok { + v := billingworkflowconfig.DefaultSubscriptionEndProrationMode + _c.mutation.SetSubscriptionEndProrationMode(v) + } + if _, ok := _c.mutation.TaxEnabled(); !ok { + v := billingworkflowconfig.DefaultTaxEnabled + _c.mutation.SetTaxEnabled(v) + } + if _, ok := _c.mutation.TaxEnforced(); !ok { + v := billingworkflowconfig.DefaultTaxEnforced + _c.mutation.SetTaxEnforced(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := billingworkflowconfig.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *BillingWorkflowConfigCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "BillingWorkflowConfig.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := billingworkflowconfig.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "BillingWorkflowConfig.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "BillingWorkflowConfig.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "BillingWorkflowConfig.updated_at"`)} + } + if v, ok := _c.mutation.TaxBehavior(); ok { + if err := billingworkflowconfig.TaxBehaviorValidator(v); err != nil { + return &ValidationError{Name: "tax_behavior", err: fmt.Errorf(`db: validator failed for field "BillingWorkflowConfig.tax_behavior": %w`, err)} + } + } + if _, ok := _c.mutation.CollectionAlignment(); !ok { + return &ValidationError{Name: "collection_alignment", err: errors.New(`db: missing required field "BillingWorkflowConfig.collection_alignment"`)} + } + if v, ok := _c.mutation.CollectionAlignment(); ok { + if err := billingworkflowconfig.CollectionAlignmentValidator(v); err != nil { + return &ValidationError{Name: "collection_alignment", err: fmt.Errorf(`db: validator failed for field "BillingWorkflowConfig.collection_alignment": %w`, err)} + } + } + if v, ok := _c.mutation.AnchoredAlignmentDetail(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "anchored_alignment_detail", err: fmt.Errorf(`db: validator failed for field "BillingWorkflowConfig.anchored_alignment_detail": %w`, err)} + } + } + if _, ok := _c.mutation.LineCollectionPeriod(); !ok { + return &ValidationError{Name: "line_collection_period", err: errors.New(`db: missing required field "BillingWorkflowConfig.line_collection_period"`)} + } + if _, ok := _c.mutation.InvoiceAutoAdvance(); !ok { + return &ValidationError{Name: "invoice_auto_advance", err: errors.New(`db: missing required field "BillingWorkflowConfig.invoice_auto_advance"`)} + } + if _, ok := _c.mutation.InvoiceDraftPeriod(); !ok { + return &ValidationError{Name: "invoice_draft_period", err: errors.New(`db: missing required field "BillingWorkflowConfig.invoice_draft_period"`)} + } + if _, ok := _c.mutation.InvoiceDueAfter(); !ok { + return &ValidationError{Name: "invoice_due_after", err: errors.New(`db: missing required field "BillingWorkflowConfig.invoice_due_after"`)} + } + if _, ok := _c.mutation.InvoiceCollectionMethod(); !ok { + return &ValidationError{Name: "invoice_collection_method", err: errors.New(`db: missing required field "BillingWorkflowConfig.invoice_collection_method"`)} + } + if v, ok := _c.mutation.InvoiceCollectionMethod(); ok { + if err := billingworkflowconfig.InvoiceCollectionMethodValidator(v); err != nil { + return &ValidationError{Name: "invoice_collection_method", err: fmt.Errorf(`db: validator failed for field "BillingWorkflowConfig.invoice_collection_method": %w`, err)} + } + } + if _, ok := _c.mutation.InvoiceProgressiveBilling(); !ok { + return &ValidationError{Name: "invoice_progressive_billing", err: errors.New(`db: missing required field "BillingWorkflowConfig.invoice_progressive_billing"`)} + } + if _, ok := _c.mutation.SubscriptionEndProrationMode(); !ok { + return &ValidationError{Name: "subscription_end_proration_mode", err: errors.New(`db: missing required field "BillingWorkflowConfig.subscription_end_proration_mode"`)} + } + if v, ok := _c.mutation.SubscriptionEndProrationMode(); ok { + if err := billingworkflowconfig.SubscriptionEndProrationModeValidator(v); err != nil { + return &ValidationError{Name: "subscription_end_proration_mode", err: fmt.Errorf(`db: validator failed for field "BillingWorkflowConfig.subscription_end_proration_mode": %w`, err)} + } + } + if v, ok := _c.mutation.InvoiceDefaultTaxSettings(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "invoice_default_tax_settings", err: fmt.Errorf(`db: validator failed for field "BillingWorkflowConfig.invoice_default_tax_settings": %w`, err)} + } + } + if _, ok := _c.mutation.TaxEnabled(); !ok { + return &ValidationError{Name: "tax_enabled", err: errors.New(`db: missing required field "BillingWorkflowConfig.tax_enabled"`)} + } + if _, ok := _c.mutation.TaxEnforced(); !ok { + return &ValidationError{Name: "tax_enforced", err: errors.New(`db: missing required field "BillingWorkflowConfig.tax_enforced"`)} + } + return nil +} + +func (_c *BillingWorkflowConfigCreate) sqlSave(ctx context.Context) (*BillingWorkflowConfig, 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 BillingWorkflowConfig.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *BillingWorkflowConfigCreate) createSpec() (*BillingWorkflowConfig, *sqlgraph.CreateSpec) { + var ( + _node = &BillingWorkflowConfig{config: _c.config} + _spec = sqlgraph.NewCreateSpec(billingworkflowconfig.Table, sqlgraph.NewFieldSpec(billingworkflowconfig.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(billingworkflowconfig.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(billingworkflowconfig.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(billingworkflowconfig.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(billingworkflowconfig.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.TaxBehavior(); ok { + _spec.SetField(billingworkflowconfig.FieldTaxBehavior, field.TypeEnum, value) + _node.TaxBehavior = &value + } + if value, ok := _c.mutation.CollectionAlignment(); ok { + _spec.SetField(billingworkflowconfig.FieldCollectionAlignment, field.TypeEnum, value) + _node.CollectionAlignment = value + } + if value, ok := _c.mutation.AnchoredAlignmentDetail(); ok { + _spec.SetField(billingworkflowconfig.FieldAnchoredAlignmentDetail, field.TypeJSON, value) + _node.AnchoredAlignmentDetail = value + } + if value, ok := _c.mutation.LineCollectionPeriod(); ok { + _spec.SetField(billingworkflowconfig.FieldLineCollectionPeriod, field.TypeString, value) + _node.LineCollectionPeriod = value + } + if value, ok := _c.mutation.InvoiceAutoAdvance(); ok { + _spec.SetField(billingworkflowconfig.FieldInvoiceAutoAdvance, field.TypeBool, value) + _node.InvoiceAutoAdvance = value + } + if value, ok := _c.mutation.InvoiceDraftPeriod(); ok { + _spec.SetField(billingworkflowconfig.FieldInvoiceDraftPeriod, field.TypeString, value) + _node.InvoiceDraftPeriod = value + } + if value, ok := _c.mutation.InvoiceDueAfter(); ok { + _spec.SetField(billingworkflowconfig.FieldInvoiceDueAfter, field.TypeString, value) + _node.InvoiceDueAfter = value + } + if value, ok := _c.mutation.InvoiceCollectionMethod(); ok { + _spec.SetField(billingworkflowconfig.FieldInvoiceCollectionMethod, field.TypeEnum, value) + _node.InvoiceCollectionMethod = value + } + if value, ok := _c.mutation.InvoiceProgressiveBilling(); ok { + _spec.SetField(billingworkflowconfig.FieldInvoiceProgressiveBilling, field.TypeBool, value) + _node.InvoiceProgressiveBilling = value + } + if value, ok := _c.mutation.SubscriptionEndProrationMode(); ok { + _spec.SetField(billingworkflowconfig.FieldSubscriptionEndProrationMode, field.TypeEnum, value) + _node.SubscriptionEndProrationMode = value + } + if value, ok := _c.mutation.InvoiceDefaultTaxSettings(); ok { + _spec.SetField(billingworkflowconfig.FieldInvoiceDefaultTaxSettings, field.TypeJSON, value) + _node.InvoiceDefaultTaxSettings = value + } + if value, ok := _c.mutation.TaxEnabled(); ok { + _spec.SetField(billingworkflowconfig.FieldTaxEnabled, field.TypeBool, value) + _node.TaxEnabled = value + } + if value, ok := _c.mutation.TaxEnforced(); ok { + _spec.SetField(billingworkflowconfig.FieldTaxEnforced, field.TypeBool, value) + _node.TaxEnforced = value + } + if nodes := _c.mutation.BillingInvoicesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: billingworkflowconfig.BillingInvoicesTable, + Columns: []string{billingworkflowconfig.BillingInvoicesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.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.BillingProfileIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: billingworkflowconfig.BillingProfileTable, + Columns: []string{billingworkflowconfig.BillingProfileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingprofile.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.TaxCodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingworkflowconfig.TaxCodeTable, + Columns: []string{billingworkflowconfig.TaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.TaxCodeID = &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.BillingWorkflowConfig.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.BillingWorkflowConfigUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *BillingWorkflowConfigCreate) OnConflict(opts ...sql.ConflictOption) *BillingWorkflowConfigUpsertOne { + _c.conflict = opts + return &BillingWorkflowConfigUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingWorkflowConfig.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingWorkflowConfigCreate) OnConflictColumns(columns ...string) *BillingWorkflowConfigUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingWorkflowConfigUpsertOne{ + create: _c, + } +} + +type ( + // BillingWorkflowConfigUpsertOne is the builder for "upsert"-ing + // one BillingWorkflowConfig node. + BillingWorkflowConfigUpsertOne struct { + create *BillingWorkflowConfigCreate + } + + // BillingWorkflowConfigUpsert is the "OnConflict" setter. + BillingWorkflowConfigUpsert struct { + *sql.UpdateSet + } +) + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingWorkflowConfigUpsert) SetUpdatedAt(v time.Time) *BillingWorkflowConfigUpsert { + u.Set(billingworkflowconfig.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsert) UpdateUpdatedAt() *BillingWorkflowConfigUpsert { + u.SetExcluded(billingworkflowconfig.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingWorkflowConfigUpsert) SetDeletedAt(v time.Time) *BillingWorkflowConfigUpsert { + u.Set(billingworkflowconfig.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsert) UpdateDeletedAt() *BillingWorkflowConfigUpsert { + u.SetExcluded(billingworkflowconfig.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingWorkflowConfigUpsert) ClearDeletedAt() *BillingWorkflowConfigUpsert { + u.SetNull(billingworkflowconfig.FieldDeletedAt) + return u +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (u *BillingWorkflowConfigUpsert) SetTaxCodeID(v string) *BillingWorkflowConfigUpsert { + u.Set(billingworkflowconfig.FieldTaxCodeID, v) + return u +} + +// UpdateTaxCodeID sets the "tax_code_id" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsert) UpdateTaxCodeID() *BillingWorkflowConfigUpsert { + u.SetExcluded(billingworkflowconfig.FieldTaxCodeID) + return u +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (u *BillingWorkflowConfigUpsert) ClearTaxCodeID() *BillingWorkflowConfigUpsert { + u.SetNull(billingworkflowconfig.FieldTaxCodeID) + return u +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (u *BillingWorkflowConfigUpsert) SetTaxBehavior(v productcatalog.TaxBehavior) *BillingWorkflowConfigUpsert { + u.Set(billingworkflowconfig.FieldTaxBehavior, v) + return u +} + +// UpdateTaxBehavior sets the "tax_behavior" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsert) UpdateTaxBehavior() *BillingWorkflowConfigUpsert { + u.SetExcluded(billingworkflowconfig.FieldTaxBehavior) + return u +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (u *BillingWorkflowConfigUpsert) ClearTaxBehavior() *BillingWorkflowConfigUpsert { + u.SetNull(billingworkflowconfig.FieldTaxBehavior) + return u +} + +// SetCollectionAlignment sets the "collection_alignment" field. +func (u *BillingWorkflowConfigUpsert) SetCollectionAlignment(v billing.AlignmentKind) *BillingWorkflowConfigUpsert { + u.Set(billingworkflowconfig.FieldCollectionAlignment, v) + return u +} + +// UpdateCollectionAlignment sets the "collection_alignment" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsert) UpdateCollectionAlignment() *BillingWorkflowConfigUpsert { + u.SetExcluded(billingworkflowconfig.FieldCollectionAlignment) + return u +} + +// SetAnchoredAlignmentDetail sets the "anchored_alignment_detail" field. +func (u *BillingWorkflowConfigUpsert) SetAnchoredAlignmentDetail(v *billing.AnchoredAlignmentDetail) *BillingWorkflowConfigUpsert { + u.Set(billingworkflowconfig.FieldAnchoredAlignmentDetail, v) + return u +} + +// UpdateAnchoredAlignmentDetail sets the "anchored_alignment_detail" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsert) UpdateAnchoredAlignmentDetail() *BillingWorkflowConfigUpsert { + u.SetExcluded(billingworkflowconfig.FieldAnchoredAlignmentDetail) + return u +} + +// ClearAnchoredAlignmentDetail clears the value of the "anchored_alignment_detail" field. +func (u *BillingWorkflowConfigUpsert) ClearAnchoredAlignmentDetail() *BillingWorkflowConfigUpsert { + u.SetNull(billingworkflowconfig.FieldAnchoredAlignmentDetail) + return u +} + +// SetLineCollectionPeriod sets the "line_collection_period" field. +func (u *BillingWorkflowConfigUpsert) SetLineCollectionPeriod(v datetime.ISODurationString) *BillingWorkflowConfigUpsert { + u.Set(billingworkflowconfig.FieldLineCollectionPeriod, v) + return u +} + +// UpdateLineCollectionPeriod sets the "line_collection_period" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsert) UpdateLineCollectionPeriod() *BillingWorkflowConfigUpsert { + u.SetExcluded(billingworkflowconfig.FieldLineCollectionPeriod) + return u +} + +// SetInvoiceAutoAdvance sets the "invoice_auto_advance" field. +func (u *BillingWorkflowConfigUpsert) SetInvoiceAutoAdvance(v bool) *BillingWorkflowConfigUpsert { + u.Set(billingworkflowconfig.FieldInvoiceAutoAdvance, v) + return u +} + +// UpdateInvoiceAutoAdvance sets the "invoice_auto_advance" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsert) UpdateInvoiceAutoAdvance() *BillingWorkflowConfigUpsert { + u.SetExcluded(billingworkflowconfig.FieldInvoiceAutoAdvance) + return u +} + +// SetInvoiceDraftPeriod sets the "invoice_draft_period" field. +func (u *BillingWorkflowConfigUpsert) SetInvoiceDraftPeriod(v datetime.ISODurationString) *BillingWorkflowConfigUpsert { + u.Set(billingworkflowconfig.FieldInvoiceDraftPeriod, v) + return u +} + +// UpdateInvoiceDraftPeriod sets the "invoice_draft_period" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsert) UpdateInvoiceDraftPeriod() *BillingWorkflowConfigUpsert { + u.SetExcluded(billingworkflowconfig.FieldInvoiceDraftPeriod) + return u +} + +// SetInvoiceDueAfter sets the "invoice_due_after" field. +func (u *BillingWorkflowConfigUpsert) SetInvoiceDueAfter(v datetime.ISODurationString) *BillingWorkflowConfigUpsert { + u.Set(billingworkflowconfig.FieldInvoiceDueAfter, v) + return u +} + +// UpdateInvoiceDueAfter sets the "invoice_due_after" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsert) UpdateInvoiceDueAfter() *BillingWorkflowConfigUpsert { + u.SetExcluded(billingworkflowconfig.FieldInvoiceDueAfter) + return u +} + +// SetInvoiceCollectionMethod sets the "invoice_collection_method" field. +func (u *BillingWorkflowConfigUpsert) SetInvoiceCollectionMethod(v billing.CollectionMethod) *BillingWorkflowConfigUpsert { + u.Set(billingworkflowconfig.FieldInvoiceCollectionMethod, v) + return u +} + +// UpdateInvoiceCollectionMethod sets the "invoice_collection_method" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsert) UpdateInvoiceCollectionMethod() *BillingWorkflowConfigUpsert { + u.SetExcluded(billingworkflowconfig.FieldInvoiceCollectionMethod) + return u +} + +// SetInvoiceProgressiveBilling sets the "invoice_progressive_billing" field. +func (u *BillingWorkflowConfigUpsert) SetInvoiceProgressiveBilling(v bool) *BillingWorkflowConfigUpsert { + u.Set(billingworkflowconfig.FieldInvoiceProgressiveBilling, v) + return u +} + +// UpdateInvoiceProgressiveBilling sets the "invoice_progressive_billing" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsert) UpdateInvoiceProgressiveBilling() *BillingWorkflowConfigUpsert { + u.SetExcluded(billingworkflowconfig.FieldInvoiceProgressiveBilling) + return u +} + +// SetSubscriptionEndProrationMode sets the "subscription_end_proration_mode" field. +func (u *BillingWorkflowConfigUpsert) SetSubscriptionEndProrationMode(v billing.SubscriptionEndProrationMode) *BillingWorkflowConfigUpsert { + u.Set(billingworkflowconfig.FieldSubscriptionEndProrationMode, v) + return u +} + +// UpdateSubscriptionEndProrationMode sets the "subscription_end_proration_mode" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsert) UpdateSubscriptionEndProrationMode() *BillingWorkflowConfigUpsert { + u.SetExcluded(billingworkflowconfig.FieldSubscriptionEndProrationMode) + return u +} + +// SetInvoiceDefaultTaxSettings sets the "invoice_default_tax_settings" field. +func (u *BillingWorkflowConfigUpsert) SetInvoiceDefaultTaxSettings(v productcatalog.TaxConfig) *BillingWorkflowConfigUpsert { + u.Set(billingworkflowconfig.FieldInvoiceDefaultTaxSettings, v) + return u +} + +// UpdateInvoiceDefaultTaxSettings sets the "invoice_default_tax_settings" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsert) UpdateInvoiceDefaultTaxSettings() *BillingWorkflowConfigUpsert { + u.SetExcluded(billingworkflowconfig.FieldInvoiceDefaultTaxSettings) + return u +} + +// ClearInvoiceDefaultTaxSettings clears the value of the "invoice_default_tax_settings" field. +func (u *BillingWorkflowConfigUpsert) ClearInvoiceDefaultTaxSettings() *BillingWorkflowConfigUpsert { + u.SetNull(billingworkflowconfig.FieldInvoiceDefaultTaxSettings) + return u +} + +// SetTaxEnabled sets the "tax_enabled" field. +func (u *BillingWorkflowConfigUpsert) SetTaxEnabled(v bool) *BillingWorkflowConfigUpsert { + u.Set(billingworkflowconfig.FieldTaxEnabled, v) + return u +} + +// UpdateTaxEnabled sets the "tax_enabled" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsert) UpdateTaxEnabled() *BillingWorkflowConfigUpsert { + u.SetExcluded(billingworkflowconfig.FieldTaxEnabled) + return u +} + +// SetTaxEnforced sets the "tax_enforced" field. +func (u *BillingWorkflowConfigUpsert) SetTaxEnforced(v bool) *BillingWorkflowConfigUpsert { + u.Set(billingworkflowconfig.FieldTaxEnforced, v) + return u +} + +// UpdateTaxEnforced sets the "tax_enforced" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsert) UpdateTaxEnforced() *BillingWorkflowConfigUpsert { + u.SetExcluded(billingworkflowconfig.FieldTaxEnforced) + 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.BillingWorkflowConfig.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(billingworkflowconfig.FieldID) +// }), +// ). +// Exec(ctx) +func (u *BillingWorkflowConfigUpsertOne) UpdateNewValues() *BillingWorkflowConfigUpsertOne { + 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(billingworkflowconfig.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(billingworkflowconfig.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(billingworkflowconfig.FieldCreatedAt) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingWorkflowConfig.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingWorkflowConfigUpsertOne) Ignore() *BillingWorkflowConfigUpsertOne { + 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 *BillingWorkflowConfigUpsertOne) DoNothing() *BillingWorkflowConfigUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingWorkflowConfigCreate.OnConflict +// documentation for more info. +func (u *BillingWorkflowConfigUpsertOne) Update(set func(*BillingWorkflowConfigUpsert)) *BillingWorkflowConfigUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingWorkflowConfigUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingWorkflowConfigUpsertOne) SetUpdatedAt(v time.Time) *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertOne) UpdateUpdatedAt() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingWorkflowConfigUpsertOne) SetDeletedAt(v time.Time) *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertOne) UpdateDeletedAt() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingWorkflowConfigUpsertOne) ClearDeletedAt() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.ClearDeletedAt() + }) +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (u *BillingWorkflowConfigUpsertOne) SetTaxCodeID(v string) *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetTaxCodeID(v) + }) +} + +// UpdateTaxCodeID sets the "tax_code_id" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertOne) UpdateTaxCodeID() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateTaxCodeID() + }) +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (u *BillingWorkflowConfigUpsertOne) ClearTaxCodeID() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.ClearTaxCodeID() + }) +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (u *BillingWorkflowConfigUpsertOne) SetTaxBehavior(v productcatalog.TaxBehavior) *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetTaxBehavior(v) + }) +} + +// UpdateTaxBehavior sets the "tax_behavior" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertOne) UpdateTaxBehavior() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateTaxBehavior() + }) +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (u *BillingWorkflowConfigUpsertOne) ClearTaxBehavior() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.ClearTaxBehavior() + }) +} + +// SetCollectionAlignment sets the "collection_alignment" field. +func (u *BillingWorkflowConfigUpsertOne) SetCollectionAlignment(v billing.AlignmentKind) *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetCollectionAlignment(v) + }) +} + +// UpdateCollectionAlignment sets the "collection_alignment" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertOne) UpdateCollectionAlignment() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateCollectionAlignment() + }) +} + +// SetAnchoredAlignmentDetail sets the "anchored_alignment_detail" field. +func (u *BillingWorkflowConfigUpsertOne) SetAnchoredAlignmentDetail(v *billing.AnchoredAlignmentDetail) *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetAnchoredAlignmentDetail(v) + }) +} + +// UpdateAnchoredAlignmentDetail sets the "anchored_alignment_detail" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertOne) UpdateAnchoredAlignmentDetail() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateAnchoredAlignmentDetail() + }) +} + +// ClearAnchoredAlignmentDetail clears the value of the "anchored_alignment_detail" field. +func (u *BillingWorkflowConfigUpsertOne) ClearAnchoredAlignmentDetail() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.ClearAnchoredAlignmentDetail() + }) +} + +// SetLineCollectionPeriod sets the "line_collection_period" field. +func (u *BillingWorkflowConfigUpsertOne) SetLineCollectionPeriod(v datetime.ISODurationString) *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetLineCollectionPeriod(v) + }) +} + +// UpdateLineCollectionPeriod sets the "line_collection_period" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertOne) UpdateLineCollectionPeriod() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateLineCollectionPeriod() + }) +} + +// SetInvoiceAutoAdvance sets the "invoice_auto_advance" field. +func (u *BillingWorkflowConfigUpsertOne) SetInvoiceAutoAdvance(v bool) *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetInvoiceAutoAdvance(v) + }) +} + +// UpdateInvoiceAutoAdvance sets the "invoice_auto_advance" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertOne) UpdateInvoiceAutoAdvance() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateInvoiceAutoAdvance() + }) +} + +// SetInvoiceDraftPeriod sets the "invoice_draft_period" field. +func (u *BillingWorkflowConfigUpsertOne) SetInvoiceDraftPeriod(v datetime.ISODurationString) *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetInvoiceDraftPeriod(v) + }) +} + +// UpdateInvoiceDraftPeriod sets the "invoice_draft_period" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertOne) UpdateInvoiceDraftPeriod() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateInvoiceDraftPeriod() + }) +} + +// SetInvoiceDueAfter sets the "invoice_due_after" field. +func (u *BillingWorkflowConfigUpsertOne) SetInvoiceDueAfter(v datetime.ISODurationString) *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetInvoiceDueAfter(v) + }) +} + +// UpdateInvoiceDueAfter sets the "invoice_due_after" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertOne) UpdateInvoiceDueAfter() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateInvoiceDueAfter() + }) +} + +// SetInvoiceCollectionMethod sets the "invoice_collection_method" field. +func (u *BillingWorkflowConfigUpsertOne) SetInvoiceCollectionMethod(v billing.CollectionMethod) *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetInvoiceCollectionMethod(v) + }) +} + +// UpdateInvoiceCollectionMethod sets the "invoice_collection_method" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertOne) UpdateInvoiceCollectionMethod() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateInvoiceCollectionMethod() + }) +} + +// SetInvoiceProgressiveBilling sets the "invoice_progressive_billing" field. +func (u *BillingWorkflowConfigUpsertOne) SetInvoiceProgressiveBilling(v bool) *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetInvoiceProgressiveBilling(v) + }) +} + +// UpdateInvoiceProgressiveBilling sets the "invoice_progressive_billing" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertOne) UpdateInvoiceProgressiveBilling() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateInvoiceProgressiveBilling() + }) +} + +// SetSubscriptionEndProrationMode sets the "subscription_end_proration_mode" field. +func (u *BillingWorkflowConfigUpsertOne) SetSubscriptionEndProrationMode(v billing.SubscriptionEndProrationMode) *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetSubscriptionEndProrationMode(v) + }) +} + +// UpdateSubscriptionEndProrationMode sets the "subscription_end_proration_mode" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertOne) UpdateSubscriptionEndProrationMode() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateSubscriptionEndProrationMode() + }) +} + +// SetInvoiceDefaultTaxSettings sets the "invoice_default_tax_settings" field. +func (u *BillingWorkflowConfigUpsertOne) SetInvoiceDefaultTaxSettings(v productcatalog.TaxConfig) *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetInvoiceDefaultTaxSettings(v) + }) +} + +// UpdateInvoiceDefaultTaxSettings sets the "invoice_default_tax_settings" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertOne) UpdateInvoiceDefaultTaxSettings() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateInvoiceDefaultTaxSettings() + }) +} + +// ClearInvoiceDefaultTaxSettings clears the value of the "invoice_default_tax_settings" field. +func (u *BillingWorkflowConfigUpsertOne) ClearInvoiceDefaultTaxSettings() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.ClearInvoiceDefaultTaxSettings() + }) +} + +// SetTaxEnabled sets the "tax_enabled" field. +func (u *BillingWorkflowConfigUpsertOne) SetTaxEnabled(v bool) *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetTaxEnabled(v) + }) +} + +// UpdateTaxEnabled sets the "tax_enabled" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertOne) UpdateTaxEnabled() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateTaxEnabled() + }) +} + +// SetTaxEnforced sets the "tax_enforced" field. +func (u *BillingWorkflowConfigUpsertOne) SetTaxEnforced(v bool) *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetTaxEnforced(v) + }) +} + +// UpdateTaxEnforced sets the "tax_enforced" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertOne) UpdateTaxEnforced() *BillingWorkflowConfigUpsertOne { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateTaxEnforced() + }) +} + +// Exec executes the query. +func (u *BillingWorkflowConfigUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingWorkflowConfigCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingWorkflowConfigUpsertOne) 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 *BillingWorkflowConfigUpsertOne) 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: BillingWorkflowConfigUpsertOne.ID is not supported by MySQL driver. Use BillingWorkflowConfigUpsertOne.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 *BillingWorkflowConfigUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// BillingWorkflowConfigCreateBulk is the builder for creating many BillingWorkflowConfig entities in bulk. +type BillingWorkflowConfigCreateBulk struct { + config + err error + builders []*BillingWorkflowConfigCreate + conflict []sql.ConflictOption +} + +// Save creates the BillingWorkflowConfig entities in the database. +func (_c *BillingWorkflowConfigCreateBulk) Save(ctx context.Context) ([]*BillingWorkflowConfig, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*BillingWorkflowConfig, 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.(*BillingWorkflowConfigMutation) + 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 *BillingWorkflowConfigCreateBulk) SaveX(ctx context.Context) []*BillingWorkflowConfig { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BillingWorkflowConfigCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BillingWorkflowConfigCreateBulk) 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.BillingWorkflowConfig.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.BillingWorkflowConfigUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *BillingWorkflowConfigCreateBulk) OnConflict(opts ...sql.ConflictOption) *BillingWorkflowConfigUpsertBulk { + _c.conflict = opts + return &BillingWorkflowConfigUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BillingWorkflowConfig.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BillingWorkflowConfigCreateBulk) OnConflictColumns(columns ...string) *BillingWorkflowConfigUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BillingWorkflowConfigUpsertBulk{ + create: _c, + } +} + +// BillingWorkflowConfigUpsertBulk is the builder for "upsert"-ing +// a bulk of BillingWorkflowConfig nodes. +type BillingWorkflowConfigUpsertBulk struct { + create *BillingWorkflowConfigCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.BillingWorkflowConfig.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(billingworkflowconfig.FieldID) +// }), +// ). +// Exec(ctx) +func (u *BillingWorkflowConfigUpsertBulk) UpdateNewValues() *BillingWorkflowConfigUpsertBulk { + 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(billingworkflowconfig.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(billingworkflowconfig.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(billingworkflowconfig.FieldCreatedAt) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BillingWorkflowConfig.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BillingWorkflowConfigUpsertBulk) Ignore() *BillingWorkflowConfigUpsertBulk { + 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 *BillingWorkflowConfigUpsertBulk) DoNothing() *BillingWorkflowConfigUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BillingWorkflowConfigCreateBulk.OnConflict +// documentation for more info. +func (u *BillingWorkflowConfigUpsertBulk) Update(set func(*BillingWorkflowConfigUpsert)) *BillingWorkflowConfigUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BillingWorkflowConfigUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *BillingWorkflowConfigUpsertBulk) SetUpdatedAt(v time.Time) *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertBulk) UpdateUpdatedAt() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *BillingWorkflowConfigUpsertBulk) SetDeletedAt(v time.Time) *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertBulk) UpdateDeletedAt() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *BillingWorkflowConfigUpsertBulk) ClearDeletedAt() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.ClearDeletedAt() + }) +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (u *BillingWorkflowConfigUpsertBulk) SetTaxCodeID(v string) *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetTaxCodeID(v) + }) +} + +// UpdateTaxCodeID sets the "tax_code_id" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertBulk) UpdateTaxCodeID() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateTaxCodeID() + }) +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (u *BillingWorkflowConfigUpsertBulk) ClearTaxCodeID() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.ClearTaxCodeID() + }) +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (u *BillingWorkflowConfigUpsertBulk) SetTaxBehavior(v productcatalog.TaxBehavior) *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetTaxBehavior(v) + }) +} + +// UpdateTaxBehavior sets the "tax_behavior" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertBulk) UpdateTaxBehavior() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateTaxBehavior() + }) +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (u *BillingWorkflowConfigUpsertBulk) ClearTaxBehavior() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.ClearTaxBehavior() + }) +} + +// SetCollectionAlignment sets the "collection_alignment" field. +func (u *BillingWorkflowConfigUpsertBulk) SetCollectionAlignment(v billing.AlignmentKind) *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetCollectionAlignment(v) + }) +} + +// UpdateCollectionAlignment sets the "collection_alignment" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertBulk) UpdateCollectionAlignment() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateCollectionAlignment() + }) +} + +// SetAnchoredAlignmentDetail sets the "anchored_alignment_detail" field. +func (u *BillingWorkflowConfigUpsertBulk) SetAnchoredAlignmentDetail(v *billing.AnchoredAlignmentDetail) *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetAnchoredAlignmentDetail(v) + }) +} + +// UpdateAnchoredAlignmentDetail sets the "anchored_alignment_detail" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertBulk) UpdateAnchoredAlignmentDetail() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateAnchoredAlignmentDetail() + }) +} + +// ClearAnchoredAlignmentDetail clears the value of the "anchored_alignment_detail" field. +func (u *BillingWorkflowConfigUpsertBulk) ClearAnchoredAlignmentDetail() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.ClearAnchoredAlignmentDetail() + }) +} + +// SetLineCollectionPeriod sets the "line_collection_period" field. +func (u *BillingWorkflowConfigUpsertBulk) SetLineCollectionPeriod(v datetime.ISODurationString) *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetLineCollectionPeriod(v) + }) +} + +// UpdateLineCollectionPeriod sets the "line_collection_period" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertBulk) UpdateLineCollectionPeriod() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateLineCollectionPeriod() + }) +} + +// SetInvoiceAutoAdvance sets the "invoice_auto_advance" field. +func (u *BillingWorkflowConfigUpsertBulk) SetInvoiceAutoAdvance(v bool) *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetInvoiceAutoAdvance(v) + }) +} + +// UpdateInvoiceAutoAdvance sets the "invoice_auto_advance" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertBulk) UpdateInvoiceAutoAdvance() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateInvoiceAutoAdvance() + }) +} + +// SetInvoiceDraftPeriod sets the "invoice_draft_period" field. +func (u *BillingWorkflowConfigUpsertBulk) SetInvoiceDraftPeriod(v datetime.ISODurationString) *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetInvoiceDraftPeriod(v) + }) +} + +// UpdateInvoiceDraftPeriod sets the "invoice_draft_period" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertBulk) UpdateInvoiceDraftPeriod() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateInvoiceDraftPeriod() + }) +} + +// SetInvoiceDueAfter sets the "invoice_due_after" field. +func (u *BillingWorkflowConfigUpsertBulk) SetInvoiceDueAfter(v datetime.ISODurationString) *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetInvoiceDueAfter(v) + }) +} + +// UpdateInvoiceDueAfter sets the "invoice_due_after" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertBulk) UpdateInvoiceDueAfter() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateInvoiceDueAfter() + }) +} + +// SetInvoiceCollectionMethod sets the "invoice_collection_method" field. +func (u *BillingWorkflowConfigUpsertBulk) SetInvoiceCollectionMethod(v billing.CollectionMethod) *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetInvoiceCollectionMethod(v) + }) +} + +// UpdateInvoiceCollectionMethod sets the "invoice_collection_method" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertBulk) UpdateInvoiceCollectionMethod() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateInvoiceCollectionMethod() + }) +} + +// SetInvoiceProgressiveBilling sets the "invoice_progressive_billing" field. +func (u *BillingWorkflowConfigUpsertBulk) SetInvoiceProgressiveBilling(v bool) *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetInvoiceProgressiveBilling(v) + }) +} + +// UpdateInvoiceProgressiveBilling sets the "invoice_progressive_billing" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertBulk) UpdateInvoiceProgressiveBilling() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateInvoiceProgressiveBilling() + }) +} + +// SetSubscriptionEndProrationMode sets the "subscription_end_proration_mode" field. +func (u *BillingWorkflowConfigUpsertBulk) SetSubscriptionEndProrationMode(v billing.SubscriptionEndProrationMode) *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetSubscriptionEndProrationMode(v) + }) +} + +// UpdateSubscriptionEndProrationMode sets the "subscription_end_proration_mode" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertBulk) UpdateSubscriptionEndProrationMode() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateSubscriptionEndProrationMode() + }) +} + +// SetInvoiceDefaultTaxSettings sets the "invoice_default_tax_settings" field. +func (u *BillingWorkflowConfigUpsertBulk) SetInvoiceDefaultTaxSettings(v productcatalog.TaxConfig) *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetInvoiceDefaultTaxSettings(v) + }) +} + +// UpdateInvoiceDefaultTaxSettings sets the "invoice_default_tax_settings" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertBulk) UpdateInvoiceDefaultTaxSettings() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateInvoiceDefaultTaxSettings() + }) +} + +// ClearInvoiceDefaultTaxSettings clears the value of the "invoice_default_tax_settings" field. +func (u *BillingWorkflowConfigUpsertBulk) ClearInvoiceDefaultTaxSettings() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.ClearInvoiceDefaultTaxSettings() + }) +} + +// SetTaxEnabled sets the "tax_enabled" field. +func (u *BillingWorkflowConfigUpsertBulk) SetTaxEnabled(v bool) *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetTaxEnabled(v) + }) +} + +// UpdateTaxEnabled sets the "tax_enabled" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertBulk) UpdateTaxEnabled() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateTaxEnabled() + }) +} + +// SetTaxEnforced sets the "tax_enforced" field. +func (u *BillingWorkflowConfigUpsertBulk) SetTaxEnforced(v bool) *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.SetTaxEnforced(v) + }) +} + +// UpdateTaxEnforced sets the "tax_enforced" field to the value that was provided on create. +func (u *BillingWorkflowConfigUpsertBulk) UpdateTaxEnforced() *BillingWorkflowConfigUpsertBulk { + return u.Update(func(s *BillingWorkflowConfigUpsert) { + s.UpdateTaxEnforced() + }) +} + +// Exec executes the query. +func (u *BillingWorkflowConfigUpsertBulk) 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 BillingWorkflowConfigCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for BillingWorkflowConfigCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BillingWorkflowConfigUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billingworkflowconfig_delete.go b/ent/db/billingworkflowconfig_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..31b440364415f058891465ec948a4fec2f0a4d0e --- /dev/null +++ b/ent/db/billingworkflowconfig_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/billingworkflowconfig" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// BillingWorkflowConfigDelete is the builder for deleting a BillingWorkflowConfig entity. +type BillingWorkflowConfigDelete struct { + config + hooks []Hook + mutation *BillingWorkflowConfigMutation +} + +// Where appends a list predicates to the BillingWorkflowConfigDelete builder. +func (_d *BillingWorkflowConfigDelete) Where(ps ...predicate.BillingWorkflowConfig) *BillingWorkflowConfigDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *BillingWorkflowConfigDelete) 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 *BillingWorkflowConfigDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *BillingWorkflowConfigDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(billingworkflowconfig.Table, sqlgraph.NewFieldSpec(billingworkflowconfig.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 +} + +// BillingWorkflowConfigDeleteOne is the builder for deleting a single BillingWorkflowConfig entity. +type BillingWorkflowConfigDeleteOne struct { + _d *BillingWorkflowConfigDelete +} + +// Where appends a list predicates to the BillingWorkflowConfigDelete builder. +func (_d *BillingWorkflowConfigDeleteOne) Where(ps ...predicate.BillingWorkflowConfig) *BillingWorkflowConfigDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *BillingWorkflowConfigDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{billingworkflowconfig.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *BillingWorkflowConfigDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/billingworkflowconfig_query.go b/ent/db/billingworkflowconfig_query.go new file mode 100644 index 0000000000000000000000000000000000000000..260c1714d6cb29d3bac48796c372ec50111d3f49 --- /dev/null +++ b/ent/db/billingworkflowconfig_query.go @@ -0,0 +1,787 @@ +// 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/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingprofile" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingworkflowconfig" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" +) + +// BillingWorkflowConfigQuery is the builder for querying BillingWorkflowConfig entities. +type BillingWorkflowConfigQuery struct { + config + ctx *QueryContext + order []billingworkflowconfig.OrderOption + inters []Interceptor + predicates []predicate.BillingWorkflowConfig + withBillingInvoices *BillingInvoiceQuery + withBillingProfile *BillingProfileQuery + withTaxCode *TaxCodeQuery + 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 BillingWorkflowConfigQuery builder. +func (_q *BillingWorkflowConfigQuery) Where(ps ...predicate.BillingWorkflowConfig) *BillingWorkflowConfigQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *BillingWorkflowConfigQuery) Limit(limit int) *BillingWorkflowConfigQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *BillingWorkflowConfigQuery) Offset(offset int) *BillingWorkflowConfigQuery { + _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 *BillingWorkflowConfigQuery) Unique(unique bool) *BillingWorkflowConfigQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *BillingWorkflowConfigQuery) Order(o ...billingworkflowconfig.OrderOption) *BillingWorkflowConfigQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryBillingInvoices chains the current query on the "billing_invoices" edge. +func (_q *BillingWorkflowConfigQuery) QueryBillingInvoices() *BillingInvoiceQuery { + query := (&BillingInvoiceClient{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(billingworkflowconfig.Table, billingworkflowconfig.FieldID, selector), + sqlgraph.To(billinginvoice.Table, billinginvoice.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, billingworkflowconfig.BillingInvoicesTable, billingworkflowconfig.BillingInvoicesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryBillingProfile chains the current query on the "billing_profile" edge. +func (_q *BillingWorkflowConfigQuery) QueryBillingProfile() *BillingProfileQuery { + query := (&BillingProfileClient{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(billingworkflowconfig.Table, billingworkflowconfig.FieldID, selector), + sqlgraph.To(billingprofile.Table, billingprofile.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, billingworkflowconfig.BillingProfileTable, billingworkflowconfig.BillingProfileColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryTaxCode chains the current query on the "tax_code" edge. +func (_q *BillingWorkflowConfigQuery) QueryTaxCode() *TaxCodeQuery { + query := (&TaxCodeClient{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(billingworkflowconfig.Table, billingworkflowconfig.FieldID, selector), + sqlgraph.To(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billingworkflowconfig.TaxCodeTable, billingworkflowconfig.TaxCodeColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first BillingWorkflowConfig entity from the query. +// Returns a *NotFoundError when no BillingWorkflowConfig was found. +func (_q *BillingWorkflowConfigQuery) First(ctx context.Context) (*BillingWorkflowConfig, 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{billingworkflowconfig.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *BillingWorkflowConfigQuery) FirstX(ctx context.Context) *BillingWorkflowConfig { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first BillingWorkflowConfig ID from the query. +// Returns a *NotFoundError when no BillingWorkflowConfig ID was found. +func (_q *BillingWorkflowConfigQuery) 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{billingworkflowconfig.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *BillingWorkflowConfigQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single BillingWorkflowConfig entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one BillingWorkflowConfig entity is found. +// Returns a *NotFoundError when no BillingWorkflowConfig entities are found. +func (_q *BillingWorkflowConfigQuery) Only(ctx context.Context) (*BillingWorkflowConfig, 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{billingworkflowconfig.Label} + default: + return nil, &NotSingularError{billingworkflowconfig.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *BillingWorkflowConfigQuery) OnlyX(ctx context.Context) *BillingWorkflowConfig { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only BillingWorkflowConfig ID in the query. +// Returns a *NotSingularError when more than one BillingWorkflowConfig ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *BillingWorkflowConfigQuery) 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{billingworkflowconfig.Label} + default: + err = &NotSingularError{billingworkflowconfig.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *BillingWorkflowConfigQuery) 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 BillingWorkflowConfigs. +func (_q *BillingWorkflowConfigQuery) All(ctx context.Context) ([]*BillingWorkflowConfig, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*BillingWorkflowConfig, *BillingWorkflowConfigQuery]() + return withInterceptors[[]*BillingWorkflowConfig](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *BillingWorkflowConfigQuery) AllX(ctx context.Context) []*BillingWorkflowConfig { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of BillingWorkflowConfig IDs. +func (_q *BillingWorkflowConfigQuery) 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(billingworkflowconfig.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *BillingWorkflowConfigQuery) 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 *BillingWorkflowConfigQuery) 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[*BillingWorkflowConfigQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *BillingWorkflowConfigQuery) 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 *BillingWorkflowConfigQuery) 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 *BillingWorkflowConfigQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the BillingWorkflowConfigQuery 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 *BillingWorkflowConfigQuery) Clone() *BillingWorkflowConfigQuery { + if _q == nil { + return nil + } + return &BillingWorkflowConfigQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]billingworkflowconfig.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.BillingWorkflowConfig{}, _q.predicates...), + withBillingInvoices: _q.withBillingInvoices.Clone(), + withBillingProfile: _q.withBillingProfile.Clone(), + withTaxCode: _q.withTaxCode.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithBillingInvoices tells the query-builder to eager-load the nodes that are connected to +// the "billing_invoices" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *BillingWorkflowConfigQuery) WithBillingInvoices(opts ...func(*BillingInvoiceQuery)) *BillingWorkflowConfigQuery { + query := (&BillingInvoiceClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingInvoices = query + return _q +} + +// WithBillingProfile tells the query-builder to eager-load the nodes that are connected to +// the "billing_profile" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *BillingWorkflowConfigQuery) WithBillingProfile(opts ...func(*BillingProfileQuery)) *BillingWorkflowConfigQuery { + query := (&BillingProfileClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingProfile = query + return _q +} + +// WithTaxCode tells the query-builder to eager-load the nodes that are connected to +// the "tax_code" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *BillingWorkflowConfigQuery) WithTaxCode(opts ...func(*TaxCodeQuery)) *BillingWorkflowConfigQuery { + query := (&TaxCodeClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withTaxCode = 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.BillingWorkflowConfig.Query(). +// GroupBy(billingworkflowconfig.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *BillingWorkflowConfigQuery) GroupBy(field string, fields ...string) *BillingWorkflowConfigGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &BillingWorkflowConfigGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = billingworkflowconfig.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.BillingWorkflowConfig.Query(). +// Select(billingworkflowconfig.FieldNamespace). +// Scan(ctx, &v) +func (_q *BillingWorkflowConfigQuery) Select(fields ...string) *BillingWorkflowConfigSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &BillingWorkflowConfigSelect{BillingWorkflowConfigQuery: _q} + sbuild.label = billingworkflowconfig.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a BillingWorkflowConfigSelect configured with the given aggregations. +func (_q *BillingWorkflowConfigQuery) Aggregate(fns ...AggregateFunc) *BillingWorkflowConfigSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *BillingWorkflowConfigQuery) 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 !billingworkflowconfig.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 *BillingWorkflowConfigQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BillingWorkflowConfig, error) { + var ( + nodes = []*BillingWorkflowConfig{} + _spec = _q.querySpec() + loadedTypes = [3]bool{ + _q.withBillingInvoices != nil, + _q.withBillingProfile != nil, + _q.withTaxCode != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*BillingWorkflowConfig).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &BillingWorkflowConfig{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.withBillingInvoices; query != nil { + if err := _q.loadBillingInvoices(ctx, query, nodes, nil, + func(n *BillingWorkflowConfig, e *BillingInvoice) { n.Edges.BillingInvoices = e }); err != nil { + return nil, err + } + } + if query := _q.withBillingProfile; query != nil { + if err := _q.loadBillingProfile(ctx, query, nodes, nil, + func(n *BillingWorkflowConfig, e *BillingProfile) { n.Edges.BillingProfile = e }); err != nil { + return nil, err + } + } + if query := _q.withTaxCode; query != nil { + if err := _q.loadTaxCode(ctx, query, nodes, nil, + func(n *BillingWorkflowConfig, e *TaxCode) { n.Edges.TaxCode = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *BillingWorkflowConfigQuery) loadBillingInvoices(ctx context.Context, query *BillingInvoiceQuery, nodes []*BillingWorkflowConfig, init func(*BillingWorkflowConfig), assign func(*BillingWorkflowConfig, *BillingInvoice)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*BillingWorkflowConfig) + 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(billinginvoice.FieldWorkflowConfigID) + } + query.Where(predicate.BillingInvoice(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(billingworkflowconfig.BillingInvoicesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.WorkflowConfigID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "workflow_config_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *BillingWorkflowConfigQuery) loadBillingProfile(ctx context.Context, query *BillingProfileQuery, nodes []*BillingWorkflowConfig, init func(*BillingWorkflowConfig), assign func(*BillingWorkflowConfig, *BillingProfile)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*BillingWorkflowConfig) + 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(billingprofile.FieldWorkflowConfigID) + } + query.Where(predicate.BillingProfile(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(billingworkflowconfig.BillingProfileColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.WorkflowConfigID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "workflow_config_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *BillingWorkflowConfigQuery) loadTaxCode(ctx context.Context, query *TaxCodeQuery, nodes []*BillingWorkflowConfig, init func(*BillingWorkflowConfig), assign func(*BillingWorkflowConfig, *TaxCode)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*BillingWorkflowConfig) + for i := range nodes { + if nodes[i].TaxCodeID == nil { + continue + } + fk := *nodes[i].TaxCodeID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(dbtaxcode.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 "tax_code_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *BillingWorkflowConfigQuery) 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 *BillingWorkflowConfigQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(billingworkflowconfig.Table, billingworkflowconfig.Columns, sqlgraph.NewFieldSpec(billingworkflowconfig.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, billingworkflowconfig.FieldID) + for i := range fields { + if fields[i] != billingworkflowconfig.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withTaxCode != nil { + _spec.Node.AddColumnOnce(billingworkflowconfig.FieldTaxCodeID) + } + } + 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 *BillingWorkflowConfigQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(billingworkflowconfig.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = billingworkflowconfig.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 *BillingWorkflowConfigQuery) ForUpdate(opts ...sql.LockOption) *BillingWorkflowConfigQuery { + 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 *BillingWorkflowConfigQuery) ForShare(opts ...sql.LockOption) *BillingWorkflowConfigQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// BillingWorkflowConfigGroupBy is the group-by builder for BillingWorkflowConfig entities. +type BillingWorkflowConfigGroupBy struct { + selector + build *BillingWorkflowConfigQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *BillingWorkflowConfigGroupBy) Aggregate(fns ...AggregateFunc) *BillingWorkflowConfigGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *BillingWorkflowConfigGroupBy) 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[*BillingWorkflowConfigQuery, *BillingWorkflowConfigGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *BillingWorkflowConfigGroupBy) sqlScan(ctx context.Context, root *BillingWorkflowConfigQuery, 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) +} + +// BillingWorkflowConfigSelect is the builder for selecting fields of BillingWorkflowConfig entities. +type BillingWorkflowConfigSelect struct { + *BillingWorkflowConfigQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *BillingWorkflowConfigSelect) Aggregate(fns ...AggregateFunc) *BillingWorkflowConfigSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *BillingWorkflowConfigSelect) 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[*BillingWorkflowConfigQuery, *BillingWorkflowConfigSelect](ctx, _s.BillingWorkflowConfigQuery, _s, _s.inters, v) +} + +func (_s *BillingWorkflowConfigSelect) sqlScan(ctx context.Context, root *BillingWorkflowConfigQuery, 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/ent/db/billingworkflowconfig_update.go b/ent/db/billingworkflowconfig_update.go new file mode 100644 index 0000000000000000000000000000000000000000..8e1d876466f81a8f80151cb53f494f0cb008c41c --- /dev/null +++ b/ent/db/billingworkflowconfig_update.go @@ -0,0 +1,1162 @@ +// 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/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingprofile" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingworkflowconfig" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/datetime" +) + +// BillingWorkflowConfigUpdate is the builder for updating BillingWorkflowConfig entities. +type BillingWorkflowConfigUpdate struct { + config + hooks []Hook + mutation *BillingWorkflowConfigMutation +} + +// Where appends a list predicates to the BillingWorkflowConfigUpdate builder. +func (_u *BillingWorkflowConfigUpdate) Where(ps ...predicate.BillingWorkflowConfig) *BillingWorkflowConfigUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *BillingWorkflowConfigUpdate) SetUpdatedAt(v time.Time) *BillingWorkflowConfigUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *BillingWorkflowConfigUpdate) SetDeletedAt(v time.Time) *BillingWorkflowConfigUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdate) SetNillableDeletedAt(v *time.Time) *BillingWorkflowConfigUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *BillingWorkflowConfigUpdate) ClearDeletedAt() *BillingWorkflowConfigUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (_u *BillingWorkflowConfigUpdate) SetTaxCodeID(v string) *BillingWorkflowConfigUpdate { + _u.mutation.SetTaxCodeID(v) + return _u +} + +// SetNillableTaxCodeID sets the "tax_code_id" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdate) SetNillableTaxCodeID(v *string) *BillingWorkflowConfigUpdate { + if v != nil { + _u.SetTaxCodeID(*v) + } + return _u +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (_u *BillingWorkflowConfigUpdate) ClearTaxCodeID() *BillingWorkflowConfigUpdate { + _u.mutation.ClearTaxCodeID() + return _u +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (_u *BillingWorkflowConfigUpdate) SetTaxBehavior(v productcatalog.TaxBehavior) *BillingWorkflowConfigUpdate { + _u.mutation.SetTaxBehavior(v) + return _u +} + +// SetNillableTaxBehavior sets the "tax_behavior" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdate) SetNillableTaxBehavior(v *productcatalog.TaxBehavior) *BillingWorkflowConfigUpdate { + if v != nil { + _u.SetTaxBehavior(*v) + } + return _u +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (_u *BillingWorkflowConfigUpdate) ClearTaxBehavior() *BillingWorkflowConfigUpdate { + _u.mutation.ClearTaxBehavior() + return _u +} + +// SetCollectionAlignment sets the "collection_alignment" field. +func (_u *BillingWorkflowConfigUpdate) SetCollectionAlignment(v billing.AlignmentKind) *BillingWorkflowConfigUpdate { + _u.mutation.SetCollectionAlignment(v) + return _u +} + +// SetNillableCollectionAlignment sets the "collection_alignment" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdate) SetNillableCollectionAlignment(v *billing.AlignmentKind) *BillingWorkflowConfigUpdate { + if v != nil { + _u.SetCollectionAlignment(*v) + } + return _u +} + +// SetAnchoredAlignmentDetail sets the "anchored_alignment_detail" field. +func (_u *BillingWorkflowConfigUpdate) SetAnchoredAlignmentDetail(v *billing.AnchoredAlignmentDetail) *BillingWorkflowConfigUpdate { + _u.mutation.SetAnchoredAlignmentDetail(v) + return _u +} + +// ClearAnchoredAlignmentDetail clears the value of the "anchored_alignment_detail" field. +func (_u *BillingWorkflowConfigUpdate) ClearAnchoredAlignmentDetail() *BillingWorkflowConfigUpdate { + _u.mutation.ClearAnchoredAlignmentDetail() + return _u +} + +// SetLineCollectionPeriod sets the "line_collection_period" field. +func (_u *BillingWorkflowConfigUpdate) SetLineCollectionPeriod(v datetime.ISODurationString) *BillingWorkflowConfigUpdate { + _u.mutation.SetLineCollectionPeriod(v) + return _u +} + +// SetNillableLineCollectionPeriod sets the "line_collection_period" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdate) SetNillableLineCollectionPeriod(v *datetime.ISODurationString) *BillingWorkflowConfigUpdate { + if v != nil { + _u.SetLineCollectionPeriod(*v) + } + return _u +} + +// SetInvoiceAutoAdvance sets the "invoice_auto_advance" field. +func (_u *BillingWorkflowConfigUpdate) SetInvoiceAutoAdvance(v bool) *BillingWorkflowConfigUpdate { + _u.mutation.SetInvoiceAutoAdvance(v) + return _u +} + +// SetNillableInvoiceAutoAdvance sets the "invoice_auto_advance" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdate) SetNillableInvoiceAutoAdvance(v *bool) *BillingWorkflowConfigUpdate { + if v != nil { + _u.SetInvoiceAutoAdvance(*v) + } + return _u +} + +// SetInvoiceDraftPeriod sets the "invoice_draft_period" field. +func (_u *BillingWorkflowConfigUpdate) SetInvoiceDraftPeriod(v datetime.ISODurationString) *BillingWorkflowConfigUpdate { + _u.mutation.SetInvoiceDraftPeriod(v) + return _u +} + +// SetNillableInvoiceDraftPeriod sets the "invoice_draft_period" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdate) SetNillableInvoiceDraftPeriod(v *datetime.ISODurationString) *BillingWorkflowConfigUpdate { + if v != nil { + _u.SetInvoiceDraftPeriod(*v) + } + return _u +} + +// SetInvoiceDueAfter sets the "invoice_due_after" field. +func (_u *BillingWorkflowConfigUpdate) SetInvoiceDueAfter(v datetime.ISODurationString) *BillingWorkflowConfigUpdate { + _u.mutation.SetInvoiceDueAfter(v) + return _u +} + +// SetNillableInvoiceDueAfter sets the "invoice_due_after" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdate) SetNillableInvoiceDueAfter(v *datetime.ISODurationString) *BillingWorkflowConfigUpdate { + if v != nil { + _u.SetInvoiceDueAfter(*v) + } + return _u +} + +// SetInvoiceCollectionMethod sets the "invoice_collection_method" field. +func (_u *BillingWorkflowConfigUpdate) SetInvoiceCollectionMethod(v billing.CollectionMethod) *BillingWorkflowConfigUpdate { + _u.mutation.SetInvoiceCollectionMethod(v) + return _u +} + +// SetNillableInvoiceCollectionMethod sets the "invoice_collection_method" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdate) SetNillableInvoiceCollectionMethod(v *billing.CollectionMethod) *BillingWorkflowConfigUpdate { + if v != nil { + _u.SetInvoiceCollectionMethod(*v) + } + return _u +} + +// SetInvoiceProgressiveBilling sets the "invoice_progressive_billing" field. +func (_u *BillingWorkflowConfigUpdate) SetInvoiceProgressiveBilling(v bool) *BillingWorkflowConfigUpdate { + _u.mutation.SetInvoiceProgressiveBilling(v) + return _u +} + +// SetNillableInvoiceProgressiveBilling sets the "invoice_progressive_billing" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdate) SetNillableInvoiceProgressiveBilling(v *bool) *BillingWorkflowConfigUpdate { + if v != nil { + _u.SetInvoiceProgressiveBilling(*v) + } + return _u +} + +// SetSubscriptionEndProrationMode sets the "subscription_end_proration_mode" field. +func (_u *BillingWorkflowConfigUpdate) SetSubscriptionEndProrationMode(v billing.SubscriptionEndProrationMode) *BillingWorkflowConfigUpdate { + _u.mutation.SetSubscriptionEndProrationMode(v) + return _u +} + +// SetNillableSubscriptionEndProrationMode sets the "subscription_end_proration_mode" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdate) SetNillableSubscriptionEndProrationMode(v *billing.SubscriptionEndProrationMode) *BillingWorkflowConfigUpdate { + if v != nil { + _u.SetSubscriptionEndProrationMode(*v) + } + return _u +} + +// SetInvoiceDefaultTaxSettings sets the "invoice_default_tax_settings" field. +func (_u *BillingWorkflowConfigUpdate) SetInvoiceDefaultTaxSettings(v productcatalog.TaxConfig) *BillingWorkflowConfigUpdate { + _u.mutation.SetInvoiceDefaultTaxSettings(v) + return _u +} + +// SetNillableInvoiceDefaultTaxSettings sets the "invoice_default_tax_settings" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdate) SetNillableInvoiceDefaultTaxSettings(v *productcatalog.TaxConfig) *BillingWorkflowConfigUpdate { + if v != nil { + _u.SetInvoiceDefaultTaxSettings(*v) + } + return _u +} + +// ClearInvoiceDefaultTaxSettings clears the value of the "invoice_default_tax_settings" field. +func (_u *BillingWorkflowConfigUpdate) ClearInvoiceDefaultTaxSettings() *BillingWorkflowConfigUpdate { + _u.mutation.ClearInvoiceDefaultTaxSettings() + return _u +} + +// SetTaxEnabled sets the "tax_enabled" field. +func (_u *BillingWorkflowConfigUpdate) SetTaxEnabled(v bool) *BillingWorkflowConfigUpdate { + _u.mutation.SetTaxEnabled(v) + return _u +} + +// SetNillableTaxEnabled sets the "tax_enabled" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdate) SetNillableTaxEnabled(v *bool) *BillingWorkflowConfigUpdate { + if v != nil { + _u.SetTaxEnabled(*v) + } + return _u +} + +// SetTaxEnforced sets the "tax_enforced" field. +func (_u *BillingWorkflowConfigUpdate) SetTaxEnforced(v bool) *BillingWorkflowConfigUpdate { + _u.mutation.SetTaxEnforced(v) + return _u +} + +// SetNillableTaxEnforced sets the "tax_enforced" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdate) SetNillableTaxEnforced(v *bool) *BillingWorkflowConfigUpdate { + if v != nil { + _u.SetTaxEnforced(*v) + } + return _u +} + +// SetBillingInvoicesID sets the "billing_invoices" edge to the BillingInvoice entity by ID. +func (_u *BillingWorkflowConfigUpdate) SetBillingInvoicesID(id string) *BillingWorkflowConfigUpdate { + _u.mutation.SetBillingInvoicesID(id) + return _u +} + +// SetNillableBillingInvoicesID sets the "billing_invoices" edge to the BillingInvoice entity by ID if the given value is not nil. +func (_u *BillingWorkflowConfigUpdate) SetNillableBillingInvoicesID(id *string) *BillingWorkflowConfigUpdate { + if id != nil { + _u = _u.SetBillingInvoicesID(*id) + } + return _u +} + +// SetBillingInvoices sets the "billing_invoices" edge to the BillingInvoice entity. +func (_u *BillingWorkflowConfigUpdate) SetBillingInvoices(v *BillingInvoice) *BillingWorkflowConfigUpdate { + return _u.SetBillingInvoicesID(v.ID) +} + +// SetBillingProfileID sets the "billing_profile" edge to the BillingProfile entity by ID. +func (_u *BillingWorkflowConfigUpdate) SetBillingProfileID(id string) *BillingWorkflowConfigUpdate { + _u.mutation.SetBillingProfileID(id) + return _u +} + +// SetNillableBillingProfileID sets the "billing_profile" edge to the BillingProfile entity by ID if the given value is not nil. +func (_u *BillingWorkflowConfigUpdate) SetNillableBillingProfileID(id *string) *BillingWorkflowConfigUpdate { + if id != nil { + _u = _u.SetBillingProfileID(*id) + } + return _u +} + +// SetBillingProfile sets the "billing_profile" edge to the BillingProfile entity. +func (_u *BillingWorkflowConfigUpdate) SetBillingProfile(v *BillingProfile) *BillingWorkflowConfigUpdate { + return _u.SetBillingProfileID(v.ID) +} + +// SetTaxCode sets the "tax_code" edge to the TaxCode entity. +func (_u *BillingWorkflowConfigUpdate) SetTaxCode(v *TaxCode) *BillingWorkflowConfigUpdate { + return _u.SetTaxCodeID(v.ID) +} + +// Mutation returns the BillingWorkflowConfigMutation object of the builder. +func (_u *BillingWorkflowConfigUpdate) Mutation() *BillingWorkflowConfigMutation { + return _u.mutation +} + +// ClearBillingInvoices clears the "billing_invoices" edge to the BillingInvoice entity. +func (_u *BillingWorkflowConfigUpdate) ClearBillingInvoices() *BillingWorkflowConfigUpdate { + _u.mutation.ClearBillingInvoices() + return _u +} + +// ClearBillingProfile clears the "billing_profile" edge to the BillingProfile entity. +func (_u *BillingWorkflowConfigUpdate) ClearBillingProfile() *BillingWorkflowConfigUpdate { + _u.mutation.ClearBillingProfile() + return _u +} + +// ClearTaxCode clears the "tax_code" edge to the TaxCode entity. +func (_u *BillingWorkflowConfigUpdate) ClearTaxCode() *BillingWorkflowConfigUpdate { + _u.mutation.ClearTaxCode() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *BillingWorkflowConfigUpdate) 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 *BillingWorkflowConfigUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *BillingWorkflowConfigUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingWorkflowConfigUpdate) 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 *BillingWorkflowConfigUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := billingworkflowconfig.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *BillingWorkflowConfigUpdate) check() error { + if v, ok := _u.mutation.TaxBehavior(); ok { + if err := billingworkflowconfig.TaxBehaviorValidator(v); err != nil { + return &ValidationError{Name: "tax_behavior", err: fmt.Errorf(`db: validator failed for field "BillingWorkflowConfig.tax_behavior": %w`, err)} + } + } + if v, ok := _u.mutation.CollectionAlignment(); ok { + if err := billingworkflowconfig.CollectionAlignmentValidator(v); err != nil { + return &ValidationError{Name: "collection_alignment", err: fmt.Errorf(`db: validator failed for field "BillingWorkflowConfig.collection_alignment": %w`, err)} + } + } + if v, ok := _u.mutation.AnchoredAlignmentDetail(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "anchored_alignment_detail", err: fmt.Errorf(`db: validator failed for field "BillingWorkflowConfig.anchored_alignment_detail": %w`, err)} + } + } + if v, ok := _u.mutation.InvoiceCollectionMethod(); ok { + if err := billingworkflowconfig.InvoiceCollectionMethodValidator(v); err != nil { + return &ValidationError{Name: "invoice_collection_method", err: fmt.Errorf(`db: validator failed for field "BillingWorkflowConfig.invoice_collection_method": %w`, err)} + } + } + if v, ok := _u.mutation.SubscriptionEndProrationMode(); ok { + if err := billingworkflowconfig.SubscriptionEndProrationModeValidator(v); err != nil { + return &ValidationError{Name: "subscription_end_proration_mode", err: fmt.Errorf(`db: validator failed for field "BillingWorkflowConfig.subscription_end_proration_mode": %w`, err)} + } + } + if v, ok := _u.mutation.InvoiceDefaultTaxSettings(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "invoice_default_tax_settings", err: fmt.Errorf(`db: validator failed for field "BillingWorkflowConfig.invoice_default_tax_settings": %w`, err)} + } + } + return nil +} + +func (_u *BillingWorkflowConfigUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(billingworkflowconfig.Table, billingworkflowconfig.Columns, sqlgraph.NewFieldSpec(billingworkflowconfig.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(billingworkflowconfig.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(billingworkflowconfig.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(billingworkflowconfig.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.TaxBehavior(); ok { + _spec.SetField(billingworkflowconfig.FieldTaxBehavior, field.TypeEnum, value) + } + if _u.mutation.TaxBehaviorCleared() { + _spec.ClearField(billingworkflowconfig.FieldTaxBehavior, field.TypeEnum) + } + if value, ok := _u.mutation.CollectionAlignment(); ok { + _spec.SetField(billingworkflowconfig.FieldCollectionAlignment, field.TypeEnum, value) + } + if value, ok := _u.mutation.AnchoredAlignmentDetail(); ok { + _spec.SetField(billingworkflowconfig.FieldAnchoredAlignmentDetail, field.TypeJSON, value) + } + if _u.mutation.AnchoredAlignmentDetailCleared() { + _spec.ClearField(billingworkflowconfig.FieldAnchoredAlignmentDetail, field.TypeJSON) + } + if value, ok := _u.mutation.LineCollectionPeriod(); ok { + _spec.SetField(billingworkflowconfig.FieldLineCollectionPeriod, field.TypeString, value) + } + if value, ok := _u.mutation.InvoiceAutoAdvance(); ok { + _spec.SetField(billingworkflowconfig.FieldInvoiceAutoAdvance, field.TypeBool, value) + } + if value, ok := _u.mutation.InvoiceDraftPeriod(); ok { + _spec.SetField(billingworkflowconfig.FieldInvoiceDraftPeriod, field.TypeString, value) + } + if value, ok := _u.mutation.InvoiceDueAfter(); ok { + _spec.SetField(billingworkflowconfig.FieldInvoiceDueAfter, field.TypeString, value) + } + if value, ok := _u.mutation.InvoiceCollectionMethod(); ok { + _spec.SetField(billingworkflowconfig.FieldInvoiceCollectionMethod, field.TypeEnum, value) + } + if value, ok := _u.mutation.InvoiceProgressiveBilling(); ok { + _spec.SetField(billingworkflowconfig.FieldInvoiceProgressiveBilling, field.TypeBool, value) + } + if value, ok := _u.mutation.SubscriptionEndProrationMode(); ok { + _spec.SetField(billingworkflowconfig.FieldSubscriptionEndProrationMode, field.TypeEnum, value) + } + if value, ok := _u.mutation.InvoiceDefaultTaxSettings(); ok { + _spec.SetField(billingworkflowconfig.FieldInvoiceDefaultTaxSettings, field.TypeJSON, value) + } + if _u.mutation.InvoiceDefaultTaxSettingsCleared() { + _spec.ClearField(billingworkflowconfig.FieldInvoiceDefaultTaxSettings, field.TypeJSON) + } + if value, ok := _u.mutation.TaxEnabled(); ok { + _spec.SetField(billingworkflowconfig.FieldTaxEnabled, field.TypeBool, value) + } + if value, ok := _u.mutation.TaxEnforced(); ok { + _spec.SetField(billingworkflowconfig.FieldTaxEnforced, field.TypeBool, value) + } + if _u.mutation.BillingInvoicesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: billingworkflowconfig.BillingInvoicesTable, + Columns: []string{billingworkflowconfig.BillingInvoicesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingInvoicesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: billingworkflowconfig.BillingInvoicesTable, + Columns: []string{billingworkflowconfig.BillingInvoicesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.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.BillingProfileCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: billingworkflowconfig.BillingProfileTable, + Columns: []string{billingworkflowconfig.BillingProfileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingprofile.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingProfileIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: billingworkflowconfig.BillingProfileTable, + Columns: []string{billingworkflowconfig.BillingProfileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingprofile.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.TaxCodeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingworkflowconfig.TaxCodeTable, + Columns: []string{billingworkflowconfig.TaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.TaxCodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingworkflowconfig.TaxCodeTable, + Columns: []string{billingworkflowconfig.TaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.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{billingworkflowconfig.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// BillingWorkflowConfigUpdateOne is the builder for updating a single BillingWorkflowConfig entity. +type BillingWorkflowConfigUpdateOne struct { + config + fields []string + hooks []Hook + mutation *BillingWorkflowConfigMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *BillingWorkflowConfigUpdateOne) SetUpdatedAt(v time.Time) *BillingWorkflowConfigUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *BillingWorkflowConfigUpdateOne) SetDeletedAt(v time.Time) *BillingWorkflowConfigUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdateOne) SetNillableDeletedAt(v *time.Time) *BillingWorkflowConfigUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *BillingWorkflowConfigUpdateOne) ClearDeletedAt() *BillingWorkflowConfigUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (_u *BillingWorkflowConfigUpdateOne) SetTaxCodeID(v string) *BillingWorkflowConfigUpdateOne { + _u.mutation.SetTaxCodeID(v) + return _u +} + +// SetNillableTaxCodeID sets the "tax_code_id" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdateOne) SetNillableTaxCodeID(v *string) *BillingWorkflowConfigUpdateOne { + if v != nil { + _u.SetTaxCodeID(*v) + } + return _u +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (_u *BillingWorkflowConfigUpdateOne) ClearTaxCodeID() *BillingWorkflowConfigUpdateOne { + _u.mutation.ClearTaxCodeID() + return _u +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (_u *BillingWorkflowConfigUpdateOne) SetTaxBehavior(v productcatalog.TaxBehavior) *BillingWorkflowConfigUpdateOne { + _u.mutation.SetTaxBehavior(v) + return _u +} + +// SetNillableTaxBehavior sets the "tax_behavior" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdateOne) SetNillableTaxBehavior(v *productcatalog.TaxBehavior) *BillingWorkflowConfigUpdateOne { + if v != nil { + _u.SetTaxBehavior(*v) + } + return _u +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (_u *BillingWorkflowConfigUpdateOne) ClearTaxBehavior() *BillingWorkflowConfigUpdateOne { + _u.mutation.ClearTaxBehavior() + return _u +} + +// SetCollectionAlignment sets the "collection_alignment" field. +func (_u *BillingWorkflowConfigUpdateOne) SetCollectionAlignment(v billing.AlignmentKind) *BillingWorkflowConfigUpdateOne { + _u.mutation.SetCollectionAlignment(v) + return _u +} + +// SetNillableCollectionAlignment sets the "collection_alignment" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdateOne) SetNillableCollectionAlignment(v *billing.AlignmentKind) *BillingWorkflowConfigUpdateOne { + if v != nil { + _u.SetCollectionAlignment(*v) + } + return _u +} + +// SetAnchoredAlignmentDetail sets the "anchored_alignment_detail" field. +func (_u *BillingWorkflowConfigUpdateOne) SetAnchoredAlignmentDetail(v *billing.AnchoredAlignmentDetail) *BillingWorkflowConfigUpdateOne { + _u.mutation.SetAnchoredAlignmentDetail(v) + return _u +} + +// ClearAnchoredAlignmentDetail clears the value of the "anchored_alignment_detail" field. +func (_u *BillingWorkflowConfigUpdateOne) ClearAnchoredAlignmentDetail() *BillingWorkflowConfigUpdateOne { + _u.mutation.ClearAnchoredAlignmentDetail() + return _u +} + +// SetLineCollectionPeriod sets the "line_collection_period" field. +func (_u *BillingWorkflowConfigUpdateOne) SetLineCollectionPeriod(v datetime.ISODurationString) *BillingWorkflowConfigUpdateOne { + _u.mutation.SetLineCollectionPeriod(v) + return _u +} + +// SetNillableLineCollectionPeriod sets the "line_collection_period" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdateOne) SetNillableLineCollectionPeriod(v *datetime.ISODurationString) *BillingWorkflowConfigUpdateOne { + if v != nil { + _u.SetLineCollectionPeriod(*v) + } + return _u +} + +// SetInvoiceAutoAdvance sets the "invoice_auto_advance" field. +func (_u *BillingWorkflowConfigUpdateOne) SetInvoiceAutoAdvance(v bool) *BillingWorkflowConfigUpdateOne { + _u.mutation.SetInvoiceAutoAdvance(v) + return _u +} + +// SetNillableInvoiceAutoAdvance sets the "invoice_auto_advance" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdateOne) SetNillableInvoiceAutoAdvance(v *bool) *BillingWorkflowConfigUpdateOne { + if v != nil { + _u.SetInvoiceAutoAdvance(*v) + } + return _u +} + +// SetInvoiceDraftPeriod sets the "invoice_draft_period" field. +func (_u *BillingWorkflowConfigUpdateOne) SetInvoiceDraftPeriod(v datetime.ISODurationString) *BillingWorkflowConfigUpdateOne { + _u.mutation.SetInvoiceDraftPeriod(v) + return _u +} + +// SetNillableInvoiceDraftPeriod sets the "invoice_draft_period" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdateOne) SetNillableInvoiceDraftPeriod(v *datetime.ISODurationString) *BillingWorkflowConfigUpdateOne { + if v != nil { + _u.SetInvoiceDraftPeriod(*v) + } + return _u +} + +// SetInvoiceDueAfter sets the "invoice_due_after" field. +func (_u *BillingWorkflowConfigUpdateOne) SetInvoiceDueAfter(v datetime.ISODurationString) *BillingWorkflowConfigUpdateOne { + _u.mutation.SetInvoiceDueAfter(v) + return _u +} + +// SetNillableInvoiceDueAfter sets the "invoice_due_after" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdateOne) SetNillableInvoiceDueAfter(v *datetime.ISODurationString) *BillingWorkflowConfigUpdateOne { + if v != nil { + _u.SetInvoiceDueAfter(*v) + } + return _u +} + +// SetInvoiceCollectionMethod sets the "invoice_collection_method" field. +func (_u *BillingWorkflowConfigUpdateOne) SetInvoiceCollectionMethod(v billing.CollectionMethod) *BillingWorkflowConfigUpdateOne { + _u.mutation.SetInvoiceCollectionMethod(v) + return _u +} + +// SetNillableInvoiceCollectionMethod sets the "invoice_collection_method" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdateOne) SetNillableInvoiceCollectionMethod(v *billing.CollectionMethod) *BillingWorkflowConfigUpdateOne { + if v != nil { + _u.SetInvoiceCollectionMethod(*v) + } + return _u +} + +// SetInvoiceProgressiveBilling sets the "invoice_progressive_billing" field. +func (_u *BillingWorkflowConfigUpdateOne) SetInvoiceProgressiveBilling(v bool) *BillingWorkflowConfigUpdateOne { + _u.mutation.SetInvoiceProgressiveBilling(v) + return _u +} + +// SetNillableInvoiceProgressiveBilling sets the "invoice_progressive_billing" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdateOne) SetNillableInvoiceProgressiveBilling(v *bool) *BillingWorkflowConfigUpdateOne { + if v != nil { + _u.SetInvoiceProgressiveBilling(*v) + } + return _u +} + +// SetSubscriptionEndProrationMode sets the "subscription_end_proration_mode" field. +func (_u *BillingWorkflowConfigUpdateOne) SetSubscriptionEndProrationMode(v billing.SubscriptionEndProrationMode) *BillingWorkflowConfigUpdateOne { + _u.mutation.SetSubscriptionEndProrationMode(v) + return _u +} + +// SetNillableSubscriptionEndProrationMode sets the "subscription_end_proration_mode" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdateOne) SetNillableSubscriptionEndProrationMode(v *billing.SubscriptionEndProrationMode) *BillingWorkflowConfigUpdateOne { + if v != nil { + _u.SetSubscriptionEndProrationMode(*v) + } + return _u +} + +// SetInvoiceDefaultTaxSettings sets the "invoice_default_tax_settings" field. +func (_u *BillingWorkflowConfigUpdateOne) SetInvoiceDefaultTaxSettings(v productcatalog.TaxConfig) *BillingWorkflowConfigUpdateOne { + _u.mutation.SetInvoiceDefaultTaxSettings(v) + return _u +} + +// SetNillableInvoiceDefaultTaxSettings sets the "invoice_default_tax_settings" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdateOne) SetNillableInvoiceDefaultTaxSettings(v *productcatalog.TaxConfig) *BillingWorkflowConfigUpdateOne { + if v != nil { + _u.SetInvoiceDefaultTaxSettings(*v) + } + return _u +} + +// ClearInvoiceDefaultTaxSettings clears the value of the "invoice_default_tax_settings" field. +func (_u *BillingWorkflowConfigUpdateOne) ClearInvoiceDefaultTaxSettings() *BillingWorkflowConfigUpdateOne { + _u.mutation.ClearInvoiceDefaultTaxSettings() + return _u +} + +// SetTaxEnabled sets the "tax_enabled" field. +func (_u *BillingWorkflowConfigUpdateOne) SetTaxEnabled(v bool) *BillingWorkflowConfigUpdateOne { + _u.mutation.SetTaxEnabled(v) + return _u +} + +// SetNillableTaxEnabled sets the "tax_enabled" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdateOne) SetNillableTaxEnabled(v *bool) *BillingWorkflowConfigUpdateOne { + if v != nil { + _u.SetTaxEnabled(*v) + } + return _u +} + +// SetTaxEnforced sets the "tax_enforced" field. +func (_u *BillingWorkflowConfigUpdateOne) SetTaxEnforced(v bool) *BillingWorkflowConfigUpdateOne { + _u.mutation.SetTaxEnforced(v) + return _u +} + +// SetNillableTaxEnforced sets the "tax_enforced" field if the given value is not nil. +func (_u *BillingWorkflowConfigUpdateOne) SetNillableTaxEnforced(v *bool) *BillingWorkflowConfigUpdateOne { + if v != nil { + _u.SetTaxEnforced(*v) + } + return _u +} + +// SetBillingInvoicesID sets the "billing_invoices" edge to the BillingInvoice entity by ID. +func (_u *BillingWorkflowConfigUpdateOne) SetBillingInvoicesID(id string) *BillingWorkflowConfigUpdateOne { + _u.mutation.SetBillingInvoicesID(id) + return _u +} + +// SetNillableBillingInvoicesID sets the "billing_invoices" edge to the BillingInvoice entity by ID if the given value is not nil. +func (_u *BillingWorkflowConfigUpdateOne) SetNillableBillingInvoicesID(id *string) *BillingWorkflowConfigUpdateOne { + if id != nil { + _u = _u.SetBillingInvoicesID(*id) + } + return _u +} + +// SetBillingInvoices sets the "billing_invoices" edge to the BillingInvoice entity. +func (_u *BillingWorkflowConfigUpdateOne) SetBillingInvoices(v *BillingInvoice) *BillingWorkflowConfigUpdateOne { + return _u.SetBillingInvoicesID(v.ID) +} + +// SetBillingProfileID sets the "billing_profile" edge to the BillingProfile entity by ID. +func (_u *BillingWorkflowConfigUpdateOne) SetBillingProfileID(id string) *BillingWorkflowConfigUpdateOne { + _u.mutation.SetBillingProfileID(id) + return _u +} + +// SetNillableBillingProfileID sets the "billing_profile" edge to the BillingProfile entity by ID if the given value is not nil. +func (_u *BillingWorkflowConfigUpdateOne) SetNillableBillingProfileID(id *string) *BillingWorkflowConfigUpdateOne { + if id != nil { + _u = _u.SetBillingProfileID(*id) + } + return _u +} + +// SetBillingProfile sets the "billing_profile" edge to the BillingProfile entity. +func (_u *BillingWorkflowConfigUpdateOne) SetBillingProfile(v *BillingProfile) *BillingWorkflowConfigUpdateOne { + return _u.SetBillingProfileID(v.ID) +} + +// SetTaxCode sets the "tax_code" edge to the TaxCode entity. +func (_u *BillingWorkflowConfigUpdateOne) SetTaxCode(v *TaxCode) *BillingWorkflowConfigUpdateOne { + return _u.SetTaxCodeID(v.ID) +} + +// Mutation returns the BillingWorkflowConfigMutation object of the builder. +func (_u *BillingWorkflowConfigUpdateOne) Mutation() *BillingWorkflowConfigMutation { + return _u.mutation +} + +// ClearBillingInvoices clears the "billing_invoices" edge to the BillingInvoice entity. +func (_u *BillingWorkflowConfigUpdateOne) ClearBillingInvoices() *BillingWorkflowConfigUpdateOne { + _u.mutation.ClearBillingInvoices() + return _u +} + +// ClearBillingProfile clears the "billing_profile" edge to the BillingProfile entity. +func (_u *BillingWorkflowConfigUpdateOne) ClearBillingProfile() *BillingWorkflowConfigUpdateOne { + _u.mutation.ClearBillingProfile() + return _u +} + +// ClearTaxCode clears the "tax_code" edge to the TaxCode entity. +func (_u *BillingWorkflowConfigUpdateOne) ClearTaxCode() *BillingWorkflowConfigUpdateOne { + _u.mutation.ClearTaxCode() + return _u +} + +// Where appends a list predicates to the BillingWorkflowConfigUpdate builder. +func (_u *BillingWorkflowConfigUpdateOne) Where(ps ...predicate.BillingWorkflowConfig) *BillingWorkflowConfigUpdateOne { + _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 *BillingWorkflowConfigUpdateOne) Select(field string, fields ...string) *BillingWorkflowConfigUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated BillingWorkflowConfig entity. +func (_u *BillingWorkflowConfigUpdateOne) Save(ctx context.Context) (*BillingWorkflowConfig, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *BillingWorkflowConfigUpdateOne) SaveX(ctx context.Context) *BillingWorkflowConfig { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *BillingWorkflowConfigUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BillingWorkflowConfigUpdateOne) 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 *BillingWorkflowConfigUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := billingworkflowconfig.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *BillingWorkflowConfigUpdateOne) check() error { + if v, ok := _u.mutation.TaxBehavior(); ok { + if err := billingworkflowconfig.TaxBehaviorValidator(v); err != nil { + return &ValidationError{Name: "tax_behavior", err: fmt.Errorf(`db: validator failed for field "BillingWorkflowConfig.tax_behavior": %w`, err)} + } + } + if v, ok := _u.mutation.CollectionAlignment(); ok { + if err := billingworkflowconfig.CollectionAlignmentValidator(v); err != nil { + return &ValidationError{Name: "collection_alignment", err: fmt.Errorf(`db: validator failed for field "BillingWorkflowConfig.collection_alignment": %w`, err)} + } + } + if v, ok := _u.mutation.AnchoredAlignmentDetail(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "anchored_alignment_detail", err: fmt.Errorf(`db: validator failed for field "BillingWorkflowConfig.anchored_alignment_detail": %w`, err)} + } + } + if v, ok := _u.mutation.InvoiceCollectionMethod(); ok { + if err := billingworkflowconfig.InvoiceCollectionMethodValidator(v); err != nil { + return &ValidationError{Name: "invoice_collection_method", err: fmt.Errorf(`db: validator failed for field "BillingWorkflowConfig.invoice_collection_method": %w`, err)} + } + } + if v, ok := _u.mutation.SubscriptionEndProrationMode(); ok { + if err := billingworkflowconfig.SubscriptionEndProrationModeValidator(v); err != nil { + return &ValidationError{Name: "subscription_end_proration_mode", err: fmt.Errorf(`db: validator failed for field "BillingWorkflowConfig.subscription_end_proration_mode": %w`, err)} + } + } + if v, ok := _u.mutation.InvoiceDefaultTaxSettings(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "invoice_default_tax_settings", err: fmt.Errorf(`db: validator failed for field "BillingWorkflowConfig.invoice_default_tax_settings": %w`, err)} + } + } + return nil +} + +func (_u *BillingWorkflowConfigUpdateOne) sqlSave(ctx context.Context) (_node *BillingWorkflowConfig, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(billingworkflowconfig.Table, billingworkflowconfig.Columns, sqlgraph.NewFieldSpec(billingworkflowconfig.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "BillingWorkflowConfig.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, billingworkflowconfig.FieldID) + for _, f := range fields { + if !billingworkflowconfig.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != billingworkflowconfig.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(billingworkflowconfig.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(billingworkflowconfig.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(billingworkflowconfig.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.TaxBehavior(); ok { + _spec.SetField(billingworkflowconfig.FieldTaxBehavior, field.TypeEnum, value) + } + if _u.mutation.TaxBehaviorCleared() { + _spec.ClearField(billingworkflowconfig.FieldTaxBehavior, field.TypeEnum) + } + if value, ok := _u.mutation.CollectionAlignment(); ok { + _spec.SetField(billingworkflowconfig.FieldCollectionAlignment, field.TypeEnum, value) + } + if value, ok := _u.mutation.AnchoredAlignmentDetail(); ok { + _spec.SetField(billingworkflowconfig.FieldAnchoredAlignmentDetail, field.TypeJSON, value) + } + if _u.mutation.AnchoredAlignmentDetailCleared() { + _spec.ClearField(billingworkflowconfig.FieldAnchoredAlignmentDetail, field.TypeJSON) + } + if value, ok := _u.mutation.LineCollectionPeriod(); ok { + _spec.SetField(billingworkflowconfig.FieldLineCollectionPeriod, field.TypeString, value) + } + if value, ok := _u.mutation.InvoiceAutoAdvance(); ok { + _spec.SetField(billingworkflowconfig.FieldInvoiceAutoAdvance, field.TypeBool, value) + } + if value, ok := _u.mutation.InvoiceDraftPeriod(); ok { + _spec.SetField(billingworkflowconfig.FieldInvoiceDraftPeriod, field.TypeString, value) + } + if value, ok := _u.mutation.InvoiceDueAfter(); ok { + _spec.SetField(billingworkflowconfig.FieldInvoiceDueAfter, field.TypeString, value) + } + if value, ok := _u.mutation.InvoiceCollectionMethod(); ok { + _spec.SetField(billingworkflowconfig.FieldInvoiceCollectionMethod, field.TypeEnum, value) + } + if value, ok := _u.mutation.InvoiceProgressiveBilling(); ok { + _spec.SetField(billingworkflowconfig.FieldInvoiceProgressiveBilling, field.TypeBool, value) + } + if value, ok := _u.mutation.SubscriptionEndProrationMode(); ok { + _spec.SetField(billingworkflowconfig.FieldSubscriptionEndProrationMode, field.TypeEnum, value) + } + if value, ok := _u.mutation.InvoiceDefaultTaxSettings(); ok { + _spec.SetField(billingworkflowconfig.FieldInvoiceDefaultTaxSettings, field.TypeJSON, value) + } + if _u.mutation.InvoiceDefaultTaxSettingsCleared() { + _spec.ClearField(billingworkflowconfig.FieldInvoiceDefaultTaxSettings, field.TypeJSON) + } + if value, ok := _u.mutation.TaxEnabled(); ok { + _spec.SetField(billingworkflowconfig.FieldTaxEnabled, field.TypeBool, value) + } + if value, ok := _u.mutation.TaxEnforced(); ok { + _spec.SetField(billingworkflowconfig.FieldTaxEnforced, field.TypeBool, value) + } + if _u.mutation.BillingInvoicesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: billingworkflowconfig.BillingInvoicesTable, + Columns: []string{billingworkflowconfig.BillingInvoicesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingInvoicesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: billingworkflowconfig.BillingInvoicesTable, + Columns: []string{billingworkflowconfig.BillingInvoicesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.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.BillingProfileCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: billingworkflowconfig.BillingProfileTable, + Columns: []string{billingworkflowconfig.BillingProfileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingprofile.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingProfileIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: billingworkflowconfig.BillingProfileTable, + Columns: []string{billingworkflowconfig.BillingProfileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingprofile.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.TaxCodeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingworkflowconfig.TaxCodeTable, + Columns: []string{billingworkflowconfig.TaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.TaxCodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: billingworkflowconfig.TaxCodeTable, + Columns: []string{billingworkflowconfig.TaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &BillingWorkflowConfig{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{billingworkflowconfig.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/ent/db/charge.go b/ent/db/charge.go new file mode 100644 index 0000000000000000000000000000000000000000..d8f9db58f980212fa0cc07f7aed92f7205d903e5 --- /dev/null +++ b/ent/db/charge.go @@ -0,0 +1,312 @@ +// 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/billing/charges/meta" + "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" +) + +// Charge is the model entity for the Charge schema. +type Charge 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"` + // DeletedAt holds the value of the "deleted_at" field. + DeletedAt *time.Time `json:"deleted_at,omitempty"` + // UniqueReferenceID holds the value of the "unique_reference_id" field. + UniqueReferenceID *string `json:"unique_reference_id,omitempty"` + // Type holds the value of the "type" field. + Type meta.ChargeType `json:"type,omitempty"` + // ChargeFlatFeeID holds the value of the "charge_flat_fee_id" field. + ChargeFlatFeeID *string `json:"charge_flat_fee_id,omitempty"` + // ChargeCreditPurchaseID holds the value of the "charge_credit_purchase_id" field. + ChargeCreditPurchaseID *string `json:"charge_credit_purchase_id,omitempty"` + // ChargeUsageBasedID holds the value of the "charge_usage_based_id" field. + ChargeUsageBasedID *string `json:"charge_usage_based_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ChargeQuery when eager-loading is set. + Edges ChargeEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ChargeEdges holds the relations/edges for other nodes in the graph. +type ChargeEdges struct { + // FlatFee holds the value of the flat_fee edge. + 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. + BillingSplitLineGroups []*BillingInvoiceSplitLineGroup `json:"billing_split_line_groups,omitempty"` + // CreditRealizationLineages holds the value of the credit_realization_lineages edge. + CreditRealizationLineages []*CreditRealizationLineage `json:"credit_realization_lineages,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [6]bool +} + +// FlatFeeOrErr returns the FlatFee value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeEdges) FlatFeeOrErr() (*ChargeFlatFee, error) { + if e.FlatFee != nil { + return e.FlatFee, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: chargeflatfee.Label} + } + return nil, &NotLoadedError{edge: "flat_fee"} +} + +// CreditPurchaseOrErr returns the CreditPurchase value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeEdges) CreditPurchaseOrErr() (*ChargeCreditPurchase, error) { + if e.CreditPurchase != nil { + return e.CreditPurchase, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: chargecreditpurchase.Label} + } + 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[3] { + return e.BillingInvoiceLines, nil + } + return nil, &NotLoadedError{edge: "billing_invoice_lines"} +} + +// 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[4] { + return e.BillingSplitLineGroups, nil + } + return nil, &NotLoadedError{edge: "billing_split_line_groups"} +} + +// CreditRealizationLineagesOrErr returns the CreditRealizationLineages value or an error if the edge +// was not loaded in eager-loading. +func (e ChargeEdges) CreditRealizationLineagesOrErr() ([]*CreditRealizationLineage, error) { + if e.loadedTypes[5] { + return e.CreditRealizationLineages, nil + } + return nil, &NotLoadedError{edge: "credit_realization_lineages"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Charge) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case charge.FieldID, charge.FieldNamespace, charge.FieldUniqueReferenceID, charge.FieldType, charge.FieldChargeFlatFeeID, charge.FieldChargeCreditPurchaseID, charge.FieldChargeUsageBasedID: + values[i] = new(sql.NullString) + case charge.FieldCreatedAt, charge.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 Charge fields. +func (_m *Charge) 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 charge.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 charge.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 charge.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 charge.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 charge.FieldUniqueReferenceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field unique_reference_id", values[i]) + } else if value.Valid { + _m.UniqueReferenceID = new(string) + *_m.UniqueReferenceID = value.String + } + case charge.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 = meta.ChargeType(value.String) + } + case charge.FieldChargeFlatFeeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field charge_flat_fee_id", values[i]) + } else if value.Valid { + _m.ChargeFlatFeeID = new(string) + *_m.ChargeFlatFeeID = value.String + } + case charge.FieldChargeCreditPurchaseID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field charge_credit_purchase_id", values[i]) + } else if value.Valid { + _m.ChargeCreditPurchaseID = new(string) + *_m.ChargeCreditPurchaseID = value.String + } + case charge.FieldChargeUsageBasedID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field charge_usage_based_id", values[i]) + } else if value.Valid { + _m.ChargeUsageBasedID = new(string) + *_m.ChargeUsageBasedID = 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 Charge. +// This includes values selected through modifiers, order, etc. +func (_m *Charge) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryFlatFee queries the "flat_fee" edge of the Charge entity. +func (_m *Charge) QueryFlatFee() *ChargeFlatFeeQuery { + return NewChargeClient(_m.config).QueryFlatFee(_m) +} + +// QueryCreditPurchase queries the "credit_purchase" edge of the Charge entity. +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) +} + +// QueryBillingSplitLineGroups queries the "billing_split_line_groups" edge of the Charge entity. +func (_m *Charge) QueryBillingSplitLineGroups() *BillingInvoiceSplitLineGroupQuery { + return NewChargeClient(_m.config).QueryBillingSplitLineGroups(_m) +} + +// QueryCreditRealizationLineages queries the "credit_realization_lineages" edge of the Charge entity. +func (_m *Charge) QueryCreditRealizationLineages() *CreditRealizationLineageQuery { + return NewChargeClient(_m.config).QueryCreditRealizationLineages(_m) +} + +// Update returns a builder for updating this Charge. +// Note that you need to call Charge.Unwrap() before calling this method if this Charge +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Charge) Update() *ChargeUpdateOne { + return NewChargeClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Charge 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 *Charge) Unwrap() *Charge { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: Charge is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Charge) String() string { + var builder strings.Builder + builder.WriteString("Charge(") + 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(", ") + if v := _m.DeletedAt; v != nil { + builder.WriteString("deleted_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + if v := _m.UniqueReferenceID; v != nil { + builder.WriteString("unique_reference_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("type=") + builder.WriteString(fmt.Sprintf("%v", _m.Type)) + builder.WriteString(", ") + if v := _m.ChargeFlatFeeID; v != nil { + builder.WriteString("charge_flat_fee_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.ChargeCreditPurchaseID; v != nil { + builder.WriteString("charge_credit_purchase_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.ChargeUsageBasedID; v != nil { + builder.WriteString("charge_usage_based_id=") + builder.WriteString(*v) + } + builder.WriteByte(')') + return builder.String() +} + +// Charges is a parsable slice of Charge. +type Charges []*Charge diff --git a/ent/db/charge/charge.go b/ent/db/charge/charge.go new file mode 100644 index 0000000000000000000000000000000000000000..d17e43e07655260837b57d51c13bc1fab32a0348 --- /dev/null +++ b/ent/db/charge/charge.go @@ -0,0 +1,276 @@ +// Code generated by ent, DO NOT EDIT. + +package charge + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the charge type in the database. + Label = "charge" + // 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" + // FieldDeletedAt holds the string denoting the deleted_at field in the database. + FieldDeletedAt = "deleted_at" + // FieldUniqueReferenceID holds the string denoting the unique_reference_id field in the database. + FieldUniqueReferenceID = "unique_reference_id" + // FieldType holds the string denoting the type field in the database. + FieldType = "type" + // FieldChargeFlatFeeID holds the string denoting the charge_flat_fee_id field in the database. + FieldChargeFlatFeeID = "charge_flat_fee_id" + // FieldChargeCreditPurchaseID holds the string denoting the charge_credit_purchase_id field in the database. + FieldChargeCreditPurchaseID = "charge_credit_purchase_id" + // FieldChargeUsageBasedID holds the string denoting the charge_usage_based_id field in the database. + FieldChargeUsageBasedID = "charge_usage_based_id" + // EdgeFlatFee holds the string denoting the flat_fee edge name in mutations. + 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. + EdgeBillingSplitLineGroups = "billing_split_line_groups" + // EdgeCreditRealizationLineages holds the string denoting the credit_realization_lineages edge name in mutations. + EdgeCreditRealizationLineages = "credit_realization_lineages" + // Table holds the table name of the charge in the database. + Table = "charges" + // FlatFeeTable is the table that holds the flat_fee relation/edge. + FlatFeeTable = "charges" + // FlatFeeInverseTable is the table name for the ChargeFlatFee entity. + // It exists in this package in order to avoid circular dependency with the "chargeflatfee" package. + FlatFeeInverseTable = "charge_flat_fees" + // FlatFeeColumn is the table column denoting the flat_fee relation/edge. + FlatFeeColumn = "charge_flat_fee_id" + // CreditPurchaseTable is the table that holds the credit_purchase relation/edge. + CreditPurchaseTable = "charges" + // CreditPurchaseInverseTable is the table name for the ChargeCreditPurchase entity. + // It exists in this package in order to avoid circular dependency with the "chargecreditpurchase" package. + CreditPurchaseInverseTable = "charge_credit_purchases" + // CreditPurchaseColumn is the table column denoting the credit_purchase relation/edge. + CreditPurchaseColumn = "charge_credit_purchase_id" + // UsageBasedTable is the table that holds the usage_based relation/edge. + UsageBasedTable = "charges" + // 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_usage_based_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. + // It exists in this package in order to avoid circular dependency with the "billinginvoiceline" package. + BillingInvoiceLinesInverseTable = "billing_invoice_lines" + // BillingInvoiceLinesColumn is the table column denoting the billing_invoice_lines relation/edge. + BillingInvoiceLinesColumn = "charge_id" + // BillingSplitLineGroupsTable is the table that holds the billing_split_line_groups relation/edge. + BillingSplitLineGroupsTable = "billing_invoice_split_line_groups" + // BillingSplitLineGroupsInverseTable is the table name for the BillingInvoiceSplitLineGroup entity. + // It exists in this package in order to avoid circular dependency with the "billinginvoicesplitlinegroup" package. + BillingSplitLineGroupsInverseTable = "billing_invoice_split_line_groups" + // BillingSplitLineGroupsColumn is the table column denoting the billing_split_line_groups relation/edge. + BillingSplitLineGroupsColumn = "charge_id" + // CreditRealizationLineagesTable is the table that holds the credit_realization_lineages relation/edge. + CreditRealizationLineagesTable = "credit_realization_lineages" + // CreditRealizationLineagesInverseTable is the table name for the CreditRealizationLineage entity. + // It exists in this package in order to avoid circular dependency with the "creditrealizationlineage" package. + CreditRealizationLineagesInverseTable = "credit_realization_lineages" + // CreditRealizationLineagesColumn is the table column denoting the credit_realization_lineages relation/edge. + CreditRealizationLineagesColumn = "charge_id" +) + +// Columns holds all SQL columns for charge fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldCreatedAt, + FieldDeletedAt, + FieldUniqueReferenceID, + FieldType, + FieldChargeFlatFeeID, + FieldChargeCreditPurchaseID, + FieldChargeUsageBasedID, +} + +// 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 + // UniqueReferenceIDValidator is a validator for the "unique_reference_id" field. It is called by the builders before save. + UniqueReferenceIDValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// OrderOption defines the ordering options for the Charge 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() +} + +// ByDeletedAt orders the results by the deleted_at field. +func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDeletedAt, opts...).ToFunc() +} + +// ByUniqueReferenceID orders the results by the unique_reference_id field. +func ByUniqueReferenceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUniqueReferenceID, opts...).ToFunc() +} + +// ByType orders the results by the type field. +func ByType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldType, opts...).ToFunc() +} + +// ByChargeFlatFeeID orders the results by the charge_flat_fee_id field. +func ByChargeFlatFeeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChargeFlatFeeID, opts...).ToFunc() +} + +// ByChargeCreditPurchaseID orders the results by the charge_credit_purchase_id field. +func ByChargeCreditPurchaseID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChargeCreditPurchaseID, opts...).ToFunc() +} + +// ByChargeUsageBasedID orders the results by the charge_usage_based_id field. +func ByChargeUsageBasedID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChargeUsageBasedID, opts...).ToFunc() +} + +// ByFlatFeeField orders the results by flat_fee field. +func ByFlatFeeField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newFlatFeeStep(), sql.OrderByField(field, opts...)) + } +} + +// ByCreditPurchaseField orders the results by credit_purchase field. +func ByCreditPurchaseField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCreditPurchaseStep(), sql.OrderByField(field, opts...)) + } +} + +// 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) { + sqlgraph.OrderByNeighborsCount(s, newBillingInvoiceLinesStep(), opts...) + } +} + +// ByBillingInvoiceLines orders the results by billing_invoice_lines terms. +func ByBillingInvoiceLines(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBillingInvoiceLinesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByBillingSplitLineGroupsCount orders the results by billing_split_line_groups count. +func ByBillingSplitLineGroupsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newBillingSplitLineGroupsStep(), opts...) + } +} + +// ByBillingSplitLineGroups orders the results by billing_split_line_groups terms. +func ByBillingSplitLineGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBillingSplitLineGroupsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByCreditRealizationLineagesCount orders the results by credit_realization_lineages count. +func ByCreditRealizationLineagesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newCreditRealizationLineagesStep(), opts...) + } +} + +// ByCreditRealizationLineages orders the results by credit_realization_lineages terms. +func ByCreditRealizationLineages(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCreditRealizationLineagesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newFlatFeeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(FlatFeeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, FlatFeeTable, FlatFeeColumn), + ) +} +func newCreditPurchaseStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CreditPurchaseInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, CreditPurchaseTable, CreditPurchaseColumn), + ) +} +func newUsageBasedStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UsageBasedInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, UsageBasedTable, UsageBasedColumn), + ) +} +func newBillingInvoiceLinesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BillingInvoiceLinesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, BillingInvoiceLinesTable, BillingInvoiceLinesColumn), + ) +} +func newBillingSplitLineGroupsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BillingSplitLineGroupsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, BillingSplitLineGroupsTable, BillingSplitLineGroupsColumn), + ) +} +func newCreditRealizationLineagesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CreditRealizationLineagesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, CreditRealizationLineagesTable, CreditRealizationLineagesColumn), + ) +} diff --git a/ent/db/charge/where.go b/ent/db/charge/where.go new file mode 100644 index 0000000000000000000000000000000000000000..bef7849baa57da901ca06538108d8e1b8d04cf6d --- /dev/null +++ b/ent/db/charge/where.go @@ -0,0 +1,800 @@ +// Code generated by ent, DO NOT EDIT. + +package charge + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.Charge { + return predicate.Charge(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.Charge { + return predicate.Charge(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.Charge { + return predicate.Charge(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.Charge { + return predicate.Charge(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.Charge { + return predicate.Charge(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.Charge { + return predicate.Charge(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.Charge { + return predicate.Charge(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.Charge { + return predicate.Charge(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.Charge { + return predicate.Charge(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.Charge { + return predicate.Charge(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.Charge { + return predicate.Charge(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.Charge { + return predicate.Charge(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.Charge { + return predicate.Charge(sql.FieldEQ(FieldCreatedAt, v)) +} + +// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ. +func DeletedAt(v time.Time) predicate.Charge { + return predicate.Charge(sql.FieldEQ(FieldDeletedAt, v)) +} + +// UniqueReferenceID applies equality check predicate on the "unique_reference_id" field. It's identical to UniqueReferenceIDEQ. +func UniqueReferenceID(v string) predicate.Charge { + return predicate.Charge(sql.FieldEQ(FieldUniqueReferenceID, v)) +} + +// Type applies equality check predicate on the "type" field. It's identical to TypeEQ. +func Type(v meta.ChargeType) predicate.Charge { + vc := string(v) + return predicate.Charge(sql.FieldEQ(FieldType, vc)) +} + +// ChargeFlatFeeID applies equality check predicate on the "charge_flat_fee_id" field. It's identical to ChargeFlatFeeIDEQ. +func ChargeFlatFeeID(v string) predicate.Charge { + return predicate.Charge(sql.FieldEQ(FieldChargeFlatFeeID, v)) +} + +// ChargeCreditPurchaseID applies equality check predicate on the "charge_credit_purchase_id" field. It's identical to ChargeCreditPurchaseIDEQ. +func ChargeCreditPurchaseID(v string) predicate.Charge { + return predicate.Charge(sql.FieldEQ(FieldChargeCreditPurchaseID, v)) +} + +// ChargeUsageBasedID applies equality check predicate on the "charge_usage_based_id" field. It's identical to ChargeUsageBasedIDEQ. +func ChargeUsageBasedID(v string) predicate.Charge { + return predicate.Charge(sql.FieldEQ(FieldChargeUsageBasedID, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.Charge { + return predicate.Charge(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.Charge { + return predicate.Charge(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.Charge { + return predicate.Charge(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.Charge { + return predicate.Charge(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.Charge { + return predicate.Charge(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.Charge { + return predicate.Charge(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.Charge { + return predicate.Charge(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.Charge { + return predicate.Charge(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.Charge { + return predicate.Charge(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.Charge { + return predicate.Charge(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.Charge { + return predicate.Charge(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.Charge { + return predicate.Charge(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.Charge { + return predicate.Charge(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Charge { + return predicate.Charge(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Charge { + return predicate.Charge(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Charge { + return predicate.Charge(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Charge { + return predicate.Charge(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Charge { + return predicate.Charge(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Charge { + return predicate.Charge(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Charge { + return predicate.Charge(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Charge { + return predicate.Charge(sql.FieldLTE(FieldCreatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.Charge { + return predicate.Charge(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.Charge { + return predicate.Charge(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.Charge { + return predicate.Charge(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.Charge { + return predicate.Charge(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.Charge { + return predicate.Charge(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.Charge { + return predicate.Charge(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.Charge { + return predicate.Charge(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.Charge { + return predicate.Charge(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.Charge { + return predicate.Charge(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.Charge { + return predicate.Charge(sql.FieldNotNull(FieldDeletedAt)) +} + +// UniqueReferenceIDEQ applies the EQ predicate on the "unique_reference_id" field. +func UniqueReferenceIDEQ(v string) predicate.Charge { + return predicate.Charge(sql.FieldEQ(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDNEQ applies the NEQ predicate on the "unique_reference_id" field. +func UniqueReferenceIDNEQ(v string) predicate.Charge { + return predicate.Charge(sql.FieldNEQ(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDIn applies the In predicate on the "unique_reference_id" field. +func UniqueReferenceIDIn(vs ...string) predicate.Charge { + return predicate.Charge(sql.FieldIn(FieldUniqueReferenceID, vs...)) +} + +// UniqueReferenceIDNotIn applies the NotIn predicate on the "unique_reference_id" field. +func UniqueReferenceIDNotIn(vs ...string) predicate.Charge { + return predicate.Charge(sql.FieldNotIn(FieldUniqueReferenceID, vs...)) +} + +// UniqueReferenceIDGT applies the GT predicate on the "unique_reference_id" field. +func UniqueReferenceIDGT(v string) predicate.Charge { + return predicate.Charge(sql.FieldGT(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDGTE applies the GTE predicate on the "unique_reference_id" field. +func UniqueReferenceIDGTE(v string) predicate.Charge { + return predicate.Charge(sql.FieldGTE(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDLT applies the LT predicate on the "unique_reference_id" field. +func UniqueReferenceIDLT(v string) predicate.Charge { + return predicate.Charge(sql.FieldLT(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDLTE applies the LTE predicate on the "unique_reference_id" field. +func UniqueReferenceIDLTE(v string) predicate.Charge { + return predicate.Charge(sql.FieldLTE(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDContains applies the Contains predicate on the "unique_reference_id" field. +func UniqueReferenceIDContains(v string) predicate.Charge { + return predicate.Charge(sql.FieldContains(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDHasPrefix applies the HasPrefix predicate on the "unique_reference_id" field. +func UniqueReferenceIDHasPrefix(v string) predicate.Charge { + return predicate.Charge(sql.FieldHasPrefix(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDHasSuffix applies the HasSuffix predicate on the "unique_reference_id" field. +func UniqueReferenceIDHasSuffix(v string) predicate.Charge { + return predicate.Charge(sql.FieldHasSuffix(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDIsNil applies the IsNil predicate on the "unique_reference_id" field. +func UniqueReferenceIDIsNil() predicate.Charge { + return predicate.Charge(sql.FieldIsNull(FieldUniqueReferenceID)) +} + +// UniqueReferenceIDNotNil applies the NotNil predicate on the "unique_reference_id" field. +func UniqueReferenceIDNotNil() predicate.Charge { + return predicate.Charge(sql.FieldNotNull(FieldUniqueReferenceID)) +} + +// UniqueReferenceIDEqualFold applies the EqualFold predicate on the "unique_reference_id" field. +func UniqueReferenceIDEqualFold(v string) predicate.Charge { + return predicate.Charge(sql.FieldEqualFold(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDContainsFold applies the ContainsFold predicate on the "unique_reference_id" field. +func UniqueReferenceIDContainsFold(v string) predicate.Charge { + return predicate.Charge(sql.FieldContainsFold(FieldUniqueReferenceID, v)) +} + +// TypeEQ applies the EQ predicate on the "type" field. +func TypeEQ(v meta.ChargeType) predicate.Charge { + vc := string(v) + return predicate.Charge(sql.FieldEQ(FieldType, vc)) +} + +// TypeNEQ applies the NEQ predicate on the "type" field. +func TypeNEQ(v meta.ChargeType) predicate.Charge { + vc := string(v) + return predicate.Charge(sql.FieldNEQ(FieldType, vc)) +} + +// TypeIn applies the In predicate on the "type" field. +func TypeIn(vs ...meta.ChargeType) predicate.Charge { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.Charge(sql.FieldIn(FieldType, v...)) +} + +// TypeNotIn applies the NotIn predicate on the "type" field. +func TypeNotIn(vs ...meta.ChargeType) predicate.Charge { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.Charge(sql.FieldNotIn(FieldType, v...)) +} + +// TypeGT applies the GT predicate on the "type" field. +func TypeGT(v meta.ChargeType) predicate.Charge { + vc := string(v) + return predicate.Charge(sql.FieldGT(FieldType, vc)) +} + +// TypeGTE applies the GTE predicate on the "type" field. +func TypeGTE(v meta.ChargeType) predicate.Charge { + vc := string(v) + return predicate.Charge(sql.FieldGTE(FieldType, vc)) +} + +// TypeLT applies the LT predicate on the "type" field. +func TypeLT(v meta.ChargeType) predicate.Charge { + vc := string(v) + return predicate.Charge(sql.FieldLT(FieldType, vc)) +} + +// TypeLTE applies the LTE predicate on the "type" field. +func TypeLTE(v meta.ChargeType) predicate.Charge { + vc := string(v) + return predicate.Charge(sql.FieldLTE(FieldType, vc)) +} + +// TypeContains applies the Contains predicate on the "type" field. +func TypeContains(v meta.ChargeType) predicate.Charge { + vc := string(v) + return predicate.Charge(sql.FieldContains(FieldType, vc)) +} + +// TypeHasPrefix applies the HasPrefix predicate on the "type" field. +func TypeHasPrefix(v meta.ChargeType) predicate.Charge { + vc := string(v) + return predicate.Charge(sql.FieldHasPrefix(FieldType, vc)) +} + +// TypeHasSuffix applies the HasSuffix predicate on the "type" field. +func TypeHasSuffix(v meta.ChargeType) predicate.Charge { + vc := string(v) + return predicate.Charge(sql.FieldHasSuffix(FieldType, vc)) +} + +// TypeEqualFold applies the EqualFold predicate on the "type" field. +func TypeEqualFold(v meta.ChargeType) predicate.Charge { + vc := string(v) + return predicate.Charge(sql.FieldEqualFold(FieldType, vc)) +} + +// TypeContainsFold applies the ContainsFold predicate on the "type" field. +func TypeContainsFold(v meta.ChargeType) predicate.Charge { + vc := string(v) + return predicate.Charge(sql.FieldContainsFold(FieldType, vc)) +} + +// ChargeFlatFeeIDEQ applies the EQ predicate on the "charge_flat_fee_id" field. +func ChargeFlatFeeIDEQ(v string) predicate.Charge { + return predicate.Charge(sql.FieldEQ(FieldChargeFlatFeeID, v)) +} + +// ChargeFlatFeeIDNEQ applies the NEQ predicate on the "charge_flat_fee_id" field. +func ChargeFlatFeeIDNEQ(v string) predicate.Charge { + return predicate.Charge(sql.FieldNEQ(FieldChargeFlatFeeID, v)) +} + +// ChargeFlatFeeIDIn applies the In predicate on the "charge_flat_fee_id" field. +func ChargeFlatFeeIDIn(vs ...string) predicate.Charge { + return predicate.Charge(sql.FieldIn(FieldChargeFlatFeeID, vs...)) +} + +// ChargeFlatFeeIDNotIn applies the NotIn predicate on the "charge_flat_fee_id" field. +func ChargeFlatFeeIDNotIn(vs ...string) predicate.Charge { + return predicate.Charge(sql.FieldNotIn(FieldChargeFlatFeeID, vs...)) +} + +// ChargeFlatFeeIDGT applies the GT predicate on the "charge_flat_fee_id" field. +func ChargeFlatFeeIDGT(v string) predicate.Charge { + return predicate.Charge(sql.FieldGT(FieldChargeFlatFeeID, v)) +} + +// ChargeFlatFeeIDGTE applies the GTE predicate on the "charge_flat_fee_id" field. +func ChargeFlatFeeIDGTE(v string) predicate.Charge { + return predicate.Charge(sql.FieldGTE(FieldChargeFlatFeeID, v)) +} + +// ChargeFlatFeeIDLT applies the LT predicate on the "charge_flat_fee_id" field. +func ChargeFlatFeeIDLT(v string) predicate.Charge { + return predicate.Charge(sql.FieldLT(FieldChargeFlatFeeID, v)) +} + +// ChargeFlatFeeIDLTE applies the LTE predicate on the "charge_flat_fee_id" field. +func ChargeFlatFeeIDLTE(v string) predicate.Charge { + return predicate.Charge(sql.FieldLTE(FieldChargeFlatFeeID, v)) +} + +// ChargeFlatFeeIDContains applies the Contains predicate on the "charge_flat_fee_id" field. +func ChargeFlatFeeIDContains(v string) predicate.Charge { + return predicate.Charge(sql.FieldContains(FieldChargeFlatFeeID, v)) +} + +// ChargeFlatFeeIDHasPrefix applies the HasPrefix predicate on the "charge_flat_fee_id" field. +func ChargeFlatFeeIDHasPrefix(v string) predicate.Charge { + return predicate.Charge(sql.FieldHasPrefix(FieldChargeFlatFeeID, v)) +} + +// ChargeFlatFeeIDHasSuffix applies the HasSuffix predicate on the "charge_flat_fee_id" field. +func ChargeFlatFeeIDHasSuffix(v string) predicate.Charge { + return predicate.Charge(sql.FieldHasSuffix(FieldChargeFlatFeeID, v)) +} + +// ChargeFlatFeeIDIsNil applies the IsNil predicate on the "charge_flat_fee_id" field. +func ChargeFlatFeeIDIsNil() predicate.Charge { + return predicate.Charge(sql.FieldIsNull(FieldChargeFlatFeeID)) +} + +// ChargeFlatFeeIDNotNil applies the NotNil predicate on the "charge_flat_fee_id" field. +func ChargeFlatFeeIDNotNil() predicate.Charge { + return predicate.Charge(sql.FieldNotNull(FieldChargeFlatFeeID)) +} + +// ChargeFlatFeeIDEqualFold applies the EqualFold predicate on the "charge_flat_fee_id" field. +func ChargeFlatFeeIDEqualFold(v string) predicate.Charge { + return predicate.Charge(sql.FieldEqualFold(FieldChargeFlatFeeID, v)) +} + +// ChargeFlatFeeIDContainsFold applies the ContainsFold predicate on the "charge_flat_fee_id" field. +func ChargeFlatFeeIDContainsFold(v string) predicate.Charge { + return predicate.Charge(sql.FieldContainsFold(FieldChargeFlatFeeID, v)) +} + +// ChargeCreditPurchaseIDEQ applies the EQ predicate on the "charge_credit_purchase_id" field. +func ChargeCreditPurchaseIDEQ(v string) predicate.Charge { + return predicate.Charge(sql.FieldEQ(FieldChargeCreditPurchaseID, v)) +} + +// ChargeCreditPurchaseIDNEQ applies the NEQ predicate on the "charge_credit_purchase_id" field. +func ChargeCreditPurchaseIDNEQ(v string) predicate.Charge { + return predicate.Charge(sql.FieldNEQ(FieldChargeCreditPurchaseID, v)) +} + +// ChargeCreditPurchaseIDIn applies the In predicate on the "charge_credit_purchase_id" field. +func ChargeCreditPurchaseIDIn(vs ...string) predicate.Charge { + return predicate.Charge(sql.FieldIn(FieldChargeCreditPurchaseID, vs...)) +} + +// ChargeCreditPurchaseIDNotIn applies the NotIn predicate on the "charge_credit_purchase_id" field. +func ChargeCreditPurchaseIDNotIn(vs ...string) predicate.Charge { + return predicate.Charge(sql.FieldNotIn(FieldChargeCreditPurchaseID, vs...)) +} + +// ChargeCreditPurchaseIDGT applies the GT predicate on the "charge_credit_purchase_id" field. +func ChargeCreditPurchaseIDGT(v string) predicate.Charge { + return predicate.Charge(sql.FieldGT(FieldChargeCreditPurchaseID, v)) +} + +// ChargeCreditPurchaseIDGTE applies the GTE predicate on the "charge_credit_purchase_id" field. +func ChargeCreditPurchaseIDGTE(v string) predicate.Charge { + return predicate.Charge(sql.FieldGTE(FieldChargeCreditPurchaseID, v)) +} + +// ChargeCreditPurchaseIDLT applies the LT predicate on the "charge_credit_purchase_id" field. +func ChargeCreditPurchaseIDLT(v string) predicate.Charge { + return predicate.Charge(sql.FieldLT(FieldChargeCreditPurchaseID, v)) +} + +// ChargeCreditPurchaseIDLTE applies the LTE predicate on the "charge_credit_purchase_id" field. +func ChargeCreditPurchaseIDLTE(v string) predicate.Charge { + return predicate.Charge(sql.FieldLTE(FieldChargeCreditPurchaseID, v)) +} + +// ChargeCreditPurchaseIDContains applies the Contains predicate on the "charge_credit_purchase_id" field. +func ChargeCreditPurchaseIDContains(v string) predicate.Charge { + return predicate.Charge(sql.FieldContains(FieldChargeCreditPurchaseID, v)) +} + +// ChargeCreditPurchaseIDHasPrefix applies the HasPrefix predicate on the "charge_credit_purchase_id" field. +func ChargeCreditPurchaseIDHasPrefix(v string) predicate.Charge { + return predicate.Charge(sql.FieldHasPrefix(FieldChargeCreditPurchaseID, v)) +} + +// ChargeCreditPurchaseIDHasSuffix applies the HasSuffix predicate on the "charge_credit_purchase_id" field. +func ChargeCreditPurchaseIDHasSuffix(v string) predicate.Charge { + return predicate.Charge(sql.FieldHasSuffix(FieldChargeCreditPurchaseID, v)) +} + +// ChargeCreditPurchaseIDIsNil applies the IsNil predicate on the "charge_credit_purchase_id" field. +func ChargeCreditPurchaseIDIsNil() predicate.Charge { + return predicate.Charge(sql.FieldIsNull(FieldChargeCreditPurchaseID)) +} + +// ChargeCreditPurchaseIDNotNil applies the NotNil predicate on the "charge_credit_purchase_id" field. +func ChargeCreditPurchaseIDNotNil() predicate.Charge { + return predicate.Charge(sql.FieldNotNull(FieldChargeCreditPurchaseID)) +} + +// ChargeCreditPurchaseIDEqualFold applies the EqualFold predicate on the "charge_credit_purchase_id" field. +func ChargeCreditPurchaseIDEqualFold(v string) predicate.Charge { + return predicate.Charge(sql.FieldEqualFold(FieldChargeCreditPurchaseID, v)) +} + +// ChargeCreditPurchaseIDContainsFold applies the ContainsFold predicate on the "charge_credit_purchase_id" field. +func ChargeCreditPurchaseIDContainsFold(v string) predicate.Charge { + return predicate.Charge(sql.FieldContainsFold(FieldChargeCreditPurchaseID, v)) +} + +// ChargeUsageBasedIDEQ applies the EQ predicate on the "charge_usage_based_id" field. +func ChargeUsageBasedIDEQ(v string) predicate.Charge { + return predicate.Charge(sql.FieldEQ(FieldChargeUsageBasedID, v)) +} + +// ChargeUsageBasedIDNEQ applies the NEQ predicate on the "charge_usage_based_id" field. +func ChargeUsageBasedIDNEQ(v string) predicate.Charge { + return predicate.Charge(sql.FieldNEQ(FieldChargeUsageBasedID, v)) +} + +// ChargeUsageBasedIDIn applies the In predicate on the "charge_usage_based_id" field. +func ChargeUsageBasedIDIn(vs ...string) predicate.Charge { + return predicate.Charge(sql.FieldIn(FieldChargeUsageBasedID, vs...)) +} + +// ChargeUsageBasedIDNotIn applies the NotIn predicate on the "charge_usage_based_id" field. +func ChargeUsageBasedIDNotIn(vs ...string) predicate.Charge { + return predicate.Charge(sql.FieldNotIn(FieldChargeUsageBasedID, vs...)) +} + +// ChargeUsageBasedIDGT applies the GT predicate on the "charge_usage_based_id" field. +func ChargeUsageBasedIDGT(v string) predicate.Charge { + return predicate.Charge(sql.FieldGT(FieldChargeUsageBasedID, v)) +} + +// ChargeUsageBasedIDGTE applies the GTE predicate on the "charge_usage_based_id" field. +func ChargeUsageBasedIDGTE(v string) predicate.Charge { + return predicate.Charge(sql.FieldGTE(FieldChargeUsageBasedID, v)) +} + +// ChargeUsageBasedIDLT applies the LT predicate on the "charge_usage_based_id" field. +func ChargeUsageBasedIDLT(v string) predicate.Charge { + return predicate.Charge(sql.FieldLT(FieldChargeUsageBasedID, v)) +} + +// ChargeUsageBasedIDLTE applies the LTE predicate on the "charge_usage_based_id" field. +func ChargeUsageBasedIDLTE(v string) predicate.Charge { + return predicate.Charge(sql.FieldLTE(FieldChargeUsageBasedID, v)) +} + +// ChargeUsageBasedIDContains applies the Contains predicate on the "charge_usage_based_id" field. +func ChargeUsageBasedIDContains(v string) predicate.Charge { + return predicate.Charge(sql.FieldContains(FieldChargeUsageBasedID, v)) +} + +// ChargeUsageBasedIDHasPrefix applies the HasPrefix predicate on the "charge_usage_based_id" field. +func ChargeUsageBasedIDHasPrefix(v string) predicate.Charge { + return predicate.Charge(sql.FieldHasPrefix(FieldChargeUsageBasedID, v)) +} + +// ChargeUsageBasedIDHasSuffix applies the HasSuffix predicate on the "charge_usage_based_id" field. +func ChargeUsageBasedIDHasSuffix(v string) predicate.Charge { + return predicate.Charge(sql.FieldHasSuffix(FieldChargeUsageBasedID, v)) +} + +// ChargeUsageBasedIDIsNil applies the IsNil predicate on the "charge_usage_based_id" field. +func ChargeUsageBasedIDIsNil() predicate.Charge { + return predicate.Charge(sql.FieldIsNull(FieldChargeUsageBasedID)) +} + +// ChargeUsageBasedIDNotNil applies the NotNil predicate on the "charge_usage_based_id" field. +func ChargeUsageBasedIDNotNil() predicate.Charge { + return predicate.Charge(sql.FieldNotNull(FieldChargeUsageBasedID)) +} + +// ChargeUsageBasedIDEqualFold applies the EqualFold predicate on the "charge_usage_based_id" field. +func ChargeUsageBasedIDEqualFold(v string) predicate.Charge { + return predicate.Charge(sql.FieldEqualFold(FieldChargeUsageBasedID, v)) +} + +// ChargeUsageBasedIDContainsFold applies the ContainsFold predicate on the "charge_usage_based_id" field. +func ChargeUsageBasedIDContainsFold(v string) predicate.Charge { + return predicate.Charge(sql.FieldContainsFold(FieldChargeUsageBasedID, v)) +} + +// HasFlatFee applies the HasEdge predicate on the "flat_fee" edge. +func HasFlatFee() predicate.Charge { + return predicate.Charge(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, FlatFeeTable, FlatFeeColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasFlatFeeWith applies the HasEdge predicate on the "flat_fee" edge with a given conditions (other predicates). +func HasFlatFeeWith(preds ...predicate.ChargeFlatFee) predicate.Charge { + return predicate.Charge(func(s *sql.Selector) { + step := newFlatFeeStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasCreditPurchase applies the HasEdge predicate on the "credit_purchase" edge. +func HasCreditPurchase() predicate.Charge { + return predicate.Charge(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, CreditPurchaseTable, CreditPurchaseColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCreditPurchaseWith applies the HasEdge predicate on the "credit_purchase" edge with a given conditions (other predicates). +func HasCreditPurchaseWith(preds ...predicate.ChargeCreditPurchase) predicate.Charge { + return predicate.Charge(func(s *sql.Selector) { + step := newCreditPurchaseStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// 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, 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.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) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, BillingInvoiceLinesTable, BillingInvoiceLinesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBillingInvoiceLinesWith applies the HasEdge predicate on the "billing_invoice_lines" edge with a given conditions (other predicates). +func HasBillingInvoiceLinesWith(preds ...predicate.BillingInvoiceLine) predicate.Charge { + return predicate.Charge(func(s *sql.Selector) { + step := newBillingInvoiceLinesStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasBillingSplitLineGroups applies the HasEdge predicate on the "billing_split_line_groups" edge. +func HasBillingSplitLineGroups() predicate.Charge { + return predicate.Charge(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, BillingSplitLineGroupsTable, BillingSplitLineGroupsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBillingSplitLineGroupsWith applies the HasEdge predicate on the "billing_split_line_groups" edge with a given conditions (other predicates). +func HasBillingSplitLineGroupsWith(preds ...predicate.BillingInvoiceSplitLineGroup) predicate.Charge { + return predicate.Charge(func(s *sql.Selector) { + step := newBillingSplitLineGroupsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasCreditRealizationLineages applies the HasEdge predicate on the "credit_realization_lineages" edge. +func HasCreditRealizationLineages() predicate.Charge { + return predicate.Charge(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, CreditRealizationLineagesTable, CreditRealizationLineagesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCreditRealizationLineagesWith applies the HasEdge predicate on the "credit_realization_lineages" edge with a given conditions (other predicates). +func HasCreditRealizationLineagesWith(preds ...predicate.CreditRealizationLineage) predicate.Charge { + return predicate.Charge(func(s *sql.Selector) { + step := newCreditRealizationLineagesStep() + 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.Charge) predicate.Charge { + return predicate.Charge(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Charge) predicate.Charge { + return predicate.Charge(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Charge) predicate.Charge { + return predicate.Charge(sql.NotPredicates(p)) +} diff --git a/ent/db/charge_create.go b/ent/db/charge_create.go new file mode 100644 index 0000000000000000000000000000000000000000..a698ec5666902493fc7c5e96027bbe4ac45784c4 --- /dev/null +++ b/ent/db/charge_create.go @@ -0,0 +1,909 @@ +// 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/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicesplitlinegroup" + "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/creditrealizationlineage" +) + +// ChargeCreate is the builder for creating a Charge entity. +type ChargeCreate struct { + config + mutation *ChargeMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *ChargeCreate) SetNamespace(v string) *ChargeCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ChargeCreate) SetCreatedAt(v time.Time) *ChargeCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *ChargeCreate) SetNillableCreatedAt(v *time.Time) *ChargeCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *ChargeCreate) SetDeletedAt(v time.Time) *ChargeCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *ChargeCreate) SetNillableDeletedAt(v *time.Time) *ChargeCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetUniqueReferenceID sets the "unique_reference_id" field. +func (_c *ChargeCreate) SetUniqueReferenceID(v string) *ChargeCreate { + _c.mutation.SetUniqueReferenceID(v) + return _c +} + +// SetNillableUniqueReferenceID sets the "unique_reference_id" field if the given value is not nil. +func (_c *ChargeCreate) SetNillableUniqueReferenceID(v *string) *ChargeCreate { + if v != nil { + _c.SetUniqueReferenceID(*v) + } + return _c +} + +// SetType sets the "type" field. +func (_c *ChargeCreate) SetType(v meta.ChargeType) *ChargeCreate { + _c.mutation.SetType(v) + return _c +} + +// SetChargeFlatFeeID sets the "charge_flat_fee_id" field. +func (_c *ChargeCreate) SetChargeFlatFeeID(v string) *ChargeCreate { + _c.mutation.SetChargeFlatFeeID(v) + return _c +} + +// SetNillableChargeFlatFeeID sets the "charge_flat_fee_id" field if the given value is not nil. +func (_c *ChargeCreate) SetNillableChargeFlatFeeID(v *string) *ChargeCreate { + if v != nil { + _c.SetChargeFlatFeeID(*v) + } + return _c +} + +// SetChargeCreditPurchaseID sets the "charge_credit_purchase_id" field. +func (_c *ChargeCreate) SetChargeCreditPurchaseID(v string) *ChargeCreate { + _c.mutation.SetChargeCreditPurchaseID(v) + return _c +} + +// SetNillableChargeCreditPurchaseID sets the "charge_credit_purchase_id" field if the given value is not nil. +func (_c *ChargeCreate) SetNillableChargeCreditPurchaseID(v *string) *ChargeCreate { + if v != nil { + _c.SetChargeCreditPurchaseID(*v) + } + return _c +} + +// SetChargeUsageBasedID sets the "charge_usage_based_id" field. +func (_c *ChargeCreate) SetChargeUsageBasedID(v string) *ChargeCreate { + _c.mutation.SetChargeUsageBasedID(v) + return _c +} + +// SetNillableChargeUsageBasedID sets the "charge_usage_based_id" field if the given value is not nil. +func (_c *ChargeCreate) SetNillableChargeUsageBasedID(v *string) *ChargeCreate { + if v != nil { + _c.SetChargeUsageBasedID(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *ChargeCreate) SetID(v string) *ChargeCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ChargeCreate) SetNillableID(v *string) *ChargeCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetFlatFeeID sets the "flat_fee" edge to the ChargeFlatFee entity by ID. +func (_c *ChargeCreate) SetFlatFeeID(id string) *ChargeCreate { + _c.mutation.SetFlatFeeID(id) + return _c +} + +// SetNillableFlatFeeID sets the "flat_fee" edge to the ChargeFlatFee entity by ID if the given value is not nil. +func (_c *ChargeCreate) SetNillableFlatFeeID(id *string) *ChargeCreate { + if id != nil { + _c = _c.SetFlatFeeID(*id) + } + return _c +} + +// SetFlatFee sets the "flat_fee" edge to the ChargeFlatFee entity. +func (_c *ChargeCreate) SetFlatFee(v *ChargeFlatFee) *ChargeCreate { + return _c.SetFlatFeeID(v.ID) +} + +// SetCreditPurchaseID sets the "credit_purchase" edge to the ChargeCreditPurchase entity by ID. +func (_c *ChargeCreate) SetCreditPurchaseID(id string) *ChargeCreate { + _c.mutation.SetCreditPurchaseID(id) + return _c +} + +// SetNillableCreditPurchaseID sets the "credit_purchase" edge to the ChargeCreditPurchase entity by ID if the given value is not nil. +func (_c *ChargeCreate) SetNillableCreditPurchaseID(id *string) *ChargeCreate { + if id != nil { + _c = _c.SetCreditPurchaseID(*id) + } + return _c +} + +// SetCreditPurchase sets the "credit_purchase" edge to the ChargeCreditPurchase entity. +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...) + return _c +} + +// AddBillingInvoiceLines adds the "billing_invoice_lines" edges to the BillingInvoiceLine entity. +func (_c *ChargeCreate) AddBillingInvoiceLines(v ...*BillingInvoiceLine) *ChargeCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddBillingInvoiceLineIDs(ids...) +} + +// AddBillingSplitLineGroupIDs adds the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity by IDs. +func (_c *ChargeCreate) AddBillingSplitLineGroupIDs(ids ...string) *ChargeCreate { + _c.mutation.AddBillingSplitLineGroupIDs(ids...) + return _c +} + +// AddBillingSplitLineGroups adds the "billing_split_line_groups" edges to the BillingInvoiceSplitLineGroup entity. +func (_c *ChargeCreate) AddBillingSplitLineGroups(v ...*BillingInvoiceSplitLineGroup) *ChargeCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddBillingSplitLineGroupIDs(ids...) +} + +// AddCreditRealizationLineageIDs adds the "credit_realization_lineages" edge to the CreditRealizationLineage entity by IDs. +func (_c *ChargeCreate) AddCreditRealizationLineageIDs(ids ...string) *ChargeCreate { + _c.mutation.AddCreditRealizationLineageIDs(ids...) + return _c +} + +// AddCreditRealizationLineages adds the "credit_realization_lineages" edges to the CreditRealizationLineage entity. +func (_c *ChargeCreate) AddCreditRealizationLineages(v ...*CreditRealizationLineage) *ChargeCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddCreditRealizationLineageIDs(ids...) +} + +// Mutation returns the ChargeMutation object of the builder. +func (_c *ChargeCreate) Mutation() *ChargeMutation { + return _c.mutation +} + +// Save creates the Charge in the database. +func (_c *ChargeCreate) Save(ctx context.Context) (*Charge, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ChargeCreate) SaveX(ctx context.Context) *Charge { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeCreate) 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 *ChargeCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := charge.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := charge.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ChargeCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "Charge.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := charge.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "Charge.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "Charge.created_at"`)} + } + if v, ok := _c.mutation.UniqueReferenceID(); ok { + if err := charge.UniqueReferenceIDValidator(v); err != nil { + return &ValidationError{Name: "unique_reference_id", err: fmt.Errorf(`db: validator failed for field "Charge.unique_reference_id": %w`, err)} + } + } + if _, ok := _c.mutation.GetType(); !ok { + return &ValidationError{Name: "type", err: errors.New(`db: missing required field "Charge.type"`)} + } + if v, ok := _c.mutation.GetType(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "type", err: fmt.Errorf(`db: validator failed for field "Charge.type": %w`, err)} + } + } + return nil +} + +func (_c *ChargeCreate) sqlSave(ctx context.Context) (*Charge, 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 Charge.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ChargeCreate) createSpec() (*Charge, *sqlgraph.CreateSpec) { + var ( + _node = &Charge{config: _c.config} + _spec = sqlgraph.NewCreateSpec(charge.Table, sqlgraph.NewFieldSpec(charge.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(charge.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(charge.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(charge.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.UniqueReferenceID(); ok { + _spec.SetField(charge.FieldUniqueReferenceID, field.TypeString, value) + _node.UniqueReferenceID = &value + } + if value, ok := _c.mutation.GetType(); ok { + _spec.SetField(charge.FieldType, field.TypeString, value) + _node.Type = value + } + if nodes := _c.mutation.FlatFeeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: charge.FlatFeeTable, + Columns: []string{charge.FlatFeeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfee.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.ChargeFlatFeeID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.CreditPurchaseIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: charge.CreditPurchaseTable, + Columns: []string{charge.CreditPurchaseColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchase.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.ChargeCreditPurchaseID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.UsageBasedIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + 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) + } + _node.ChargeUsageBasedID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.BillingInvoiceLinesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.BillingInvoiceLinesTable, + Columns: []string{charge.BillingInvoiceLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.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.BillingSplitLineGroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.BillingSplitLineGroupsTable, + Columns: []string{charge.BillingSplitLineGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoicesplitlinegroup.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.CreditRealizationLineagesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.CreditRealizationLineagesTable, + Columns: []string{charge.CreditRealizationLineagesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(creditrealizationlineage.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.Charge.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.ChargeUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *ChargeCreate) OnConflict(opts ...sql.ConflictOption) *ChargeUpsertOne { + _c.conflict = opts + return &ChargeUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Charge.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeCreate) OnConflictColumns(columns ...string) *ChargeUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeUpsertOne{ + create: _c, + } +} + +type ( + // ChargeUpsertOne is the builder for "upsert"-ing + // one Charge node. + ChargeUpsertOne struct { + create *ChargeCreate + } + + // ChargeUpsert is the "OnConflict" setter. + ChargeUpsert struct { + *sql.UpdateSet + } +) + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUpsert) SetDeletedAt(v time.Time) *ChargeUpsert { + u.Set(charge.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUpsert) UpdateDeletedAt() *ChargeUpsert { + u.SetExcluded(charge.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUpsert) ClearDeletedAt() *ChargeUpsert { + u.SetNull(charge.FieldDeletedAt) + 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.Charge.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(charge.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeUpsertOne) UpdateNewValues() *ChargeUpsertOne { + 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(charge.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(charge.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(charge.FieldCreatedAt) + } + if _, exists := u.create.mutation.UniqueReferenceID(); exists { + s.SetIgnore(charge.FieldUniqueReferenceID) + } + if _, exists := u.create.mutation.GetType(); exists { + s.SetIgnore(charge.FieldType) + } + if _, exists := u.create.mutation.ChargeFlatFeeID(); exists { + s.SetIgnore(charge.FieldChargeFlatFeeID) + } + if _, exists := u.create.mutation.ChargeCreditPurchaseID(); exists { + s.SetIgnore(charge.FieldChargeCreditPurchaseID) + } + if _, exists := u.create.mutation.ChargeUsageBasedID(); exists { + s.SetIgnore(charge.FieldChargeUsageBasedID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Charge.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeUpsertOne) Ignore() *ChargeUpsertOne { + 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 *ChargeUpsertOne) DoNothing() *ChargeUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeCreate.OnConflict +// documentation for more info. +func (u *ChargeUpsertOne) Update(set func(*ChargeUpsert)) *ChargeUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeUpsert{UpdateSet: update}) + })) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUpsertOne) SetDeletedAt(v time.Time) *ChargeUpsertOne { + return u.Update(func(s *ChargeUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUpsertOne) UpdateDeletedAt() *ChargeUpsertOne { + return u.Update(func(s *ChargeUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUpsertOne) ClearDeletedAt() *ChargeUpsertOne { + return u.Update(func(s *ChargeUpsert) { + s.ClearDeletedAt() + }) +} + +// Exec executes the query. +func (u *ChargeUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeUpsertOne) 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 *ChargeUpsertOne) 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: ChargeUpsertOne.ID is not supported by MySQL driver. Use ChargeUpsertOne.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 *ChargeUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ChargeCreateBulk is the builder for creating many Charge entities in bulk. +type ChargeCreateBulk struct { + config + err error + builders []*ChargeCreate + conflict []sql.ConflictOption +} + +// Save creates the Charge entities in the database. +func (_c *ChargeCreateBulk) Save(ctx context.Context) ([]*Charge, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Charge, 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.(*ChargeMutation) + 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 *ChargeCreateBulk) SaveX(ctx context.Context) []*Charge { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeCreateBulk) 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.Charge.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.ChargeUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *ChargeCreateBulk) OnConflict(opts ...sql.ConflictOption) *ChargeUpsertBulk { + _c.conflict = opts + return &ChargeUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Charge.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeCreateBulk) OnConflictColumns(columns ...string) *ChargeUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeUpsertBulk{ + create: _c, + } +} + +// ChargeUpsertBulk is the builder for "upsert"-ing +// a bulk of Charge nodes. +type ChargeUpsertBulk struct { + create *ChargeCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.Charge.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(charge.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeUpsertBulk) UpdateNewValues() *ChargeUpsertBulk { + 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(charge.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(charge.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(charge.FieldCreatedAt) + } + if _, exists := b.mutation.UniqueReferenceID(); exists { + s.SetIgnore(charge.FieldUniqueReferenceID) + } + if _, exists := b.mutation.GetType(); exists { + s.SetIgnore(charge.FieldType) + } + if _, exists := b.mutation.ChargeFlatFeeID(); exists { + s.SetIgnore(charge.FieldChargeFlatFeeID) + } + if _, exists := b.mutation.ChargeCreditPurchaseID(); exists { + s.SetIgnore(charge.FieldChargeCreditPurchaseID) + } + if _, exists := b.mutation.ChargeUsageBasedID(); exists { + s.SetIgnore(charge.FieldChargeUsageBasedID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Charge.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeUpsertBulk) Ignore() *ChargeUpsertBulk { + 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 *ChargeUpsertBulk) DoNothing() *ChargeUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeCreateBulk.OnConflict +// documentation for more info. +func (u *ChargeUpsertBulk) Update(set func(*ChargeUpsert)) *ChargeUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeUpsert{UpdateSet: update}) + })) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUpsertBulk) SetDeletedAt(v time.Time) *ChargeUpsertBulk { + return u.Update(func(s *ChargeUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUpsertBulk) UpdateDeletedAt() *ChargeUpsertBulk { + return u.Update(func(s *ChargeUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUpsertBulk) ClearDeletedAt() *ChargeUpsertBulk { + return u.Update(func(s *ChargeUpsert) { + s.ClearDeletedAt() + }) +} + +// Exec executes the query. +func (u *ChargeUpsertBulk) 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 ChargeCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/charge_delete.go b/ent/db/charge_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..81153b79c015d511acd110e301712b5e5f4b4149 --- /dev/null +++ b/ent/db/charge_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/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeDelete is the builder for deleting a Charge entity. +type ChargeDelete struct { + config + hooks []Hook + mutation *ChargeMutation +} + +// Where appends a list predicates to the ChargeDelete builder. +func (_d *ChargeDelete) Where(ps ...predicate.Charge) *ChargeDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ChargeDelete) 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 *ChargeDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ChargeDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(charge.Table, sqlgraph.NewFieldSpec(charge.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 +} + +// ChargeDeleteOne is the builder for deleting a single Charge entity. +type ChargeDeleteOne struct { + _d *ChargeDelete +} + +// Where appends a list predicates to the ChargeDelete builder. +func (_d *ChargeDeleteOne) Where(ps ...predicate.Charge) *ChargeDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ChargeDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{charge.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/charge_query.go b/ent/db/charge_query.go new file mode 100644 index 0000000000000000000000000000000000000000..0596d13840a5922aa76f6649073f855bbadffcef --- /dev/null +++ b/ent/db/charge_query.go @@ -0,0 +1,1038 @@ +// 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/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicesplitlinegroup" + "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/creditrealizationlineage" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeQuery is the builder for querying Charge entities. +type ChargeQuery struct { + config + ctx *QueryContext + order []charge.OrderOption + inters []Interceptor + predicates []predicate.Charge + withFlatFee *ChargeFlatFeeQuery + withCreditPurchase *ChargeCreditPurchaseQuery + withUsageBased *ChargeUsageBasedQuery + withBillingInvoiceLines *BillingInvoiceLineQuery + withBillingSplitLineGroups *BillingInvoiceSplitLineGroupQuery + withCreditRealizationLineages *CreditRealizationLineageQuery + 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 ChargeQuery builder. +func (_q *ChargeQuery) Where(ps ...predicate.Charge) *ChargeQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ChargeQuery) Limit(limit int) *ChargeQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ChargeQuery) Offset(offset int) *ChargeQuery { + _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 *ChargeQuery) Unique(unique bool) *ChargeQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ChargeQuery) Order(o ...charge.OrderOption) *ChargeQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryFlatFee chains the current query on the "flat_fee" edge. +func (_q *ChargeQuery) QueryFlatFee() *ChargeFlatFeeQuery { + query := (&ChargeFlatFeeClient{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(chargeflatfee.Table, chargeflatfee.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, charge.FlatFeeTable, charge.FlatFeeColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCreditPurchase chains the current query on the "credit_purchase" edge. +func (_q *ChargeQuery) QueryCreditPurchase() *ChargeCreditPurchaseQuery { + query := (&ChargeCreditPurchaseClient{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(chargecreditpurchase.Table, chargecreditpurchase.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, charge.CreditPurchaseTable, charge.CreditPurchaseColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + 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, true, 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() + 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(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, charge.BillingInvoiceLinesTable, charge.BillingInvoiceLinesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryBillingSplitLineGroups chains the current query on the "billing_split_line_groups" edge. +func (_q *ChargeQuery) QueryBillingSplitLineGroups() *BillingInvoiceSplitLineGroupQuery { + query := (&BillingInvoiceSplitLineGroupClient{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(billinginvoicesplitlinegroup.Table, billinginvoicesplitlinegroup.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, charge.BillingSplitLineGroupsTable, charge.BillingSplitLineGroupsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCreditRealizationLineages chains the current query on the "credit_realization_lineages" edge. +func (_q *ChargeQuery) QueryCreditRealizationLineages() *CreditRealizationLineageQuery { + query := (&CreditRealizationLineageClient{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(creditrealizationlineage.Table, creditrealizationlineage.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, charge.CreditRealizationLineagesTable, charge.CreditRealizationLineagesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Charge entity from the query. +// Returns a *NotFoundError when no Charge was found. +func (_q *ChargeQuery) First(ctx context.Context) (*Charge, 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{charge.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ChargeQuery) FirstX(ctx context.Context) *Charge { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Charge ID from the query. +// Returns a *NotFoundError when no Charge ID was found. +func (_q *ChargeQuery) 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{charge.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ChargeQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Charge entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Charge entity is found. +// Returns a *NotFoundError when no Charge entities are found. +func (_q *ChargeQuery) Only(ctx context.Context) (*Charge, 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{charge.Label} + default: + return nil, &NotSingularError{charge.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ChargeQuery) OnlyX(ctx context.Context) *Charge { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Charge ID in the query. +// Returns a *NotSingularError when more than one Charge ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ChargeQuery) 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{charge.Label} + default: + err = &NotSingularError{charge.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ChargeQuery) 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 Charges. +func (_q *ChargeQuery) All(ctx context.Context) ([]*Charge, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Charge, *ChargeQuery]() + return withInterceptors[[]*Charge](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ChargeQuery) AllX(ctx context.Context) []*Charge { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Charge IDs. +func (_q *ChargeQuery) 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(charge.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ChargeQuery) 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 *ChargeQuery) 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[*ChargeQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ChargeQuery) 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 *ChargeQuery) 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 *ChargeQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ChargeQuery 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 *ChargeQuery) Clone() *ChargeQuery { + if _q == nil { + return nil + } + return &ChargeQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]charge.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + 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(), + withCreditRealizationLineages: _q.withCreditRealizationLineages.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithFlatFee tells the query-builder to eager-load the nodes that are connected to +// the "flat_fee" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeQuery) WithFlatFee(opts ...func(*ChargeFlatFeeQuery)) *ChargeQuery { + query := (&ChargeFlatFeeClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withFlatFee = query + return _q +} + +// WithCreditPurchase tells the query-builder to eager-load the nodes that are connected to +// the "credit_purchase" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeQuery) WithCreditPurchase(opts ...func(*ChargeCreditPurchaseQuery)) *ChargeQuery { + query := (&ChargeCreditPurchaseClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCreditPurchase = query + 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 { + query := (&BillingInvoiceLineClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingInvoiceLines = query + return _q +} + +// WithBillingSplitLineGroups tells the query-builder to eager-load the nodes that are connected to +// the "billing_split_line_groups" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeQuery) WithBillingSplitLineGroups(opts ...func(*BillingInvoiceSplitLineGroupQuery)) *ChargeQuery { + query := (&BillingInvoiceSplitLineGroupClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingSplitLineGroups = query + return _q +} + +// WithCreditRealizationLineages tells the query-builder to eager-load the nodes that are connected to +// the "credit_realization_lineages" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeQuery) WithCreditRealizationLineages(opts ...func(*CreditRealizationLineageQuery)) *ChargeQuery { + query := (&CreditRealizationLineageClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCreditRealizationLineages = 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.Charge.Query(). +// GroupBy(charge.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *ChargeQuery) GroupBy(field string, fields ...string) *ChargeGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ChargeGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = charge.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.Charge.Query(). +// Select(charge.FieldNamespace). +// Scan(ctx, &v) +func (_q *ChargeQuery) Select(fields ...string) *ChargeSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ChargeSelect{ChargeQuery: _q} + sbuild.label = charge.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ChargeSelect configured with the given aggregations. +func (_q *ChargeQuery) Aggregate(fns ...AggregateFunc) *ChargeSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ChargeQuery) 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 !charge.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 *ChargeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Charge, error) { + var ( + nodes = []*Charge{} + _spec = _q.querySpec() + loadedTypes = [6]bool{ + _q.withFlatFee != nil, + _q.withCreditPurchase != nil, + _q.withUsageBased != nil, + _q.withBillingInvoiceLines != nil, + _q.withBillingSplitLineGroups != nil, + _q.withCreditRealizationLineages != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Charge).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Charge{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.withFlatFee; query != nil { + if err := _q.loadFlatFee(ctx, query, nodes, nil, + func(n *Charge, e *ChargeFlatFee) { n.Edges.FlatFee = e }); err != nil { + return nil, err + } + } + if query := _q.withCreditPurchase; query != nil { + if err := _q.loadCreditPurchase(ctx, query, nodes, nil, + func(n *Charge, e *ChargeCreditPurchase) { n.Edges.CreditPurchase = e }); err != nil { + 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{} }, + func(n *Charge, e *BillingInvoiceLine) { + n.Edges.BillingInvoiceLines = append(n.Edges.BillingInvoiceLines, e) + }); err != nil { + return nil, err + } + } + if query := _q.withBillingSplitLineGroups; query != nil { + if err := _q.loadBillingSplitLineGroups(ctx, query, nodes, + func(n *Charge) { n.Edges.BillingSplitLineGroups = []*BillingInvoiceSplitLineGroup{} }, + func(n *Charge, e *BillingInvoiceSplitLineGroup) { + n.Edges.BillingSplitLineGroups = append(n.Edges.BillingSplitLineGroups, e) + }); err != nil { + return nil, err + } + } + if query := _q.withCreditRealizationLineages; query != nil { + if err := _q.loadCreditRealizationLineages(ctx, query, nodes, + func(n *Charge) { n.Edges.CreditRealizationLineages = []*CreditRealizationLineage{} }, + func(n *Charge, e *CreditRealizationLineage) { + n.Edges.CreditRealizationLineages = append(n.Edges.CreditRealizationLineages, e) + }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ChargeQuery) loadFlatFee(ctx context.Context, query *ChargeFlatFeeQuery, nodes []*Charge, init func(*Charge), assign func(*Charge, *ChargeFlatFee)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*Charge) + for i := range nodes { + if nodes[i].ChargeFlatFeeID == nil { + continue + } + fk := *nodes[i].ChargeFlatFeeID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(chargeflatfee.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_flat_fee_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeQuery) loadCreditPurchase(ctx context.Context, query *ChargeCreditPurchaseQuery, nodes []*Charge, init func(*Charge), assign func(*Charge, *ChargeCreditPurchase)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*Charge) + for i := range nodes { + if nodes[i].ChargeCreditPurchaseID == nil { + continue + } + fk := *nodes[i].ChargeCreditPurchaseID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(chargecreditpurchase.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_credit_purchase_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeQuery) loadUsageBased(ctx context.Context, query *ChargeUsageBasedQuery, nodes []*Charge, init func(*Charge), assign func(*Charge, *ChargeUsageBased)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*Charge) + for i := range nodes { + if nodes[i].ChargeUsageBasedID == nil { + continue + } + fk := *nodes[i].ChargeUsageBasedID + 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_usage_based_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], 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) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + query.withFKs = true + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(billinginvoiceline.FieldChargeID) + } + query.Where(predicate.BillingInvoiceLine(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(charge.BillingInvoiceLinesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.ChargeID + if fk == nil { + return fmt.Errorf(`foreign-key "charge_id" is nil for node %v`, n.ID) + } + 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 *ChargeQuery) loadBillingSplitLineGroups(ctx context.Context, query *BillingInvoiceSplitLineGroupQuery, nodes []*Charge, init func(*Charge), assign func(*Charge, *BillingInvoiceSplitLineGroup)) 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] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(billinginvoicesplitlinegroup.FieldChargeID) + } + query.Where(predicate.BillingInvoiceSplitLineGroup(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(charge.BillingSplitLineGroupsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.ChargeID + if fk == nil { + return fmt.Errorf(`foreign-key "charge_id" is nil for node %v`, n.ID) + } + 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 *ChargeQuery) loadCreditRealizationLineages(ctx context.Context, query *CreditRealizationLineageQuery, nodes []*Charge, init func(*Charge), assign func(*Charge, *CreditRealizationLineage)) 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] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(creditrealizationlineage.FieldChargeID) + } + query.Where(predicate.CreditRealizationLineage(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(charge.CreditRealizationLineagesColumn), 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 *ChargeQuery) 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 *ChargeQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(charge.Table, charge.Columns, sqlgraph.NewFieldSpec(charge.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, charge.FieldID) + for i := range fields { + if fields[i] != charge.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withFlatFee != nil { + _spec.Node.AddColumnOnce(charge.FieldChargeFlatFeeID) + } + if _q.withCreditPurchase != nil { + _spec.Node.AddColumnOnce(charge.FieldChargeCreditPurchaseID) + } + if _q.withUsageBased != nil { + _spec.Node.AddColumnOnce(charge.FieldChargeUsageBasedID) + } + } + 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 *ChargeQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(charge.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = charge.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 *ChargeQuery) ForUpdate(opts ...sql.LockOption) *ChargeQuery { + 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 *ChargeQuery) ForShare(opts ...sql.LockOption) *ChargeQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ChargeGroupBy is the group-by builder for Charge entities. +type ChargeGroupBy struct { + selector + build *ChargeQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ChargeGroupBy) Aggregate(fns ...AggregateFunc) *ChargeGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ChargeGroupBy) 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[*ChargeQuery, *ChargeGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ChargeGroupBy) sqlScan(ctx context.Context, root *ChargeQuery, 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) +} + +// ChargeSelect is the builder for selecting fields of Charge entities. +type ChargeSelect struct { + *ChargeQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ChargeSelect) Aggregate(fns ...AggregateFunc) *ChargeSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ChargeSelect) 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[*ChargeQuery, *ChargeSelect](ctx, _s.ChargeQuery, _s, _s.inters, v) +} + +func (_s *ChargeSelect) sqlScan(ctx context.Context, root *ChargeQuery, 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/ent/db/charge_update.go b/ent/db/charge_update.go new file mode 100644 index 0000000000000000000000000000000000000000..b3efd1752d79e7089c48b0c85c4fb081ba8bf52d --- /dev/null +++ b/ent/db/charge_update.go @@ -0,0 +1,723 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicesplitlinegroup" + "github.com/openmeterio/openmeter/openmeter/ent/db/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/creditrealizationlineage" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeUpdate is the builder for updating Charge entities. +type ChargeUpdate struct { + config + hooks []Hook + mutation *ChargeMutation +} + +// Where appends a list predicates to the ChargeUpdate builder. +func (_u *ChargeUpdate) Where(ps ...predicate.Charge) *ChargeUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeUpdate) SetDeletedAt(v time.Time) *ChargeUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeUpdate) SetNillableDeletedAt(v *time.Time) *ChargeUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeUpdate) ClearDeletedAt() *ChargeUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// AddBillingInvoiceLineIDs adds the "billing_invoice_lines" edge to the BillingInvoiceLine entity by IDs. +func (_u *ChargeUpdate) AddBillingInvoiceLineIDs(ids ...string) *ChargeUpdate { + _u.mutation.AddBillingInvoiceLineIDs(ids...) + return _u +} + +// AddBillingInvoiceLines adds the "billing_invoice_lines" edges to the BillingInvoiceLine entity. +func (_u *ChargeUpdate) AddBillingInvoiceLines(v ...*BillingInvoiceLine) *ChargeUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddBillingInvoiceLineIDs(ids...) +} + +// AddBillingSplitLineGroupIDs adds the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity by IDs. +func (_u *ChargeUpdate) AddBillingSplitLineGroupIDs(ids ...string) *ChargeUpdate { + _u.mutation.AddBillingSplitLineGroupIDs(ids...) + return _u +} + +// AddBillingSplitLineGroups adds the "billing_split_line_groups" edges to the BillingInvoiceSplitLineGroup entity. +func (_u *ChargeUpdate) AddBillingSplitLineGroups(v ...*BillingInvoiceSplitLineGroup) *ChargeUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddBillingSplitLineGroupIDs(ids...) +} + +// AddCreditRealizationLineageIDs adds the "credit_realization_lineages" edge to the CreditRealizationLineage entity by IDs. +func (_u *ChargeUpdate) AddCreditRealizationLineageIDs(ids ...string) *ChargeUpdate { + _u.mutation.AddCreditRealizationLineageIDs(ids...) + return _u +} + +// AddCreditRealizationLineages adds the "credit_realization_lineages" edges to the CreditRealizationLineage entity. +func (_u *ChargeUpdate) AddCreditRealizationLineages(v ...*CreditRealizationLineage) *ChargeUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddCreditRealizationLineageIDs(ids...) +} + +// Mutation returns the ChargeMutation object of the builder. +func (_u *ChargeUpdate) Mutation() *ChargeMutation { + return _u.mutation +} + +// ClearBillingInvoiceLines clears all "billing_invoice_lines" edges to the BillingInvoiceLine entity. +func (_u *ChargeUpdate) ClearBillingInvoiceLines() *ChargeUpdate { + _u.mutation.ClearBillingInvoiceLines() + return _u +} + +// RemoveBillingInvoiceLineIDs removes the "billing_invoice_lines" edge to BillingInvoiceLine entities by IDs. +func (_u *ChargeUpdate) RemoveBillingInvoiceLineIDs(ids ...string) *ChargeUpdate { + _u.mutation.RemoveBillingInvoiceLineIDs(ids...) + return _u +} + +// RemoveBillingInvoiceLines removes "billing_invoice_lines" edges to BillingInvoiceLine entities. +func (_u *ChargeUpdate) RemoveBillingInvoiceLines(v ...*BillingInvoiceLine) *ChargeUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveBillingInvoiceLineIDs(ids...) +} + +// ClearBillingSplitLineGroups clears all "billing_split_line_groups" edges to the BillingInvoiceSplitLineGroup entity. +func (_u *ChargeUpdate) ClearBillingSplitLineGroups() *ChargeUpdate { + _u.mutation.ClearBillingSplitLineGroups() + return _u +} + +// RemoveBillingSplitLineGroupIDs removes the "billing_split_line_groups" edge to BillingInvoiceSplitLineGroup entities by IDs. +func (_u *ChargeUpdate) RemoveBillingSplitLineGroupIDs(ids ...string) *ChargeUpdate { + _u.mutation.RemoveBillingSplitLineGroupIDs(ids...) + return _u +} + +// RemoveBillingSplitLineGroups removes "billing_split_line_groups" edges to BillingInvoiceSplitLineGroup entities. +func (_u *ChargeUpdate) RemoveBillingSplitLineGroups(v ...*BillingInvoiceSplitLineGroup) *ChargeUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveBillingSplitLineGroupIDs(ids...) +} + +// ClearCreditRealizationLineages clears all "credit_realization_lineages" edges to the CreditRealizationLineage entity. +func (_u *ChargeUpdate) ClearCreditRealizationLineages() *ChargeUpdate { + _u.mutation.ClearCreditRealizationLineages() + return _u +} + +// RemoveCreditRealizationLineageIDs removes the "credit_realization_lineages" edge to CreditRealizationLineage entities by IDs. +func (_u *ChargeUpdate) RemoveCreditRealizationLineageIDs(ids ...string) *ChargeUpdate { + _u.mutation.RemoveCreditRealizationLineageIDs(ids...) + return _u +} + +// RemoveCreditRealizationLineages removes "credit_realization_lineages" edges to CreditRealizationLineage entities. +func (_u *ChargeUpdate) RemoveCreditRealizationLineages(v ...*CreditRealizationLineage) *ChargeUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveCreditRealizationLineageIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ChargeUpdate) 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 *ChargeUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ChargeUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *ChargeUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(charge.Table, charge.Columns, sqlgraph.NewFieldSpec(charge.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.DeletedAt(); ok { + _spec.SetField(charge.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(charge.FieldDeletedAt, field.TypeTime) + } + if _u.mutation.UniqueReferenceIDCleared() { + _spec.ClearField(charge.FieldUniqueReferenceID, field.TypeString) + } + if _u.mutation.BillingInvoiceLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.BillingInvoiceLinesTable, + Columns: []string{charge.BillingInvoiceLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedBillingInvoiceLinesIDs(); len(nodes) > 0 && !_u.mutation.BillingInvoiceLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.BillingInvoiceLinesTable, + Columns: []string{charge.BillingInvoiceLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.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.BillingInvoiceLinesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.BillingInvoiceLinesTable, + Columns: []string{charge.BillingInvoiceLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.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.BillingSplitLineGroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.BillingSplitLineGroupsTable, + Columns: []string{charge.BillingSplitLineGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoicesplitlinegroup.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedBillingSplitLineGroupsIDs(); len(nodes) > 0 && !_u.mutation.BillingSplitLineGroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.BillingSplitLineGroupsTable, + Columns: []string{charge.BillingSplitLineGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoicesplitlinegroup.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.BillingSplitLineGroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.BillingSplitLineGroupsTable, + Columns: []string{charge.BillingSplitLineGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoicesplitlinegroup.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.CreditRealizationLineagesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.CreditRealizationLineagesTable, + Columns: []string{charge.CreditRealizationLineagesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(creditrealizationlineage.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedCreditRealizationLineagesIDs(); len(nodes) > 0 && !_u.mutation.CreditRealizationLineagesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.CreditRealizationLineagesTable, + Columns: []string{charge.CreditRealizationLineagesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(creditrealizationlineage.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.CreditRealizationLineagesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.CreditRealizationLineagesTable, + Columns: []string{charge.CreditRealizationLineagesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(creditrealizationlineage.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{charge.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ChargeUpdateOne is the builder for updating a single Charge entity. +type ChargeUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ChargeMutation +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeUpdateOne) SetDeletedAt(v time.Time) *ChargeUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeUpdateOne) SetNillableDeletedAt(v *time.Time) *ChargeUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeUpdateOne) ClearDeletedAt() *ChargeUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// AddBillingInvoiceLineIDs adds the "billing_invoice_lines" edge to the BillingInvoiceLine entity by IDs. +func (_u *ChargeUpdateOne) AddBillingInvoiceLineIDs(ids ...string) *ChargeUpdateOne { + _u.mutation.AddBillingInvoiceLineIDs(ids...) + return _u +} + +// AddBillingInvoiceLines adds the "billing_invoice_lines" edges to the BillingInvoiceLine entity. +func (_u *ChargeUpdateOne) AddBillingInvoiceLines(v ...*BillingInvoiceLine) *ChargeUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddBillingInvoiceLineIDs(ids...) +} + +// AddBillingSplitLineGroupIDs adds the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity by IDs. +func (_u *ChargeUpdateOne) AddBillingSplitLineGroupIDs(ids ...string) *ChargeUpdateOne { + _u.mutation.AddBillingSplitLineGroupIDs(ids...) + return _u +} + +// AddBillingSplitLineGroups adds the "billing_split_line_groups" edges to the BillingInvoiceSplitLineGroup entity. +func (_u *ChargeUpdateOne) AddBillingSplitLineGroups(v ...*BillingInvoiceSplitLineGroup) *ChargeUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddBillingSplitLineGroupIDs(ids...) +} + +// AddCreditRealizationLineageIDs adds the "credit_realization_lineages" edge to the CreditRealizationLineage entity by IDs. +func (_u *ChargeUpdateOne) AddCreditRealizationLineageIDs(ids ...string) *ChargeUpdateOne { + _u.mutation.AddCreditRealizationLineageIDs(ids...) + return _u +} + +// AddCreditRealizationLineages adds the "credit_realization_lineages" edges to the CreditRealizationLineage entity. +func (_u *ChargeUpdateOne) AddCreditRealizationLineages(v ...*CreditRealizationLineage) *ChargeUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddCreditRealizationLineageIDs(ids...) +} + +// Mutation returns the ChargeMutation object of the builder. +func (_u *ChargeUpdateOne) Mutation() *ChargeMutation { + return _u.mutation +} + +// ClearBillingInvoiceLines clears all "billing_invoice_lines" edges to the BillingInvoiceLine entity. +func (_u *ChargeUpdateOne) ClearBillingInvoiceLines() *ChargeUpdateOne { + _u.mutation.ClearBillingInvoiceLines() + return _u +} + +// RemoveBillingInvoiceLineIDs removes the "billing_invoice_lines" edge to BillingInvoiceLine entities by IDs. +func (_u *ChargeUpdateOne) RemoveBillingInvoiceLineIDs(ids ...string) *ChargeUpdateOne { + _u.mutation.RemoveBillingInvoiceLineIDs(ids...) + return _u +} + +// RemoveBillingInvoiceLines removes "billing_invoice_lines" edges to BillingInvoiceLine entities. +func (_u *ChargeUpdateOne) RemoveBillingInvoiceLines(v ...*BillingInvoiceLine) *ChargeUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveBillingInvoiceLineIDs(ids...) +} + +// ClearBillingSplitLineGroups clears all "billing_split_line_groups" edges to the BillingInvoiceSplitLineGroup entity. +func (_u *ChargeUpdateOne) ClearBillingSplitLineGroups() *ChargeUpdateOne { + _u.mutation.ClearBillingSplitLineGroups() + return _u +} + +// RemoveBillingSplitLineGroupIDs removes the "billing_split_line_groups" edge to BillingInvoiceSplitLineGroup entities by IDs. +func (_u *ChargeUpdateOne) RemoveBillingSplitLineGroupIDs(ids ...string) *ChargeUpdateOne { + _u.mutation.RemoveBillingSplitLineGroupIDs(ids...) + return _u +} + +// RemoveBillingSplitLineGroups removes "billing_split_line_groups" edges to BillingInvoiceSplitLineGroup entities. +func (_u *ChargeUpdateOne) RemoveBillingSplitLineGroups(v ...*BillingInvoiceSplitLineGroup) *ChargeUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveBillingSplitLineGroupIDs(ids...) +} + +// ClearCreditRealizationLineages clears all "credit_realization_lineages" edges to the CreditRealizationLineage entity. +func (_u *ChargeUpdateOne) ClearCreditRealizationLineages() *ChargeUpdateOne { + _u.mutation.ClearCreditRealizationLineages() + return _u +} + +// RemoveCreditRealizationLineageIDs removes the "credit_realization_lineages" edge to CreditRealizationLineage entities by IDs. +func (_u *ChargeUpdateOne) RemoveCreditRealizationLineageIDs(ids ...string) *ChargeUpdateOne { + _u.mutation.RemoveCreditRealizationLineageIDs(ids...) + return _u +} + +// RemoveCreditRealizationLineages removes "credit_realization_lineages" edges to CreditRealizationLineage entities. +func (_u *ChargeUpdateOne) RemoveCreditRealizationLineages(v ...*CreditRealizationLineage) *ChargeUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveCreditRealizationLineageIDs(ids...) +} + +// Where appends a list predicates to the ChargeUpdate builder. +func (_u *ChargeUpdateOne) Where(ps ...predicate.Charge) *ChargeUpdateOne { + _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 *ChargeUpdateOne) Select(field string, fields ...string) *ChargeUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Charge entity. +func (_u *ChargeUpdateOne) Save(ctx context.Context) (*Charge, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeUpdateOne) SaveX(ctx context.Context) *Charge { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ChargeUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *ChargeUpdateOne) sqlSave(ctx context.Context) (_node *Charge, err error) { + _spec := sqlgraph.NewUpdateSpec(charge.Table, charge.Columns, sqlgraph.NewFieldSpec(charge.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "Charge.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, charge.FieldID) + for _, f := range fields { + if !charge.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != charge.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.DeletedAt(); ok { + _spec.SetField(charge.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(charge.FieldDeletedAt, field.TypeTime) + } + if _u.mutation.UniqueReferenceIDCleared() { + _spec.ClearField(charge.FieldUniqueReferenceID, field.TypeString) + } + if _u.mutation.BillingInvoiceLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.BillingInvoiceLinesTable, + Columns: []string{charge.BillingInvoiceLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedBillingInvoiceLinesIDs(); len(nodes) > 0 && !_u.mutation.BillingInvoiceLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.BillingInvoiceLinesTable, + Columns: []string{charge.BillingInvoiceLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.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.BillingInvoiceLinesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.BillingInvoiceLinesTable, + Columns: []string{charge.BillingInvoiceLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.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.BillingSplitLineGroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.BillingSplitLineGroupsTable, + Columns: []string{charge.BillingSplitLineGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoicesplitlinegroup.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedBillingSplitLineGroupsIDs(); len(nodes) > 0 && !_u.mutation.BillingSplitLineGroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.BillingSplitLineGroupsTable, + Columns: []string{charge.BillingSplitLineGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoicesplitlinegroup.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.BillingSplitLineGroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.BillingSplitLineGroupsTable, + Columns: []string{charge.BillingSplitLineGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoicesplitlinegroup.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.CreditRealizationLineagesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.CreditRealizationLineagesTable, + Columns: []string{charge.CreditRealizationLineagesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(creditrealizationlineage.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedCreditRealizationLineagesIDs(); len(nodes) > 0 && !_u.mutation.CreditRealizationLineagesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.CreditRealizationLineagesTable, + Columns: []string{charge.CreditRealizationLineagesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(creditrealizationlineage.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.CreditRealizationLineagesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: charge.CreditRealizationLineagesTable, + Columns: []string{charge.CreditRealizationLineagesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(creditrealizationlineage.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &Charge{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{charge.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/ent/db/chargecreditpurchase.go b/ent/db/chargecreditpurchase.go new file mode 100644 index 0000000000000000000000000000000000000000..57fcff54e1a6bb8dd5acb400b22178721df1ad8e --- /dev/null +++ b/ent/db/chargecreditpurchase.go @@ -0,0 +1,710 @@ +// 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/lib/pq" + "github.com/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/billing/charges/creditpurchase" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/ent/db/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchase" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchasecreditgrant" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchaseexternalpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchaseinvoicedpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/customer" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionphase" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeCreditPurchase is the model entity for the ChargeCreditPurchase schema. +type ChargeCreditPurchase struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // CustomerID holds the value of the "customer_id" field. + CustomerID string `json:"customer_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"` + // BillingPeriodFrom holds the value of the "billing_period_from" field. + BillingPeriodFrom time.Time `json:"billing_period_from,omitempty"` + // BillingPeriodTo holds the value of the "billing_period_to" field. + BillingPeriodTo time.Time `json:"billing_period_to,omitempty"` + // FullServicePeriodFrom holds the value of the "full_service_period_from" field. + FullServicePeriodFrom time.Time `json:"full_service_period_from,omitempty"` + // FullServicePeriodTo holds the value of the "full_service_period_to" field. + FullServicePeriodTo time.Time `json:"full_service_period_to,omitempty"` + // Status holds the value of the "status" field. + Status meta.ChargeStatus `json:"status,omitempty"` + // UniqueReferenceID holds the value of the "unique_reference_id" field. + UniqueReferenceID *string `json:"unique_reference_id,omitempty"` + // Currency holds the value of the "currency" field. + Currency currencyx.Code `json:"currency,omitempty"` + // ManagedBy holds the value of the "managed_by" field. + ManagedBy billing.InvoiceLineManagedBy `json:"managed_by,omitempty"` + // SubscriptionID holds the value of the "subscription_id" field. + SubscriptionID *string `json:"subscription_id,omitempty"` + // SubscriptionPhaseID holds the value of the "subscription_phase_id" field. + SubscriptionPhaseID *string `json:"subscription_phase_id,omitempty"` + // SubscriptionItemID holds the value of the "subscription_item_id" field. + SubscriptionItemID *string `json:"subscription_item_id,omitempty"` + // AdvanceAfter holds the value of the "advance_after" field. + AdvanceAfter *time.Time `json:"advance_after,omitempty"` + // TaxCodeID holds the value of the "tax_code_id" field. + TaxCodeID string `json:"tax_code_id,omitempty"` + // TaxBehavior holds the value of the "tax_behavior" field. + TaxBehavior *productcatalog.TaxBehavior `json:"tax_behavior,omitempty"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,omitempty"` + // Namespace holds the value of the "namespace" field. + Namespace string `json:"namespace,omitempty"` + // Metadata holds the value of the "metadata" field. + Metadata map[string]string `json:"metadata,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"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Description holds the value of the "description" field. + Description *string `json:"description,omitempty"` + // CreditAmount holds the value of the "credit_amount" field. + CreditAmount alpacadecimal.Decimal `json:"credit_amount,omitempty"` + // EffectiveAt holds the value of the "effective_at" field. + EffectiveAt *time.Time `json:"effective_at,omitempty"` + // ExpiresAt holds the value of the "expires_at" field. + ExpiresAt *time.Time `json:"expires_at,omitempty"` + // Priority holds the value of the "priority" field. + Priority *int `json:"priority,omitempty"` + // FeatureFilters holds the value of the "feature_filters" field. + FeatureFilters pq.StringArray `json:"feature_filters,omitempty"` + // Settlement holds the value of the "settlement" field. + Settlement creditpurchase.Settlement `json:"settlement,omitempty"` + // StatusDetailed holds the value of the "status_detailed" field. + StatusDetailed creditpurchase.Status `json:"status_detailed,omitempty"` + // Key holds the value of the "key" field. + Key *string `json:"key,omitempty"` + // VoidedAt holds the value of the "voided_at" field. + VoidedAt *time.Time `json:"voided_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ChargeCreditPurchaseQuery when eager-loading is set. + Edges ChargeCreditPurchaseEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ChargeCreditPurchaseEdges holds the relations/edges for other nodes in the graph. +type ChargeCreditPurchaseEdges struct { + // ExternalPayment holds the value of the external_payment edge. + ExternalPayment *ChargeCreditPurchaseExternalPayment `json:"external_payment,omitempty"` + // InvoicedPayment holds the value of the invoiced_payment edge. + InvoicedPayment *ChargeCreditPurchaseInvoicedPayment `json:"invoiced_payment,omitempty"` + // CreditGrant holds the value of the credit_grant edge. + CreditGrant *ChargeCreditPurchaseCreditGrant `json:"credit_grant,omitempty"` + // Charge holds the value of the charge edge. + Charge *Charge `json:"charge,omitempty"` + // Subscription holds the value of the subscription edge. + Subscription *Subscription `json:"subscription,omitempty"` + // SubscriptionPhase holds the value of the subscription_phase edge. + SubscriptionPhase *SubscriptionPhase `json:"subscription_phase,omitempty"` + // SubscriptionItem holds the value of the subscription_item edge. + SubscriptionItem *SubscriptionItem `json:"subscription_item,omitempty"` + // Customer holds the value of the customer edge. + Customer *Customer `json:"customer,omitempty"` + // TaxCode holds the value of the tax_code edge. + TaxCode *TaxCode `json:"tax_code,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [9]bool +} + +// ExternalPaymentOrErr returns the ExternalPayment value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeCreditPurchaseEdges) ExternalPaymentOrErr() (*ChargeCreditPurchaseExternalPayment, error) { + if e.ExternalPayment != nil { + return e.ExternalPayment, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: chargecreditpurchaseexternalpayment.Label} + } + return nil, &NotLoadedError{edge: "external_payment"} +} + +// InvoicedPaymentOrErr returns the InvoicedPayment value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeCreditPurchaseEdges) InvoicedPaymentOrErr() (*ChargeCreditPurchaseInvoicedPayment, error) { + if e.InvoicedPayment != nil { + return e.InvoicedPayment, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: chargecreditpurchaseinvoicedpayment.Label} + } + return nil, &NotLoadedError{edge: "invoiced_payment"} +} + +// CreditGrantOrErr returns the CreditGrant value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeCreditPurchaseEdges) CreditGrantOrErr() (*ChargeCreditPurchaseCreditGrant, error) { + if e.CreditGrant != nil { + return e.CreditGrant, nil + } else if e.loadedTypes[2] { + return nil, &NotFoundError{label: chargecreditpurchasecreditgrant.Label} + } + return nil, &NotLoadedError{edge: "credit_grant"} +} + +// 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 ChargeCreditPurchaseEdges) ChargeOrErr() (*Charge, error) { + if e.Charge != nil { + return e.Charge, nil + } else if e.loadedTypes[3] { + return nil, &NotFoundError{label: charge.Label} + } + return nil, &NotLoadedError{edge: "charge"} +} + +// SubscriptionOrErr returns the Subscription value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeCreditPurchaseEdges) SubscriptionOrErr() (*Subscription, error) { + if e.Subscription != nil { + return e.Subscription, nil + } else if e.loadedTypes[4] { + return nil, &NotFoundError{label: subscription.Label} + } + return nil, &NotLoadedError{edge: "subscription"} +} + +// SubscriptionPhaseOrErr returns the SubscriptionPhase value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeCreditPurchaseEdges) SubscriptionPhaseOrErr() (*SubscriptionPhase, error) { + if e.SubscriptionPhase != nil { + return e.SubscriptionPhase, nil + } else if e.loadedTypes[5] { + return nil, &NotFoundError{label: subscriptionphase.Label} + } + return nil, &NotLoadedError{edge: "subscription_phase"} +} + +// SubscriptionItemOrErr returns the SubscriptionItem value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeCreditPurchaseEdges) SubscriptionItemOrErr() (*SubscriptionItem, error) { + if e.SubscriptionItem != nil { + return e.SubscriptionItem, nil + } else if e.loadedTypes[6] { + return nil, &NotFoundError{label: subscriptionitem.Label} + } + return nil, &NotLoadedError{edge: "subscription_item"} +} + +// CustomerOrErr returns the Customer value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeCreditPurchaseEdges) CustomerOrErr() (*Customer, error) { + if e.Customer != nil { + return e.Customer, nil + } else if e.loadedTypes[7] { + return nil, &NotFoundError{label: customer.Label} + } + return nil, &NotLoadedError{edge: "customer"} +} + +// TaxCodeOrErr returns the TaxCode value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeCreditPurchaseEdges) TaxCodeOrErr() (*TaxCode, error) { + if e.TaxCode != nil { + return e.TaxCode, nil + } else if e.loadedTypes[8] { + return nil, &NotFoundError{label: dbtaxcode.Label} + } + return nil, &NotLoadedError{edge: "tax_code"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ChargeCreditPurchase) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case chargecreditpurchase.FieldAnnotations, chargecreditpurchase.FieldMetadata: + values[i] = new([]byte) + case chargecreditpurchase.FieldCreditAmount: + values[i] = new(alpacadecimal.Decimal) + case chargecreditpurchase.FieldFeatureFilters: + values[i] = new(pq.StringArray) + case chargecreditpurchase.FieldPriority: + values[i] = new(sql.NullInt64) + case chargecreditpurchase.FieldID, chargecreditpurchase.FieldCustomerID, chargecreditpurchase.FieldStatus, chargecreditpurchase.FieldUniqueReferenceID, chargecreditpurchase.FieldCurrency, chargecreditpurchase.FieldManagedBy, chargecreditpurchase.FieldSubscriptionID, chargecreditpurchase.FieldSubscriptionPhaseID, chargecreditpurchase.FieldSubscriptionItemID, chargecreditpurchase.FieldTaxCodeID, chargecreditpurchase.FieldTaxBehavior, chargecreditpurchase.FieldNamespace, chargecreditpurchase.FieldName, chargecreditpurchase.FieldDescription, chargecreditpurchase.FieldStatusDetailed, chargecreditpurchase.FieldKey: + values[i] = new(sql.NullString) + case chargecreditpurchase.FieldServicePeriodFrom, chargecreditpurchase.FieldServicePeriodTo, chargecreditpurchase.FieldBillingPeriodFrom, chargecreditpurchase.FieldBillingPeriodTo, chargecreditpurchase.FieldFullServicePeriodFrom, chargecreditpurchase.FieldFullServicePeriodTo, chargecreditpurchase.FieldAdvanceAfter, chargecreditpurchase.FieldCreatedAt, chargecreditpurchase.FieldUpdatedAt, chargecreditpurchase.FieldDeletedAt, chargecreditpurchase.FieldEffectiveAt, chargecreditpurchase.FieldExpiresAt, chargecreditpurchase.FieldVoidedAt: + values[i] = new(sql.NullTime) + case chargecreditpurchase.FieldSettlement: + values[i] = chargecreditpurchase.ValueScanner.Settlement.ScanValue() + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the ChargeCreditPurchase fields. +func (_m *ChargeCreditPurchase) 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 chargecreditpurchase.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 chargecreditpurchase.FieldCustomerID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field customer_id", values[i]) + } else if value.Valid { + _m.CustomerID = value.String + } + case chargecreditpurchase.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 chargecreditpurchase.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 chargecreditpurchase.FieldBillingPeriodFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field billing_period_from", values[i]) + } else if value.Valid { + _m.BillingPeriodFrom = value.Time + } + case chargecreditpurchase.FieldBillingPeriodTo: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field billing_period_to", values[i]) + } else if value.Valid { + _m.BillingPeriodTo = value.Time + } + case chargecreditpurchase.FieldFullServicePeriodFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field full_service_period_from", values[i]) + } else if value.Valid { + _m.FullServicePeriodFrom = value.Time + } + case chargecreditpurchase.FieldFullServicePeriodTo: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field full_service_period_to", values[i]) + } else if value.Valid { + _m.FullServicePeriodTo = value.Time + } + case chargecreditpurchase.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 = meta.ChargeStatus(value.String) + } + case chargecreditpurchase.FieldUniqueReferenceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field unique_reference_id", values[i]) + } else if value.Valid { + _m.UniqueReferenceID = new(string) + *_m.UniqueReferenceID = value.String + } + case chargecreditpurchase.FieldCurrency: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field currency", values[i]) + } else if value.Valid { + _m.Currency = currencyx.Code(value.String) + } + case chargecreditpurchase.FieldManagedBy: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field managed_by", values[i]) + } else if value.Valid { + _m.ManagedBy = billing.InvoiceLineManagedBy(value.String) + } + case chargecreditpurchase.FieldSubscriptionID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field subscription_id", values[i]) + } else if value.Valid { + _m.SubscriptionID = new(string) + *_m.SubscriptionID = value.String + } + case chargecreditpurchase.FieldSubscriptionPhaseID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field subscription_phase_id", values[i]) + } else if value.Valid { + _m.SubscriptionPhaseID = new(string) + *_m.SubscriptionPhaseID = value.String + } + case chargecreditpurchase.FieldSubscriptionItemID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field subscription_item_id", values[i]) + } else if value.Valid { + _m.SubscriptionItemID = new(string) + *_m.SubscriptionItemID = value.String + } + case chargecreditpurchase.FieldAdvanceAfter: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field advance_after", values[i]) + } else if value.Valid { + _m.AdvanceAfter = new(time.Time) + *_m.AdvanceAfter = value.Time + } + case chargecreditpurchase.FieldTaxCodeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field tax_code_id", values[i]) + } else if value.Valid { + _m.TaxCodeID = value.String + } + case chargecreditpurchase.FieldTaxBehavior: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field tax_behavior", values[i]) + } else if value.Valid { + _m.TaxBehavior = new(productcatalog.TaxBehavior) + *_m.TaxBehavior = productcatalog.TaxBehavior(value.String) + } + case chargecreditpurchase.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 chargecreditpurchase.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 chargecreditpurchase.FieldMetadata: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field metadata", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Metadata); err != nil { + return fmt.Errorf("unmarshal field metadata: %w", err) + } + } + case chargecreditpurchase.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 chargecreditpurchase.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 chargecreditpurchase.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 chargecreditpurchase.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case chargecreditpurchase.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + _m.Description = new(string) + *_m.Description = value.String + } + case chargecreditpurchase.FieldCreditAmount: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field credit_amount", values[i]) + } else if value != nil { + _m.CreditAmount = *value + } + case chargecreditpurchase.FieldEffectiveAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field effective_at", values[i]) + } else if value.Valid { + _m.EffectiveAt = new(time.Time) + *_m.EffectiveAt = value.Time + } + case chargecreditpurchase.FieldExpiresAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field expires_at", values[i]) + } else if value.Valid { + _m.ExpiresAt = new(time.Time) + *_m.ExpiresAt = value.Time + } + case chargecreditpurchase.FieldPriority: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field priority", values[i]) + } else if value.Valid { + _m.Priority = new(int) + *_m.Priority = int(value.Int64) + } + case chargecreditpurchase.FieldFeatureFilters: + if value, ok := values[i].(*pq.StringArray); !ok { + return fmt.Errorf("unexpected type %T for field feature_filters", values[i]) + } else if value != nil { + _m.FeatureFilters = *value + } + case chargecreditpurchase.FieldSettlement: + if value, err := chargecreditpurchase.ValueScanner.Settlement.FromValue(values[i]); err != nil { + return err + } else { + _m.Settlement = value + } + case chargecreditpurchase.FieldStatusDetailed: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field status_detailed", values[i]) + } else if value.Valid { + _m.StatusDetailed = creditpurchase.Status(value.String) + } + case chargecreditpurchase.FieldKey: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field key", values[i]) + } else if value.Valid { + _m.Key = new(string) + *_m.Key = value.String + } + case chargecreditpurchase.FieldVoidedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field voided_at", values[i]) + } else if value.Valid { + _m.VoidedAt = new(time.Time) + *_m.VoidedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the ChargeCreditPurchase. +// This includes values selected through modifiers, order, etc. +func (_m *ChargeCreditPurchase) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryExternalPayment queries the "external_payment" edge of the ChargeCreditPurchase entity. +func (_m *ChargeCreditPurchase) QueryExternalPayment() *ChargeCreditPurchaseExternalPaymentQuery { + return NewChargeCreditPurchaseClient(_m.config).QueryExternalPayment(_m) +} + +// QueryInvoicedPayment queries the "invoiced_payment" edge of the ChargeCreditPurchase entity. +func (_m *ChargeCreditPurchase) QueryInvoicedPayment() *ChargeCreditPurchaseInvoicedPaymentQuery { + return NewChargeCreditPurchaseClient(_m.config).QueryInvoicedPayment(_m) +} + +// QueryCreditGrant queries the "credit_grant" edge of the ChargeCreditPurchase entity. +func (_m *ChargeCreditPurchase) QueryCreditGrant() *ChargeCreditPurchaseCreditGrantQuery { + return NewChargeCreditPurchaseClient(_m.config).QueryCreditGrant(_m) +} + +// QueryCharge queries the "charge" edge of the ChargeCreditPurchase entity. +func (_m *ChargeCreditPurchase) QueryCharge() *ChargeQuery { + return NewChargeCreditPurchaseClient(_m.config).QueryCharge(_m) +} + +// QuerySubscription queries the "subscription" edge of the ChargeCreditPurchase entity. +func (_m *ChargeCreditPurchase) QuerySubscription() *SubscriptionQuery { + return NewChargeCreditPurchaseClient(_m.config).QuerySubscription(_m) +} + +// QuerySubscriptionPhase queries the "subscription_phase" edge of the ChargeCreditPurchase entity. +func (_m *ChargeCreditPurchase) QuerySubscriptionPhase() *SubscriptionPhaseQuery { + return NewChargeCreditPurchaseClient(_m.config).QuerySubscriptionPhase(_m) +} + +// QuerySubscriptionItem queries the "subscription_item" edge of the ChargeCreditPurchase entity. +func (_m *ChargeCreditPurchase) QuerySubscriptionItem() *SubscriptionItemQuery { + return NewChargeCreditPurchaseClient(_m.config).QuerySubscriptionItem(_m) +} + +// QueryCustomer queries the "customer" edge of the ChargeCreditPurchase entity. +func (_m *ChargeCreditPurchase) QueryCustomer() *CustomerQuery { + return NewChargeCreditPurchaseClient(_m.config).QueryCustomer(_m) +} + +// QueryTaxCode queries the "tax_code" edge of the ChargeCreditPurchase entity. +func (_m *ChargeCreditPurchase) QueryTaxCode() *TaxCodeQuery { + return NewChargeCreditPurchaseClient(_m.config).QueryTaxCode(_m) +} + +// Update returns a builder for updating this ChargeCreditPurchase. +// Note that you need to call ChargeCreditPurchase.Unwrap() before calling this method if this ChargeCreditPurchase +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ChargeCreditPurchase) Update() *ChargeCreditPurchaseUpdateOne { + return NewChargeCreditPurchaseClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ChargeCreditPurchase 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 *ChargeCreditPurchase) Unwrap() *ChargeCreditPurchase { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: ChargeCreditPurchase is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ChargeCreditPurchase) String() string { + var builder strings.Builder + builder.WriteString("ChargeCreditPurchase(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("customer_id=") + builder.WriteString(_m.CustomerID) + 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("billing_period_from=") + builder.WriteString(_m.BillingPeriodFrom.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("billing_period_to=") + builder.WriteString(_m.BillingPeriodTo.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("full_service_period_from=") + builder.WriteString(_m.FullServicePeriodFrom.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("full_service_period_to=") + builder.WriteString(_m.FullServicePeriodTo.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("status=") + builder.WriteString(fmt.Sprintf("%v", _m.Status)) + builder.WriteString(", ") + if v := _m.UniqueReferenceID; v != nil { + builder.WriteString("unique_reference_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("currency=") + builder.WriteString(fmt.Sprintf("%v", _m.Currency)) + builder.WriteString(", ") + builder.WriteString("managed_by=") + builder.WriteString(fmt.Sprintf("%v", _m.ManagedBy)) + builder.WriteString(", ") + if v := _m.SubscriptionID; v != nil { + builder.WriteString("subscription_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SubscriptionPhaseID; v != nil { + builder.WriteString("subscription_phase_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SubscriptionItemID; v != nil { + builder.WriteString("subscription_item_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.AdvanceAfter; v != nil { + builder.WriteString("advance_after=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + builder.WriteString("tax_code_id=") + builder.WriteString(_m.TaxCodeID) + builder.WriteString(", ") + if v := _m.TaxBehavior; v != nil { + builder.WriteString("tax_behavior=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + builder.WriteString(", ") + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("metadata=") + builder.WriteString(fmt.Sprintf("%v", _m.Metadata)) + 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("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + if v := _m.Description; v != nil { + builder.WriteString("description=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("credit_amount=") + builder.WriteString(fmt.Sprintf("%v", _m.CreditAmount)) + builder.WriteString(", ") + if v := _m.EffectiveAt; v != nil { + builder.WriteString("effective_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + if v := _m.ExpiresAt; v != nil { + builder.WriteString("expires_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + if v := _m.Priority; v != nil { + builder.WriteString("priority=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + builder.WriteString("feature_filters=") + builder.WriteString(fmt.Sprintf("%v", _m.FeatureFilters)) + builder.WriteString(", ") + builder.WriteString("settlement=") + builder.WriteString(fmt.Sprintf("%v", _m.Settlement)) + builder.WriteString(", ") + builder.WriteString("status_detailed=") + builder.WriteString(fmt.Sprintf("%v", _m.StatusDetailed)) + builder.WriteString(", ") + if v := _m.Key; v != nil { + builder.WriteString("key=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.VoidedAt; v != nil { + builder.WriteString("voided_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteByte(')') + return builder.String() +} + +// ChargeCreditPurchases is a parsable slice of ChargeCreditPurchase. +type ChargeCreditPurchases []*ChargeCreditPurchase diff --git a/ent/db/chargecreditpurchase/chargecreditpurchase.go b/ent/db/chargecreditpurchase/chargecreditpurchase.go new file mode 100644 index 0000000000000000000000000000000000000000..d3a93e20a81e2fb6040ed9a6268eee78567c8669 --- /dev/null +++ b/ent/db/chargecreditpurchase/chargecreditpurchase.go @@ -0,0 +1,580 @@ +// Code generated by ent, DO NOT EDIT. + +package chargecreditpurchase + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/billing/charges/creditpurchase" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/productcatalog" +) + +const ( + // Label holds the string label denoting the chargecreditpurchase type in the database. + Label = "charge_credit_purchase" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldCustomerID holds the string denoting the customer_id field in the database. + FieldCustomerID = "customer_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" + // FieldBillingPeriodFrom holds the string denoting the billing_period_from field in the database. + FieldBillingPeriodFrom = "billing_period_from" + // FieldBillingPeriodTo holds the string denoting the billing_period_to field in the database. + FieldBillingPeriodTo = "billing_period_to" + // FieldFullServicePeriodFrom holds the string denoting the full_service_period_from field in the database. + FieldFullServicePeriodFrom = "full_service_period_from" + // FieldFullServicePeriodTo holds the string denoting the full_service_period_to field in the database. + FieldFullServicePeriodTo = "full_service_period_to" + // FieldStatus holds the string denoting the status field in the database. + FieldStatus = "status" + // FieldUniqueReferenceID holds the string denoting the unique_reference_id field in the database. + FieldUniqueReferenceID = "unique_reference_id" + // FieldCurrency holds the string denoting the currency field in the database. + FieldCurrency = "currency" + // FieldManagedBy holds the string denoting the managed_by field in the database. + FieldManagedBy = "managed_by" + // FieldSubscriptionID holds the string denoting the subscription_id field in the database. + FieldSubscriptionID = "subscription_id" + // FieldSubscriptionPhaseID holds the string denoting the subscription_phase_id field in the database. + FieldSubscriptionPhaseID = "subscription_phase_id" + // FieldSubscriptionItemID holds the string denoting the subscription_item_id field in the database. + FieldSubscriptionItemID = "subscription_item_id" + // FieldAdvanceAfter holds the string denoting the advance_after field in the database. + FieldAdvanceAfter = "advance_after" + // FieldTaxCodeID holds the string denoting the tax_code_id field in the database. + FieldTaxCodeID = "tax_code_id" + // FieldTaxBehavior holds the string denoting the tax_behavior field in the database. + FieldTaxBehavior = "tax_behavior" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // FieldNamespace holds the string denoting the namespace field in the database. + FieldNamespace = "namespace" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // 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" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // FieldCreditAmount holds the string denoting the credit_amount field in the database. + FieldCreditAmount = "credit_amount" + // FieldEffectiveAt holds the string denoting the effective_at field in the database. + FieldEffectiveAt = "effective_at" + // FieldExpiresAt holds the string denoting the expires_at field in the database. + FieldExpiresAt = "expires_at" + // FieldPriority holds the string denoting the priority field in the database. + FieldPriority = "priority" + // FieldFeatureFilters holds the string denoting the feature_filters field in the database. + FieldFeatureFilters = "feature_filters" + // FieldSettlement holds the string denoting the settlement field in the database. + FieldSettlement = "settlement" + // FieldStatusDetailed holds the string denoting the status_detailed field in the database. + FieldStatusDetailed = "status_detailed" + // FieldKey holds the string denoting the key field in the database. + FieldKey = "key" + // FieldVoidedAt holds the string denoting the voided_at field in the database. + FieldVoidedAt = "voided_at" + // EdgeExternalPayment holds the string denoting the external_payment edge name in mutations. + EdgeExternalPayment = "external_payment" + // EdgeInvoicedPayment holds the string denoting the invoiced_payment edge name in mutations. + EdgeInvoicedPayment = "invoiced_payment" + // EdgeCreditGrant holds the string denoting the credit_grant edge name in mutations. + EdgeCreditGrant = "credit_grant" + // EdgeCharge holds the string denoting the charge edge name in mutations. + EdgeCharge = "charge" + // EdgeSubscription holds the string denoting the subscription edge name in mutations. + EdgeSubscription = "subscription" + // EdgeSubscriptionPhase holds the string denoting the subscription_phase edge name in mutations. + EdgeSubscriptionPhase = "subscription_phase" + // EdgeSubscriptionItem holds the string denoting the subscription_item edge name in mutations. + EdgeSubscriptionItem = "subscription_item" + // EdgeCustomer holds the string denoting the customer edge name in mutations. + EdgeCustomer = "customer" + // EdgeTaxCode holds the string denoting the tax_code edge name in mutations. + EdgeTaxCode = "tax_code" + // Table holds the table name of the chargecreditpurchase in the database. + Table = "charge_credit_purchases" + // ExternalPaymentTable is the table that holds the external_payment relation/edge. + ExternalPaymentTable = "charge_credit_purchase_external_payments" + // ExternalPaymentInverseTable is the table name for the ChargeCreditPurchaseExternalPayment entity. + // It exists in this package in order to avoid circular dependency with the "chargecreditpurchaseexternalpayment" package. + ExternalPaymentInverseTable = "charge_credit_purchase_external_payments" + // ExternalPaymentColumn is the table column denoting the external_payment relation/edge. + ExternalPaymentColumn = "charge_id" + // InvoicedPaymentTable is the table that holds the invoiced_payment relation/edge. + InvoicedPaymentTable = "charge_credit_purchase_invoiced_payments" + // InvoicedPaymentInverseTable is the table name for the ChargeCreditPurchaseInvoicedPayment entity. + // It exists in this package in order to avoid circular dependency with the "chargecreditpurchaseinvoicedpayment" package. + InvoicedPaymentInverseTable = "charge_credit_purchase_invoiced_payments" + // InvoicedPaymentColumn is the table column denoting the invoiced_payment relation/edge. + InvoicedPaymentColumn = "charge_id" + // CreditGrantTable is the table that holds the credit_grant relation/edge. + CreditGrantTable = "charge_credit_purchase_credit_grants" + // CreditGrantInverseTable is the table name for the ChargeCreditPurchaseCreditGrant entity. + // It exists in this package in order to avoid circular dependency with the "chargecreditpurchasecreditgrant" package. + CreditGrantInverseTable = "charge_credit_purchase_credit_grants" + // CreditGrantColumn is the table column denoting the credit_grant relation/edge. + CreditGrantColumn = "charge_id" + // ChargeTable is the table that holds the charge relation/edge. + ChargeTable = "charges" + // 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 = "charge_credit_purchase_id" + // SubscriptionTable is the table that holds the subscription relation/edge. + SubscriptionTable = "charge_credit_purchases" + // SubscriptionInverseTable is the table name for the Subscription entity. + // It exists in this package in order to avoid circular dependency with the "subscription" package. + SubscriptionInverseTable = "subscriptions" + // SubscriptionColumn is the table column denoting the subscription relation/edge. + SubscriptionColumn = "subscription_id" + // SubscriptionPhaseTable is the table that holds the subscription_phase relation/edge. + SubscriptionPhaseTable = "charge_credit_purchases" + // SubscriptionPhaseInverseTable is the table name for the SubscriptionPhase entity. + // It exists in this package in order to avoid circular dependency with the "subscriptionphase" package. + SubscriptionPhaseInverseTable = "subscription_phases" + // SubscriptionPhaseColumn is the table column denoting the subscription_phase relation/edge. + SubscriptionPhaseColumn = "subscription_phase_id" + // SubscriptionItemTable is the table that holds the subscription_item relation/edge. + SubscriptionItemTable = "charge_credit_purchases" + // SubscriptionItemInverseTable is the table name for the SubscriptionItem entity. + // It exists in this package in order to avoid circular dependency with the "subscriptionitem" package. + SubscriptionItemInverseTable = "subscription_items" + // SubscriptionItemColumn is the table column denoting the subscription_item relation/edge. + SubscriptionItemColumn = "subscription_item_id" + // CustomerTable is the table that holds the customer relation/edge. + CustomerTable = "charge_credit_purchases" + // CustomerInverseTable is the table name for the Customer entity. + // It exists in this package in order to avoid circular dependency with the "customer" package. + CustomerInverseTable = "customers" + // CustomerColumn is the table column denoting the customer relation/edge. + CustomerColumn = "customer_id" + // TaxCodeTable is the table that holds the tax_code relation/edge. + TaxCodeTable = "charge_credit_purchases" + // TaxCodeInverseTable is the table name for the TaxCode entity. + // It exists in this package in order to avoid circular dependency with the "dbtaxcode" package. + TaxCodeInverseTable = "tax_codes" + // TaxCodeColumn is the table column denoting the tax_code relation/edge. + TaxCodeColumn = "tax_code_id" +) + +// Columns holds all SQL columns for chargecreditpurchase fields. +var Columns = []string{ + FieldID, + FieldCustomerID, + FieldServicePeriodFrom, + FieldServicePeriodTo, + FieldBillingPeriodFrom, + FieldBillingPeriodTo, + FieldFullServicePeriodFrom, + FieldFullServicePeriodTo, + FieldStatus, + FieldUniqueReferenceID, + FieldCurrency, + FieldManagedBy, + FieldSubscriptionID, + FieldSubscriptionPhaseID, + FieldSubscriptionItemID, + FieldAdvanceAfter, + FieldTaxCodeID, + FieldTaxBehavior, + FieldAnnotations, + FieldNamespace, + FieldMetadata, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldName, + FieldDescription, + FieldCreditAmount, + FieldEffectiveAt, + FieldExpiresAt, + FieldPriority, + FieldFeatureFilters, + FieldSettlement, + FieldStatusDetailed, + FieldKey, + FieldVoidedAt, +} + +// 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 ( + // CustomerIDValidator is a validator for the "customer_id" field. It is called by the builders before save. + CustomerIDValidator func(string) error + // CurrencyValidator is a validator for the "currency" field. It is called by the builders before save. + CurrencyValidator func(string) error + // TaxCodeIDValidator is a validator for the "tax_code_id" field. It is called by the builders before save. + TaxCodeIDValidator 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 + // ValueScanner of all ChargeCreditPurchase fields. + ValueScanner struct { + Settlement field.TypeValueScanner[creditpurchase.Settlement] + } +) + +// StatusValidator is a validator for the "status" field enum values. It is called by the builders before save. +func StatusValidator(s meta.ChargeStatus) error { + switch s { + case "created", "active", "final", "deleted": + return nil + default: + return fmt.Errorf("chargecreditpurchase: invalid enum value for status field: %q", s) + } +} + +// ManagedByValidator is a validator for the "managed_by" field enum values. It is called by the builders before save. +func ManagedByValidator(mb billing.InvoiceLineManagedBy) error { + switch mb { + case "subscription", "system", "manual": + return nil + default: + return fmt.Errorf("chargecreditpurchase: invalid enum value for managed_by field: %q", mb) + } +} + +// TaxBehaviorValidator is a validator for the "tax_behavior" field enum values. It is called by the builders before save. +func TaxBehaviorValidator(tb productcatalog.TaxBehavior) error { + switch tb { + case "inclusive", "exclusive": + return nil + default: + return fmt.Errorf("chargecreditpurchase: invalid enum value for tax_behavior field: %q", tb) + } +} + +// StatusDetailedValidator is a validator for the "status_detailed" field enum values. It is called by the builders before save. +func StatusDetailedValidator(sd creditpurchase.Status) error { + switch sd { + case "created", "active", "active.initial_credit_grant", "active.payment.pending", "active.payment.authorized", "active.payment.paid_and_authorized", "active.payment.settled", "final", "deleted": + return nil + default: + return fmt.Errorf("chargecreditpurchase: invalid enum value for status_detailed field: %q", sd) + } +} + +// OrderOption defines the ordering options for the ChargeCreditPurchase 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() +} + +// ByCustomerID orders the results by the customer_id field. +func ByCustomerID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCustomerID, 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() +} + +// ByBillingPeriodFrom orders the results by the billing_period_from field. +func ByBillingPeriodFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBillingPeriodFrom, opts...).ToFunc() +} + +// ByBillingPeriodTo orders the results by the billing_period_to field. +func ByBillingPeriodTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBillingPeriodTo, opts...).ToFunc() +} + +// ByFullServicePeriodFrom orders the results by the full_service_period_from field. +func ByFullServicePeriodFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFullServicePeriodFrom, opts...).ToFunc() +} + +// ByFullServicePeriodTo orders the results by the full_service_period_to field. +func ByFullServicePeriodTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFullServicePeriodTo, opts...).ToFunc() +} + +// ByStatus orders the results by the status field. +func ByStatus(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStatus, opts...).ToFunc() +} + +// ByUniqueReferenceID orders the results by the unique_reference_id field. +func ByUniqueReferenceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUniqueReferenceID, opts...).ToFunc() +} + +// ByCurrency orders the results by the currency field. +func ByCurrency(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCurrency, opts...).ToFunc() +} + +// ByManagedBy orders the results by the managed_by field. +func ByManagedBy(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldManagedBy, opts...).ToFunc() +} + +// BySubscriptionID orders the results by the subscription_id field. +func BySubscriptionID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSubscriptionID, opts...).ToFunc() +} + +// BySubscriptionPhaseID orders the results by the subscription_phase_id field. +func BySubscriptionPhaseID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSubscriptionPhaseID, opts...).ToFunc() +} + +// BySubscriptionItemID orders the results by the subscription_item_id field. +func BySubscriptionItemID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSubscriptionItemID, opts...).ToFunc() +} + +// ByAdvanceAfter orders the results by the advance_after field. +func ByAdvanceAfter(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAdvanceAfter, opts...).ToFunc() +} + +// ByTaxCodeID orders the results by the tax_code_id field. +func ByTaxCodeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxCodeID, opts...).ToFunc() +} + +// ByTaxBehavior orders the results by the tax_behavior field. +func ByTaxBehavior(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxBehavior, 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() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, opts...).ToFunc() +} + +// ByCreditAmount orders the results by the credit_amount field. +func ByCreditAmount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreditAmount, opts...).ToFunc() +} + +// ByEffectiveAt orders the results by the effective_at field. +func ByEffectiveAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEffectiveAt, opts...).ToFunc() +} + +// ByExpiresAt orders the results by the expires_at field. +func ByExpiresAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldExpiresAt, opts...).ToFunc() +} + +// ByPriority orders the results by the priority field. +func ByPriority(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPriority, opts...).ToFunc() +} + +// ByFeatureFilters orders the results by the feature_filters field. +func ByFeatureFilters(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFeatureFilters, opts...).ToFunc() +} + +// BySettlement orders the results by the settlement field. +func BySettlement(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSettlement, opts...).ToFunc() +} + +// ByStatusDetailed orders the results by the status_detailed field. +func ByStatusDetailed(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStatusDetailed, opts...).ToFunc() +} + +// ByKey orders the results by the key field. +func ByKey(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldKey, opts...).ToFunc() +} + +// ByVoidedAt orders the results by the voided_at field. +func ByVoidedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVoidedAt, opts...).ToFunc() +} + +// ByExternalPaymentField orders the results by external_payment field. +func ByExternalPaymentField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newExternalPaymentStep(), sql.OrderByField(field, opts...)) + } +} + +// ByInvoicedPaymentField orders the results by invoiced_payment field. +func ByInvoicedPaymentField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newInvoicedPaymentStep(), sql.OrderByField(field, opts...)) + } +} + +// ByCreditGrantField orders the results by credit_grant field. +func ByCreditGrantField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCreditGrantStep(), sql.OrderByField(field, opts...)) + } +} + +// 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...)) + } +} + +// BySubscriptionField orders the results by subscription field. +func BySubscriptionField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubscriptionStep(), sql.OrderByField(field, opts...)) + } +} + +// BySubscriptionPhaseField orders the results by subscription_phase field. +func BySubscriptionPhaseField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubscriptionPhaseStep(), sql.OrderByField(field, opts...)) + } +} + +// BySubscriptionItemField orders the results by subscription_item field. +func BySubscriptionItemField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubscriptionItemStep(), sql.OrderByField(field, opts...)) + } +} + +// ByCustomerField orders the results by customer field. +func ByCustomerField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCustomerStep(), sql.OrderByField(field, opts...)) + } +} + +// ByTaxCodeField orders the results by tax_code field. +func ByTaxCodeField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTaxCodeStep(), sql.OrderByField(field, opts...)) + } +} +func newExternalPaymentStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ExternalPaymentInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, ExternalPaymentTable, ExternalPaymentColumn), + ) +} +func newInvoicedPaymentStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(InvoicedPaymentInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, InvoicedPaymentTable, InvoicedPaymentColumn), + ) +} +func newCreditGrantStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CreditGrantInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, CreditGrantTable, CreditGrantColumn), + ) +} +func newChargeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ChargeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, ChargeTable, ChargeColumn), + ) +} +func newSubscriptionStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SubscriptionInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionTable, SubscriptionColumn), + ) +} +func newSubscriptionPhaseStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SubscriptionPhaseInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionPhaseTable, SubscriptionPhaseColumn), + ) +} +func newSubscriptionItemStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SubscriptionItemInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionItemTable, SubscriptionItemColumn), + ) +} +func newCustomerStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CustomerInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, CustomerTable, CustomerColumn), + ) +} +func newTaxCodeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TaxCodeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, TaxCodeTable, TaxCodeColumn), + ) +} diff --git a/ent/db/chargecreditpurchase/where.go b/ent/db/chargecreditpurchase/where.go new file mode 100644 index 0000000000000000000000000000000000000000..67d39b566f4fa9134170d954f7b795be6a40e732 --- /dev/null +++ b/ent/db/chargecreditpurchase/where.go @@ -0,0 +1,2085 @@ +// Code generated by ent, DO NOT EDIT. + +package chargecreditpurchase + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/alpacahq/alpacadecimal" + "github.com/lib/pq" + "github.com/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/billing/charges/creditpurchase" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContainsFold(FieldID, id)) +} + +// CustomerID applies equality check predicate on the "customer_id" field. It's identical to CustomerIDEQ. +func CustomerID(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldCustomerID, v)) +} + +// ServicePeriodFrom applies equality check predicate on the "service_period_from" field. It's identical to ServicePeriodFromEQ. +func ServicePeriodFrom(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(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.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// BillingPeriodFrom applies equality check predicate on the "billing_period_from" field. It's identical to BillingPeriodFromEQ. +func BillingPeriodFrom(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodTo applies equality check predicate on the "billing_period_to" field. It's identical to BillingPeriodToEQ. +func BillingPeriodTo(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldBillingPeriodTo, v)) +} + +// FullServicePeriodFrom applies equality check predicate on the "full_service_period_from" field. It's identical to FullServicePeriodFromEQ. +func FullServicePeriodFrom(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodTo applies equality check predicate on the "full_service_period_to" field. It's identical to FullServicePeriodToEQ. +func FullServicePeriodTo(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldFullServicePeriodTo, v)) +} + +// UniqueReferenceID applies equality check predicate on the "unique_reference_id" field. It's identical to UniqueReferenceIDEQ. +func UniqueReferenceID(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldUniqueReferenceID, v)) +} + +// Currency applies equality check predicate on the "currency" field. It's identical to CurrencyEQ. +func Currency(v currencyx.Code) predicate.ChargeCreditPurchase { + vc := string(v) + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldCurrency, vc)) +} + +// SubscriptionID applies equality check predicate on the "subscription_id" field. It's identical to SubscriptionIDEQ. +func SubscriptionID(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldSubscriptionID, v)) +} + +// SubscriptionPhaseID applies equality check predicate on the "subscription_phase_id" field. It's identical to SubscriptionPhaseIDEQ. +func SubscriptionPhaseID(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionItemID applies equality check predicate on the "subscription_item_id" field. It's identical to SubscriptionItemIDEQ. +func SubscriptionItemID(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldSubscriptionItemID, v)) +} + +// AdvanceAfter applies equality check predicate on the "advance_after" field. It's identical to AdvanceAfterEQ. +func AdvanceAfter(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldAdvanceAfter, v)) +} + +// TaxCodeID applies equality check predicate on the "tax_code_id" field. It's identical to TaxCodeIDEQ. +func TaxCodeID(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldTaxCodeID, v)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(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.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(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.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(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.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldName, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldDescription, v)) +} + +// CreditAmount applies equality check predicate on the "credit_amount" field. It's identical to CreditAmountEQ. +func CreditAmount(v alpacadecimal.Decimal) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldCreditAmount, v)) +} + +// EffectiveAt applies equality check predicate on the "effective_at" field. It's identical to EffectiveAtEQ. +func EffectiveAt(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldEffectiveAt, v)) +} + +// ExpiresAt applies equality check predicate on the "expires_at" field. It's identical to ExpiresAtEQ. +func ExpiresAt(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldExpiresAt, v)) +} + +// Priority applies equality check predicate on the "priority" field. It's identical to PriorityEQ. +func Priority(v int) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldPriority, v)) +} + +// FeatureFilters applies equality check predicate on the "feature_filters" field. It's identical to FeatureFiltersEQ. +func FeatureFilters(v pq.StringArray) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldFeatureFilters, v)) +} + +// Key applies equality check predicate on the "key" field. It's identical to KeyEQ. +func Key(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldKey, v)) +} + +// VoidedAt applies equality check predicate on the "voided_at" field. It's identical to VoidedAtEQ. +func VoidedAt(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldVoidedAt, v)) +} + +// CustomerIDEQ applies the EQ predicate on the "customer_id" field. +func CustomerIDEQ(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldCustomerID, v)) +} + +// CustomerIDNEQ applies the NEQ predicate on the "customer_id" field. +func CustomerIDNEQ(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldCustomerID, v)) +} + +// CustomerIDIn applies the In predicate on the "customer_id" field. +func CustomerIDIn(vs ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldCustomerID, vs...)) +} + +// CustomerIDNotIn applies the NotIn predicate on the "customer_id" field. +func CustomerIDNotIn(vs ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldCustomerID, vs...)) +} + +// CustomerIDGT applies the GT predicate on the "customer_id" field. +func CustomerIDGT(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldCustomerID, v)) +} + +// CustomerIDGTE applies the GTE predicate on the "customer_id" field. +func CustomerIDGTE(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldCustomerID, v)) +} + +// CustomerIDLT applies the LT predicate on the "customer_id" field. +func CustomerIDLT(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldCustomerID, v)) +} + +// CustomerIDLTE applies the LTE predicate on the "customer_id" field. +func CustomerIDLTE(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldCustomerID, v)) +} + +// CustomerIDContains applies the Contains predicate on the "customer_id" field. +func CustomerIDContains(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContains(FieldCustomerID, v)) +} + +// CustomerIDHasPrefix applies the HasPrefix predicate on the "customer_id" field. +func CustomerIDHasPrefix(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldHasPrefix(FieldCustomerID, v)) +} + +// CustomerIDHasSuffix applies the HasSuffix predicate on the "customer_id" field. +func CustomerIDHasSuffix(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldHasSuffix(FieldCustomerID, v)) +} + +// CustomerIDEqualFold applies the EqualFold predicate on the "customer_id" field. +func CustomerIDEqualFold(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEqualFold(FieldCustomerID, v)) +} + +// CustomerIDContainsFold applies the ContainsFold predicate on the "customer_id" field. +func CustomerIDContainsFold(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContainsFold(FieldCustomerID, v)) +} + +// ServicePeriodFromEQ applies the EQ predicate on the "service_period_from" field. +func ServicePeriodFromEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromNEQ applies the NEQ predicate on the "service_period_from" field. +func ServicePeriodFromNEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromIn applies the In predicate on the "service_period_from" field. +func ServicePeriodFromIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromNotIn applies the NotIn predicate on the "service_period_from" field. +func ServicePeriodFromNotIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromGT applies the GT predicate on the "service_period_from" field. +func ServicePeriodFromGT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromGTE applies the GTE predicate on the "service_period_from" field. +func ServicePeriodFromGTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLT applies the LT predicate on the "service_period_from" field. +func ServicePeriodFromLT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLTE applies the LTE predicate on the "service_period_from" field. +func ServicePeriodFromLTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodToEQ applies the EQ predicate on the "service_period_to" field. +func ServicePeriodToEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToNEQ applies the NEQ predicate on the "service_period_to" field. +func ServicePeriodToNEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToIn applies the In predicate on the "service_period_to" field. +func ServicePeriodToIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToNotIn applies the NotIn predicate on the "service_period_to" field. +func ServicePeriodToNotIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToGT applies the GT predicate on the "service_period_to" field. +func ServicePeriodToGT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToGTE applies the GTE predicate on the "service_period_to" field. +func ServicePeriodToGTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLT applies the LT predicate on the "service_period_to" field. +func ServicePeriodToLT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLTE applies the LTE predicate on the "service_period_to" field. +func ServicePeriodToLTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldServicePeriodTo, v)) +} + +// BillingPeriodFromEQ applies the EQ predicate on the "billing_period_from" field. +func BillingPeriodFromEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromNEQ applies the NEQ predicate on the "billing_period_from" field. +func BillingPeriodFromNEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromIn applies the In predicate on the "billing_period_from" field. +func BillingPeriodFromIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldBillingPeriodFrom, vs...)) +} + +// BillingPeriodFromNotIn applies the NotIn predicate on the "billing_period_from" field. +func BillingPeriodFromNotIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldBillingPeriodFrom, vs...)) +} + +// BillingPeriodFromGT applies the GT predicate on the "billing_period_from" field. +func BillingPeriodFromGT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromGTE applies the GTE predicate on the "billing_period_from" field. +func BillingPeriodFromGTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromLT applies the LT predicate on the "billing_period_from" field. +func BillingPeriodFromLT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromLTE applies the LTE predicate on the "billing_period_from" field. +func BillingPeriodFromLTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodToEQ applies the EQ predicate on the "billing_period_to" field. +func BillingPeriodToEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToNEQ applies the NEQ predicate on the "billing_period_to" field. +func BillingPeriodToNEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToIn applies the In predicate on the "billing_period_to" field. +func BillingPeriodToIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldBillingPeriodTo, vs...)) +} + +// BillingPeriodToNotIn applies the NotIn predicate on the "billing_period_to" field. +func BillingPeriodToNotIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldBillingPeriodTo, vs...)) +} + +// BillingPeriodToGT applies the GT predicate on the "billing_period_to" field. +func BillingPeriodToGT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToGTE applies the GTE predicate on the "billing_period_to" field. +func BillingPeriodToGTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToLT applies the LT predicate on the "billing_period_to" field. +func BillingPeriodToLT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToLTE applies the LTE predicate on the "billing_period_to" field. +func BillingPeriodToLTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldBillingPeriodTo, v)) +} + +// FullServicePeriodFromEQ applies the EQ predicate on the "full_service_period_from" field. +func FullServicePeriodFromEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromNEQ applies the NEQ predicate on the "full_service_period_from" field. +func FullServicePeriodFromNEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromIn applies the In predicate on the "full_service_period_from" field. +func FullServicePeriodFromIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldFullServicePeriodFrom, vs...)) +} + +// FullServicePeriodFromNotIn applies the NotIn predicate on the "full_service_period_from" field. +func FullServicePeriodFromNotIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldFullServicePeriodFrom, vs...)) +} + +// FullServicePeriodFromGT applies the GT predicate on the "full_service_period_from" field. +func FullServicePeriodFromGT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromGTE applies the GTE predicate on the "full_service_period_from" field. +func FullServicePeriodFromGTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromLT applies the LT predicate on the "full_service_period_from" field. +func FullServicePeriodFromLT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromLTE applies the LTE predicate on the "full_service_period_from" field. +func FullServicePeriodFromLTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodToEQ applies the EQ predicate on the "full_service_period_to" field. +func FullServicePeriodToEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToNEQ applies the NEQ predicate on the "full_service_period_to" field. +func FullServicePeriodToNEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToIn applies the In predicate on the "full_service_period_to" field. +func FullServicePeriodToIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldFullServicePeriodTo, vs...)) +} + +// FullServicePeriodToNotIn applies the NotIn predicate on the "full_service_period_to" field. +func FullServicePeriodToNotIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldFullServicePeriodTo, vs...)) +} + +// FullServicePeriodToGT applies the GT predicate on the "full_service_period_to" field. +func FullServicePeriodToGT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToGTE applies the GTE predicate on the "full_service_period_to" field. +func FullServicePeriodToGTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToLT applies the LT predicate on the "full_service_period_to" field. +func FullServicePeriodToLT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToLTE applies the LTE predicate on the "full_service_period_to" field. +func FullServicePeriodToLTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldFullServicePeriodTo, v)) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v meta.ChargeStatus) predicate.ChargeCreditPurchase { + vc := v + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldStatus, vc)) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v meta.ChargeStatus) predicate.ChargeCreditPurchase { + vc := v + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldStatus, vc)) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...meta.ChargeStatus) predicate.ChargeCreditPurchase { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldStatus, v...)) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...meta.ChargeStatus) predicate.ChargeCreditPurchase { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldStatus, v...)) +} + +// UniqueReferenceIDEQ applies the EQ predicate on the "unique_reference_id" field. +func UniqueReferenceIDEQ(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDNEQ applies the NEQ predicate on the "unique_reference_id" field. +func UniqueReferenceIDNEQ(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDIn applies the In predicate on the "unique_reference_id" field. +func UniqueReferenceIDIn(vs ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldUniqueReferenceID, vs...)) +} + +// UniqueReferenceIDNotIn applies the NotIn predicate on the "unique_reference_id" field. +func UniqueReferenceIDNotIn(vs ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldUniqueReferenceID, vs...)) +} + +// UniqueReferenceIDGT applies the GT predicate on the "unique_reference_id" field. +func UniqueReferenceIDGT(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDGTE applies the GTE predicate on the "unique_reference_id" field. +func UniqueReferenceIDGTE(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDLT applies the LT predicate on the "unique_reference_id" field. +func UniqueReferenceIDLT(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDLTE applies the LTE predicate on the "unique_reference_id" field. +func UniqueReferenceIDLTE(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDContains applies the Contains predicate on the "unique_reference_id" field. +func UniqueReferenceIDContains(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContains(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDHasPrefix applies the HasPrefix predicate on the "unique_reference_id" field. +func UniqueReferenceIDHasPrefix(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldHasPrefix(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDHasSuffix applies the HasSuffix predicate on the "unique_reference_id" field. +func UniqueReferenceIDHasSuffix(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldHasSuffix(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDIsNil applies the IsNil predicate on the "unique_reference_id" field. +func UniqueReferenceIDIsNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIsNull(FieldUniqueReferenceID)) +} + +// UniqueReferenceIDNotNil applies the NotNil predicate on the "unique_reference_id" field. +func UniqueReferenceIDNotNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotNull(FieldUniqueReferenceID)) +} + +// UniqueReferenceIDEqualFold applies the EqualFold predicate on the "unique_reference_id" field. +func UniqueReferenceIDEqualFold(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEqualFold(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDContainsFold applies the ContainsFold predicate on the "unique_reference_id" field. +func UniqueReferenceIDContainsFold(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContainsFold(FieldUniqueReferenceID, v)) +} + +// CurrencyEQ applies the EQ predicate on the "currency" field. +func CurrencyEQ(v currencyx.Code) predicate.ChargeCreditPurchase { + vc := string(v) + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldCurrency, vc)) +} + +// CurrencyNEQ applies the NEQ predicate on the "currency" field. +func CurrencyNEQ(v currencyx.Code) predicate.ChargeCreditPurchase { + vc := string(v) + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldCurrency, vc)) +} + +// CurrencyIn applies the In predicate on the "currency" field. +func CurrencyIn(vs ...currencyx.Code) predicate.ChargeCreditPurchase { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldCurrency, v...)) +} + +// CurrencyNotIn applies the NotIn predicate on the "currency" field. +func CurrencyNotIn(vs ...currencyx.Code) predicate.ChargeCreditPurchase { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldCurrency, v...)) +} + +// CurrencyGT applies the GT predicate on the "currency" field. +func CurrencyGT(v currencyx.Code) predicate.ChargeCreditPurchase { + vc := string(v) + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldCurrency, vc)) +} + +// CurrencyGTE applies the GTE predicate on the "currency" field. +func CurrencyGTE(v currencyx.Code) predicate.ChargeCreditPurchase { + vc := string(v) + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldCurrency, vc)) +} + +// CurrencyLT applies the LT predicate on the "currency" field. +func CurrencyLT(v currencyx.Code) predicate.ChargeCreditPurchase { + vc := string(v) + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldCurrency, vc)) +} + +// CurrencyLTE applies the LTE predicate on the "currency" field. +func CurrencyLTE(v currencyx.Code) predicate.ChargeCreditPurchase { + vc := string(v) + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldCurrency, vc)) +} + +// CurrencyContains applies the Contains predicate on the "currency" field. +func CurrencyContains(v currencyx.Code) predicate.ChargeCreditPurchase { + vc := string(v) + return predicate.ChargeCreditPurchase(sql.FieldContains(FieldCurrency, vc)) +} + +// CurrencyHasPrefix applies the HasPrefix predicate on the "currency" field. +func CurrencyHasPrefix(v currencyx.Code) predicate.ChargeCreditPurchase { + vc := string(v) + return predicate.ChargeCreditPurchase(sql.FieldHasPrefix(FieldCurrency, vc)) +} + +// CurrencyHasSuffix applies the HasSuffix predicate on the "currency" field. +func CurrencyHasSuffix(v currencyx.Code) predicate.ChargeCreditPurchase { + vc := string(v) + return predicate.ChargeCreditPurchase(sql.FieldHasSuffix(FieldCurrency, vc)) +} + +// CurrencyEqualFold applies the EqualFold predicate on the "currency" field. +func CurrencyEqualFold(v currencyx.Code) predicate.ChargeCreditPurchase { + vc := string(v) + return predicate.ChargeCreditPurchase(sql.FieldEqualFold(FieldCurrency, vc)) +} + +// CurrencyContainsFold applies the ContainsFold predicate on the "currency" field. +func CurrencyContainsFold(v currencyx.Code) predicate.ChargeCreditPurchase { + vc := string(v) + return predicate.ChargeCreditPurchase(sql.FieldContainsFold(FieldCurrency, vc)) +} + +// ManagedByEQ applies the EQ predicate on the "managed_by" field. +func ManagedByEQ(v billing.InvoiceLineManagedBy) predicate.ChargeCreditPurchase { + vc := v + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldManagedBy, vc)) +} + +// ManagedByNEQ applies the NEQ predicate on the "managed_by" field. +func ManagedByNEQ(v billing.InvoiceLineManagedBy) predicate.ChargeCreditPurchase { + vc := v + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldManagedBy, vc)) +} + +// ManagedByIn applies the In predicate on the "managed_by" field. +func ManagedByIn(vs ...billing.InvoiceLineManagedBy) predicate.ChargeCreditPurchase { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldManagedBy, v...)) +} + +// ManagedByNotIn applies the NotIn predicate on the "managed_by" field. +func ManagedByNotIn(vs ...billing.InvoiceLineManagedBy) predicate.ChargeCreditPurchase { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldManagedBy, v...)) +} + +// SubscriptionIDEQ applies the EQ predicate on the "subscription_id" field. +func SubscriptionIDEQ(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldSubscriptionID, v)) +} + +// SubscriptionIDNEQ applies the NEQ predicate on the "subscription_id" field. +func SubscriptionIDNEQ(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldSubscriptionID, v)) +} + +// SubscriptionIDIn applies the In predicate on the "subscription_id" field. +func SubscriptionIDIn(vs ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldSubscriptionID, vs...)) +} + +// SubscriptionIDNotIn applies the NotIn predicate on the "subscription_id" field. +func SubscriptionIDNotIn(vs ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldSubscriptionID, vs...)) +} + +// SubscriptionIDGT applies the GT predicate on the "subscription_id" field. +func SubscriptionIDGT(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldSubscriptionID, v)) +} + +// SubscriptionIDGTE applies the GTE predicate on the "subscription_id" field. +func SubscriptionIDGTE(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldSubscriptionID, v)) +} + +// SubscriptionIDLT applies the LT predicate on the "subscription_id" field. +func SubscriptionIDLT(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldSubscriptionID, v)) +} + +// SubscriptionIDLTE applies the LTE predicate on the "subscription_id" field. +func SubscriptionIDLTE(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldSubscriptionID, v)) +} + +// SubscriptionIDContains applies the Contains predicate on the "subscription_id" field. +func SubscriptionIDContains(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContains(FieldSubscriptionID, v)) +} + +// SubscriptionIDHasPrefix applies the HasPrefix predicate on the "subscription_id" field. +func SubscriptionIDHasPrefix(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldHasPrefix(FieldSubscriptionID, v)) +} + +// SubscriptionIDHasSuffix applies the HasSuffix predicate on the "subscription_id" field. +func SubscriptionIDHasSuffix(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldHasSuffix(FieldSubscriptionID, v)) +} + +// SubscriptionIDIsNil applies the IsNil predicate on the "subscription_id" field. +func SubscriptionIDIsNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIsNull(FieldSubscriptionID)) +} + +// SubscriptionIDNotNil applies the NotNil predicate on the "subscription_id" field. +func SubscriptionIDNotNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotNull(FieldSubscriptionID)) +} + +// SubscriptionIDEqualFold applies the EqualFold predicate on the "subscription_id" field. +func SubscriptionIDEqualFold(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEqualFold(FieldSubscriptionID, v)) +} + +// SubscriptionIDContainsFold applies the ContainsFold predicate on the "subscription_id" field. +func SubscriptionIDContainsFold(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContainsFold(FieldSubscriptionID, v)) +} + +// SubscriptionPhaseIDEQ applies the EQ predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDEQ(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDNEQ applies the NEQ predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDNEQ(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDIn applies the In predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDIn(vs ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldSubscriptionPhaseID, vs...)) +} + +// SubscriptionPhaseIDNotIn applies the NotIn predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDNotIn(vs ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldSubscriptionPhaseID, vs...)) +} + +// SubscriptionPhaseIDGT applies the GT predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDGT(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDGTE applies the GTE predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDGTE(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDLT applies the LT predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDLT(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDLTE applies the LTE predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDLTE(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDContains applies the Contains predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDContains(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContains(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDHasPrefix applies the HasPrefix predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDHasPrefix(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldHasPrefix(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDHasSuffix applies the HasSuffix predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDHasSuffix(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldHasSuffix(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDIsNil applies the IsNil predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDIsNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIsNull(FieldSubscriptionPhaseID)) +} + +// SubscriptionPhaseIDNotNil applies the NotNil predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDNotNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotNull(FieldSubscriptionPhaseID)) +} + +// SubscriptionPhaseIDEqualFold applies the EqualFold predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDEqualFold(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEqualFold(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDContainsFold applies the ContainsFold predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDContainsFold(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContainsFold(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionItemIDEQ applies the EQ predicate on the "subscription_item_id" field. +func SubscriptionItemIDEQ(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDNEQ applies the NEQ predicate on the "subscription_item_id" field. +func SubscriptionItemIDNEQ(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDIn applies the In predicate on the "subscription_item_id" field. +func SubscriptionItemIDIn(vs ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldSubscriptionItemID, vs...)) +} + +// SubscriptionItemIDNotIn applies the NotIn predicate on the "subscription_item_id" field. +func SubscriptionItemIDNotIn(vs ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldSubscriptionItemID, vs...)) +} + +// SubscriptionItemIDGT applies the GT predicate on the "subscription_item_id" field. +func SubscriptionItemIDGT(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDGTE applies the GTE predicate on the "subscription_item_id" field. +func SubscriptionItemIDGTE(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDLT applies the LT predicate on the "subscription_item_id" field. +func SubscriptionItemIDLT(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDLTE applies the LTE predicate on the "subscription_item_id" field. +func SubscriptionItemIDLTE(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDContains applies the Contains predicate on the "subscription_item_id" field. +func SubscriptionItemIDContains(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContains(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDHasPrefix applies the HasPrefix predicate on the "subscription_item_id" field. +func SubscriptionItemIDHasPrefix(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldHasPrefix(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDHasSuffix applies the HasSuffix predicate on the "subscription_item_id" field. +func SubscriptionItemIDHasSuffix(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldHasSuffix(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDIsNil applies the IsNil predicate on the "subscription_item_id" field. +func SubscriptionItemIDIsNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIsNull(FieldSubscriptionItemID)) +} + +// SubscriptionItemIDNotNil applies the NotNil predicate on the "subscription_item_id" field. +func SubscriptionItemIDNotNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotNull(FieldSubscriptionItemID)) +} + +// SubscriptionItemIDEqualFold applies the EqualFold predicate on the "subscription_item_id" field. +func SubscriptionItemIDEqualFold(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEqualFold(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDContainsFold applies the ContainsFold predicate on the "subscription_item_id" field. +func SubscriptionItemIDContainsFold(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContainsFold(FieldSubscriptionItemID, v)) +} + +// AdvanceAfterEQ applies the EQ predicate on the "advance_after" field. +func AdvanceAfterEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldAdvanceAfter, v)) +} + +// AdvanceAfterNEQ applies the NEQ predicate on the "advance_after" field. +func AdvanceAfterNEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldAdvanceAfter, v)) +} + +// AdvanceAfterIn applies the In predicate on the "advance_after" field. +func AdvanceAfterIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldAdvanceAfter, vs...)) +} + +// AdvanceAfterNotIn applies the NotIn predicate on the "advance_after" field. +func AdvanceAfterNotIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldAdvanceAfter, vs...)) +} + +// AdvanceAfterGT applies the GT predicate on the "advance_after" field. +func AdvanceAfterGT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldAdvanceAfter, v)) +} + +// AdvanceAfterGTE applies the GTE predicate on the "advance_after" field. +func AdvanceAfterGTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldAdvanceAfter, v)) +} + +// AdvanceAfterLT applies the LT predicate on the "advance_after" field. +func AdvanceAfterLT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldAdvanceAfter, v)) +} + +// AdvanceAfterLTE applies the LTE predicate on the "advance_after" field. +func AdvanceAfterLTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldAdvanceAfter, v)) +} + +// AdvanceAfterIsNil applies the IsNil predicate on the "advance_after" field. +func AdvanceAfterIsNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIsNull(FieldAdvanceAfter)) +} + +// AdvanceAfterNotNil applies the NotNil predicate on the "advance_after" field. +func AdvanceAfterNotNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotNull(FieldAdvanceAfter)) +} + +// TaxCodeIDEQ applies the EQ predicate on the "tax_code_id" field. +func TaxCodeIDEQ(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldTaxCodeID, v)) +} + +// TaxCodeIDNEQ applies the NEQ predicate on the "tax_code_id" field. +func TaxCodeIDNEQ(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldTaxCodeID, v)) +} + +// TaxCodeIDIn applies the In predicate on the "tax_code_id" field. +func TaxCodeIDIn(vs ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldTaxCodeID, vs...)) +} + +// TaxCodeIDNotIn applies the NotIn predicate on the "tax_code_id" field. +func TaxCodeIDNotIn(vs ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldTaxCodeID, vs...)) +} + +// TaxCodeIDGT applies the GT predicate on the "tax_code_id" field. +func TaxCodeIDGT(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldTaxCodeID, v)) +} + +// TaxCodeIDGTE applies the GTE predicate on the "tax_code_id" field. +func TaxCodeIDGTE(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldTaxCodeID, v)) +} + +// TaxCodeIDLT applies the LT predicate on the "tax_code_id" field. +func TaxCodeIDLT(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldTaxCodeID, v)) +} + +// TaxCodeIDLTE applies the LTE predicate on the "tax_code_id" field. +func TaxCodeIDLTE(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldTaxCodeID, v)) +} + +// TaxCodeIDContains applies the Contains predicate on the "tax_code_id" field. +func TaxCodeIDContains(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContains(FieldTaxCodeID, v)) +} + +// TaxCodeIDHasPrefix applies the HasPrefix predicate on the "tax_code_id" field. +func TaxCodeIDHasPrefix(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldHasPrefix(FieldTaxCodeID, v)) +} + +// TaxCodeIDHasSuffix applies the HasSuffix predicate on the "tax_code_id" field. +func TaxCodeIDHasSuffix(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldHasSuffix(FieldTaxCodeID, v)) +} + +// TaxCodeIDEqualFold applies the EqualFold predicate on the "tax_code_id" field. +func TaxCodeIDEqualFold(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEqualFold(FieldTaxCodeID, v)) +} + +// TaxCodeIDContainsFold applies the ContainsFold predicate on the "tax_code_id" field. +func TaxCodeIDContainsFold(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContainsFold(FieldTaxCodeID, v)) +} + +// TaxBehaviorEQ applies the EQ predicate on the "tax_behavior" field. +func TaxBehaviorEQ(v productcatalog.TaxBehavior) predicate.ChargeCreditPurchase { + vc := v + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldTaxBehavior, vc)) +} + +// TaxBehaviorNEQ applies the NEQ predicate on the "tax_behavior" field. +func TaxBehaviorNEQ(v productcatalog.TaxBehavior) predicate.ChargeCreditPurchase { + vc := v + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldTaxBehavior, vc)) +} + +// TaxBehaviorIn applies the In predicate on the "tax_behavior" field. +func TaxBehaviorIn(vs ...productcatalog.TaxBehavior) predicate.ChargeCreditPurchase { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldTaxBehavior, v...)) +} + +// TaxBehaviorNotIn applies the NotIn predicate on the "tax_behavior" field. +func TaxBehaviorNotIn(vs ...productcatalog.TaxBehavior) predicate.ChargeCreditPurchase { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldTaxBehavior, v...)) +} + +// TaxBehaviorIsNil applies the IsNil predicate on the "tax_behavior" field. +func TaxBehaviorIsNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIsNull(FieldTaxBehavior)) +} + +// TaxBehaviorNotNil applies the NotNil predicate on the "tax_behavior" field. +func TaxBehaviorNotNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotNull(FieldTaxBehavior)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotNull(FieldAnnotations)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContainsFold(FieldNamespace, v)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotNull(FieldMetadata)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotNull(FieldDeletedAt)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContainsFold(FieldName, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContainsFold(FieldDescription, v)) +} + +// CreditAmountEQ applies the EQ predicate on the "credit_amount" field. +func CreditAmountEQ(v alpacadecimal.Decimal) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldCreditAmount, v)) +} + +// CreditAmountNEQ applies the NEQ predicate on the "credit_amount" field. +func CreditAmountNEQ(v alpacadecimal.Decimal) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldCreditAmount, v)) +} + +// CreditAmountIn applies the In predicate on the "credit_amount" field. +func CreditAmountIn(vs ...alpacadecimal.Decimal) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldCreditAmount, vs...)) +} + +// CreditAmountNotIn applies the NotIn predicate on the "credit_amount" field. +func CreditAmountNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldCreditAmount, vs...)) +} + +// CreditAmountGT applies the GT predicate on the "credit_amount" field. +func CreditAmountGT(v alpacadecimal.Decimal) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldCreditAmount, v)) +} + +// CreditAmountGTE applies the GTE predicate on the "credit_amount" field. +func CreditAmountGTE(v alpacadecimal.Decimal) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldCreditAmount, v)) +} + +// CreditAmountLT applies the LT predicate on the "credit_amount" field. +func CreditAmountLT(v alpacadecimal.Decimal) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldCreditAmount, v)) +} + +// CreditAmountLTE applies the LTE predicate on the "credit_amount" field. +func CreditAmountLTE(v alpacadecimal.Decimal) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldCreditAmount, v)) +} + +// EffectiveAtEQ applies the EQ predicate on the "effective_at" field. +func EffectiveAtEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldEffectiveAt, v)) +} + +// EffectiveAtNEQ applies the NEQ predicate on the "effective_at" field. +func EffectiveAtNEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldEffectiveAt, v)) +} + +// EffectiveAtIn applies the In predicate on the "effective_at" field. +func EffectiveAtIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldEffectiveAt, vs...)) +} + +// EffectiveAtNotIn applies the NotIn predicate on the "effective_at" field. +func EffectiveAtNotIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldEffectiveAt, vs...)) +} + +// EffectiveAtGT applies the GT predicate on the "effective_at" field. +func EffectiveAtGT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldEffectiveAt, v)) +} + +// EffectiveAtGTE applies the GTE predicate on the "effective_at" field. +func EffectiveAtGTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldEffectiveAt, v)) +} + +// EffectiveAtLT applies the LT predicate on the "effective_at" field. +func EffectiveAtLT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldEffectiveAt, v)) +} + +// EffectiveAtLTE applies the LTE predicate on the "effective_at" field. +func EffectiveAtLTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldEffectiveAt, v)) +} + +// EffectiveAtIsNil applies the IsNil predicate on the "effective_at" field. +func EffectiveAtIsNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIsNull(FieldEffectiveAt)) +} + +// EffectiveAtNotNil applies the NotNil predicate on the "effective_at" field. +func EffectiveAtNotNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotNull(FieldEffectiveAt)) +} + +// ExpiresAtEQ applies the EQ predicate on the "expires_at" field. +func ExpiresAtEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldExpiresAt, v)) +} + +// ExpiresAtNEQ applies the NEQ predicate on the "expires_at" field. +func ExpiresAtNEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldExpiresAt, v)) +} + +// ExpiresAtIn applies the In predicate on the "expires_at" field. +func ExpiresAtIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldExpiresAt, vs...)) +} + +// ExpiresAtNotIn applies the NotIn predicate on the "expires_at" field. +func ExpiresAtNotIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldExpiresAt, vs...)) +} + +// ExpiresAtGT applies the GT predicate on the "expires_at" field. +func ExpiresAtGT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldExpiresAt, v)) +} + +// ExpiresAtGTE applies the GTE predicate on the "expires_at" field. +func ExpiresAtGTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldExpiresAt, v)) +} + +// ExpiresAtLT applies the LT predicate on the "expires_at" field. +func ExpiresAtLT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldExpiresAt, v)) +} + +// ExpiresAtLTE applies the LTE predicate on the "expires_at" field. +func ExpiresAtLTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldExpiresAt, v)) +} + +// ExpiresAtIsNil applies the IsNil predicate on the "expires_at" field. +func ExpiresAtIsNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIsNull(FieldExpiresAt)) +} + +// ExpiresAtNotNil applies the NotNil predicate on the "expires_at" field. +func ExpiresAtNotNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotNull(FieldExpiresAt)) +} + +// PriorityEQ applies the EQ predicate on the "priority" field. +func PriorityEQ(v int) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldPriority, v)) +} + +// PriorityNEQ applies the NEQ predicate on the "priority" field. +func PriorityNEQ(v int) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldPriority, v)) +} + +// PriorityIn applies the In predicate on the "priority" field. +func PriorityIn(vs ...int) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldPriority, vs...)) +} + +// PriorityNotIn applies the NotIn predicate on the "priority" field. +func PriorityNotIn(vs ...int) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldPriority, vs...)) +} + +// PriorityGT applies the GT predicate on the "priority" field. +func PriorityGT(v int) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldPriority, v)) +} + +// PriorityGTE applies the GTE predicate on the "priority" field. +func PriorityGTE(v int) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldPriority, v)) +} + +// PriorityLT applies the LT predicate on the "priority" field. +func PriorityLT(v int) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldPriority, v)) +} + +// PriorityLTE applies the LTE predicate on the "priority" field. +func PriorityLTE(v int) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldPriority, v)) +} + +// PriorityIsNil applies the IsNil predicate on the "priority" field. +func PriorityIsNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIsNull(FieldPriority)) +} + +// PriorityNotNil applies the NotNil predicate on the "priority" field. +func PriorityNotNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotNull(FieldPriority)) +} + +// FeatureFiltersEQ applies the EQ predicate on the "feature_filters" field. +func FeatureFiltersEQ(v pq.StringArray) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldFeatureFilters, v)) +} + +// FeatureFiltersNEQ applies the NEQ predicate on the "feature_filters" field. +func FeatureFiltersNEQ(v pq.StringArray) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldFeatureFilters, v)) +} + +// FeatureFiltersIn applies the In predicate on the "feature_filters" field. +func FeatureFiltersIn(vs ...pq.StringArray) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldFeatureFilters, vs...)) +} + +// FeatureFiltersNotIn applies the NotIn predicate on the "feature_filters" field. +func FeatureFiltersNotIn(vs ...pq.StringArray) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldFeatureFilters, vs...)) +} + +// FeatureFiltersGT applies the GT predicate on the "feature_filters" field. +func FeatureFiltersGT(v pq.StringArray) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldFeatureFilters, v)) +} + +// FeatureFiltersGTE applies the GTE predicate on the "feature_filters" field. +func FeatureFiltersGTE(v pq.StringArray) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldFeatureFilters, v)) +} + +// FeatureFiltersLT applies the LT predicate on the "feature_filters" field. +func FeatureFiltersLT(v pq.StringArray) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldFeatureFilters, v)) +} + +// FeatureFiltersLTE applies the LTE predicate on the "feature_filters" field. +func FeatureFiltersLTE(v pq.StringArray) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldFeatureFilters, v)) +} + +// FeatureFiltersIsNil applies the IsNil predicate on the "feature_filters" field. +func FeatureFiltersIsNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIsNull(FieldFeatureFilters)) +} + +// FeatureFiltersNotNil applies the NotNil predicate on the "feature_filters" field. +func FeatureFiltersNotNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotNull(FieldFeatureFilters)) +} + +// StatusDetailedEQ applies the EQ predicate on the "status_detailed" field. +func StatusDetailedEQ(v creditpurchase.Status) predicate.ChargeCreditPurchase { + vc := v + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldStatusDetailed, vc)) +} + +// StatusDetailedNEQ applies the NEQ predicate on the "status_detailed" field. +func StatusDetailedNEQ(v creditpurchase.Status) predicate.ChargeCreditPurchase { + vc := v + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldStatusDetailed, vc)) +} + +// StatusDetailedIn applies the In predicate on the "status_detailed" field. +func StatusDetailedIn(vs ...creditpurchase.Status) predicate.ChargeCreditPurchase { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldStatusDetailed, v...)) +} + +// StatusDetailedNotIn applies the NotIn predicate on the "status_detailed" field. +func StatusDetailedNotIn(vs ...creditpurchase.Status) predicate.ChargeCreditPurchase { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldStatusDetailed, v...)) +} + +// KeyEQ applies the EQ predicate on the "key" field. +func KeyEQ(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldKey, v)) +} + +// KeyNEQ applies the NEQ predicate on the "key" field. +func KeyNEQ(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldKey, v)) +} + +// KeyIn applies the In predicate on the "key" field. +func KeyIn(vs ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldKey, vs...)) +} + +// KeyNotIn applies the NotIn predicate on the "key" field. +func KeyNotIn(vs ...string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldKey, vs...)) +} + +// KeyGT applies the GT predicate on the "key" field. +func KeyGT(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldKey, v)) +} + +// KeyGTE applies the GTE predicate on the "key" field. +func KeyGTE(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldKey, v)) +} + +// KeyLT applies the LT predicate on the "key" field. +func KeyLT(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldKey, v)) +} + +// KeyLTE applies the LTE predicate on the "key" field. +func KeyLTE(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldKey, v)) +} + +// KeyContains applies the Contains predicate on the "key" field. +func KeyContains(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContains(FieldKey, v)) +} + +// KeyHasPrefix applies the HasPrefix predicate on the "key" field. +func KeyHasPrefix(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldHasPrefix(FieldKey, v)) +} + +// KeyHasSuffix applies the HasSuffix predicate on the "key" field. +func KeyHasSuffix(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldHasSuffix(FieldKey, v)) +} + +// KeyIsNil applies the IsNil predicate on the "key" field. +func KeyIsNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIsNull(FieldKey)) +} + +// KeyNotNil applies the NotNil predicate on the "key" field. +func KeyNotNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotNull(FieldKey)) +} + +// KeyEqualFold applies the EqualFold predicate on the "key" field. +func KeyEqualFold(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEqualFold(FieldKey, v)) +} + +// KeyContainsFold applies the ContainsFold predicate on the "key" field. +func KeyContainsFold(v string) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldContainsFold(FieldKey, v)) +} + +// VoidedAtEQ applies the EQ predicate on the "voided_at" field. +func VoidedAtEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldEQ(FieldVoidedAt, v)) +} + +// VoidedAtNEQ applies the NEQ predicate on the "voided_at" field. +func VoidedAtNEQ(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNEQ(FieldVoidedAt, v)) +} + +// VoidedAtIn applies the In predicate on the "voided_at" field. +func VoidedAtIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIn(FieldVoidedAt, vs...)) +} + +// VoidedAtNotIn applies the NotIn predicate on the "voided_at" field. +func VoidedAtNotIn(vs ...time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotIn(FieldVoidedAt, vs...)) +} + +// VoidedAtGT applies the GT predicate on the "voided_at" field. +func VoidedAtGT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGT(FieldVoidedAt, v)) +} + +// VoidedAtGTE applies the GTE predicate on the "voided_at" field. +func VoidedAtGTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldGTE(FieldVoidedAt, v)) +} + +// VoidedAtLT applies the LT predicate on the "voided_at" field. +func VoidedAtLT(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLT(FieldVoidedAt, v)) +} + +// VoidedAtLTE applies the LTE predicate on the "voided_at" field. +func VoidedAtLTE(v time.Time) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldLTE(FieldVoidedAt, v)) +} + +// VoidedAtIsNil applies the IsNil predicate on the "voided_at" field. +func VoidedAtIsNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldIsNull(FieldVoidedAt)) +} + +// VoidedAtNotNil applies the NotNil predicate on the "voided_at" field. +func VoidedAtNotNil() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.FieldNotNull(FieldVoidedAt)) +} + +// HasExternalPayment applies the HasEdge predicate on the "external_payment" edge. +func HasExternalPayment() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, ExternalPaymentTable, ExternalPaymentColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasExternalPaymentWith applies the HasEdge predicate on the "external_payment" edge with a given conditions (other predicates). +func HasExternalPaymentWith(preds ...predicate.ChargeCreditPurchaseExternalPayment) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(func(s *sql.Selector) { + step := newExternalPaymentStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasInvoicedPayment applies the HasEdge predicate on the "invoiced_payment" edge. +func HasInvoicedPayment() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, InvoicedPaymentTable, InvoicedPaymentColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasInvoicedPaymentWith applies the HasEdge predicate on the "invoiced_payment" edge with a given conditions (other predicates). +func HasInvoicedPaymentWith(preds ...predicate.ChargeCreditPurchaseInvoicedPayment) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(func(s *sql.Selector) { + step := newInvoicedPaymentStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasCreditGrant applies the HasEdge predicate on the "credit_grant" edge. +func HasCreditGrant() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, CreditGrantTable, CreditGrantColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCreditGrantWith applies the HasEdge predicate on the "credit_grant" edge with a given conditions (other predicates). +func HasCreditGrantWith(preds ...predicate.ChargeCreditPurchaseCreditGrant) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(func(s *sql.Selector) { + step := newCreditGrantStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasCharge applies the HasEdge predicate on the "charge" edge. +func HasCharge() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, 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.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(func(s *sql.Selector) { + step := newChargeStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSubscription applies the HasEdge predicate on the "subscription" edge. +func HasSubscription() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionTable, SubscriptionColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubscriptionWith applies the HasEdge predicate on the "subscription" edge with a given conditions (other predicates). +func HasSubscriptionWith(preds ...predicate.Subscription) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(func(s *sql.Selector) { + step := newSubscriptionStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSubscriptionPhase applies the HasEdge predicate on the "subscription_phase" edge. +func HasSubscriptionPhase() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionPhaseTable, SubscriptionPhaseColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubscriptionPhaseWith applies the HasEdge predicate on the "subscription_phase" edge with a given conditions (other predicates). +func HasSubscriptionPhaseWith(preds ...predicate.SubscriptionPhase) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(func(s *sql.Selector) { + step := newSubscriptionPhaseStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSubscriptionItem applies the HasEdge predicate on the "subscription_item" edge. +func HasSubscriptionItem() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionItemTable, SubscriptionItemColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubscriptionItemWith applies the HasEdge predicate on the "subscription_item" edge with a given conditions (other predicates). +func HasSubscriptionItemWith(preds ...predicate.SubscriptionItem) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(func(s *sql.Selector) { + step := newSubscriptionItemStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasCustomer applies the HasEdge predicate on the "customer" edge. +func HasCustomer() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, CustomerTable, CustomerColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCustomerWith applies the HasEdge predicate on the "customer" edge with a given conditions (other predicates). +func HasCustomerWith(preds ...predicate.Customer) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(func(s *sql.Selector) { + step := newCustomerStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasTaxCode applies the HasEdge predicate on the "tax_code" edge. +func HasTaxCode() predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, TaxCodeTable, TaxCodeColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTaxCodeWith applies the HasEdge predicate on the "tax_code" edge with a given conditions (other predicates). +func HasTaxCodeWith(preds ...predicate.TaxCode) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(func(s *sql.Selector) { + step := newTaxCodeStep() + 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.ChargeCreditPurchase) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ChargeCreditPurchase) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ChargeCreditPurchase) predicate.ChargeCreditPurchase { + return predicate.ChargeCreditPurchase(sql.NotPredicates(p)) +} diff --git a/ent/db/chargecreditpurchase_create.go b/ent/db/chargecreditpurchase_create.go new file mode 100644 index 0000000000000000000000000000000000000000..c09f51c503097b98e17d5b2ffcdb4c0b76b925b0 --- /dev/null +++ b/ent/db/chargecreditpurchase_create.go @@ -0,0 +1,2275 @@ +// 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/lib/pq" + "github.com/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/billing/charges/creditpurchase" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/ent/db/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchase" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchasecreditgrant" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchaseexternalpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchaseinvoicedpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/customer" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionphase" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeCreditPurchaseCreate is the builder for creating a ChargeCreditPurchase entity. +type ChargeCreditPurchaseCreate struct { + config + mutation *ChargeCreditPurchaseMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetCustomerID sets the "customer_id" field. +func (_c *ChargeCreditPurchaseCreate) SetCustomerID(v string) *ChargeCreditPurchaseCreate { + _c.mutation.SetCustomerID(v) + return _c +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_c *ChargeCreditPurchaseCreate) SetServicePeriodFrom(v time.Time) *ChargeCreditPurchaseCreate { + _c.mutation.SetServicePeriodFrom(v) + return _c +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_c *ChargeCreditPurchaseCreate) SetServicePeriodTo(v time.Time) *ChargeCreditPurchaseCreate { + _c.mutation.SetServicePeriodTo(v) + return _c +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (_c *ChargeCreditPurchaseCreate) SetBillingPeriodFrom(v time.Time) *ChargeCreditPurchaseCreate { + _c.mutation.SetBillingPeriodFrom(v) + return _c +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (_c *ChargeCreditPurchaseCreate) SetBillingPeriodTo(v time.Time) *ChargeCreditPurchaseCreate { + _c.mutation.SetBillingPeriodTo(v) + return _c +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (_c *ChargeCreditPurchaseCreate) SetFullServicePeriodFrom(v time.Time) *ChargeCreditPurchaseCreate { + _c.mutation.SetFullServicePeriodFrom(v) + return _c +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (_c *ChargeCreditPurchaseCreate) SetFullServicePeriodTo(v time.Time) *ChargeCreditPurchaseCreate { + _c.mutation.SetFullServicePeriodTo(v) + return _c +} + +// SetStatus sets the "status" field. +func (_c *ChargeCreditPurchaseCreate) SetStatus(v meta.ChargeStatus) *ChargeCreditPurchaseCreate { + _c.mutation.SetStatus(v) + return _c +} + +// SetUniqueReferenceID sets the "unique_reference_id" field. +func (_c *ChargeCreditPurchaseCreate) SetUniqueReferenceID(v string) *ChargeCreditPurchaseCreate { + _c.mutation.SetUniqueReferenceID(v) + return _c +} + +// SetNillableUniqueReferenceID sets the "unique_reference_id" field if the given value is not nil. +func (_c *ChargeCreditPurchaseCreate) SetNillableUniqueReferenceID(v *string) *ChargeCreditPurchaseCreate { + if v != nil { + _c.SetUniqueReferenceID(*v) + } + return _c +} + +// SetCurrency sets the "currency" field. +func (_c *ChargeCreditPurchaseCreate) SetCurrency(v currencyx.Code) *ChargeCreditPurchaseCreate { + _c.mutation.SetCurrency(v) + return _c +} + +// SetManagedBy sets the "managed_by" field. +func (_c *ChargeCreditPurchaseCreate) SetManagedBy(v billing.InvoiceLineManagedBy) *ChargeCreditPurchaseCreate { + _c.mutation.SetManagedBy(v) + return _c +} + +// SetSubscriptionID sets the "subscription_id" field. +func (_c *ChargeCreditPurchaseCreate) SetSubscriptionID(v string) *ChargeCreditPurchaseCreate { + _c.mutation.SetSubscriptionID(v) + return _c +} + +// SetNillableSubscriptionID sets the "subscription_id" field if the given value is not nil. +func (_c *ChargeCreditPurchaseCreate) SetNillableSubscriptionID(v *string) *ChargeCreditPurchaseCreate { + if v != nil { + _c.SetSubscriptionID(*v) + } + return _c +} + +// SetSubscriptionPhaseID sets the "subscription_phase_id" field. +func (_c *ChargeCreditPurchaseCreate) SetSubscriptionPhaseID(v string) *ChargeCreditPurchaseCreate { + _c.mutation.SetSubscriptionPhaseID(v) + return _c +} + +// SetNillableSubscriptionPhaseID sets the "subscription_phase_id" field if the given value is not nil. +func (_c *ChargeCreditPurchaseCreate) SetNillableSubscriptionPhaseID(v *string) *ChargeCreditPurchaseCreate { + if v != nil { + _c.SetSubscriptionPhaseID(*v) + } + return _c +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (_c *ChargeCreditPurchaseCreate) SetSubscriptionItemID(v string) *ChargeCreditPurchaseCreate { + _c.mutation.SetSubscriptionItemID(v) + return _c +} + +// SetNillableSubscriptionItemID sets the "subscription_item_id" field if the given value is not nil. +func (_c *ChargeCreditPurchaseCreate) SetNillableSubscriptionItemID(v *string) *ChargeCreditPurchaseCreate { + if v != nil { + _c.SetSubscriptionItemID(*v) + } + return _c +} + +// SetAdvanceAfter sets the "advance_after" field. +func (_c *ChargeCreditPurchaseCreate) SetAdvanceAfter(v time.Time) *ChargeCreditPurchaseCreate { + _c.mutation.SetAdvanceAfter(v) + return _c +} + +// SetNillableAdvanceAfter sets the "advance_after" field if the given value is not nil. +func (_c *ChargeCreditPurchaseCreate) SetNillableAdvanceAfter(v *time.Time) *ChargeCreditPurchaseCreate { + if v != nil { + _c.SetAdvanceAfter(*v) + } + return _c +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (_c *ChargeCreditPurchaseCreate) SetTaxCodeID(v string) *ChargeCreditPurchaseCreate { + _c.mutation.SetTaxCodeID(v) + return _c +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (_c *ChargeCreditPurchaseCreate) SetTaxBehavior(v productcatalog.TaxBehavior) *ChargeCreditPurchaseCreate { + _c.mutation.SetTaxBehavior(v) + return _c +} + +// SetNillableTaxBehavior sets the "tax_behavior" field if the given value is not nil. +func (_c *ChargeCreditPurchaseCreate) SetNillableTaxBehavior(v *productcatalog.TaxBehavior) *ChargeCreditPurchaseCreate { + if v != nil { + _c.SetTaxBehavior(*v) + } + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *ChargeCreditPurchaseCreate) SetAnnotations(v models.Annotations) *ChargeCreditPurchaseCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetNamespace sets the "namespace" field. +func (_c *ChargeCreditPurchaseCreate) SetNamespace(v string) *ChargeCreditPurchaseCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetMetadata sets the "metadata" field. +func (_c *ChargeCreditPurchaseCreate) SetMetadata(v map[string]string) *ChargeCreditPurchaseCreate { + _c.mutation.SetMetadata(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ChargeCreditPurchaseCreate) SetCreatedAt(v time.Time) *ChargeCreditPurchaseCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *ChargeCreditPurchaseCreate) SetNillableCreatedAt(v *time.Time) *ChargeCreditPurchaseCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *ChargeCreditPurchaseCreate) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *ChargeCreditPurchaseCreate) SetNillableUpdatedAt(v *time.Time) *ChargeCreditPurchaseCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *ChargeCreditPurchaseCreate) SetDeletedAt(v time.Time) *ChargeCreditPurchaseCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *ChargeCreditPurchaseCreate) SetNillableDeletedAt(v *time.Time) *ChargeCreditPurchaseCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetName sets the "name" field. +func (_c *ChargeCreditPurchaseCreate) SetName(v string) *ChargeCreditPurchaseCreate { + _c.mutation.SetName(v) + return _c +} + +// SetDescription sets the "description" field. +func (_c *ChargeCreditPurchaseCreate) SetDescription(v string) *ChargeCreditPurchaseCreate { + _c.mutation.SetDescription(v) + return _c +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_c *ChargeCreditPurchaseCreate) SetNillableDescription(v *string) *ChargeCreditPurchaseCreate { + if v != nil { + _c.SetDescription(*v) + } + return _c +} + +// SetCreditAmount sets the "credit_amount" field. +func (_c *ChargeCreditPurchaseCreate) SetCreditAmount(v alpacadecimal.Decimal) *ChargeCreditPurchaseCreate { + _c.mutation.SetCreditAmount(v) + return _c +} + +// SetEffectiveAt sets the "effective_at" field. +func (_c *ChargeCreditPurchaseCreate) SetEffectiveAt(v time.Time) *ChargeCreditPurchaseCreate { + _c.mutation.SetEffectiveAt(v) + return _c +} + +// SetNillableEffectiveAt sets the "effective_at" field if the given value is not nil. +func (_c *ChargeCreditPurchaseCreate) SetNillableEffectiveAt(v *time.Time) *ChargeCreditPurchaseCreate { + if v != nil { + _c.SetEffectiveAt(*v) + } + return _c +} + +// SetExpiresAt sets the "expires_at" field. +func (_c *ChargeCreditPurchaseCreate) SetExpiresAt(v time.Time) *ChargeCreditPurchaseCreate { + _c.mutation.SetExpiresAt(v) + return _c +} + +// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil. +func (_c *ChargeCreditPurchaseCreate) SetNillableExpiresAt(v *time.Time) *ChargeCreditPurchaseCreate { + if v != nil { + _c.SetExpiresAt(*v) + } + return _c +} + +// SetPriority sets the "priority" field. +func (_c *ChargeCreditPurchaseCreate) SetPriority(v int) *ChargeCreditPurchaseCreate { + _c.mutation.SetPriority(v) + return _c +} + +// SetNillablePriority sets the "priority" field if the given value is not nil. +func (_c *ChargeCreditPurchaseCreate) SetNillablePriority(v *int) *ChargeCreditPurchaseCreate { + if v != nil { + _c.SetPriority(*v) + } + return _c +} + +// SetFeatureFilters sets the "feature_filters" field. +func (_c *ChargeCreditPurchaseCreate) SetFeatureFilters(v pq.StringArray) *ChargeCreditPurchaseCreate { + _c.mutation.SetFeatureFilters(v) + return _c +} + +// SetSettlement sets the "settlement" field. +func (_c *ChargeCreditPurchaseCreate) SetSettlement(v creditpurchase.Settlement) *ChargeCreditPurchaseCreate { + _c.mutation.SetSettlement(v) + return _c +} + +// SetStatusDetailed sets the "status_detailed" field. +func (_c *ChargeCreditPurchaseCreate) SetStatusDetailed(v creditpurchase.Status) *ChargeCreditPurchaseCreate { + _c.mutation.SetStatusDetailed(v) + return _c +} + +// SetKey sets the "key" field. +func (_c *ChargeCreditPurchaseCreate) SetKey(v string) *ChargeCreditPurchaseCreate { + _c.mutation.SetKey(v) + return _c +} + +// SetNillableKey sets the "key" field if the given value is not nil. +func (_c *ChargeCreditPurchaseCreate) SetNillableKey(v *string) *ChargeCreditPurchaseCreate { + if v != nil { + _c.SetKey(*v) + } + return _c +} + +// SetVoidedAt sets the "voided_at" field. +func (_c *ChargeCreditPurchaseCreate) SetVoidedAt(v time.Time) *ChargeCreditPurchaseCreate { + _c.mutation.SetVoidedAt(v) + return _c +} + +// SetNillableVoidedAt sets the "voided_at" field if the given value is not nil. +func (_c *ChargeCreditPurchaseCreate) SetNillableVoidedAt(v *time.Time) *ChargeCreditPurchaseCreate { + if v != nil { + _c.SetVoidedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *ChargeCreditPurchaseCreate) SetID(v string) *ChargeCreditPurchaseCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ChargeCreditPurchaseCreate) SetNillableID(v *string) *ChargeCreditPurchaseCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetExternalPaymentID sets the "external_payment" edge to the ChargeCreditPurchaseExternalPayment entity by ID. +func (_c *ChargeCreditPurchaseCreate) SetExternalPaymentID(id string) *ChargeCreditPurchaseCreate { + _c.mutation.SetExternalPaymentID(id) + return _c +} + +// SetNillableExternalPaymentID sets the "external_payment" edge to the ChargeCreditPurchaseExternalPayment entity by ID if the given value is not nil. +func (_c *ChargeCreditPurchaseCreate) SetNillableExternalPaymentID(id *string) *ChargeCreditPurchaseCreate { + if id != nil { + _c = _c.SetExternalPaymentID(*id) + } + return _c +} + +// SetExternalPayment sets the "external_payment" edge to the ChargeCreditPurchaseExternalPayment entity. +func (_c *ChargeCreditPurchaseCreate) SetExternalPayment(v *ChargeCreditPurchaseExternalPayment) *ChargeCreditPurchaseCreate { + return _c.SetExternalPaymentID(v.ID) +} + +// SetInvoicedPaymentID sets the "invoiced_payment" edge to the ChargeCreditPurchaseInvoicedPayment entity by ID. +func (_c *ChargeCreditPurchaseCreate) SetInvoicedPaymentID(id string) *ChargeCreditPurchaseCreate { + _c.mutation.SetInvoicedPaymentID(id) + return _c +} + +// SetNillableInvoicedPaymentID sets the "invoiced_payment" edge to the ChargeCreditPurchaseInvoicedPayment entity by ID if the given value is not nil. +func (_c *ChargeCreditPurchaseCreate) SetNillableInvoicedPaymentID(id *string) *ChargeCreditPurchaseCreate { + if id != nil { + _c = _c.SetInvoicedPaymentID(*id) + } + return _c +} + +// SetInvoicedPayment sets the "invoiced_payment" edge to the ChargeCreditPurchaseInvoicedPayment entity. +func (_c *ChargeCreditPurchaseCreate) SetInvoicedPayment(v *ChargeCreditPurchaseInvoicedPayment) *ChargeCreditPurchaseCreate { + return _c.SetInvoicedPaymentID(v.ID) +} + +// SetCreditGrantID sets the "credit_grant" edge to the ChargeCreditPurchaseCreditGrant entity by ID. +func (_c *ChargeCreditPurchaseCreate) SetCreditGrantID(id string) *ChargeCreditPurchaseCreate { + _c.mutation.SetCreditGrantID(id) + return _c +} + +// SetNillableCreditGrantID sets the "credit_grant" edge to the ChargeCreditPurchaseCreditGrant entity by ID if the given value is not nil. +func (_c *ChargeCreditPurchaseCreate) SetNillableCreditGrantID(id *string) *ChargeCreditPurchaseCreate { + if id != nil { + _c = _c.SetCreditGrantID(*id) + } + return _c +} + +// SetCreditGrant sets the "credit_grant" edge to the ChargeCreditPurchaseCreditGrant entity. +func (_c *ChargeCreditPurchaseCreate) SetCreditGrant(v *ChargeCreditPurchaseCreditGrant) *ChargeCreditPurchaseCreate { + return _c.SetCreditGrantID(v.ID) +} + +// SetChargeID sets the "charge" edge to the Charge entity by ID. +func (_c *ChargeCreditPurchaseCreate) SetChargeID(id string) *ChargeCreditPurchaseCreate { + _c.mutation.SetChargeID(id) + return _c +} + +// SetNillableChargeID sets the "charge" edge to the Charge entity by ID if the given value is not nil. +func (_c *ChargeCreditPurchaseCreate) SetNillableChargeID(id *string) *ChargeCreditPurchaseCreate { + if id != nil { + _c = _c.SetChargeID(*id) + } + return _c +} + +// SetCharge sets the "charge" edge to the Charge entity. +func (_c *ChargeCreditPurchaseCreate) SetCharge(v *Charge) *ChargeCreditPurchaseCreate { + return _c.SetChargeID(v.ID) +} + +// SetSubscription sets the "subscription" edge to the Subscription entity. +func (_c *ChargeCreditPurchaseCreate) SetSubscription(v *Subscription) *ChargeCreditPurchaseCreate { + return _c.SetSubscriptionID(v.ID) +} + +// SetSubscriptionPhase sets the "subscription_phase" edge to the SubscriptionPhase entity. +func (_c *ChargeCreditPurchaseCreate) SetSubscriptionPhase(v *SubscriptionPhase) *ChargeCreditPurchaseCreate { + return _c.SetSubscriptionPhaseID(v.ID) +} + +// SetSubscriptionItem sets the "subscription_item" edge to the SubscriptionItem entity. +func (_c *ChargeCreditPurchaseCreate) SetSubscriptionItem(v *SubscriptionItem) *ChargeCreditPurchaseCreate { + return _c.SetSubscriptionItemID(v.ID) +} + +// SetCustomer sets the "customer" edge to the Customer entity. +func (_c *ChargeCreditPurchaseCreate) SetCustomer(v *Customer) *ChargeCreditPurchaseCreate { + return _c.SetCustomerID(v.ID) +} + +// SetTaxCode sets the "tax_code" edge to the TaxCode entity. +func (_c *ChargeCreditPurchaseCreate) SetTaxCode(v *TaxCode) *ChargeCreditPurchaseCreate { + return _c.SetTaxCodeID(v.ID) +} + +// Mutation returns the ChargeCreditPurchaseMutation object of the builder. +func (_c *ChargeCreditPurchaseCreate) Mutation() *ChargeCreditPurchaseMutation { + return _c.mutation +} + +// Save creates the ChargeCreditPurchase in the database. +func (_c *ChargeCreditPurchaseCreate) Save(ctx context.Context) (*ChargeCreditPurchase, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ChargeCreditPurchaseCreate) SaveX(ctx context.Context) *ChargeCreditPurchase { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeCreditPurchaseCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeCreditPurchaseCreate) 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 *ChargeCreditPurchaseCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := chargecreditpurchase.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := chargecreditpurchase.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := chargecreditpurchase.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ChargeCreditPurchaseCreate) check() error { + if _, ok := _c.mutation.CustomerID(); !ok { + return &ValidationError{Name: "customer_id", err: errors.New(`db: missing required field "ChargeCreditPurchase.customer_id"`)} + } + if v, ok := _c.mutation.CustomerID(); ok { + if err := chargecreditpurchase.CustomerIDValidator(v); err != nil { + return &ValidationError{Name: "customer_id", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchase.customer_id": %w`, err)} + } + } + if _, ok := _c.mutation.ServicePeriodFrom(); !ok { + return &ValidationError{Name: "service_period_from", err: errors.New(`db: missing required field "ChargeCreditPurchase.service_period_from"`)} + } + if _, ok := _c.mutation.ServicePeriodTo(); !ok { + return &ValidationError{Name: "service_period_to", err: errors.New(`db: missing required field "ChargeCreditPurchase.service_period_to"`)} + } + if _, ok := _c.mutation.BillingPeriodFrom(); !ok { + return &ValidationError{Name: "billing_period_from", err: errors.New(`db: missing required field "ChargeCreditPurchase.billing_period_from"`)} + } + if _, ok := _c.mutation.BillingPeriodTo(); !ok { + return &ValidationError{Name: "billing_period_to", err: errors.New(`db: missing required field "ChargeCreditPurchase.billing_period_to"`)} + } + if _, ok := _c.mutation.FullServicePeriodFrom(); !ok { + return &ValidationError{Name: "full_service_period_from", err: errors.New(`db: missing required field "ChargeCreditPurchase.full_service_period_from"`)} + } + if _, ok := _c.mutation.FullServicePeriodTo(); !ok { + return &ValidationError{Name: "full_service_period_to", err: errors.New(`db: missing required field "ChargeCreditPurchase.full_service_period_to"`)} + } + if _, ok := _c.mutation.Status(); !ok { + return &ValidationError{Name: "status", err: errors.New(`db: missing required field "ChargeCreditPurchase.status"`)} + } + if v, ok := _c.mutation.Status(); ok { + if err := chargecreditpurchase.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchase.status": %w`, err)} + } + } + if _, ok := _c.mutation.Currency(); !ok { + return &ValidationError{Name: "currency", err: errors.New(`db: missing required field "ChargeCreditPurchase.currency"`)} + } + if v, ok := _c.mutation.Currency(); ok { + if err := chargecreditpurchase.CurrencyValidator(string(v)); err != nil { + return &ValidationError{Name: "currency", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchase.currency": %w`, err)} + } + } + if _, ok := _c.mutation.ManagedBy(); !ok { + return &ValidationError{Name: "managed_by", err: errors.New(`db: missing required field "ChargeCreditPurchase.managed_by"`)} + } + if v, ok := _c.mutation.ManagedBy(); ok { + if err := chargecreditpurchase.ManagedByValidator(v); err != nil { + return &ValidationError{Name: "managed_by", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchase.managed_by": %w`, err)} + } + } + if _, ok := _c.mutation.TaxCodeID(); !ok { + return &ValidationError{Name: "tax_code_id", err: errors.New(`db: missing required field "ChargeCreditPurchase.tax_code_id"`)} + } + if v, ok := _c.mutation.TaxCodeID(); ok { + if err := chargecreditpurchase.TaxCodeIDValidator(v); err != nil { + return &ValidationError{Name: "tax_code_id", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchase.tax_code_id": %w`, err)} + } + } + if v, ok := _c.mutation.TaxBehavior(); ok { + if err := chargecreditpurchase.TaxBehaviorValidator(v); err != nil { + return &ValidationError{Name: "tax_behavior", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchase.tax_behavior": %w`, err)} + } + } + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "ChargeCreditPurchase.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := chargecreditpurchase.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchase.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "ChargeCreditPurchase.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "ChargeCreditPurchase.updated_at"`)} + } + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "ChargeCreditPurchase.name"`)} + } + if _, ok := _c.mutation.CreditAmount(); !ok { + return &ValidationError{Name: "credit_amount", err: errors.New(`db: missing required field "ChargeCreditPurchase.credit_amount"`)} + } + if _, ok := _c.mutation.Settlement(); !ok { + return &ValidationError{Name: "settlement", err: errors.New(`db: missing required field "ChargeCreditPurchase.settlement"`)} + } + if v, ok := _c.mutation.Settlement(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "settlement", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchase.settlement": %w`, err)} + } + } + if _, ok := _c.mutation.StatusDetailed(); !ok { + return &ValidationError{Name: "status_detailed", err: errors.New(`db: missing required field "ChargeCreditPurchase.status_detailed"`)} + } + if v, ok := _c.mutation.StatusDetailed(); ok { + if err := chargecreditpurchase.StatusDetailedValidator(v); err != nil { + return &ValidationError{Name: "status_detailed", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchase.status_detailed": %w`, err)} + } + } + if len(_c.mutation.CustomerIDs()) == 0 { + return &ValidationError{Name: "customer", err: errors.New(`db: missing required edge "ChargeCreditPurchase.customer"`)} + } + if len(_c.mutation.TaxCodeIDs()) == 0 { + return &ValidationError{Name: "tax_code", err: errors.New(`db: missing required edge "ChargeCreditPurchase.tax_code"`)} + } + return nil +} + +func (_c *ChargeCreditPurchaseCreate) sqlSave(ctx context.Context) (*ChargeCreditPurchase, 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 ChargeCreditPurchase.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ChargeCreditPurchaseCreate) createSpec() (*ChargeCreditPurchase, *sqlgraph.CreateSpec, error) { + var ( + _node = &ChargeCreditPurchase{config: _c.config} + _spec = sqlgraph.NewCreateSpec(chargecreditpurchase.Table, sqlgraph.NewFieldSpec(chargecreditpurchase.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.ServicePeriodFrom(); ok { + _spec.SetField(chargecreditpurchase.FieldServicePeriodFrom, field.TypeTime, value) + _node.ServicePeriodFrom = value + } + if value, ok := _c.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargecreditpurchase.FieldServicePeriodTo, field.TypeTime, value) + _node.ServicePeriodTo = value + } + if value, ok := _c.mutation.BillingPeriodFrom(); ok { + _spec.SetField(chargecreditpurchase.FieldBillingPeriodFrom, field.TypeTime, value) + _node.BillingPeriodFrom = value + } + if value, ok := _c.mutation.BillingPeriodTo(); ok { + _spec.SetField(chargecreditpurchase.FieldBillingPeriodTo, field.TypeTime, value) + _node.BillingPeriodTo = value + } + if value, ok := _c.mutation.FullServicePeriodFrom(); ok { + _spec.SetField(chargecreditpurchase.FieldFullServicePeriodFrom, field.TypeTime, value) + _node.FullServicePeriodFrom = value + } + if value, ok := _c.mutation.FullServicePeriodTo(); ok { + _spec.SetField(chargecreditpurchase.FieldFullServicePeriodTo, field.TypeTime, value) + _node.FullServicePeriodTo = value + } + if value, ok := _c.mutation.Status(); ok { + _spec.SetField(chargecreditpurchase.FieldStatus, field.TypeEnum, value) + _node.Status = value + } + if value, ok := _c.mutation.UniqueReferenceID(); ok { + _spec.SetField(chargecreditpurchase.FieldUniqueReferenceID, field.TypeString, value) + _node.UniqueReferenceID = &value + } + if value, ok := _c.mutation.Currency(); ok { + _spec.SetField(chargecreditpurchase.FieldCurrency, field.TypeString, value) + _node.Currency = value + } + if value, ok := _c.mutation.ManagedBy(); ok { + _spec.SetField(chargecreditpurchase.FieldManagedBy, field.TypeEnum, value) + _node.ManagedBy = value + } + if value, ok := _c.mutation.AdvanceAfter(); ok { + _spec.SetField(chargecreditpurchase.FieldAdvanceAfter, field.TypeTime, value) + _node.AdvanceAfter = &value + } + if value, ok := _c.mutation.TaxBehavior(); ok { + _spec.SetField(chargecreditpurchase.FieldTaxBehavior, field.TypeEnum, value) + _node.TaxBehavior = &value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(chargecreditpurchase.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(chargecreditpurchase.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Metadata(); ok { + _spec.SetField(chargecreditpurchase.FieldMetadata, field.TypeJSON, value) + _node.Metadata = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(chargecreditpurchase.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(chargecreditpurchase.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(chargecreditpurchase.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(chargecreditpurchase.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Description(); ok { + _spec.SetField(chargecreditpurchase.FieldDescription, field.TypeString, value) + _node.Description = &value + } + if value, ok := _c.mutation.CreditAmount(); ok { + _spec.SetField(chargecreditpurchase.FieldCreditAmount, field.TypeOther, value) + _node.CreditAmount = value + } + if value, ok := _c.mutation.EffectiveAt(); ok { + _spec.SetField(chargecreditpurchase.FieldEffectiveAt, field.TypeTime, value) + _node.EffectiveAt = &value + } + if value, ok := _c.mutation.ExpiresAt(); ok { + _spec.SetField(chargecreditpurchase.FieldExpiresAt, field.TypeTime, value) + _node.ExpiresAt = &value + } + if value, ok := _c.mutation.Priority(); ok { + _spec.SetField(chargecreditpurchase.FieldPriority, field.TypeInt, value) + _node.Priority = &value + } + if value, ok := _c.mutation.FeatureFilters(); ok { + _spec.SetField(chargecreditpurchase.FieldFeatureFilters, field.TypeOther, value) + _node.FeatureFilters = value + } + if value, ok := _c.mutation.Settlement(); ok { + vv, err := chargecreditpurchase.ValueScanner.Settlement.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(chargecreditpurchase.FieldSettlement, field.TypeString, vv) + _node.Settlement = value + } + if value, ok := _c.mutation.StatusDetailed(); ok { + _spec.SetField(chargecreditpurchase.FieldStatusDetailed, field.TypeEnum, value) + _node.StatusDetailed = value + } + if value, ok := _c.mutation.Key(); ok { + _spec.SetField(chargecreditpurchase.FieldKey, field.TypeString, value) + _node.Key = &value + } + if value, ok := _c.mutation.VoidedAt(); ok { + _spec.SetField(chargecreditpurchase.FieldVoidedAt, field.TypeTime, value) + _node.VoidedAt = &value + } + if nodes := _c.mutation.ExternalPaymentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargecreditpurchase.ExternalPaymentTable, + Columns: []string{chargecreditpurchase.ExternalPaymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchaseexternalpayment.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.InvoicedPaymentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargecreditpurchase.InvoicedPaymentTable, + Columns: []string{chargecreditpurchase.InvoicedPaymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchaseinvoicedpayment.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.CreditGrantIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargecreditpurchase.CreditGrantTable, + Columns: []string{chargecreditpurchase.CreditGrantColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchasecreditgrant.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.ChargeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargecreditpurchase.ChargeTable, + Columns: []string{chargecreditpurchase.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 = append(_spec.Edges, edge) + } + if nodes := _c.mutation.SubscriptionIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargecreditpurchase.SubscriptionTable, + Columns: []string{chargecreditpurchase.SubscriptionColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscription.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.SubscriptionID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.SubscriptionPhaseIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargecreditpurchase.SubscriptionPhaseTable, + Columns: []string{chargecreditpurchase.SubscriptionPhaseColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionphase.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.SubscriptionPhaseID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.SubscriptionItemIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargecreditpurchase.SubscriptionItemTable, + Columns: []string{chargecreditpurchase.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.SubscriptionItemID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.CustomerIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargecreditpurchase.CustomerTable, + Columns: []string{chargecreditpurchase.CustomerColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(customer.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.CustomerID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.TaxCodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargecreditpurchase.TaxCodeTable, + Columns: []string{chargecreditpurchase.TaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.TaxCodeID = nodes[0] + _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.ChargeCreditPurchase.Create(). +// SetCustomerID(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.ChargeCreditPurchaseUpsert) { +// SetCustomerID(v+v). +// }). +// Exec(ctx) +func (_c *ChargeCreditPurchaseCreate) OnConflict(opts ...sql.ConflictOption) *ChargeCreditPurchaseUpsertOne { + _c.conflict = opts + return &ChargeCreditPurchaseUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeCreditPurchase.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeCreditPurchaseCreate) OnConflictColumns(columns ...string) *ChargeCreditPurchaseUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeCreditPurchaseUpsertOne{ + create: _c, + } +} + +type ( + // ChargeCreditPurchaseUpsertOne is the builder for "upsert"-ing + // one ChargeCreditPurchase node. + ChargeCreditPurchaseUpsertOne struct { + create *ChargeCreditPurchaseCreate + } + + // ChargeCreditPurchaseUpsert is the "OnConflict" setter. + ChargeCreditPurchaseUpsert struct { + *sql.UpdateSet + } +) + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeCreditPurchaseUpsert) SetServicePeriodFrom(v time.Time) *ChargeCreditPurchaseUpsert { + u.Set(chargecreditpurchase.FieldServicePeriodFrom, v) + return u +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsert) UpdateServicePeriodFrom() *ChargeCreditPurchaseUpsert { + u.SetExcluded(chargecreditpurchase.FieldServicePeriodFrom) + return u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeCreditPurchaseUpsert) SetServicePeriodTo(v time.Time) *ChargeCreditPurchaseUpsert { + u.Set(chargecreditpurchase.FieldServicePeriodTo, v) + return u +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsert) UpdateServicePeriodTo() *ChargeCreditPurchaseUpsert { + u.SetExcluded(chargecreditpurchase.FieldServicePeriodTo) + return u +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (u *ChargeCreditPurchaseUpsert) SetBillingPeriodFrom(v time.Time) *ChargeCreditPurchaseUpsert { + u.Set(chargecreditpurchase.FieldBillingPeriodFrom, v) + return u +} + +// UpdateBillingPeriodFrom sets the "billing_period_from" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsert) UpdateBillingPeriodFrom() *ChargeCreditPurchaseUpsert { + u.SetExcluded(chargecreditpurchase.FieldBillingPeriodFrom) + return u +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (u *ChargeCreditPurchaseUpsert) SetBillingPeriodTo(v time.Time) *ChargeCreditPurchaseUpsert { + u.Set(chargecreditpurchase.FieldBillingPeriodTo, v) + return u +} + +// UpdateBillingPeriodTo sets the "billing_period_to" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsert) UpdateBillingPeriodTo() *ChargeCreditPurchaseUpsert { + u.SetExcluded(chargecreditpurchase.FieldBillingPeriodTo) + return u +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (u *ChargeCreditPurchaseUpsert) SetFullServicePeriodFrom(v time.Time) *ChargeCreditPurchaseUpsert { + u.Set(chargecreditpurchase.FieldFullServicePeriodFrom, v) + return u +} + +// UpdateFullServicePeriodFrom sets the "full_service_period_from" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsert) UpdateFullServicePeriodFrom() *ChargeCreditPurchaseUpsert { + u.SetExcluded(chargecreditpurchase.FieldFullServicePeriodFrom) + return u +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (u *ChargeCreditPurchaseUpsert) SetFullServicePeriodTo(v time.Time) *ChargeCreditPurchaseUpsert { + u.Set(chargecreditpurchase.FieldFullServicePeriodTo, v) + return u +} + +// UpdateFullServicePeriodTo sets the "full_service_period_to" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsert) UpdateFullServicePeriodTo() *ChargeCreditPurchaseUpsert { + u.SetExcluded(chargecreditpurchase.FieldFullServicePeriodTo) + return u +} + +// SetStatus sets the "status" field. +func (u *ChargeCreditPurchaseUpsert) SetStatus(v meta.ChargeStatus) *ChargeCreditPurchaseUpsert { + u.Set(chargecreditpurchase.FieldStatus, v) + return u +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsert) UpdateStatus() *ChargeCreditPurchaseUpsert { + u.SetExcluded(chargecreditpurchase.FieldStatus) + return u +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (u *ChargeCreditPurchaseUpsert) SetSubscriptionItemID(v string) *ChargeCreditPurchaseUpsert { + u.Set(chargecreditpurchase.FieldSubscriptionItemID, v) + return u +} + +// UpdateSubscriptionItemID sets the "subscription_item_id" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsert) UpdateSubscriptionItemID() *ChargeCreditPurchaseUpsert { + u.SetExcluded(chargecreditpurchase.FieldSubscriptionItemID) + return u +} + +// ClearSubscriptionItemID clears the value of the "subscription_item_id" field. +func (u *ChargeCreditPurchaseUpsert) ClearSubscriptionItemID() *ChargeCreditPurchaseUpsert { + u.SetNull(chargecreditpurchase.FieldSubscriptionItemID) + return u +} + +// SetAdvanceAfter sets the "advance_after" field. +func (u *ChargeCreditPurchaseUpsert) SetAdvanceAfter(v time.Time) *ChargeCreditPurchaseUpsert { + u.Set(chargecreditpurchase.FieldAdvanceAfter, v) + return u +} + +// UpdateAdvanceAfter sets the "advance_after" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsert) UpdateAdvanceAfter() *ChargeCreditPurchaseUpsert { + u.SetExcluded(chargecreditpurchase.FieldAdvanceAfter) + return u +} + +// ClearAdvanceAfter clears the value of the "advance_after" field. +func (u *ChargeCreditPurchaseUpsert) ClearAdvanceAfter() *ChargeCreditPurchaseUpsert { + u.SetNull(chargecreditpurchase.FieldAdvanceAfter) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeCreditPurchaseUpsert) SetAnnotations(v models.Annotations) *ChargeCreditPurchaseUpsert { + u.Set(chargecreditpurchase.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsert) UpdateAnnotations() *ChargeCreditPurchaseUpsert { + u.SetExcluded(chargecreditpurchase.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeCreditPurchaseUpsert) ClearAnnotations() *ChargeCreditPurchaseUpsert { + u.SetNull(chargecreditpurchase.FieldAnnotations) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeCreditPurchaseUpsert) SetMetadata(v map[string]string) *ChargeCreditPurchaseUpsert { + u.Set(chargecreditpurchase.FieldMetadata, v) + return u +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsert) UpdateMetadata() *ChargeCreditPurchaseUpsert { + u.SetExcluded(chargecreditpurchase.FieldMetadata) + return u +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeCreditPurchaseUpsert) ClearMetadata() *ChargeCreditPurchaseUpsert { + u.SetNull(chargecreditpurchase.FieldMetadata) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeCreditPurchaseUpsert) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseUpsert { + u.Set(chargecreditpurchase.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsert) UpdateUpdatedAt() *ChargeCreditPurchaseUpsert { + u.SetExcluded(chargecreditpurchase.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeCreditPurchaseUpsert) SetDeletedAt(v time.Time) *ChargeCreditPurchaseUpsert { + u.Set(chargecreditpurchase.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsert) UpdateDeletedAt() *ChargeCreditPurchaseUpsert { + u.SetExcluded(chargecreditpurchase.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeCreditPurchaseUpsert) ClearDeletedAt() *ChargeCreditPurchaseUpsert { + u.SetNull(chargecreditpurchase.FieldDeletedAt) + return u +} + +// SetName sets the "name" field. +func (u *ChargeCreditPurchaseUpsert) SetName(v string) *ChargeCreditPurchaseUpsert { + u.Set(chargecreditpurchase.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsert) UpdateName() *ChargeCreditPurchaseUpsert { + u.SetExcluded(chargecreditpurchase.FieldName) + return u +} + +// SetDescription sets the "description" field. +func (u *ChargeCreditPurchaseUpsert) SetDescription(v string) *ChargeCreditPurchaseUpsert { + u.Set(chargecreditpurchase.FieldDescription, v) + return u +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsert) UpdateDescription() *ChargeCreditPurchaseUpsert { + u.SetExcluded(chargecreditpurchase.FieldDescription) + return u +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeCreditPurchaseUpsert) ClearDescription() *ChargeCreditPurchaseUpsert { + u.SetNull(chargecreditpurchase.FieldDescription) + return u +} + +// SetCreditAmount sets the "credit_amount" field. +func (u *ChargeCreditPurchaseUpsert) SetCreditAmount(v alpacadecimal.Decimal) *ChargeCreditPurchaseUpsert { + u.Set(chargecreditpurchase.FieldCreditAmount, v) + return u +} + +// UpdateCreditAmount sets the "credit_amount" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsert) UpdateCreditAmount() *ChargeCreditPurchaseUpsert { + u.SetExcluded(chargecreditpurchase.FieldCreditAmount) + return u +} + +// SetSettlement sets the "settlement" field. +func (u *ChargeCreditPurchaseUpsert) SetSettlement(v creditpurchase.Settlement) *ChargeCreditPurchaseUpsert { + u.Set(chargecreditpurchase.FieldSettlement, v) + return u +} + +// UpdateSettlement sets the "settlement" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsert) UpdateSettlement() *ChargeCreditPurchaseUpsert { + u.SetExcluded(chargecreditpurchase.FieldSettlement) + return u +} + +// SetStatusDetailed sets the "status_detailed" field. +func (u *ChargeCreditPurchaseUpsert) SetStatusDetailed(v creditpurchase.Status) *ChargeCreditPurchaseUpsert { + u.Set(chargecreditpurchase.FieldStatusDetailed, v) + return u +} + +// UpdateStatusDetailed sets the "status_detailed" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsert) UpdateStatusDetailed() *ChargeCreditPurchaseUpsert { + u.SetExcluded(chargecreditpurchase.FieldStatusDetailed) + return u +} + +// SetVoidedAt sets the "voided_at" field. +func (u *ChargeCreditPurchaseUpsert) SetVoidedAt(v time.Time) *ChargeCreditPurchaseUpsert { + u.Set(chargecreditpurchase.FieldVoidedAt, v) + return u +} + +// UpdateVoidedAt sets the "voided_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsert) UpdateVoidedAt() *ChargeCreditPurchaseUpsert { + u.SetExcluded(chargecreditpurchase.FieldVoidedAt) + return u +} + +// ClearVoidedAt clears the value of the "voided_at" field. +func (u *ChargeCreditPurchaseUpsert) ClearVoidedAt() *ChargeCreditPurchaseUpsert { + u.SetNull(chargecreditpurchase.FieldVoidedAt) + 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.ChargeCreditPurchase.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargecreditpurchase.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeCreditPurchaseUpsertOne) UpdateNewValues() *ChargeCreditPurchaseUpsertOne { + 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(chargecreditpurchase.FieldID) + } + if _, exists := u.create.mutation.CustomerID(); exists { + s.SetIgnore(chargecreditpurchase.FieldCustomerID) + } + if _, exists := u.create.mutation.UniqueReferenceID(); exists { + s.SetIgnore(chargecreditpurchase.FieldUniqueReferenceID) + } + if _, exists := u.create.mutation.Currency(); exists { + s.SetIgnore(chargecreditpurchase.FieldCurrency) + } + if _, exists := u.create.mutation.ManagedBy(); exists { + s.SetIgnore(chargecreditpurchase.FieldManagedBy) + } + if _, exists := u.create.mutation.SubscriptionID(); exists { + s.SetIgnore(chargecreditpurchase.FieldSubscriptionID) + } + if _, exists := u.create.mutation.SubscriptionPhaseID(); exists { + s.SetIgnore(chargecreditpurchase.FieldSubscriptionPhaseID) + } + if _, exists := u.create.mutation.TaxCodeID(); exists { + s.SetIgnore(chargecreditpurchase.FieldTaxCodeID) + } + if _, exists := u.create.mutation.TaxBehavior(); exists { + s.SetIgnore(chargecreditpurchase.FieldTaxBehavior) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(chargecreditpurchase.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(chargecreditpurchase.FieldCreatedAt) + } + if _, exists := u.create.mutation.EffectiveAt(); exists { + s.SetIgnore(chargecreditpurchase.FieldEffectiveAt) + } + if _, exists := u.create.mutation.ExpiresAt(); exists { + s.SetIgnore(chargecreditpurchase.FieldExpiresAt) + } + if _, exists := u.create.mutation.Priority(); exists { + s.SetIgnore(chargecreditpurchase.FieldPriority) + } + if _, exists := u.create.mutation.FeatureFilters(); exists { + s.SetIgnore(chargecreditpurchase.FieldFeatureFilters) + } + if _, exists := u.create.mutation.Key(); exists { + s.SetIgnore(chargecreditpurchase.FieldKey) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeCreditPurchase.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeCreditPurchaseUpsertOne) Ignore() *ChargeCreditPurchaseUpsertOne { + 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 *ChargeCreditPurchaseUpsertOne) DoNothing() *ChargeCreditPurchaseUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeCreditPurchaseCreate.OnConflict +// documentation for more info. +func (u *ChargeCreditPurchaseUpsertOne) Update(set func(*ChargeCreditPurchaseUpsert)) *ChargeCreditPurchaseUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeCreditPurchaseUpsert{UpdateSet: update}) + })) + return u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeCreditPurchaseUpsertOne) SetServicePeriodFrom(v time.Time) *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertOne) UpdateServicePeriodFrom() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeCreditPurchaseUpsertOne) SetServicePeriodTo(v time.Time) *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertOne) UpdateServicePeriodTo() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (u *ChargeCreditPurchaseUpsertOne) SetBillingPeriodFrom(v time.Time) *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetBillingPeriodFrom(v) + }) +} + +// UpdateBillingPeriodFrom sets the "billing_period_from" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertOne) UpdateBillingPeriodFrom() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateBillingPeriodFrom() + }) +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (u *ChargeCreditPurchaseUpsertOne) SetBillingPeriodTo(v time.Time) *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetBillingPeriodTo(v) + }) +} + +// UpdateBillingPeriodTo sets the "billing_period_to" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertOne) UpdateBillingPeriodTo() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateBillingPeriodTo() + }) +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (u *ChargeCreditPurchaseUpsertOne) SetFullServicePeriodFrom(v time.Time) *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetFullServicePeriodFrom(v) + }) +} + +// UpdateFullServicePeriodFrom sets the "full_service_period_from" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertOne) UpdateFullServicePeriodFrom() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateFullServicePeriodFrom() + }) +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (u *ChargeCreditPurchaseUpsertOne) SetFullServicePeriodTo(v time.Time) *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetFullServicePeriodTo(v) + }) +} + +// UpdateFullServicePeriodTo sets the "full_service_period_to" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertOne) UpdateFullServicePeriodTo() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateFullServicePeriodTo() + }) +} + +// SetStatus sets the "status" field. +func (u *ChargeCreditPurchaseUpsertOne) SetStatus(v meta.ChargeStatus) *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertOne) UpdateStatus() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateStatus() + }) +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (u *ChargeCreditPurchaseUpsertOne) SetSubscriptionItemID(v string) *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetSubscriptionItemID(v) + }) +} + +// UpdateSubscriptionItemID sets the "subscription_item_id" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertOne) UpdateSubscriptionItemID() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateSubscriptionItemID() + }) +} + +// ClearSubscriptionItemID clears the value of the "subscription_item_id" field. +func (u *ChargeCreditPurchaseUpsertOne) ClearSubscriptionItemID() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.ClearSubscriptionItemID() + }) +} + +// SetAdvanceAfter sets the "advance_after" field. +func (u *ChargeCreditPurchaseUpsertOne) SetAdvanceAfter(v time.Time) *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetAdvanceAfter(v) + }) +} + +// UpdateAdvanceAfter sets the "advance_after" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertOne) UpdateAdvanceAfter() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateAdvanceAfter() + }) +} + +// ClearAdvanceAfter clears the value of the "advance_after" field. +func (u *ChargeCreditPurchaseUpsertOne) ClearAdvanceAfter() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.ClearAdvanceAfter() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeCreditPurchaseUpsertOne) SetAnnotations(v models.Annotations) *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertOne) UpdateAnnotations() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeCreditPurchaseUpsertOne) ClearAnnotations() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.ClearAnnotations() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeCreditPurchaseUpsertOne) SetMetadata(v map[string]string) *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertOne) UpdateMetadata() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeCreditPurchaseUpsertOne) ClearMetadata() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeCreditPurchaseUpsertOne) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertOne) UpdateUpdatedAt() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeCreditPurchaseUpsertOne) SetDeletedAt(v time.Time) *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertOne) UpdateDeletedAt() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeCreditPurchaseUpsertOne) ClearDeletedAt() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *ChargeCreditPurchaseUpsertOne) SetName(v string) *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertOne) UpdateName() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *ChargeCreditPurchaseUpsertOne) SetDescription(v string) *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertOne) UpdateDescription() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeCreditPurchaseUpsertOne) ClearDescription() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.ClearDescription() + }) +} + +// SetCreditAmount sets the "credit_amount" field. +func (u *ChargeCreditPurchaseUpsertOne) SetCreditAmount(v alpacadecimal.Decimal) *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetCreditAmount(v) + }) +} + +// UpdateCreditAmount sets the "credit_amount" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertOne) UpdateCreditAmount() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateCreditAmount() + }) +} + +// SetSettlement sets the "settlement" field. +func (u *ChargeCreditPurchaseUpsertOne) SetSettlement(v creditpurchase.Settlement) *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetSettlement(v) + }) +} + +// UpdateSettlement sets the "settlement" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertOne) UpdateSettlement() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateSettlement() + }) +} + +// SetStatusDetailed sets the "status_detailed" field. +func (u *ChargeCreditPurchaseUpsertOne) SetStatusDetailed(v creditpurchase.Status) *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetStatusDetailed(v) + }) +} + +// UpdateStatusDetailed sets the "status_detailed" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertOne) UpdateStatusDetailed() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateStatusDetailed() + }) +} + +// SetVoidedAt sets the "voided_at" field. +func (u *ChargeCreditPurchaseUpsertOne) SetVoidedAt(v time.Time) *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetVoidedAt(v) + }) +} + +// UpdateVoidedAt sets the "voided_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertOne) UpdateVoidedAt() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateVoidedAt() + }) +} + +// ClearVoidedAt clears the value of the "voided_at" field. +func (u *ChargeCreditPurchaseUpsertOne) ClearVoidedAt() *ChargeCreditPurchaseUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.ClearVoidedAt() + }) +} + +// Exec executes the query. +func (u *ChargeCreditPurchaseUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeCreditPurchaseCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeCreditPurchaseUpsertOne) 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 *ChargeCreditPurchaseUpsertOne) 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: ChargeCreditPurchaseUpsertOne.ID is not supported by MySQL driver. Use ChargeCreditPurchaseUpsertOne.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 *ChargeCreditPurchaseUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ChargeCreditPurchaseCreateBulk is the builder for creating many ChargeCreditPurchase entities in bulk. +type ChargeCreditPurchaseCreateBulk struct { + config + err error + builders []*ChargeCreditPurchaseCreate + conflict []sql.ConflictOption +} + +// Save creates the ChargeCreditPurchase entities in the database. +func (_c *ChargeCreditPurchaseCreateBulk) Save(ctx context.Context) ([]*ChargeCreditPurchase, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ChargeCreditPurchase, 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.(*ChargeCreditPurchaseMutation) + 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 *ChargeCreditPurchaseCreateBulk) SaveX(ctx context.Context) []*ChargeCreditPurchase { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeCreditPurchaseCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeCreditPurchaseCreateBulk) 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.ChargeCreditPurchase.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.ChargeCreditPurchaseUpsert) { +// SetCustomerID(v+v). +// }). +// Exec(ctx) +func (_c *ChargeCreditPurchaseCreateBulk) OnConflict(opts ...sql.ConflictOption) *ChargeCreditPurchaseUpsertBulk { + _c.conflict = opts + return &ChargeCreditPurchaseUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeCreditPurchase.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeCreditPurchaseCreateBulk) OnConflictColumns(columns ...string) *ChargeCreditPurchaseUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeCreditPurchaseUpsertBulk{ + create: _c, + } +} + +// ChargeCreditPurchaseUpsertBulk is the builder for "upsert"-ing +// a bulk of ChargeCreditPurchase nodes. +type ChargeCreditPurchaseUpsertBulk struct { + create *ChargeCreditPurchaseCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ChargeCreditPurchase.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargecreditpurchase.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeCreditPurchaseUpsertBulk) UpdateNewValues() *ChargeCreditPurchaseUpsertBulk { + 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(chargecreditpurchase.FieldID) + } + if _, exists := b.mutation.CustomerID(); exists { + s.SetIgnore(chargecreditpurchase.FieldCustomerID) + } + if _, exists := b.mutation.UniqueReferenceID(); exists { + s.SetIgnore(chargecreditpurchase.FieldUniqueReferenceID) + } + if _, exists := b.mutation.Currency(); exists { + s.SetIgnore(chargecreditpurchase.FieldCurrency) + } + if _, exists := b.mutation.ManagedBy(); exists { + s.SetIgnore(chargecreditpurchase.FieldManagedBy) + } + if _, exists := b.mutation.SubscriptionID(); exists { + s.SetIgnore(chargecreditpurchase.FieldSubscriptionID) + } + if _, exists := b.mutation.SubscriptionPhaseID(); exists { + s.SetIgnore(chargecreditpurchase.FieldSubscriptionPhaseID) + } + if _, exists := b.mutation.TaxCodeID(); exists { + s.SetIgnore(chargecreditpurchase.FieldTaxCodeID) + } + if _, exists := b.mutation.TaxBehavior(); exists { + s.SetIgnore(chargecreditpurchase.FieldTaxBehavior) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(chargecreditpurchase.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(chargecreditpurchase.FieldCreatedAt) + } + if _, exists := b.mutation.EffectiveAt(); exists { + s.SetIgnore(chargecreditpurchase.FieldEffectiveAt) + } + if _, exists := b.mutation.ExpiresAt(); exists { + s.SetIgnore(chargecreditpurchase.FieldExpiresAt) + } + if _, exists := b.mutation.Priority(); exists { + s.SetIgnore(chargecreditpurchase.FieldPriority) + } + if _, exists := b.mutation.FeatureFilters(); exists { + s.SetIgnore(chargecreditpurchase.FieldFeatureFilters) + } + if _, exists := b.mutation.Key(); exists { + s.SetIgnore(chargecreditpurchase.FieldKey) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeCreditPurchase.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeCreditPurchaseUpsertBulk) Ignore() *ChargeCreditPurchaseUpsertBulk { + 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 *ChargeCreditPurchaseUpsertBulk) DoNothing() *ChargeCreditPurchaseUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeCreditPurchaseCreateBulk.OnConflict +// documentation for more info. +func (u *ChargeCreditPurchaseUpsertBulk) Update(set func(*ChargeCreditPurchaseUpsert)) *ChargeCreditPurchaseUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeCreditPurchaseUpsert{UpdateSet: update}) + })) + return u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeCreditPurchaseUpsertBulk) SetServicePeriodFrom(v time.Time) *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertBulk) UpdateServicePeriodFrom() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeCreditPurchaseUpsertBulk) SetServicePeriodTo(v time.Time) *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertBulk) UpdateServicePeriodTo() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (u *ChargeCreditPurchaseUpsertBulk) SetBillingPeriodFrom(v time.Time) *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetBillingPeriodFrom(v) + }) +} + +// UpdateBillingPeriodFrom sets the "billing_period_from" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertBulk) UpdateBillingPeriodFrom() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateBillingPeriodFrom() + }) +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (u *ChargeCreditPurchaseUpsertBulk) SetBillingPeriodTo(v time.Time) *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetBillingPeriodTo(v) + }) +} + +// UpdateBillingPeriodTo sets the "billing_period_to" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertBulk) UpdateBillingPeriodTo() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateBillingPeriodTo() + }) +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (u *ChargeCreditPurchaseUpsertBulk) SetFullServicePeriodFrom(v time.Time) *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetFullServicePeriodFrom(v) + }) +} + +// UpdateFullServicePeriodFrom sets the "full_service_period_from" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertBulk) UpdateFullServicePeriodFrom() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateFullServicePeriodFrom() + }) +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (u *ChargeCreditPurchaseUpsertBulk) SetFullServicePeriodTo(v time.Time) *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetFullServicePeriodTo(v) + }) +} + +// UpdateFullServicePeriodTo sets the "full_service_period_to" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertBulk) UpdateFullServicePeriodTo() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateFullServicePeriodTo() + }) +} + +// SetStatus sets the "status" field. +func (u *ChargeCreditPurchaseUpsertBulk) SetStatus(v meta.ChargeStatus) *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertBulk) UpdateStatus() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateStatus() + }) +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (u *ChargeCreditPurchaseUpsertBulk) SetSubscriptionItemID(v string) *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetSubscriptionItemID(v) + }) +} + +// UpdateSubscriptionItemID sets the "subscription_item_id" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertBulk) UpdateSubscriptionItemID() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateSubscriptionItemID() + }) +} + +// ClearSubscriptionItemID clears the value of the "subscription_item_id" field. +func (u *ChargeCreditPurchaseUpsertBulk) ClearSubscriptionItemID() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.ClearSubscriptionItemID() + }) +} + +// SetAdvanceAfter sets the "advance_after" field. +func (u *ChargeCreditPurchaseUpsertBulk) SetAdvanceAfter(v time.Time) *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetAdvanceAfter(v) + }) +} + +// UpdateAdvanceAfter sets the "advance_after" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertBulk) UpdateAdvanceAfter() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateAdvanceAfter() + }) +} + +// ClearAdvanceAfter clears the value of the "advance_after" field. +func (u *ChargeCreditPurchaseUpsertBulk) ClearAdvanceAfter() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.ClearAdvanceAfter() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeCreditPurchaseUpsertBulk) SetAnnotations(v models.Annotations) *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertBulk) UpdateAnnotations() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeCreditPurchaseUpsertBulk) ClearAnnotations() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.ClearAnnotations() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeCreditPurchaseUpsertBulk) SetMetadata(v map[string]string) *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertBulk) UpdateMetadata() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeCreditPurchaseUpsertBulk) ClearMetadata() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeCreditPurchaseUpsertBulk) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertBulk) UpdateUpdatedAt() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeCreditPurchaseUpsertBulk) SetDeletedAt(v time.Time) *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertBulk) UpdateDeletedAt() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeCreditPurchaseUpsertBulk) ClearDeletedAt() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *ChargeCreditPurchaseUpsertBulk) SetName(v string) *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertBulk) UpdateName() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *ChargeCreditPurchaseUpsertBulk) SetDescription(v string) *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertBulk) UpdateDescription() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeCreditPurchaseUpsertBulk) ClearDescription() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.ClearDescription() + }) +} + +// SetCreditAmount sets the "credit_amount" field. +func (u *ChargeCreditPurchaseUpsertBulk) SetCreditAmount(v alpacadecimal.Decimal) *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetCreditAmount(v) + }) +} + +// UpdateCreditAmount sets the "credit_amount" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertBulk) UpdateCreditAmount() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateCreditAmount() + }) +} + +// SetSettlement sets the "settlement" field. +func (u *ChargeCreditPurchaseUpsertBulk) SetSettlement(v creditpurchase.Settlement) *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetSettlement(v) + }) +} + +// UpdateSettlement sets the "settlement" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertBulk) UpdateSettlement() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateSettlement() + }) +} + +// SetStatusDetailed sets the "status_detailed" field. +func (u *ChargeCreditPurchaseUpsertBulk) SetStatusDetailed(v creditpurchase.Status) *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetStatusDetailed(v) + }) +} + +// UpdateStatusDetailed sets the "status_detailed" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertBulk) UpdateStatusDetailed() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateStatusDetailed() + }) +} + +// SetVoidedAt sets the "voided_at" field. +func (u *ChargeCreditPurchaseUpsertBulk) SetVoidedAt(v time.Time) *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.SetVoidedAt(v) + }) +} + +// UpdateVoidedAt sets the "voided_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseUpsertBulk) UpdateVoidedAt() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.UpdateVoidedAt() + }) +} + +// ClearVoidedAt clears the value of the "voided_at" field. +func (u *ChargeCreditPurchaseUpsertBulk) ClearVoidedAt() *ChargeCreditPurchaseUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseUpsert) { + s.ClearVoidedAt() + }) +} + +// Exec executes the query. +func (u *ChargeCreditPurchaseUpsertBulk) 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 ChargeCreditPurchaseCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeCreditPurchaseCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeCreditPurchaseUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargecreditpurchase_delete.go b/ent/db/chargecreditpurchase_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..52660330ae224da839600162285bee22026481bf --- /dev/null +++ b/ent/db/chargecreditpurchase_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/chargecreditpurchase" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeCreditPurchaseDelete is the builder for deleting a ChargeCreditPurchase entity. +type ChargeCreditPurchaseDelete struct { + config + hooks []Hook + mutation *ChargeCreditPurchaseMutation +} + +// Where appends a list predicates to the ChargeCreditPurchaseDelete builder. +func (_d *ChargeCreditPurchaseDelete) Where(ps ...predicate.ChargeCreditPurchase) *ChargeCreditPurchaseDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ChargeCreditPurchaseDelete) 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 *ChargeCreditPurchaseDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ChargeCreditPurchaseDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(chargecreditpurchase.Table, sqlgraph.NewFieldSpec(chargecreditpurchase.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 +} + +// ChargeCreditPurchaseDeleteOne is the builder for deleting a single ChargeCreditPurchase entity. +type ChargeCreditPurchaseDeleteOne struct { + _d *ChargeCreditPurchaseDelete +} + +// Where appends a list predicates to the ChargeCreditPurchaseDelete builder. +func (_d *ChargeCreditPurchaseDeleteOne) Where(ps ...predicate.ChargeCreditPurchase) *ChargeCreditPurchaseDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ChargeCreditPurchaseDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{chargecreditpurchase.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeCreditPurchaseDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargecreditpurchase_query.go b/ent/db/chargecreditpurchase_query.go new file mode 100644 index 0000000000000000000000000000000000000000..1bdd028a251952ff9ab04a9f85ad5022dab3a4bf --- /dev/null +++ b/ent/db/chargecreditpurchase_query.go @@ -0,0 +1,1236 @@ +// 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/chargecreditpurchase" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchasecreditgrant" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchaseexternalpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchaseinvoicedpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/customer" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionphase" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" +) + +// ChargeCreditPurchaseQuery is the builder for querying ChargeCreditPurchase entities. +type ChargeCreditPurchaseQuery struct { + config + ctx *QueryContext + order []chargecreditpurchase.OrderOption + inters []Interceptor + predicates []predicate.ChargeCreditPurchase + withExternalPayment *ChargeCreditPurchaseExternalPaymentQuery + withInvoicedPayment *ChargeCreditPurchaseInvoicedPaymentQuery + withCreditGrant *ChargeCreditPurchaseCreditGrantQuery + withCharge *ChargeQuery + withSubscription *SubscriptionQuery + withSubscriptionPhase *SubscriptionPhaseQuery + withSubscriptionItem *SubscriptionItemQuery + withCustomer *CustomerQuery + withTaxCode *TaxCodeQuery + 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 ChargeCreditPurchaseQuery builder. +func (_q *ChargeCreditPurchaseQuery) Where(ps ...predicate.ChargeCreditPurchase) *ChargeCreditPurchaseQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ChargeCreditPurchaseQuery) Limit(limit int) *ChargeCreditPurchaseQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ChargeCreditPurchaseQuery) Offset(offset int) *ChargeCreditPurchaseQuery { + _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 *ChargeCreditPurchaseQuery) Unique(unique bool) *ChargeCreditPurchaseQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ChargeCreditPurchaseQuery) Order(o ...chargecreditpurchase.OrderOption) *ChargeCreditPurchaseQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryExternalPayment chains the current query on the "external_payment" edge. +func (_q *ChargeCreditPurchaseQuery) QueryExternalPayment() *ChargeCreditPurchaseExternalPaymentQuery { + query := (&ChargeCreditPurchaseExternalPaymentClient{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(chargecreditpurchase.Table, chargecreditpurchase.FieldID, selector), + sqlgraph.To(chargecreditpurchaseexternalpayment.Table, chargecreditpurchaseexternalpayment.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargecreditpurchase.ExternalPaymentTable, chargecreditpurchase.ExternalPaymentColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryInvoicedPayment chains the current query on the "invoiced_payment" edge. +func (_q *ChargeCreditPurchaseQuery) QueryInvoicedPayment() *ChargeCreditPurchaseInvoicedPaymentQuery { + query := (&ChargeCreditPurchaseInvoicedPaymentClient{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(chargecreditpurchase.Table, chargecreditpurchase.FieldID, selector), + sqlgraph.To(chargecreditpurchaseinvoicedpayment.Table, chargecreditpurchaseinvoicedpayment.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargecreditpurchase.InvoicedPaymentTable, chargecreditpurchase.InvoicedPaymentColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCreditGrant chains the current query on the "credit_grant" edge. +func (_q *ChargeCreditPurchaseQuery) QueryCreditGrant() *ChargeCreditPurchaseCreditGrantQuery { + query := (&ChargeCreditPurchaseCreditGrantClient{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(chargecreditpurchase.Table, chargecreditpurchase.FieldID, selector), + sqlgraph.To(chargecreditpurchasecreditgrant.Table, chargecreditpurchasecreditgrant.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargecreditpurchase.CreditGrantTable, chargecreditpurchase.CreditGrantColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCharge chains the current query on the "charge" edge. +func (_q *ChargeCreditPurchaseQuery) 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(chargecreditpurchase.Table, chargecreditpurchase.FieldID, selector), + sqlgraph.To(charge.Table, charge.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargecreditpurchase.ChargeTable, chargecreditpurchase.ChargeColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySubscription chains the current query on the "subscription" edge. +func (_q *ChargeCreditPurchaseQuery) QuerySubscription() *SubscriptionQuery { + query := (&SubscriptionClient{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(chargecreditpurchase.Table, chargecreditpurchase.FieldID, selector), + sqlgraph.To(subscription.Table, subscription.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargecreditpurchase.SubscriptionTable, chargecreditpurchase.SubscriptionColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySubscriptionPhase chains the current query on the "subscription_phase" edge. +func (_q *ChargeCreditPurchaseQuery) QuerySubscriptionPhase() *SubscriptionPhaseQuery { + query := (&SubscriptionPhaseClient{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(chargecreditpurchase.Table, chargecreditpurchase.FieldID, selector), + sqlgraph.To(subscriptionphase.Table, subscriptionphase.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargecreditpurchase.SubscriptionPhaseTable, chargecreditpurchase.SubscriptionPhaseColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySubscriptionItem chains the current query on the "subscription_item" edge. +func (_q *ChargeCreditPurchaseQuery) QuerySubscriptionItem() *SubscriptionItemQuery { + query := (&SubscriptionItemClient{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(chargecreditpurchase.Table, chargecreditpurchase.FieldID, selector), + sqlgraph.To(subscriptionitem.Table, subscriptionitem.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargecreditpurchase.SubscriptionItemTable, chargecreditpurchase.SubscriptionItemColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCustomer chains the current query on the "customer" edge. +func (_q *ChargeCreditPurchaseQuery) QueryCustomer() *CustomerQuery { + query := (&CustomerClient{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(chargecreditpurchase.Table, chargecreditpurchase.FieldID, selector), + sqlgraph.To(customer.Table, customer.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargecreditpurchase.CustomerTable, chargecreditpurchase.CustomerColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryTaxCode chains the current query on the "tax_code" edge. +func (_q *ChargeCreditPurchaseQuery) QueryTaxCode() *TaxCodeQuery { + query := (&TaxCodeClient{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(chargecreditpurchase.Table, chargecreditpurchase.FieldID, selector), + sqlgraph.To(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargecreditpurchase.TaxCodeTable, chargecreditpurchase.TaxCodeColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ChargeCreditPurchase entity from the query. +// Returns a *NotFoundError when no ChargeCreditPurchase was found. +func (_q *ChargeCreditPurchaseQuery) First(ctx context.Context) (*ChargeCreditPurchase, 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{chargecreditpurchase.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ChargeCreditPurchaseQuery) FirstX(ctx context.Context) *ChargeCreditPurchase { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ChargeCreditPurchase ID from the query. +// Returns a *NotFoundError when no ChargeCreditPurchase ID was found. +func (_q *ChargeCreditPurchaseQuery) 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{chargecreditpurchase.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ChargeCreditPurchaseQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ChargeCreditPurchase entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ChargeCreditPurchase entity is found. +// Returns a *NotFoundError when no ChargeCreditPurchase entities are found. +func (_q *ChargeCreditPurchaseQuery) Only(ctx context.Context) (*ChargeCreditPurchase, 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{chargecreditpurchase.Label} + default: + return nil, &NotSingularError{chargecreditpurchase.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ChargeCreditPurchaseQuery) OnlyX(ctx context.Context) *ChargeCreditPurchase { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ChargeCreditPurchase ID in the query. +// Returns a *NotSingularError when more than one ChargeCreditPurchase ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ChargeCreditPurchaseQuery) 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{chargecreditpurchase.Label} + default: + err = &NotSingularError{chargecreditpurchase.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ChargeCreditPurchaseQuery) 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 ChargeCreditPurchases. +func (_q *ChargeCreditPurchaseQuery) All(ctx context.Context) ([]*ChargeCreditPurchase, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ChargeCreditPurchase, *ChargeCreditPurchaseQuery]() + return withInterceptors[[]*ChargeCreditPurchase](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ChargeCreditPurchaseQuery) AllX(ctx context.Context) []*ChargeCreditPurchase { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ChargeCreditPurchase IDs. +func (_q *ChargeCreditPurchaseQuery) 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(chargecreditpurchase.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ChargeCreditPurchaseQuery) 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 *ChargeCreditPurchaseQuery) 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[*ChargeCreditPurchaseQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ChargeCreditPurchaseQuery) 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 *ChargeCreditPurchaseQuery) 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 *ChargeCreditPurchaseQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ChargeCreditPurchaseQuery 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 *ChargeCreditPurchaseQuery) Clone() *ChargeCreditPurchaseQuery { + if _q == nil { + return nil + } + return &ChargeCreditPurchaseQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]chargecreditpurchase.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ChargeCreditPurchase{}, _q.predicates...), + withExternalPayment: _q.withExternalPayment.Clone(), + withInvoicedPayment: _q.withInvoicedPayment.Clone(), + withCreditGrant: _q.withCreditGrant.Clone(), + withCharge: _q.withCharge.Clone(), + withSubscription: _q.withSubscription.Clone(), + withSubscriptionPhase: _q.withSubscriptionPhase.Clone(), + withSubscriptionItem: _q.withSubscriptionItem.Clone(), + withCustomer: _q.withCustomer.Clone(), + withTaxCode: _q.withTaxCode.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithExternalPayment tells the query-builder to eager-load the nodes that are connected to +// the "external_payment" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeCreditPurchaseQuery) WithExternalPayment(opts ...func(*ChargeCreditPurchaseExternalPaymentQuery)) *ChargeCreditPurchaseQuery { + query := (&ChargeCreditPurchaseExternalPaymentClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withExternalPayment = query + return _q +} + +// WithInvoicedPayment tells the query-builder to eager-load the nodes that are connected to +// the "invoiced_payment" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeCreditPurchaseQuery) WithInvoicedPayment(opts ...func(*ChargeCreditPurchaseInvoicedPaymentQuery)) *ChargeCreditPurchaseQuery { + query := (&ChargeCreditPurchaseInvoicedPaymentClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withInvoicedPayment = query + return _q +} + +// WithCreditGrant tells the query-builder to eager-load the nodes that are connected to +// the "credit_grant" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeCreditPurchaseQuery) WithCreditGrant(opts ...func(*ChargeCreditPurchaseCreditGrantQuery)) *ChargeCreditPurchaseQuery { + query := (&ChargeCreditPurchaseCreditGrantClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCreditGrant = query + return _q +} + +// 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 *ChargeCreditPurchaseQuery) WithCharge(opts ...func(*ChargeQuery)) *ChargeCreditPurchaseQuery { + query := (&ChargeClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCharge = query + return _q +} + +// WithSubscription tells the query-builder to eager-load the nodes that are connected to +// the "subscription" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeCreditPurchaseQuery) WithSubscription(opts ...func(*SubscriptionQuery)) *ChargeCreditPurchaseQuery { + query := (&SubscriptionClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSubscription = query + return _q +} + +// WithSubscriptionPhase tells the query-builder to eager-load the nodes that are connected to +// the "subscription_phase" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeCreditPurchaseQuery) WithSubscriptionPhase(opts ...func(*SubscriptionPhaseQuery)) *ChargeCreditPurchaseQuery { + query := (&SubscriptionPhaseClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSubscriptionPhase = query + return _q +} + +// WithSubscriptionItem tells the query-builder to eager-load the nodes that are connected to +// the "subscription_item" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeCreditPurchaseQuery) WithSubscriptionItem(opts ...func(*SubscriptionItemQuery)) *ChargeCreditPurchaseQuery { + query := (&SubscriptionItemClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSubscriptionItem = query + return _q +} + +// WithCustomer tells the query-builder to eager-load the nodes that are connected to +// the "customer" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeCreditPurchaseQuery) WithCustomer(opts ...func(*CustomerQuery)) *ChargeCreditPurchaseQuery { + query := (&CustomerClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCustomer = query + return _q +} + +// WithTaxCode tells the query-builder to eager-load the nodes that are connected to +// the "tax_code" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeCreditPurchaseQuery) WithTaxCode(opts ...func(*TaxCodeQuery)) *ChargeCreditPurchaseQuery { + query := (&TaxCodeClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withTaxCode = 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 { +// CustomerID string `json:"customer_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.ChargeCreditPurchase.Query(). +// GroupBy(chargecreditpurchase.FieldCustomerID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *ChargeCreditPurchaseQuery) GroupBy(field string, fields ...string) *ChargeCreditPurchaseGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ChargeCreditPurchaseGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = chargecreditpurchase.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 { +// CustomerID string `json:"customer_id,omitempty"` +// } +// +// client.ChargeCreditPurchase.Query(). +// Select(chargecreditpurchase.FieldCustomerID). +// Scan(ctx, &v) +func (_q *ChargeCreditPurchaseQuery) Select(fields ...string) *ChargeCreditPurchaseSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ChargeCreditPurchaseSelect{ChargeCreditPurchaseQuery: _q} + sbuild.label = chargecreditpurchase.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ChargeCreditPurchaseSelect configured with the given aggregations. +func (_q *ChargeCreditPurchaseQuery) Aggregate(fns ...AggregateFunc) *ChargeCreditPurchaseSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ChargeCreditPurchaseQuery) 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 !chargecreditpurchase.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 *ChargeCreditPurchaseQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ChargeCreditPurchase, error) { + var ( + nodes = []*ChargeCreditPurchase{} + _spec = _q.querySpec() + loadedTypes = [9]bool{ + _q.withExternalPayment != nil, + _q.withInvoicedPayment != nil, + _q.withCreditGrant != nil, + _q.withCharge != nil, + _q.withSubscription != nil, + _q.withSubscriptionPhase != nil, + _q.withSubscriptionItem != nil, + _q.withCustomer != nil, + _q.withTaxCode != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ChargeCreditPurchase).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ChargeCreditPurchase{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.withExternalPayment; query != nil { + if err := _q.loadExternalPayment(ctx, query, nodes, nil, + func(n *ChargeCreditPurchase, e *ChargeCreditPurchaseExternalPayment) { n.Edges.ExternalPayment = e }); err != nil { + return nil, err + } + } + if query := _q.withInvoicedPayment; query != nil { + if err := _q.loadInvoicedPayment(ctx, query, nodes, nil, + func(n *ChargeCreditPurchase, e *ChargeCreditPurchaseInvoicedPayment) { n.Edges.InvoicedPayment = e }); err != nil { + return nil, err + } + } + if query := _q.withCreditGrant; query != nil { + if err := _q.loadCreditGrant(ctx, query, nodes, nil, + func(n *ChargeCreditPurchase, e *ChargeCreditPurchaseCreditGrant) { n.Edges.CreditGrant = e }); err != nil { + return nil, err + } + } + if query := _q.withCharge; query != nil { + if err := _q.loadCharge(ctx, query, nodes, nil, + func(n *ChargeCreditPurchase, e *Charge) { n.Edges.Charge = e }); err != nil { + return nil, err + } + } + if query := _q.withSubscription; query != nil { + if err := _q.loadSubscription(ctx, query, nodes, nil, + func(n *ChargeCreditPurchase, e *Subscription) { n.Edges.Subscription = e }); err != nil { + return nil, err + } + } + if query := _q.withSubscriptionPhase; query != nil { + if err := _q.loadSubscriptionPhase(ctx, query, nodes, nil, + func(n *ChargeCreditPurchase, e *SubscriptionPhase) { n.Edges.SubscriptionPhase = e }); err != nil { + return nil, err + } + } + if query := _q.withSubscriptionItem; query != nil { + if err := _q.loadSubscriptionItem(ctx, query, nodes, nil, + func(n *ChargeCreditPurchase, e *SubscriptionItem) { n.Edges.SubscriptionItem = e }); err != nil { + return nil, err + } + } + if query := _q.withCustomer; query != nil { + if err := _q.loadCustomer(ctx, query, nodes, nil, + func(n *ChargeCreditPurchase, e *Customer) { n.Edges.Customer = e }); err != nil { + return nil, err + } + } + if query := _q.withTaxCode; query != nil { + if err := _q.loadTaxCode(ctx, query, nodes, nil, + func(n *ChargeCreditPurchase, e *TaxCode) { n.Edges.TaxCode = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ChargeCreditPurchaseQuery) loadExternalPayment(ctx context.Context, query *ChargeCreditPurchaseExternalPaymentQuery, nodes []*ChargeCreditPurchase, init func(*ChargeCreditPurchase), assign func(*ChargeCreditPurchase, *ChargeCreditPurchaseExternalPayment)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*ChargeCreditPurchase) + 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(chargecreditpurchaseexternalpayment.FieldChargeID) + } + query.Where(predicate.ChargeCreditPurchaseExternalPayment(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargecreditpurchase.ExternalPaymentColumn), 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 *ChargeCreditPurchaseQuery) loadInvoicedPayment(ctx context.Context, query *ChargeCreditPurchaseInvoicedPaymentQuery, nodes []*ChargeCreditPurchase, init func(*ChargeCreditPurchase), assign func(*ChargeCreditPurchase, *ChargeCreditPurchaseInvoicedPayment)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*ChargeCreditPurchase) + 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(chargecreditpurchaseinvoicedpayment.FieldChargeID) + } + query.Where(predicate.ChargeCreditPurchaseInvoicedPayment(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargecreditpurchase.InvoicedPaymentColumn), 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 *ChargeCreditPurchaseQuery) loadCreditGrant(ctx context.Context, query *ChargeCreditPurchaseCreditGrantQuery, nodes []*ChargeCreditPurchase, init func(*ChargeCreditPurchase), assign func(*ChargeCreditPurchase, *ChargeCreditPurchaseCreditGrant)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*ChargeCreditPurchase) + 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(chargecreditpurchasecreditgrant.FieldChargeID) + } + query.Where(predicate.ChargeCreditPurchaseCreditGrant(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargecreditpurchase.CreditGrantColumn), 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 *ChargeCreditPurchaseQuery) loadCharge(ctx context.Context, query *ChargeQuery, nodes []*ChargeCreditPurchase, init func(*ChargeCreditPurchase), assign func(*ChargeCreditPurchase, *Charge)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*ChargeCreditPurchase) + 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(charge.FieldChargeCreditPurchaseID) + } + query.Where(predicate.Charge(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargecreditpurchase.ChargeColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.ChargeCreditPurchaseID + if fk == nil { + return fmt.Errorf(`foreign-key "charge_credit_purchase_id" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "charge_credit_purchase_id" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *ChargeCreditPurchaseQuery) loadSubscription(ctx context.Context, query *SubscriptionQuery, nodes []*ChargeCreditPurchase, init func(*ChargeCreditPurchase), assign func(*ChargeCreditPurchase, *Subscription)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeCreditPurchase) + for i := range nodes { + if nodes[i].SubscriptionID == nil { + continue + } + fk := *nodes[i].SubscriptionID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(subscription.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 "subscription_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeCreditPurchaseQuery) loadSubscriptionPhase(ctx context.Context, query *SubscriptionPhaseQuery, nodes []*ChargeCreditPurchase, init func(*ChargeCreditPurchase), assign func(*ChargeCreditPurchase, *SubscriptionPhase)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeCreditPurchase) + for i := range nodes { + if nodes[i].SubscriptionPhaseID == nil { + continue + } + fk := *nodes[i].SubscriptionPhaseID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(subscriptionphase.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 "subscription_phase_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeCreditPurchaseQuery) loadSubscriptionItem(ctx context.Context, query *SubscriptionItemQuery, nodes []*ChargeCreditPurchase, init func(*ChargeCreditPurchase), assign func(*ChargeCreditPurchase, *SubscriptionItem)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeCreditPurchase) + for i := range nodes { + if nodes[i].SubscriptionItemID == nil { + continue + } + fk := *nodes[i].SubscriptionItemID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(subscriptionitem.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 "subscription_item_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeCreditPurchaseQuery) loadCustomer(ctx context.Context, query *CustomerQuery, nodes []*ChargeCreditPurchase, init func(*ChargeCreditPurchase), assign func(*ChargeCreditPurchase, *Customer)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeCreditPurchase) + for i := range nodes { + fk := nodes[i].CustomerID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(customer.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 "customer_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeCreditPurchaseQuery) loadTaxCode(ctx context.Context, query *TaxCodeQuery, nodes []*ChargeCreditPurchase, init func(*ChargeCreditPurchase), assign func(*ChargeCreditPurchase, *TaxCode)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeCreditPurchase) + for i := range nodes { + fk := nodes[i].TaxCodeID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(dbtaxcode.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 "tax_code_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *ChargeCreditPurchaseQuery) 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 *ChargeCreditPurchaseQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(chargecreditpurchase.Table, chargecreditpurchase.Columns, sqlgraph.NewFieldSpec(chargecreditpurchase.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, chargecreditpurchase.FieldID) + for i := range fields { + if fields[i] != chargecreditpurchase.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withSubscription != nil { + _spec.Node.AddColumnOnce(chargecreditpurchase.FieldSubscriptionID) + } + if _q.withSubscriptionPhase != nil { + _spec.Node.AddColumnOnce(chargecreditpurchase.FieldSubscriptionPhaseID) + } + if _q.withSubscriptionItem != nil { + _spec.Node.AddColumnOnce(chargecreditpurchase.FieldSubscriptionItemID) + } + if _q.withCustomer != nil { + _spec.Node.AddColumnOnce(chargecreditpurchase.FieldCustomerID) + } + if _q.withTaxCode != nil { + _spec.Node.AddColumnOnce(chargecreditpurchase.FieldTaxCodeID) + } + } + 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 *ChargeCreditPurchaseQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(chargecreditpurchase.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = chargecreditpurchase.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 *ChargeCreditPurchaseQuery) ForUpdate(opts ...sql.LockOption) *ChargeCreditPurchaseQuery { + 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 *ChargeCreditPurchaseQuery) ForShare(opts ...sql.LockOption) *ChargeCreditPurchaseQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ChargeCreditPurchaseGroupBy is the group-by builder for ChargeCreditPurchase entities. +type ChargeCreditPurchaseGroupBy struct { + selector + build *ChargeCreditPurchaseQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ChargeCreditPurchaseGroupBy) Aggregate(fns ...AggregateFunc) *ChargeCreditPurchaseGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ChargeCreditPurchaseGroupBy) 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[*ChargeCreditPurchaseQuery, *ChargeCreditPurchaseGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ChargeCreditPurchaseGroupBy) sqlScan(ctx context.Context, root *ChargeCreditPurchaseQuery, 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) +} + +// ChargeCreditPurchaseSelect is the builder for selecting fields of ChargeCreditPurchase entities. +type ChargeCreditPurchaseSelect struct { + *ChargeCreditPurchaseQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ChargeCreditPurchaseSelect) Aggregate(fns ...AggregateFunc) *ChargeCreditPurchaseSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ChargeCreditPurchaseSelect) 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[*ChargeCreditPurchaseQuery, *ChargeCreditPurchaseSelect](ctx, _s.ChargeCreditPurchaseQuery, _s, _s.inters, v) +} + +func (_s *ChargeCreditPurchaseSelect) sqlScan(ctx context.Context, root *ChargeCreditPurchaseQuery, 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/ent/db/chargecreditpurchase_update.go b/ent/db/chargecreditpurchase_update.go new file mode 100644 index 0000000000000000000000000000000000000000..8d7591211781d06a33a6223cf37428745e6f94bd --- /dev/null +++ b/ent/db/chargecreditpurchase_update.go @@ -0,0 +1,1426 @@ +// 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/creditpurchase" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchase" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchasecreditgrant" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchaseexternalpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchaseinvoicedpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeCreditPurchaseUpdate is the builder for updating ChargeCreditPurchase entities. +type ChargeCreditPurchaseUpdate struct { + config + hooks []Hook + mutation *ChargeCreditPurchaseMutation +} + +// Where appends a list predicates to the ChargeCreditPurchaseUpdate builder. +func (_u *ChargeCreditPurchaseUpdate) Where(ps ...predicate.ChargeCreditPurchase) *ChargeCreditPurchaseUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeCreditPurchaseUpdate) SetServicePeriodFrom(v time.Time) *ChargeCreditPurchaseUpdate { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdate) SetNillableServicePeriodFrom(v *time.Time) *ChargeCreditPurchaseUpdate { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeCreditPurchaseUpdate) SetServicePeriodTo(v time.Time) *ChargeCreditPurchaseUpdate { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdate) SetNillableServicePeriodTo(v *time.Time) *ChargeCreditPurchaseUpdate { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (_u *ChargeCreditPurchaseUpdate) SetBillingPeriodFrom(v time.Time) *ChargeCreditPurchaseUpdate { + _u.mutation.SetBillingPeriodFrom(v) + return _u +} + +// SetNillableBillingPeriodFrom sets the "billing_period_from" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdate) SetNillableBillingPeriodFrom(v *time.Time) *ChargeCreditPurchaseUpdate { + if v != nil { + _u.SetBillingPeriodFrom(*v) + } + return _u +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (_u *ChargeCreditPurchaseUpdate) SetBillingPeriodTo(v time.Time) *ChargeCreditPurchaseUpdate { + _u.mutation.SetBillingPeriodTo(v) + return _u +} + +// SetNillableBillingPeriodTo sets the "billing_period_to" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdate) SetNillableBillingPeriodTo(v *time.Time) *ChargeCreditPurchaseUpdate { + if v != nil { + _u.SetBillingPeriodTo(*v) + } + return _u +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (_u *ChargeCreditPurchaseUpdate) SetFullServicePeriodFrom(v time.Time) *ChargeCreditPurchaseUpdate { + _u.mutation.SetFullServicePeriodFrom(v) + return _u +} + +// SetNillableFullServicePeriodFrom sets the "full_service_period_from" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdate) SetNillableFullServicePeriodFrom(v *time.Time) *ChargeCreditPurchaseUpdate { + if v != nil { + _u.SetFullServicePeriodFrom(*v) + } + return _u +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (_u *ChargeCreditPurchaseUpdate) SetFullServicePeriodTo(v time.Time) *ChargeCreditPurchaseUpdate { + _u.mutation.SetFullServicePeriodTo(v) + return _u +} + +// SetNillableFullServicePeriodTo sets the "full_service_period_to" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdate) SetNillableFullServicePeriodTo(v *time.Time) *ChargeCreditPurchaseUpdate { + if v != nil { + _u.SetFullServicePeriodTo(*v) + } + return _u +} + +// SetStatus sets the "status" field. +func (_u *ChargeCreditPurchaseUpdate) SetStatus(v meta.ChargeStatus) *ChargeCreditPurchaseUpdate { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdate) SetNillableStatus(v *meta.ChargeStatus) *ChargeCreditPurchaseUpdate { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (_u *ChargeCreditPurchaseUpdate) SetSubscriptionItemID(v string) *ChargeCreditPurchaseUpdate { + _u.mutation.SetSubscriptionItemID(v) + return _u +} + +// SetNillableSubscriptionItemID sets the "subscription_item_id" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdate) SetNillableSubscriptionItemID(v *string) *ChargeCreditPurchaseUpdate { + if v != nil { + _u.SetSubscriptionItemID(*v) + } + return _u +} + +// ClearSubscriptionItemID clears the value of the "subscription_item_id" field. +func (_u *ChargeCreditPurchaseUpdate) ClearSubscriptionItemID() *ChargeCreditPurchaseUpdate { + _u.mutation.ClearSubscriptionItemID() + return _u +} + +// SetAdvanceAfter sets the "advance_after" field. +func (_u *ChargeCreditPurchaseUpdate) SetAdvanceAfter(v time.Time) *ChargeCreditPurchaseUpdate { + _u.mutation.SetAdvanceAfter(v) + return _u +} + +// SetNillableAdvanceAfter sets the "advance_after" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdate) SetNillableAdvanceAfter(v *time.Time) *ChargeCreditPurchaseUpdate { + if v != nil { + _u.SetAdvanceAfter(*v) + } + return _u +} + +// ClearAdvanceAfter clears the value of the "advance_after" field. +func (_u *ChargeCreditPurchaseUpdate) ClearAdvanceAfter() *ChargeCreditPurchaseUpdate { + _u.mutation.ClearAdvanceAfter() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeCreditPurchaseUpdate) SetAnnotations(v models.Annotations) *ChargeCreditPurchaseUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeCreditPurchaseUpdate) ClearAnnotations() *ChargeCreditPurchaseUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *ChargeCreditPurchaseUpdate) SetMetadata(v map[string]string) *ChargeCreditPurchaseUpdate { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *ChargeCreditPurchaseUpdate) ClearMetadata() *ChargeCreditPurchaseUpdate { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeCreditPurchaseUpdate) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeCreditPurchaseUpdate) SetDeletedAt(v time.Time) *ChargeCreditPurchaseUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdate) SetNillableDeletedAt(v *time.Time) *ChargeCreditPurchaseUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeCreditPurchaseUpdate) ClearDeletedAt() *ChargeCreditPurchaseUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *ChargeCreditPurchaseUpdate) SetName(v string) *ChargeCreditPurchaseUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdate) SetNillableName(v *string) *ChargeCreditPurchaseUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *ChargeCreditPurchaseUpdate) SetDescription(v string) *ChargeCreditPurchaseUpdate { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdate) SetNillableDescription(v *string) *ChargeCreditPurchaseUpdate { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *ChargeCreditPurchaseUpdate) ClearDescription() *ChargeCreditPurchaseUpdate { + _u.mutation.ClearDescription() + return _u +} + +// SetCreditAmount sets the "credit_amount" field. +func (_u *ChargeCreditPurchaseUpdate) SetCreditAmount(v alpacadecimal.Decimal) *ChargeCreditPurchaseUpdate { + _u.mutation.SetCreditAmount(v) + return _u +} + +// SetNillableCreditAmount sets the "credit_amount" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdate) SetNillableCreditAmount(v *alpacadecimal.Decimal) *ChargeCreditPurchaseUpdate { + if v != nil { + _u.SetCreditAmount(*v) + } + return _u +} + +// SetSettlement sets the "settlement" field. +func (_u *ChargeCreditPurchaseUpdate) SetSettlement(v creditpurchase.Settlement) *ChargeCreditPurchaseUpdate { + _u.mutation.SetSettlement(v) + return _u +} + +// SetNillableSettlement sets the "settlement" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdate) SetNillableSettlement(v *creditpurchase.Settlement) *ChargeCreditPurchaseUpdate { + if v != nil { + _u.SetSettlement(*v) + } + return _u +} + +// SetStatusDetailed sets the "status_detailed" field. +func (_u *ChargeCreditPurchaseUpdate) SetStatusDetailed(v creditpurchase.Status) *ChargeCreditPurchaseUpdate { + _u.mutation.SetStatusDetailed(v) + return _u +} + +// SetNillableStatusDetailed sets the "status_detailed" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdate) SetNillableStatusDetailed(v *creditpurchase.Status) *ChargeCreditPurchaseUpdate { + if v != nil { + _u.SetStatusDetailed(*v) + } + return _u +} + +// SetVoidedAt sets the "voided_at" field. +func (_u *ChargeCreditPurchaseUpdate) SetVoidedAt(v time.Time) *ChargeCreditPurchaseUpdate { + _u.mutation.SetVoidedAt(v) + return _u +} + +// SetNillableVoidedAt sets the "voided_at" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdate) SetNillableVoidedAt(v *time.Time) *ChargeCreditPurchaseUpdate { + if v != nil { + _u.SetVoidedAt(*v) + } + return _u +} + +// ClearVoidedAt clears the value of the "voided_at" field. +func (_u *ChargeCreditPurchaseUpdate) ClearVoidedAt() *ChargeCreditPurchaseUpdate { + _u.mutation.ClearVoidedAt() + return _u +} + +// SetExternalPaymentID sets the "external_payment" edge to the ChargeCreditPurchaseExternalPayment entity by ID. +func (_u *ChargeCreditPurchaseUpdate) SetExternalPaymentID(id string) *ChargeCreditPurchaseUpdate { + _u.mutation.SetExternalPaymentID(id) + return _u +} + +// SetNillableExternalPaymentID sets the "external_payment" edge to the ChargeCreditPurchaseExternalPayment entity by ID if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdate) SetNillableExternalPaymentID(id *string) *ChargeCreditPurchaseUpdate { + if id != nil { + _u = _u.SetExternalPaymentID(*id) + } + return _u +} + +// SetExternalPayment sets the "external_payment" edge to the ChargeCreditPurchaseExternalPayment entity. +func (_u *ChargeCreditPurchaseUpdate) SetExternalPayment(v *ChargeCreditPurchaseExternalPayment) *ChargeCreditPurchaseUpdate { + return _u.SetExternalPaymentID(v.ID) +} + +// SetInvoicedPaymentID sets the "invoiced_payment" edge to the ChargeCreditPurchaseInvoicedPayment entity by ID. +func (_u *ChargeCreditPurchaseUpdate) SetInvoicedPaymentID(id string) *ChargeCreditPurchaseUpdate { + _u.mutation.SetInvoicedPaymentID(id) + return _u +} + +// SetNillableInvoicedPaymentID sets the "invoiced_payment" edge to the ChargeCreditPurchaseInvoicedPayment entity by ID if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdate) SetNillableInvoicedPaymentID(id *string) *ChargeCreditPurchaseUpdate { + if id != nil { + _u = _u.SetInvoicedPaymentID(*id) + } + return _u +} + +// SetInvoicedPayment sets the "invoiced_payment" edge to the ChargeCreditPurchaseInvoicedPayment entity. +func (_u *ChargeCreditPurchaseUpdate) SetInvoicedPayment(v *ChargeCreditPurchaseInvoicedPayment) *ChargeCreditPurchaseUpdate { + return _u.SetInvoicedPaymentID(v.ID) +} + +// SetCreditGrantID sets the "credit_grant" edge to the ChargeCreditPurchaseCreditGrant entity by ID. +func (_u *ChargeCreditPurchaseUpdate) SetCreditGrantID(id string) *ChargeCreditPurchaseUpdate { + _u.mutation.SetCreditGrantID(id) + return _u +} + +// SetNillableCreditGrantID sets the "credit_grant" edge to the ChargeCreditPurchaseCreditGrant entity by ID if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdate) SetNillableCreditGrantID(id *string) *ChargeCreditPurchaseUpdate { + if id != nil { + _u = _u.SetCreditGrantID(*id) + } + return _u +} + +// SetCreditGrant sets the "credit_grant" edge to the ChargeCreditPurchaseCreditGrant entity. +func (_u *ChargeCreditPurchaseUpdate) SetCreditGrant(v *ChargeCreditPurchaseCreditGrant) *ChargeCreditPurchaseUpdate { + return _u.SetCreditGrantID(v.ID) +} + +// SetSubscriptionItem sets the "subscription_item" edge to the SubscriptionItem entity. +func (_u *ChargeCreditPurchaseUpdate) SetSubscriptionItem(v *SubscriptionItem) *ChargeCreditPurchaseUpdate { + return _u.SetSubscriptionItemID(v.ID) +} + +// Mutation returns the ChargeCreditPurchaseMutation object of the builder. +func (_u *ChargeCreditPurchaseUpdate) Mutation() *ChargeCreditPurchaseMutation { + return _u.mutation +} + +// ClearExternalPayment clears the "external_payment" edge to the ChargeCreditPurchaseExternalPayment entity. +func (_u *ChargeCreditPurchaseUpdate) ClearExternalPayment() *ChargeCreditPurchaseUpdate { + _u.mutation.ClearExternalPayment() + return _u +} + +// ClearInvoicedPayment clears the "invoiced_payment" edge to the ChargeCreditPurchaseInvoicedPayment entity. +func (_u *ChargeCreditPurchaseUpdate) ClearInvoicedPayment() *ChargeCreditPurchaseUpdate { + _u.mutation.ClearInvoicedPayment() + return _u +} + +// ClearCreditGrant clears the "credit_grant" edge to the ChargeCreditPurchaseCreditGrant entity. +func (_u *ChargeCreditPurchaseUpdate) ClearCreditGrant() *ChargeCreditPurchaseUpdate { + _u.mutation.ClearCreditGrant() + return _u +} + +// ClearSubscriptionItem clears the "subscription_item" edge to the SubscriptionItem entity. +func (_u *ChargeCreditPurchaseUpdate) ClearSubscriptionItem() *ChargeCreditPurchaseUpdate { + _u.mutation.ClearSubscriptionItem() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ChargeCreditPurchaseUpdate) 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 *ChargeCreditPurchaseUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ChargeCreditPurchaseUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeCreditPurchaseUpdate) 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 *ChargeCreditPurchaseUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargecreditpurchase.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeCreditPurchaseUpdate) check() error { + if v, ok := _u.mutation.Status(); ok { + if err := chargecreditpurchase.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchase.status": %w`, err)} + } + } + if v, ok := _u.mutation.Settlement(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "settlement", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchase.settlement": %w`, err)} + } + } + if v, ok := _u.mutation.StatusDetailed(); ok { + if err := chargecreditpurchase.StatusDetailedValidator(v); err != nil { + return &ValidationError{Name: "status_detailed", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchase.status_detailed": %w`, err)} + } + } + if _u.mutation.CustomerCleared() && len(_u.mutation.CustomerIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeCreditPurchase.customer"`) + } + if _u.mutation.TaxCodeCleared() && len(_u.mutation.TaxCodeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeCreditPurchase.tax_code"`) + } + return nil +} + +func (_u *ChargeCreditPurchaseUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargecreditpurchase.Table, chargecreditpurchase.Columns, sqlgraph.NewFieldSpec(chargecreditpurchase.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(chargecreditpurchase.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargecreditpurchase.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.BillingPeriodFrom(); ok { + _spec.SetField(chargecreditpurchase.FieldBillingPeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.BillingPeriodTo(); ok { + _spec.SetField(chargecreditpurchase.FieldBillingPeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.FullServicePeriodFrom(); ok { + _spec.SetField(chargecreditpurchase.FieldFullServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.FullServicePeriodTo(); ok { + _spec.SetField(chargecreditpurchase.FieldFullServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(chargecreditpurchase.FieldStatus, field.TypeEnum, value) + } + if _u.mutation.UniqueReferenceIDCleared() { + _spec.ClearField(chargecreditpurchase.FieldUniqueReferenceID, field.TypeString) + } + if value, ok := _u.mutation.AdvanceAfter(); ok { + _spec.SetField(chargecreditpurchase.FieldAdvanceAfter, field.TypeTime, value) + } + if _u.mutation.AdvanceAfterCleared() { + _spec.ClearField(chargecreditpurchase.FieldAdvanceAfter, field.TypeTime) + } + if _u.mutation.TaxBehaviorCleared() { + _spec.ClearField(chargecreditpurchase.FieldTaxBehavior, field.TypeEnum) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargecreditpurchase.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargecreditpurchase.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(chargecreditpurchase.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(chargecreditpurchase.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargecreditpurchase.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargecreditpurchase.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargecreditpurchase.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(chargecreditpurchase.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(chargecreditpurchase.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(chargecreditpurchase.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.CreditAmount(); ok { + _spec.SetField(chargecreditpurchase.FieldCreditAmount, field.TypeOther, value) + } + if _u.mutation.EffectiveAtCleared() { + _spec.ClearField(chargecreditpurchase.FieldEffectiveAt, field.TypeTime) + } + if _u.mutation.ExpiresAtCleared() { + _spec.ClearField(chargecreditpurchase.FieldExpiresAt, field.TypeTime) + } + if _u.mutation.PriorityCleared() { + _spec.ClearField(chargecreditpurchase.FieldPriority, field.TypeInt) + } + if _u.mutation.FeatureFiltersCleared() { + _spec.ClearField(chargecreditpurchase.FieldFeatureFilters, field.TypeOther) + } + if value, ok := _u.mutation.Settlement(); ok { + vv, err := chargecreditpurchase.ValueScanner.Settlement.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(chargecreditpurchase.FieldSettlement, field.TypeString, vv) + } + if value, ok := _u.mutation.StatusDetailed(); ok { + _spec.SetField(chargecreditpurchase.FieldStatusDetailed, field.TypeEnum, value) + } + if _u.mutation.KeyCleared() { + _spec.ClearField(chargecreditpurchase.FieldKey, field.TypeString) + } + if value, ok := _u.mutation.VoidedAt(); ok { + _spec.SetField(chargecreditpurchase.FieldVoidedAt, field.TypeTime, value) + } + if _u.mutation.VoidedAtCleared() { + _spec.ClearField(chargecreditpurchase.FieldVoidedAt, field.TypeTime) + } + if _u.mutation.ExternalPaymentCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargecreditpurchase.ExternalPaymentTable, + Columns: []string{chargecreditpurchase.ExternalPaymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchaseexternalpayment.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ExternalPaymentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargecreditpurchase.ExternalPaymentTable, + Columns: []string{chargecreditpurchase.ExternalPaymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchaseexternalpayment.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.InvoicedPaymentCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargecreditpurchase.InvoicedPaymentTable, + Columns: []string{chargecreditpurchase.InvoicedPaymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchaseinvoicedpayment.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.InvoicedPaymentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargecreditpurchase.InvoicedPaymentTable, + Columns: []string{chargecreditpurchase.InvoicedPaymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchaseinvoicedpayment.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.CreditGrantCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargecreditpurchase.CreditGrantTable, + Columns: []string{chargecreditpurchase.CreditGrantColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchasecreditgrant.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.CreditGrantIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargecreditpurchase.CreditGrantTable, + Columns: []string{chargecreditpurchase.CreditGrantColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchasecreditgrant.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.SubscriptionItemCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargecreditpurchase.SubscriptionItemTable, + Columns: []string{chargecreditpurchase.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.SubscriptionItemIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargecreditpurchase.SubscriptionItemTable, + Columns: []string{chargecreditpurchase.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.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{chargecreditpurchase.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ChargeCreditPurchaseUpdateOne is the builder for updating a single ChargeCreditPurchase entity. +type ChargeCreditPurchaseUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ChargeCreditPurchaseMutation +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeCreditPurchaseUpdateOne) SetServicePeriodFrom(v time.Time) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdateOne) SetNillableServicePeriodFrom(v *time.Time) *ChargeCreditPurchaseUpdateOne { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeCreditPurchaseUpdateOne) SetServicePeriodTo(v time.Time) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdateOne) SetNillableServicePeriodTo(v *time.Time) *ChargeCreditPurchaseUpdateOne { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (_u *ChargeCreditPurchaseUpdateOne) SetBillingPeriodFrom(v time.Time) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetBillingPeriodFrom(v) + return _u +} + +// SetNillableBillingPeriodFrom sets the "billing_period_from" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdateOne) SetNillableBillingPeriodFrom(v *time.Time) *ChargeCreditPurchaseUpdateOne { + if v != nil { + _u.SetBillingPeriodFrom(*v) + } + return _u +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (_u *ChargeCreditPurchaseUpdateOne) SetBillingPeriodTo(v time.Time) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetBillingPeriodTo(v) + return _u +} + +// SetNillableBillingPeriodTo sets the "billing_period_to" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdateOne) SetNillableBillingPeriodTo(v *time.Time) *ChargeCreditPurchaseUpdateOne { + if v != nil { + _u.SetBillingPeriodTo(*v) + } + return _u +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (_u *ChargeCreditPurchaseUpdateOne) SetFullServicePeriodFrom(v time.Time) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetFullServicePeriodFrom(v) + return _u +} + +// SetNillableFullServicePeriodFrom sets the "full_service_period_from" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdateOne) SetNillableFullServicePeriodFrom(v *time.Time) *ChargeCreditPurchaseUpdateOne { + if v != nil { + _u.SetFullServicePeriodFrom(*v) + } + return _u +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (_u *ChargeCreditPurchaseUpdateOne) SetFullServicePeriodTo(v time.Time) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetFullServicePeriodTo(v) + return _u +} + +// SetNillableFullServicePeriodTo sets the "full_service_period_to" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdateOne) SetNillableFullServicePeriodTo(v *time.Time) *ChargeCreditPurchaseUpdateOne { + if v != nil { + _u.SetFullServicePeriodTo(*v) + } + return _u +} + +// SetStatus sets the "status" field. +func (_u *ChargeCreditPurchaseUpdateOne) SetStatus(v meta.ChargeStatus) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdateOne) SetNillableStatus(v *meta.ChargeStatus) *ChargeCreditPurchaseUpdateOne { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (_u *ChargeCreditPurchaseUpdateOne) SetSubscriptionItemID(v string) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetSubscriptionItemID(v) + return _u +} + +// SetNillableSubscriptionItemID sets the "subscription_item_id" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdateOne) SetNillableSubscriptionItemID(v *string) *ChargeCreditPurchaseUpdateOne { + if v != nil { + _u.SetSubscriptionItemID(*v) + } + return _u +} + +// ClearSubscriptionItemID clears the value of the "subscription_item_id" field. +func (_u *ChargeCreditPurchaseUpdateOne) ClearSubscriptionItemID() *ChargeCreditPurchaseUpdateOne { + _u.mutation.ClearSubscriptionItemID() + return _u +} + +// SetAdvanceAfter sets the "advance_after" field. +func (_u *ChargeCreditPurchaseUpdateOne) SetAdvanceAfter(v time.Time) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetAdvanceAfter(v) + return _u +} + +// SetNillableAdvanceAfter sets the "advance_after" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdateOne) SetNillableAdvanceAfter(v *time.Time) *ChargeCreditPurchaseUpdateOne { + if v != nil { + _u.SetAdvanceAfter(*v) + } + return _u +} + +// ClearAdvanceAfter clears the value of the "advance_after" field. +func (_u *ChargeCreditPurchaseUpdateOne) ClearAdvanceAfter() *ChargeCreditPurchaseUpdateOne { + _u.mutation.ClearAdvanceAfter() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeCreditPurchaseUpdateOne) SetAnnotations(v models.Annotations) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeCreditPurchaseUpdateOne) ClearAnnotations() *ChargeCreditPurchaseUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *ChargeCreditPurchaseUpdateOne) SetMetadata(v map[string]string) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *ChargeCreditPurchaseUpdateOne) ClearMetadata() *ChargeCreditPurchaseUpdateOne { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeCreditPurchaseUpdateOne) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeCreditPurchaseUpdateOne) SetDeletedAt(v time.Time) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdateOne) SetNillableDeletedAt(v *time.Time) *ChargeCreditPurchaseUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeCreditPurchaseUpdateOne) ClearDeletedAt() *ChargeCreditPurchaseUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *ChargeCreditPurchaseUpdateOne) SetName(v string) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdateOne) SetNillableName(v *string) *ChargeCreditPurchaseUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *ChargeCreditPurchaseUpdateOne) SetDescription(v string) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdateOne) SetNillableDescription(v *string) *ChargeCreditPurchaseUpdateOne { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *ChargeCreditPurchaseUpdateOne) ClearDescription() *ChargeCreditPurchaseUpdateOne { + _u.mutation.ClearDescription() + return _u +} + +// SetCreditAmount sets the "credit_amount" field. +func (_u *ChargeCreditPurchaseUpdateOne) SetCreditAmount(v alpacadecimal.Decimal) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetCreditAmount(v) + return _u +} + +// SetNillableCreditAmount sets the "credit_amount" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdateOne) SetNillableCreditAmount(v *alpacadecimal.Decimal) *ChargeCreditPurchaseUpdateOne { + if v != nil { + _u.SetCreditAmount(*v) + } + return _u +} + +// SetSettlement sets the "settlement" field. +func (_u *ChargeCreditPurchaseUpdateOne) SetSettlement(v creditpurchase.Settlement) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetSettlement(v) + return _u +} + +// SetNillableSettlement sets the "settlement" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdateOne) SetNillableSettlement(v *creditpurchase.Settlement) *ChargeCreditPurchaseUpdateOne { + if v != nil { + _u.SetSettlement(*v) + } + return _u +} + +// SetStatusDetailed sets the "status_detailed" field. +func (_u *ChargeCreditPurchaseUpdateOne) SetStatusDetailed(v creditpurchase.Status) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetStatusDetailed(v) + return _u +} + +// SetNillableStatusDetailed sets the "status_detailed" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdateOne) SetNillableStatusDetailed(v *creditpurchase.Status) *ChargeCreditPurchaseUpdateOne { + if v != nil { + _u.SetStatusDetailed(*v) + } + return _u +} + +// SetVoidedAt sets the "voided_at" field. +func (_u *ChargeCreditPurchaseUpdateOne) SetVoidedAt(v time.Time) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetVoidedAt(v) + return _u +} + +// SetNillableVoidedAt sets the "voided_at" field if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdateOne) SetNillableVoidedAt(v *time.Time) *ChargeCreditPurchaseUpdateOne { + if v != nil { + _u.SetVoidedAt(*v) + } + return _u +} + +// ClearVoidedAt clears the value of the "voided_at" field. +func (_u *ChargeCreditPurchaseUpdateOne) ClearVoidedAt() *ChargeCreditPurchaseUpdateOne { + _u.mutation.ClearVoidedAt() + return _u +} + +// SetExternalPaymentID sets the "external_payment" edge to the ChargeCreditPurchaseExternalPayment entity by ID. +func (_u *ChargeCreditPurchaseUpdateOne) SetExternalPaymentID(id string) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetExternalPaymentID(id) + return _u +} + +// SetNillableExternalPaymentID sets the "external_payment" edge to the ChargeCreditPurchaseExternalPayment entity by ID if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdateOne) SetNillableExternalPaymentID(id *string) *ChargeCreditPurchaseUpdateOne { + if id != nil { + _u = _u.SetExternalPaymentID(*id) + } + return _u +} + +// SetExternalPayment sets the "external_payment" edge to the ChargeCreditPurchaseExternalPayment entity. +func (_u *ChargeCreditPurchaseUpdateOne) SetExternalPayment(v *ChargeCreditPurchaseExternalPayment) *ChargeCreditPurchaseUpdateOne { + return _u.SetExternalPaymentID(v.ID) +} + +// SetInvoicedPaymentID sets the "invoiced_payment" edge to the ChargeCreditPurchaseInvoicedPayment entity by ID. +func (_u *ChargeCreditPurchaseUpdateOne) SetInvoicedPaymentID(id string) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetInvoicedPaymentID(id) + return _u +} + +// SetNillableInvoicedPaymentID sets the "invoiced_payment" edge to the ChargeCreditPurchaseInvoicedPayment entity by ID if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdateOne) SetNillableInvoicedPaymentID(id *string) *ChargeCreditPurchaseUpdateOne { + if id != nil { + _u = _u.SetInvoicedPaymentID(*id) + } + return _u +} + +// SetInvoicedPayment sets the "invoiced_payment" edge to the ChargeCreditPurchaseInvoicedPayment entity. +func (_u *ChargeCreditPurchaseUpdateOne) SetInvoicedPayment(v *ChargeCreditPurchaseInvoicedPayment) *ChargeCreditPurchaseUpdateOne { + return _u.SetInvoicedPaymentID(v.ID) +} + +// SetCreditGrantID sets the "credit_grant" edge to the ChargeCreditPurchaseCreditGrant entity by ID. +func (_u *ChargeCreditPurchaseUpdateOne) SetCreditGrantID(id string) *ChargeCreditPurchaseUpdateOne { + _u.mutation.SetCreditGrantID(id) + return _u +} + +// SetNillableCreditGrantID sets the "credit_grant" edge to the ChargeCreditPurchaseCreditGrant entity by ID if the given value is not nil. +func (_u *ChargeCreditPurchaseUpdateOne) SetNillableCreditGrantID(id *string) *ChargeCreditPurchaseUpdateOne { + if id != nil { + _u = _u.SetCreditGrantID(*id) + } + return _u +} + +// SetCreditGrant sets the "credit_grant" edge to the ChargeCreditPurchaseCreditGrant entity. +func (_u *ChargeCreditPurchaseUpdateOne) SetCreditGrant(v *ChargeCreditPurchaseCreditGrant) *ChargeCreditPurchaseUpdateOne { + return _u.SetCreditGrantID(v.ID) +} + +// SetSubscriptionItem sets the "subscription_item" edge to the SubscriptionItem entity. +func (_u *ChargeCreditPurchaseUpdateOne) SetSubscriptionItem(v *SubscriptionItem) *ChargeCreditPurchaseUpdateOne { + return _u.SetSubscriptionItemID(v.ID) +} + +// Mutation returns the ChargeCreditPurchaseMutation object of the builder. +func (_u *ChargeCreditPurchaseUpdateOne) Mutation() *ChargeCreditPurchaseMutation { + return _u.mutation +} + +// ClearExternalPayment clears the "external_payment" edge to the ChargeCreditPurchaseExternalPayment entity. +func (_u *ChargeCreditPurchaseUpdateOne) ClearExternalPayment() *ChargeCreditPurchaseUpdateOne { + _u.mutation.ClearExternalPayment() + return _u +} + +// ClearInvoicedPayment clears the "invoiced_payment" edge to the ChargeCreditPurchaseInvoicedPayment entity. +func (_u *ChargeCreditPurchaseUpdateOne) ClearInvoicedPayment() *ChargeCreditPurchaseUpdateOne { + _u.mutation.ClearInvoicedPayment() + return _u +} + +// ClearCreditGrant clears the "credit_grant" edge to the ChargeCreditPurchaseCreditGrant entity. +func (_u *ChargeCreditPurchaseUpdateOne) ClearCreditGrant() *ChargeCreditPurchaseUpdateOne { + _u.mutation.ClearCreditGrant() + return _u +} + +// ClearSubscriptionItem clears the "subscription_item" edge to the SubscriptionItem entity. +func (_u *ChargeCreditPurchaseUpdateOne) ClearSubscriptionItem() *ChargeCreditPurchaseUpdateOne { + _u.mutation.ClearSubscriptionItem() + return _u +} + +// Where appends a list predicates to the ChargeCreditPurchaseUpdate builder. +func (_u *ChargeCreditPurchaseUpdateOne) Where(ps ...predicate.ChargeCreditPurchase) *ChargeCreditPurchaseUpdateOne { + _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 *ChargeCreditPurchaseUpdateOne) Select(field string, fields ...string) *ChargeCreditPurchaseUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ChargeCreditPurchase entity. +func (_u *ChargeCreditPurchaseUpdateOne) Save(ctx context.Context) (*ChargeCreditPurchase, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeCreditPurchaseUpdateOne) SaveX(ctx context.Context) *ChargeCreditPurchase { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ChargeCreditPurchaseUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeCreditPurchaseUpdateOne) 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 *ChargeCreditPurchaseUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargecreditpurchase.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeCreditPurchaseUpdateOne) check() error { + if v, ok := _u.mutation.Status(); ok { + if err := chargecreditpurchase.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchase.status": %w`, err)} + } + } + if v, ok := _u.mutation.Settlement(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "settlement", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchase.settlement": %w`, err)} + } + } + if v, ok := _u.mutation.StatusDetailed(); ok { + if err := chargecreditpurchase.StatusDetailedValidator(v); err != nil { + return &ValidationError{Name: "status_detailed", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchase.status_detailed": %w`, err)} + } + } + if _u.mutation.CustomerCleared() && len(_u.mutation.CustomerIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeCreditPurchase.customer"`) + } + if _u.mutation.TaxCodeCleared() && len(_u.mutation.TaxCodeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeCreditPurchase.tax_code"`) + } + return nil +} + +func (_u *ChargeCreditPurchaseUpdateOne) sqlSave(ctx context.Context) (_node *ChargeCreditPurchase, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargecreditpurchase.Table, chargecreditpurchase.Columns, sqlgraph.NewFieldSpec(chargecreditpurchase.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "ChargeCreditPurchase.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, chargecreditpurchase.FieldID) + for _, f := range fields { + if !chargecreditpurchase.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != chargecreditpurchase.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(chargecreditpurchase.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargecreditpurchase.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.BillingPeriodFrom(); ok { + _spec.SetField(chargecreditpurchase.FieldBillingPeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.BillingPeriodTo(); ok { + _spec.SetField(chargecreditpurchase.FieldBillingPeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.FullServicePeriodFrom(); ok { + _spec.SetField(chargecreditpurchase.FieldFullServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.FullServicePeriodTo(); ok { + _spec.SetField(chargecreditpurchase.FieldFullServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(chargecreditpurchase.FieldStatus, field.TypeEnum, value) + } + if _u.mutation.UniqueReferenceIDCleared() { + _spec.ClearField(chargecreditpurchase.FieldUniqueReferenceID, field.TypeString) + } + if value, ok := _u.mutation.AdvanceAfter(); ok { + _spec.SetField(chargecreditpurchase.FieldAdvanceAfter, field.TypeTime, value) + } + if _u.mutation.AdvanceAfterCleared() { + _spec.ClearField(chargecreditpurchase.FieldAdvanceAfter, field.TypeTime) + } + if _u.mutation.TaxBehaviorCleared() { + _spec.ClearField(chargecreditpurchase.FieldTaxBehavior, field.TypeEnum) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargecreditpurchase.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargecreditpurchase.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(chargecreditpurchase.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(chargecreditpurchase.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargecreditpurchase.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargecreditpurchase.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargecreditpurchase.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(chargecreditpurchase.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(chargecreditpurchase.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(chargecreditpurchase.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.CreditAmount(); ok { + _spec.SetField(chargecreditpurchase.FieldCreditAmount, field.TypeOther, value) + } + if _u.mutation.EffectiveAtCleared() { + _spec.ClearField(chargecreditpurchase.FieldEffectiveAt, field.TypeTime) + } + if _u.mutation.ExpiresAtCleared() { + _spec.ClearField(chargecreditpurchase.FieldExpiresAt, field.TypeTime) + } + if _u.mutation.PriorityCleared() { + _spec.ClearField(chargecreditpurchase.FieldPriority, field.TypeInt) + } + if _u.mutation.FeatureFiltersCleared() { + _spec.ClearField(chargecreditpurchase.FieldFeatureFilters, field.TypeOther) + } + if value, ok := _u.mutation.Settlement(); ok { + vv, err := chargecreditpurchase.ValueScanner.Settlement.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(chargecreditpurchase.FieldSettlement, field.TypeString, vv) + } + if value, ok := _u.mutation.StatusDetailed(); ok { + _spec.SetField(chargecreditpurchase.FieldStatusDetailed, field.TypeEnum, value) + } + if _u.mutation.KeyCleared() { + _spec.ClearField(chargecreditpurchase.FieldKey, field.TypeString) + } + if value, ok := _u.mutation.VoidedAt(); ok { + _spec.SetField(chargecreditpurchase.FieldVoidedAt, field.TypeTime, value) + } + if _u.mutation.VoidedAtCleared() { + _spec.ClearField(chargecreditpurchase.FieldVoidedAt, field.TypeTime) + } + if _u.mutation.ExternalPaymentCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargecreditpurchase.ExternalPaymentTable, + Columns: []string{chargecreditpurchase.ExternalPaymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchaseexternalpayment.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ExternalPaymentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargecreditpurchase.ExternalPaymentTable, + Columns: []string{chargecreditpurchase.ExternalPaymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchaseexternalpayment.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.InvoicedPaymentCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargecreditpurchase.InvoicedPaymentTable, + Columns: []string{chargecreditpurchase.InvoicedPaymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchaseinvoicedpayment.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.InvoicedPaymentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargecreditpurchase.InvoicedPaymentTable, + Columns: []string{chargecreditpurchase.InvoicedPaymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchaseinvoicedpayment.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.CreditGrantCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargecreditpurchase.CreditGrantTable, + Columns: []string{chargecreditpurchase.CreditGrantColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchasecreditgrant.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.CreditGrantIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargecreditpurchase.CreditGrantTable, + Columns: []string{chargecreditpurchase.CreditGrantColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchasecreditgrant.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.SubscriptionItemCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargecreditpurchase.SubscriptionItemTable, + Columns: []string{chargecreditpurchase.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.SubscriptionItemIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargecreditpurchase.SubscriptionItemTable, + Columns: []string{chargecreditpurchase.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &ChargeCreditPurchase{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{chargecreditpurchase.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/ent/db/chargecreditpurchasecreditgrant.go b/ent/db/chargecreditpurchasecreditgrant.go new file mode 100644 index 0000000000000000000000000000000000000000..e2b7f684125a4bf30a58d68f22ed2e5d46dc9e52 --- /dev/null +++ b/ent/db/chargecreditpurchasecreditgrant.go @@ -0,0 +1,202 @@ +// 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/chargecreditpurchase" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchasecreditgrant" +) + +// ChargeCreditPurchaseCreditGrant is the model entity for the ChargeCreditPurchaseCreditGrant schema. +type ChargeCreditPurchaseCreditGrant 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"` + // TransactionGroupID holds the value of the "transaction_group_id" field. + TransactionGroupID string `json:"transaction_group_id,omitempty"` + // GrantedAt holds the value of the "granted_at" field. + GrantedAt time.Time `json:"granted_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ChargeCreditPurchaseCreditGrantQuery when eager-loading is set. + Edges ChargeCreditPurchaseCreditGrantEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ChargeCreditPurchaseCreditGrantEdges holds the relations/edges for other nodes in the graph. +type ChargeCreditPurchaseCreditGrantEdges struct { + // CreditPurchase holds the value of the credit_purchase edge. + CreditPurchase *ChargeCreditPurchase `json:"credit_purchase,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// CreditPurchaseOrErr returns the CreditPurchase value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeCreditPurchaseCreditGrantEdges) CreditPurchaseOrErr() (*ChargeCreditPurchase, error) { + if e.CreditPurchase != nil { + return e.CreditPurchase, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: chargecreditpurchase.Label} + } + return nil, &NotLoadedError{edge: "credit_purchase"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ChargeCreditPurchaseCreditGrant) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case chargecreditpurchasecreditgrant.FieldID, chargecreditpurchasecreditgrant.FieldNamespace, chargecreditpurchasecreditgrant.FieldChargeID, chargecreditpurchasecreditgrant.FieldTransactionGroupID: + values[i] = new(sql.NullString) + case chargecreditpurchasecreditgrant.FieldCreatedAt, chargecreditpurchasecreditgrant.FieldUpdatedAt, chargecreditpurchasecreditgrant.FieldDeletedAt, chargecreditpurchasecreditgrant.FieldGrantedAt: + 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 ChargeCreditPurchaseCreditGrant fields. +func (_m *ChargeCreditPurchaseCreditGrant) 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 chargecreditpurchasecreditgrant.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 chargecreditpurchasecreditgrant.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 chargecreditpurchasecreditgrant.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 chargecreditpurchasecreditgrant.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 chargecreditpurchasecreditgrant.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 chargecreditpurchasecreditgrant.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 chargecreditpurchasecreditgrant.FieldTransactionGroupID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field transaction_group_id", values[i]) + } else if value.Valid { + _m.TransactionGroupID = value.String + } + case chargecreditpurchasecreditgrant.FieldGrantedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field granted_at", values[i]) + } else if value.Valid { + _m.GrantedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the ChargeCreditPurchaseCreditGrant. +// This includes values selected through modifiers, order, etc. +func (_m *ChargeCreditPurchaseCreditGrant) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryCreditPurchase queries the "credit_purchase" edge of the ChargeCreditPurchaseCreditGrant entity. +func (_m *ChargeCreditPurchaseCreditGrant) QueryCreditPurchase() *ChargeCreditPurchaseQuery { + return NewChargeCreditPurchaseCreditGrantClient(_m.config).QueryCreditPurchase(_m) +} + +// Update returns a builder for updating this ChargeCreditPurchaseCreditGrant. +// Note that you need to call ChargeCreditPurchaseCreditGrant.Unwrap() before calling this method if this ChargeCreditPurchaseCreditGrant +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ChargeCreditPurchaseCreditGrant) Update() *ChargeCreditPurchaseCreditGrantUpdateOne { + return NewChargeCreditPurchaseCreditGrantClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ChargeCreditPurchaseCreditGrant 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 *ChargeCreditPurchaseCreditGrant) Unwrap() *ChargeCreditPurchaseCreditGrant { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: ChargeCreditPurchaseCreditGrant is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ChargeCreditPurchaseCreditGrant) String() string { + var builder strings.Builder + builder.WriteString("ChargeCreditPurchaseCreditGrant(") + 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("transaction_group_id=") + builder.WriteString(_m.TransactionGroupID) + builder.WriteString(", ") + builder.WriteString("granted_at=") + builder.WriteString(_m.GrantedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// ChargeCreditPurchaseCreditGrants is a parsable slice of ChargeCreditPurchaseCreditGrant. +type ChargeCreditPurchaseCreditGrants []*ChargeCreditPurchaseCreditGrant diff --git a/ent/db/chargecreditpurchasecreditgrant/chargecreditpurchasecreditgrant.go b/ent/db/chargecreditpurchasecreditgrant/chargecreditpurchasecreditgrant.go new file mode 100644 index 0000000000000000000000000000000000000000..a36d0528e06f2e9f75dfa43d258d97a67b58d77f --- /dev/null +++ b/ent/db/chargecreditpurchasecreditgrant/chargecreditpurchasecreditgrant.go @@ -0,0 +1,136 @@ +// Code generated by ent, DO NOT EDIT. + +package chargecreditpurchasecreditgrant + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the chargecreditpurchasecreditgrant type in the database. + Label = "charge_credit_purchase_credit_grant" + // 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" + // FieldTransactionGroupID holds the string denoting the transaction_group_id field in the database. + FieldTransactionGroupID = "transaction_group_id" + // FieldGrantedAt holds the string denoting the granted_at field in the database. + FieldGrantedAt = "granted_at" + // EdgeCreditPurchase holds the string denoting the credit_purchase edge name in mutations. + EdgeCreditPurchase = "credit_purchase" + // Table holds the table name of the chargecreditpurchasecreditgrant in the database. + Table = "charge_credit_purchase_credit_grants" + // CreditPurchaseTable is the table that holds the credit_purchase relation/edge. + CreditPurchaseTable = "charge_credit_purchase_credit_grants" + // CreditPurchaseInverseTable is the table name for the ChargeCreditPurchase entity. + // It exists in this package in order to avoid circular dependency with the "chargecreditpurchase" package. + CreditPurchaseInverseTable = "charge_credit_purchases" + // CreditPurchaseColumn is the table column denoting the credit_purchase relation/edge. + CreditPurchaseColumn = "charge_id" +) + +// Columns holds all SQL columns for chargecreditpurchasecreditgrant fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldChargeID, + FieldTransactionGroupID, + FieldGrantedAt, +} + +// 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 + // TransactionGroupIDValidator is a validator for the "transaction_group_id" field. It is called by the builders before save. + TransactionGroupIDValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// OrderOption defines the ordering options for the ChargeCreditPurchaseCreditGrant 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() +} + +// ByTransactionGroupID orders the results by the transaction_group_id field. +func ByTransactionGroupID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTransactionGroupID, opts...).ToFunc() +} + +// ByGrantedAt orders the results by the granted_at field. +func ByGrantedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldGrantedAt, opts...).ToFunc() +} + +// ByCreditPurchaseField orders the results by credit_purchase field. +func ByCreditPurchaseField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCreditPurchaseStep(), sql.OrderByField(field, opts...)) + } +} +func newCreditPurchaseStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CreditPurchaseInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, CreditPurchaseTable, CreditPurchaseColumn), + ) +} diff --git a/ent/db/chargecreditpurchasecreditgrant/where.go b/ent/db/chargecreditpurchasecreditgrant/where.go new file mode 100644 index 0000000000000000000000000000000000000000..1078ea74d577815cb706b84cabffa0144770baab --- /dev/null +++ b/ent/db/chargecreditpurchasecreditgrant/where.go @@ -0,0 +1,504 @@ +// Code generated by ent, DO NOT EDIT. + +package chargecreditpurchasecreditgrant + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(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.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(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.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(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.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldEQ(FieldDeletedAt, v)) +} + +// ChargeID applies equality check predicate on the "charge_id" field. It's identical to ChargeIDEQ. +func ChargeID(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldEQ(FieldChargeID, v)) +} + +// TransactionGroupID applies equality check predicate on the "transaction_group_id" field. It's identical to TransactionGroupIDEQ. +func TransactionGroupID(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldEQ(FieldTransactionGroupID, v)) +} + +// GrantedAt applies equality check predicate on the "granted_at" field. It's identical to GrantedAtEQ. +func GrantedAt(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldEQ(FieldGrantedAt, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldNotNull(FieldDeletedAt)) +} + +// ChargeIDEQ applies the EQ predicate on the "charge_id" field. +func ChargeIDEQ(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldEQ(FieldChargeID, v)) +} + +// ChargeIDNEQ applies the NEQ predicate on the "charge_id" field. +func ChargeIDNEQ(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldNEQ(FieldChargeID, v)) +} + +// ChargeIDIn applies the In predicate on the "charge_id" field. +func ChargeIDIn(vs ...string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldIn(FieldChargeID, vs...)) +} + +// ChargeIDNotIn applies the NotIn predicate on the "charge_id" field. +func ChargeIDNotIn(vs ...string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldNotIn(FieldChargeID, vs...)) +} + +// ChargeIDGT applies the GT predicate on the "charge_id" field. +func ChargeIDGT(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldGT(FieldChargeID, v)) +} + +// ChargeIDGTE applies the GTE predicate on the "charge_id" field. +func ChargeIDGTE(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldGTE(FieldChargeID, v)) +} + +// ChargeIDLT applies the LT predicate on the "charge_id" field. +func ChargeIDLT(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldLT(FieldChargeID, v)) +} + +// ChargeIDLTE applies the LTE predicate on the "charge_id" field. +func ChargeIDLTE(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldLTE(FieldChargeID, v)) +} + +// ChargeIDContains applies the Contains predicate on the "charge_id" field. +func ChargeIDContains(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldContains(FieldChargeID, v)) +} + +// ChargeIDHasPrefix applies the HasPrefix predicate on the "charge_id" field. +func ChargeIDHasPrefix(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldHasPrefix(FieldChargeID, v)) +} + +// ChargeIDHasSuffix applies the HasSuffix predicate on the "charge_id" field. +func ChargeIDHasSuffix(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldHasSuffix(FieldChargeID, v)) +} + +// ChargeIDEqualFold applies the EqualFold predicate on the "charge_id" field. +func ChargeIDEqualFold(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldEqualFold(FieldChargeID, v)) +} + +// ChargeIDContainsFold applies the ContainsFold predicate on the "charge_id" field. +func ChargeIDContainsFold(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldContainsFold(FieldChargeID, v)) +} + +// TransactionGroupIDEQ applies the EQ predicate on the "transaction_group_id" field. +func TransactionGroupIDEQ(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldEQ(FieldTransactionGroupID, v)) +} + +// TransactionGroupIDNEQ applies the NEQ predicate on the "transaction_group_id" field. +func TransactionGroupIDNEQ(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldNEQ(FieldTransactionGroupID, v)) +} + +// TransactionGroupIDIn applies the In predicate on the "transaction_group_id" field. +func TransactionGroupIDIn(vs ...string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldIn(FieldTransactionGroupID, vs...)) +} + +// TransactionGroupIDNotIn applies the NotIn predicate on the "transaction_group_id" field. +func TransactionGroupIDNotIn(vs ...string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldNotIn(FieldTransactionGroupID, vs...)) +} + +// TransactionGroupIDGT applies the GT predicate on the "transaction_group_id" field. +func TransactionGroupIDGT(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldGT(FieldTransactionGroupID, v)) +} + +// TransactionGroupIDGTE applies the GTE predicate on the "transaction_group_id" field. +func TransactionGroupIDGTE(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldGTE(FieldTransactionGroupID, v)) +} + +// TransactionGroupIDLT applies the LT predicate on the "transaction_group_id" field. +func TransactionGroupIDLT(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldLT(FieldTransactionGroupID, v)) +} + +// TransactionGroupIDLTE applies the LTE predicate on the "transaction_group_id" field. +func TransactionGroupIDLTE(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldLTE(FieldTransactionGroupID, v)) +} + +// TransactionGroupIDContains applies the Contains predicate on the "transaction_group_id" field. +func TransactionGroupIDContains(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldContains(FieldTransactionGroupID, v)) +} + +// TransactionGroupIDHasPrefix applies the HasPrefix predicate on the "transaction_group_id" field. +func TransactionGroupIDHasPrefix(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldHasPrefix(FieldTransactionGroupID, v)) +} + +// TransactionGroupIDHasSuffix applies the HasSuffix predicate on the "transaction_group_id" field. +func TransactionGroupIDHasSuffix(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldHasSuffix(FieldTransactionGroupID, v)) +} + +// TransactionGroupIDEqualFold applies the EqualFold predicate on the "transaction_group_id" field. +func TransactionGroupIDEqualFold(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldEqualFold(FieldTransactionGroupID, v)) +} + +// TransactionGroupIDContainsFold applies the ContainsFold predicate on the "transaction_group_id" field. +func TransactionGroupIDContainsFold(v string) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldContainsFold(FieldTransactionGroupID, v)) +} + +// GrantedAtEQ applies the EQ predicate on the "granted_at" field. +func GrantedAtEQ(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldEQ(FieldGrantedAt, v)) +} + +// GrantedAtNEQ applies the NEQ predicate on the "granted_at" field. +func GrantedAtNEQ(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldNEQ(FieldGrantedAt, v)) +} + +// GrantedAtIn applies the In predicate on the "granted_at" field. +func GrantedAtIn(vs ...time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldIn(FieldGrantedAt, vs...)) +} + +// GrantedAtNotIn applies the NotIn predicate on the "granted_at" field. +func GrantedAtNotIn(vs ...time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldNotIn(FieldGrantedAt, vs...)) +} + +// GrantedAtGT applies the GT predicate on the "granted_at" field. +func GrantedAtGT(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldGT(FieldGrantedAt, v)) +} + +// GrantedAtGTE applies the GTE predicate on the "granted_at" field. +func GrantedAtGTE(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldGTE(FieldGrantedAt, v)) +} + +// GrantedAtLT applies the LT predicate on the "granted_at" field. +func GrantedAtLT(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldLT(FieldGrantedAt, v)) +} + +// GrantedAtLTE applies the LTE predicate on the "granted_at" field. +func GrantedAtLTE(v time.Time) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.FieldLTE(FieldGrantedAt, v)) +} + +// HasCreditPurchase applies the HasEdge predicate on the "credit_purchase" edge. +func HasCreditPurchase() predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, CreditPurchaseTable, CreditPurchaseColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCreditPurchaseWith applies the HasEdge predicate on the "credit_purchase" edge with a given conditions (other predicates). +func HasCreditPurchaseWith(preds ...predicate.ChargeCreditPurchase) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(func(s *sql.Selector) { + step := newCreditPurchaseStep() + 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.ChargeCreditPurchaseCreditGrant) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ChargeCreditPurchaseCreditGrant) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ChargeCreditPurchaseCreditGrant) predicate.ChargeCreditPurchaseCreditGrant { + return predicate.ChargeCreditPurchaseCreditGrant(sql.NotPredicates(p)) +} diff --git a/ent/db/chargecreditpurchasecreditgrant_create.go b/ent/db/chargecreditpurchasecreditgrant_create.go new file mode 100644 index 0000000000000000000000000000000000000000..3b20c6808e29746f042e7889e2eb189f6a95f433 --- /dev/null +++ b/ent/db/chargecreditpurchasecreditgrant_create.go @@ -0,0 +1,811 @@ +// 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/chargecreditpurchase" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchasecreditgrant" +) + +// ChargeCreditPurchaseCreditGrantCreate is the builder for creating a ChargeCreditPurchaseCreditGrant entity. +type ChargeCreditPurchaseCreditGrantCreate struct { + config + mutation *ChargeCreditPurchaseCreditGrantMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *ChargeCreditPurchaseCreditGrantCreate) SetNamespace(v string) *ChargeCreditPurchaseCreditGrantCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ChargeCreditPurchaseCreditGrantCreate) SetCreatedAt(v time.Time) *ChargeCreditPurchaseCreditGrantCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *ChargeCreditPurchaseCreditGrantCreate) SetNillableCreatedAt(v *time.Time) *ChargeCreditPurchaseCreditGrantCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *ChargeCreditPurchaseCreditGrantCreate) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseCreditGrantCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *ChargeCreditPurchaseCreditGrantCreate) SetNillableUpdatedAt(v *time.Time) *ChargeCreditPurchaseCreditGrantCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *ChargeCreditPurchaseCreditGrantCreate) SetDeletedAt(v time.Time) *ChargeCreditPurchaseCreditGrantCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *ChargeCreditPurchaseCreditGrantCreate) SetNillableDeletedAt(v *time.Time) *ChargeCreditPurchaseCreditGrantCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetChargeID sets the "charge_id" field. +func (_c *ChargeCreditPurchaseCreditGrantCreate) SetChargeID(v string) *ChargeCreditPurchaseCreditGrantCreate { + _c.mutation.SetChargeID(v) + return _c +} + +// SetTransactionGroupID sets the "transaction_group_id" field. +func (_c *ChargeCreditPurchaseCreditGrantCreate) SetTransactionGroupID(v string) *ChargeCreditPurchaseCreditGrantCreate { + _c.mutation.SetTransactionGroupID(v) + return _c +} + +// SetGrantedAt sets the "granted_at" field. +func (_c *ChargeCreditPurchaseCreditGrantCreate) SetGrantedAt(v time.Time) *ChargeCreditPurchaseCreditGrantCreate { + _c.mutation.SetGrantedAt(v) + return _c +} + +// SetID sets the "id" field. +func (_c *ChargeCreditPurchaseCreditGrantCreate) SetID(v string) *ChargeCreditPurchaseCreditGrantCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ChargeCreditPurchaseCreditGrantCreate) SetNillableID(v *string) *ChargeCreditPurchaseCreditGrantCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetCreditPurchaseID sets the "credit_purchase" edge to the ChargeCreditPurchase entity by ID. +func (_c *ChargeCreditPurchaseCreditGrantCreate) SetCreditPurchaseID(id string) *ChargeCreditPurchaseCreditGrantCreate { + _c.mutation.SetCreditPurchaseID(id) + return _c +} + +// SetCreditPurchase sets the "credit_purchase" edge to the ChargeCreditPurchase entity. +func (_c *ChargeCreditPurchaseCreditGrantCreate) SetCreditPurchase(v *ChargeCreditPurchase) *ChargeCreditPurchaseCreditGrantCreate { + return _c.SetCreditPurchaseID(v.ID) +} + +// Mutation returns the ChargeCreditPurchaseCreditGrantMutation object of the builder. +func (_c *ChargeCreditPurchaseCreditGrantCreate) Mutation() *ChargeCreditPurchaseCreditGrantMutation { + return _c.mutation +} + +// Save creates the ChargeCreditPurchaseCreditGrant in the database. +func (_c *ChargeCreditPurchaseCreditGrantCreate) Save(ctx context.Context) (*ChargeCreditPurchaseCreditGrant, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ChargeCreditPurchaseCreditGrantCreate) SaveX(ctx context.Context) *ChargeCreditPurchaseCreditGrant { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeCreditPurchaseCreditGrantCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeCreditPurchaseCreditGrantCreate) 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 *ChargeCreditPurchaseCreditGrantCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := chargecreditpurchasecreditgrant.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := chargecreditpurchasecreditgrant.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := chargecreditpurchasecreditgrant.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ChargeCreditPurchaseCreditGrantCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "ChargeCreditPurchaseCreditGrant.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := chargecreditpurchasecreditgrant.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseCreditGrant.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "ChargeCreditPurchaseCreditGrant.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "ChargeCreditPurchaseCreditGrant.updated_at"`)} + } + if _, ok := _c.mutation.ChargeID(); !ok { + return &ValidationError{Name: "charge_id", err: errors.New(`db: missing required field "ChargeCreditPurchaseCreditGrant.charge_id"`)} + } + if _, ok := _c.mutation.TransactionGroupID(); !ok { + return &ValidationError{Name: "transaction_group_id", err: errors.New(`db: missing required field "ChargeCreditPurchaseCreditGrant.transaction_group_id"`)} + } + if v, ok := _c.mutation.TransactionGroupID(); ok { + if err := chargecreditpurchasecreditgrant.TransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseCreditGrant.transaction_group_id": %w`, err)} + } + } + if _, ok := _c.mutation.GrantedAt(); !ok { + return &ValidationError{Name: "granted_at", err: errors.New(`db: missing required field "ChargeCreditPurchaseCreditGrant.granted_at"`)} + } + if len(_c.mutation.CreditPurchaseIDs()) == 0 { + return &ValidationError{Name: "credit_purchase", err: errors.New(`db: missing required edge "ChargeCreditPurchaseCreditGrant.credit_purchase"`)} + } + return nil +} + +func (_c *ChargeCreditPurchaseCreditGrantCreate) sqlSave(ctx context.Context) (*ChargeCreditPurchaseCreditGrant, 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 ChargeCreditPurchaseCreditGrant.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ChargeCreditPurchaseCreditGrantCreate) createSpec() (*ChargeCreditPurchaseCreditGrant, *sqlgraph.CreateSpec) { + var ( + _node = &ChargeCreditPurchaseCreditGrant{config: _c.config} + _spec = sqlgraph.NewCreateSpec(chargecreditpurchasecreditgrant.Table, sqlgraph.NewFieldSpec(chargecreditpurchasecreditgrant.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(chargecreditpurchasecreditgrant.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(chargecreditpurchasecreditgrant.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(chargecreditpurchasecreditgrant.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(chargecreditpurchasecreditgrant.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.TransactionGroupID(); ok { + _spec.SetField(chargecreditpurchasecreditgrant.FieldTransactionGroupID, field.TypeString, value) + _node.TransactionGroupID = value + } + if value, ok := _c.mutation.GrantedAt(); ok { + _spec.SetField(chargecreditpurchasecreditgrant.FieldGrantedAt, field.TypeTime, value) + _node.GrantedAt = value + } + if nodes := _c.mutation.CreditPurchaseIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargecreditpurchasecreditgrant.CreditPurchaseTable, + Columns: []string{chargecreditpurchasecreditgrant.CreditPurchaseColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchase.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) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ChargeCreditPurchaseCreditGrant.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.ChargeCreditPurchaseCreditGrantUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *ChargeCreditPurchaseCreditGrantCreate) OnConflict(opts ...sql.ConflictOption) *ChargeCreditPurchaseCreditGrantUpsertOne { + _c.conflict = opts + return &ChargeCreditPurchaseCreditGrantUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeCreditPurchaseCreditGrant.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeCreditPurchaseCreditGrantCreate) OnConflictColumns(columns ...string) *ChargeCreditPurchaseCreditGrantUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeCreditPurchaseCreditGrantUpsertOne{ + create: _c, + } +} + +type ( + // ChargeCreditPurchaseCreditGrantUpsertOne is the builder for "upsert"-ing + // one ChargeCreditPurchaseCreditGrant node. + ChargeCreditPurchaseCreditGrantUpsertOne struct { + create *ChargeCreditPurchaseCreditGrantCreate + } + + // ChargeCreditPurchaseCreditGrantUpsert is the "OnConflict" setter. + ChargeCreditPurchaseCreditGrantUpsert struct { + *sql.UpdateSet + } +) + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeCreditPurchaseCreditGrantUpsert) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseCreditGrantUpsert { + u.Set(chargecreditpurchasecreditgrant.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseCreditGrantUpsert) UpdateUpdatedAt() *ChargeCreditPurchaseCreditGrantUpsert { + u.SetExcluded(chargecreditpurchasecreditgrant.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeCreditPurchaseCreditGrantUpsert) SetDeletedAt(v time.Time) *ChargeCreditPurchaseCreditGrantUpsert { + u.Set(chargecreditpurchasecreditgrant.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseCreditGrantUpsert) UpdateDeletedAt() *ChargeCreditPurchaseCreditGrantUpsert { + u.SetExcluded(chargecreditpurchasecreditgrant.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeCreditPurchaseCreditGrantUpsert) ClearDeletedAt() *ChargeCreditPurchaseCreditGrantUpsert { + u.SetNull(chargecreditpurchasecreditgrant.FieldDeletedAt) + return u +} + +// SetTransactionGroupID sets the "transaction_group_id" field. +func (u *ChargeCreditPurchaseCreditGrantUpsert) SetTransactionGroupID(v string) *ChargeCreditPurchaseCreditGrantUpsert { + u.Set(chargecreditpurchasecreditgrant.FieldTransactionGroupID, v) + return u +} + +// UpdateTransactionGroupID sets the "transaction_group_id" field to the value that was provided on create. +func (u *ChargeCreditPurchaseCreditGrantUpsert) UpdateTransactionGroupID() *ChargeCreditPurchaseCreditGrantUpsert { + u.SetExcluded(chargecreditpurchasecreditgrant.FieldTransactionGroupID) + return u +} + +// SetGrantedAt sets the "granted_at" field. +func (u *ChargeCreditPurchaseCreditGrantUpsert) SetGrantedAt(v time.Time) *ChargeCreditPurchaseCreditGrantUpsert { + u.Set(chargecreditpurchasecreditgrant.FieldGrantedAt, v) + return u +} + +// UpdateGrantedAt sets the "granted_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseCreditGrantUpsert) UpdateGrantedAt() *ChargeCreditPurchaseCreditGrantUpsert { + u.SetExcluded(chargecreditpurchasecreditgrant.FieldGrantedAt) + 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.ChargeCreditPurchaseCreditGrant.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargecreditpurchasecreditgrant.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeCreditPurchaseCreditGrantUpsertOne) UpdateNewValues() *ChargeCreditPurchaseCreditGrantUpsertOne { + 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(chargecreditpurchasecreditgrant.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(chargecreditpurchasecreditgrant.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(chargecreditpurchasecreditgrant.FieldCreatedAt) + } + if _, exists := u.create.mutation.ChargeID(); exists { + s.SetIgnore(chargecreditpurchasecreditgrant.FieldChargeID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeCreditPurchaseCreditGrant.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeCreditPurchaseCreditGrantUpsertOne) Ignore() *ChargeCreditPurchaseCreditGrantUpsertOne { + 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 *ChargeCreditPurchaseCreditGrantUpsertOne) DoNothing() *ChargeCreditPurchaseCreditGrantUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeCreditPurchaseCreditGrantCreate.OnConflict +// documentation for more info. +func (u *ChargeCreditPurchaseCreditGrantUpsertOne) Update(set func(*ChargeCreditPurchaseCreditGrantUpsert)) *ChargeCreditPurchaseCreditGrantUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeCreditPurchaseCreditGrantUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeCreditPurchaseCreditGrantUpsertOne) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseCreditGrantUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseCreditGrantUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseCreditGrantUpsertOne) UpdateUpdatedAt() *ChargeCreditPurchaseCreditGrantUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseCreditGrantUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeCreditPurchaseCreditGrantUpsertOne) SetDeletedAt(v time.Time) *ChargeCreditPurchaseCreditGrantUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseCreditGrantUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseCreditGrantUpsertOne) UpdateDeletedAt() *ChargeCreditPurchaseCreditGrantUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseCreditGrantUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeCreditPurchaseCreditGrantUpsertOne) ClearDeletedAt() *ChargeCreditPurchaseCreditGrantUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseCreditGrantUpsert) { + s.ClearDeletedAt() + }) +} + +// SetTransactionGroupID sets the "transaction_group_id" field. +func (u *ChargeCreditPurchaseCreditGrantUpsertOne) SetTransactionGroupID(v string) *ChargeCreditPurchaseCreditGrantUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseCreditGrantUpsert) { + s.SetTransactionGroupID(v) + }) +} + +// UpdateTransactionGroupID sets the "transaction_group_id" field to the value that was provided on create. +func (u *ChargeCreditPurchaseCreditGrantUpsertOne) UpdateTransactionGroupID() *ChargeCreditPurchaseCreditGrantUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseCreditGrantUpsert) { + s.UpdateTransactionGroupID() + }) +} + +// SetGrantedAt sets the "granted_at" field. +func (u *ChargeCreditPurchaseCreditGrantUpsertOne) SetGrantedAt(v time.Time) *ChargeCreditPurchaseCreditGrantUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseCreditGrantUpsert) { + s.SetGrantedAt(v) + }) +} + +// UpdateGrantedAt sets the "granted_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseCreditGrantUpsertOne) UpdateGrantedAt() *ChargeCreditPurchaseCreditGrantUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseCreditGrantUpsert) { + s.UpdateGrantedAt() + }) +} + +// Exec executes the query. +func (u *ChargeCreditPurchaseCreditGrantUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeCreditPurchaseCreditGrantCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeCreditPurchaseCreditGrantUpsertOne) 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 *ChargeCreditPurchaseCreditGrantUpsertOne) 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: ChargeCreditPurchaseCreditGrantUpsertOne.ID is not supported by MySQL driver. Use ChargeCreditPurchaseCreditGrantUpsertOne.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 *ChargeCreditPurchaseCreditGrantUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ChargeCreditPurchaseCreditGrantCreateBulk is the builder for creating many ChargeCreditPurchaseCreditGrant entities in bulk. +type ChargeCreditPurchaseCreditGrantCreateBulk struct { + config + err error + builders []*ChargeCreditPurchaseCreditGrantCreate + conflict []sql.ConflictOption +} + +// Save creates the ChargeCreditPurchaseCreditGrant entities in the database. +func (_c *ChargeCreditPurchaseCreditGrantCreateBulk) Save(ctx context.Context) ([]*ChargeCreditPurchaseCreditGrant, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ChargeCreditPurchaseCreditGrant, 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.(*ChargeCreditPurchaseCreditGrantMutation) + 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 *ChargeCreditPurchaseCreditGrantCreateBulk) SaveX(ctx context.Context) []*ChargeCreditPurchaseCreditGrant { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeCreditPurchaseCreditGrantCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeCreditPurchaseCreditGrantCreateBulk) 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.ChargeCreditPurchaseCreditGrant.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.ChargeCreditPurchaseCreditGrantUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *ChargeCreditPurchaseCreditGrantCreateBulk) OnConflict(opts ...sql.ConflictOption) *ChargeCreditPurchaseCreditGrantUpsertBulk { + _c.conflict = opts + return &ChargeCreditPurchaseCreditGrantUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeCreditPurchaseCreditGrant.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeCreditPurchaseCreditGrantCreateBulk) OnConflictColumns(columns ...string) *ChargeCreditPurchaseCreditGrantUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeCreditPurchaseCreditGrantUpsertBulk{ + create: _c, + } +} + +// ChargeCreditPurchaseCreditGrantUpsertBulk is the builder for "upsert"-ing +// a bulk of ChargeCreditPurchaseCreditGrant nodes. +type ChargeCreditPurchaseCreditGrantUpsertBulk struct { + create *ChargeCreditPurchaseCreditGrantCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ChargeCreditPurchaseCreditGrant.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargecreditpurchasecreditgrant.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeCreditPurchaseCreditGrantUpsertBulk) UpdateNewValues() *ChargeCreditPurchaseCreditGrantUpsertBulk { + 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(chargecreditpurchasecreditgrant.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(chargecreditpurchasecreditgrant.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(chargecreditpurchasecreditgrant.FieldCreatedAt) + } + if _, exists := b.mutation.ChargeID(); exists { + s.SetIgnore(chargecreditpurchasecreditgrant.FieldChargeID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeCreditPurchaseCreditGrant.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeCreditPurchaseCreditGrantUpsertBulk) Ignore() *ChargeCreditPurchaseCreditGrantUpsertBulk { + 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 *ChargeCreditPurchaseCreditGrantUpsertBulk) DoNothing() *ChargeCreditPurchaseCreditGrantUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeCreditPurchaseCreditGrantCreateBulk.OnConflict +// documentation for more info. +func (u *ChargeCreditPurchaseCreditGrantUpsertBulk) Update(set func(*ChargeCreditPurchaseCreditGrantUpsert)) *ChargeCreditPurchaseCreditGrantUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeCreditPurchaseCreditGrantUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeCreditPurchaseCreditGrantUpsertBulk) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseCreditGrantUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseCreditGrantUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseCreditGrantUpsertBulk) UpdateUpdatedAt() *ChargeCreditPurchaseCreditGrantUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseCreditGrantUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeCreditPurchaseCreditGrantUpsertBulk) SetDeletedAt(v time.Time) *ChargeCreditPurchaseCreditGrantUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseCreditGrantUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseCreditGrantUpsertBulk) UpdateDeletedAt() *ChargeCreditPurchaseCreditGrantUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseCreditGrantUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeCreditPurchaseCreditGrantUpsertBulk) ClearDeletedAt() *ChargeCreditPurchaseCreditGrantUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseCreditGrantUpsert) { + s.ClearDeletedAt() + }) +} + +// SetTransactionGroupID sets the "transaction_group_id" field. +func (u *ChargeCreditPurchaseCreditGrantUpsertBulk) SetTransactionGroupID(v string) *ChargeCreditPurchaseCreditGrantUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseCreditGrantUpsert) { + s.SetTransactionGroupID(v) + }) +} + +// UpdateTransactionGroupID sets the "transaction_group_id" field to the value that was provided on create. +func (u *ChargeCreditPurchaseCreditGrantUpsertBulk) UpdateTransactionGroupID() *ChargeCreditPurchaseCreditGrantUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseCreditGrantUpsert) { + s.UpdateTransactionGroupID() + }) +} + +// SetGrantedAt sets the "granted_at" field. +func (u *ChargeCreditPurchaseCreditGrantUpsertBulk) SetGrantedAt(v time.Time) *ChargeCreditPurchaseCreditGrantUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseCreditGrantUpsert) { + s.SetGrantedAt(v) + }) +} + +// UpdateGrantedAt sets the "granted_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseCreditGrantUpsertBulk) UpdateGrantedAt() *ChargeCreditPurchaseCreditGrantUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseCreditGrantUpsert) { + s.UpdateGrantedAt() + }) +} + +// Exec executes the query. +func (u *ChargeCreditPurchaseCreditGrantUpsertBulk) 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 ChargeCreditPurchaseCreditGrantCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeCreditPurchaseCreditGrantCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeCreditPurchaseCreditGrantUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargecreditpurchasecreditgrant_delete.go b/ent/db/chargecreditpurchasecreditgrant_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..29d82d5eaba990dbe63a9dda75ada5c534831e7e --- /dev/null +++ b/ent/db/chargecreditpurchasecreditgrant_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/chargecreditpurchasecreditgrant" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeCreditPurchaseCreditGrantDelete is the builder for deleting a ChargeCreditPurchaseCreditGrant entity. +type ChargeCreditPurchaseCreditGrantDelete struct { + config + hooks []Hook + mutation *ChargeCreditPurchaseCreditGrantMutation +} + +// Where appends a list predicates to the ChargeCreditPurchaseCreditGrantDelete builder. +func (_d *ChargeCreditPurchaseCreditGrantDelete) Where(ps ...predicate.ChargeCreditPurchaseCreditGrant) *ChargeCreditPurchaseCreditGrantDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ChargeCreditPurchaseCreditGrantDelete) 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 *ChargeCreditPurchaseCreditGrantDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ChargeCreditPurchaseCreditGrantDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(chargecreditpurchasecreditgrant.Table, sqlgraph.NewFieldSpec(chargecreditpurchasecreditgrant.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 +} + +// ChargeCreditPurchaseCreditGrantDeleteOne is the builder for deleting a single ChargeCreditPurchaseCreditGrant entity. +type ChargeCreditPurchaseCreditGrantDeleteOne struct { + _d *ChargeCreditPurchaseCreditGrantDelete +} + +// Where appends a list predicates to the ChargeCreditPurchaseCreditGrantDelete builder. +func (_d *ChargeCreditPurchaseCreditGrantDeleteOne) Where(ps ...predicate.ChargeCreditPurchaseCreditGrant) *ChargeCreditPurchaseCreditGrantDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ChargeCreditPurchaseCreditGrantDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{chargecreditpurchasecreditgrant.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeCreditPurchaseCreditGrantDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargecreditpurchasecreditgrant_query.go b/ent/db/chargecreditpurchasecreditgrant_query.go new file mode 100644 index 0000000000000000000000000000000000000000..de08ab3b1ecee3a7abe62b1ae9de901c7634c51b --- /dev/null +++ b/ent/db/chargecreditpurchasecreditgrant_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/chargecreditpurchase" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchasecreditgrant" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeCreditPurchaseCreditGrantQuery is the builder for querying ChargeCreditPurchaseCreditGrant entities. +type ChargeCreditPurchaseCreditGrantQuery struct { + config + ctx *QueryContext + order []chargecreditpurchasecreditgrant.OrderOption + inters []Interceptor + predicates []predicate.ChargeCreditPurchaseCreditGrant + withCreditPurchase *ChargeCreditPurchaseQuery + 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 ChargeCreditPurchaseCreditGrantQuery builder. +func (_q *ChargeCreditPurchaseCreditGrantQuery) Where(ps ...predicate.ChargeCreditPurchaseCreditGrant) *ChargeCreditPurchaseCreditGrantQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ChargeCreditPurchaseCreditGrantQuery) Limit(limit int) *ChargeCreditPurchaseCreditGrantQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ChargeCreditPurchaseCreditGrantQuery) Offset(offset int) *ChargeCreditPurchaseCreditGrantQuery { + _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 *ChargeCreditPurchaseCreditGrantQuery) Unique(unique bool) *ChargeCreditPurchaseCreditGrantQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ChargeCreditPurchaseCreditGrantQuery) Order(o ...chargecreditpurchasecreditgrant.OrderOption) *ChargeCreditPurchaseCreditGrantQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryCreditPurchase chains the current query on the "credit_purchase" edge. +func (_q *ChargeCreditPurchaseCreditGrantQuery) QueryCreditPurchase() *ChargeCreditPurchaseQuery { + query := (&ChargeCreditPurchaseClient{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(chargecreditpurchasecreditgrant.Table, chargecreditpurchasecreditgrant.FieldID, selector), + sqlgraph.To(chargecreditpurchase.Table, chargecreditpurchase.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargecreditpurchasecreditgrant.CreditPurchaseTable, chargecreditpurchasecreditgrant.CreditPurchaseColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ChargeCreditPurchaseCreditGrant entity from the query. +// Returns a *NotFoundError when no ChargeCreditPurchaseCreditGrant was found. +func (_q *ChargeCreditPurchaseCreditGrantQuery) First(ctx context.Context) (*ChargeCreditPurchaseCreditGrant, 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{chargecreditpurchasecreditgrant.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ChargeCreditPurchaseCreditGrantQuery) FirstX(ctx context.Context) *ChargeCreditPurchaseCreditGrant { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ChargeCreditPurchaseCreditGrant ID from the query. +// Returns a *NotFoundError when no ChargeCreditPurchaseCreditGrant ID was found. +func (_q *ChargeCreditPurchaseCreditGrantQuery) 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{chargecreditpurchasecreditgrant.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ChargeCreditPurchaseCreditGrantQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ChargeCreditPurchaseCreditGrant entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ChargeCreditPurchaseCreditGrant entity is found. +// Returns a *NotFoundError when no ChargeCreditPurchaseCreditGrant entities are found. +func (_q *ChargeCreditPurchaseCreditGrantQuery) Only(ctx context.Context) (*ChargeCreditPurchaseCreditGrant, 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{chargecreditpurchasecreditgrant.Label} + default: + return nil, &NotSingularError{chargecreditpurchasecreditgrant.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ChargeCreditPurchaseCreditGrantQuery) OnlyX(ctx context.Context) *ChargeCreditPurchaseCreditGrant { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ChargeCreditPurchaseCreditGrant ID in the query. +// Returns a *NotSingularError when more than one ChargeCreditPurchaseCreditGrant ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ChargeCreditPurchaseCreditGrantQuery) 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{chargecreditpurchasecreditgrant.Label} + default: + err = &NotSingularError{chargecreditpurchasecreditgrant.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ChargeCreditPurchaseCreditGrantQuery) 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 ChargeCreditPurchaseCreditGrants. +func (_q *ChargeCreditPurchaseCreditGrantQuery) All(ctx context.Context) ([]*ChargeCreditPurchaseCreditGrant, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ChargeCreditPurchaseCreditGrant, *ChargeCreditPurchaseCreditGrantQuery]() + return withInterceptors[[]*ChargeCreditPurchaseCreditGrant](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ChargeCreditPurchaseCreditGrantQuery) AllX(ctx context.Context) []*ChargeCreditPurchaseCreditGrant { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ChargeCreditPurchaseCreditGrant IDs. +func (_q *ChargeCreditPurchaseCreditGrantQuery) 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(chargecreditpurchasecreditgrant.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ChargeCreditPurchaseCreditGrantQuery) 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 *ChargeCreditPurchaseCreditGrantQuery) 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[*ChargeCreditPurchaseCreditGrantQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ChargeCreditPurchaseCreditGrantQuery) 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 *ChargeCreditPurchaseCreditGrantQuery) 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 *ChargeCreditPurchaseCreditGrantQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ChargeCreditPurchaseCreditGrantQuery 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 *ChargeCreditPurchaseCreditGrantQuery) Clone() *ChargeCreditPurchaseCreditGrantQuery { + if _q == nil { + return nil + } + return &ChargeCreditPurchaseCreditGrantQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]chargecreditpurchasecreditgrant.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ChargeCreditPurchaseCreditGrant{}, _q.predicates...), + withCreditPurchase: _q.withCreditPurchase.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithCreditPurchase tells the query-builder to eager-load the nodes that are connected to +// the "credit_purchase" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeCreditPurchaseCreditGrantQuery) WithCreditPurchase(opts ...func(*ChargeCreditPurchaseQuery)) *ChargeCreditPurchaseCreditGrantQuery { + query := (&ChargeCreditPurchaseClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCreditPurchase = 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.ChargeCreditPurchaseCreditGrant.Query(). +// GroupBy(chargecreditpurchasecreditgrant.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *ChargeCreditPurchaseCreditGrantQuery) GroupBy(field string, fields ...string) *ChargeCreditPurchaseCreditGrantGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ChargeCreditPurchaseCreditGrantGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = chargecreditpurchasecreditgrant.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.ChargeCreditPurchaseCreditGrant.Query(). +// Select(chargecreditpurchasecreditgrant.FieldNamespace). +// Scan(ctx, &v) +func (_q *ChargeCreditPurchaseCreditGrantQuery) Select(fields ...string) *ChargeCreditPurchaseCreditGrantSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ChargeCreditPurchaseCreditGrantSelect{ChargeCreditPurchaseCreditGrantQuery: _q} + sbuild.label = chargecreditpurchasecreditgrant.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ChargeCreditPurchaseCreditGrantSelect configured with the given aggregations. +func (_q *ChargeCreditPurchaseCreditGrantQuery) Aggregate(fns ...AggregateFunc) *ChargeCreditPurchaseCreditGrantSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ChargeCreditPurchaseCreditGrantQuery) 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 !chargecreditpurchasecreditgrant.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 *ChargeCreditPurchaseCreditGrantQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ChargeCreditPurchaseCreditGrant, error) { + var ( + nodes = []*ChargeCreditPurchaseCreditGrant{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withCreditPurchase != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ChargeCreditPurchaseCreditGrant).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ChargeCreditPurchaseCreditGrant{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.withCreditPurchase; query != nil { + if err := _q.loadCreditPurchase(ctx, query, nodes, nil, + func(n *ChargeCreditPurchaseCreditGrant, e *ChargeCreditPurchase) { n.Edges.CreditPurchase = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ChargeCreditPurchaseCreditGrantQuery) loadCreditPurchase(ctx context.Context, query *ChargeCreditPurchaseQuery, nodes []*ChargeCreditPurchaseCreditGrant, init func(*ChargeCreditPurchaseCreditGrant), assign func(*ChargeCreditPurchaseCreditGrant, *ChargeCreditPurchase)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeCreditPurchaseCreditGrant) + 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(chargecreditpurchase.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 *ChargeCreditPurchaseCreditGrantQuery) 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 *ChargeCreditPurchaseCreditGrantQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(chargecreditpurchasecreditgrant.Table, chargecreditpurchasecreditgrant.Columns, sqlgraph.NewFieldSpec(chargecreditpurchasecreditgrant.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, chargecreditpurchasecreditgrant.FieldID) + for i := range fields { + if fields[i] != chargecreditpurchasecreditgrant.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withCreditPurchase != nil { + _spec.Node.AddColumnOnce(chargecreditpurchasecreditgrant.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 *ChargeCreditPurchaseCreditGrantQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(chargecreditpurchasecreditgrant.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = chargecreditpurchasecreditgrant.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 *ChargeCreditPurchaseCreditGrantQuery) ForUpdate(opts ...sql.LockOption) *ChargeCreditPurchaseCreditGrantQuery { + 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 *ChargeCreditPurchaseCreditGrantQuery) ForShare(opts ...sql.LockOption) *ChargeCreditPurchaseCreditGrantQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ChargeCreditPurchaseCreditGrantGroupBy is the group-by builder for ChargeCreditPurchaseCreditGrant entities. +type ChargeCreditPurchaseCreditGrantGroupBy struct { + selector + build *ChargeCreditPurchaseCreditGrantQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ChargeCreditPurchaseCreditGrantGroupBy) Aggregate(fns ...AggregateFunc) *ChargeCreditPurchaseCreditGrantGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ChargeCreditPurchaseCreditGrantGroupBy) 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[*ChargeCreditPurchaseCreditGrantQuery, *ChargeCreditPurchaseCreditGrantGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ChargeCreditPurchaseCreditGrantGroupBy) sqlScan(ctx context.Context, root *ChargeCreditPurchaseCreditGrantQuery, 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) +} + +// ChargeCreditPurchaseCreditGrantSelect is the builder for selecting fields of ChargeCreditPurchaseCreditGrant entities. +type ChargeCreditPurchaseCreditGrantSelect struct { + *ChargeCreditPurchaseCreditGrantQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ChargeCreditPurchaseCreditGrantSelect) Aggregate(fns ...AggregateFunc) *ChargeCreditPurchaseCreditGrantSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ChargeCreditPurchaseCreditGrantSelect) 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[*ChargeCreditPurchaseCreditGrantQuery, *ChargeCreditPurchaseCreditGrantSelect](ctx, _s.ChargeCreditPurchaseCreditGrantQuery, _s, _s.inters, v) +} + +func (_s *ChargeCreditPurchaseCreditGrantSelect) sqlScan(ctx context.Context, root *ChargeCreditPurchaseCreditGrantQuery, 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/ent/db/chargecreditpurchasecreditgrant_update.go b/ent/db/chargecreditpurchasecreditgrant_update.go new file mode 100644 index 0000000000000000000000000000000000000000..63e76ae038e265a6c00dd91d2df89b60f1248f69 --- /dev/null +++ b/ent/db/chargecreditpurchasecreditgrant_update.go @@ -0,0 +1,364 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchasecreditgrant" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeCreditPurchaseCreditGrantUpdate is the builder for updating ChargeCreditPurchaseCreditGrant entities. +type ChargeCreditPurchaseCreditGrantUpdate struct { + config + hooks []Hook + mutation *ChargeCreditPurchaseCreditGrantMutation +} + +// Where appends a list predicates to the ChargeCreditPurchaseCreditGrantUpdate builder. +func (_u *ChargeCreditPurchaseCreditGrantUpdate) Where(ps ...predicate.ChargeCreditPurchaseCreditGrant) *ChargeCreditPurchaseCreditGrantUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeCreditPurchaseCreditGrantUpdate) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseCreditGrantUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeCreditPurchaseCreditGrantUpdate) SetDeletedAt(v time.Time) *ChargeCreditPurchaseCreditGrantUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeCreditPurchaseCreditGrantUpdate) SetNillableDeletedAt(v *time.Time) *ChargeCreditPurchaseCreditGrantUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeCreditPurchaseCreditGrantUpdate) ClearDeletedAt() *ChargeCreditPurchaseCreditGrantUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetTransactionGroupID sets the "transaction_group_id" field. +func (_u *ChargeCreditPurchaseCreditGrantUpdate) SetTransactionGroupID(v string) *ChargeCreditPurchaseCreditGrantUpdate { + _u.mutation.SetTransactionGroupID(v) + return _u +} + +// SetNillableTransactionGroupID sets the "transaction_group_id" field if the given value is not nil. +func (_u *ChargeCreditPurchaseCreditGrantUpdate) SetNillableTransactionGroupID(v *string) *ChargeCreditPurchaseCreditGrantUpdate { + if v != nil { + _u.SetTransactionGroupID(*v) + } + return _u +} + +// SetGrantedAt sets the "granted_at" field. +func (_u *ChargeCreditPurchaseCreditGrantUpdate) SetGrantedAt(v time.Time) *ChargeCreditPurchaseCreditGrantUpdate { + _u.mutation.SetGrantedAt(v) + return _u +} + +// SetNillableGrantedAt sets the "granted_at" field if the given value is not nil. +func (_u *ChargeCreditPurchaseCreditGrantUpdate) SetNillableGrantedAt(v *time.Time) *ChargeCreditPurchaseCreditGrantUpdate { + if v != nil { + _u.SetGrantedAt(*v) + } + return _u +} + +// Mutation returns the ChargeCreditPurchaseCreditGrantMutation object of the builder. +func (_u *ChargeCreditPurchaseCreditGrantUpdate) Mutation() *ChargeCreditPurchaseCreditGrantMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ChargeCreditPurchaseCreditGrantUpdate) 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 *ChargeCreditPurchaseCreditGrantUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ChargeCreditPurchaseCreditGrantUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeCreditPurchaseCreditGrantUpdate) 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 *ChargeCreditPurchaseCreditGrantUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargecreditpurchasecreditgrant.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeCreditPurchaseCreditGrantUpdate) check() error { + if v, ok := _u.mutation.TransactionGroupID(); ok { + if err := chargecreditpurchasecreditgrant.TransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseCreditGrant.transaction_group_id": %w`, err)} + } + } + if _u.mutation.CreditPurchaseCleared() && len(_u.mutation.CreditPurchaseIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeCreditPurchaseCreditGrant.credit_purchase"`) + } + return nil +} + +func (_u *ChargeCreditPurchaseCreditGrantUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargecreditpurchasecreditgrant.Table, chargecreditpurchasecreditgrant.Columns, sqlgraph.NewFieldSpec(chargecreditpurchasecreditgrant.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(chargecreditpurchasecreditgrant.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargecreditpurchasecreditgrant.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargecreditpurchasecreditgrant.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.TransactionGroupID(); ok { + _spec.SetField(chargecreditpurchasecreditgrant.FieldTransactionGroupID, field.TypeString, value) + } + if value, ok := _u.mutation.GrantedAt(); ok { + _spec.SetField(chargecreditpurchasecreditgrant.FieldGrantedAt, field.TypeTime, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{chargecreditpurchasecreditgrant.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ChargeCreditPurchaseCreditGrantUpdateOne is the builder for updating a single ChargeCreditPurchaseCreditGrant entity. +type ChargeCreditPurchaseCreditGrantUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ChargeCreditPurchaseCreditGrantMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeCreditPurchaseCreditGrantUpdateOne) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseCreditGrantUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeCreditPurchaseCreditGrantUpdateOne) SetDeletedAt(v time.Time) *ChargeCreditPurchaseCreditGrantUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeCreditPurchaseCreditGrantUpdateOne) SetNillableDeletedAt(v *time.Time) *ChargeCreditPurchaseCreditGrantUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeCreditPurchaseCreditGrantUpdateOne) ClearDeletedAt() *ChargeCreditPurchaseCreditGrantUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetTransactionGroupID sets the "transaction_group_id" field. +func (_u *ChargeCreditPurchaseCreditGrantUpdateOne) SetTransactionGroupID(v string) *ChargeCreditPurchaseCreditGrantUpdateOne { + _u.mutation.SetTransactionGroupID(v) + return _u +} + +// SetNillableTransactionGroupID sets the "transaction_group_id" field if the given value is not nil. +func (_u *ChargeCreditPurchaseCreditGrantUpdateOne) SetNillableTransactionGroupID(v *string) *ChargeCreditPurchaseCreditGrantUpdateOne { + if v != nil { + _u.SetTransactionGroupID(*v) + } + return _u +} + +// SetGrantedAt sets the "granted_at" field. +func (_u *ChargeCreditPurchaseCreditGrantUpdateOne) SetGrantedAt(v time.Time) *ChargeCreditPurchaseCreditGrantUpdateOne { + _u.mutation.SetGrantedAt(v) + return _u +} + +// SetNillableGrantedAt sets the "granted_at" field if the given value is not nil. +func (_u *ChargeCreditPurchaseCreditGrantUpdateOne) SetNillableGrantedAt(v *time.Time) *ChargeCreditPurchaseCreditGrantUpdateOne { + if v != nil { + _u.SetGrantedAt(*v) + } + return _u +} + +// Mutation returns the ChargeCreditPurchaseCreditGrantMutation object of the builder. +func (_u *ChargeCreditPurchaseCreditGrantUpdateOne) Mutation() *ChargeCreditPurchaseCreditGrantMutation { + return _u.mutation +} + +// Where appends a list predicates to the ChargeCreditPurchaseCreditGrantUpdate builder. +func (_u *ChargeCreditPurchaseCreditGrantUpdateOne) Where(ps ...predicate.ChargeCreditPurchaseCreditGrant) *ChargeCreditPurchaseCreditGrantUpdateOne { + _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 *ChargeCreditPurchaseCreditGrantUpdateOne) Select(field string, fields ...string) *ChargeCreditPurchaseCreditGrantUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ChargeCreditPurchaseCreditGrant entity. +func (_u *ChargeCreditPurchaseCreditGrantUpdateOne) Save(ctx context.Context) (*ChargeCreditPurchaseCreditGrant, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeCreditPurchaseCreditGrantUpdateOne) SaveX(ctx context.Context) *ChargeCreditPurchaseCreditGrant { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ChargeCreditPurchaseCreditGrantUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeCreditPurchaseCreditGrantUpdateOne) 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 *ChargeCreditPurchaseCreditGrantUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargecreditpurchasecreditgrant.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeCreditPurchaseCreditGrantUpdateOne) check() error { + if v, ok := _u.mutation.TransactionGroupID(); ok { + if err := chargecreditpurchasecreditgrant.TransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseCreditGrant.transaction_group_id": %w`, err)} + } + } + if _u.mutation.CreditPurchaseCleared() && len(_u.mutation.CreditPurchaseIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeCreditPurchaseCreditGrant.credit_purchase"`) + } + return nil +} + +func (_u *ChargeCreditPurchaseCreditGrantUpdateOne) sqlSave(ctx context.Context) (_node *ChargeCreditPurchaseCreditGrant, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargecreditpurchasecreditgrant.Table, chargecreditpurchasecreditgrant.Columns, sqlgraph.NewFieldSpec(chargecreditpurchasecreditgrant.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "ChargeCreditPurchaseCreditGrant.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, chargecreditpurchasecreditgrant.FieldID) + for _, f := range fields { + if !chargecreditpurchasecreditgrant.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != chargecreditpurchasecreditgrant.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(chargecreditpurchasecreditgrant.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargecreditpurchasecreditgrant.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargecreditpurchasecreditgrant.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.TransactionGroupID(); ok { + _spec.SetField(chargecreditpurchasecreditgrant.FieldTransactionGroupID, field.TypeString, value) + } + if value, ok := _u.mutation.GrantedAt(); ok { + _spec.SetField(chargecreditpurchasecreditgrant.FieldGrantedAt, field.TypeTime, value) + } + _node = &ChargeCreditPurchaseCreditGrant{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{chargecreditpurchasecreditgrant.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/ent/db/chargecreditpurchaseexternalpayment.go b/ent/db/chargecreditpurchaseexternalpayment.go new file mode 100644 index 0000000000000000000000000000000000000000..82c4b5ae750b3199e34089904caf71d0b3fd5c8d --- /dev/null +++ b/ent/db/chargecreditpurchaseexternalpayment.go @@ -0,0 +1,301 @@ +// 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/chargecreditpurchase" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchaseexternalpayment" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeCreditPurchaseExternalPayment is the model entity for the ChargeCreditPurchaseExternalPayment schema. +type ChargeCreditPurchaseExternalPayment struct { + config `json:"-"` + // ID of the ent. + ID string `json:"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"` + // ChargeID holds the value of the "charge_id" field. + ChargeID string `json:"charge_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ChargeCreditPurchaseExternalPaymentQuery when eager-loading is set. + Edges ChargeCreditPurchaseExternalPaymentEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ChargeCreditPurchaseExternalPaymentEdges holds the relations/edges for other nodes in the graph. +type ChargeCreditPurchaseExternalPaymentEdges struct { + // CreditPurchase holds the value of the credit_purchase edge. + CreditPurchase *ChargeCreditPurchase `json:"credit_purchase,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// CreditPurchaseOrErr returns the CreditPurchase value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeCreditPurchaseExternalPaymentEdges) CreditPurchaseOrErr() (*ChargeCreditPurchase, error) { + if e.CreditPurchase != nil { + return e.CreditPurchase, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: chargecreditpurchase.Label} + } + return nil, &NotLoadedError{edge: "credit_purchase"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ChargeCreditPurchaseExternalPayment) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case chargecreditpurchaseexternalpayment.FieldAnnotations: + values[i] = new([]byte) + case chargecreditpurchaseexternalpayment.FieldAmount: + values[i] = new(alpacadecimal.Decimal) + case chargecreditpurchaseexternalpayment.FieldID, chargecreditpurchaseexternalpayment.FieldStatus, chargecreditpurchaseexternalpayment.FieldAuthorizedTransactionGroupID, chargecreditpurchaseexternalpayment.FieldSettledTransactionGroupID, chargecreditpurchaseexternalpayment.FieldNamespace, chargecreditpurchaseexternalpayment.FieldChargeID: + values[i] = new(sql.NullString) + case chargecreditpurchaseexternalpayment.FieldServicePeriodFrom, chargecreditpurchaseexternalpayment.FieldServicePeriodTo, chargecreditpurchaseexternalpayment.FieldAuthorizedAt, chargecreditpurchaseexternalpayment.FieldSettledAt, chargecreditpurchaseexternalpayment.FieldCreatedAt, chargecreditpurchaseexternalpayment.FieldUpdatedAt, chargecreditpurchaseexternalpayment.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 ChargeCreditPurchaseExternalPayment fields. +func (_m *ChargeCreditPurchaseExternalPayment) 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 chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.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 + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the ChargeCreditPurchaseExternalPayment. +// This includes values selected through modifiers, order, etc. +func (_m *ChargeCreditPurchaseExternalPayment) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryCreditPurchase queries the "credit_purchase" edge of the ChargeCreditPurchaseExternalPayment entity. +func (_m *ChargeCreditPurchaseExternalPayment) QueryCreditPurchase() *ChargeCreditPurchaseQuery { + return NewChargeCreditPurchaseExternalPaymentClient(_m.config).QueryCreditPurchase(_m) +} + +// Update returns a builder for updating this ChargeCreditPurchaseExternalPayment. +// Note that you need to call ChargeCreditPurchaseExternalPayment.Unwrap() before calling this method if this ChargeCreditPurchaseExternalPayment +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ChargeCreditPurchaseExternalPayment) Update() *ChargeCreditPurchaseExternalPaymentUpdateOne { + return NewChargeCreditPurchaseExternalPaymentClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ChargeCreditPurchaseExternalPayment 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 *ChargeCreditPurchaseExternalPayment) Unwrap() *ChargeCreditPurchaseExternalPayment { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: ChargeCreditPurchaseExternalPayment is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ChargeCreditPurchaseExternalPayment) String() string { + var builder strings.Builder + builder.WriteString("ChargeCreditPurchaseExternalPayment(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + 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("charge_id=") + builder.WriteString(_m.ChargeID) + builder.WriteByte(')') + return builder.String() +} + +// ChargeCreditPurchaseExternalPayments is a parsable slice of ChargeCreditPurchaseExternalPayment. +type ChargeCreditPurchaseExternalPayments []*ChargeCreditPurchaseExternalPayment diff --git a/ent/db/chargecreditpurchaseexternalpayment/chargecreditpurchaseexternalpayment.go b/ent/db/chargecreditpurchaseexternalpayment/chargecreditpurchaseexternalpayment.go new file mode 100644 index 0000000000000000000000000000000000000000..c4b02c2c3fa148987f1c4020c25842946208e9a2 --- /dev/null +++ b/ent/db/chargecreditpurchaseexternalpayment/chargecreditpurchaseexternalpayment.go @@ -0,0 +1,201 @@ +// Code generated by ent, DO NOT EDIT. + +package chargecreditpurchaseexternalpayment + +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 chargecreditpurchaseexternalpayment type in the database. + Label = "charge_credit_purchase_external_payment" + // FieldID holds the string denoting the id field in the database. + FieldID = "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" + // FieldChargeID holds the string denoting the charge_id field in the database. + FieldChargeID = "charge_id" + // EdgeCreditPurchase holds the string denoting the credit_purchase edge name in mutations. + EdgeCreditPurchase = "credit_purchase" + // Table holds the table name of the chargecreditpurchaseexternalpayment in the database. + Table = "charge_credit_purchase_external_payments" + // CreditPurchaseTable is the table that holds the credit_purchase relation/edge. + CreditPurchaseTable = "charge_credit_purchase_external_payments" + // CreditPurchaseInverseTable is the table name for the ChargeCreditPurchase entity. + // It exists in this package in order to avoid circular dependency with the "chargecreditpurchase" package. + CreditPurchaseInverseTable = "charge_credit_purchases" + // CreditPurchaseColumn is the table column denoting the credit_purchase relation/edge. + CreditPurchaseColumn = "charge_id" +) + +// Columns holds all SQL columns for chargecreditpurchaseexternalpayment fields. +var Columns = []string{ + FieldID, + FieldServicePeriodFrom, + FieldServicePeriodTo, + FieldStatus, + FieldAmount, + FieldAuthorizedTransactionGroupID, + FieldAuthorizedAt, + FieldSettledTransactionGroupID, + FieldSettledAt, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldAnnotations, + FieldChargeID, +} + +// 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("chargecreditpurchaseexternalpayment: invalid enum value for status field: %q", s) + } +} + +// OrderOption defines the ordering options for the ChargeCreditPurchaseExternalPayment 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() +} + +// 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() +} + +// ByChargeID orders the results by the charge_id field. +func ByChargeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChargeID, opts...).ToFunc() +} + +// ByCreditPurchaseField orders the results by credit_purchase field. +func ByCreditPurchaseField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCreditPurchaseStep(), sql.OrderByField(field, opts...)) + } +} +func newCreditPurchaseStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CreditPurchaseInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, CreditPurchaseTable, CreditPurchaseColumn), + ) +} diff --git a/ent/db/chargecreditpurchaseexternalpayment/where.go b/ent/db/chargecreditpurchaseexternalpayment/where.go new file mode 100644 index 0000000000000000000000000000000000000000..b9033d59d4700a400021923d67eb113ad2e61326 --- /dev/null +++ b/ent/db/chargecreditpurchaseexternalpayment/where.go @@ -0,0 +1,836 @@ +// Code generated by ent, DO NOT EDIT. + +package chargecreditpurchaseexternalpayment + +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.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldContainsFold(FieldID, id)) +} + +// ServicePeriodFrom applies equality check predicate on the "service_period_from" field. It's identical to ServicePeriodFromEQ. +func ServicePeriodFrom(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(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.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ. +func Amount(v alpacadecimal.Decimal) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(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.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(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.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(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.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(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.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEQ(FieldSettledAt, v)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(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.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(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.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(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.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEQ(FieldDeletedAt, v)) +} + +// ChargeID applies equality check predicate on the "charge_id" field. It's identical to ChargeIDEQ. +func ChargeID(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEQ(FieldChargeID, v)) +} + +// ServicePeriodFromEQ applies the EQ predicate on the "service_period_from" field. +func ServicePeriodFromEQ(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromNEQ applies the NEQ predicate on the "service_period_from" field. +func ServicePeriodFromNEQ(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromIn applies the In predicate on the "service_period_from" field. +func ServicePeriodFromIn(vs ...time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromNotIn applies the NotIn predicate on the "service_period_from" field. +func ServicePeriodFromNotIn(vs ...time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNotIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromGT applies the GT predicate on the "service_period_from" field. +func ServicePeriodFromGT(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromGTE applies the GTE predicate on the "service_period_from" field. +func ServicePeriodFromGTE(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLT applies the LT predicate on the "service_period_from" field. +func ServicePeriodFromLT(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLTE applies the LTE predicate on the "service_period_from" field. +func ServicePeriodFromLTE(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodToEQ applies the EQ predicate on the "service_period_to" field. +func ServicePeriodToEQ(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToNEQ applies the NEQ predicate on the "service_period_to" field. +func ServicePeriodToNEQ(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToIn applies the In predicate on the "service_period_to" field. +func ServicePeriodToIn(vs ...time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToNotIn applies the NotIn predicate on the "service_period_to" field. +func ServicePeriodToNotIn(vs ...time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNotIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToGT applies the GT predicate on the "service_period_to" field. +func ServicePeriodToGT(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToGTE applies the GTE predicate on the "service_period_to" field. +func ServicePeriodToGTE(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGTE(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLT applies the LT predicate on the "service_period_to" field. +func ServicePeriodToLT(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLTE applies the LTE predicate on the "service_period_to" field. +func ServicePeriodToLTE(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLTE(FieldServicePeriodTo, v)) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v payment.Status) predicate.ChargeCreditPurchaseExternalPayment { + vc := v + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEQ(FieldStatus, vc)) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v payment.Status) predicate.ChargeCreditPurchaseExternalPayment { + vc := v + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNEQ(FieldStatus, vc)) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...payment.Status) predicate.ChargeCreditPurchaseExternalPayment { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldIn(FieldStatus, v...)) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...payment.Status) predicate.ChargeCreditPurchaseExternalPayment { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNotIn(FieldStatus, v...)) +} + +// AmountEQ applies the EQ predicate on the "amount" field. +func AmountEQ(v alpacadecimal.Decimal) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEQ(FieldAmount, v)) +} + +// AmountNEQ applies the NEQ predicate on the "amount" field. +func AmountNEQ(v alpacadecimal.Decimal) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNEQ(FieldAmount, v)) +} + +// AmountIn applies the In predicate on the "amount" field. +func AmountIn(vs ...alpacadecimal.Decimal) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldIn(FieldAmount, vs...)) +} + +// AmountNotIn applies the NotIn predicate on the "amount" field. +func AmountNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNotIn(FieldAmount, vs...)) +} + +// AmountGT applies the GT predicate on the "amount" field. +func AmountGT(v alpacadecimal.Decimal) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGT(FieldAmount, v)) +} + +// AmountGTE applies the GTE predicate on the "amount" field. +func AmountGTE(v alpacadecimal.Decimal) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGTE(FieldAmount, v)) +} + +// AmountLT applies the LT predicate on the "amount" field. +func AmountLT(v alpacadecimal.Decimal) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLT(FieldAmount, v)) +} + +// AmountLTE applies the LTE predicate on the "amount" field. +func AmountLTE(v alpacadecimal.Decimal) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLTE(FieldAmount, v)) +} + +// AuthorizedTransactionGroupIDEQ applies the EQ predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDEQ(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEQ(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDNEQ applies the NEQ predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDNEQ(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNEQ(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDIn applies the In predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDIn(vs ...string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldIn(FieldAuthorizedTransactionGroupID, vs...)) +} + +// AuthorizedTransactionGroupIDNotIn applies the NotIn predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDNotIn(vs ...string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNotIn(FieldAuthorizedTransactionGroupID, vs...)) +} + +// AuthorizedTransactionGroupIDGT applies the GT predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDGT(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGT(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDGTE applies the GTE predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDGTE(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGTE(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDLT applies the LT predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDLT(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLT(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDLTE applies the LTE predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDLTE(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLTE(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDContains applies the Contains predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDContains(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldContains(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDHasPrefix applies the HasPrefix predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDHasPrefix(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldHasPrefix(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDHasSuffix applies the HasSuffix predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDHasSuffix(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldHasSuffix(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDIsNil applies the IsNil predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDIsNil() predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldIsNull(FieldAuthorizedTransactionGroupID)) +} + +// AuthorizedTransactionGroupIDNotNil applies the NotNil predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDNotNil() predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNotNull(FieldAuthorizedTransactionGroupID)) +} + +// AuthorizedTransactionGroupIDEqualFold applies the EqualFold predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDEqualFold(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEqualFold(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDContainsFold applies the ContainsFold predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDContainsFold(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldContainsFold(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedAtEQ applies the EQ predicate on the "authorized_at" field. +func AuthorizedAtEQ(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEQ(FieldAuthorizedAt, v)) +} + +// AuthorizedAtNEQ applies the NEQ predicate on the "authorized_at" field. +func AuthorizedAtNEQ(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNEQ(FieldAuthorizedAt, v)) +} + +// AuthorizedAtIn applies the In predicate on the "authorized_at" field. +func AuthorizedAtIn(vs ...time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldIn(FieldAuthorizedAt, vs...)) +} + +// AuthorizedAtNotIn applies the NotIn predicate on the "authorized_at" field. +func AuthorizedAtNotIn(vs ...time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNotIn(FieldAuthorizedAt, vs...)) +} + +// AuthorizedAtGT applies the GT predicate on the "authorized_at" field. +func AuthorizedAtGT(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGT(FieldAuthorizedAt, v)) +} + +// AuthorizedAtGTE applies the GTE predicate on the "authorized_at" field. +func AuthorizedAtGTE(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGTE(FieldAuthorizedAt, v)) +} + +// AuthorizedAtLT applies the LT predicate on the "authorized_at" field. +func AuthorizedAtLT(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLT(FieldAuthorizedAt, v)) +} + +// AuthorizedAtLTE applies the LTE predicate on the "authorized_at" field. +func AuthorizedAtLTE(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLTE(FieldAuthorizedAt, v)) +} + +// AuthorizedAtIsNil applies the IsNil predicate on the "authorized_at" field. +func AuthorizedAtIsNil() predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldIsNull(FieldAuthorizedAt)) +} + +// AuthorizedAtNotNil applies the NotNil predicate on the "authorized_at" field. +func AuthorizedAtNotNil() predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNotNull(FieldAuthorizedAt)) +} + +// SettledTransactionGroupIDEQ applies the EQ predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDEQ(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEQ(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDNEQ applies the NEQ predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDNEQ(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNEQ(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDIn applies the In predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDIn(vs ...string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldIn(FieldSettledTransactionGroupID, vs...)) +} + +// SettledTransactionGroupIDNotIn applies the NotIn predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDNotIn(vs ...string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNotIn(FieldSettledTransactionGroupID, vs...)) +} + +// SettledTransactionGroupIDGT applies the GT predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDGT(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGT(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDGTE applies the GTE predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDGTE(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGTE(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDLT applies the LT predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDLT(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLT(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDLTE applies the LTE predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDLTE(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLTE(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDContains applies the Contains predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDContains(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldContains(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDHasPrefix applies the HasPrefix predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDHasPrefix(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldHasPrefix(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDHasSuffix applies the HasSuffix predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDHasSuffix(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldHasSuffix(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDIsNil applies the IsNil predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDIsNil() predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldIsNull(FieldSettledTransactionGroupID)) +} + +// SettledTransactionGroupIDNotNil applies the NotNil predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDNotNil() predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNotNull(FieldSettledTransactionGroupID)) +} + +// SettledTransactionGroupIDEqualFold applies the EqualFold predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDEqualFold(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEqualFold(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDContainsFold applies the ContainsFold predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDContainsFold(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldContainsFold(FieldSettledTransactionGroupID, v)) +} + +// SettledAtEQ applies the EQ predicate on the "settled_at" field. +func SettledAtEQ(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEQ(FieldSettledAt, v)) +} + +// SettledAtNEQ applies the NEQ predicate on the "settled_at" field. +func SettledAtNEQ(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNEQ(FieldSettledAt, v)) +} + +// SettledAtIn applies the In predicate on the "settled_at" field. +func SettledAtIn(vs ...time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldIn(FieldSettledAt, vs...)) +} + +// SettledAtNotIn applies the NotIn predicate on the "settled_at" field. +func SettledAtNotIn(vs ...time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNotIn(FieldSettledAt, vs...)) +} + +// SettledAtGT applies the GT predicate on the "settled_at" field. +func SettledAtGT(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGT(FieldSettledAt, v)) +} + +// SettledAtGTE applies the GTE predicate on the "settled_at" field. +func SettledAtGTE(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGTE(FieldSettledAt, v)) +} + +// SettledAtLT applies the LT predicate on the "settled_at" field. +func SettledAtLT(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLT(FieldSettledAt, v)) +} + +// SettledAtLTE applies the LTE predicate on the "settled_at" field. +func SettledAtLTE(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLTE(FieldSettledAt, v)) +} + +// SettledAtIsNil applies the IsNil predicate on the "settled_at" field. +func SettledAtIsNil() predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldIsNull(FieldSettledAt)) +} + +// SettledAtNotNil applies the NotNil predicate on the "settled_at" field. +func SettledAtNotNil() predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNotNull(FieldSettledAt)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNotNull(FieldDeletedAt)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNotNull(FieldAnnotations)) +} + +// ChargeIDEQ applies the EQ predicate on the "charge_id" field. +func ChargeIDEQ(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEQ(FieldChargeID, v)) +} + +// ChargeIDNEQ applies the NEQ predicate on the "charge_id" field. +func ChargeIDNEQ(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNEQ(FieldChargeID, v)) +} + +// ChargeIDIn applies the In predicate on the "charge_id" field. +func ChargeIDIn(vs ...string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldIn(FieldChargeID, vs...)) +} + +// ChargeIDNotIn applies the NotIn predicate on the "charge_id" field. +func ChargeIDNotIn(vs ...string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldNotIn(FieldChargeID, vs...)) +} + +// ChargeIDGT applies the GT predicate on the "charge_id" field. +func ChargeIDGT(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGT(FieldChargeID, v)) +} + +// ChargeIDGTE applies the GTE predicate on the "charge_id" field. +func ChargeIDGTE(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldGTE(FieldChargeID, v)) +} + +// ChargeIDLT applies the LT predicate on the "charge_id" field. +func ChargeIDLT(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLT(FieldChargeID, v)) +} + +// ChargeIDLTE applies the LTE predicate on the "charge_id" field. +func ChargeIDLTE(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldLTE(FieldChargeID, v)) +} + +// ChargeIDContains applies the Contains predicate on the "charge_id" field. +func ChargeIDContains(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldContains(FieldChargeID, v)) +} + +// ChargeIDHasPrefix applies the HasPrefix predicate on the "charge_id" field. +func ChargeIDHasPrefix(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldHasPrefix(FieldChargeID, v)) +} + +// ChargeIDHasSuffix applies the HasSuffix predicate on the "charge_id" field. +func ChargeIDHasSuffix(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldHasSuffix(FieldChargeID, v)) +} + +// ChargeIDEqualFold applies the EqualFold predicate on the "charge_id" field. +func ChargeIDEqualFold(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldEqualFold(FieldChargeID, v)) +} + +// ChargeIDContainsFold applies the ContainsFold predicate on the "charge_id" field. +func ChargeIDContainsFold(v string) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.FieldContainsFold(FieldChargeID, v)) +} + +// HasCreditPurchase applies the HasEdge predicate on the "credit_purchase" edge. +func HasCreditPurchase() predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, CreditPurchaseTable, CreditPurchaseColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCreditPurchaseWith applies the HasEdge predicate on the "credit_purchase" edge with a given conditions (other predicates). +func HasCreditPurchaseWith(preds ...predicate.ChargeCreditPurchase) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(func(s *sql.Selector) { + step := newCreditPurchaseStep() + 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.ChargeCreditPurchaseExternalPayment) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ChargeCreditPurchaseExternalPayment) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ChargeCreditPurchaseExternalPayment) predicate.ChargeCreditPurchaseExternalPayment { + return predicate.ChargeCreditPurchaseExternalPayment(sql.NotPredicates(p)) +} diff --git a/ent/db/chargecreditpurchaseexternalpayment_create.go b/ent/db/chargecreditpurchaseexternalpayment_create.go new file mode 100644 index 0000000000000000000000000000000000000000..77d0b5d214671dcac0c66e7bee59615b3265d501 --- /dev/null +++ b/ent/db/chargecreditpurchaseexternalpayment_create.go @@ -0,0 +1,1312 @@ +// 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/chargecreditpurchase" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchaseexternalpayment" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeCreditPurchaseExternalPaymentCreate is the builder for creating a ChargeCreditPurchaseExternalPayment entity. +type ChargeCreditPurchaseExternalPaymentCreate struct { + config + mutation *ChargeCreditPurchaseExternalPaymentMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetServicePeriodFrom(v time.Time) *ChargeCreditPurchaseExternalPaymentCreate { + _c.mutation.SetServicePeriodFrom(v) + return _c +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetServicePeriodTo(v time.Time) *ChargeCreditPurchaseExternalPaymentCreate { + _c.mutation.SetServicePeriodTo(v) + return _c +} + +// SetStatus sets the "status" field. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetStatus(v payment.Status) *ChargeCreditPurchaseExternalPaymentCreate { + _c.mutation.SetStatus(v) + return _c +} + +// SetAmount sets the "amount" field. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetAmount(v alpacadecimal.Decimal) *ChargeCreditPurchaseExternalPaymentCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetAuthorizedTransactionGroupID(v string) *ChargeCreditPurchaseExternalPaymentCreate { + _c.mutation.SetAuthorizedTransactionGroupID(v) + return _c +} + +// SetNillableAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field if the given value is not nil. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetNillableAuthorizedTransactionGroupID(v *string) *ChargeCreditPurchaseExternalPaymentCreate { + if v != nil { + _c.SetAuthorizedTransactionGroupID(*v) + } + return _c +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetAuthorizedAt(v time.Time) *ChargeCreditPurchaseExternalPaymentCreate { + _c.mutation.SetAuthorizedAt(v) + return _c +} + +// SetNillableAuthorizedAt sets the "authorized_at" field if the given value is not nil. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetNillableAuthorizedAt(v *time.Time) *ChargeCreditPurchaseExternalPaymentCreate { + if v != nil { + _c.SetAuthorizedAt(*v) + } + return _c +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetSettledTransactionGroupID(v string) *ChargeCreditPurchaseExternalPaymentCreate { + _c.mutation.SetSettledTransactionGroupID(v) + return _c +} + +// SetNillableSettledTransactionGroupID sets the "settled_transaction_group_id" field if the given value is not nil. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetNillableSettledTransactionGroupID(v *string) *ChargeCreditPurchaseExternalPaymentCreate { + if v != nil { + _c.SetSettledTransactionGroupID(*v) + } + return _c +} + +// SetSettledAt sets the "settled_at" field. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetSettledAt(v time.Time) *ChargeCreditPurchaseExternalPaymentCreate { + _c.mutation.SetSettledAt(v) + return _c +} + +// SetNillableSettledAt sets the "settled_at" field if the given value is not nil. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetNillableSettledAt(v *time.Time) *ChargeCreditPurchaseExternalPaymentCreate { + if v != nil { + _c.SetSettledAt(*v) + } + return _c +} + +// SetNamespace sets the "namespace" field. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetNamespace(v string) *ChargeCreditPurchaseExternalPaymentCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetCreatedAt(v time.Time) *ChargeCreditPurchaseExternalPaymentCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetNillableCreatedAt(v *time.Time) *ChargeCreditPurchaseExternalPaymentCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseExternalPaymentCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetNillableUpdatedAt(v *time.Time) *ChargeCreditPurchaseExternalPaymentCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetDeletedAt(v time.Time) *ChargeCreditPurchaseExternalPaymentCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetNillableDeletedAt(v *time.Time) *ChargeCreditPurchaseExternalPaymentCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetAnnotations(v models.Annotations) *ChargeCreditPurchaseExternalPaymentCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetChargeID sets the "charge_id" field. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetChargeID(v string) *ChargeCreditPurchaseExternalPaymentCreate { + _c.mutation.SetChargeID(v) + return _c +} + +// SetID sets the "id" field. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetID(v string) *ChargeCreditPurchaseExternalPaymentCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetNillableID(v *string) *ChargeCreditPurchaseExternalPaymentCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetCreditPurchaseID sets the "credit_purchase" edge to the ChargeCreditPurchase entity by ID. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetCreditPurchaseID(id string) *ChargeCreditPurchaseExternalPaymentCreate { + _c.mutation.SetCreditPurchaseID(id) + return _c +} + +// SetCreditPurchase sets the "credit_purchase" edge to the ChargeCreditPurchase entity. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SetCreditPurchase(v *ChargeCreditPurchase) *ChargeCreditPurchaseExternalPaymentCreate { + return _c.SetCreditPurchaseID(v.ID) +} + +// Mutation returns the ChargeCreditPurchaseExternalPaymentMutation object of the builder. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) Mutation() *ChargeCreditPurchaseExternalPaymentMutation { + return _c.mutation +} + +// Save creates the ChargeCreditPurchaseExternalPayment in the database. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) Save(ctx context.Context) (*ChargeCreditPurchaseExternalPayment, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) SaveX(ctx context.Context) *ChargeCreditPurchaseExternalPayment { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) 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 *ChargeCreditPurchaseExternalPaymentCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := chargecreditpurchaseexternalpayment.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := chargecreditpurchaseexternalpayment.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := chargecreditpurchaseexternalpayment.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ChargeCreditPurchaseExternalPaymentCreate) check() error { + if _, ok := _c.mutation.ServicePeriodFrom(); !ok { + return &ValidationError{Name: "service_period_from", err: errors.New(`db: missing required field "ChargeCreditPurchaseExternalPayment.service_period_from"`)} + } + if _, ok := _c.mutation.ServicePeriodTo(); !ok { + return &ValidationError{Name: "service_period_to", err: errors.New(`db: missing required field "ChargeCreditPurchaseExternalPayment.service_period_to"`)} + } + if _, ok := _c.mutation.Status(); !ok { + return &ValidationError{Name: "status", err: errors.New(`db: missing required field "ChargeCreditPurchaseExternalPayment.status"`)} + } + if v, ok := _c.mutation.Status(); ok { + if err := chargecreditpurchaseexternalpayment.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseExternalPayment.status": %w`, err)} + } + } + if _, ok := _c.mutation.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`db: missing required field "ChargeCreditPurchaseExternalPayment.amount"`)} + } + if v, ok := _c.mutation.AuthorizedTransactionGroupID(); ok { + if err := chargecreditpurchaseexternalpayment.AuthorizedTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "authorized_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseExternalPayment.authorized_transaction_group_id": %w`, err)} + } + } + if v, ok := _c.mutation.SettledTransactionGroupID(); ok { + if err := chargecreditpurchaseexternalpayment.SettledTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "settled_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseExternalPayment.settled_transaction_group_id": %w`, err)} + } + } + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "ChargeCreditPurchaseExternalPayment.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := chargecreditpurchaseexternalpayment.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseExternalPayment.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "ChargeCreditPurchaseExternalPayment.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "ChargeCreditPurchaseExternalPayment.updated_at"`)} + } + if _, ok := _c.mutation.ChargeID(); !ok { + return &ValidationError{Name: "charge_id", err: errors.New(`db: missing required field "ChargeCreditPurchaseExternalPayment.charge_id"`)} + } + if len(_c.mutation.CreditPurchaseIDs()) == 0 { + return &ValidationError{Name: "credit_purchase", err: errors.New(`db: missing required edge "ChargeCreditPurchaseExternalPayment.credit_purchase"`)} + } + return nil +} + +func (_c *ChargeCreditPurchaseExternalPaymentCreate) sqlSave(ctx context.Context) (*ChargeCreditPurchaseExternalPayment, 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 ChargeCreditPurchaseExternalPayment.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ChargeCreditPurchaseExternalPaymentCreate) createSpec() (*ChargeCreditPurchaseExternalPayment, *sqlgraph.CreateSpec) { + var ( + _node = &ChargeCreditPurchaseExternalPayment{config: _c.config} + _spec = sqlgraph.NewCreateSpec(chargecreditpurchaseexternalpayment.Table, sqlgraph.NewFieldSpec(chargecreditpurchaseexternalpayment.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.ServicePeriodFrom(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldServicePeriodFrom, field.TypeTime, value) + _node.ServicePeriodFrom = value + } + if value, ok := _c.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldServicePeriodTo, field.TypeTime, value) + _node.ServicePeriodTo = value + } + if value, ok := _c.mutation.Status(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldStatus, field.TypeEnum, value) + _node.Status = value + } + if value, ok := _c.mutation.Amount(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldAmount, field.TypeOther, value) + _node.Amount = value + } + if value, ok := _c.mutation.AuthorizedTransactionGroupID(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldAuthorizedTransactionGroupID, field.TypeString, value) + _node.AuthorizedTransactionGroupID = &value + } + if value, ok := _c.mutation.AuthorizedAt(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldAuthorizedAt, field.TypeTime, value) + _node.AuthorizedAt = &value + } + if value, ok := _c.mutation.SettledTransactionGroupID(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldSettledTransactionGroupID, field.TypeString, value) + _node.SettledTransactionGroupID = &value + } + if value, ok := _c.mutation.SettledAt(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldSettledAt, field.TypeTime, value) + _node.SettledAt = &value + } + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if nodes := _c.mutation.CreditPurchaseIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargecreditpurchaseexternalpayment.CreditPurchaseTable, + Columns: []string{chargecreditpurchaseexternalpayment.CreditPurchaseColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchase.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) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ChargeCreditPurchaseExternalPayment.Create(). +// SetServicePeriodFrom(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.ChargeCreditPurchaseExternalPaymentUpsert) { +// SetServicePeriodFrom(v+v). +// }). +// Exec(ctx) +func (_c *ChargeCreditPurchaseExternalPaymentCreate) OnConflict(opts ...sql.ConflictOption) *ChargeCreditPurchaseExternalPaymentUpsertOne { + _c.conflict = opts + return &ChargeCreditPurchaseExternalPaymentUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeCreditPurchaseExternalPayment.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeCreditPurchaseExternalPaymentCreate) OnConflictColumns(columns ...string) *ChargeCreditPurchaseExternalPaymentUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeCreditPurchaseExternalPaymentUpsertOne{ + create: _c, + } +} + +type ( + // ChargeCreditPurchaseExternalPaymentUpsertOne is the builder for "upsert"-ing + // one ChargeCreditPurchaseExternalPayment node. + ChargeCreditPurchaseExternalPaymentUpsertOne struct { + create *ChargeCreditPurchaseExternalPaymentCreate + } + + // ChargeCreditPurchaseExternalPaymentUpsert is the "OnConflict" setter. + ChargeCreditPurchaseExternalPaymentUpsert struct { + *sql.UpdateSet + } +) + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) SetServicePeriodFrom(v time.Time) *ChargeCreditPurchaseExternalPaymentUpsert { + u.Set(chargecreditpurchaseexternalpayment.FieldServicePeriodFrom, v) + return u +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) UpdateServicePeriodFrom() *ChargeCreditPurchaseExternalPaymentUpsert { + u.SetExcluded(chargecreditpurchaseexternalpayment.FieldServicePeriodFrom) + return u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) SetServicePeriodTo(v time.Time) *ChargeCreditPurchaseExternalPaymentUpsert { + u.Set(chargecreditpurchaseexternalpayment.FieldServicePeriodTo, v) + return u +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) UpdateServicePeriodTo() *ChargeCreditPurchaseExternalPaymentUpsert { + u.SetExcluded(chargecreditpurchaseexternalpayment.FieldServicePeriodTo) + return u +} + +// SetStatus sets the "status" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) SetStatus(v payment.Status) *ChargeCreditPurchaseExternalPaymentUpsert { + u.Set(chargecreditpurchaseexternalpayment.FieldStatus, v) + return u +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) UpdateStatus() *ChargeCreditPurchaseExternalPaymentUpsert { + u.SetExcluded(chargecreditpurchaseexternalpayment.FieldStatus) + return u +} + +// SetAmount sets the "amount" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) SetAmount(v alpacadecimal.Decimal) *ChargeCreditPurchaseExternalPaymentUpsert { + u.Set(chargecreditpurchaseexternalpayment.FieldAmount, v) + return u +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) UpdateAmount() *ChargeCreditPurchaseExternalPaymentUpsert { + u.SetExcluded(chargecreditpurchaseexternalpayment.FieldAmount) + return u +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) SetAuthorizedTransactionGroupID(v string) *ChargeCreditPurchaseExternalPaymentUpsert { + u.Set(chargecreditpurchaseexternalpayment.FieldAuthorizedTransactionGroupID, v) + return u +} + +// UpdateAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) UpdateAuthorizedTransactionGroupID() *ChargeCreditPurchaseExternalPaymentUpsert { + u.SetExcluded(chargecreditpurchaseexternalpayment.FieldAuthorizedTransactionGroupID) + return u +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) ClearAuthorizedTransactionGroupID() *ChargeCreditPurchaseExternalPaymentUpsert { + u.SetNull(chargecreditpurchaseexternalpayment.FieldAuthorizedTransactionGroupID) + return u +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) SetAuthorizedAt(v time.Time) *ChargeCreditPurchaseExternalPaymentUpsert { + u.Set(chargecreditpurchaseexternalpayment.FieldAuthorizedAt, v) + return u +} + +// UpdateAuthorizedAt sets the "authorized_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) UpdateAuthorizedAt() *ChargeCreditPurchaseExternalPaymentUpsert { + u.SetExcluded(chargecreditpurchaseexternalpayment.FieldAuthorizedAt) + return u +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) ClearAuthorizedAt() *ChargeCreditPurchaseExternalPaymentUpsert { + u.SetNull(chargecreditpurchaseexternalpayment.FieldAuthorizedAt) + return u +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) SetSettledTransactionGroupID(v string) *ChargeCreditPurchaseExternalPaymentUpsert { + u.Set(chargecreditpurchaseexternalpayment.FieldSettledTransactionGroupID, v) + return u +} + +// UpdateSettledTransactionGroupID sets the "settled_transaction_group_id" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) UpdateSettledTransactionGroupID() *ChargeCreditPurchaseExternalPaymentUpsert { + u.SetExcluded(chargecreditpurchaseexternalpayment.FieldSettledTransactionGroupID) + return u +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) ClearSettledTransactionGroupID() *ChargeCreditPurchaseExternalPaymentUpsert { + u.SetNull(chargecreditpurchaseexternalpayment.FieldSettledTransactionGroupID) + return u +} + +// SetSettledAt sets the "settled_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) SetSettledAt(v time.Time) *ChargeCreditPurchaseExternalPaymentUpsert { + u.Set(chargecreditpurchaseexternalpayment.FieldSettledAt, v) + return u +} + +// UpdateSettledAt sets the "settled_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) UpdateSettledAt() *ChargeCreditPurchaseExternalPaymentUpsert { + u.SetExcluded(chargecreditpurchaseexternalpayment.FieldSettledAt) + return u +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) ClearSettledAt() *ChargeCreditPurchaseExternalPaymentUpsert { + u.SetNull(chargecreditpurchaseexternalpayment.FieldSettledAt) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseExternalPaymentUpsert { + u.Set(chargecreditpurchaseexternalpayment.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) UpdateUpdatedAt() *ChargeCreditPurchaseExternalPaymentUpsert { + u.SetExcluded(chargecreditpurchaseexternalpayment.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) SetDeletedAt(v time.Time) *ChargeCreditPurchaseExternalPaymentUpsert { + u.Set(chargecreditpurchaseexternalpayment.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) UpdateDeletedAt() *ChargeCreditPurchaseExternalPaymentUpsert { + u.SetExcluded(chargecreditpurchaseexternalpayment.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) ClearDeletedAt() *ChargeCreditPurchaseExternalPaymentUpsert { + u.SetNull(chargecreditpurchaseexternalpayment.FieldDeletedAt) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) SetAnnotations(v models.Annotations) *ChargeCreditPurchaseExternalPaymentUpsert { + u.Set(chargecreditpurchaseexternalpayment.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) UpdateAnnotations() *ChargeCreditPurchaseExternalPaymentUpsert { + u.SetExcluded(chargecreditpurchaseexternalpayment.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsert) ClearAnnotations() *ChargeCreditPurchaseExternalPaymentUpsert { + u.SetNull(chargecreditpurchaseexternalpayment.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.ChargeCreditPurchaseExternalPayment.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargecreditpurchaseexternalpayment.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) UpdateNewValues() *ChargeCreditPurchaseExternalPaymentUpsertOne { + 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(chargecreditpurchaseexternalpayment.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(chargecreditpurchaseexternalpayment.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(chargecreditpurchaseexternalpayment.FieldCreatedAt) + } + if _, exists := u.create.mutation.ChargeID(); exists { + s.SetIgnore(chargecreditpurchaseexternalpayment.FieldChargeID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeCreditPurchaseExternalPayment.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) Ignore() *ChargeCreditPurchaseExternalPaymentUpsertOne { + 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 *ChargeCreditPurchaseExternalPaymentUpsertOne) DoNothing() *ChargeCreditPurchaseExternalPaymentUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeCreditPurchaseExternalPaymentCreate.OnConflict +// documentation for more info. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) Update(set func(*ChargeCreditPurchaseExternalPaymentUpsert)) *ChargeCreditPurchaseExternalPaymentUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeCreditPurchaseExternalPaymentUpsert{UpdateSet: update}) + })) + return u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) SetServicePeriodFrom(v time.Time) *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) UpdateServicePeriodFrom() *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) SetServicePeriodTo(v time.Time) *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) UpdateServicePeriodTo() *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetStatus sets the "status" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) SetStatus(v payment.Status) *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) UpdateStatus() *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateStatus() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) SetAmount(v alpacadecimal.Decimal) *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) UpdateAmount() *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateAmount() + }) +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) SetAuthorizedTransactionGroupID(v string) *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetAuthorizedTransactionGroupID(v) + }) +} + +// UpdateAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) UpdateAuthorizedTransactionGroupID() *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateAuthorizedTransactionGroupID() + }) +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) ClearAuthorizedTransactionGroupID() *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.ClearAuthorizedTransactionGroupID() + }) +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) SetAuthorizedAt(v time.Time) *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetAuthorizedAt(v) + }) +} + +// UpdateAuthorizedAt sets the "authorized_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) UpdateAuthorizedAt() *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateAuthorizedAt() + }) +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) ClearAuthorizedAt() *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.ClearAuthorizedAt() + }) +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) SetSettledTransactionGroupID(v string) *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetSettledTransactionGroupID(v) + }) +} + +// UpdateSettledTransactionGroupID sets the "settled_transaction_group_id" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) UpdateSettledTransactionGroupID() *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateSettledTransactionGroupID() + }) +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) ClearSettledTransactionGroupID() *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.ClearSettledTransactionGroupID() + }) +} + +// SetSettledAt sets the "settled_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) SetSettledAt(v time.Time) *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetSettledAt(v) + }) +} + +// UpdateSettledAt sets the "settled_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) UpdateSettledAt() *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateSettledAt() + }) +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) ClearSettledAt() *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.ClearSettledAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) UpdateUpdatedAt() *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) SetDeletedAt(v time.Time) *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) UpdateDeletedAt() *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) ClearDeletedAt() *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) SetAnnotations(v models.Annotations) *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) UpdateAnnotations() *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) ClearAnnotations() *ChargeCreditPurchaseExternalPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.ClearAnnotations() + }) +} + +// Exec executes the query. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeCreditPurchaseExternalPaymentCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeCreditPurchaseExternalPaymentUpsertOne) 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 *ChargeCreditPurchaseExternalPaymentUpsertOne) 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: ChargeCreditPurchaseExternalPaymentUpsertOne.ID is not supported by MySQL driver. Use ChargeCreditPurchaseExternalPaymentUpsertOne.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 *ChargeCreditPurchaseExternalPaymentUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ChargeCreditPurchaseExternalPaymentCreateBulk is the builder for creating many ChargeCreditPurchaseExternalPayment entities in bulk. +type ChargeCreditPurchaseExternalPaymentCreateBulk struct { + config + err error + builders []*ChargeCreditPurchaseExternalPaymentCreate + conflict []sql.ConflictOption +} + +// Save creates the ChargeCreditPurchaseExternalPayment entities in the database. +func (_c *ChargeCreditPurchaseExternalPaymentCreateBulk) Save(ctx context.Context) ([]*ChargeCreditPurchaseExternalPayment, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ChargeCreditPurchaseExternalPayment, 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.(*ChargeCreditPurchaseExternalPaymentMutation) + 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 *ChargeCreditPurchaseExternalPaymentCreateBulk) SaveX(ctx context.Context) []*ChargeCreditPurchaseExternalPayment { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeCreditPurchaseExternalPaymentCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeCreditPurchaseExternalPaymentCreateBulk) 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.ChargeCreditPurchaseExternalPayment.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.ChargeCreditPurchaseExternalPaymentUpsert) { +// SetServicePeriodFrom(v+v). +// }). +// Exec(ctx) +func (_c *ChargeCreditPurchaseExternalPaymentCreateBulk) OnConflict(opts ...sql.ConflictOption) *ChargeCreditPurchaseExternalPaymentUpsertBulk { + _c.conflict = opts + return &ChargeCreditPurchaseExternalPaymentUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeCreditPurchaseExternalPayment.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeCreditPurchaseExternalPaymentCreateBulk) OnConflictColumns(columns ...string) *ChargeCreditPurchaseExternalPaymentUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeCreditPurchaseExternalPaymentUpsertBulk{ + create: _c, + } +} + +// ChargeCreditPurchaseExternalPaymentUpsertBulk is the builder for "upsert"-ing +// a bulk of ChargeCreditPurchaseExternalPayment nodes. +type ChargeCreditPurchaseExternalPaymentUpsertBulk struct { + create *ChargeCreditPurchaseExternalPaymentCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ChargeCreditPurchaseExternalPayment.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargecreditpurchaseexternalpayment.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) UpdateNewValues() *ChargeCreditPurchaseExternalPaymentUpsertBulk { + 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(chargecreditpurchaseexternalpayment.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(chargecreditpurchaseexternalpayment.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(chargecreditpurchaseexternalpayment.FieldCreatedAt) + } + if _, exists := b.mutation.ChargeID(); exists { + s.SetIgnore(chargecreditpurchaseexternalpayment.FieldChargeID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeCreditPurchaseExternalPayment.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) Ignore() *ChargeCreditPurchaseExternalPaymentUpsertBulk { + 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 *ChargeCreditPurchaseExternalPaymentUpsertBulk) DoNothing() *ChargeCreditPurchaseExternalPaymentUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeCreditPurchaseExternalPaymentCreateBulk.OnConflict +// documentation for more info. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) Update(set func(*ChargeCreditPurchaseExternalPaymentUpsert)) *ChargeCreditPurchaseExternalPaymentUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeCreditPurchaseExternalPaymentUpsert{UpdateSet: update}) + })) + return u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) SetServicePeriodFrom(v time.Time) *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) UpdateServicePeriodFrom() *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) SetServicePeriodTo(v time.Time) *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) UpdateServicePeriodTo() *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetStatus sets the "status" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) SetStatus(v payment.Status) *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) UpdateStatus() *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateStatus() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) SetAmount(v alpacadecimal.Decimal) *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) UpdateAmount() *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateAmount() + }) +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) SetAuthorizedTransactionGroupID(v string) *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetAuthorizedTransactionGroupID(v) + }) +} + +// UpdateAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) UpdateAuthorizedTransactionGroupID() *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateAuthorizedTransactionGroupID() + }) +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) ClearAuthorizedTransactionGroupID() *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.ClearAuthorizedTransactionGroupID() + }) +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) SetAuthorizedAt(v time.Time) *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetAuthorizedAt(v) + }) +} + +// UpdateAuthorizedAt sets the "authorized_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) UpdateAuthorizedAt() *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateAuthorizedAt() + }) +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) ClearAuthorizedAt() *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.ClearAuthorizedAt() + }) +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) SetSettledTransactionGroupID(v string) *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetSettledTransactionGroupID(v) + }) +} + +// UpdateSettledTransactionGroupID sets the "settled_transaction_group_id" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) UpdateSettledTransactionGroupID() *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateSettledTransactionGroupID() + }) +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) ClearSettledTransactionGroupID() *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.ClearSettledTransactionGroupID() + }) +} + +// SetSettledAt sets the "settled_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) SetSettledAt(v time.Time) *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetSettledAt(v) + }) +} + +// UpdateSettledAt sets the "settled_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) UpdateSettledAt() *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateSettledAt() + }) +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) ClearSettledAt() *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.ClearSettledAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) UpdateUpdatedAt() *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) SetDeletedAt(v time.Time) *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) UpdateDeletedAt() *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) ClearDeletedAt() *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) SetAnnotations(v models.Annotations) *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) UpdateAnnotations() *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) ClearAnnotations() *ChargeCreditPurchaseExternalPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseExternalPaymentUpsert) { + s.ClearAnnotations() + }) +} + +// Exec executes the query. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) 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 ChargeCreditPurchaseExternalPaymentCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeCreditPurchaseExternalPaymentCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeCreditPurchaseExternalPaymentUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargecreditpurchaseexternalpayment_delete.go b/ent/db/chargecreditpurchaseexternalpayment_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..34953b0abd168b453df2c9140b63034909414d8b --- /dev/null +++ b/ent/db/chargecreditpurchaseexternalpayment_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/chargecreditpurchaseexternalpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeCreditPurchaseExternalPaymentDelete is the builder for deleting a ChargeCreditPurchaseExternalPayment entity. +type ChargeCreditPurchaseExternalPaymentDelete struct { + config + hooks []Hook + mutation *ChargeCreditPurchaseExternalPaymentMutation +} + +// Where appends a list predicates to the ChargeCreditPurchaseExternalPaymentDelete builder. +func (_d *ChargeCreditPurchaseExternalPaymentDelete) Where(ps ...predicate.ChargeCreditPurchaseExternalPayment) *ChargeCreditPurchaseExternalPaymentDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ChargeCreditPurchaseExternalPaymentDelete) 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 *ChargeCreditPurchaseExternalPaymentDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ChargeCreditPurchaseExternalPaymentDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(chargecreditpurchaseexternalpayment.Table, sqlgraph.NewFieldSpec(chargecreditpurchaseexternalpayment.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 +} + +// ChargeCreditPurchaseExternalPaymentDeleteOne is the builder for deleting a single ChargeCreditPurchaseExternalPayment entity. +type ChargeCreditPurchaseExternalPaymentDeleteOne struct { + _d *ChargeCreditPurchaseExternalPaymentDelete +} + +// Where appends a list predicates to the ChargeCreditPurchaseExternalPaymentDelete builder. +func (_d *ChargeCreditPurchaseExternalPaymentDeleteOne) Where(ps ...predicate.ChargeCreditPurchaseExternalPayment) *ChargeCreditPurchaseExternalPaymentDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ChargeCreditPurchaseExternalPaymentDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{chargecreditpurchaseexternalpayment.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeCreditPurchaseExternalPaymentDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargecreditpurchaseexternalpayment_query.go b/ent/db/chargecreditpurchaseexternalpayment_query.go new file mode 100644 index 0000000000000000000000000000000000000000..1a456a3f93e54ab61c41cce9d2571b96547d19e2 --- /dev/null +++ b/ent/db/chargecreditpurchaseexternalpayment_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/chargecreditpurchase" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchaseexternalpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeCreditPurchaseExternalPaymentQuery is the builder for querying ChargeCreditPurchaseExternalPayment entities. +type ChargeCreditPurchaseExternalPaymentQuery struct { + config + ctx *QueryContext + order []chargecreditpurchaseexternalpayment.OrderOption + inters []Interceptor + predicates []predicate.ChargeCreditPurchaseExternalPayment + withCreditPurchase *ChargeCreditPurchaseQuery + 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 ChargeCreditPurchaseExternalPaymentQuery builder. +func (_q *ChargeCreditPurchaseExternalPaymentQuery) Where(ps ...predicate.ChargeCreditPurchaseExternalPayment) *ChargeCreditPurchaseExternalPaymentQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ChargeCreditPurchaseExternalPaymentQuery) Limit(limit int) *ChargeCreditPurchaseExternalPaymentQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ChargeCreditPurchaseExternalPaymentQuery) Offset(offset int) *ChargeCreditPurchaseExternalPaymentQuery { + _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 *ChargeCreditPurchaseExternalPaymentQuery) Unique(unique bool) *ChargeCreditPurchaseExternalPaymentQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ChargeCreditPurchaseExternalPaymentQuery) Order(o ...chargecreditpurchaseexternalpayment.OrderOption) *ChargeCreditPurchaseExternalPaymentQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryCreditPurchase chains the current query on the "credit_purchase" edge. +func (_q *ChargeCreditPurchaseExternalPaymentQuery) QueryCreditPurchase() *ChargeCreditPurchaseQuery { + query := (&ChargeCreditPurchaseClient{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(chargecreditpurchaseexternalpayment.Table, chargecreditpurchaseexternalpayment.FieldID, selector), + sqlgraph.To(chargecreditpurchase.Table, chargecreditpurchase.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargecreditpurchaseexternalpayment.CreditPurchaseTable, chargecreditpurchaseexternalpayment.CreditPurchaseColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ChargeCreditPurchaseExternalPayment entity from the query. +// Returns a *NotFoundError when no ChargeCreditPurchaseExternalPayment was found. +func (_q *ChargeCreditPurchaseExternalPaymentQuery) First(ctx context.Context) (*ChargeCreditPurchaseExternalPayment, 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{chargecreditpurchaseexternalpayment.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ChargeCreditPurchaseExternalPaymentQuery) FirstX(ctx context.Context) *ChargeCreditPurchaseExternalPayment { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ChargeCreditPurchaseExternalPayment ID from the query. +// Returns a *NotFoundError when no ChargeCreditPurchaseExternalPayment ID was found. +func (_q *ChargeCreditPurchaseExternalPaymentQuery) 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{chargecreditpurchaseexternalpayment.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ChargeCreditPurchaseExternalPaymentQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ChargeCreditPurchaseExternalPayment entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ChargeCreditPurchaseExternalPayment entity is found. +// Returns a *NotFoundError when no ChargeCreditPurchaseExternalPayment entities are found. +func (_q *ChargeCreditPurchaseExternalPaymentQuery) Only(ctx context.Context) (*ChargeCreditPurchaseExternalPayment, 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{chargecreditpurchaseexternalpayment.Label} + default: + return nil, &NotSingularError{chargecreditpurchaseexternalpayment.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ChargeCreditPurchaseExternalPaymentQuery) OnlyX(ctx context.Context) *ChargeCreditPurchaseExternalPayment { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ChargeCreditPurchaseExternalPayment ID in the query. +// Returns a *NotSingularError when more than one ChargeCreditPurchaseExternalPayment ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ChargeCreditPurchaseExternalPaymentQuery) 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{chargecreditpurchaseexternalpayment.Label} + default: + err = &NotSingularError{chargecreditpurchaseexternalpayment.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ChargeCreditPurchaseExternalPaymentQuery) 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 ChargeCreditPurchaseExternalPayments. +func (_q *ChargeCreditPurchaseExternalPaymentQuery) All(ctx context.Context) ([]*ChargeCreditPurchaseExternalPayment, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ChargeCreditPurchaseExternalPayment, *ChargeCreditPurchaseExternalPaymentQuery]() + return withInterceptors[[]*ChargeCreditPurchaseExternalPayment](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ChargeCreditPurchaseExternalPaymentQuery) AllX(ctx context.Context) []*ChargeCreditPurchaseExternalPayment { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ChargeCreditPurchaseExternalPayment IDs. +func (_q *ChargeCreditPurchaseExternalPaymentQuery) 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(chargecreditpurchaseexternalpayment.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ChargeCreditPurchaseExternalPaymentQuery) 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 *ChargeCreditPurchaseExternalPaymentQuery) 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[*ChargeCreditPurchaseExternalPaymentQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ChargeCreditPurchaseExternalPaymentQuery) 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 *ChargeCreditPurchaseExternalPaymentQuery) 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 *ChargeCreditPurchaseExternalPaymentQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ChargeCreditPurchaseExternalPaymentQuery 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 *ChargeCreditPurchaseExternalPaymentQuery) Clone() *ChargeCreditPurchaseExternalPaymentQuery { + if _q == nil { + return nil + } + return &ChargeCreditPurchaseExternalPaymentQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]chargecreditpurchaseexternalpayment.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ChargeCreditPurchaseExternalPayment{}, _q.predicates...), + withCreditPurchase: _q.withCreditPurchase.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithCreditPurchase tells the query-builder to eager-load the nodes that are connected to +// the "credit_purchase" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeCreditPurchaseExternalPaymentQuery) WithCreditPurchase(opts ...func(*ChargeCreditPurchaseQuery)) *ChargeCreditPurchaseExternalPaymentQuery { + query := (&ChargeCreditPurchaseClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCreditPurchase = 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 { +// ServicePeriodFrom time.Time `json:"service_period_from,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.ChargeCreditPurchaseExternalPayment.Query(). +// GroupBy(chargecreditpurchaseexternalpayment.FieldServicePeriodFrom). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *ChargeCreditPurchaseExternalPaymentQuery) GroupBy(field string, fields ...string) *ChargeCreditPurchaseExternalPaymentGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ChargeCreditPurchaseExternalPaymentGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = chargecreditpurchaseexternalpayment.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 { +// ServicePeriodFrom time.Time `json:"service_period_from,omitempty"` +// } +// +// client.ChargeCreditPurchaseExternalPayment.Query(). +// Select(chargecreditpurchaseexternalpayment.FieldServicePeriodFrom). +// Scan(ctx, &v) +func (_q *ChargeCreditPurchaseExternalPaymentQuery) Select(fields ...string) *ChargeCreditPurchaseExternalPaymentSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ChargeCreditPurchaseExternalPaymentSelect{ChargeCreditPurchaseExternalPaymentQuery: _q} + sbuild.label = chargecreditpurchaseexternalpayment.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ChargeCreditPurchaseExternalPaymentSelect configured with the given aggregations. +func (_q *ChargeCreditPurchaseExternalPaymentQuery) Aggregate(fns ...AggregateFunc) *ChargeCreditPurchaseExternalPaymentSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ChargeCreditPurchaseExternalPaymentQuery) 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 !chargecreditpurchaseexternalpayment.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 *ChargeCreditPurchaseExternalPaymentQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ChargeCreditPurchaseExternalPayment, error) { + var ( + nodes = []*ChargeCreditPurchaseExternalPayment{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withCreditPurchase != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ChargeCreditPurchaseExternalPayment).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ChargeCreditPurchaseExternalPayment{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.withCreditPurchase; query != nil { + if err := _q.loadCreditPurchase(ctx, query, nodes, nil, + func(n *ChargeCreditPurchaseExternalPayment, e *ChargeCreditPurchase) { n.Edges.CreditPurchase = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ChargeCreditPurchaseExternalPaymentQuery) loadCreditPurchase(ctx context.Context, query *ChargeCreditPurchaseQuery, nodes []*ChargeCreditPurchaseExternalPayment, init func(*ChargeCreditPurchaseExternalPayment), assign func(*ChargeCreditPurchaseExternalPayment, *ChargeCreditPurchase)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeCreditPurchaseExternalPayment) + 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(chargecreditpurchase.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 *ChargeCreditPurchaseExternalPaymentQuery) 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 *ChargeCreditPurchaseExternalPaymentQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(chargecreditpurchaseexternalpayment.Table, chargecreditpurchaseexternalpayment.Columns, sqlgraph.NewFieldSpec(chargecreditpurchaseexternalpayment.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, chargecreditpurchaseexternalpayment.FieldID) + for i := range fields { + if fields[i] != chargecreditpurchaseexternalpayment.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withCreditPurchase != nil { + _spec.Node.AddColumnOnce(chargecreditpurchaseexternalpayment.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 *ChargeCreditPurchaseExternalPaymentQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(chargecreditpurchaseexternalpayment.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = chargecreditpurchaseexternalpayment.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 *ChargeCreditPurchaseExternalPaymentQuery) ForUpdate(opts ...sql.LockOption) *ChargeCreditPurchaseExternalPaymentQuery { + 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 *ChargeCreditPurchaseExternalPaymentQuery) ForShare(opts ...sql.LockOption) *ChargeCreditPurchaseExternalPaymentQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ChargeCreditPurchaseExternalPaymentGroupBy is the group-by builder for ChargeCreditPurchaseExternalPayment entities. +type ChargeCreditPurchaseExternalPaymentGroupBy struct { + selector + build *ChargeCreditPurchaseExternalPaymentQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ChargeCreditPurchaseExternalPaymentGroupBy) Aggregate(fns ...AggregateFunc) *ChargeCreditPurchaseExternalPaymentGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ChargeCreditPurchaseExternalPaymentGroupBy) 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[*ChargeCreditPurchaseExternalPaymentQuery, *ChargeCreditPurchaseExternalPaymentGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ChargeCreditPurchaseExternalPaymentGroupBy) sqlScan(ctx context.Context, root *ChargeCreditPurchaseExternalPaymentQuery, 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) +} + +// ChargeCreditPurchaseExternalPaymentSelect is the builder for selecting fields of ChargeCreditPurchaseExternalPayment entities. +type ChargeCreditPurchaseExternalPaymentSelect struct { + *ChargeCreditPurchaseExternalPaymentQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ChargeCreditPurchaseExternalPaymentSelect) Aggregate(fns ...AggregateFunc) *ChargeCreditPurchaseExternalPaymentSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ChargeCreditPurchaseExternalPaymentSelect) 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[*ChargeCreditPurchaseExternalPaymentQuery, *ChargeCreditPurchaseExternalPaymentSelect](ctx, _s.ChargeCreditPurchaseExternalPaymentQuery, _s, _s.inters, v) +} + +func (_s *ChargeCreditPurchaseExternalPaymentSelect) sqlScan(ctx context.Context, root *ChargeCreditPurchaseExternalPaymentQuery, 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/ent/db/chargecreditpurchaseexternalpayment_update.go b/ent/db/chargecreditpurchaseexternalpayment_update.go new file mode 100644 index 0000000000000000000000000000000000000000..3f7cd84ba7ae37d2c660bca29822fe5cf7732250 --- /dev/null +++ b/ent/db/chargecreditpurchaseexternalpayment_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/chargecreditpurchaseexternalpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeCreditPurchaseExternalPaymentUpdate is the builder for updating ChargeCreditPurchaseExternalPayment entities. +type ChargeCreditPurchaseExternalPaymentUpdate struct { + config + hooks []Hook + mutation *ChargeCreditPurchaseExternalPaymentMutation +} + +// Where appends a list predicates to the ChargeCreditPurchaseExternalPaymentUpdate builder. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) Where(ps ...predicate.ChargeCreditPurchaseExternalPayment) *ChargeCreditPurchaseExternalPaymentUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) SetServicePeriodFrom(v time.Time) *ChargeCreditPurchaseExternalPaymentUpdate { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) SetNillableServicePeriodFrom(v *time.Time) *ChargeCreditPurchaseExternalPaymentUpdate { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) SetServicePeriodTo(v time.Time) *ChargeCreditPurchaseExternalPaymentUpdate { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) SetNillableServicePeriodTo(v *time.Time) *ChargeCreditPurchaseExternalPaymentUpdate { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetStatus sets the "status" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) SetStatus(v payment.Status) *ChargeCreditPurchaseExternalPaymentUpdate { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) SetNillableStatus(v *payment.Status) *ChargeCreditPurchaseExternalPaymentUpdate { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) SetAmount(v alpacadecimal.Decimal) *ChargeCreditPurchaseExternalPaymentUpdate { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeCreditPurchaseExternalPaymentUpdate { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) SetAuthorizedTransactionGroupID(v string) *ChargeCreditPurchaseExternalPaymentUpdate { + _u.mutation.SetAuthorizedTransactionGroupID(v) + return _u +} + +// SetNillableAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field if the given value is not nil. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) SetNillableAuthorizedTransactionGroupID(v *string) *ChargeCreditPurchaseExternalPaymentUpdate { + if v != nil { + _u.SetAuthorizedTransactionGroupID(*v) + } + return _u +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) ClearAuthorizedTransactionGroupID() *ChargeCreditPurchaseExternalPaymentUpdate { + _u.mutation.ClearAuthorizedTransactionGroupID() + return _u +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) SetAuthorizedAt(v time.Time) *ChargeCreditPurchaseExternalPaymentUpdate { + _u.mutation.SetAuthorizedAt(v) + return _u +} + +// SetNillableAuthorizedAt sets the "authorized_at" field if the given value is not nil. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) SetNillableAuthorizedAt(v *time.Time) *ChargeCreditPurchaseExternalPaymentUpdate { + if v != nil { + _u.SetAuthorizedAt(*v) + } + return _u +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) ClearAuthorizedAt() *ChargeCreditPurchaseExternalPaymentUpdate { + _u.mutation.ClearAuthorizedAt() + return _u +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) SetSettledTransactionGroupID(v string) *ChargeCreditPurchaseExternalPaymentUpdate { + _u.mutation.SetSettledTransactionGroupID(v) + return _u +} + +// SetNillableSettledTransactionGroupID sets the "settled_transaction_group_id" field if the given value is not nil. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) SetNillableSettledTransactionGroupID(v *string) *ChargeCreditPurchaseExternalPaymentUpdate { + if v != nil { + _u.SetSettledTransactionGroupID(*v) + } + return _u +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) ClearSettledTransactionGroupID() *ChargeCreditPurchaseExternalPaymentUpdate { + _u.mutation.ClearSettledTransactionGroupID() + return _u +} + +// SetSettledAt sets the "settled_at" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) SetSettledAt(v time.Time) *ChargeCreditPurchaseExternalPaymentUpdate { + _u.mutation.SetSettledAt(v) + return _u +} + +// SetNillableSettledAt sets the "settled_at" field if the given value is not nil. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) SetNillableSettledAt(v *time.Time) *ChargeCreditPurchaseExternalPaymentUpdate { + if v != nil { + _u.SetSettledAt(*v) + } + return _u +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) ClearSettledAt() *ChargeCreditPurchaseExternalPaymentUpdate { + _u.mutation.ClearSettledAt() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseExternalPaymentUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) SetDeletedAt(v time.Time) *ChargeCreditPurchaseExternalPaymentUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) SetNillableDeletedAt(v *time.Time) *ChargeCreditPurchaseExternalPaymentUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) ClearDeletedAt() *ChargeCreditPurchaseExternalPaymentUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) SetAnnotations(v models.Annotations) *ChargeCreditPurchaseExternalPaymentUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) ClearAnnotations() *ChargeCreditPurchaseExternalPaymentUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// Mutation returns the ChargeCreditPurchaseExternalPaymentMutation object of the builder. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) Mutation() *ChargeCreditPurchaseExternalPaymentMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) 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 *ChargeCreditPurchaseExternalPaymentUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) 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 *ChargeCreditPurchaseExternalPaymentUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargecreditpurchaseexternalpayment.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) check() error { + if v, ok := _u.mutation.Status(); ok { + if err := chargecreditpurchaseexternalpayment.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseExternalPayment.status": %w`, err)} + } + } + if v, ok := _u.mutation.AuthorizedTransactionGroupID(); ok { + if err := chargecreditpurchaseexternalpayment.AuthorizedTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "authorized_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseExternalPayment.authorized_transaction_group_id": %w`, err)} + } + } + if v, ok := _u.mutation.SettledTransactionGroupID(); ok { + if err := chargecreditpurchaseexternalpayment.SettledTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "settled_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseExternalPayment.settled_transaction_group_id": %w`, err)} + } + } + if _u.mutation.CreditPurchaseCleared() && len(_u.mutation.CreditPurchaseIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeCreditPurchaseExternalPayment.credit_purchase"`) + } + return nil +} + +func (_u *ChargeCreditPurchaseExternalPaymentUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargecreditpurchaseexternalpayment.Table, chargecreditpurchaseexternalpayment.Columns, sqlgraph.NewFieldSpec(chargecreditpurchaseexternalpayment.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(chargecreditpurchaseexternalpayment.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldStatus, field.TypeEnum, value) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.AuthorizedTransactionGroupID(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldAuthorizedTransactionGroupID, field.TypeString, value) + } + if _u.mutation.AuthorizedTransactionGroupIDCleared() { + _spec.ClearField(chargecreditpurchaseexternalpayment.FieldAuthorizedTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.AuthorizedAt(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldAuthorizedAt, field.TypeTime, value) + } + if _u.mutation.AuthorizedAtCleared() { + _spec.ClearField(chargecreditpurchaseexternalpayment.FieldAuthorizedAt, field.TypeTime) + } + if value, ok := _u.mutation.SettledTransactionGroupID(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldSettledTransactionGroupID, field.TypeString, value) + } + if _u.mutation.SettledTransactionGroupIDCleared() { + _spec.ClearField(chargecreditpurchaseexternalpayment.FieldSettledTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.SettledAt(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldSettledAt, field.TypeTime, value) + } + if _u.mutation.SettledAtCleared() { + _spec.ClearField(chargecreditpurchaseexternalpayment.FieldSettledAt, field.TypeTime) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargecreditpurchaseexternalpayment.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargecreditpurchaseexternalpayment.FieldAnnotations, field.TypeJSON) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{chargecreditpurchaseexternalpayment.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ChargeCreditPurchaseExternalPaymentUpdateOne is the builder for updating a single ChargeCreditPurchaseExternalPayment entity. +type ChargeCreditPurchaseExternalPaymentUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ChargeCreditPurchaseExternalPaymentMutation +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SetServicePeriodFrom(v time.Time) *ChargeCreditPurchaseExternalPaymentUpdateOne { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SetNillableServicePeriodFrom(v *time.Time) *ChargeCreditPurchaseExternalPaymentUpdateOne { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SetServicePeriodTo(v time.Time) *ChargeCreditPurchaseExternalPaymentUpdateOne { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SetNillableServicePeriodTo(v *time.Time) *ChargeCreditPurchaseExternalPaymentUpdateOne { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetStatus sets the "status" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SetStatus(v payment.Status) *ChargeCreditPurchaseExternalPaymentUpdateOne { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SetNillableStatus(v *payment.Status) *ChargeCreditPurchaseExternalPaymentUpdateOne { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SetAmount(v alpacadecimal.Decimal) *ChargeCreditPurchaseExternalPaymentUpdateOne { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeCreditPurchaseExternalPaymentUpdateOne { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SetAuthorizedTransactionGroupID(v string) *ChargeCreditPurchaseExternalPaymentUpdateOne { + _u.mutation.SetAuthorizedTransactionGroupID(v) + return _u +} + +// SetNillableAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field if the given value is not nil. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SetNillableAuthorizedTransactionGroupID(v *string) *ChargeCreditPurchaseExternalPaymentUpdateOne { + if v != nil { + _u.SetAuthorizedTransactionGroupID(*v) + } + return _u +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) ClearAuthorizedTransactionGroupID() *ChargeCreditPurchaseExternalPaymentUpdateOne { + _u.mutation.ClearAuthorizedTransactionGroupID() + return _u +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SetAuthorizedAt(v time.Time) *ChargeCreditPurchaseExternalPaymentUpdateOne { + _u.mutation.SetAuthorizedAt(v) + return _u +} + +// SetNillableAuthorizedAt sets the "authorized_at" field if the given value is not nil. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SetNillableAuthorizedAt(v *time.Time) *ChargeCreditPurchaseExternalPaymentUpdateOne { + if v != nil { + _u.SetAuthorizedAt(*v) + } + return _u +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) ClearAuthorizedAt() *ChargeCreditPurchaseExternalPaymentUpdateOne { + _u.mutation.ClearAuthorizedAt() + return _u +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SetSettledTransactionGroupID(v string) *ChargeCreditPurchaseExternalPaymentUpdateOne { + _u.mutation.SetSettledTransactionGroupID(v) + return _u +} + +// SetNillableSettledTransactionGroupID sets the "settled_transaction_group_id" field if the given value is not nil. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SetNillableSettledTransactionGroupID(v *string) *ChargeCreditPurchaseExternalPaymentUpdateOne { + if v != nil { + _u.SetSettledTransactionGroupID(*v) + } + return _u +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) ClearSettledTransactionGroupID() *ChargeCreditPurchaseExternalPaymentUpdateOne { + _u.mutation.ClearSettledTransactionGroupID() + return _u +} + +// SetSettledAt sets the "settled_at" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SetSettledAt(v time.Time) *ChargeCreditPurchaseExternalPaymentUpdateOne { + _u.mutation.SetSettledAt(v) + return _u +} + +// SetNillableSettledAt sets the "settled_at" field if the given value is not nil. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SetNillableSettledAt(v *time.Time) *ChargeCreditPurchaseExternalPaymentUpdateOne { + if v != nil { + _u.SetSettledAt(*v) + } + return _u +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) ClearSettledAt() *ChargeCreditPurchaseExternalPaymentUpdateOne { + _u.mutation.ClearSettledAt() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseExternalPaymentUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SetDeletedAt(v time.Time) *ChargeCreditPurchaseExternalPaymentUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SetNillableDeletedAt(v *time.Time) *ChargeCreditPurchaseExternalPaymentUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) ClearDeletedAt() *ChargeCreditPurchaseExternalPaymentUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SetAnnotations(v models.Annotations) *ChargeCreditPurchaseExternalPaymentUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) ClearAnnotations() *ChargeCreditPurchaseExternalPaymentUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// Mutation returns the ChargeCreditPurchaseExternalPaymentMutation object of the builder. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) Mutation() *ChargeCreditPurchaseExternalPaymentMutation { + return _u.mutation +} + +// Where appends a list predicates to the ChargeCreditPurchaseExternalPaymentUpdate builder. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) Where(ps ...predicate.ChargeCreditPurchaseExternalPayment) *ChargeCreditPurchaseExternalPaymentUpdateOne { + _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 *ChargeCreditPurchaseExternalPaymentUpdateOne) Select(field string, fields ...string) *ChargeCreditPurchaseExternalPaymentUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ChargeCreditPurchaseExternalPayment entity. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) Save(ctx context.Context) (*ChargeCreditPurchaseExternalPayment, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) SaveX(ctx context.Context) *ChargeCreditPurchaseExternalPayment { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) 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 *ChargeCreditPurchaseExternalPaymentUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargecreditpurchaseexternalpayment.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) check() error { + if v, ok := _u.mutation.Status(); ok { + if err := chargecreditpurchaseexternalpayment.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseExternalPayment.status": %w`, err)} + } + } + if v, ok := _u.mutation.AuthorizedTransactionGroupID(); ok { + if err := chargecreditpurchaseexternalpayment.AuthorizedTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "authorized_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseExternalPayment.authorized_transaction_group_id": %w`, err)} + } + } + if v, ok := _u.mutation.SettledTransactionGroupID(); ok { + if err := chargecreditpurchaseexternalpayment.SettledTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "settled_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseExternalPayment.settled_transaction_group_id": %w`, err)} + } + } + if _u.mutation.CreditPurchaseCleared() && len(_u.mutation.CreditPurchaseIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeCreditPurchaseExternalPayment.credit_purchase"`) + } + return nil +} + +func (_u *ChargeCreditPurchaseExternalPaymentUpdateOne) sqlSave(ctx context.Context) (_node *ChargeCreditPurchaseExternalPayment, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargecreditpurchaseexternalpayment.Table, chargecreditpurchaseexternalpayment.Columns, sqlgraph.NewFieldSpec(chargecreditpurchaseexternalpayment.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "ChargeCreditPurchaseExternalPayment.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, chargecreditpurchaseexternalpayment.FieldID) + for _, f := range fields { + if !chargecreditpurchaseexternalpayment.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != chargecreditpurchaseexternalpayment.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(chargecreditpurchaseexternalpayment.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldStatus, field.TypeEnum, value) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.AuthorizedTransactionGroupID(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldAuthorizedTransactionGroupID, field.TypeString, value) + } + if _u.mutation.AuthorizedTransactionGroupIDCleared() { + _spec.ClearField(chargecreditpurchaseexternalpayment.FieldAuthorizedTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.AuthorizedAt(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldAuthorizedAt, field.TypeTime, value) + } + if _u.mutation.AuthorizedAtCleared() { + _spec.ClearField(chargecreditpurchaseexternalpayment.FieldAuthorizedAt, field.TypeTime) + } + if value, ok := _u.mutation.SettledTransactionGroupID(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldSettledTransactionGroupID, field.TypeString, value) + } + if _u.mutation.SettledTransactionGroupIDCleared() { + _spec.ClearField(chargecreditpurchaseexternalpayment.FieldSettledTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.SettledAt(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldSettledAt, field.TypeTime, value) + } + if _u.mutation.SettledAtCleared() { + _spec.ClearField(chargecreditpurchaseexternalpayment.FieldSettledAt, field.TypeTime) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargecreditpurchaseexternalpayment.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargecreditpurchaseexternalpayment.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargecreditpurchaseexternalpayment.FieldAnnotations, field.TypeJSON) + } + _node = &ChargeCreditPurchaseExternalPayment{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{chargecreditpurchaseexternalpayment.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/ent/db/chargecreditpurchaseinvoicedpayment.go b/ent/db/chargecreditpurchaseinvoicedpayment.go new file mode 100644 index 0000000000000000000000000000000000000000..37f21bab3e24a0f35088b0c72aeda368df85b405 --- /dev/null +++ b/ent/db/chargecreditpurchaseinvoicedpayment.go @@ -0,0 +1,342 @@ +// 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/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchase" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchaseinvoicedpayment" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeCreditPurchaseInvoicedPayment is the model entity for the ChargeCreditPurchaseInvoicedPayment schema. +type ChargeCreditPurchaseInvoicedPayment 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"` + // InvoiceID holds the value of the "invoice_id" field. + InvoiceID string `json:"invoice_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"` + // ChargeID holds the value of the "charge_id" field. + ChargeID string `json:"charge_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ChargeCreditPurchaseInvoicedPaymentQuery when eager-loading is set. + Edges ChargeCreditPurchaseInvoicedPaymentEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ChargeCreditPurchaseInvoicedPaymentEdges holds the relations/edges for other nodes in the graph. +type ChargeCreditPurchaseInvoicedPaymentEdges struct { + // BillingInvoiceLine holds the value of the billing_invoice_line edge. + BillingInvoiceLine *BillingInvoiceLine `json:"billing_invoice_line,omitempty"` + // CreditPurchase holds the value of the credit_purchase edge. + CreditPurchase *ChargeCreditPurchase `json:"credit_purchase,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// BillingInvoiceLineOrErr returns the BillingInvoiceLine value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeCreditPurchaseInvoicedPaymentEdges) BillingInvoiceLineOrErr() (*BillingInvoiceLine, error) { + if e.BillingInvoiceLine != nil { + return e.BillingInvoiceLine, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: billinginvoiceline.Label} + } + return nil, &NotLoadedError{edge: "billing_invoice_line"} +} + +// CreditPurchaseOrErr returns the CreditPurchase value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeCreditPurchaseInvoicedPaymentEdges) CreditPurchaseOrErr() (*ChargeCreditPurchase, error) { + if e.CreditPurchase != nil { + return e.CreditPurchase, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: chargecreditpurchase.Label} + } + return nil, &NotLoadedError{edge: "credit_purchase"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ChargeCreditPurchaseInvoicedPayment) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case chargecreditpurchaseinvoicedpayment.FieldAnnotations: + values[i] = new([]byte) + case chargecreditpurchaseinvoicedpayment.FieldAmount: + values[i] = new(alpacadecimal.Decimal) + case chargecreditpurchaseinvoicedpayment.FieldID, chargecreditpurchaseinvoicedpayment.FieldLineID, chargecreditpurchaseinvoicedpayment.FieldInvoiceID, chargecreditpurchaseinvoicedpayment.FieldStatus, chargecreditpurchaseinvoicedpayment.FieldAuthorizedTransactionGroupID, chargecreditpurchaseinvoicedpayment.FieldSettledTransactionGroupID, chargecreditpurchaseinvoicedpayment.FieldNamespace, chargecreditpurchaseinvoicedpayment.FieldChargeID: + values[i] = new(sql.NullString) + case chargecreditpurchaseinvoicedpayment.FieldServicePeriodFrom, chargecreditpurchaseinvoicedpayment.FieldServicePeriodTo, chargecreditpurchaseinvoicedpayment.FieldAuthorizedAt, chargecreditpurchaseinvoicedpayment.FieldSettledAt, chargecreditpurchaseinvoicedpayment.FieldCreatedAt, chargecreditpurchaseinvoicedpayment.FieldUpdatedAt, chargecreditpurchaseinvoicedpayment.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 ChargeCreditPurchaseInvoicedPayment fields. +func (_m *ChargeCreditPurchaseInvoicedPayment) 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 chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.FieldInvoiceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field invoice_id", values[i]) + } else if value.Valid { + _m.InvoiceID = value.String + } + case chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.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 + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the ChargeCreditPurchaseInvoicedPayment. +// This includes values selected through modifiers, order, etc. +func (_m *ChargeCreditPurchaseInvoicedPayment) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryBillingInvoiceLine queries the "billing_invoice_line" edge of the ChargeCreditPurchaseInvoicedPayment entity. +func (_m *ChargeCreditPurchaseInvoicedPayment) QueryBillingInvoiceLine() *BillingInvoiceLineQuery { + return NewChargeCreditPurchaseInvoicedPaymentClient(_m.config).QueryBillingInvoiceLine(_m) +} + +// QueryCreditPurchase queries the "credit_purchase" edge of the ChargeCreditPurchaseInvoicedPayment entity. +func (_m *ChargeCreditPurchaseInvoicedPayment) QueryCreditPurchase() *ChargeCreditPurchaseQuery { + return NewChargeCreditPurchaseInvoicedPaymentClient(_m.config).QueryCreditPurchase(_m) +} + +// Update returns a builder for updating this ChargeCreditPurchaseInvoicedPayment. +// Note that you need to call ChargeCreditPurchaseInvoicedPayment.Unwrap() before calling this method if this ChargeCreditPurchaseInvoicedPayment +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ChargeCreditPurchaseInvoicedPayment) Update() *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + return NewChargeCreditPurchaseInvoicedPaymentClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ChargeCreditPurchaseInvoicedPayment 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 *ChargeCreditPurchaseInvoicedPayment) Unwrap() *ChargeCreditPurchaseInvoicedPayment { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: ChargeCreditPurchaseInvoicedPayment is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ChargeCreditPurchaseInvoicedPayment) String() string { + var builder strings.Builder + builder.WriteString("ChargeCreditPurchaseInvoicedPayment(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("line_id=") + builder.WriteString(_m.LineID) + builder.WriteString(", ") + builder.WriteString("invoice_id=") + builder.WriteString(_m.InvoiceID) + 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("charge_id=") + builder.WriteString(_m.ChargeID) + builder.WriteByte(')') + return builder.String() +} + +// ChargeCreditPurchaseInvoicedPayments is a parsable slice of ChargeCreditPurchaseInvoicedPayment. +type ChargeCreditPurchaseInvoicedPayments []*ChargeCreditPurchaseInvoicedPayment diff --git a/ent/db/chargecreditpurchaseinvoicedpayment/chargecreditpurchaseinvoicedpayment.go b/ent/db/chargecreditpurchaseinvoicedpayment/chargecreditpurchaseinvoicedpayment.go new file mode 100644 index 0000000000000000000000000000000000000000..950f40f2b7394f316de34409902779e222ef299c --- /dev/null +++ b/ent/db/chargecreditpurchaseinvoicedpayment/chargecreditpurchaseinvoicedpayment.go @@ -0,0 +1,240 @@ +// Code generated by ent, DO NOT EDIT. + +package chargecreditpurchaseinvoicedpayment + +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 chargecreditpurchaseinvoicedpayment type in the database. + Label = "charge_credit_purchase_invoiced_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" + // FieldInvoiceID holds the string denoting the invoice_id field in the database. + FieldInvoiceID = "invoice_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" + // FieldChargeID holds the string denoting the charge_id field in the database. + FieldChargeID = "charge_id" + // EdgeBillingInvoiceLine holds the string denoting the billing_invoice_line edge name in mutations. + EdgeBillingInvoiceLine = "billing_invoice_line" + // EdgeCreditPurchase holds the string denoting the credit_purchase edge name in mutations. + EdgeCreditPurchase = "credit_purchase" + // Table holds the table name of the chargecreditpurchaseinvoicedpayment in the database. + Table = "charge_credit_purchase_invoiced_payments" + // BillingInvoiceLineTable is the table that holds the billing_invoice_line relation/edge. + BillingInvoiceLineTable = "charge_credit_purchase_invoiced_payments" + // BillingInvoiceLineInverseTable is the table name for the BillingInvoiceLine entity. + // It exists in this package in order to avoid circular dependency with the "billinginvoiceline" package. + BillingInvoiceLineInverseTable = "billing_invoice_lines" + // BillingInvoiceLineColumn is the table column denoting the billing_invoice_line relation/edge. + BillingInvoiceLineColumn = "line_id" + // CreditPurchaseTable is the table that holds the credit_purchase relation/edge. + CreditPurchaseTable = "charge_credit_purchase_invoiced_payments" + // CreditPurchaseInverseTable is the table name for the ChargeCreditPurchase entity. + // It exists in this package in order to avoid circular dependency with the "chargecreditpurchase" package. + CreditPurchaseInverseTable = "charge_credit_purchases" + // CreditPurchaseColumn is the table column denoting the credit_purchase relation/edge. + CreditPurchaseColumn = "charge_id" +) + +// Columns holds all SQL columns for chargecreditpurchaseinvoicedpayment fields. +var Columns = []string{ + FieldID, + FieldLineID, + FieldInvoiceID, + FieldServicePeriodFrom, + FieldServicePeriodTo, + FieldStatus, + FieldAmount, + FieldAuthorizedTransactionGroupID, + FieldAuthorizedAt, + FieldSettledTransactionGroupID, + FieldSettledAt, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldAnnotations, + FieldChargeID, +} + +// 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("chargecreditpurchaseinvoicedpayment: invalid enum value for status field: %q", s) + } +} + +// OrderOption defines the ordering options for the ChargeCreditPurchaseInvoicedPayment 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() +} + +// ByInvoiceID orders the results by the invoice_id field. +func ByInvoiceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoiceID, 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() +} + +// ByChargeID orders the results by the charge_id field. +func ByChargeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChargeID, opts...).ToFunc() +} + +// ByBillingInvoiceLineField orders the results by billing_invoice_line field. +func ByBillingInvoiceLineField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBillingInvoiceLineStep(), sql.OrderByField(field, opts...)) + } +} + +// ByCreditPurchaseField orders the results by credit_purchase field. +func ByCreditPurchaseField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCreditPurchaseStep(), sql.OrderByField(field, opts...)) + } +} +func newBillingInvoiceLineStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BillingInvoiceLineInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, BillingInvoiceLineTable, BillingInvoiceLineColumn), + ) +} +func newCreditPurchaseStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CreditPurchaseInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, CreditPurchaseTable, CreditPurchaseColumn), + ) +} diff --git a/ent/db/chargecreditpurchaseinvoicedpayment/where.go b/ent/db/chargecreditpurchaseinvoicedpayment/where.go new file mode 100644 index 0000000000000000000000000000000000000000..2842ea0206f0239eadac6ad3f36bc786972fb6aa --- /dev/null +++ b/ent/db/chargecreditpurchaseinvoicedpayment/where.go @@ -0,0 +1,999 @@ +// Code generated by ent, DO NOT EDIT. + +package chargecreditpurchaseinvoicedpayment + +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.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldContainsFold(FieldID, id)) +} + +// LineID applies equality check predicate on the "line_id" field. It's identical to LineIDEQ. +func LineID(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldLineID, v)) +} + +// InvoiceID applies equality check predicate on the "invoice_id" field. It's identical to InvoiceIDEQ. +func InvoiceID(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldInvoiceID, v)) +} + +// ServicePeriodFrom applies equality check predicate on the "service_period_from" field. It's identical to ServicePeriodFromEQ. +func ServicePeriodFrom(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(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.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ. +func Amount(v alpacadecimal.Decimal) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(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.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(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.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(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.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(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.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldSettledAt, v)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(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.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(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.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(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.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldDeletedAt, v)) +} + +// ChargeID applies equality check predicate on the "charge_id" field. It's identical to ChargeIDEQ. +func ChargeID(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldChargeID, v)) +} + +// LineIDEQ applies the EQ predicate on the "line_id" field. +func LineIDEQ(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldLineID, v)) +} + +// LineIDNEQ applies the NEQ predicate on the "line_id" field. +func LineIDNEQ(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNEQ(FieldLineID, v)) +} + +// LineIDIn applies the In predicate on the "line_id" field. +func LineIDIn(vs ...string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIn(FieldLineID, vs...)) +} + +// LineIDNotIn applies the NotIn predicate on the "line_id" field. +func LineIDNotIn(vs ...string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotIn(FieldLineID, vs...)) +} + +// LineIDGT applies the GT predicate on the "line_id" field. +func LineIDGT(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGT(FieldLineID, v)) +} + +// LineIDGTE applies the GTE predicate on the "line_id" field. +func LineIDGTE(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGTE(FieldLineID, v)) +} + +// LineIDLT applies the LT predicate on the "line_id" field. +func LineIDLT(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLT(FieldLineID, v)) +} + +// LineIDLTE applies the LTE predicate on the "line_id" field. +func LineIDLTE(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLTE(FieldLineID, v)) +} + +// LineIDContains applies the Contains predicate on the "line_id" field. +func LineIDContains(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldContains(FieldLineID, v)) +} + +// LineIDHasPrefix applies the HasPrefix predicate on the "line_id" field. +func LineIDHasPrefix(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldHasPrefix(FieldLineID, v)) +} + +// LineIDHasSuffix applies the HasSuffix predicate on the "line_id" field. +func LineIDHasSuffix(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldHasSuffix(FieldLineID, v)) +} + +// LineIDEqualFold applies the EqualFold predicate on the "line_id" field. +func LineIDEqualFold(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEqualFold(FieldLineID, v)) +} + +// LineIDContainsFold applies the ContainsFold predicate on the "line_id" field. +func LineIDContainsFold(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldContainsFold(FieldLineID, v)) +} + +// InvoiceIDEQ applies the EQ predicate on the "invoice_id" field. +func InvoiceIDEQ(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldInvoiceID, v)) +} + +// InvoiceIDNEQ applies the NEQ predicate on the "invoice_id" field. +func InvoiceIDNEQ(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNEQ(FieldInvoiceID, v)) +} + +// InvoiceIDIn applies the In predicate on the "invoice_id" field. +func InvoiceIDIn(vs ...string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIn(FieldInvoiceID, vs...)) +} + +// InvoiceIDNotIn applies the NotIn predicate on the "invoice_id" field. +func InvoiceIDNotIn(vs ...string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotIn(FieldInvoiceID, vs...)) +} + +// InvoiceIDGT applies the GT predicate on the "invoice_id" field. +func InvoiceIDGT(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGT(FieldInvoiceID, v)) +} + +// InvoiceIDGTE applies the GTE predicate on the "invoice_id" field. +func InvoiceIDGTE(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGTE(FieldInvoiceID, v)) +} + +// InvoiceIDLT applies the LT predicate on the "invoice_id" field. +func InvoiceIDLT(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLT(FieldInvoiceID, v)) +} + +// InvoiceIDLTE applies the LTE predicate on the "invoice_id" field. +func InvoiceIDLTE(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLTE(FieldInvoiceID, v)) +} + +// InvoiceIDContains applies the Contains predicate on the "invoice_id" field. +func InvoiceIDContains(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldContains(FieldInvoiceID, v)) +} + +// InvoiceIDHasPrefix applies the HasPrefix predicate on the "invoice_id" field. +func InvoiceIDHasPrefix(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldHasPrefix(FieldInvoiceID, v)) +} + +// InvoiceIDHasSuffix applies the HasSuffix predicate on the "invoice_id" field. +func InvoiceIDHasSuffix(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldHasSuffix(FieldInvoiceID, v)) +} + +// InvoiceIDEqualFold applies the EqualFold predicate on the "invoice_id" field. +func InvoiceIDEqualFold(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEqualFold(FieldInvoiceID, v)) +} + +// InvoiceIDContainsFold applies the ContainsFold predicate on the "invoice_id" field. +func InvoiceIDContainsFold(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldContainsFold(FieldInvoiceID, v)) +} + +// ServicePeriodFromEQ applies the EQ predicate on the "service_period_from" field. +func ServicePeriodFromEQ(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromNEQ applies the NEQ predicate on the "service_period_from" field. +func ServicePeriodFromNEQ(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromIn applies the In predicate on the "service_period_from" field. +func ServicePeriodFromIn(vs ...time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromNotIn applies the NotIn predicate on the "service_period_from" field. +func ServicePeriodFromNotIn(vs ...time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromGT applies the GT predicate on the "service_period_from" field. +func ServicePeriodFromGT(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromGTE applies the GTE predicate on the "service_period_from" field. +func ServicePeriodFromGTE(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLT applies the LT predicate on the "service_period_from" field. +func ServicePeriodFromLT(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLTE applies the LTE predicate on the "service_period_from" field. +func ServicePeriodFromLTE(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodToEQ applies the EQ predicate on the "service_period_to" field. +func ServicePeriodToEQ(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToNEQ applies the NEQ predicate on the "service_period_to" field. +func ServicePeriodToNEQ(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToIn applies the In predicate on the "service_period_to" field. +func ServicePeriodToIn(vs ...time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToNotIn applies the NotIn predicate on the "service_period_to" field. +func ServicePeriodToNotIn(vs ...time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToGT applies the GT predicate on the "service_period_to" field. +func ServicePeriodToGT(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToGTE applies the GTE predicate on the "service_period_to" field. +func ServicePeriodToGTE(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGTE(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLT applies the LT predicate on the "service_period_to" field. +func ServicePeriodToLT(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLTE applies the LTE predicate on the "service_period_to" field. +func ServicePeriodToLTE(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLTE(FieldServicePeriodTo, v)) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v payment.Status) predicate.ChargeCreditPurchaseInvoicedPayment { + vc := v + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldStatus, vc)) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v payment.Status) predicate.ChargeCreditPurchaseInvoicedPayment { + vc := v + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNEQ(FieldStatus, vc)) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...payment.Status) predicate.ChargeCreditPurchaseInvoicedPayment { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIn(FieldStatus, v...)) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...payment.Status) predicate.ChargeCreditPurchaseInvoicedPayment { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotIn(FieldStatus, v...)) +} + +// AmountEQ applies the EQ predicate on the "amount" field. +func AmountEQ(v alpacadecimal.Decimal) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldAmount, v)) +} + +// AmountNEQ applies the NEQ predicate on the "amount" field. +func AmountNEQ(v alpacadecimal.Decimal) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNEQ(FieldAmount, v)) +} + +// AmountIn applies the In predicate on the "amount" field. +func AmountIn(vs ...alpacadecimal.Decimal) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIn(FieldAmount, vs...)) +} + +// AmountNotIn applies the NotIn predicate on the "amount" field. +func AmountNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotIn(FieldAmount, vs...)) +} + +// AmountGT applies the GT predicate on the "amount" field. +func AmountGT(v alpacadecimal.Decimal) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGT(FieldAmount, v)) +} + +// AmountGTE applies the GTE predicate on the "amount" field. +func AmountGTE(v alpacadecimal.Decimal) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGTE(FieldAmount, v)) +} + +// AmountLT applies the LT predicate on the "amount" field. +func AmountLT(v alpacadecimal.Decimal) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLT(FieldAmount, v)) +} + +// AmountLTE applies the LTE predicate on the "amount" field. +func AmountLTE(v alpacadecimal.Decimal) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLTE(FieldAmount, v)) +} + +// AuthorizedTransactionGroupIDEQ applies the EQ predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDEQ(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDNEQ applies the NEQ predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDNEQ(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNEQ(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDIn applies the In predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDIn(vs ...string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIn(FieldAuthorizedTransactionGroupID, vs...)) +} + +// AuthorizedTransactionGroupIDNotIn applies the NotIn predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDNotIn(vs ...string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotIn(FieldAuthorizedTransactionGroupID, vs...)) +} + +// AuthorizedTransactionGroupIDGT applies the GT predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDGT(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGT(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDGTE applies the GTE predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDGTE(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGTE(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDLT applies the LT predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDLT(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLT(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDLTE applies the LTE predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDLTE(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLTE(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDContains applies the Contains predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDContains(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldContains(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDHasPrefix applies the HasPrefix predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDHasPrefix(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldHasPrefix(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDHasSuffix applies the HasSuffix predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDHasSuffix(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldHasSuffix(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDIsNil applies the IsNil predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDIsNil() predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIsNull(FieldAuthorizedTransactionGroupID)) +} + +// AuthorizedTransactionGroupIDNotNil applies the NotNil predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDNotNil() predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotNull(FieldAuthorizedTransactionGroupID)) +} + +// AuthorizedTransactionGroupIDEqualFold applies the EqualFold predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDEqualFold(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEqualFold(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDContainsFold applies the ContainsFold predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDContainsFold(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldContainsFold(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedAtEQ applies the EQ predicate on the "authorized_at" field. +func AuthorizedAtEQ(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldAuthorizedAt, v)) +} + +// AuthorizedAtNEQ applies the NEQ predicate on the "authorized_at" field. +func AuthorizedAtNEQ(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNEQ(FieldAuthorizedAt, v)) +} + +// AuthorizedAtIn applies the In predicate on the "authorized_at" field. +func AuthorizedAtIn(vs ...time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIn(FieldAuthorizedAt, vs...)) +} + +// AuthorizedAtNotIn applies the NotIn predicate on the "authorized_at" field. +func AuthorizedAtNotIn(vs ...time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotIn(FieldAuthorizedAt, vs...)) +} + +// AuthorizedAtGT applies the GT predicate on the "authorized_at" field. +func AuthorizedAtGT(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGT(FieldAuthorizedAt, v)) +} + +// AuthorizedAtGTE applies the GTE predicate on the "authorized_at" field. +func AuthorizedAtGTE(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGTE(FieldAuthorizedAt, v)) +} + +// AuthorizedAtLT applies the LT predicate on the "authorized_at" field. +func AuthorizedAtLT(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLT(FieldAuthorizedAt, v)) +} + +// AuthorizedAtLTE applies the LTE predicate on the "authorized_at" field. +func AuthorizedAtLTE(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLTE(FieldAuthorizedAt, v)) +} + +// AuthorizedAtIsNil applies the IsNil predicate on the "authorized_at" field. +func AuthorizedAtIsNil() predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIsNull(FieldAuthorizedAt)) +} + +// AuthorizedAtNotNil applies the NotNil predicate on the "authorized_at" field. +func AuthorizedAtNotNil() predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotNull(FieldAuthorizedAt)) +} + +// SettledTransactionGroupIDEQ applies the EQ predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDEQ(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDNEQ applies the NEQ predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDNEQ(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNEQ(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDIn applies the In predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDIn(vs ...string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIn(FieldSettledTransactionGroupID, vs...)) +} + +// SettledTransactionGroupIDNotIn applies the NotIn predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDNotIn(vs ...string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotIn(FieldSettledTransactionGroupID, vs...)) +} + +// SettledTransactionGroupIDGT applies the GT predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDGT(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGT(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDGTE applies the GTE predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDGTE(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGTE(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDLT applies the LT predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDLT(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLT(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDLTE applies the LTE predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDLTE(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLTE(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDContains applies the Contains predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDContains(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldContains(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDHasPrefix applies the HasPrefix predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDHasPrefix(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldHasPrefix(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDHasSuffix applies the HasSuffix predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDHasSuffix(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldHasSuffix(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDIsNil applies the IsNil predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDIsNil() predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIsNull(FieldSettledTransactionGroupID)) +} + +// SettledTransactionGroupIDNotNil applies the NotNil predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDNotNil() predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotNull(FieldSettledTransactionGroupID)) +} + +// SettledTransactionGroupIDEqualFold applies the EqualFold predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDEqualFold(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEqualFold(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDContainsFold applies the ContainsFold predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDContainsFold(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldContainsFold(FieldSettledTransactionGroupID, v)) +} + +// SettledAtEQ applies the EQ predicate on the "settled_at" field. +func SettledAtEQ(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldSettledAt, v)) +} + +// SettledAtNEQ applies the NEQ predicate on the "settled_at" field. +func SettledAtNEQ(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNEQ(FieldSettledAt, v)) +} + +// SettledAtIn applies the In predicate on the "settled_at" field. +func SettledAtIn(vs ...time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIn(FieldSettledAt, vs...)) +} + +// SettledAtNotIn applies the NotIn predicate on the "settled_at" field. +func SettledAtNotIn(vs ...time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotIn(FieldSettledAt, vs...)) +} + +// SettledAtGT applies the GT predicate on the "settled_at" field. +func SettledAtGT(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGT(FieldSettledAt, v)) +} + +// SettledAtGTE applies the GTE predicate on the "settled_at" field. +func SettledAtGTE(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGTE(FieldSettledAt, v)) +} + +// SettledAtLT applies the LT predicate on the "settled_at" field. +func SettledAtLT(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLT(FieldSettledAt, v)) +} + +// SettledAtLTE applies the LTE predicate on the "settled_at" field. +func SettledAtLTE(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLTE(FieldSettledAt, v)) +} + +// SettledAtIsNil applies the IsNil predicate on the "settled_at" field. +func SettledAtIsNil() predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIsNull(FieldSettledAt)) +} + +// SettledAtNotNil applies the NotNil predicate on the "settled_at" field. +func SettledAtNotNil() predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotNull(FieldSettledAt)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotNull(FieldDeletedAt)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotNull(FieldAnnotations)) +} + +// ChargeIDEQ applies the EQ predicate on the "charge_id" field. +func ChargeIDEQ(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEQ(FieldChargeID, v)) +} + +// ChargeIDNEQ applies the NEQ predicate on the "charge_id" field. +func ChargeIDNEQ(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNEQ(FieldChargeID, v)) +} + +// ChargeIDIn applies the In predicate on the "charge_id" field. +func ChargeIDIn(vs ...string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldIn(FieldChargeID, vs...)) +} + +// ChargeIDNotIn applies the NotIn predicate on the "charge_id" field. +func ChargeIDNotIn(vs ...string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldNotIn(FieldChargeID, vs...)) +} + +// ChargeIDGT applies the GT predicate on the "charge_id" field. +func ChargeIDGT(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGT(FieldChargeID, v)) +} + +// ChargeIDGTE applies the GTE predicate on the "charge_id" field. +func ChargeIDGTE(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldGTE(FieldChargeID, v)) +} + +// ChargeIDLT applies the LT predicate on the "charge_id" field. +func ChargeIDLT(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLT(FieldChargeID, v)) +} + +// ChargeIDLTE applies the LTE predicate on the "charge_id" field. +func ChargeIDLTE(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldLTE(FieldChargeID, v)) +} + +// ChargeIDContains applies the Contains predicate on the "charge_id" field. +func ChargeIDContains(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldContains(FieldChargeID, v)) +} + +// ChargeIDHasPrefix applies the HasPrefix predicate on the "charge_id" field. +func ChargeIDHasPrefix(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldHasPrefix(FieldChargeID, v)) +} + +// ChargeIDHasSuffix applies the HasSuffix predicate on the "charge_id" field. +func ChargeIDHasSuffix(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldHasSuffix(FieldChargeID, v)) +} + +// ChargeIDEqualFold applies the EqualFold predicate on the "charge_id" field. +func ChargeIDEqualFold(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldEqualFold(FieldChargeID, v)) +} + +// ChargeIDContainsFold applies the ContainsFold predicate on the "charge_id" field. +func ChargeIDContainsFold(v string) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.FieldContainsFold(FieldChargeID, v)) +} + +// HasBillingInvoiceLine applies the HasEdge predicate on the "billing_invoice_line" edge. +func HasBillingInvoiceLine() predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, BillingInvoiceLineTable, BillingInvoiceLineColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBillingInvoiceLineWith applies the HasEdge predicate on the "billing_invoice_line" edge with a given conditions (other predicates). +func HasBillingInvoiceLineWith(preds ...predicate.BillingInvoiceLine) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(func(s *sql.Selector) { + step := newBillingInvoiceLineStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasCreditPurchase applies the HasEdge predicate on the "credit_purchase" edge. +func HasCreditPurchase() predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, CreditPurchaseTable, CreditPurchaseColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCreditPurchaseWith applies the HasEdge predicate on the "credit_purchase" edge with a given conditions (other predicates). +func HasCreditPurchaseWith(preds ...predicate.ChargeCreditPurchase) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(func(s *sql.Selector) { + step := newCreditPurchaseStep() + 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.ChargeCreditPurchaseInvoicedPayment) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ChargeCreditPurchaseInvoicedPayment) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ChargeCreditPurchaseInvoicedPayment) predicate.ChargeCreditPurchaseInvoicedPayment { + return predicate.ChargeCreditPurchaseInvoicedPayment(sql.NotPredicates(p)) +} diff --git a/ent/db/chargecreditpurchaseinvoicedpayment_create.go b/ent/db/chargecreditpurchaseinvoicedpayment_create.go new file mode 100644 index 0000000000000000000000000000000000000000..db8db34d241aca94e02c010f56000d3a72c79929 --- /dev/null +++ b/ent/db/chargecreditpurchaseinvoicedpayment_create.go @@ -0,0 +1,1378 @@ +// 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/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchase" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchaseinvoicedpayment" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeCreditPurchaseInvoicedPaymentCreate is the builder for creating a ChargeCreditPurchaseInvoicedPayment entity. +type ChargeCreditPurchaseInvoicedPaymentCreate struct { + config + mutation *ChargeCreditPurchaseInvoicedPaymentMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetLineID sets the "line_id" field. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetLineID(v string) *ChargeCreditPurchaseInvoicedPaymentCreate { + _c.mutation.SetLineID(v) + return _c +} + +// SetInvoiceID sets the "invoice_id" field. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetInvoiceID(v string) *ChargeCreditPurchaseInvoicedPaymentCreate { + _c.mutation.SetInvoiceID(v) + return _c +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetServicePeriodFrom(v time.Time) *ChargeCreditPurchaseInvoicedPaymentCreate { + _c.mutation.SetServicePeriodFrom(v) + return _c +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetServicePeriodTo(v time.Time) *ChargeCreditPurchaseInvoicedPaymentCreate { + _c.mutation.SetServicePeriodTo(v) + return _c +} + +// SetStatus sets the "status" field. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetStatus(v payment.Status) *ChargeCreditPurchaseInvoicedPaymentCreate { + _c.mutation.SetStatus(v) + return _c +} + +// SetAmount sets the "amount" field. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetAmount(v alpacadecimal.Decimal) *ChargeCreditPurchaseInvoicedPaymentCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetAuthorizedTransactionGroupID(v string) *ChargeCreditPurchaseInvoicedPaymentCreate { + _c.mutation.SetAuthorizedTransactionGroupID(v) + return _c +} + +// SetNillableAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field if the given value is not nil. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetNillableAuthorizedTransactionGroupID(v *string) *ChargeCreditPurchaseInvoicedPaymentCreate { + if v != nil { + _c.SetAuthorizedTransactionGroupID(*v) + } + return _c +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetAuthorizedAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentCreate { + _c.mutation.SetAuthorizedAt(v) + return _c +} + +// SetNillableAuthorizedAt sets the "authorized_at" field if the given value is not nil. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetNillableAuthorizedAt(v *time.Time) *ChargeCreditPurchaseInvoicedPaymentCreate { + if v != nil { + _c.SetAuthorizedAt(*v) + } + return _c +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetSettledTransactionGroupID(v string) *ChargeCreditPurchaseInvoicedPaymentCreate { + _c.mutation.SetSettledTransactionGroupID(v) + return _c +} + +// SetNillableSettledTransactionGroupID sets the "settled_transaction_group_id" field if the given value is not nil. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetNillableSettledTransactionGroupID(v *string) *ChargeCreditPurchaseInvoicedPaymentCreate { + if v != nil { + _c.SetSettledTransactionGroupID(*v) + } + return _c +} + +// SetSettledAt sets the "settled_at" field. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetSettledAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentCreate { + _c.mutation.SetSettledAt(v) + return _c +} + +// SetNillableSettledAt sets the "settled_at" field if the given value is not nil. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetNillableSettledAt(v *time.Time) *ChargeCreditPurchaseInvoicedPaymentCreate { + if v != nil { + _c.SetSettledAt(*v) + } + return _c +} + +// SetNamespace sets the "namespace" field. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetNamespace(v string) *ChargeCreditPurchaseInvoicedPaymentCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetCreatedAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetNillableCreatedAt(v *time.Time) *ChargeCreditPurchaseInvoicedPaymentCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetNillableUpdatedAt(v *time.Time) *ChargeCreditPurchaseInvoicedPaymentCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetDeletedAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetNillableDeletedAt(v *time.Time) *ChargeCreditPurchaseInvoicedPaymentCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetAnnotations(v models.Annotations) *ChargeCreditPurchaseInvoicedPaymentCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetChargeID sets the "charge_id" field. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetChargeID(v string) *ChargeCreditPurchaseInvoicedPaymentCreate { + _c.mutation.SetChargeID(v) + return _c +} + +// SetID sets the "id" field. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetID(v string) *ChargeCreditPurchaseInvoicedPaymentCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetNillableID(v *string) *ChargeCreditPurchaseInvoicedPaymentCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetBillingInvoiceLineID(id string) *ChargeCreditPurchaseInvoicedPaymentCreate { + _c.mutation.SetBillingInvoiceLineID(id) + return _c +} + +// SetBillingInvoiceLine sets the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetBillingInvoiceLine(v *BillingInvoiceLine) *ChargeCreditPurchaseInvoicedPaymentCreate { + return _c.SetBillingInvoiceLineID(v.ID) +} + +// SetCreditPurchaseID sets the "credit_purchase" edge to the ChargeCreditPurchase entity by ID. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetCreditPurchaseID(id string) *ChargeCreditPurchaseInvoicedPaymentCreate { + _c.mutation.SetCreditPurchaseID(id) + return _c +} + +// SetCreditPurchase sets the "credit_purchase" edge to the ChargeCreditPurchase entity. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SetCreditPurchase(v *ChargeCreditPurchase) *ChargeCreditPurchaseInvoicedPaymentCreate { + return _c.SetCreditPurchaseID(v.ID) +} + +// Mutation returns the ChargeCreditPurchaseInvoicedPaymentMutation object of the builder. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) Mutation() *ChargeCreditPurchaseInvoicedPaymentMutation { + return _c.mutation +} + +// Save creates the ChargeCreditPurchaseInvoicedPayment in the database. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) Save(ctx context.Context) (*ChargeCreditPurchaseInvoicedPayment, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) SaveX(ctx context.Context) *ChargeCreditPurchaseInvoicedPayment { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) 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 *ChargeCreditPurchaseInvoicedPaymentCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := chargecreditpurchaseinvoicedpayment.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := chargecreditpurchaseinvoicedpayment.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := chargecreditpurchaseinvoicedpayment.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) check() error { + if _, ok := _c.mutation.LineID(); !ok { + return &ValidationError{Name: "line_id", err: errors.New(`db: missing required field "ChargeCreditPurchaseInvoicedPayment.line_id"`)} + } + if _, ok := _c.mutation.InvoiceID(); !ok { + return &ValidationError{Name: "invoice_id", err: errors.New(`db: missing required field "ChargeCreditPurchaseInvoicedPayment.invoice_id"`)} + } + if _, ok := _c.mutation.ServicePeriodFrom(); !ok { + return &ValidationError{Name: "service_period_from", err: errors.New(`db: missing required field "ChargeCreditPurchaseInvoicedPayment.service_period_from"`)} + } + if _, ok := _c.mutation.ServicePeriodTo(); !ok { + return &ValidationError{Name: "service_period_to", err: errors.New(`db: missing required field "ChargeCreditPurchaseInvoicedPayment.service_period_to"`)} + } + if _, ok := _c.mutation.Status(); !ok { + return &ValidationError{Name: "status", err: errors.New(`db: missing required field "ChargeCreditPurchaseInvoicedPayment.status"`)} + } + if v, ok := _c.mutation.Status(); ok { + if err := chargecreditpurchaseinvoicedpayment.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseInvoicedPayment.status": %w`, err)} + } + } + if _, ok := _c.mutation.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`db: missing required field "ChargeCreditPurchaseInvoicedPayment.amount"`)} + } + if v, ok := _c.mutation.AuthorizedTransactionGroupID(); ok { + if err := chargecreditpurchaseinvoicedpayment.AuthorizedTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "authorized_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseInvoicedPayment.authorized_transaction_group_id": %w`, err)} + } + } + if v, ok := _c.mutation.SettledTransactionGroupID(); ok { + if err := chargecreditpurchaseinvoicedpayment.SettledTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "settled_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseInvoicedPayment.settled_transaction_group_id": %w`, err)} + } + } + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "ChargeCreditPurchaseInvoicedPayment.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := chargecreditpurchaseinvoicedpayment.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseInvoicedPayment.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "ChargeCreditPurchaseInvoicedPayment.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "ChargeCreditPurchaseInvoicedPayment.updated_at"`)} + } + if _, ok := _c.mutation.ChargeID(); !ok { + return &ValidationError{Name: "charge_id", err: errors.New(`db: missing required field "ChargeCreditPurchaseInvoicedPayment.charge_id"`)} + } + if len(_c.mutation.BillingInvoiceLineIDs()) == 0 { + return &ValidationError{Name: "billing_invoice_line", err: errors.New(`db: missing required edge "ChargeCreditPurchaseInvoicedPayment.billing_invoice_line"`)} + } + if len(_c.mutation.CreditPurchaseIDs()) == 0 { + return &ValidationError{Name: "credit_purchase", err: errors.New(`db: missing required edge "ChargeCreditPurchaseInvoicedPayment.credit_purchase"`)} + } + return nil +} + +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) sqlSave(ctx context.Context) (*ChargeCreditPurchaseInvoicedPayment, 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 ChargeCreditPurchaseInvoicedPayment.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) createSpec() (*ChargeCreditPurchaseInvoicedPayment, *sqlgraph.CreateSpec) { + var ( + _node = &ChargeCreditPurchaseInvoicedPayment{config: _c.config} + _spec = sqlgraph.NewCreateSpec(chargecreditpurchaseinvoicedpayment.Table, sqlgraph.NewFieldSpec(chargecreditpurchaseinvoicedpayment.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.InvoiceID(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldInvoiceID, field.TypeString, value) + _node.InvoiceID = value + } + if value, ok := _c.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldServicePeriodFrom, field.TypeTime, value) + _node.ServicePeriodFrom = value + } + if value, ok := _c.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldServicePeriodTo, field.TypeTime, value) + _node.ServicePeriodTo = value + } + if value, ok := _c.mutation.Status(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldStatus, field.TypeEnum, value) + _node.Status = value + } + if value, ok := _c.mutation.Amount(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldAmount, field.TypeOther, value) + _node.Amount = value + } + if value, ok := _c.mutation.AuthorizedTransactionGroupID(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldAuthorizedTransactionGroupID, field.TypeString, value) + _node.AuthorizedTransactionGroupID = &value + } + if value, ok := _c.mutation.AuthorizedAt(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldAuthorizedAt, field.TypeTime, value) + _node.AuthorizedAt = &value + } + if value, ok := _c.mutation.SettledTransactionGroupID(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldSettledTransactionGroupID, field.TypeString, value) + _node.SettledTransactionGroupID = &value + } + if value, ok := _c.mutation.SettledAt(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldSettledAt, field.TypeTime, value) + _node.SettledAt = &value + } + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if nodes := _c.mutation.BillingInvoiceLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargecreditpurchaseinvoicedpayment.BillingInvoiceLineTable, + Columns: []string{chargecreditpurchaseinvoicedpayment.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.LineID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.CreditPurchaseIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargecreditpurchaseinvoicedpayment.CreditPurchaseTable, + Columns: []string{chargecreditpurchaseinvoicedpayment.CreditPurchaseColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchase.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) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ChargeCreditPurchaseInvoicedPayment.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.ChargeCreditPurchaseInvoicedPaymentUpsert) { +// SetLineID(v+v). +// }). +// Exec(ctx) +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) OnConflict(opts ...sql.ConflictOption) *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + _c.conflict = opts + return &ChargeCreditPurchaseInvoicedPaymentUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeCreditPurchaseInvoicedPayment.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeCreditPurchaseInvoicedPaymentCreate) OnConflictColumns(columns ...string) *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeCreditPurchaseInvoicedPaymentUpsertOne{ + create: _c, + } +} + +type ( + // ChargeCreditPurchaseInvoicedPaymentUpsertOne is the builder for "upsert"-ing + // one ChargeCreditPurchaseInvoicedPayment node. + ChargeCreditPurchaseInvoicedPaymentUpsertOne struct { + create *ChargeCreditPurchaseInvoicedPaymentCreate + } + + // ChargeCreditPurchaseInvoicedPaymentUpsert is the "OnConflict" setter. + ChargeCreditPurchaseInvoicedPaymentUpsert struct { + *sql.UpdateSet + } +) + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) SetServicePeriodFrom(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.Set(chargecreditpurchaseinvoicedpayment.FieldServicePeriodFrom, v) + return u +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) UpdateServicePeriodFrom() *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.SetExcluded(chargecreditpurchaseinvoicedpayment.FieldServicePeriodFrom) + return u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) SetServicePeriodTo(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.Set(chargecreditpurchaseinvoicedpayment.FieldServicePeriodTo, v) + return u +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) UpdateServicePeriodTo() *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.SetExcluded(chargecreditpurchaseinvoicedpayment.FieldServicePeriodTo) + return u +} + +// SetStatus sets the "status" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) SetStatus(v payment.Status) *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.Set(chargecreditpurchaseinvoicedpayment.FieldStatus, v) + return u +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) UpdateStatus() *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.SetExcluded(chargecreditpurchaseinvoicedpayment.FieldStatus) + return u +} + +// SetAmount sets the "amount" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) SetAmount(v alpacadecimal.Decimal) *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.Set(chargecreditpurchaseinvoicedpayment.FieldAmount, v) + return u +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) UpdateAmount() *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.SetExcluded(chargecreditpurchaseinvoicedpayment.FieldAmount) + return u +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) SetAuthorizedTransactionGroupID(v string) *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.Set(chargecreditpurchaseinvoicedpayment.FieldAuthorizedTransactionGroupID, v) + return u +} + +// UpdateAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) UpdateAuthorizedTransactionGroupID() *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.SetExcluded(chargecreditpurchaseinvoicedpayment.FieldAuthorizedTransactionGroupID) + return u +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) ClearAuthorizedTransactionGroupID() *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.SetNull(chargecreditpurchaseinvoicedpayment.FieldAuthorizedTransactionGroupID) + return u +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) SetAuthorizedAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.Set(chargecreditpurchaseinvoicedpayment.FieldAuthorizedAt, v) + return u +} + +// UpdateAuthorizedAt sets the "authorized_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) UpdateAuthorizedAt() *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.SetExcluded(chargecreditpurchaseinvoicedpayment.FieldAuthorizedAt) + return u +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) ClearAuthorizedAt() *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.SetNull(chargecreditpurchaseinvoicedpayment.FieldAuthorizedAt) + return u +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) SetSettledTransactionGroupID(v string) *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.Set(chargecreditpurchaseinvoicedpayment.FieldSettledTransactionGroupID, v) + return u +} + +// UpdateSettledTransactionGroupID sets the "settled_transaction_group_id" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) UpdateSettledTransactionGroupID() *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.SetExcluded(chargecreditpurchaseinvoicedpayment.FieldSettledTransactionGroupID) + return u +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) ClearSettledTransactionGroupID() *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.SetNull(chargecreditpurchaseinvoicedpayment.FieldSettledTransactionGroupID) + return u +} + +// SetSettledAt sets the "settled_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) SetSettledAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.Set(chargecreditpurchaseinvoicedpayment.FieldSettledAt, v) + return u +} + +// UpdateSettledAt sets the "settled_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) UpdateSettledAt() *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.SetExcluded(chargecreditpurchaseinvoicedpayment.FieldSettledAt) + return u +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) ClearSettledAt() *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.SetNull(chargecreditpurchaseinvoicedpayment.FieldSettledAt) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.Set(chargecreditpurchaseinvoicedpayment.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) UpdateUpdatedAt() *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.SetExcluded(chargecreditpurchaseinvoicedpayment.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) SetDeletedAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.Set(chargecreditpurchaseinvoicedpayment.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) UpdateDeletedAt() *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.SetExcluded(chargecreditpurchaseinvoicedpayment.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) ClearDeletedAt() *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.SetNull(chargecreditpurchaseinvoicedpayment.FieldDeletedAt) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) SetAnnotations(v models.Annotations) *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.Set(chargecreditpurchaseinvoicedpayment.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) UpdateAnnotations() *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.SetExcluded(chargecreditpurchaseinvoicedpayment.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsert) ClearAnnotations() *ChargeCreditPurchaseInvoicedPaymentUpsert { + u.SetNull(chargecreditpurchaseinvoicedpayment.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.ChargeCreditPurchaseInvoicedPayment.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargecreditpurchaseinvoicedpayment.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) UpdateNewValues() *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + 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(chargecreditpurchaseinvoicedpayment.FieldID) + } + if _, exists := u.create.mutation.LineID(); exists { + s.SetIgnore(chargecreditpurchaseinvoicedpayment.FieldLineID) + } + if _, exists := u.create.mutation.InvoiceID(); exists { + s.SetIgnore(chargecreditpurchaseinvoicedpayment.FieldInvoiceID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(chargecreditpurchaseinvoicedpayment.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(chargecreditpurchaseinvoicedpayment.FieldCreatedAt) + } + if _, exists := u.create.mutation.ChargeID(); exists { + s.SetIgnore(chargecreditpurchaseinvoicedpayment.FieldChargeID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeCreditPurchaseInvoicedPayment.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) Ignore() *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + 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 *ChargeCreditPurchaseInvoicedPaymentUpsertOne) DoNothing() *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeCreditPurchaseInvoicedPaymentCreate.OnConflict +// documentation for more info. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) Update(set func(*ChargeCreditPurchaseInvoicedPaymentUpsert)) *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeCreditPurchaseInvoicedPaymentUpsert{UpdateSet: update}) + })) + return u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) SetServicePeriodFrom(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) UpdateServicePeriodFrom() *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) SetServicePeriodTo(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) UpdateServicePeriodTo() *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetStatus sets the "status" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) SetStatus(v payment.Status) *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) UpdateStatus() *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateStatus() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) SetAmount(v alpacadecimal.Decimal) *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) UpdateAmount() *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateAmount() + }) +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) SetAuthorizedTransactionGroupID(v string) *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetAuthorizedTransactionGroupID(v) + }) +} + +// UpdateAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) UpdateAuthorizedTransactionGroupID() *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateAuthorizedTransactionGroupID() + }) +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) ClearAuthorizedTransactionGroupID() *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.ClearAuthorizedTransactionGroupID() + }) +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) SetAuthorizedAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetAuthorizedAt(v) + }) +} + +// UpdateAuthorizedAt sets the "authorized_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) UpdateAuthorizedAt() *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateAuthorizedAt() + }) +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) ClearAuthorizedAt() *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.ClearAuthorizedAt() + }) +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) SetSettledTransactionGroupID(v string) *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetSettledTransactionGroupID(v) + }) +} + +// UpdateSettledTransactionGroupID sets the "settled_transaction_group_id" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) UpdateSettledTransactionGroupID() *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateSettledTransactionGroupID() + }) +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) ClearSettledTransactionGroupID() *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.ClearSettledTransactionGroupID() + }) +} + +// SetSettledAt sets the "settled_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) SetSettledAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetSettledAt(v) + }) +} + +// UpdateSettledAt sets the "settled_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) UpdateSettledAt() *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateSettledAt() + }) +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) ClearSettledAt() *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.ClearSettledAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) UpdateUpdatedAt() *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) SetDeletedAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) UpdateDeletedAt() *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) ClearDeletedAt() *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) SetAnnotations(v models.Annotations) *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) UpdateAnnotations() *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) ClearAnnotations() *ChargeCreditPurchaseInvoicedPaymentUpsertOne { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.ClearAnnotations() + }) +} + +// Exec executes the query. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeCreditPurchaseInvoicedPaymentCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertOne) 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 *ChargeCreditPurchaseInvoicedPaymentUpsertOne) 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: ChargeCreditPurchaseInvoicedPaymentUpsertOne.ID is not supported by MySQL driver. Use ChargeCreditPurchaseInvoicedPaymentUpsertOne.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 *ChargeCreditPurchaseInvoicedPaymentUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ChargeCreditPurchaseInvoicedPaymentCreateBulk is the builder for creating many ChargeCreditPurchaseInvoicedPayment entities in bulk. +type ChargeCreditPurchaseInvoicedPaymentCreateBulk struct { + config + err error + builders []*ChargeCreditPurchaseInvoicedPaymentCreate + conflict []sql.ConflictOption +} + +// Save creates the ChargeCreditPurchaseInvoicedPayment entities in the database. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreateBulk) Save(ctx context.Context) ([]*ChargeCreditPurchaseInvoicedPayment, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ChargeCreditPurchaseInvoicedPayment, 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.(*ChargeCreditPurchaseInvoicedPaymentMutation) + 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 *ChargeCreditPurchaseInvoicedPaymentCreateBulk) SaveX(ctx context.Context) []*ChargeCreditPurchaseInvoicedPayment { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeCreditPurchaseInvoicedPaymentCreateBulk) 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.ChargeCreditPurchaseInvoicedPayment.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.ChargeCreditPurchaseInvoicedPaymentUpsert) { +// SetLineID(v+v). +// }). +// Exec(ctx) +func (_c *ChargeCreditPurchaseInvoicedPaymentCreateBulk) OnConflict(opts ...sql.ConflictOption) *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + _c.conflict = opts + return &ChargeCreditPurchaseInvoicedPaymentUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeCreditPurchaseInvoicedPayment.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeCreditPurchaseInvoicedPaymentCreateBulk) OnConflictColumns(columns ...string) *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeCreditPurchaseInvoicedPaymentUpsertBulk{ + create: _c, + } +} + +// ChargeCreditPurchaseInvoicedPaymentUpsertBulk is the builder for "upsert"-ing +// a bulk of ChargeCreditPurchaseInvoicedPayment nodes. +type ChargeCreditPurchaseInvoicedPaymentUpsertBulk struct { + create *ChargeCreditPurchaseInvoicedPaymentCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ChargeCreditPurchaseInvoicedPayment.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargecreditpurchaseinvoicedpayment.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) UpdateNewValues() *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + 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(chargecreditpurchaseinvoicedpayment.FieldID) + } + if _, exists := b.mutation.LineID(); exists { + s.SetIgnore(chargecreditpurchaseinvoicedpayment.FieldLineID) + } + if _, exists := b.mutation.InvoiceID(); exists { + s.SetIgnore(chargecreditpurchaseinvoicedpayment.FieldInvoiceID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(chargecreditpurchaseinvoicedpayment.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(chargecreditpurchaseinvoicedpayment.FieldCreatedAt) + } + if _, exists := b.mutation.ChargeID(); exists { + s.SetIgnore(chargecreditpurchaseinvoicedpayment.FieldChargeID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeCreditPurchaseInvoicedPayment.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) Ignore() *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + 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 *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) DoNothing() *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeCreditPurchaseInvoicedPaymentCreateBulk.OnConflict +// documentation for more info. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) Update(set func(*ChargeCreditPurchaseInvoicedPaymentUpsert)) *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeCreditPurchaseInvoicedPaymentUpsert{UpdateSet: update}) + })) + return u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) SetServicePeriodFrom(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) UpdateServicePeriodFrom() *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) SetServicePeriodTo(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) UpdateServicePeriodTo() *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetStatus sets the "status" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) SetStatus(v payment.Status) *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) UpdateStatus() *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateStatus() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) SetAmount(v alpacadecimal.Decimal) *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) UpdateAmount() *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateAmount() + }) +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) SetAuthorizedTransactionGroupID(v string) *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetAuthorizedTransactionGroupID(v) + }) +} + +// UpdateAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) UpdateAuthorizedTransactionGroupID() *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateAuthorizedTransactionGroupID() + }) +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) ClearAuthorizedTransactionGroupID() *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.ClearAuthorizedTransactionGroupID() + }) +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) SetAuthorizedAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetAuthorizedAt(v) + }) +} + +// UpdateAuthorizedAt sets the "authorized_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) UpdateAuthorizedAt() *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateAuthorizedAt() + }) +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) ClearAuthorizedAt() *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.ClearAuthorizedAt() + }) +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) SetSettledTransactionGroupID(v string) *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetSettledTransactionGroupID(v) + }) +} + +// UpdateSettledTransactionGroupID sets the "settled_transaction_group_id" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) UpdateSettledTransactionGroupID() *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateSettledTransactionGroupID() + }) +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) ClearSettledTransactionGroupID() *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.ClearSettledTransactionGroupID() + }) +} + +// SetSettledAt sets the "settled_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) SetSettledAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetSettledAt(v) + }) +} + +// UpdateSettledAt sets the "settled_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) UpdateSettledAt() *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateSettledAt() + }) +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) ClearSettledAt() *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.ClearSettledAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) UpdateUpdatedAt() *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) SetDeletedAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) UpdateDeletedAt() *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) ClearDeletedAt() *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) SetAnnotations(v models.Annotations) *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) UpdateAnnotations() *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) ClearAnnotations() *ChargeCreditPurchaseInvoicedPaymentUpsertBulk { + return u.Update(func(s *ChargeCreditPurchaseInvoicedPaymentUpsert) { + s.ClearAnnotations() + }) +} + +// Exec executes the query. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) 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 ChargeCreditPurchaseInvoicedPaymentCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeCreditPurchaseInvoicedPaymentCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeCreditPurchaseInvoicedPaymentUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargecreditpurchaseinvoicedpayment_delete.go b/ent/db/chargecreditpurchaseinvoicedpayment_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..1ac740eb94db836ad4ee1a3ff1b21f3557210b04 --- /dev/null +++ b/ent/db/chargecreditpurchaseinvoicedpayment_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/chargecreditpurchaseinvoicedpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeCreditPurchaseInvoicedPaymentDelete is the builder for deleting a ChargeCreditPurchaseInvoicedPayment entity. +type ChargeCreditPurchaseInvoicedPaymentDelete struct { + config + hooks []Hook + mutation *ChargeCreditPurchaseInvoicedPaymentMutation +} + +// Where appends a list predicates to the ChargeCreditPurchaseInvoicedPaymentDelete builder. +func (_d *ChargeCreditPurchaseInvoicedPaymentDelete) Where(ps ...predicate.ChargeCreditPurchaseInvoicedPayment) *ChargeCreditPurchaseInvoicedPaymentDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ChargeCreditPurchaseInvoicedPaymentDelete) 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 *ChargeCreditPurchaseInvoicedPaymentDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ChargeCreditPurchaseInvoicedPaymentDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(chargecreditpurchaseinvoicedpayment.Table, sqlgraph.NewFieldSpec(chargecreditpurchaseinvoicedpayment.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 +} + +// ChargeCreditPurchaseInvoicedPaymentDeleteOne is the builder for deleting a single ChargeCreditPurchaseInvoicedPayment entity. +type ChargeCreditPurchaseInvoicedPaymentDeleteOne struct { + _d *ChargeCreditPurchaseInvoicedPaymentDelete +} + +// Where appends a list predicates to the ChargeCreditPurchaseInvoicedPaymentDelete builder. +func (_d *ChargeCreditPurchaseInvoicedPaymentDeleteOne) Where(ps ...predicate.ChargeCreditPurchaseInvoicedPayment) *ChargeCreditPurchaseInvoicedPaymentDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ChargeCreditPurchaseInvoicedPaymentDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{chargecreditpurchaseinvoicedpayment.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeCreditPurchaseInvoicedPaymentDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargecreditpurchaseinvoicedpayment_query.go b/ent/db/chargecreditpurchaseinvoicedpayment_query.go new file mode 100644 index 0000000000000000000000000000000000000000..08aac33efe45e64a267636d83d702eb066f324f4 --- /dev/null +++ b/ent/db/chargecreditpurchaseinvoicedpayment_query.go @@ -0,0 +1,718 @@ +// 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/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchase" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchaseinvoicedpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeCreditPurchaseInvoicedPaymentQuery is the builder for querying ChargeCreditPurchaseInvoicedPayment entities. +type ChargeCreditPurchaseInvoicedPaymentQuery struct { + config + ctx *QueryContext + order []chargecreditpurchaseinvoicedpayment.OrderOption + inters []Interceptor + predicates []predicate.ChargeCreditPurchaseInvoicedPayment + withBillingInvoiceLine *BillingInvoiceLineQuery + withCreditPurchase *ChargeCreditPurchaseQuery + 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 ChargeCreditPurchaseInvoicedPaymentQuery builder. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) Where(ps ...predicate.ChargeCreditPurchaseInvoicedPayment) *ChargeCreditPurchaseInvoicedPaymentQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) Limit(limit int) *ChargeCreditPurchaseInvoicedPaymentQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) Offset(offset int) *ChargeCreditPurchaseInvoicedPaymentQuery { + _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 *ChargeCreditPurchaseInvoicedPaymentQuery) Unique(unique bool) *ChargeCreditPurchaseInvoicedPaymentQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) Order(o ...chargecreditpurchaseinvoicedpayment.OrderOption) *ChargeCreditPurchaseInvoicedPaymentQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryBillingInvoiceLine chains the current query on the "billing_invoice_line" edge. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) QueryBillingInvoiceLine() *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{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(chargecreditpurchaseinvoicedpayment.Table, chargecreditpurchaseinvoicedpayment.FieldID, selector), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargecreditpurchaseinvoicedpayment.BillingInvoiceLineTable, chargecreditpurchaseinvoicedpayment.BillingInvoiceLineColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCreditPurchase chains the current query on the "credit_purchase" edge. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) QueryCreditPurchase() *ChargeCreditPurchaseQuery { + query := (&ChargeCreditPurchaseClient{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(chargecreditpurchaseinvoicedpayment.Table, chargecreditpurchaseinvoicedpayment.FieldID, selector), + sqlgraph.To(chargecreditpurchase.Table, chargecreditpurchase.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargecreditpurchaseinvoicedpayment.CreditPurchaseTable, chargecreditpurchaseinvoicedpayment.CreditPurchaseColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ChargeCreditPurchaseInvoicedPayment entity from the query. +// Returns a *NotFoundError when no ChargeCreditPurchaseInvoicedPayment was found. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) First(ctx context.Context) (*ChargeCreditPurchaseInvoicedPayment, 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{chargecreditpurchaseinvoicedpayment.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) FirstX(ctx context.Context) *ChargeCreditPurchaseInvoicedPayment { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ChargeCreditPurchaseInvoicedPayment ID from the query. +// Returns a *NotFoundError when no ChargeCreditPurchaseInvoicedPayment ID was found. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) 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{chargecreditpurchaseinvoicedpayment.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ChargeCreditPurchaseInvoicedPayment entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ChargeCreditPurchaseInvoicedPayment entity is found. +// Returns a *NotFoundError when no ChargeCreditPurchaseInvoicedPayment entities are found. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) Only(ctx context.Context) (*ChargeCreditPurchaseInvoicedPayment, 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{chargecreditpurchaseinvoicedpayment.Label} + default: + return nil, &NotSingularError{chargecreditpurchaseinvoicedpayment.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) OnlyX(ctx context.Context) *ChargeCreditPurchaseInvoicedPayment { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ChargeCreditPurchaseInvoicedPayment ID in the query. +// Returns a *NotSingularError when more than one ChargeCreditPurchaseInvoicedPayment ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) 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{chargecreditpurchaseinvoicedpayment.Label} + default: + err = &NotSingularError{chargecreditpurchaseinvoicedpayment.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) 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 ChargeCreditPurchaseInvoicedPayments. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) All(ctx context.Context) ([]*ChargeCreditPurchaseInvoicedPayment, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ChargeCreditPurchaseInvoicedPayment, *ChargeCreditPurchaseInvoicedPaymentQuery]() + return withInterceptors[[]*ChargeCreditPurchaseInvoicedPayment](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) AllX(ctx context.Context) []*ChargeCreditPurchaseInvoicedPayment { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ChargeCreditPurchaseInvoicedPayment IDs. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) 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(chargecreditpurchaseinvoicedpayment.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) 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 *ChargeCreditPurchaseInvoicedPaymentQuery) 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[*ChargeCreditPurchaseInvoicedPaymentQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) 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 *ChargeCreditPurchaseInvoicedPaymentQuery) 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 *ChargeCreditPurchaseInvoicedPaymentQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ChargeCreditPurchaseInvoicedPaymentQuery 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 *ChargeCreditPurchaseInvoicedPaymentQuery) Clone() *ChargeCreditPurchaseInvoicedPaymentQuery { + if _q == nil { + return nil + } + return &ChargeCreditPurchaseInvoicedPaymentQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]chargecreditpurchaseinvoicedpayment.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ChargeCreditPurchaseInvoicedPayment{}, _q.predicates...), + withBillingInvoiceLine: _q.withBillingInvoiceLine.Clone(), + withCreditPurchase: _q.withCreditPurchase.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithBillingInvoiceLine tells the query-builder to eager-load the nodes that are connected to +// the "billing_invoice_line" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) WithBillingInvoiceLine(opts ...func(*BillingInvoiceLineQuery)) *ChargeCreditPurchaseInvoicedPaymentQuery { + query := (&BillingInvoiceLineClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingInvoiceLine = query + return _q +} + +// WithCreditPurchase tells the query-builder to eager-load the nodes that are connected to +// the "credit_purchase" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) WithCreditPurchase(opts ...func(*ChargeCreditPurchaseQuery)) *ChargeCreditPurchaseInvoicedPaymentQuery { + query := (&ChargeCreditPurchaseClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCreditPurchase = 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.ChargeCreditPurchaseInvoicedPayment.Query(). +// GroupBy(chargecreditpurchaseinvoicedpayment.FieldLineID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) GroupBy(field string, fields ...string) *ChargeCreditPurchaseInvoicedPaymentGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ChargeCreditPurchaseInvoicedPaymentGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = chargecreditpurchaseinvoicedpayment.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.ChargeCreditPurchaseInvoicedPayment.Query(). +// Select(chargecreditpurchaseinvoicedpayment.FieldLineID). +// Scan(ctx, &v) +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) Select(fields ...string) *ChargeCreditPurchaseInvoicedPaymentSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ChargeCreditPurchaseInvoicedPaymentSelect{ChargeCreditPurchaseInvoicedPaymentQuery: _q} + sbuild.label = chargecreditpurchaseinvoicedpayment.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ChargeCreditPurchaseInvoicedPaymentSelect configured with the given aggregations. +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) Aggregate(fns ...AggregateFunc) *ChargeCreditPurchaseInvoicedPaymentSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) 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 !chargecreditpurchaseinvoicedpayment.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 *ChargeCreditPurchaseInvoicedPaymentQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ChargeCreditPurchaseInvoicedPayment, error) { + var ( + nodes = []*ChargeCreditPurchaseInvoicedPayment{} + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withBillingInvoiceLine != nil, + _q.withCreditPurchase != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ChargeCreditPurchaseInvoicedPayment).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ChargeCreditPurchaseInvoicedPayment{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.withBillingInvoiceLine; query != nil { + if err := _q.loadBillingInvoiceLine(ctx, query, nodes, nil, + func(n *ChargeCreditPurchaseInvoicedPayment, e *BillingInvoiceLine) { n.Edges.BillingInvoiceLine = e }); err != nil { + return nil, err + } + } + if query := _q.withCreditPurchase; query != nil { + if err := _q.loadCreditPurchase(ctx, query, nodes, nil, + func(n *ChargeCreditPurchaseInvoicedPayment, e *ChargeCreditPurchase) { n.Edges.CreditPurchase = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) loadBillingInvoiceLine(ctx context.Context, query *BillingInvoiceLineQuery, nodes []*ChargeCreditPurchaseInvoicedPayment, init func(*ChargeCreditPurchaseInvoicedPayment), assign func(*ChargeCreditPurchaseInvoicedPayment, *BillingInvoiceLine)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeCreditPurchaseInvoicedPayment) + for i := range nodes { + fk := nodes[i].LineID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(billinginvoiceline.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 "line_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeCreditPurchaseInvoicedPaymentQuery) loadCreditPurchase(ctx context.Context, query *ChargeCreditPurchaseQuery, nodes []*ChargeCreditPurchaseInvoicedPayment, init func(*ChargeCreditPurchaseInvoicedPayment), assign func(*ChargeCreditPurchaseInvoicedPayment, *ChargeCreditPurchase)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeCreditPurchaseInvoicedPayment) + 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(chargecreditpurchase.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 *ChargeCreditPurchaseInvoicedPaymentQuery) 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 *ChargeCreditPurchaseInvoicedPaymentQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(chargecreditpurchaseinvoicedpayment.Table, chargecreditpurchaseinvoicedpayment.Columns, sqlgraph.NewFieldSpec(chargecreditpurchaseinvoicedpayment.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, chargecreditpurchaseinvoicedpayment.FieldID) + for i := range fields { + if fields[i] != chargecreditpurchaseinvoicedpayment.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withBillingInvoiceLine != nil { + _spec.Node.AddColumnOnce(chargecreditpurchaseinvoicedpayment.FieldLineID) + } + if _q.withCreditPurchase != nil { + _spec.Node.AddColumnOnce(chargecreditpurchaseinvoicedpayment.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 *ChargeCreditPurchaseInvoicedPaymentQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(chargecreditpurchaseinvoicedpayment.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = chargecreditpurchaseinvoicedpayment.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 *ChargeCreditPurchaseInvoicedPaymentQuery) ForUpdate(opts ...sql.LockOption) *ChargeCreditPurchaseInvoicedPaymentQuery { + 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 *ChargeCreditPurchaseInvoicedPaymentQuery) ForShare(opts ...sql.LockOption) *ChargeCreditPurchaseInvoicedPaymentQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ChargeCreditPurchaseInvoicedPaymentGroupBy is the group-by builder for ChargeCreditPurchaseInvoicedPayment entities. +type ChargeCreditPurchaseInvoicedPaymentGroupBy struct { + selector + build *ChargeCreditPurchaseInvoicedPaymentQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ChargeCreditPurchaseInvoicedPaymentGroupBy) Aggregate(fns ...AggregateFunc) *ChargeCreditPurchaseInvoicedPaymentGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ChargeCreditPurchaseInvoicedPaymentGroupBy) 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[*ChargeCreditPurchaseInvoicedPaymentQuery, *ChargeCreditPurchaseInvoicedPaymentGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ChargeCreditPurchaseInvoicedPaymentGroupBy) sqlScan(ctx context.Context, root *ChargeCreditPurchaseInvoicedPaymentQuery, 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) +} + +// ChargeCreditPurchaseInvoicedPaymentSelect is the builder for selecting fields of ChargeCreditPurchaseInvoicedPayment entities. +type ChargeCreditPurchaseInvoicedPaymentSelect struct { + *ChargeCreditPurchaseInvoicedPaymentQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ChargeCreditPurchaseInvoicedPaymentSelect) Aggregate(fns ...AggregateFunc) *ChargeCreditPurchaseInvoicedPaymentSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ChargeCreditPurchaseInvoicedPaymentSelect) 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[*ChargeCreditPurchaseInvoicedPaymentQuery, *ChargeCreditPurchaseInvoicedPaymentSelect](ctx, _s.ChargeCreditPurchaseInvoicedPaymentQuery, _s, _s.inters, v) +} + +func (_s *ChargeCreditPurchaseInvoicedPaymentSelect) sqlScan(ctx context.Context, root *ChargeCreditPurchaseInvoicedPaymentQuery, 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/ent/db/chargecreditpurchaseinvoicedpayment_update.go b/ent/db/chargecreditpurchaseinvoicedpayment_update.go new file mode 100644 index 0000000000000000000000000000000000000000..09cc539767c8a9d42b6a1fa1645a95797ee88713 --- /dev/null +++ b/ent/db/chargecreditpurchaseinvoicedpayment_update.go @@ -0,0 +1,705 @@ +// 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/chargecreditpurchaseinvoicedpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeCreditPurchaseInvoicedPaymentUpdate is the builder for updating ChargeCreditPurchaseInvoicedPayment entities. +type ChargeCreditPurchaseInvoicedPaymentUpdate struct { + config + hooks []Hook + mutation *ChargeCreditPurchaseInvoicedPaymentMutation +} + +// Where appends a list predicates to the ChargeCreditPurchaseInvoicedPaymentUpdate builder. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) Where(ps ...predicate.ChargeCreditPurchaseInvoicedPayment) *ChargeCreditPurchaseInvoicedPaymentUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) SetServicePeriodFrom(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdate { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) SetNillableServicePeriodFrom(v *time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdate { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) SetServicePeriodTo(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdate { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) SetNillableServicePeriodTo(v *time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdate { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetStatus sets the "status" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) SetStatus(v payment.Status) *ChargeCreditPurchaseInvoicedPaymentUpdate { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) SetNillableStatus(v *payment.Status) *ChargeCreditPurchaseInvoicedPaymentUpdate { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) SetAmount(v alpacadecimal.Decimal) *ChargeCreditPurchaseInvoicedPaymentUpdate { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeCreditPurchaseInvoicedPaymentUpdate { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) SetAuthorizedTransactionGroupID(v string) *ChargeCreditPurchaseInvoicedPaymentUpdate { + _u.mutation.SetAuthorizedTransactionGroupID(v) + return _u +} + +// SetNillableAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field if the given value is not nil. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) SetNillableAuthorizedTransactionGroupID(v *string) *ChargeCreditPurchaseInvoicedPaymentUpdate { + if v != nil { + _u.SetAuthorizedTransactionGroupID(*v) + } + return _u +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) ClearAuthorizedTransactionGroupID() *ChargeCreditPurchaseInvoicedPaymentUpdate { + _u.mutation.ClearAuthorizedTransactionGroupID() + return _u +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) SetAuthorizedAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdate { + _u.mutation.SetAuthorizedAt(v) + return _u +} + +// SetNillableAuthorizedAt sets the "authorized_at" field if the given value is not nil. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) SetNillableAuthorizedAt(v *time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdate { + if v != nil { + _u.SetAuthorizedAt(*v) + } + return _u +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) ClearAuthorizedAt() *ChargeCreditPurchaseInvoicedPaymentUpdate { + _u.mutation.ClearAuthorizedAt() + return _u +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) SetSettledTransactionGroupID(v string) *ChargeCreditPurchaseInvoicedPaymentUpdate { + _u.mutation.SetSettledTransactionGroupID(v) + return _u +} + +// SetNillableSettledTransactionGroupID sets the "settled_transaction_group_id" field if the given value is not nil. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) SetNillableSettledTransactionGroupID(v *string) *ChargeCreditPurchaseInvoicedPaymentUpdate { + if v != nil { + _u.SetSettledTransactionGroupID(*v) + } + return _u +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) ClearSettledTransactionGroupID() *ChargeCreditPurchaseInvoicedPaymentUpdate { + _u.mutation.ClearSettledTransactionGroupID() + return _u +} + +// SetSettledAt sets the "settled_at" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) SetSettledAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdate { + _u.mutation.SetSettledAt(v) + return _u +} + +// SetNillableSettledAt sets the "settled_at" field if the given value is not nil. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) SetNillableSettledAt(v *time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdate { + if v != nil { + _u.SetSettledAt(*v) + } + return _u +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) ClearSettledAt() *ChargeCreditPurchaseInvoicedPaymentUpdate { + _u.mutation.ClearSettledAt() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) SetDeletedAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) SetNillableDeletedAt(v *time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) ClearDeletedAt() *ChargeCreditPurchaseInvoicedPaymentUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) SetAnnotations(v models.Annotations) *ChargeCreditPurchaseInvoicedPaymentUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) ClearAnnotations() *ChargeCreditPurchaseInvoicedPaymentUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// Mutation returns the ChargeCreditPurchaseInvoicedPaymentMutation object of the builder. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) Mutation() *ChargeCreditPurchaseInvoicedPaymentMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) 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 *ChargeCreditPurchaseInvoicedPaymentUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) 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 *ChargeCreditPurchaseInvoicedPaymentUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargecreditpurchaseinvoicedpayment.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) check() error { + if v, ok := _u.mutation.Status(); ok { + if err := chargecreditpurchaseinvoicedpayment.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseInvoicedPayment.status": %w`, err)} + } + } + if v, ok := _u.mutation.AuthorizedTransactionGroupID(); ok { + if err := chargecreditpurchaseinvoicedpayment.AuthorizedTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "authorized_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseInvoicedPayment.authorized_transaction_group_id": %w`, err)} + } + } + if v, ok := _u.mutation.SettledTransactionGroupID(); ok { + if err := chargecreditpurchaseinvoicedpayment.SettledTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "settled_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseInvoicedPayment.settled_transaction_group_id": %w`, err)} + } + } + if _u.mutation.BillingInvoiceLineCleared() && len(_u.mutation.BillingInvoiceLineIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeCreditPurchaseInvoicedPayment.billing_invoice_line"`) + } + if _u.mutation.CreditPurchaseCleared() && len(_u.mutation.CreditPurchaseIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeCreditPurchaseInvoicedPayment.credit_purchase"`) + } + return nil +} + +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargecreditpurchaseinvoicedpayment.Table, chargecreditpurchaseinvoicedpayment.Columns, sqlgraph.NewFieldSpec(chargecreditpurchaseinvoicedpayment.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(chargecreditpurchaseinvoicedpayment.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldStatus, field.TypeEnum, value) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.AuthorizedTransactionGroupID(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldAuthorizedTransactionGroupID, field.TypeString, value) + } + if _u.mutation.AuthorizedTransactionGroupIDCleared() { + _spec.ClearField(chargecreditpurchaseinvoicedpayment.FieldAuthorizedTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.AuthorizedAt(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldAuthorizedAt, field.TypeTime, value) + } + if _u.mutation.AuthorizedAtCleared() { + _spec.ClearField(chargecreditpurchaseinvoicedpayment.FieldAuthorizedAt, field.TypeTime) + } + if value, ok := _u.mutation.SettledTransactionGroupID(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldSettledTransactionGroupID, field.TypeString, value) + } + if _u.mutation.SettledTransactionGroupIDCleared() { + _spec.ClearField(chargecreditpurchaseinvoicedpayment.FieldSettledTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.SettledAt(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldSettledAt, field.TypeTime, value) + } + if _u.mutation.SettledAtCleared() { + _spec.ClearField(chargecreditpurchaseinvoicedpayment.FieldSettledAt, field.TypeTime) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargecreditpurchaseinvoicedpayment.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargecreditpurchaseinvoicedpayment.FieldAnnotations, field.TypeJSON) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{chargecreditpurchaseinvoicedpayment.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ChargeCreditPurchaseInvoicedPaymentUpdateOne is the builder for updating a single ChargeCreditPurchaseInvoicedPayment entity. +type ChargeCreditPurchaseInvoicedPaymentUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ChargeCreditPurchaseInvoicedPaymentMutation +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SetServicePeriodFrom(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SetNillableServicePeriodFrom(v *time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SetServicePeriodTo(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SetNillableServicePeriodTo(v *time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetStatus sets the "status" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SetStatus(v payment.Status) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SetNillableStatus(v *payment.Status) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SetAmount(v alpacadecimal.Decimal) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SetAuthorizedTransactionGroupID(v string) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + _u.mutation.SetAuthorizedTransactionGroupID(v) + return _u +} + +// SetNillableAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field if the given value is not nil. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SetNillableAuthorizedTransactionGroupID(v *string) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + if v != nil { + _u.SetAuthorizedTransactionGroupID(*v) + } + return _u +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) ClearAuthorizedTransactionGroupID() *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + _u.mutation.ClearAuthorizedTransactionGroupID() + return _u +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SetAuthorizedAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + _u.mutation.SetAuthorizedAt(v) + return _u +} + +// SetNillableAuthorizedAt sets the "authorized_at" field if the given value is not nil. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SetNillableAuthorizedAt(v *time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + if v != nil { + _u.SetAuthorizedAt(*v) + } + return _u +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) ClearAuthorizedAt() *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + _u.mutation.ClearAuthorizedAt() + return _u +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SetSettledTransactionGroupID(v string) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + _u.mutation.SetSettledTransactionGroupID(v) + return _u +} + +// SetNillableSettledTransactionGroupID sets the "settled_transaction_group_id" field if the given value is not nil. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SetNillableSettledTransactionGroupID(v *string) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + if v != nil { + _u.SetSettledTransactionGroupID(*v) + } + return _u +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) ClearSettledTransactionGroupID() *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + _u.mutation.ClearSettledTransactionGroupID() + return _u +} + +// SetSettledAt sets the "settled_at" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SetSettledAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + _u.mutation.SetSettledAt(v) + return _u +} + +// SetNillableSettledAt sets the "settled_at" field if the given value is not nil. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SetNillableSettledAt(v *time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + if v != nil { + _u.SetSettledAt(*v) + } + return _u +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) ClearSettledAt() *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + _u.mutation.ClearSettledAt() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SetUpdatedAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SetDeletedAt(v time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SetNillableDeletedAt(v *time.Time) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) ClearDeletedAt() *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SetAnnotations(v models.Annotations) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) ClearAnnotations() *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// Mutation returns the ChargeCreditPurchaseInvoicedPaymentMutation object of the builder. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) Mutation() *ChargeCreditPurchaseInvoicedPaymentMutation { + return _u.mutation +} + +// Where appends a list predicates to the ChargeCreditPurchaseInvoicedPaymentUpdate builder. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) Where(ps ...predicate.ChargeCreditPurchaseInvoicedPayment) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + _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 *ChargeCreditPurchaseInvoicedPaymentUpdateOne) Select(field string, fields ...string) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ChargeCreditPurchaseInvoicedPayment entity. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) Save(ctx context.Context) (*ChargeCreditPurchaseInvoicedPayment, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) SaveX(ctx context.Context) *ChargeCreditPurchaseInvoicedPayment { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) 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 *ChargeCreditPurchaseInvoicedPaymentUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargecreditpurchaseinvoicedpayment.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) check() error { + if v, ok := _u.mutation.Status(); ok { + if err := chargecreditpurchaseinvoicedpayment.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseInvoicedPayment.status": %w`, err)} + } + } + if v, ok := _u.mutation.AuthorizedTransactionGroupID(); ok { + if err := chargecreditpurchaseinvoicedpayment.AuthorizedTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "authorized_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseInvoicedPayment.authorized_transaction_group_id": %w`, err)} + } + } + if v, ok := _u.mutation.SettledTransactionGroupID(); ok { + if err := chargecreditpurchaseinvoicedpayment.SettledTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "settled_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeCreditPurchaseInvoicedPayment.settled_transaction_group_id": %w`, err)} + } + } + if _u.mutation.BillingInvoiceLineCleared() && len(_u.mutation.BillingInvoiceLineIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeCreditPurchaseInvoicedPayment.billing_invoice_line"`) + } + if _u.mutation.CreditPurchaseCleared() && len(_u.mutation.CreditPurchaseIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeCreditPurchaseInvoicedPayment.credit_purchase"`) + } + return nil +} + +func (_u *ChargeCreditPurchaseInvoicedPaymentUpdateOne) sqlSave(ctx context.Context) (_node *ChargeCreditPurchaseInvoicedPayment, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargecreditpurchaseinvoicedpayment.Table, chargecreditpurchaseinvoicedpayment.Columns, sqlgraph.NewFieldSpec(chargecreditpurchaseinvoicedpayment.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "ChargeCreditPurchaseInvoicedPayment.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, chargecreditpurchaseinvoicedpayment.FieldID) + for _, f := range fields { + if !chargecreditpurchaseinvoicedpayment.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != chargecreditpurchaseinvoicedpayment.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(chargecreditpurchaseinvoicedpayment.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldStatus, field.TypeEnum, value) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.AuthorizedTransactionGroupID(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldAuthorizedTransactionGroupID, field.TypeString, value) + } + if _u.mutation.AuthorizedTransactionGroupIDCleared() { + _spec.ClearField(chargecreditpurchaseinvoicedpayment.FieldAuthorizedTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.AuthorizedAt(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldAuthorizedAt, field.TypeTime, value) + } + if _u.mutation.AuthorizedAtCleared() { + _spec.ClearField(chargecreditpurchaseinvoicedpayment.FieldAuthorizedAt, field.TypeTime) + } + if value, ok := _u.mutation.SettledTransactionGroupID(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldSettledTransactionGroupID, field.TypeString, value) + } + if _u.mutation.SettledTransactionGroupIDCleared() { + _spec.ClearField(chargecreditpurchaseinvoicedpayment.FieldSettledTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.SettledAt(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldSettledAt, field.TypeTime, value) + } + if _u.mutation.SettledAtCleared() { + _spec.ClearField(chargecreditpurchaseinvoicedpayment.FieldSettledAt, field.TypeTime) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargecreditpurchaseinvoicedpayment.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargecreditpurchaseinvoicedpayment.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargecreditpurchaseinvoicedpayment.FieldAnnotations, field.TypeJSON) + } + _node = &ChargeCreditPurchaseInvoicedPayment{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{chargecreditpurchaseinvoicedpayment.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/ent/db/chargeflatfee.go b/ent/db/chargeflatfee.go new file mode 100644 index 0000000000000000000000000000000000000000..20eac10c912f0096aae56c3dca1d5469c73e6c83 --- /dev/null +++ b/ent/db/chargeflatfee.go @@ -0,0 +1,753 @@ +// 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" + "github.com/openmeterio/openmeter/openmeter/billing/charges/flatfee" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/ent/db/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeoverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/customer" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionphase" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeFlatFee is the model entity for the ChargeFlatFee schema. +type ChargeFlatFee struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // CustomerID holds the value of the "customer_id" field. + CustomerID string `json:"customer_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"` + // BillingPeriodFrom holds the value of the "billing_period_from" field. + BillingPeriodFrom time.Time `json:"billing_period_from,omitempty"` + // BillingPeriodTo holds the value of the "billing_period_to" field. + BillingPeriodTo time.Time `json:"billing_period_to,omitempty"` + // FullServicePeriodFrom holds the value of the "full_service_period_from" field. + FullServicePeriodFrom time.Time `json:"full_service_period_from,omitempty"` + // FullServicePeriodTo holds the value of the "full_service_period_to" field. + FullServicePeriodTo time.Time `json:"full_service_period_to,omitempty"` + // Status holds the value of the "status" field. + Status meta.ChargeStatus `json:"status,omitempty"` + // UniqueReferenceID holds the value of the "unique_reference_id" field. + UniqueReferenceID *string `json:"unique_reference_id,omitempty"` + // Currency holds the value of the "currency" field. + Currency currencyx.Code `json:"currency,omitempty"` + // ManagedBy holds the value of the "managed_by" field. + ManagedBy billing.InvoiceLineManagedBy `json:"managed_by,omitempty"` + // SubscriptionID holds the value of the "subscription_id" field. + SubscriptionID *string `json:"subscription_id,omitempty"` + // SubscriptionPhaseID holds the value of the "subscription_phase_id" field. + SubscriptionPhaseID *string `json:"subscription_phase_id,omitempty"` + // SubscriptionItemID holds the value of the "subscription_item_id" field. + SubscriptionItemID *string `json:"subscription_item_id,omitempty"` + // AdvanceAfter holds the value of the "advance_after" field. + AdvanceAfter *time.Time `json:"advance_after,omitempty"` + // TaxCodeID holds the value of the "tax_code_id" field. + TaxCodeID string `json:"tax_code_id,omitempty"` + // TaxBehavior holds the value of the "tax_behavior" field. + TaxBehavior *productcatalog.TaxBehavior `json:"tax_behavior,omitempty"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,omitempty"` + // Namespace holds the value of the "namespace" field. + Namespace string `json:"namespace,omitempty"` + // Metadata holds the value of the "metadata" field. + Metadata map[string]string `json:"metadata,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"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Description holds the value of the "description" field. + Description *string `json:"description,omitempty"` + // PaymentTerm holds the value of the "payment_term" field. + PaymentTerm productcatalog.PaymentTermType `json:"payment_term,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"` + // IntentDeletedAt holds the value of the "intent_deleted_at" field. + IntentDeletedAt *time.Time `json:"intent_deleted_at,omitempty"` + // Discounts holds the value of the "discounts" field. + Discounts *billing.Discounts `json:"discounts,omitempty"` + // ProRating holds the value of the "pro_rating" field. + ProRating flatfee.ProRatingModeAdapterEnum `json:"pro_rating,omitempty"` + // FeatureKey holds the value of the "feature_key" field. + FeatureKey *string `json:"feature_key,omitempty"` + // FeatureID holds the value of the "feature_id" field. + FeatureID *string `json:"feature_id,omitempty"` + // AmountBeforeProration holds the value of the "amount_before_proration" field. + AmountBeforeProration alpacadecimal.Decimal `json:"amount_before_proration,omitempty"` + // AmountAfterProration holds the value of the "amount_after_proration" field. + AmountAfterProration alpacadecimal.Decimal `json:"amount_after_proration,omitempty"` + // CurrentRealizationRunID holds the value of the "current_realization_run_id" field. + CurrentRealizationRunID *string `json:"current_realization_run_id,omitempty"` + // StatusDetailed holds the value of the "status_detailed" field. + StatusDetailed flatfee.Status `json:"status_detailed,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ChargeFlatFeeQuery when eager-loading is set. + Edges ChargeFlatFeeEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ChargeFlatFeeEdges holds the relations/edges for other nodes in the graph. +type ChargeFlatFeeEdges struct { + // Runs holds the value of the runs edge. + Runs []*ChargeFlatFeeRun `json:"runs,omitempty"` + // CurrentRun holds the value of the current_run edge. + CurrentRun *ChargeFlatFeeRun `json:"current_run,omitempty"` + // Charge holds the value of the charge edge. + Charge *Charge `json:"charge,omitempty"` + // IntentOverride holds the value of the intent_override edge. + IntentOverride *ChargeFlatFeeOverride `json:"intent_override,omitempty"` + // Subscription holds the value of the subscription edge. + Subscription *Subscription `json:"subscription,omitempty"` + // SubscriptionPhase holds the value of the subscription_phase edge. + SubscriptionPhase *SubscriptionPhase `json:"subscription_phase,omitempty"` + // SubscriptionItem holds the value of the subscription_item edge. + SubscriptionItem *SubscriptionItem `json:"subscription_item,omitempty"` + // Customer holds the value of the customer edge. + Customer *Customer `json:"customer,omitempty"` + // Feature holds the value of the feature edge. + Feature *Feature `json:"feature,omitempty"` + // TaxCode holds the value of the tax_code edge. + TaxCode *TaxCode `json:"tax_code,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [10]bool +} + +// RunsOrErr returns the Runs value or an error if the edge +// was not loaded in eager-loading. +func (e ChargeFlatFeeEdges) RunsOrErr() ([]*ChargeFlatFeeRun, error) { + if e.loadedTypes[0] { + return e.Runs, nil + } + return nil, &NotLoadedError{edge: "runs"} +} + +// CurrentRunOrErr returns the CurrentRun value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeFlatFeeEdges) CurrentRunOrErr() (*ChargeFlatFeeRun, error) { + if e.CurrentRun != nil { + return e.CurrentRun, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: chargeflatfeerun.Label} + } + return nil, &NotLoadedError{edge: "current_run"} +} + +// 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 ChargeFlatFeeEdges) ChargeOrErr() (*Charge, error) { + if e.Charge != nil { + return e.Charge, nil + } else if e.loadedTypes[2] { + return nil, &NotFoundError{label: charge.Label} + } + return nil, &NotLoadedError{edge: "charge"} +} + +// IntentOverrideOrErr returns the IntentOverride value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeFlatFeeEdges) IntentOverrideOrErr() (*ChargeFlatFeeOverride, error) { + if e.IntentOverride != nil { + return e.IntentOverride, nil + } else if e.loadedTypes[3] { + return nil, &NotFoundError{label: chargeflatfeeoverride.Label} + } + return nil, &NotLoadedError{edge: "intent_override"} +} + +// SubscriptionOrErr returns the Subscription value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeFlatFeeEdges) SubscriptionOrErr() (*Subscription, error) { + if e.Subscription != nil { + return e.Subscription, nil + } else if e.loadedTypes[4] { + return nil, &NotFoundError{label: subscription.Label} + } + return nil, &NotLoadedError{edge: "subscription"} +} + +// SubscriptionPhaseOrErr returns the SubscriptionPhase value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeFlatFeeEdges) SubscriptionPhaseOrErr() (*SubscriptionPhase, error) { + if e.SubscriptionPhase != nil { + return e.SubscriptionPhase, nil + } else if e.loadedTypes[5] { + return nil, &NotFoundError{label: subscriptionphase.Label} + } + return nil, &NotLoadedError{edge: "subscription_phase"} +} + +// SubscriptionItemOrErr returns the SubscriptionItem value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeFlatFeeEdges) SubscriptionItemOrErr() (*SubscriptionItem, error) { + if e.SubscriptionItem != nil { + return e.SubscriptionItem, nil + } else if e.loadedTypes[6] { + return nil, &NotFoundError{label: subscriptionitem.Label} + } + return nil, &NotLoadedError{edge: "subscription_item"} +} + +// CustomerOrErr returns the Customer value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeFlatFeeEdges) CustomerOrErr() (*Customer, error) { + if e.Customer != nil { + return e.Customer, nil + } else if e.loadedTypes[7] { + return nil, &NotFoundError{label: customer.Label} + } + return nil, &NotLoadedError{edge: "customer"} +} + +// FeatureOrErr returns the Feature value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeFlatFeeEdges) FeatureOrErr() (*Feature, error) { + if e.Feature != nil { + return e.Feature, nil + } else if e.loadedTypes[8] { + return nil, &NotFoundError{label: dbfeature.Label} + } + return nil, &NotLoadedError{edge: "feature"} +} + +// TaxCodeOrErr returns the TaxCode value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeFlatFeeEdges) TaxCodeOrErr() (*TaxCode, error) { + if e.TaxCode != nil { + return e.TaxCode, nil + } else if e.loadedTypes[9] { + return nil, &NotFoundError{label: dbtaxcode.Label} + } + return nil, &NotLoadedError{edge: "tax_code"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ChargeFlatFee) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case chargeflatfee.FieldAnnotations, chargeflatfee.FieldMetadata: + values[i] = new([]byte) + case chargeflatfee.FieldAmountBeforeProration, chargeflatfee.FieldAmountAfterProration: + values[i] = new(alpacadecimal.Decimal) + case chargeflatfee.FieldID, chargeflatfee.FieldCustomerID, chargeflatfee.FieldStatus, chargeflatfee.FieldUniqueReferenceID, chargeflatfee.FieldCurrency, chargeflatfee.FieldManagedBy, chargeflatfee.FieldSubscriptionID, chargeflatfee.FieldSubscriptionPhaseID, chargeflatfee.FieldSubscriptionItemID, chargeflatfee.FieldTaxCodeID, chargeflatfee.FieldTaxBehavior, chargeflatfee.FieldNamespace, chargeflatfee.FieldName, chargeflatfee.FieldDescription, chargeflatfee.FieldPaymentTerm, chargeflatfee.FieldSettlementMode, chargeflatfee.FieldProRating, chargeflatfee.FieldFeatureKey, chargeflatfee.FieldFeatureID, chargeflatfee.FieldCurrentRealizationRunID, chargeflatfee.FieldStatusDetailed: + values[i] = new(sql.NullString) + case chargeflatfee.FieldServicePeriodFrom, chargeflatfee.FieldServicePeriodTo, chargeflatfee.FieldBillingPeriodFrom, chargeflatfee.FieldBillingPeriodTo, chargeflatfee.FieldFullServicePeriodFrom, chargeflatfee.FieldFullServicePeriodTo, chargeflatfee.FieldAdvanceAfter, chargeflatfee.FieldCreatedAt, chargeflatfee.FieldUpdatedAt, chargeflatfee.FieldDeletedAt, chargeflatfee.FieldInvoiceAt, chargeflatfee.FieldIntentDeletedAt: + values[i] = new(sql.NullTime) + case chargeflatfee.FieldDiscounts: + values[i] = chargeflatfee.ValueScanner.Discounts.ScanValue() + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the ChargeFlatFee fields. +func (_m *ChargeFlatFee) 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 chargeflatfee.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 chargeflatfee.FieldCustomerID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field customer_id", values[i]) + } else if value.Valid { + _m.CustomerID = value.String + } + case chargeflatfee.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 chargeflatfee.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 chargeflatfee.FieldBillingPeriodFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field billing_period_from", values[i]) + } else if value.Valid { + _m.BillingPeriodFrom = value.Time + } + case chargeflatfee.FieldBillingPeriodTo: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field billing_period_to", values[i]) + } else if value.Valid { + _m.BillingPeriodTo = value.Time + } + case chargeflatfee.FieldFullServicePeriodFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field full_service_period_from", values[i]) + } else if value.Valid { + _m.FullServicePeriodFrom = value.Time + } + case chargeflatfee.FieldFullServicePeriodTo: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field full_service_period_to", values[i]) + } else if value.Valid { + _m.FullServicePeriodTo = value.Time + } + case chargeflatfee.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 = meta.ChargeStatus(value.String) + } + case chargeflatfee.FieldUniqueReferenceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field unique_reference_id", values[i]) + } else if value.Valid { + _m.UniqueReferenceID = new(string) + *_m.UniqueReferenceID = value.String + } + case chargeflatfee.FieldCurrency: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field currency", values[i]) + } else if value.Valid { + _m.Currency = currencyx.Code(value.String) + } + case chargeflatfee.FieldManagedBy: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field managed_by", values[i]) + } else if value.Valid { + _m.ManagedBy = billing.InvoiceLineManagedBy(value.String) + } + case chargeflatfee.FieldSubscriptionID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field subscription_id", values[i]) + } else if value.Valid { + _m.SubscriptionID = new(string) + *_m.SubscriptionID = value.String + } + case chargeflatfee.FieldSubscriptionPhaseID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field subscription_phase_id", values[i]) + } else if value.Valid { + _m.SubscriptionPhaseID = new(string) + *_m.SubscriptionPhaseID = value.String + } + case chargeflatfee.FieldSubscriptionItemID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field subscription_item_id", values[i]) + } else if value.Valid { + _m.SubscriptionItemID = new(string) + *_m.SubscriptionItemID = value.String + } + case chargeflatfee.FieldAdvanceAfter: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field advance_after", values[i]) + } else if value.Valid { + _m.AdvanceAfter = new(time.Time) + *_m.AdvanceAfter = value.Time + } + case chargeflatfee.FieldTaxCodeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field tax_code_id", values[i]) + } else if value.Valid { + _m.TaxCodeID = value.String + } + case chargeflatfee.FieldTaxBehavior: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field tax_behavior", values[i]) + } else if value.Valid { + _m.TaxBehavior = new(productcatalog.TaxBehavior) + *_m.TaxBehavior = productcatalog.TaxBehavior(value.String) + } + case chargeflatfee.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 chargeflatfee.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 chargeflatfee.FieldMetadata: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field metadata", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Metadata); err != nil { + return fmt.Errorf("unmarshal field metadata: %w", err) + } + } + case chargeflatfee.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 chargeflatfee.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 chargeflatfee.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 chargeflatfee.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case chargeflatfee.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + _m.Description = new(string) + *_m.Description = value.String + } + case chargeflatfee.FieldPaymentTerm: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field payment_term", values[i]) + } else if value.Valid { + _m.PaymentTerm = productcatalog.PaymentTermType(value.String) + } + case chargeflatfee.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 chargeflatfee.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 chargeflatfee.FieldIntentDeletedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field intent_deleted_at", values[i]) + } else if value.Valid { + _m.IntentDeletedAt = new(time.Time) + *_m.IntentDeletedAt = value.Time + } + case chargeflatfee.FieldDiscounts: + if value, err := chargeflatfee.ValueScanner.Discounts.FromValue(values[i]); err != nil { + return err + } else { + _m.Discounts = value + } + case chargeflatfee.FieldProRating: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field pro_rating", values[i]) + } else if value.Valid { + _m.ProRating = flatfee.ProRatingModeAdapterEnum(value.String) + } + case chargeflatfee.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 = new(string) + *_m.FeatureKey = value.String + } + case chargeflatfee.FieldFeatureID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field feature_id", values[i]) + } else if value.Valid { + _m.FeatureID = new(string) + *_m.FeatureID = value.String + } + case chargeflatfee.FieldAmountBeforeProration: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field amount_before_proration", values[i]) + } else if value != nil { + _m.AmountBeforeProration = *value + } + case chargeflatfee.FieldAmountAfterProration: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field amount_after_proration", values[i]) + } else if value != nil { + _m.AmountAfterProration = *value + } + case chargeflatfee.FieldCurrentRealizationRunID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field current_realization_run_id", values[i]) + } else if value.Valid { + _m.CurrentRealizationRunID = new(string) + *_m.CurrentRealizationRunID = value.String + } + case chargeflatfee.FieldStatusDetailed: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field status_detailed", values[i]) + } else if value.Valid { + _m.StatusDetailed = flatfee.Status(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 ChargeFlatFee. +// This includes values selected through modifiers, order, etc. +func (_m *ChargeFlatFee) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryRuns queries the "runs" edge of the ChargeFlatFee entity. +func (_m *ChargeFlatFee) QueryRuns() *ChargeFlatFeeRunQuery { + return NewChargeFlatFeeClient(_m.config).QueryRuns(_m) +} + +// QueryCurrentRun queries the "current_run" edge of the ChargeFlatFee entity. +func (_m *ChargeFlatFee) QueryCurrentRun() *ChargeFlatFeeRunQuery { + return NewChargeFlatFeeClient(_m.config).QueryCurrentRun(_m) +} + +// QueryCharge queries the "charge" edge of the ChargeFlatFee entity. +func (_m *ChargeFlatFee) QueryCharge() *ChargeQuery { + return NewChargeFlatFeeClient(_m.config).QueryCharge(_m) +} + +// QueryIntentOverride queries the "intent_override" edge of the ChargeFlatFee entity. +func (_m *ChargeFlatFee) QueryIntentOverride() *ChargeFlatFeeOverrideQuery { + return NewChargeFlatFeeClient(_m.config).QueryIntentOverride(_m) +} + +// QuerySubscription queries the "subscription" edge of the ChargeFlatFee entity. +func (_m *ChargeFlatFee) QuerySubscription() *SubscriptionQuery { + return NewChargeFlatFeeClient(_m.config).QuerySubscription(_m) +} + +// QuerySubscriptionPhase queries the "subscription_phase" edge of the ChargeFlatFee entity. +func (_m *ChargeFlatFee) QuerySubscriptionPhase() *SubscriptionPhaseQuery { + return NewChargeFlatFeeClient(_m.config).QuerySubscriptionPhase(_m) +} + +// QuerySubscriptionItem queries the "subscription_item" edge of the ChargeFlatFee entity. +func (_m *ChargeFlatFee) QuerySubscriptionItem() *SubscriptionItemQuery { + return NewChargeFlatFeeClient(_m.config).QuerySubscriptionItem(_m) +} + +// QueryCustomer queries the "customer" edge of the ChargeFlatFee entity. +func (_m *ChargeFlatFee) QueryCustomer() *CustomerQuery { + return NewChargeFlatFeeClient(_m.config).QueryCustomer(_m) +} + +// QueryFeature queries the "feature" edge of the ChargeFlatFee entity. +func (_m *ChargeFlatFee) QueryFeature() *FeatureQuery { + return NewChargeFlatFeeClient(_m.config).QueryFeature(_m) +} + +// QueryTaxCode queries the "tax_code" edge of the ChargeFlatFee entity. +func (_m *ChargeFlatFee) QueryTaxCode() *TaxCodeQuery { + return NewChargeFlatFeeClient(_m.config).QueryTaxCode(_m) +} + +// Update returns a builder for updating this ChargeFlatFee. +// Note that you need to call ChargeFlatFee.Unwrap() before calling this method if this ChargeFlatFee +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ChargeFlatFee) Update() *ChargeFlatFeeUpdateOne { + return NewChargeFlatFeeClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ChargeFlatFee 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 *ChargeFlatFee) Unwrap() *ChargeFlatFee { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: ChargeFlatFee is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ChargeFlatFee) String() string { + var builder strings.Builder + builder.WriteString("ChargeFlatFee(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("customer_id=") + builder.WriteString(_m.CustomerID) + 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("billing_period_from=") + builder.WriteString(_m.BillingPeriodFrom.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("billing_period_to=") + builder.WriteString(_m.BillingPeriodTo.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("full_service_period_from=") + builder.WriteString(_m.FullServicePeriodFrom.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("full_service_period_to=") + builder.WriteString(_m.FullServicePeriodTo.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("status=") + builder.WriteString(fmt.Sprintf("%v", _m.Status)) + builder.WriteString(", ") + if v := _m.UniqueReferenceID; v != nil { + builder.WriteString("unique_reference_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("currency=") + builder.WriteString(fmt.Sprintf("%v", _m.Currency)) + builder.WriteString(", ") + builder.WriteString("managed_by=") + builder.WriteString(fmt.Sprintf("%v", _m.ManagedBy)) + builder.WriteString(", ") + if v := _m.SubscriptionID; v != nil { + builder.WriteString("subscription_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SubscriptionPhaseID; v != nil { + builder.WriteString("subscription_phase_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SubscriptionItemID; v != nil { + builder.WriteString("subscription_item_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.AdvanceAfter; v != nil { + builder.WriteString("advance_after=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + builder.WriteString("tax_code_id=") + builder.WriteString(_m.TaxCodeID) + builder.WriteString(", ") + if v := _m.TaxBehavior; v != nil { + builder.WriteString("tax_behavior=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + builder.WriteString(", ") + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("metadata=") + builder.WriteString(fmt.Sprintf("%v", _m.Metadata)) + 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("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + if v := _m.Description; v != nil { + builder.WriteString("description=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("payment_term=") + builder.WriteString(fmt.Sprintf("%v", _m.PaymentTerm)) + 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.IntentDeletedAt; v != nil { + builder.WriteString("intent_deleted_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + if v := _m.Discounts; v != nil { + builder.WriteString("discounts=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + builder.WriteString("pro_rating=") + builder.WriteString(fmt.Sprintf("%v", _m.ProRating)) + builder.WriteString(", ") + if v := _m.FeatureKey; v != nil { + builder.WriteString("feature_key=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.FeatureID; v != nil { + builder.WriteString("feature_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("amount_before_proration=") + builder.WriteString(fmt.Sprintf("%v", _m.AmountBeforeProration)) + builder.WriteString(", ") + builder.WriteString("amount_after_proration=") + builder.WriteString(fmt.Sprintf("%v", _m.AmountAfterProration)) + builder.WriteString(", ") + if v := _m.CurrentRealizationRunID; v != nil { + builder.WriteString("current_realization_run_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("status_detailed=") + builder.WriteString(fmt.Sprintf("%v", _m.StatusDetailed)) + builder.WriteByte(')') + return builder.String() +} + +// ChargeFlatFees is a parsable slice of ChargeFlatFee. +type ChargeFlatFees []*ChargeFlatFee diff --git a/ent/db/chargeflatfee/chargeflatfee.go b/ent/db/chargeflatfee/chargeflatfee.go new file mode 100644 index 0000000000000000000000000000000000000000..18a4c66f3fe66b21e24caf2f9dc939d6f719d02d --- /dev/null +++ b/ent/db/chargeflatfee/chargeflatfee.go @@ -0,0 +1,658 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeflatfee + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/billing/charges/flatfee" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/productcatalog" +) + +const ( + // Label holds the string label denoting the chargeflatfee type in the database. + Label = "charge_flat_fee" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldCustomerID holds the string denoting the customer_id field in the database. + FieldCustomerID = "customer_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" + // FieldBillingPeriodFrom holds the string denoting the billing_period_from field in the database. + FieldBillingPeriodFrom = "billing_period_from" + // FieldBillingPeriodTo holds the string denoting the billing_period_to field in the database. + FieldBillingPeriodTo = "billing_period_to" + // FieldFullServicePeriodFrom holds the string denoting the full_service_period_from field in the database. + FieldFullServicePeriodFrom = "full_service_period_from" + // FieldFullServicePeriodTo holds the string denoting the full_service_period_to field in the database. + FieldFullServicePeriodTo = "full_service_period_to" + // FieldStatus holds the string denoting the status field in the database. + FieldStatus = "status" + // FieldUniqueReferenceID holds the string denoting the unique_reference_id field in the database. + FieldUniqueReferenceID = "unique_reference_id" + // FieldCurrency holds the string denoting the currency field in the database. + FieldCurrency = "currency" + // FieldManagedBy holds the string denoting the managed_by field in the database. + FieldManagedBy = "managed_by" + // FieldSubscriptionID holds the string denoting the subscription_id field in the database. + FieldSubscriptionID = "subscription_id" + // FieldSubscriptionPhaseID holds the string denoting the subscription_phase_id field in the database. + FieldSubscriptionPhaseID = "subscription_phase_id" + // FieldSubscriptionItemID holds the string denoting the subscription_item_id field in the database. + FieldSubscriptionItemID = "subscription_item_id" + // FieldAdvanceAfter holds the string denoting the advance_after field in the database. + FieldAdvanceAfter = "advance_after" + // FieldTaxCodeID holds the string denoting the tax_code_id field in the database. + FieldTaxCodeID = "tax_code_id" + // FieldTaxBehavior holds the string denoting the tax_behavior field in the database. + FieldTaxBehavior = "tax_behavior" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // FieldNamespace holds the string denoting the namespace field in the database. + FieldNamespace = "namespace" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // 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" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // FieldPaymentTerm holds the string denoting the payment_term field in the database. + FieldPaymentTerm = "payment_term" + // 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" + // FieldIntentDeletedAt holds the string denoting the intent_deleted_at field in the database. + FieldIntentDeletedAt = "intent_deleted_at" + // FieldDiscounts holds the string denoting the discounts field in the database. + FieldDiscounts = "discounts" + // FieldProRating holds the string denoting the pro_rating field in the database. + FieldProRating = "pro_rating" + // FieldFeatureKey holds the string denoting the feature_key field in the database. + FieldFeatureKey = "feature_key" + // FieldFeatureID holds the string denoting the feature_id field in the database. + FieldFeatureID = "feature_id" + // FieldAmountBeforeProration holds the string denoting the amount_before_proration field in the database. + FieldAmountBeforeProration = "amount_before_proration" + // FieldAmountAfterProration holds the string denoting the amount_after_proration field in the database. + FieldAmountAfterProration = "amount_after_proration" + // FieldCurrentRealizationRunID holds the string denoting the current_realization_run_id field in the database. + FieldCurrentRealizationRunID = "current_realization_run_id" + // FieldStatusDetailed holds the string denoting the status_detailed field in the database. + FieldStatusDetailed = "status_detailed" + // EdgeRuns holds the string denoting the runs edge name in mutations. + EdgeRuns = "runs" + // EdgeCurrentRun holds the string denoting the current_run edge name in mutations. + EdgeCurrentRun = "current_run" + // EdgeCharge holds the string denoting the charge edge name in mutations. + EdgeCharge = "charge" + // EdgeIntentOverride holds the string denoting the intent_override edge name in mutations. + EdgeIntentOverride = "intent_override" + // EdgeSubscription holds the string denoting the subscription edge name in mutations. + EdgeSubscription = "subscription" + // EdgeSubscriptionPhase holds the string denoting the subscription_phase edge name in mutations. + EdgeSubscriptionPhase = "subscription_phase" + // EdgeSubscriptionItem holds the string denoting the subscription_item edge name in mutations. + EdgeSubscriptionItem = "subscription_item" + // EdgeCustomer holds the string denoting the customer edge name in mutations. + EdgeCustomer = "customer" + // EdgeFeature holds the string denoting the feature edge name in mutations. + EdgeFeature = "feature" + // EdgeTaxCode holds the string denoting the tax_code edge name in mutations. + EdgeTaxCode = "tax_code" + // Table holds the table name of the chargeflatfee in the database. + Table = "charge_flat_fees" + // RunsTable is the table that holds the runs relation/edge. + RunsTable = "charge_flat_fee_runs" + // RunsInverseTable is the table name for the ChargeFlatFeeRun entity. + // It exists in this package in order to avoid circular dependency with the "chargeflatfeerun" package. + RunsInverseTable = "charge_flat_fee_runs" + // RunsColumn is the table column denoting the runs relation/edge. + RunsColumn = "charge_id" + // CurrentRunTable is the table that holds the current_run relation/edge. + CurrentRunTable = "charge_flat_fees" + // CurrentRunInverseTable is the table name for the ChargeFlatFeeRun entity. + // It exists in this package in order to avoid circular dependency with the "chargeflatfeerun" package. + CurrentRunInverseTable = "charge_flat_fee_runs" + // CurrentRunColumn is the table column denoting the current_run relation/edge. + CurrentRunColumn = "current_realization_run_id" + // ChargeTable is the table that holds the charge relation/edge. + ChargeTable = "charges" + // 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 = "charge_flat_fee_id" + // IntentOverrideTable is the table that holds the intent_override relation/edge. + IntentOverrideTable = "charge_flat_fee_overrides" + // IntentOverrideInverseTable is the table name for the ChargeFlatFeeOverride entity. + // It exists in this package in order to avoid circular dependency with the "chargeflatfeeoverride" package. + IntentOverrideInverseTable = "charge_flat_fee_overrides" + // IntentOverrideColumn is the table column denoting the intent_override relation/edge. + IntentOverrideColumn = "charge_id" + // SubscriptionTable is the table that holds the subscription relation/edge. + SubscriptionTable = "charge_flat_fees" + // SubscriptionInverseTable is the table name for the Subscription entity. + // It exists in this package in order to avoid circular dependency with the "subscription" package. + SubscriptionInverseTable = "subscriptions" + // SubscriptionColumn is the table column denoting the subscription relation/edge. + SubscriptionColumn = "subscription_id" + // SubscriptionPhaseTable is the table that holds the subscription_phase relation/edge. + SubscriptionPhaseTable = "charge_flat_fees" + // SubscriptionPhaseInverseTable is the table name for the SubscriptionPhase entity. + // It exists in this package in order to avoid circular dependency with the "subscriptionphase" package. + SubscriptionPhaseInverseTable = "subscription_phases" + // SubscriptionPhaseColumn is the table column denoting the subscription_phase relation/edge. + SubscriptionPhaseColumn = "subscription_phase_id" + // SubscriptionItemTable is the table that holds the subscription_item relation/edge. + SubscriptionItemTable = "charge_flat_fees" + // SubscriptionItemInverseTable is the table name for the SubscriptionItem entity. + // It exists in this package in order to avoid circular dependency with the "subscriptionitem" package. + SubscriptionItemInverseTable = "subscription_items" + // SubscriptionItemColumn is the table column denoting the subscription_item relation/edge. + SubscriptionItemColumn = "subscription_item_id" + // CustomerTable is the table that holds the customer relation/edge. + CustomerTable = "charge_flat_fees" + // CustomerInverseTable is the table name for the Customer entity. + // It exists in this package in order to avoid circular dependency with the "customer" package. + CustomerInverseTable = "customers" + // CustomerColumn is the table column denoting the customer relation/edge. + CustomerColumn = "customer_id" + // FeatureTable is the table that holds the feature relation/edge. + FeatureTable = "charge_flat_fees" + // FeatureInverseTable is the table name for the Feature entity. + // It exists in this package in order to avoid circular dependency with the "dbfeature" package. + FeatureInverseTable = "features" + // FeatureColumn is the table column denoting the feature relation/edge. + FeatureColumn = "feature_id" + // TaxCodeTable is the table that holds the tax_code relation/edge. + TaxCodeTable = "charge_flat_fees" + // TaxCodeInverseTable is the table name for the TaxCode entity. + // It exists in this package in order to avoid circular dependency with the "dbtaxcode" package. + TaxCodeInverseTable = "tax_codes" + // TaxCodeColumn is the table column denoting the tax_code relation/edge. + TaxCodeColumn = "tax_code_id" +) + +// Columns holds all SQL columns for chargeflatfee fields. +var Columns = []string{ + FieldID, + FieldCustomerID, + FieldServicePeriodFrom, + FieldServicePeriodTo, + FieldBillingPeriodFrom, + FieldBillingPeriodTo, + FieldFullServicePeriodFrom, + FieldFullServicePeriodTo, + FieldStatus, + FieldUniqueReferenceID, + FieldCurrency, + FieldManagedBy, + FieldSubscriptionID, + FieldSubscriptionPhaseID, + FieldSubscriptionItemID, + FieldAdvanceAfter, + FieldTaxCodeID, + FieldTaxBehavior, + FieldAnnotations, + FieldNamespace, + FieldMetadata, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldName, + FieldDescription, + FieldPaymentTerm, + FieldInvoiceAt, + FieldSettlementMode, + FieldIntentDeletedAt, + FieldDiscounts, + FieldProRating, + FieldFeatureKey, + FieldFeatureID, + FieldAmountBeforeProration, + FieldAmountAfterProration, + FieldCurrentRealizationRunID, + FieldStatusDetailed, +} + +// 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 ( + // CustomerIDValidator is a validator for the "customer_id" field. It is called by the builders before save. + CustomerIDValidator func(string) error + // CurrencyValidator is a validator for the "currency" field. It is called by the builders before save. + CurrencyValidator func(string) error + // TaxCodeIDValidator is a validator for the "tax_code_id" field. It is called by the builders before save. + TaxCodeIDValidator 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 + // PaymentTermValidator is a validator for the "payment_term" field. It is called by the builders before save. + PaymentTermValidator 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 ChargeFlatFee fields. + ValueScanner struct { + Discounts field.TypeValueScanner[*billing.Discounts] + } +) + +// StatusValidator is a validator for the "status" field enum values. It is called by the builders before save. +func StatusValidator(s meta.ChargeStatus) error { + switch s { + case "created", "active", "final", "deleted": + return nil + default: + return fmt.Errorf("chargeflatfee: invalid enum value for status field: %q", s) + } +} + +// ManagedByValidator is a validator for the "managed_by" field enum values. It is called by the builders before save. +func ManagedByValidator(mb billing.InvoiceLineManagedBy) error { + switch mb { + case "subscription", "system", "manual": + return nil + default: + return fmt.Errorf("chargeflatfee: invalid enum value for managed_by field: %q", mb) + } +} + +// TaxBehaviorValidator is a validator for the "tax_behavior" field enum values. It is called by the builders before save. +func TaxBehaviorValidator(tb productcatalog.TaxBehavior) error { + switch tb { + case "inclusive", "exclusive": + return nil + default: + return fmt.Errorf("chargeflatfee: invalid enum value for tax_behavior field: %q", tb) + } +} + +// 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 "credit_then_invoice", "credit_only": + return nil + default: + return fmt.Errorf("chargeflatfee: invalid enum value for settlement_mode field: %q", sm) + } +} + +// ProRatingValidator is a validator for the "pro_rating" field enum values. It is called by the builders before save. +func ProRatingValidator(pr flatfee.ProRatingModeAdapterEnum) error { + switch pr { + case "prorate_prices", "no_prorate": + return nil + default: + return fmt.Errorf("chargeflatfee: invalid enum value for pro_rating field: %q", pr) + } +} + +// StatusDetailedValidator is a validator for the "status_detailed" field enum values. It is called by the builders before save. +func StatusDetailedValidator(sd flatfee.Status) error { + switch sd { + case "created", "active", "active.realization.started", "active.realization.waiting_for_collection", "active.realization.processing", "active.realization.issuing", "active.realization.completed", "active.awaiting_payment_settlement", "final", "deleted": + return nil + default: + return fmt.Errorf("chargeflatfee: invalid enum value for status_detailed field: %q", sd) + } +} + +// OrderOption defines the ordering options for the ChargeFlatFee 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() +} + +// ByCustomerID orders the results by the customer_id field. +func ByCustomerID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCustomerID, 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() +} + +// ByBillingPeriodFrom orders the results by the billing_period_from field. +func ByBillingPeriodFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBillingPeriodFrom, opts...).ToFunc() +} + +// ByBillingPeriodTo orders the results by the billing_period_to field. +func ByBillingPeriodTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBillingPeriodTo, opts...).ToFunc() +} + +// ByFullServicePeriodFrom orders the results by the full_service_period_from field. +func ByFullServicePeriodFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFullServicePeriodFrom, opts...).ToFunc() +} + +// ByFullServicePeriodTo orders the results by the full_service_period_to field. +func ByFullServicePeriodTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFullServicePeriodTo, opts...).ToFunc() +} + +// ByStatus orders the results by the status field. +func ByStatus(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStatus, opts...).ToFunc() +} + +// ByUniqueReferenceID orders the results by the unique_reference_id field. +func ByUniqueReferenceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUniqueReferenceID, opts...).ToFunc() +} + +// ByCurrency orders the results by the currency field. +func ByCurrency(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCurrency, opts...).ToFunc() +} + +// ByManagedBy orders the results by the managed_by field. +func ByManagedBy(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldManagedBy, opts...).ToFunc() +} + +// BySubscriptionID orders the results by the subscription_id field. +func BySubscriptionID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSubscriptionID, opts...).ToFunc() +} + +// BySubscriptionPhaseID orders the results by the subscription_phase_id field. +func BySubscriptionPhaseID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSubscriptionPhaseID, opts...).ToFunc() +} + +// BySubscriptionItemID orders the results by the subscription_item_id field. +func BySubscriptionItemID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSubscriptionItemID, opts...).ToFunc() +} + +// ByAdvanceAfter orders the results by the advance_after field. +func ByAdvanceAfter(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAdvanceAfter, opts...).ToFunc() +} + +// ByTaxCodeID orders the results by the tax_code_id field. +func ByTaxCodeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxCodeID, opts...).ToFunc() +} + +// ByTaxBehavior orders the results by the tax_behavior field. +func ByTaxBehavior(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxBehavior, 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() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, opts...).ToFunc() +} + +// ByPaymentTerm orders the results by the payment_term field. +func ByPaymentTerm(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPaymentTerm, 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() +} + +// ByIntentDeletedAt orders the results by the intent_deleted_at field. +func ByIntentDeletedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIntentDeletedAt, opts...).ToFunc() +} + +// ByDiscounts orders the results by the discounts field. +func ByDiscounts(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDiscounts, opts...).ToFunc() +} + +// ByProRating orders the results by the pro_rating field. +func ByProRating(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldProRating, opts...).ToFunc() +} + +// ByFeatureKey orders the results by the feature_key field. +func ByFeatureKey(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFeatureKey, opts...).ToFunc() +} + +// ByFeatureID orders the results by the feature_id field. +func ByFeatureID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFeatureID, opts...).ToFunc() +} + +// ByAmountBeforeProration orders the results by the amount_before_proration field. +func ByAmountBeforeProration(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAmountBeforeProration, opts...).ToFunc() +} + +// ByAmountAfterProration orders the results by the amount_after_proration field. +func ByAmountAfterProration(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAmountAfterProration, opts...).ToFunc() +} + +// ByCurrentRealizationRunID orders the results by the current_realization_run_id field. +func ByCurrentRealizationRunID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCurrentRealizationRunID, opts...).ToFunc() +} + +// ByStatusDetailed orders the results by the status_detailed field. +func ByStatusDetailed(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStatusDetailed, opts...).ToFunc() +} + +// 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...)...) + } +} + +// ByCurrentRunField orders the results by current_run field. +func ByCurrentRunField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCurrentRunStep(), sql.OrderByField(field, opts...)) + } +} + +// 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...)) + } +} + +// ByIntentOverrideField orders the results by intent_override field. +func ByIntentOverrideField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newIntentOverrideStep(), sql.OrderByField(field, opts...)) + } +} + +// BySubscriptionField orders the results by subscription field. +func BySubscriptionField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubscriptionStep(), sql.OrderByField(field, opts...)) + } +} + +// BySubscriptionPhaseField orders the results by subscription_phase field. +func BySubscriptionPhaseField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubscriptionPhaseStep(), sql.OrderByField(field, opts...)) + } +} + +// BySubscriptionItemField orders the results by subscription_item field. +func BySubscriptionItemField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubscriptionItemStep(), sql.OrderByField(field, opts...)) + } +} + +// ByCustomerField orders the results by customer field. +func ByCustomerField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCustomerStep(), sql.OrderByField(field, opts...)) + } +} + +// ByFeatureField orders the results by feature field. +func ByFeatureField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newFeatureStep(), sql.OrderByField(field, opts...)) + } +} + +// ByTaxCodeField orders the results by tax_code field. +func ByTaxCodeField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTaxCodeStep(), sql.OrderByField(field, opts...)) + } +} +func newRunsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RunsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, RunsTable, RunsColumn), + ) +} +func newCurrentRunStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CurrentRunInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, CurrentRunTable, CurrentRunColumn), + ) +} +func newChargeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ChargeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, ChargeTable, ChargeColumn), + ) +} +func newIntentOverrideStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(IntentOverrideInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, IntentOverrideTable, IntentOverrideColumn), + ) +} +func newSubscriptionStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SubscriptionInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionTable, SubscriptionColumn), + ) +} +func newSubscriptionPhaseStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SubscriptionPhaseInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionPhaseTable, SubscriptionPhaseColumn), + ) +} +func newSubscriptionItemStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SubscriptionItemInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionItemTable, SubscriptionItemColumn), + ) +} +func newCustomerStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CustomerInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, CustomerTable, CustomerColumn), + ) +} +func newFeatureStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(FeatureInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, FeatureTable, FeatureColumn), + ) +} +func newTaxCodeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TaxCodeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, TaxCodeTable, TaxCodeColumn), + ) +} diff --git a/ent/db/chargeflatfee/where.go b/ent/db/chargeflatfee/where.go new file mode 100644 index 0000000000000000000000000000000000000000..ead19f442ed68edf0444876b238f98a23bd1f64c --- /dev/null +++ b/ent/db/chargeflatfee/where.go @@ -0,0 +1,2297 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeflatfee + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/billing/charges/flatfee" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContainsFold(FieldID, id)) +} + +// CustomerID applies equality check predicate on the "customer_id" field. It's identical to CustomerIDEQ. +func CustomerID(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldCustomerID, v)) +} + +// ServicePeriodFrom applies equality check predicate on the "service_period_from" field. It's identical to ServicePeriodFromEQ. +func ServicePeriodFrom(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(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.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// BillingPeriodFrom applies equality check predicate on the "billing_period_from" field. It's identical to BillingPeriodFromEQ. +func BillingPeriodFrom(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodTo applies equality check predicate on the "billing_period_to" field. It's identical to BillingPeriodToEQ. +func BillingPeriodTo(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldBillingPeriodTo, v)) +} + +// FullServicePeriodFrom applies equality check predicate on the "full_service_period_from" field. It's identical to FullServicePeriodFromEQ. +func FullServicePeriodFrom(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodTo applies equality check predicate on the "full_service_period_to" field. It's identical to FullServicePeriodToEQ. +func FullServicePeriodTo(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldFullServicePeriodTo, v)) +} + +// UniqueReferenceID applies equality check predicate on the "unique_reference_id" field. It's identical to UniqueReferenceIDEQ. +func UniqueReferenceID(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldUniqueReferenceID, v)) +} + +// Currency applies equality check predicate on the "currency" field. It's identical to CurrencyEQ. +func Currency(v currencyx.Code) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldEQ(FieldCurrency, vc)) +} + +// SubscriptionID applies equality check predicate on the "subscription_id" field. It's identical to SubscriptionIDEQ. +func SubscriptionID(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldSubscriptionID, v)) +} + +// SubscriptionPhaseID applies equality check predicate on the "subscription_phase_id" field. It's identical to SubscriptionPhaseIDEQ. +func SubscriptionPhaseID(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionItemID applies equality check predicate on the "subscription_item_id" field. It's identical to SubscriptionItemIDEQ. +func SubscriptionItemID(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldSubscriptionItemID, v)) +} + +// AdvanceAfter applies equality check predicate on the "advance_after" field. It's identical to AdvanceAfterEQ. +func AdvanceAfter(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldAdvanceAfter, v)) +} + +// TaxCodeID applies equality check predicate on the "tax_code_id" field. It's identical to TaxCodeIDEQ. +func TaxCodeID(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldTaxCodeID, v)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(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.ChargeFlatFee { + return predicate.ChargeFlatFee(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.ChargeFlatFee { + return predicate.ChargeFlatFee(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.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldName, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldDescription, v)) +} + +// PaymentTerm applies equality check predicate on the "payment_term" field. It's identical to PaymentTermEQ. +func PaymentTerm(v productcatalog.PaymentTermType) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldEQ(FieldPaymentTerm, vc)) +} + +// InvoiceAt applies equality check predicate on the "invoice_at" field. It's identical to InvoiceAtEQ. +func InvoiceAt(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldInvoiceAt, v)) +} + +// IntentDeletedAt applies equality check predicate on the "intent_deleted_at" field. It's identical to IntentDeletedAtEQ. +func IntentDeletedAt(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldIntentDeletedAt, v)) +} + +// FeatureKey applies equality check predicate on the "feature_key" field. It's identical to FeatureKeyEQ. +func FeatureKey(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldFeatureKey, v)) +} + +// FeatureID applies equality check predicate on the "feature_id" field. It's identical to FeatureIDEQ. +func FeatureID(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldFeatureID, v)) +} + +// AmountBeforeProration applies equality check predicate on the "amount_before_proration" field. It's identical to AmountBeforeProrationEQ. +func AmountBeforeProration(v alpacadecimal.Decimal) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldAmountBeforeProration, v)) +} + +// AmountAfterProration applies equality check predicate on the "amount_after_proration" field. It's identical to AmountAfterProrationEQ. +func AmountAfterProration(v alpacadecimal.Decimal) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldAmountAfterProration, v)) +} + +// CurrentRealizationRunID applies equality check predicate on the "current_realization_run_id" field. It's identical to CurrentRealizationRunIDEQ. +func CurrentRealizationRunID(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldCurrentRealizationRunID, v)) +} + +// CustomerIDEQ applies the EQ predicate on the "customer_id" field. +func CustomerIDEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldCustomerID, v)) +} + +// CustomerIDNEQ applies the NEQ predicate on the "customer_id" field. +func CustomerIDNEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldCustomerID, v)) +} + +// CustomerIDIn applies the In predicate on the "customer_id" field. +func CustomerIDIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldCustomerID, vs...)) +} + +// CustomerIDNotIn applies the NotIn predicate on the "customer_id" field. +func CustomerIDNotIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldCustomerID, vs...)) +} + +// CustomerIDGT applies the GT predicate on the "customer_id" field. +func CustomerIDGT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldCustomerID, v)) +} + +// CustomerIDGTE applies the GTE predicate on the "customer_id" field. +func CustomerIDGTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldCustomerID, v)) +} + +// CustomerIDLT applies the LT predicate on the "customer_id" field. +func CustomerIDLT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldCustomerID, v)) +} + +// CustomerIDLTE applies the LTE predicate on the "customer_id" field. +func CustomerIDLTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldCustomerID, v)) +} + +// CustomerIDContains applies the Contains predicate on the "customer_id" field. +func CustomerIDContains(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContains(FieldCustomerID, v)) +} + +// CustomerIDHasPrefix applies the HasPrefix predicate on the "customer_id" field. +func CustomerIDHasPrefix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasPrefix(FieldCustomerID, v)) +} + +// CustomerIDHasSuffix applies the HasSuffix predicate on the "customer_id" field. +func CustomerIDHasSuffix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasSuffix(FieldCustomerID, v)) +} + +// CustomerIDEqualFold applies the EqualFold predicate on the "customer_id" field. +func CustomerIDEqualFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEqualFold(FieldCustomerID, v)) +} + +// CustomerIDContainsFold applies the ContainsFold predicate on the "customer_id" field. +func CustomerIDContainsFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContainsFold(FieldCustomerID, v)) +} + +// ServicePeriodFromEQ applies the EQ predicate on the "service_period_from" field. +func ServicePeriodFromEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromNEQ applies the NEQ predicate on the "service_period_from" field. +func ServicePeriodFromNEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromIn applies the In predicate on the "service_period_from" field. +func ServicePeriodFromIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromNotIn applies the NotIn predicate on the "service_period_from" field. +func ServicePeriodFromNotIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromGT applies the GT predicate on the "service_period_from" field. +func ServicePeriodFromGT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromGTE applies the GTE predicate on the "service_period_from" field. +func ServicePeriodFromGTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLT applies the LT predicate on the "service_period_from" field. +func ServicePeriodFromLT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLTE applies the LTE predicate on the "service_period_from" field. +func ServicePeriodFromLTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodToEQ applies the EQ predicate on the "service_period_to" field. +func ServicePeriodToEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToNEQ applies the NEQ predicate on the "service_period_to" field. +func ServicePeriodToNEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToIn applies the In predicate on the "service_period_to" field. +func ServicePeriodToIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToNotIn applies the NotIn predicate on the "service_period_to" field. +func ServicePeriodToNotIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToGT applies the GT predicate on the "service_period_to" field. +func ServicePeriodToGT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToGTE applies the GTE predicate on the "service_period_to" field. +func ServicePeriodToGTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLT applies the LT predicate on the "service_period_to" field. +func ServicePeriodToLT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLTE applies the LTE predicate on the "service_period_to" field. +func ServicePeriodToLTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldServicePeriodTo, v)) +} + +// BillingPeriodFromEQ applies the EQ predicate on the "billing_period_from" field. +func BillingPeriodFromEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromNEQ applies the NEQ predicate on the "billing_period_from" field. +func BillingPeriodFromNEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromIn applies the In predicate on the "billing_period_from" field. +func BillingPeriodFromIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldBillingPeriodFrom, vs...)) +} + +// BillingPeriodFromNotIn applies the NotIn predicate on the "billing_period_from" field. +func BillingPeriodFromNotIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldBillingPeriodFrom, vs...)) +} + +// BillingPeriodFromGT applies the GT predicate on the "billing_period_from" field. +func BillingPeriodFromGT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromGTE applies the GTE predicate on the "billing_period_from" field. +func BillingPeriodFromGTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromLT applies the LT predicate on the "billing_period_from" field. +func BillingPeriodFromLT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromLTE applies the LTE predicate on the "billing_period_from" field. +func BillingPeriodFromLTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodToEQ applies the EQ predicate on the "billing_period_to" field. +func BillingPeriodToEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToNEQ applies the NEQ predicate on the "billing_period_to" field. +func BillingPeriodToNEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToIn applies the In predicate on the "billing_period_to" field. +func BillingPeriodToIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldBillingPeriodTo, vs...)) +} + +// BillingPeriodToNotIn applies the NotIn predicate on the "billing_period_to" field. +func BillingPeriodToNotIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldBillingPeriodTo, vs...)) +} + +// BillingPeriodToGT applies the GT predicate on the "billing_period_to" field. +func BillingPeriodToGT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToGTE applies the GTE predicate on the "billing_period_to" field. +func BillingPeriodToGTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToLT applies the LT predicate on the "billing_period_to" field. +func BillingPeriodToLT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToLTE applies the LTE predicate on the "billing_period_to" field. +func BillingPeriodToLTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldBillingPeriodTo, v)) +} + +// FullServicePeriodFromEQ applies the EQ predicate on the "full_service_period_from" field. +func FullServicePeriodFromEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromNEQ applies the NEQ predicate on the "full_service_period_from" field. +func FullServicePeriodFromNEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromIn applies the In predicate on the "full_service_period_from" field. +func FullServicePeriodFromIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldFullServicePeriodFrom, vs...)) +} + +// FullServicePeriodFromNotIn applies the NotIn predicate on the "full_service_period_from" field. +func FullServicePeriodFromNotIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldFullServicePeriodFrom, vs...)) +} + +// FullServicePeriodFromGT applies the GT predicate on the "full_service_period_from" field. +func FullServicePeriodFromGT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromGTE applies the GTE predicate on the "full_service_period_from" field. +func FullServicePeriodFromGTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromLT applies the LT predicate on the "full_service_period_from" field. +func FullServicePeriodFromLT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromLTE applies the LTE predicate on the "full_service_period_from" field. +func FullServicePeriodFromLTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodToEQ applies the EQ predicate on the "full_service_period_to" field. +func FullServicePeriodToEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToNEQ applies the NEQ predicate on the "full_service_period_to" field. +func FullServicePeriodToNEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToIn applies the In predicate on the "full_service_period_to" field. +func FullServicePeriodToIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldFullServicePeriodTo, vs...)) +} + +// FullServicePeriodToNotIn applies the NotIn predicate on the "full_service_period_to" field. +func FullServicePeriodToNotIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldFullServicePeriodTo, vs...)) +} + +// FullServicePeriodToGT applies the GT predicate on the "full_service_period_to" field. +func FullServicePeriodToGT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToGTE applies the GTE predicate on the "full_service_period_to" field. +func FullServicePeriodToGTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToLT applies the LT predicate on the "full_service_period_to" field. +func FullServicePeriodToLT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToLTE applies the LTE predicate on the "full_service_period_to" field. +func FullServicePeriodToLTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldFullServicePeriodTo, v)) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v meta.ChargeStatus) predicate.ChargeFlatFee { + vc := v + return predicate.ChargeFlatFee(sql.FieldEQ(FieldStatus, vc)) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v meta.ChargeStatus) predicate.ChargeFlatFee { + vc := v + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldStatus, vc)) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...meta.ChargeStatus) predicate.ChargeFlatFee { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFee(sql.FieldIn(FieldStatus, v...)) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...meta.ChargeStatus) predicate.ChargeFlatFee { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldStatus, v...)) +} + +// UniqueReferenceIDEQ applies the EQ predicate on the "unique_reference_id" field. +func UniqueReferenceIDEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDNEQ applies the NEQ predicate on the "unique_reference_id" field. +func UniqueReferenceIDNEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDIn applies the In predicate on the "unique_reference_id" field. +func UniqueReferenceIDIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldUniqueReferenceID, vs...)) +} + +// UniqueReferenceIDNotIn applies the NotIn predicate on the "unique_reference_id" field. +func UniqueReferenceIDNotIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldUniqueReferenceID, vs...)) +} + +// UniqueReferenceIDGT applies the GT predicate on the "unique_reference_id" field. +func UniqueReferenceIDGT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDGTE applies the GTE predicate on the "unique_reference_id" field. +func UniqueReferenceIDGTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDLT applies the LT predicate on the "unique_reference_id" field. +func UniqueReferenceIDLT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDLTE applies the LTE predicate on the "unique_reference_id" field. +func UniqueReferenceIDLTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDContains applies the Contains predicate on the "unique_reference_id" field. +func UniqueReferenceIDContains(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContains(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDHasPrefix applies the HasPrefix predicate on the "unique_reference_id" field. +func UniqueReferenceIDHasPrefix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasPrefix(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDHasSuffix applies the HasSuffix predicate on the "unique_reference_id" field. +func UniqueReferenceIDHasSuffix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasSuffix(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDIsNil applies the IsNil predicate on the "unique_reference_id" field. +func UniqueReferenceIDIsNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIsNull(FieldUniqueReferenceID)) +} + +// UniqueReferenceIDNotNil applies the NotNil predicate on the "unique_reference_id" field. +func UniqueReferenceIDNotNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotNull(FieldUniqueReferenceID)) +} + +// UniqueReferenceIDEqualFold applies the EqualFold predicate on the "unique_reference_id" field. +func UniqueReferenceIDEqualFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEqualFold(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDContainsFold applies the ContainsFold predicate on the "unique_reference_id" field. +func UniqueReferenceIDContainsFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContainsFold(FieldUniqueReferenceID, v)) +} + +// CurrencyEQ applies the EQ predicate on the "currency" field. +func CurrencyEQ(v currencyx.Code) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldEQ(FieldCurrency, vc)) +} + +// CurrencyNEQ applies the NEQ predicate on the "currency" field. +func CurrencyNEQ(v currencyx.Code) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldCurrency, vc)) +} + +// CurrencyIn applies the In predicate on the "currency" field. +func CurrencyIn(vs ...currencyx.Code) predicate.ChargeFlatFee { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargeFlatFee(sql.FieldIn(FieldCurrency, v...)) +} + +// CurrencyNotIn applies the NotIn predicate on the "currency" field. +func CurrencyNotIn(vs ...currencyx.Code) predicate.ChargeFlatFee { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldCurrency, v...)) +} + +// CurrencyGT applies the GT predicate on the "currency" field. +func CurrencyGT(v currencyx.Code) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldGT(FieldCurrency, vc)) +} + +// CurrencyGTE applies the GTE predicate on the "currency" field. +func CurrencyGTE(v currencyx.Code) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldGTE(FieldCurrency, vc)) +} + +// CurrencyLT applies the LT predicate on the "currency" field. +func CurrencyLT(v currencyx.Code) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldLT(FieldCurrency, vc)) +} + +// CurrencyLTE applies the LTE predicate on the "currency" field. +func CurrencyLTE(v currencyx.Code) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldLTE(FieldCurrency, vc)) +} + +// CurrencyContains applies the Contains predicate on the "currency" field. +func CurrencyContains(v currencyx.Code) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldContains(FieldCurrency, vc)) +} + +// CurrencyHasPrefix applies the HasPrefix predicate on the "currency" field. +func CurrencyHasPrefix(v currencyx.Code) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldHasPrefix(FieldCurrency, vc)) +} + +// CurrencyHasSuffix applies the HasSuffix predicate on the "currency" field. +func CurrencyHasSuffix(v currencyx.Code) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldHasSuffix(FieldCurrency, vc)) +} + +// CurrencyEqualFold applies the EqualFold predicate on the "currency" field. +func CurrencyEqualFold(v currencyx.Code) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldEqualFold(FieldCurrency, vc)) +} + +// CurrencyContainsFold applies the ContainsFold predicate on the "currency" field. +func CurrencyContainsFold(v currencyx.Code) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldContainsFold(FieldCurrency, vc)) +} + +// ManagedByEQ applies the EQ predicate on the "managed_by" field. +func ManagedByEQ(v billing.InvoiceLineManagedBy) predicate.ChargeFlatFee { + vc := v + return predicate.ChargeFlatFee(sql.FieldEQ(FieldManagedBy, vc)) +} + +// ManagedByNEQ applies the NEQ predicate on the "managed_by" field. +func ManagedByNEQ(v billing.InvoiceLineManagedBy) predicate.ChargeFlatFee { + vc := v + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldManagedBy, vc)) +} + +// ManagedByIn applies the In predicate on the "managed_by" field. +func ManagedByIn(vs ...billing.InvoiceLineManagedBy) predicate.ChargeFlatFee { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFee(sql.FieldIn(FieldManagedBy, v...)) +} + +// ManagedByNotIn applies the NotIn predicate on the "managed_by" field. +func ManagedByNotIn(vs ...billing.InvoiceLineManagedBy) predicate.ChargeFlatFee { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldManagedBy, v...)) +} + +// SubscriptionIDEQ applies the EQ predicate on the "subscription_id" field. +func SubscriptionIDEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldSubscriptionID, v)) +} + +// SubscriptionIDNEQ applies the NEQ predicate on the "subscription_id" field. +func SubscriptionIDNEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldSubscriptionID, v)) +} + +// SubscriptionIDIn applies the In predicate on the "subscription_id" field. +func SubscriptionIDIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldSubscriptionID, vs...)) +} + +// SubscriptionIDNotIn applies the NotIn predicate on the "subscription_id" field. +func SubscriptionIDNotIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldSubscriptionID, vs...)) +} + +// SubscriptionIDGT applies the GT predicate on the "subscription_id" field. +func SubscriptionIDGT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldSubscriptionID, v)) +} + +// SubscriptionIDGTE applies the GTE predicate on the "subscription_id" field. +func SubscriptionIDGTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldSubscriptionID, v)) +} + +// SubscriptionIDLT applies the LT predicate on the "subscription_id" field. +func SubscriptionIDLT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldSubscriptionID, v)) +} + +// SubscriptionIDLTE applies the LTE predicate on the "subscription_id" field. +func SubscriptionIDLTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldSubscriptionID, v)) +} + +// SubscriptionIDContains applies the Contains predicate on the "subscription_id" field. +func SubscriptionIDContains(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContains(FieldSubscriptionID, v)) +} + +// SubscriptionIDHasPrefix applies the HasPrefix predicate on the "subscription_id" field. +func SubscriptionIDHasPrefix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasPrefix(FieldSubscriptionID, v)) +} + +// SubscriptionIDHasSuffix applies the HasSuffix predicate on the "subscription_id" field. +func SubscriptionIDHasSuffix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasSuffix(FieldSubscriptionID, v)) +} + +// SubscriptionIDIsNil applies the IsNil predicate on the "subscription_id" field. +func SubscriptionIDIsNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIsNull(FieldSubscriptionID)) +} + +// SubscriptionIDNotNil applies the NotNil predicate on the "subscription_id" field. +func SubscriptionIDNotNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotNull(FieldSubscriptionID)) +} + +// SubscriptionIDEqualFold applies the EqualFold predicate on the "subscription_id" field. +func SubscriptionIDEqualFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEqualFold(FieldSubscriptionID, v)) +} + +// SubscriptionIDContainsFold applies the ContainsFold predicate on the "subscription_id" field. +func SubscriptionIDContainsFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContainsFold(FieldSubscriptionID, v)) +} + +// SubscriptionPhaseIDEQ applies the EQ predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDNEQ applies the NEQ predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDNEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDIn applies the In predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldSubscriptionPhaseID, vs...)) +} + +// SubscriptionPhaseIDNotIn applies the NotIn predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDNotIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldSubscriptionPhaseID, vs...)) +} + +// SubscriptionPhaseIDGT applies the GT predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDGT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDGTE applies the GTE predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDGTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDLT applies the LT predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDLT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDLTE applies the LTE predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDLTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDContains applies the Contains predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDContains(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContains(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDHasPrefix applies the HasPrefix predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDHasPrefix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasPrefix(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDHasSuffix applies the HasSuffix predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDHasSuffix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasSuffix(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDIsNil applies the IsNil predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDIsNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIsNull(FieldSubscriptionPhaseID)) +} + +// SubscriptionPhaseIDNotNil applies the NotNil predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDNotNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotNull(FieldSubscriptionPhaseID)) +} + +// SubscriptionPhaseIDEqualFold applies the EqualFold predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDEqualFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEqualFold(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDContainsFold applies the ContainsFold predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDContainsFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContainsFold(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionItemIDEQ applies the EQ predicate on the "subscription_item_id" field. +func SubscriptionItemIDEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDNEQ applies the NEQ predicate on the "subscription_item_id" field. +func SubscriptionItemIDNEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDIn applies the In predicate on the "subscription_item_id" field. +func SubscriptionItemIDIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldSubscriptionItemID, vs...)) +} + +// SubscriptionItemIDNotIn applies the NotIn predicate on the "subscription_item_id" field. +func SubscriptionItemIDNotIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldSubscriptionItemID, vs...)) +} + +// SubscriptionItemIDGT applies the GT predicate on the "subscription_item_id" field. +func SubscriptionItemIDGT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDGTE applies the GTE predicate on the "subscription_item_id" field. +func SubscriptionItemIDGTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDLT applies the LT predicate on the "subscription_item_id" field. +func SubscriptionItemIDLT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDLTE applies the LTE predicate on the "subscription_item_id" field. +func SubscriptionItemIDLTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDContains applies the Contains predicate on the "subscription_item_id" field. +func SubscriptionItemIDContains(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContains(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDHasPrefix applies the HasPrefix predicate on the "subscription_item_id" field. +func SubscriptionItemIDHasPrefix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasPrefix(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDHasSuffix applies the HasSuffix predicate on the "subscription_item_id" field. +func SubscriptionItemIDHasSuffix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasSuffix(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDIsNil applies the IsNil predicate on the "subscription_item_id" field. +func SubscriptionItemIDIsNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIsNull(FieldSubscriptionItemID)) +} + +// SubscriptionItemIDNotNil applies the NotNil predicate on the "subscription_item_id" field. +func SubscriptionItemIDNotNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotNull(FieldSubscriptionItemID)) +} + +// SubscriptionItemIDEqualFold applies the EqualFold predicate on the "subscription_item_id" field. +func SubscriptionItemIDEqualFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEqualFold(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDContainsFold applies the ContainsFold predicate on the "subscription_item_id" field. +func SubscriptionItemIDContainsFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContainsFold(FieldSubscriptionItemID, v)) +} + +// AdvanceAfterEQ applies the EQ predicate on the "advance_after" field. +func AdvanceAfterEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldAdvanceAfter, v)) +} + +// AdvanceAfterNEQ applies the NEQ predicate on the "advance_after" field. +func AdvanceAfterNEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldAdvanceAfter, v)) +} + +// AdvanceAfterIn applies the In predicate on the "advance_after" field. +func AdvanceAfterIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldAdvanceAfter, vs...)) +} + +// AdvanceAfterNotIn applies the NotIn predicate on the "advance_after" field. +func AdvanceAfterNotIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldAdvanceAfter, vs...)) +} + +// AdvanceAfterGT applies the GT predicate on the "advance_after" field. +func AdvanceAfterGT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldAdvanceAfter, v)) +} + +// AdvanceAfterGTE applies the GTE predicate on the "advance_after" field. +func AdvanceAfterGTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldAdvanceAfter, v)) +} + +// AdvanceAfterLT applies the LT predicate on the "advance_after" field. +func AdvanceAfterLT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldAdvanceAfter, v)) +} + +// AdvanceAfterLTE applies the LTE predicate on the "advance_after" field. +func AdvanceAfterLTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldAdvanceAfter, v)) +} + +// AdvanceAfterIsNil applies the IsNil predicate on the "advance_after" field. +func AdvanceAfterIsNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIsNull(FieldAdvanceAfter)) +} + +// AdvanceAfterNotNil applies the NotNil predicate on the "advance_after" field. +func AdvanceAfterNotNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotNull(FieldAdvanceAfter)) +} + +// TaxCodeIDEQ applies the EQ predicate on the "tax_code_id" field. +func TaxCodeIDEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldTaxCodeID, v)) +} + +// TaxCodeIDNEQ applies the NEQ predicate on the "tax_code_id" field. +func TaxCodeIDNEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldTaxCodeID, v)) +} + +// TaxCodeIDIn applies the In predicate on the "tax_code_id" field. +func TaxCodeIDIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldTaxCodeID, vs...)) +} + +// TaxCodeIDNotIn applies the NotIn predicate on the "tax_code_id" field. +func TaxCodeIDNotIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldTaxCodeID, vs...)) +} + +// TaxCodeIDGT applies the GT predicate on the "tax_code_id" field. +func TaxCodeIDGT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldTaxCodeID, v)) +} + +// TaxCodeIDGTE applies the GTE predicate on the "tax_code_id" field. +func TaxCodeIDGTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldTaxCodeID, v)) +} + +// TaxCodeIDLT applies the LT predicate on the "tax_code_id" field. +func TaxCodeIDLT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldTaxCodeID, v)) +} + +// TaxCodeIDLTE applies the LTE predicate on the "tax_code_id" field. +func TaxCodeIDLTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldTaxCodeID, v)) +} + +// TaxCodeIDContains applies the Contains predicate on the "tax_code_id" field. +func TaxCodeIDContains(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContains(FieldTaxCodeID, v)) +} + +// TaxCodeIDHasPrefix applies the HasPrefix predicate on the "tax_code_id" field. +func TaxCodeIDHasPrefix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasPrefix(FieldTaxCodeID, v)) +} + +// TaxCodeIDHasSuffix applies the HasSuffix predicate on the "tax_code_id" field. +func TaxCodeIDHasSuffix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasSuffix(FieldTaxCodeID, v)) +} + +// TaxCodeIDEqualFold applies the EqualFold predicate on the "tax_code_id" field. +func TaxCodeIDEqualFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEqualFold(FieldTaxCodeID, v)) +} + +// TaxCodeIDContainsFold applies the ContainsFold predicate on the "tax_code_id" field. +func TaxCodeIDContainsFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContainsFold(FieldTaxCodeID, v)) +} + +// TaxBehaviorEQ applies the EQ predicate on the "tax_behavior" field. +func TaxBehaviorEQ(v productcatalog.TaxBehavior) predicate.ChargeFlatFee { + vc := v + return predicate.ChargeFlatFee(sql.FieldEQ(FieldTaxBehavior, vc)) +} + +// TaxBehaviorNEQ applies the NEQ predicate on the "tax_behavior" field. +func TaxBehaviorNEQ(v productcatalog.TaxBehavior) predicate.ChargeFlatFee { + vc := v + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldTaxBehavior, vc)) +} + +// TaxBehaviorIn applies the In predicate on the "tax_behavior" field. +func TaxBehaviorIn(vs ...productcatalog.TaxBehavior) predicate.ChargeFlatFee { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFee(sql.FieldIn(FieldTaxBehavior, v...)) +} + +// TaxBehaviorNotIn applies the NotIn predicate on the "tax_behavior" field. +func TaxBehaviorNotIn(vs ...productcatalog.TaxBehavior) predicate.ChargeFlatFee { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldTaxBehavior, v...)) +} + +// TaxBehaviorIsNil applies the IsNil predicate on the "tax_behavior" field. +func TaxBehaviorIsNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIsNull(FieldTaxBehavior)) +} + +// TaxBehaviorNotNil applies the NotNil predicate on the "tax_behavior" field. +func TaxBehaviorNotNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotNull(FieldTaxBehavior)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotNull(FieldAnnotations)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContainsFold(FieldNamespace, v)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotNull(FieldMetadata)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotNull(FieldDeletedAt)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContainsFold(FieldName, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContainsFold(FieldDescription, v)) +} + +// PaymentTermEQ applies the EQ predicate on the "payment_term" field. +func PaymentTermEQ(v productcatalog.PaymentTermType) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldEQ(FieldPaymentTerm, vc)) +} + +// PaymentTermNEQ applies the NEQ predicate on the "payment_term" field. +func PaymentTermNEQ(v productcatalog.PaymentTermType) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldPaymentTerm, vc)) +} + +// PaymentTermIn applies the In predicate on the "payment_term" field. +func PaymentTermIn(vs ...productcatalog.PaymentTermType) predicate.ChargeFlatFee { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargeFlatFee(sql.FieldIn(FieldPaymentTerm, v...)) +} + +// PaymentTermNotIn applies the NotIn predicate on the "payment_term" field. +func PaymentTermNotIn(vs ...productcatalog.PaymentTermType) predicate.ChargeFlatFee { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldPaymentTerm, v...)) +} + +// PaymentTermGT applies the GT predicate on the "payment_term" field. +func PaymentTermGT(v productcatalog.PaymentTermType) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldGT(FieldPaymentTerm, vc)) +} + +// PaymentTermGTE applies the GTE predicate on the "payment_term" field. +func PaymentTermGTE(v productcatalog.PaymentTermType) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldGTE(FieldPaymentTerm, vc)) +} + +// PaymentTermLT applies the LT predicate on the "payment_term" field. +func PaymentTermLT(v productcatalog.PaymentTermType) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldLT(FieldPaymentTerm, vc)) +} + +// PaymentTermLTE applies the LTE predicate on the "payment_term" field. +func PaymentTermLTE(v productcatalog.PaymentTermType) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldLTE(FieldPaymentTerm, vc)) +} + +// PaymentTermContains applies the Contains predicate on the "payment_term" field. +func PaymentTermContains(v productcatalog.PaymentTermType) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldContains(FieldPaymentTerm, vc)) +} + +// PaymentTermHasPrefix applies the HasPrefix predicate on the "payment_term" field. +func PaymentTermHasPrefix(v productcatalog.PaymentTermType) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldHasPrefix(FieldPaymentTerm, vc)) +} + +// PaymentTermHasSuffix applies the HasSuffix predicate on the "payment_term" field. +func PaymentTermHasSuffix(v productcatalog.PaymentTermType) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldHasSuffix(FieldPaymentTerm, vc)) +} + +// PaymentTermEqualFold applies the EqualFold predicate on the "payment_term" field. +func PaymentTermEqualFold(v productcatalog.PaymentTermType) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldEqualFold(FieldPaymentTerm, vc)) +} + +// PaymentTermContainsFold applies the ContainsFold predicate on the "payment_term" field. +func PaymentTermContainsFold(v productcatalog.PaymentTermType) predicate.ChargeFlatFee { + vc := string(v) + return predicate.ChargeFlatFee(sql.FieldContainsFold(FieldPaymentTerm, vc)) +} + +// InvoiceAtEQ applies the EQ predicate on the "invoice_at" field. +func InvoiceAtEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldInvoiceAt, v)) +} + +// InvoiceAtNEQ applies the NEQ predicate on the "invoice_at" field. +func InvoiceAtNEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldInvoiceAt, v)) +} + +// InvoiceAtIn applies the In predicate on the "invoice_at" field. +func InvoiceAtIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldInvoiceAt, vs...)) +} + +// InvoiceAtNotIn applies the NotIn predicate on the "invoice_at" field. +func InvoiceAtNotIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldInvoiceAt, vs...)) +} + +// InvoiceAtGT applies the GT predicate on the "invoice_at" field. +func InvoiceAtGT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldInvoiceAt, v)) +} + +// InvoiceAtGTE applies the GTE predicate on the "invoice_at" field. +func InvoiceAtGTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldInvoiceAt, v)) +} + +// InvoiceAtLT applies the LT predicate on the "invoice_at" field. +func InvoiceAtLT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldInvoiceAt, v)) +} + +// InvoiceAtLTE applies the LTE predicate on the "invoice_at" field. +func InvoiceAtLTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldInvoiceAt, v)) +} + +// SettlementModeEQ applies the EQ predicate on the "settlement_mode" field. +func SettlementModeEQ(v productcatalog.SettlementMode) predicate.ChargeFlatFee { + vc := v + return predicate.ChargeFlatFee(sql.FieldEQ(FieldSettlementMode, vc)) +} + +// SettlementModeNEQ applies the NEQ predicate on the "settlement_mode" field. +func SettlementModeNEQ(v productcatalog.SettlementMode) predicate.ChargeFlatFee { + vc := v + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldSettlementMode, vc)) +} + +// SettlementModeIn applies the In predicate on the "settlement_mode" field. +func SettlementModeIn(vs ...productcatalog.SettlementMode) predicate.ChargeFlatFee { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFee(sql.FieldIn(FieldSettlementMode, v...)) +} + +// SettlementModeNotIn applies the NotIn predicate on the "settlement_mode" field. +func SettlementModeNotIn(vs ...productcatalog.SettlementMode) predicate.ChargeFlatFee { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldSettlementMode, v...)) +} + +// IntentDeletedAtEQ applies the EQ predicate on the "intent_deleted_at" field. +func IntentDeletedAtEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtNEQ applies the NEQ predicate on the "intent_deleted_at" field. +func IntentDeletedAtNEQ(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtIn applies the In predicate on the "intent_deleted_at" field. +func IntentDeletedAtIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldIntentDeletedAt, vs...)) +} + +// IntentDeletedAtNotIn applies the NotIn predicate on the "intent_deleted_at" field. +func IntentDeletedAtNotIn(vs ...time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldIntentDeletedAt, vs...)) +} + +// IntentDeletedAtGT applies the GT predicate on the "intent_deleted_at" field. +func IntentDeletedAtGT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtGTE applies the GTE predicate on the "intent_deleted_at" field. +func IntentDeletedAtGTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtLT applies the LT predicate on the "intent_deleted_at" field. +func IntentDeletedAtLT(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtLTE applies the LTE predicate on the "intent_deleted_at" field. +func IntentDeletedAtLTE(v time.Time) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtIsNil applies the IsNil predicate on the "intent_deleted_at" field. +func IntentDeletedAtIsNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIsNull(FieldIntentDeletedAt)) +} + +// IntentDeletedAtNotNil applies the NotNil predicate on the "intent_deleted_at" field. +func IntentDeletedAtNotNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotNull(FieldIntentDeletedAt)) +} + +// DiscountsIsNil applies the IsNil predicate on the "discounts" field. +func DiscountsIsNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIsNull(FieldDiscounts)) +} + +// DiscountsNotNil applies the NotNil predicate on the "discounts" field. +func DiscountsNotNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotNull(FieldDiscounts)) +} + +// ProRatingEQ applies the EQ predicate on the "pro_rating" field. +func ProRatingEQ(v flatfee.ProRatingModeAdapterEnum) predicate.ChargeFlatFee { + vc := v + return predicate.ChargeFlatFee(sql.FieldEQ(FieldProRating, vc)) +} + +// ProRatingNEQ applies the NEQ predicate on the "pro_rating" field. +func ProRatingNEQ(v flatfee.ProRatingModeAdapterEnum) predicate.ChargeFlatFee { + vc := v + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldProRating, vc)) +} + +// ProRatingIn applies the In predicate on the "pro_rating" field. +func ProRatingIn(vs ...flatfee.ProRatingModeAdapterEnum) predicate.ChargeFlatFee { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFee(sql.FieldIn(FieldProRating, v...)) +} + +// ProRatingNotIn applies the NotIn predicate on the "pro_rating" field. +func ProRatingNotIn(vs ...flatfee.ProRatingModeAdapterEnum) predicate.ChargeFlatFee { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldProRating, v...)) +} + +// FeatureKeyEQ applies the EQ predicate on the "feature_key" field. +func FeatureKeyEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldFeatureKey, v)) +} + +// FeatureKeyNEQ applies the NEQ predicate on the "feature_key" field. +func FeatureKeyNEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldFeatureKey, v)) +} + +// FeatureKeyIn applies the In predicate on the "feature_key" field. +func FeatureKeyIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldFeatureKey, vs...)) +} + +// FeatureKeyNotIn applies the NotIn predicate on the "feature_key" field. +func FeatureKeyNotIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldFeatureKey, vs...)) +} + +// FeatureKeyGT applies the GT predicate on the "feature_key" field. +func FeatureKeyGT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldFeatureKey, v)) +} + +// FeatureKeyGTE applies the GTE predicate on the "feature_key" field. +func FeatureKeyGTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldFeatureKey, v)) +} + +// FeatureKeyLT applies the LT predicate on the "feature_key" field. +func FeatureKeyLT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldFeatureKey, v)) +} + +// FeatureKeyLTE applies the LTE predicate on the "feature_key" field. +func FeatureKeyLTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldFeatureKey, v)) +} + +// FeatureKeyContains applies the Contains predicate on the "feature_key" field. +func FeatureKeyContains(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContains(FieldFeatureKey, v)) +} + +// FeatureKeyHasPrefix applies the HasPrefix predicate on the "feature_key" field. +func FeatureKeyHasPrefix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasPrefix(FieldFeatureKey, v)) +} + +// FeatureKeyHasSuffix applies the HasSuffix predicate on the "feature_key" field. +func FeatureKeyHasSuffix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasSuffix(FieldFeatureKey, v)) +} + +// FeatureKeyIsNil applies the IsNil predicate on the "feature_key" field. +func FeatureKeyIsNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIsNull(FieldFeatureKey)) +} + +// FeatureKeyNotNil applies the NotNil predicate on the "feature_key" field. +func FeatureKeyNotNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotNull(FieldFeatureKey)) +} + +// FeatureKeyEqualFold applies the EqualFold predicate on the "feature_key" field. +func FeatureKeyEqualFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEqualFold(FieldFeatureKey, v)) +} + +// FeatureKeyContainsFold applies the ContainsFold predicate on the "feature_key" field. +func FeatureKeyContainsFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContainsFold(FieldFeatureKey, v)) +} + +// FeatureIDEQ applies the EQ predicate on the "feature_id" field. +func FeatureIDEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldFeatureID, v)) +} + +// FeatureIDNEQ applies the NEQ predicate on the "feature_id" field. +func FeatureIDNEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldFeatureID, v)) +} + +// FeatureIDIn applies the In predicate on the "feature_id" field. +func FeatureIDIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldFeatureID, vs...)) +} + +// FeatureIDNotIn applies the NotIn predicate on the "feature_id" field. +func FeatureIDNotIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldFeatureID, vs...)) +} + +// FeatureIDGT applies the GT predicate on the "feature_id" field. +func FeatureIDGT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldFeatureID, v)) +} + +// FeatureIDGTE applies the GTE predicate on the "feature_id" field. +func FeatureIDGTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldFeatureID, v)) +} + +// FeatureIDLT applies the LT predicate on the "feature_id" field. +func FeatureIDLT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldFeatureID, v)) +} + +// FeatureIDLTE applies the LTE predicate on the "feature_id" field. +func FeatureIDLTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldFeatureID, v)) +} + +// FeatureIDContains applies the Contains predicate on the "feature_id" field. +func FeatureIDContains(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContains(FieldFeatureID, v)) +} + +// FeatureIDHasPrefix applies the HasPrefix predicate on the "feature_id" field. +func FeatureIDHasPrefix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasPrefix(FieldFeatureID, v)) +} + +// FeatureIDHasSuffix applies the HasSuffix predicate on the "feature_id" field. +func FeatureIDHasSuffix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasSuffix(FieldFeatureID, v)) +} + +// FeatureIDIsNil applies the IsNil predicate on the "feature_id" field. +func FeatureIDIsNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIsNull(FieldFeatureID)) +} + +// FeatureIDNotNil applies the NotNil predicate on the "feature_id" field. +func FeatureIDNotNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotNull(FieldFeatureID)) +} + +// FeatureIDEqualFold applies the EqualFold predicate on the "feature_id" field. +func FeatureIDEqualFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEqualFold(FieldFeatureID, v)) +} + +// FeatureIDContainsFold applies the ContainsFold predicate on the "feature_id" field. +func FeatureIDContainsFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContainsFold(FieldFeatureID, v)) +} + +// AmountBeforeProrationEQ applies the EQ predicate on the "amount_before_proration" field. +func AmountBeforeProrationEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldAmountBeforeProration, v)) +} + +// AmountBeforeProrationNEQ applies the NEQ predicate on the "amount_before_proration" field. +func AmountBeforeProrationNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldAmountBeforeProration, v)) +} + +// AmountBeforeProrationIn applies the In predicate on the "amount_before_proration" field. +func AmountBeforeProrationIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldAmountBeforeProration, vs...)) +} + +// AmountBeforeProrationNotIn applies the NotIn predicate on the "amount_before_proration" field. +func AmountBeforeProrationNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldAmountBeforeProration, vs...)) +} + +// AmountBeforeProrationGT applies the GT predicate on the "amount_before_proration" field. +func AmountBeforeProrationGT(v alpacadecimal.Decimal) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldAmountBeforeProration, v)) +} + +// AmountBeforeProrationGTE applies the GTE predicate on the "amount_before_proration" field. +func AmountBeforeProrationGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldAmountBeforeProration, v)) +} + +// AmountBeforeProrationLT applies the LT predicate on the "amount_before_proration" field. +func AmountBeforeProrationLT(v alpacadecimal.Decimal) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldAmountBeforeProration, v)) +} + +// AmountBeforeProrationLTE applies the LTE predicate on the "amount_before_proration" field. +func AmountBeforeProrationLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldAmountBeforeProration, v)) +} + +// AmountAfterProrationEQ applies the EQ predicate on the "amount_after_proration" field. +func AmountAfterProrationEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldAmountAfterProration, v)) +} + +// AmountAfterProrationNEQ applies the NEQ predicate on the "amount_after_proration" field. +func AmountAfterProrationNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldAmountAfterProration, v)) +} + +// AmountAfterProrationIn applies the In predicate on the "amount_after_proration" field. +func AmountAfterProrationIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldAmountAfterProration, vs...)) +} + +// AmountAfterProrationNotIn applies the NotIn predicate on the "amount_after_proration" field. +func AmountAfterProrationNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldAmountAfterProration, vs...)) +} + +// AmountAfterProrationGT applies the GT predicate on the "amount_after_proration" field. +func AmountAfterProrationGT(v alpacadecimal.Decimal) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldAmountAfterProration, v)) +} + +// AmountAfterProrationGTE applies the GTE predicate on the "amount_after_proration" field. +func AmountAfterProrationGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldAmountAfterProration, v)) +} + +// AmountAfterProrationLT applies the LT predicate on the "amount_after_proration" field. +func AmountAfterProrationLT(v alpacadecimal.Decimal) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldAmountAfterProration, v)) +} + +// AmountAfterProrationLTE applies the LTE predicate on the "amount_after_proration" field. +func AmountAfterProrationLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldAmountAfterProration, v)) +} + +// CurrentRealizationRunIDEQ applies the EQ predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEQ(FieldCurrentRealizationRunID, v)) +} + +// CurrentRealizationRunIDNEQ applies the NEQ predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDNEQ(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldCurrentRealizationRunID, v)) +} + +// CurrentRealizationRunIDIn applies the In predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIn(FieldCurrentRealizationRunID, vs...)) +} + +// CurrentRealizationRunIDNotIn applies the NotIn predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDNotIn(vs ...string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldCurrentRealizationRunID, vs...)) +} + +// CurrentRealizationRunIDGT applies the GT predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDGT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGT(FieldCurrentRealizationRunID, v)) +} + +// CurrentRealizationRunIDGTE applies the GTE predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDGTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldGTE(FieldCurrentRealizationRunID, v)) +} + +// CurrentRealizationRunIDLT applies the LT predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDLT(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLT(FieldCurrentRealizationRunID, v)) +} + +// CurrentRealizationRunIDLTE applies the LTE predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDLTE(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldLTE(FieldCurrentRealizationRunID, v)) +} + +// CurrentRealizationRunIDContains applies the Contains predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDContains(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContains(FieldCurrentRealizationRunID, v)) +} + +// CurrentRealizationRunIDHasPrefix applies the HasPrefix predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDHasPrefix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasPrefix(FieldCurrentRealizationRunID, v)) +} + +// CurrentRealizationRunIDHasSuffix applies the HasSuffix predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDHasSuffix(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldHasSuffix(FieldCurrentRealizationRunID, v)) +} + +// CurrentRealizationRunIDIsNil applies the IsNil predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDIsNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldIsNull(FieldCurrentRealizationRunID)) +} + +// CurrentRealizationRunIDNotNil applies the NotNil predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDNotNil() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldNotNull(FieldCurrentRealizationRunID)) +} + +// CurrentRealizationRunIDEqualFold applies the EqualFold predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDEqualFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldEqualFold(FieldCurrentRealizationRunID, v)) +} + +// CurrentRealizationRunIDContainsFold applies the ContainsFold predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDContainsFold(v string) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.FieldContainsFold(FieldCurrentRealizationRunID, v)) +} + +// StatusDetailedEQ applies the EQ predicate on the "status_detailed" field. +func StatusDetailedEQ(v flatfee.Status) predicate.ChargeFlatFee { + vc := v + return predicate.ChargeFlatFee(sql.FieldEQ(FieldStatusDetailed, vc)) +} + +// StatusDetailedNEQ applies the NEQ predicate on the "status_detailed" field. +func StatusDetailedNEQ(v flatfee.Status) predicate.ChargeFlatFee { + vc := v + return predicate.ChargeFlatFee(sql.FieldNEQ(FieldStatusDetailed, vc)) +} + +// StatusDetailedIn applies the In predicate on the "status_detailed" field. +func StatusDetailedIn(vs ...flatfee.Status) predicate.ChargeFlatFee { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFee(sql.FieldIn(FieldStatusDetailed, v...)) +} + +// StatusDetailedNotIn applies the NotIn predicate on the "status_detailed" field. +func StatusDetailedNotIn(vs ...flatfee.Status) predicate.ChargeFlatFee { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFee(sql.FieldNotIn(FieldStatusDetailed, v...)) +} + +// HasRuns applies the HasEdge predicate on the "runs" edge. +func HasRuns() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(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.ChargeFlatFeeRun) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(func(s *sql.Selector) { + step := newRunsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasCurrentRun applies the HasEdge predicate on the "current_run" edge. +func HasCurrentRun() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, CurrentRunTable, CurrentRunColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCurrentRunWith applies the HasEdge predicate on the "current_run" edge with a given conditions (other predicates). +func HasCurrentRunWith(preds ...predicate.ChargeFlatFeeRun) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(func(s *sql.Selector) { + step := newCurrentRunStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasCharge applies the HasEdge predicate on the "charge" edge. +func HasCharge() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, 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.ChargeFlatFee { + return predicate.ChargeFlatFee(func(s *sql.Selector) { + step := newChargeStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasIntentOverride applies the HasEdge predicate on the "intent_override" edge. +func HasIntentOverride() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, IntentOverrideTable, IntentOverrideColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasIntentOverrideWith applies the HasEdge predicate on the "intent_override" edge with a given conditions (other predicates). +func HasIntentOverrideWith(preds ...predicate.ChargeFlatFeeOverride) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(func(s *sql.Selector) { + step := newIntentOverrideStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSubscription applies the HasEdge predicate on the "subscription" edge. +func HasSubscription() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionTable, SubscriptionColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubscriptionWith applies the HasEdge predicate on the "subscription" edge with a given conditions (other predicates). +func HasSubscriptionWith(preds ...predicate.Subscription) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(func(s *sql.Selector) { + step := newSubscriptionStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSubscriptionPhase applies the HasEdge predicate on the "subscription_phase" edge. +func HasSubscriptionPhase() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionPhaseTable, SubscriptionPhaseColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubscriptionPhaseWith applies the HasEdge predicate on the "subscription_phase" edge with a given conditions (other predicates). +func HasSubscriptionPhaseWith(preds ...predicate.SubscriptionPhase) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(func(s *sql.Selector) { + step := newSubscriptionPhaseStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSubscriptionItem applies the HasEdge predicate on the "subscription_item" edge. +func HasSubscriptionItem() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionItemTable, SubscriptionItemColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubscriptionItemWith applies the HasEdge predicate on the "subscription_item" edge with a given conditions (other predicates). +func HasSubscriptionItemWith(preds ...predicate.SubscriptionItem) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(func(s *sql.Selector) { + step := newSubscriptionItemStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasCustomer applies the HasEdge predicate on the "customer" edge. +func HasCustomer() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, CustomerTable, CustomerColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCustomerWith applies the HasEdge predicate on the "customer" edge with a given conditions (other predicates). +func HasCustomerWith(preds ...predicate.Customer) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(func(s *sql.Selector) { + step := newCustomerStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasFeature applies the HasEdge predicate on the "feature" edge. +func HasFeature() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, FeatureTable, FeatureColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasFeatureWith applies the HasEdge predicate on the "feature" edge with a given conditions (other predicates). +func HasFeatureWith(preds ...predicate.Feature) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(func(s *sql.Selector) { + step := newFeatureStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasTaxCode applies the HasEdge predicate on the "tax_code" edge. +func HasTaxCode() predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, TaxCodeTable, TaxCodeColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTaxCodeWith applies the HasEdge predicate on the "tax_code" edge with a given conditions (other predicates). +func HasTaxCodeWith(preds ...predicate.TaxCode) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(func(s *sql.Selector) { + step := newTaxCodeStep() + 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.ChargeFlatFee) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ChargeFlatFee) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ChargeFlatFee) predicate.ChargeFlatFee { + return predicate.ChargeFlatFee(sql.NotPredicates(p)) +} diff --git a/ent/db/chargeflatfee_create.go b/ent/db/chargeflatfee_create.go new file mode 100644 index 0000000000000000000000000000000000000000..0dc733fc47828b96180288e587328e5411fdc3a9 --- /dev/null +++ b/ent/db/chargeflatfee_create.go @@ -0,0 +1,2621 @@ +// 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" + "github.com/openmeterio/openmeter/openmeter/billing/charges/flatfee" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/ent/db/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeoverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/customer" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionphase" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeFlatFeeCreate is the builder for creating a ChargeFlatFee entity. +type ChargeFlatFeeCreate struct { + config + mutation *ChargeFlatFeeMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetCustomerID sets the "customer_id" field. +func (_c *ChargeFlatFeeCreate) SetCustomerID(v string) *ChargeFlatFeeCreate { + _c.mutation.SetCustomerID(v) + return _c +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_c *ChargeFlatFeeCreate) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeCreate { + _c.mutation.SetServicePeriodFrom(v) + return _c +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_c *ChargeFlatFeeCreate) SetServicePeriodTo(v time.Time) *ChargeFlatFeeCreate { + _c.mutation.SetServicePeriodTo(v) + return _c +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (_c *ChargeFlatFeeCreate) SetBillingPeriodFrom(v time.Time) *ChargeFlatFeeCreate { + _c.mutation.SetBillingPeriodFrom(v) + return _c +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (_c *ChargeFlatFeeCreate) SetBillingPeriodTo(v time.Time) *ChargeFlatFeeCreate { + _c.mutation.SetBillingPeriodTo(v) + return _c +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (_c *ChargeFlatFeeCreate) SetFullServicePeriodFrom(v time.Time) *ChargeFlatFeeCreate { + _c.mutation.SetFullServicePeriodFrom(v) + return _c +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (_c *ChargeFlatFeeCreate) SetFullServicePeriodTo(v time.Time) *ChargeFlatFeeCreate { + _c.mutation.SetFullServicePeriodTo(v) + return _c +} + +// SetStatus sets the "status" field. +func (_c *ChargeFlatFeeCreate) SetStatus(v meta.ChargeStatus) *ChargeFlatFeeCreate { + _c.mutation.SetStatus(v) + return _c +} + +// SetUniqueReferenceID sets the "unique_reference_id" field. +func (_c *ChargeFlatFeeCreate) SetUniqueReferenceID(v string) *ChargeFlatFeeCreate { + _c.mutation.SetUniqueReferenceID(v) + return _c +} + +// SetNillableUniqueReferenceID sets the "unique_reference_id" field if the given value is not nil. +func (_c *ChargeFlatFeeCreate) SetNillableUniqueReferenceID(v *string) *ChargeFlatFeeCreate { + if v != nil { + _c.SetUniqueReferenceID(*v) + } + return _c +} + +// SetCurrency sets the "currency" field. +func (_c *ChargeFlatFeeCreate) SetCurrency(v currencyx.Code) *ChargeFlatFeeCreate { + _c.mutation.SetCurrency(v) + return _c +} + +// SetManagedBy sets the "managed_by" field. +func (_c *ChargeFlatFeeCreate) SetManagedBy(v billing.InvoiceLineManagedBy) *ChargeFlatFeeCreate { + _c.mutation.SetManagedBy(v) + return _c +} + +// SetSubscriptionID sets the "subscription_id" field. +func (_c *ChargeFlatFeeCreate) SetSubscriptionID(v string) *ChargeFlatFeeCreate { + _c.mutation.SetSubscriptionID(v) + return _c +} + +// SetNillableSubscriptionID sets the "subscription_id" field if the given value is not nil. +func (_c *ChargeFlatFeeCreate) SetNillableSubscriptionID(v *string) *ChargeFlatFeeCreate { + if v != nil { + _c.SetSubscriptionID(*v) + } + return _c +} + +// SetSubscriptionPhaseID sets the "subscription_phase_id" field. +func (_c *ChargeFlatFeeCreate) SetSubscriptionPhaseID(v string) *ChargeFlatFeeCreate { + _c.mutation.SetSubscriptionPhaseID(v) + return _c +} + +// SetNillableSubscriptionPhaseID sets the "subscription_phase_id" field if the given value is not nil. +func (_c *ChargeFlatFeeCreate) SetNillableSubscriptionPhaseID(v *string) *ChargeFlatFeeCreate { + if v != nil { + _c.SetSubscriptionPhaseID(*v) + } + return _c +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (_c *ChargeFlatFeeCreate) SetSubscriptionItemID(v string) *ChargeFlatFeeCreate { + _c.mutation.SetSubscriptionItemID(v) + return _c +} + +// SetNillableSubscriptionItemID sets the "subscription_item_id" field if the given value is not nil. +func (_c *ChargeFlatFeeCreate) SetNillableSubscriptionItemID(v *string) *ChargeFlatFeeCreate { + if v != nil { + _c.SetSubscriptionItemID(*v) + } + return _c +} + +// SetAdvanceAfter sets the "advance_after" field. +func (_c *ChargeFlatFeeCreate) SetAdvanceAfter(v time.Time) *ChargeFlatFeeCreate { + _c.mutation.SetAdvanceAfter(v) + return _c +} + +// SetNillableAdvanceAfter sets the "advance_after" field if the given value is not nil. +func (_c *ChargeFlatFeeCreate) SetNillableAdvanceAfter(v *time.Time) *ChargeFlatFeeCreate { + if v != nil { + _c.SetAdvanceAfter(*v) + } + return _c +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (_c *ChargeFlatFeeCreate) SetTaxCodeID(v string) *ChargeFlatFeeCreate { + _c.mutation.SetTaxCodeID(v) + return _c +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (_c *ChargeFlatFeeCreate) SetTaxBehavior(v productcatalog.TaxBehavior) *ChargeFlatFeeCreate { + _c.mutation.SetTaxBehavior(v) + return _c +} + +// SetNillableTaxBehavior sets the "tax_behavior" field if the given value is not nil. +func (_c *ChargeFlatFeeCreate) SetNillableTaxBehavior(v *productcatalog.TaxBehavior) *ChargeFlatFeeCreate { + if v != nil { + _c.SetTaxBehavior(*v) + } + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *ChargeFlatFeeCreate) SetAnnotations(v models.Annotations) *ChargeFlatFeeCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetNamespace sets the "namespace" field. +func (_c *ChargeFlatFeeCreate) SetNamespace(v string) *ChargeFlatFeeCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetMetadata sets the "metadata" field. +func (_c *ChargeFlatFeeCreate) SetMetadata(v map[string]string) *ChargeFlatFeeCreate { + _c.mutation.SetMetadata(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ChargeFlatFeeCreate) SetCreatedAt(v time.Time) *ChargeFlatFeeCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *ChargeFlatFeeCreate) SetNillableCreatedAt(v *time.Time) *ChargeFlatFeeCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *ChargeFlatFeeCreate) SetUpdatedAt(v time.Time) *ChargeFlatFeeCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *ChargeFlatFeeCreate) SetNillableUpdatedAt(v *time.Time) *ChargeFlatFeeCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *ChargeFlatFeeCreate) SetDeletedAt(v time.Time) *ChargeFlatFeeCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *ChargeFlatFeeCreate) SetNillableDeletedAt(v *time.Time) *ChargeFlatFeeCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetName sets the "name" field. +func (_c *ChargeFlatFeeCreate) SetName(v string) *ChargeFlatFeeCreate { + _c.mutation.SetName(v) + return _c +} + +// SetDescription sets the "description" field. +func (_c *ChargeFlatFeeCreate) SetDescription(v string) *ChargeFlatFeeCreate { + _c.mutation.SetDescription(v) + return _c +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_c *ChargeFlatFeeCreate) SetNillableDescription(v *string) *ChargeFlatFeeCreate { + if v != nil { + _c.SetDescription(*v) + } + return _c +} + +// SetPaymentTerm sets the "payment_term" field. +func (_c *ChargeFlatFeeCreate) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeFlatFeeCreate { + _c.mutation.SetPaymentTerm(v) + return _c +} + +// SetInvoiceAt sets the "invoice_at" field. +func (_c *ChargeFlatFeeCreate) SetInvoiceAt(v time.Time) *ChargeFlatFeeCreate { + _c.mutation.SetInvoiceAt(v) + return _c +} + +// SetSettlementMode sets the "settlement_mode" field. +func (_c *ChargeFlatFeeCreate) SetSettlementMode(v productcatalog.SettlementMode) *ChargeFlatFeeCreate { + _c.mutation.SetSettlementMode(v) + return _c +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (_c *ChargeFlatFeeCreate) SetIntentDeletedAt(v time.Time) *ChargeFlatFeeCreate { + _c.mutation.SetIntentDeletedAt(v) + return _c +} + +// SetNillableIntentDeletedAt sets the "intent_deleted_at" field if the given value is not nil. +func (_c *ChargeFlatFeeCreate) SetNillableIntentDeletedAt(v *time.Time) *ChargeFlatFeeCreate { + if v != nil { + _c.SetIntentDeletedAt(*v) + } + return _c +} + +// SetDiscounts sets the "discounts" field. +func (_c *ChargeFlatFeeCreate) SetDiscounts(v *billing.Discounts) *ChargeFlatFeeCreate { + _c.mutation.SetDiscounts(v) + return _c +} + +// SetProRating sets the "pro_rating" field. +func (_c *ChargeFlatFeeCreate) SetProRating(v flatfee.ProRatingModeAdapterEnum) *ChargeFlatFeeCreate { + _c.mutation.SetProRating(v) + return _c +} + +// SetFeatureKey sets the "feature_key" field. +func (_c *ChargeFlatFeeCreate) SetFeatureKey(v string) *ChargeFlatFeeCreate { + _c.mutation.SetFeatureKey(v) + return _c +} + +// SetNillableFeatureKey sets the "feature_key" field if the given value is not nil. +func (_c *ChargeFlatFeeCreate) SetNillableFeatureKey(v *string) *ChargeFlatFeeCreate { + if v != nil { + _c.SetFeatureKey(*v) + } + return _c +} + +// SetFeatureID sets the "feature_id" field. +func (_c *ChargeFlatFeeCreate) SetFeatureID(v string) *ChargeFlatFeeCreate { + _c.mutation.SetFeatureID(v) + return _c +} + +// SetNillableFeatureID sets the "feature_id" field if the given value is not nil. +func (_c *ChargeFlatFeeCreate) SetNillableFeatureID(v *string) *ChargeFlatFeeCreate { + if v != nil { + _c.SetFeatureID(*v) + } + return _c +} + +// SetAmountBeforeProration sets the "amount_before_proration" field. +func (_c *ChargeFlatFeeCreate) SetAmountBeforeProration(v alpacadecimal.Decimal) *ChargeFlatFeeCreate { + _c.mutation.SetAmountBeforeProration(v) + return _c +} + +// SetAmountAfterProration sets the "amount_after_proration" field. +func (_c *ChargeFlatFeeCreate) SetAmountAfterProration(v alpacadecimal.Decimal) *ChargeFlatFeeCreate { + _c.mutation.SetAmountAfterProration(v) + return _c +} + +// SetCurrentRealizationRunID sets the "current_realization_run_id" field. +func (_c *ChargeFlatFeeCreate) SetCurrentRealizationRunID(v string) *ChargeFlatFeeCreate { + _c.mutation.SetCurrentRealizationRunID(v) + return _c +} + +// SetNillableCurrentRealizationRunID sets the "current_realization_run_id" field if the given value is not nil. +func (_c *ChargeFlatFeeCreate) SetNillableCurrentRealizationRunID(v *string) *ChargeFlatFeeCreate { + if v != nil { + _c.SetCurrentRealizationRunID(*v) + } + return _c +} + +// SetStatusDetailed sets the "status_detailed" field. +func (_c *ChargeFlatFeeCreate) SetStatusDetailed(v flatfee.Status) *ChargeFlatFeeCreate { + _c.mutation.SetStatusDetailed(v) + return _c +} + +// SetID sets the "id" field. +func (_c *ChargeFlatFeeCreate) SetID(v string) *ChargeFlatFeeCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ChargeFlatFeeCreate) SetNillableID(v *string) *ChargeFlatFeeCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// AddRunIDs adds the "runs" edge to the ChargeFlatFeeRun entity by IDs. +func (_c *ChargeFlatFeeCreate) AddRunIDs(ids ...string) *ChargeFlatFeeCreate { + _c.mutation.AddRunIDs(ids...) + return _c +} + +// AddRuns adds the "runs" edges to the ChargeFlatFeeRun entity. +func (_c *ChargeFlatFeeCreate) AddRuns(v ...*ChargeFlatFeeRun) *ChargeFlatFeeCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddRunIDs(ids...) +} + +// SetCurrentRunID sets the "current_run" edge to the ChargeFlatFeeRun entity by ID. +func (_c *ChargeFlatFeeCreate) SetCurrentRunID(id string) *ChargeFlatFeeCreate { + _c.mutation.SetCurrentRunID(id) + return _c +} + +// SetNillableCurrentRunID sets the "current_run" edge to the ChargeFlatFeeRun entity by ID if the given value is not nil. +func (_c *ChargeFlatFeeCreate) SetNillableCurrentRunID(id *string) *ChargeFlatFeeCreate { + if id != nil { + _c = _c.SetCurrentRunID(*id) + } + return _c +} + +// SetCurrentRun sets the "current_run" edge to the ChargeFlatFeeRun entity. +func (_c *ChargeFlatFeeCreate) SetCurrentRun(v *ChargeFlatFeeRun) *ChargeFlatFeeCreate { + return _c.SetCurrentRunID(v.ID) +} + +// SetChargeID sets the "charge" edge to the Charge entity by ID. +func (_c *ChargeFlatFeeCreate) SetChargeID(id string) *ChargeFlatFeeCreate { + _c.mutation.SetChargeID(id) + return _c +} + +// SetNillableChargeID sets the "charge" edge to the Charge entity by ID if the given value is not nil. +func (_c *ChargeFlatFeeCreate) SetNillableChargeID(id *string) *ChargeFlatFeeCreate { + if id != nil { + _c = _c.SetChargeID(*id) + } + return _c +} + +// SetCharge sets the "charge" edge to the Charge entity. +func (_c *ChargeFlatFeeCreate) SetCharge(v *Charge) *ChargeFlatFeeCreate { + return _c.SetChargeID(v.ID) +} + +// SetIntentOverrideID sets the "intent_override" edge to the ChargeFlatFeeOverride entity by ID. +func (_c *ChargeFlatFeeCreate) SetIntentOverrideID(id string) *ChargeFlatFeeCreate { + _c.mutation.SetIntentOverrideID(id) + return _c +} + +// SetNillableIntentOverrideID sets the "intent_override" edge to the ChargeFlatFeeOverride entity by ID if the given value is not nil. +func (_c *ChargeFlatFeeCreate) SetNillableIntentOverrideID(id *string) *ChargeFlatFeeCreate { + if id != nil { + _c = _c.SetIntentOverrideID(*id) + } + return _c +} + +// SetIntentOverride sets the "intent_override" edge to the ChargeFlatFeeOverride entity. +func (_c *ChargeFlatFeeCreate) SetIntentOverride(v *ChargeFlatFeeOverride) *ChargeFlatFeeCreate { + return _c.SetIntentOverrideID(v.ID) +} + +// SetSubscription sets the "subscription" edge to the Subscription entity. +func (_c *ChargeFlatFeeCreate) SetSubscription(v *Subscription) *ChargeFlatFeeCreate { + return _c.SetSubscriptionID(v.ID) +} + +// SetSubscriptionPhase sets the "subscription_phase" edge to the SubscriptionPhase entity. +func (_c *ChargeFlatFeeCreate) SetSubscriptionPhase(v *SubscriptionPhase) *ChargeFlatFeeCreate { + return _c.SetSubscriptionPhaseID(v.ID) +} + +// SetSubscriptionItem sets the "subscription_item" edge to the SubscriptionItem entity. +func (_c *ChargeFlatFeeCreate) SetSubscriptionItem(v *SubscriptionItem) *ChargeFlatFeeCreate { + return _c.SetSubscriptionItemID(v.ID) +} + +// SetCustomer sets the "customer" edge to the Customer entity. +func (_c *ChargeFlatFeeCreate) SetCustomer(v *Customer) *ChargeFlatFeeCreate { + return _c.SetCustomerID(v.ID) +} + +// SetFeature sets the "feature" edge to the Feature entity. +func (_c *ChargeFlatFeeCreate) SetFeature(v *Feature) *ChargeFlatFeeCreate { + return _c.SetFeatureID(v.ID) +} + +// SetTaxCode sets the "tax_code" edge to the TaxCode entity. +func (_c *ChargeFlatFeeCreate) SetTaxCode(v *TaxCode) *ChargeFlatFeeCreate { + return _c.SetTaxCodeID(v.ID) +} + +// Mutation returns the ChargeFlatFeeMutation object of the builder. +func (_c *ChargeFlatFeeCreate) Mutation() *ChargeFlatFeeMutation { + return _c.mutation +} + +// Save creates the ChargeFlatFee in the database. +func (_c *ChargeFlatFeeCreate) Save(ctx context.Context) (*ChargeFlatFee, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ChargeFlatFeeCreate) SaveX(ctx context.Context) *ChargeFlatFee { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeFlatFeeCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeFlatFeeCreate) 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 *ChargeFlatFeeCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := chargeflatfee.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := chargeflatfee.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := chargeflatfee.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ChargeFlatFeeCreate) check() error { + if _, ok := _c.mutation.CustomerID(); !ok { + return &ValidationError{Name: "customer_id", err: errors.New(`db: missing required field "ChargeFlatFee.customer_id"`)} + } + if v, ok := _c.mutation.CustomerID(); ok { + if err := chargeflatfee.CustomerIDValidator(v); err != nil { + return &ValidationError{Name: "customer_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFee.customer_id": %w`, err)} + } + } + if _, ok := _c.mutation.ServicePeriodFrom(); !ok { + return &ValidationError{Name: "service_period_from", err: errors.New(`db: missing required field "ChargeFlatFee.service_period_from"`)} + } + if _, ok := _c.mutation.ServicePeriodTo(); !ok { + return &ValidationError{Name: "service_period_to", err: errors.New(`db: missing required field "ChargeFlatFee.service_period_to"`)} + } + if _, ok := _c.mutation.BillingPeriodFrom(); !ok { + return &ValidationError{Name: "billing_period_from", err: errors.New(`db: missing required field "ChargeFlatFee.billing_period_from"`)} + } + if _, ok := _c.mutation.BillingPeriodTo(); !ok { + return &ValidationError{Name: "billing_period_to", err: errors.New(`db: missing required field "ChargeFlatFee.billing_period_to"`)} + } + if _, ok := _c.mutation.FullServicePeriodFrom(); !ok { + return &ValidationError{Name: "full_service_period_from", err: errors.New(`db: missing required field "ChargeFlatFee.full_service_period_from"`)} + } + if _, ok := _c.mutation.FullServicePeriodTo(); !ok { + return &ValidationError{Name: "full_service_period_to", err: errors.New(`db: missing required field "ChargeFlatFee.full_service_period_to"`)} + } + if _, ok := _c.mutation.Status(); !ok { + return &ValidationError{Name: "status", err: errors.New(`db: missing required field "ChargeFlatFee.status"`)} + } + if v, ok := _c.mutation.Status(); ok { + if err := chargeflatfee.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFee.status": %w`, err)} + } + } + if _, ok := _c.mutation.Currency(); !ok { + return &ValidationError{Name: "currency", err: errors.New(`db: missing required field "ChargeFlatFee.currency"`)} + } + if v, ok := _c.mutation.Currency(); ok { + if err := chargeflatfee.CurrencyValidator(string(v)); err != nil { + return &ValidationError{Name: "currency", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFee.currency": %w`, err)} + } + } + if _, ok := _c.mutation.ManagedBy(); !ok { + return &ValidationError{Name: "managed_by", err: errors.New(`db: missing required field "ChargeFlatFee.managed_by"`)} + } + if v, ok := _c.mutation.ManagedBy(); ok { + if err := chargeflatfee.ManagedByValidator(v); err != nil { + return &ValidationError{Name: "managed_by", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFee.managed_by": %w`, err)} + } + } + if _, ok := _c.mutation.TaxCodeID(); !ok { + return &ValidationError{Name: "tax_code_id", err: errors.New(`db: missing required field "ChargeFlatFee.tax_code_id"`)} + } + if v, ok := _c.mutation.TaxCodeID(); ok { + if err := chargeflatfee.TaxCodeIDValidator(v); err != nil { + return &ValidationError{Name: "tax_code_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFee.tax_code_id": %w`, err)} + } + } + if v, ok := _c.mutation.TaxBehavior(); ok { + if err := chargeflatfee.TaxBehaviorValidator(v); err != nil { + return &ValidationError{Name: "tax_behavior", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFee.tax_behavior": %w`, err)} + } + } + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "ChargeFlatFee.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := chargeflatfee.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFee.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "ChargeFlatFee.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "ChargeFlatFee.updated_at"`)} + } + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "ChargeFlatFee.name"`)} + } + if _, ok := _c.mutation.PaymentTerm(); !ok { + return &ValidationError{Name: "payment_term", err: errors.New(`db: missing required field "ChargeFlatFee.payment_term"`)} + } + if v, ok := _c.mutation.PaymentTerm(); ok { + if err := chargeflatfee.PaymentTermValidator(string(v)); err != nil { + return &ValidationError{Name: "payment_term", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFee.payment_term": %w`, err)} + } + } + if _, ok := _c.mutation.InvoiceAt(); !ok { + return &ValidationError{Name: "invoice_at", err: errors.New(`db: missing required field "ChargeFlatFee.invoice_at"`)} + } + if _, ok := _c.mutation.SettlementMode(); !ok { + return &ValidationError{Name: "settlement_mode", err: errors.New(`db: missing required field "ChargeFlatFee.settlement_mode"`)} + } + if v, ok := _c.mutation.SettlementMode(); ok { + if err := chargeflatfee.SettlementModeValidator(v); err != nil { + return &ValidationError{Name: "settlement_mode", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFee.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 "ChargeFlatFee.discounts": %w`, err)} + } + } + if _, ok := _c.mutation.ProRating(); !ok { + return &ValidationError{Name: "pro_rating", err: errors.New(`db: missing required field "ChargeFlatFee.pro_rating"`)} + } + if v, ok := _c.mutation.ProRating(); ok { + if err := chargeflatfee.ProRatingValidator(v); err != nil { + return &ValidationError{Name: "pro_rating", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFee.pro_rating": %w`, err)} + } + } + if v, ok := _c.mutation.FeatureKey(); ok { + if err := chargeflatfee.FeatureKeyValidator(v); err != nil { + return &ValidationError{Name: "feature_key", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFee.feature_key": %w`, err)} + } + } + if _, ok := _c.mutation.AmountBeforeProration(); !ok { + return &ValidationError{Name: "amount_before_proration", err: errors.New(`db: missing required field "ChargeFlatFee.amount_before_proration"`)} + } + if _, ok := _c.mutation.AmountAfterProration(); !ok { + return &ValidationError{Name: "amount_after_proration", err: errors.New(`db: missing required field "ChargeFlatFee.amount_after_proration"`)} + } + if _, ok := _c.mutation.StatusDetailed(); !ok { + return &ValidationError{Name: "status_detailed", err: errors.New(`db: missing required field "ChargeFlatFee.status_detailed"`)} + } + if v, ok := _c.mutation.StatusDetailed(); ok { + if err := chargeflatfee.StatusDetailedValidator(v); err != nil { + return &ValidationError{Name: "status_detailed", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFee.status_detailed": %w`, err)} + } + } + if len(_c.mutation.CustomerIDs()) == 0 { + return &ValidationError{Name: "customer", err: errors.New(`db: missing required edge "ChargeFlatFee.customer"`)} + } + if len(_c.mutation.TaxCodeIDs()) == 0 { + return &ValidationError{Name: "tax_code", err: errors.New(`db: missing required edge "ChargeFlatFee.tax_code"`)} + } + return nil +} + +func (_c *ChargeFlatFeeCreate) sqlSave(ctx context.Context) (*ChargeFlatFee, 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 ChargeFlatFee.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ChargeFlatFeeCreate) createSpec() (*ChargeFlatFee, *sqlgraph.CreateSpec, error) { + var ( + _node = &ChargeFlatFee{config: _c.config} + _spec = sqlgraph.NewCreateSpec(chargeflatfee.Table, sqlgraph.NewFieldSpec(chargeflatfee.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.ServicePeriodFrom(); ok { + _spec.SetField(chargeflatfee.FieldServicePeriodFrom, field.TypeTime, value) + _node.ServicePeriodFrom = value + } + if value, ok := _c.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeflatfee.FieldServicePeriodTo, field.TypeTime, value) + _node.ServicePeriodTo = value + } + if value, ok := _c.mutation.BillingPeriodFrom(); ok { + _spec.SetField(chargeflatfee.FieldBillingPeriodFrom, field.TypeTime, value) + _node.BillingPeriodFrom = value + } + if value, ok := _c.mutation.BillingPeriodTo(); ok { + _spec.SetField(chargeflatfee.FieldBillingPeriodTo, field.TypeTime, value) + _node.BillingPeriodTo = value + } + if value, ok := _c.mutation.FullServicePeriodFrom(); ok { + _spec.SetField(chargeflatfee.FieldFullServicePeriodFrom, field.TypeTime, value) + _node.FullServicePeriodFrom = value + } + if value, ok := _c.mutation.FullServicePeriodTo(); ok { + _spec.SetField(chargeflatfee.FieldFullServicePeriodTo, field.TypeTime, value) + _node.FullServicePeriodTo = value + } + if value, ok := _c.mutation.Status(); ok { + _spec.SetField(chargeflatfee.FieldStatus, field.TypeEnum, value) + _node.Status = value + } + if value, ok := _c.mutation.UniqueReferenceID(); ok { + _spec.SetField(chargeflatfee.FieldUniqueReferenceID, field.TypeString, value) + _node.UniqueReferenceID = &value + } + if value, ok := _c.mutation.Currency(); ok { + _spec.SetField(chargeflatfee.FieldCurrency, field.TypeString, value) + _node.Currency = value + } + if value, ok := _c.mutation.ManagedBy(); ok { + _spec.SetField(chargeflatfee.FieldManagedBy, field.TypeEnum, value) + _node.ManagedBy = value + } + if value, ok := _c.mutation.AdvanceAfter(); ok { + _spec.SetField(chargeflatfee.FieldAdvanceAfter, field.TypeTime, value) + _node.AdvanceAfter = &value + } + if value, ok := _c.mutation.TaxBehavior(); ok { + _spec.SetField(chargeflatfee.FieldTaxBehavior, field.TypeEnum, value) + _node.TaxBehavior = &value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(chargeflatfee.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(chargeflatfee.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Metadata(); ok { + _spec.SetField(chargeflatfee.FieldMetadata, field.TypeJSON, value) + _node.Metadata = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(chargeflatfee.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(chargeflatfee.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(chargeflatfee.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(chargeflatfee.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Description(); ok { + _spec.SetField(chargeflatfee.FieldDescription, field.TypeString, value) + _node.Description = &value + } + if value, ok := _c.mutation.PaymentTerm(); ok { + _spec.SetField(chargeflatfee.FieldPaymentTerm, field.TypeString, value) + _node.PaymentTerm = value + } + if value, ok := _c.mutation.InvoiceAt(); ok { + _spec.SetField(chargeflatfee.FieldInvoiceAt, field.TypeTime, value) + _node.InvoiceAt = value + } + if value, ok := _c.mutation.SettlementMode(); ok { + _spec.SetField(chargeflatfee.FieldSettlementMode, field.TypeEnum, value) + _node.SettlementMode = value + } + if value, ok := _c.mutation.IntentDeletedAt(); ok { + _spec.SetField(chargeflatfee.FieldIntentDeletedAt, field.TypeTime, value) + _node.IntentDeletedAt = &value + } + if value, ok := _c.mutation.Discounts(); ok { + vv, err := chargeflatfee.ValueScanner.Discounts.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(chargeflatfee.FieldDiscounts, field.TypeString, vv) + _node.Discounts = value + } + if value, ok := _c.mutation.ProRating(); ok { + _spec.SetField(chargeflatfee.FieldProRating, field.TypeEnum, value) + _node.ProRating = value + } + if value, ok := _c.mutation.FeatureKey(); ok { + _spec.SetField(chargeflatfee.FieldFeatureKey, field.TypeString, value) + _node.FeatureKey = &value + } + if value, ok := _c.mutation.AmountBeforeProration(); ok { + _spec.SetField(chargeflatfee.FieldAmountBeforeProration, field.TypeOther, value) + _node.AmountBeforeProration = value + } + if value, ok := _c.mutation.AmountAfterProration(); ok { + _spec.SetField(chargeflatfee.FieldAmountAfterProration, field.TypeOther, value) + _node.AmountAfterProration = value + } + if value, ok := _c.mutation.StatusDetailed(); ok { + _spec.SetField(chargeflatfee.FieldStatusDetailed, field.TypeEnum, value) + _node.StatusDetailed = value + } + if nodes := _c.mutation.RunsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeflatfee.RunsTable, + Columns: []string{chargeflatfee.RunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerun.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.CurrentRunIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: chargeflatfee.CurrentRunTable, + Columns: []string{chargeflatfee.CurrentRunColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerun.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.CurrentRealizationRunID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.ChargeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeflatfee.ChargeTable, + Columns: []string{chargeflatfee.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 = append(_spec.Edges, edge) + } + if nodes := _c.mutation.IntentOverrideIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeflatfee.IntentOverrideTable, + Columns: []string{chargeflatfee.IntentOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeoverride.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.SubscriptionIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfee.SubscriptionTable, + Columns: []string{chargeflatfee.SubscriptionColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscription.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.SubscriptionID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.SubscriptionPhaseIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfee.SubscriptionPhaseTable, + Columns: []string{chargeflatfee.SubscriptionPhaseColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionphase.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.SubscriptionPhaseID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.SubscriptionItemIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfee.SubscriptionItemTable, + Columns: []string{chargeflatfee.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.SubscriptionItemID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.CustomerIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfee.CustomerTable, + Columns: []string{chargeflatfee.CustomerColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(customer.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.CustomerID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.FeatureIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfee.FeatureTable, + Columns: []string{chargeflatfee.FeatureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbfeature.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.FeatureID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.TaxCodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfee.TaxCodeTable, + Columns: []string{chargeflatfee.TaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.TaxCodeID = nodes[0] + _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.ChargeFlatFee.Create(). +// SetCustomerID(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.ChargeFlatFeeUpsert) { +// SetCustomerID(v+v). +// }). +// Exec(ctx) +func (_c *ChargeFlatFeeCreate) OnConflict(opts ...sql.ConflictOption) *ChargeFlatFeeUpsertOne { + _c.conflict = opts + return &ChargeFlatFeeUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeFlatFee.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeFlatFeeCreate) OnConflictColumns(columns ...string) *ChargeFlatFeeUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeFlatFeeUpsertOne{ + create: _c, + } +} + +type ( + // ChargeFlatFeeUpsertOne is the builder for "upsert"-ing + // one ChargeFlatFee node. + ChargeFlatFeeUpsertOne struct { + create *ChargeFlatFeeCreate + } + + // ChargeFlatFeeUpsert is the "OnConflict" setter. + ChargeFlatFeeUpsert struct { + *sql.UpdateSet + } +) + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeFlatFeeUpsert) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldServicePeriodFrom, v) + return u +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateServicePeriodFrom() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldServicePeriodFrom) + return u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeFlatFeeUpsert) SetServicePeriodTo(v time.Time) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldServicePeriodTo, v) + return u +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateServicePeriodTo() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldServicePeriodTo) + return u +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (u *ChargeFlatFeeUpsert) SetBillingPeriodFrom(v time.Time) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldBillingPeriodFrom, v) + return u +} + +// UpdateBillingPeriodFrom sets the "billing_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateBillingPeriodFrom() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldBillingPeriodFrom) + return u +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (u *ChargeFlatFeeUpsert) SetBillingPeriodTo(v time.Time) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldBillingPeriodTo, v) + return u +} + +// UpdateBillingPeriodTo sets the "billing_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateBillingPeriodTo() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldBillingPeriodTo) + return u +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (u *ChargeFlatFeeUpsert) SetFullServicePeriodFrom(v time.Time) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldFullServicePeriodFrom, v) + return u +} + +// UpdateFullServicePeriodFrom sets the "full_service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateFullServicePeriodFrom() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldFullServicePeriodFrom) + return u +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (u *ChargeFlatFeeUpsert) SetFullServicePeriodTo(v time.Time) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldFullServicePeriodTo, v) + return u +} + +// UpdateFullServicePeriodTo sets the "full_service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateFullServicePeriodTo() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldFullServicePeriodTo) + return u +} + +// SetStatus sets the "status" field. +func (u *ChargeFlatFeeUpsert) SetStatus(v meta.ChargeStatus) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldStatus, v) + return u +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateStatus() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldStatus) + return u +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (u *ChargeFlatFeeUpsert) SetSubscriptionItemID(v string) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldSubscriptionItemID, v) + return u +} + +// UpdateSubscriptionItemID sets the "subscription_item_id" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateSubscriptionItemID() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldSubscriptionItemID) + return u +} + +// ClearSubscriptionItemID clears the value of the "subscription_item_id" field. +func (u *ChargeFlatFeeUpsert) ClearSubscriptionItemID() *ChargeFlatFeeUpsert { + u.SetNull(chargeflatfee.FieldSubscriptionItemID) + return u +} + +// SetAdvanceAfter sets the "advance_after" field. +func (u *ChargeFlatFeeUpsert) SetAdvanceAfter(v time.Time) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldAdvanceAfter, v) + return u +} + +// UpdateAdvanceAfter sets the "advance_after" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateAdvanceAfter() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldAdvanceAfter) + return u +} + +// ClearAdvanceAfter clears the value of the "advance_after" field. +func (u *ChargeFlatFeeUpsert) ClearAdvanceAfter() *ChargeFlatFeeUpsert { + u.SetNull(chargeflatfee.FieldAdvanceAfter) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeFlatFeeUpsert) SetAnnotations(v models.Annotations) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateAnnotations() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeFlatFeeUpsert) ClearAnnotations() *ChargeFlatFeeUpsert { + u.SetNull(chargeflatfee.FieldAnnotations) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeFlatFeeUpsert) SetMetadata(v map[string]string) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldMetadata, v) + return u +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateMetadata() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldMetadata) + return u +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeFlatFeeUpsert) ClearMetadata() *ChargeFlatFeeUpsert { + u.SetNull(chargeflatfee.FieldMetadata) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeFlatFeeUpsert) SetUpdatedAt(v time.Time) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateUpdatedAt() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeFlatFeeUpsert) SetDeletedAt(v time.Time) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateDeletedAt() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeFlatFeeUpsert) ClearDeletedAt() *ChargeFlatFeeUpsert { + u.SetNull(chargeflatfee.FieldDeletedAt) + return u +} + +// SetName sets the "name" field. +func (u *ChargeFlatFeeUpsert) SetName(v string) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateName() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldName) + return u +} + +// SetDescription sets the "description" field. +func (u *ChargeFlatFeeUpsert) SetDescription(v string) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldDescription, v) + return u +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateDescription() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldDescription) + return u +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeFlatFeeUpsert) ClearDescription() *ChargeFlatFeeUpsert { + u.SetNull(chargeflatfee.FieldDescription) + return u +} + +// SetPaymentTerm sets the "payment_term" field. +func (u *ChargeFlatFeeUpsert) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldPaymentTerm, v) + return u +} + +// UpdatePaymentTerm sets the "payment_term" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdatePaymentTerm() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldPaymentTerm) + return u +} + +// SetInvoiceAt sets the "invoice_at" field. +func (u *ChargeFlatFeeUpsert) SetInvoiceAt(v time.Time) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldInvoiceAt, v) + return u +} + +// UpdateInvoiceAt sets the "invoice_at" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateInvoiceAt() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldInvoiceAt) + return u +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (u *ChargeFlatFeeUpsert) SetIntentDeletedAt(v time.Time) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldIntentDeletedAt, v) + return u +} + +// UpdateIntentDeletedAt sets the "intent_deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateIntentDeletedAt() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldIntentDeletedAt) + return u +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (u *ChargeFlatFeeUpsert) ClearIntentDeletedAt() *ChargeFlatFeeUpsert { + u.SetNull(chargeflatfee.FieldIntentDeletedAt) + return u +} + +// SetDiscounts sets the "discounts" field. +func (u *ChargeFlatFeeUpsert) SetDiscounts(v *billing.Discounts) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldDiscounts, v) + return u +} + +// UpdateDiscounts sets the "discounts" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateDiscounts() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldDiscounts) + return u +} + +// ClearDiscounts clears the value of the "discounts" field. +func (u *ChargeFlatFeeUpsert) ClearDiscounts() *ChargeFlatFeeUpsert { + u.SetNull(chargeflatfee.FieldDiscounts) + return u +} + +// SetProRating sets the "pro_rating" field. +func (u *ChargeFlatFeeUpsert) SetProRating(v flatfee.ProRatingModeAdapterEnum) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldProRating, v) + return u +} + +// UpdateProRating sets the "pro_rating" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateProRating() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldProRating) + return u +} + +// SetFeatureID sets the "feature_id" field. +func (u *ChargeFlatFeeUpsert) SetFeatureID(v string) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldFeatureID, v) + return u +} + +// UpdateFeatureID sets the "feature_id" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateFeatureID() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldFeatureID) + return u +} + +// ClearFeatureID clears the value of the "feature_id" field. +func (u *ChargeFlatFeeUpsert) ClearFeatureID() *ChargeFlatFeeUpsert { + u.SetNull(chargeflatfee.FieldFeatureID) + return u +} + +// SetAmountBeforeProration sets the "amount_before_proration" field. +func (u *ChargeFlatFeeUpsert) SetAmountBeforeProration(v alpacadecimal.Decimal) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldAmountBeforeProration, v) + return u +} + +// UpdateAmountBeforeProration sets the "amount_before_proration" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateAmountBeforeProration() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldAmountBeforeProration) + return u +} + +// SetAmountAfterProration sets the "amount_after_proration" field. +func (u *ChargeFlatFeeUpsert) SetAmountAfterProration(v alpacadecimal.Decimal) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldAmountAfterProration, v) + return u +} + +// UpdateAmountAfterProration sets the "amount_after_proration" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateAmountAfterProration() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldAmountAfterProration) + return u +} + +// SetCurrentRealizationRunID sets the "current_realization_run_id" field. +func (u *ChargeFlatFeeUpsert) SetCurrentRealizationRunID(v string) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldCurrentRealizationRunID, v) + return u +} + +// UpdateCurrentRealizationRunID sets the "current_realization_run_id" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateCurrentRealizationRunID() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldCurrentRealizationRunID) + return u +} + +// ClearCurrentRealizationRunID clears the value of the "current_realization_run_id" field. +func (u *ChargeFlatFeeUpsert) ClearCurrentRealizationRunID() *ChargeFlatFeeUpsert { + u.SetNull(chargeflatfee.FieldCurrentRealizationRunID) + return u +} + +// SetStatusDetailed sets the "status_detailed" field. +func (u *ChargeFlatFeeUpsert) SetStatusDetailed(v flatfee.Status) *ChargeFlatFeeUpsert { + u.Set(chargeflatfee.FieldStatusDetailed, v) + return u +} + +// UpdateStatusDetailed sets the "status_detailed" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsert) UpdateStatusDetailed() *ChargeFlatFeeUpsert { + u.SetExcluded(chargeflatfee.FieldStatusDetailed) + 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.ChargeFlatFee.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeflatfee.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeFlatFeeUpsertOne) UpdateNewValues() *ChargeFlatFeeUpsertOne { + 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(chargeflatfee.FieldID) + } + if _, exists := u.create.mutation.CustomerID(); exists { + s.SetIgnore(chargeflatfee.FieldCustomerID) + } + if _, exists := u.create.mutation.UniqueReferenceID(); exists { + s.SetIgnore(chargeflatfee.FieldUniqueReferenceID) + } + if _, exists := u.create.mutation.Currency(); exists { + s.SetIgnore(chargeflatfee.FieldCurrency) + } + if _, exists := u.create.mutation.ManagedBy(); exists { + s.SetIgnore(chargeflatfee.FieldManagedBy) + } + if _, exists := u.create.mutation.SubscriptionID(); exists { + s.SetIgnore(chargeflatfee.FieldSubscriptionID) + } + if _, exists := u.create.mutation.SubscriptionPhaseID(); exists { + s.SetIgnore(chargeflatfee.FieldSubscriptionPhaseID) + } + if _, exists := u.create.mutation.TaxCodeID(); exists { + s.SetIgnore(chargeflatfee.FieldTaxCodeID) + } + if _, exists := u.create.mutation.TaxBehavior(); exists { + s.SetIgnore(chargeflatfee.FieldTaxBehavior) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(chargeflatfee.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(chargeflatfee.FieldCreatedAt) + } + if _, exists := u.create.mutation.SettlementMode(); exists { + s.SetIgnore(chargeflatfee.FieldSettlementMode) + } + if _, exists := u.create.mutation.FeatureKey(); exists { + s.SetIgnore(chargeflatfee.FieldFeatureKey) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeFlatFee.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeFlatFeeUpsertOne) Ignore() *ChargeFlatFeeUpsertOne { + 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 *ChargeFlatFeeUpsertOne) DoNothing() *ChargeFlatFeeUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeFlatFeeCreate.OnConflict +// documentation for more info. +func (u *ChargeFlatFeeUpsertOne) Update(set func(*ChargeFlatFeeUpsert)) *ChargeFlatFeeUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeFlatFeeUpsert{UpdateSet: update}) + })) + return u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeFlatFeeUpsertOne) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateServicePeriodFrom() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeFlatFeeUpsertOne) SetServicePeriodTo(v time.Time) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateServicePeriodTo() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (u *ChargeFlatFeeUpsertOne) SetBillingPeriodFrom(v time.Time) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetBillingPeriodFrom(v) + }) +} + +// UpdateBillingPeriodFrom sets the "billing_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateBillingPeriodFrom() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateBillingPeriodFrom() + }) +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (u *ChargeFlatFeeUpsertOne) SetBillingPeriodTo(v time.Time) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetBillingPeriodTo(v) + }) +} + +// UpdateBillingPeriodTo sets the "billing_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateBillingPeriodTo() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateBillingPeriodTo() + }) +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (u *ChargeFlatFeeUpsertOne) SetFullServicePeriodFrom(v time.Time) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetFullServicePeriodFrom(v) + }) +} + +// UpdateFullServicePeriodFrom sets the "full_service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateFullServicePeriodFrom() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateFullServicePeriodFrom() + }) +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (u *ChargeFlatFeeUpsertOne) SetFullServicePeriodTo(v time.Time) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetFullServicePeriodTo(v) + }) +} + +// UpdateFullServicePeriodTo sets the "full_service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateFullServicePeriodTo() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateFullServicePeriodTo() + }) +} + +// SetStatus sets the "status" field. +func (u *ChargeFlatFeeUpsertOne) SetStatus(v meta.ChargeStatus) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateStatus() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateStatus() + }) +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (u *ChargeFlatFeeUpsertOne) SetSubscriptionItemID(v string) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetSubscriptionItemID(v) + }) +} + +// UpdateSubscriptionItemID sets the "subscription_item_id" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateSubscriptionItemID() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateSubscriptionItemID() + }) +} + +// ClearSubscriptionItemID clears the value of the "subscription_item_id" field. +func (u *ChargeFlatFeeUpsertOne) ClearSubscriptionItemID() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.ClearSubscriptionItemID() + }) +} + +// SetAdvanceAfter sets the "advance_after" field. +func (u *ChargeFlatFeeUpsertOne) SetAdvanceAfter(v time.Time) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetAdvanceAfter(v) + }) +} + +// UpdateAdvanceAfter sets the "advance_after" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateAdvanceAfter() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateAdvanceAfter() + }) +} + +// ClearAdvanceAfter clears the value of the "advance_after" field. +func (u *ChargeFlatFeeUpsertOne) ClearAdvanceAfter() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.ClearAdvanceAfter() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeFlatFeeUpsertOne) SetAnnotations(v models.Annotations) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateAnnotations() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeFlatFeeUpsertOne) ClearAnnotations() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.ClearAnnotations() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeFlatFeeUpsertOne) SetMetadata(v map[string]string) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateMetadata() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeFlatFeeUpsertOne) ClearMetadata() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeFlatFeeUpsertOne) SetUpdatedAt(v time.Time) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateUpdatedAt() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeFlatFeeUpsertOne) SetDeletedAt(v time.Time) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateDeletedAt() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeFlatFeeUpsertOne) ClearDeletedAt() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *ChargeFlatFeeUpsertOne) SetName(v string) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateName() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *ChargeFlatFeeUpsertOne) SetDescription(v string) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateDescription() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeFlatFeeUpsertOne) ClearDescription() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.ClearDescription() + }) +} + +// SetPaymentTerm sets the "payment_term" field. +func (u *ChargeFlatFeeUpsertOne) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetPaymentTerm(v) + }) +} + +// UpdatePaymentTerm sets the "payment_term" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdatePaymentTerm() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdatePaymentTerm() + }) +} + +// SetInvoiceAt sets the "invoice_at" field. +func (u *ChargeFlatFeeUpsertOne) SetInvoiceAt(v time.Time) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetInvoiceAt(v) + }) +} + +// UpdateInvoiceAt sets the "invoice_at" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateInvoiceAt() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateInvoiceAt() + }) +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (u *ChargeFlatFeeUpsertOne) SetIntentDeletedAt(v time.Time) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetIntentDeletedAt(v) + }) +} + +// UpdateIntentDeletedAt sets the "intent_deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateIntentDeletedAt() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateIntentDeletedAt() + }) +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (u *ChargeFlatFeeUpsertOne) ClearIntentDeletedAt() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.ClearIntentDeletedAt() + }) +} + +// SetDiscounts sets the "discounts" field. +func (u *ChargeFlatFeeUpsertOne) SetDiscounts(v *billing.Discounts) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetDiscounts(v) + }) +} + +// UpdateDiscounts sets the "discounts" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateDiscounts() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateDiscounts() + }) +} + +// ClearDiscounts clears the value of the "discounts" field. +func (u *ChargeFlatFeeUpsertOne) ClearDiscounts() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.ClearDiscounts() + }) +} + +// SetProRating sets the "pro_rating" field. +func (u *ChargeFlatFeeUpsertOne) SetProRating(v flatfee.ProRatingModeAdapterEnum) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetProRating(v) + }) +} + +// UpdateProRating sets the "pro_rating" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateProRating() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateProRating() + }) +} + +// SetFeatureID sets the "feature_id" field. +func (u *ChargeFlatFeeUpsertOne) SetFeatureID(v string) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetFeatureID(v) + }) +} + +// UpdateFeatureID sets the "feature_id" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateFeatureID() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateFeatureID() + }) +} + +// ClearFeatureID clears the value of the "feature_id" field. +func (u *ChargeFlatFeeUpsertOne) ClearFeatureID() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.ClearFeatureID() + }) +} + +// SetAmountBeforeProration sets the "amount_before_proration" field. +func (u *ChargeFlatFeeUpsertOne) SetAmountBeforeProration(v alpacadecimal.Decimal) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetAmountBeforeProration(v) + }) +} + +// UpdateAmountBeforeProration sets the "amount_before_proration" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateAmountBeforeProration() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateAmountBeforeProration() + }) +} + +// SetAmountAfterProration sets the "amount_after_proration" field. +func (u *ChargeFlatFeeUpsertOne) SetAmountAfterProration(v alpacadecimal.Decimal) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetAmountAfterProration(v) + }) +} + +// UpdateAmountAfterProration sets the "amount_after_proration" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateAmountAfterProration() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateAmountAfterProration() + }) +} + +// SetCurrentRealizationRunID sets the "current_realization_run_id" field. +func (u *ChargeFlatFeeUpsertOne) SetCurrentRealizationRunID(v string) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetCurrentRealizationRunID(v) + }) +} + +// UpdateCurrentRealizationRunID sets the "current_realization_run_id" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateCurrentRealizationRunID() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateCurrentRealizationRunID() + }) +} + +// ClearCurrentRealizationRunID clears the value of the "current_realization_run_id" field. +func (u *ChargeFlatFeeUpsertOne) ClearCurrentRealizationRunID() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.ClearCurrentRealizationRunID() + }) +} + +// SetStatusDetailed sets the "status_detailed" field. +func (u *ChargeFlatFeeUpsertOne) SetStatusDetailed(v flatfee.Status) *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetStatusDetailed(v) + }) +} + +// UpdateStatusDetailed sets the "status_detailed" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertOne) UpdateStatusDetailed() *ChargeFlatFeeUpsertOne { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateStatusDetailed() + }) +} + +// Exec executes the query. +func (u *ChargeFlatFeeUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeFlatFeeCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeFlatFeeUpsertOne) 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 *ChargeFlatFeeUpsertOne) 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: ChargeFlatFeeUpsertOne.ID is not supported by MySQL driver. Use ChargeFlatFeeUpsertOne.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 *ChargeFlatFeeUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ChargeFlatFeeCreateBulk is the builder for creating many ChargeFlatFee entities in bulk. +type ChargeFlatFeeCreateBulk struct { + config + err error + builders []*ChargeFlatFeeCreate + conflict []sql.ConflictOption +} + +// Save creates the ChargeFlatFee entities in the database. +func (_c *ChargeFlatFeeCreateBulk) Save(ctx context.Context) ([]*ChargeFlatFee, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ChargeFlatFee, 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.(*ChargeFlatFeeMutation) + 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 *ChargeFlatFeeCreateBulk) SaveX(ctx context.Context) []*ChargeFlatFee { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeFlatFeeCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeFlatFeeCreateBulk) 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.ChargeFlatFee.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.ChargeFlatFeeUpsert) { +// SetCustomerID(v+v). +// }). +// Exec(ctx) +func (_c *ChargeFlatFeeCreateBulk) OnConflict(opts ...sql.ConflictOption) *ChargeFlatFeeUpsertBulk { + _c.conflict = opts + return &ChargeFlatFeeUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeFlatFee.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeFlatFeeCreateBulk) OnConflictColumns(columns ...string) *ChargeFlatFeeUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeFlatFeeUpsertBulk{ + create: _c, + } +} + +// ChargeFlatFeeUpsertBulk is the builder for "upsert"-ing +// a bulk of ChargeFlatFee nodes. +type ChargeFlatFeeUpsertBulk struct { + create *ChargeFlatFeeCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ChargeFlatFee.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeflatfee.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeFlatFeeUpsertBulk) UpdateNewValues() *ChargeFlatFeeUpsertBulk { + 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(chargeflatfee.FieldID) + } + if _, exists := b.mutation.CustomerID(); exists { + s.SetIgnore(chargeflatfee.FieldCustomerID) + } + if _, exists := b.mutation.UniqueReferenceID(); exists { + s.SetIgnore(chargeflatfee.FieldUniqueReferenceID) + } + if _, exists := b.mutation.Currency(); exists { + s.SetIgnore(chargeflatfee.FieldCurrency) + } + if _, exists := b.mutation.ManagedBy(); exists { + s.SetIgnore(chargeflatfee.FieldManagedBy) + } + if _, exists := b.mutation.SubscriptionID(); exists { + s.SetIgnore(chargeflatfee.FieldSubscriptionID) + } + if _, exists := b.mutation.SubscriptionPhaseID(); exists { + s.SetIgnore(chargeflatfee.FieldSubscriptionPhaseID) + } + if _, exists := b.mutation.TaxCodeID(); exists { + s.SetIgnore(chargeflatfee.FieldTaxCodeID) + } + if _, exists := b.mutation.TaxBehavior(); exists { + s.SetIgnore(chargeflatfee.FieldTaxBehavior) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(chargeflatfee.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(chargeflatfee.FieldCreatedAt) + } + if _, exists := b.mutation.SettlementMode(); exists { + s.SetIgnore(chargeflatfee.FieldSettlementMode) + } + if _, exists := b.mutation.FeatureKey(); exists { + s.SetIgnore(chargeflatfee.FieldFeatureKey) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeFlatFee.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeFlatFeeUpsertBulk) Ignore() *ChargeFlatFeeUpsertBulk { + 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 *ChargeFlatFeeUpsertBulk) DoNothing() *ChargeFlatFeeUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeFlatFeeCreateBulk.OnConflict +// documentation for more info. +func (u *ChargeFlatFeeUpsertBulk) Update(set func(*ChargeFlatFeeUpsert)) *ChargeFlatFeeUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeFlatFeeUpsert{UpdateSet: update}) + })) + return u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeFlatFeeUpsertBulk) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateServicePeriodFrom() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeFlatFeeUpsertBulk) SetServicePeriodTo(v time.Time) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateServicePeriodTo() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (u *ChargeFlatFeeUpsertBulk) SetBillingPeriodFrom(v time.Time) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetBillingPeriodFrom(v) + }) +} + +// UpdateBillingPeriodFrom sets the "billing_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateBillingPeriodFrom() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateBillingPeriodFrom() + }) +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (u *ChargeFlatFeeUpsertBulk) SetBillingPeriodTo(v time.Time) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetBillingPeriodTo(v) + }) +} + +// UpdateBillingPeriodTo sets the "billing_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateBillingPeriodTo() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateBillingPeriodTo() + }) +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (u *ChargeFlatFeeUpsertBulk) SetFullServicePeriodFrom(v time.Time) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetFullServicePeriodFrom(v) + }) +} + +// UpdateFullServicePeriodFrom sets the "full_service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateFullServicePeriodFrom() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateFullServicePeriodFrom() + }) +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (u *ChargeFlatFeeUpsertBulk) SetFullServicePeriodTo(v time.Time) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetFullServicePeriodTo(v) + }) +} + +// UpdateFullServicePeriodTo sets the "full_service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateFullServicePeriodTo() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateFullServicePeriodTo() + }) +} + +// SetStatus sets the "status" field. +func (u *ChargeFlatFeeUpsertBulk) SetStatus(v meta.ChargeStatus) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateStatus() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateStatus() + }) +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (u *ChargeFlatFeeUpsertBulk) SetSubscriptionItemID(v string) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetSubscriptionItemID(v) + }) +} + +// UpdateSubscriptionItemID sets the "subscription_item_id" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateSubscriptionItemID() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateSubscriptionItemID() + }) +} + +// ClearSubscriptionItemID clears the value of the "subscription_item_id" field. +func (u *ChargeFlatFeeUpsertBulk) ClearSubscriptionItemID() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.ClearSubscriptionItemID() + }) +} + +// SetAdvanceAfter sets the "advance_after" field. +func (u *ChargeFlatFeeUpsertBulk) SetAdvanceAfter(v time.Time) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetAdvanceAfter(v) + }) +} + +// UpdateAdvanceAfter sets the "advance_after" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateAdvanceAfter() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateAdvanceAfter() + }) +} + +// ClearAdvanceAfter clears the value of the "advance_after" field. +func (u *ChargeFlatFeeUpsertBulk) ClearAdvanceAfter() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.ClearAdvanceAfter() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeFlatFeeUpsertBulk) SetAnnotations(v models.Annotations) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateAnnotations() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeFlatFeeUpsertBulk) ClearAnnotations() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.ClearAnnotations() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeFlatFeeUpsertBulk) SetMetadata(v map[string]string) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateMetadata() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeFlatFeeUpsertBulk) ClearMetadata() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeFlatFeeUpsertBulk) SetUpdatedAt(v time.Time) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateUpdatedAt() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeFlatFeeUpsertBulk) SetDeletedAt(v time.Time) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateDeletedAt() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeFlatFeeUpsertBulk) ClearDeletedAt() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *ChargeFlatFeeUpsertBulk) SetName(v string) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateName() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *ChargeFlatFeeUpsertBulk) SetDescription(v string) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateDescription() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeFlatFeeUpsertBulk) ClearDescription() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.ClearDescription() + }) +} + +// SetPaymentTerm sets the "payment_term" field. +func (u *ChargeFlatFeeUpsertBulk) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetPaymentTerm(v) + }) +} + +// UpdatePaymentTerm sets the "payment_term" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdatePaymentTerm() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdatePaymentTerm() + }) +} + +// SetInvoiceAt sets the "invoice_at" field. +func (u *ChargeFlatFeeUpsertBulk) SetInvoiceAt(v time.Time) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetInvoiceAt(v) + }) +} + +// UpdateInvoiceAt sets the "invoice_at" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateInvoiceAt() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateInvoiceAt() + }) +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (u *ChargeFlatFeeUpsertBulk) SetIntentDeletedAt(v time.Time) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetIntentDeletedAt(v) + }) +} + +// UpdateIntentDeletedAt sets the "intent_deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateIntentDeletedAt() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateIntentDeletedAt() + }) +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (u *ChargeFlatFeeUpsertBulk) ClearIntentDeletedAt() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.ClearIntentDeletedAt() + }) +} + +// SetDiscounts sets the "discounts" field. +func (u *ChargeFlatFeeUpsertBulk) SetDiscounts(v *billing.Discounts) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetDiscounts(v) + }) +} + +// UpdateDiscounts sets the "discounts" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateDiscounts() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateDiscounts() + }) +} + +// ClearDiscounts clears the value of the "discounts" field. +func (u *ChargeFlatFeeUpsertBulk) ClearDiscounts() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.ClearDiscounts() + }) +} + +// SetProRating sets the "pro_rating" field. +func (u *ChargeFlatFeeUpsertBulk) SetProRating(v flatfee.ProRatingModeAdapterEnum) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetProRating(v) + }) +} + +// UpdateProRating sets the "pro_rating" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateProRating() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateProRating() + }) +} + +// SetFeatureID sets the "feature_id" field. +func (u *ChargeFlatFeeUpsertBulk) SetFeatureID(v string) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetFeatureID(v) + }) +} + +// UpdateFeatureID sets the "feature_id" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateFeatureID() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateFeatureID() + }) +} + +// ClearFeatureID clears the value of the "feature_id" field. +func (u *ChargeFlatFeeUpsertBulk) ClearFeatureID() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.ClearFeatureID() + }) +} + +// SetAmountBeforeProration sets the "amount_before_proration" field. +func (u *ChargeFlatFeeUpsertBulk) SetAmountBeforeProration(v alpacadecimal.Decimal) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetAmountBeforeProration(v) + }) +} + +// UpdateAmountBeforeProration sets the "amount_before_proration" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateAmountBeforeProration() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateAmountBeforeProration() + }) +} + +// SetAmountAfterProration sets the "amount_after_proration" field. +func (u *ChargeFlatFeeUpsertBulk) SetAmountAfterProration(v alpacadecimal.Decimal) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetAmountAfterProration(v) + }) +} + +// UpdateAmountAfterProration sets the "amount_after_proration" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateAmountAfterProration() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateAmountAfterProration() + }) +} + +// SetCurrentRealizationRunID sets the "current_realization_run_id" field. +func (u *ChargeFlatFeeUpsertBulk) SetCurrentRealizationRunID(v string) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetCurrentRealizationRunID(v) + }) +} + +// UpdateCurrentRealizationRunID sets the "current_realization_run_id" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateCurrentRealizationRunID() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateCurrentRealizationRunID() + }) +} + +// ClearCurrentRealizationRunID clears the value of the "current_realization_run_id" field. +func (u *ChargeFlatFeeUpsertBulk) ClearCurrentRealizationRunID() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.ClearCurrentRealizationRunID() + }) +} + +// SetStatusDetailed sets the "status_detailed" field. +func (u *ChargeFlatFeeUpsertBulk) SetStatusDetailed(v flatfee.Status) *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.SetStatusDetailed(v) + }) +} + +// UpdateStatusDetailed sets the "status_detailed" field to the value that was provided on create. +func (u *ChargeFlatFeeUpsertBulk) UpdateStatusDetailed() *ChargeFlatFeeUpsertBulk { + return u.Update(func(s *ChargeFlatFeeUpsert) { + s.UpdateStatusDetailed() + }) +} + +// Exec executes the query. +func (u *ChargeFlatFeeUpsertBulk) 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 ChargeFlatFeeCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeFlatFeeCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeFlatFeeUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargeflatfee_delete.go b/ent/db/chargeflatfee_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..75535d0ded97a6c86c9e280b9c407d55e2b40ae5 --- /dev/null +++ b/ent/db/chargeflatfee_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/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeFlatFeeDelete is the builder for deleting a ChargeFlatFee entity. +type ChargeFlatFeeDelete struct { + config + hooks []Hook + mutation *ChargeFlatFeeMutation +} + +// Where appends a list predicates to the ChargeFlatFeeDelete builder. +func (_d *ChargeFlatFeeDelete) Where(ps ...predicate.ChargeFlatFee) *ChargeFlatFeeDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ChargeFlatFeeDelete) 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 *ChargeFlatFeeDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ChargeFlatFeeDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(chargeflatfee.Table, sqlgraph.NewFieldSpec(chargeflatfee.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 +} + +// ChargeFlatFeeDeleteOne is the builder for deleting a single ChargeFlatFee entity. +type ChargeFlatFeeDeleteOne struct { + _d *ChargeFlatFeeDelete +} + +// Where appends a list predicates to the ChargeFlatFeeDelete builder. +func (_d *ChargeFlatFeeDeleteOne) Where(ps ...predicate.ChargeFlatFee) *ChargeFlatFeeDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ChargeFlatFeeDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{chargeflatfee.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeFlatFeeDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargeflatfee_query.go b/ent/db/chargeflatfee_query.go new file mode 100644 index 0000000000000000000000000000000000000000..d70b28c904d98f3b0d09a49a8524e80e7fc1ecdb --- /dev/null +++ b/ent/db/chargeflatfee_query.go @@ -0,0 +1,1325 @@ +// 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/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeoverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/customer" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionphase" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" +) + +// ChargeFlatFeeQuery is the builder for querying ChargeFlatFee entities. +type ChargeFlatFeeQuery struct { + config + ctx *QueryContext + order []chargeflatfee.OrderOption + inters []Interceptor + predicates []predicate.ChargeFlatFee + withRuns *ChargeFlatFeeRunQuery + withCurrentRun *ChargeFlatFeeRunQuery + withCharge *ChargeQuery + withIntentOverride *ChargeFlatFeeOverrideQuery + withSubscription *SubscriptionQuery + withSubscriptionPhase *SubscriptionPhaseQuery + withSubscriptionItem *SubscriptionItemQuery + withCustomer *CustomerQuery + withFeature *FeatureQuery + withTaxCode *TaxCodeQuery + 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 ChargeFlatFeeQuery builder. +func (_q *ChargeFlatFeeQuery) Where(ps ...predicate.ChargeFlatFee) *ChargeFlatFeeQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ChargeFlatFeeQuery) Limit(limit int) *ChargeFlatFeeQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ChargeFlatFeeQuery) Offset(offset int) *ChargeFlatFeeQuery { + _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 *ChargeFlatFeeQuery) Unique(unique bool) *ChargeFlatFeeQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ChargeFlatFeeQuery) Order(o ...chargeflatfee.OrderOption) *ChargeFlatFeeQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryRuns chains the current query on the "runs" edge. +func (_q *ChargeFlatFeeQuery) QueryRuns() *ChargeFlatFeeRunQuery { + query := (&ChargeFlatFeeRunClient{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(chargeflatfee.Table, chargeflatfee.FieldID, selector), + sqlgraph.To(chargeflatfeerun.Table, chargeflatfeerun.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, chargeflatfee.RunsTable, chargeflatfee.RunsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCurrentRun chains the current query on the "current_run" edge. +func (_q *ChargeFlatFeeQuery) QueryCurrentRun() *ChargeFlatFeeRunQuery { + query := (&ChargeFlatFeeRunClient{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(chargeflatfee.Table, chargeflatfee.FieldID, selector), + sqlgraph.To(chargeflatfeerun.Table, chargeflatfeerun.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, chargeflatfee.CurrentRunTable, chargeflatfee.CurrentRunColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCharge chains the current query on the "charge" edge. +func (_q *ChargeFlatFeeQuery) 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(chargeflatfee.Table, chargeflatfee.FieldID, selector), + sqlgraph.To(charge.Table, charge.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargeflatfee.ChargeTable, chargeflatfee.ChargeColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryIntentOverride chains the current query on the "intent_override" edge. +func (_q *ChargeFlatFeeQuery) QueryIntentOverride() *ChargeFlatFeeOverrideQuery { + query := (&ChargeFlatFeeOverrideClient{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(chargeflatfee.Table, chargeflatfee.FieldID, selector), + sqlgraph.To(chargeflatfeeoverride.Table, chargeflatfeeoverride.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargeflatfee.IntentOverrideTable, chargeflatfee.IntentOverrideColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySubscription chains the current query on the "subscription" edge. +func (_q *ChargeFlatFeeQuery) QuerySubscription() *SubscriptionQuery { + query := (&SubscriptionClient{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(chargeflatfee.Table, chargeflatfee.FieldID, selector), + sqlgraph.To(subscription.Table, subscription.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfee.SubscriptionTable, chargeflatfee.SubscriptionColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySubscriptionPhase chains the current query on the "subscription_phase" edge. +func (_q *ChargeFlatFeeQuery) QuerySubscriptionPhase() *SubscriptionPhaseQuery { + query := (&SubscriptionPhaseClient{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(chargeflatfee.Table, chargeflatfee.FieldID, selector), + sqlgraph.To(subscriptionphase.Table, subscriptionphase.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfee.SubscriptionPhaseTable, chargeflatfee.SubscriptionPhaseColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySubscriptionItem chains the current query on the "subscription_item" edge. +func (_q *ChargeFlatFeeQuery) QuerySubscriptionItem() *SubscriptionItemQuery { + query := (&SubscriptionItemClient{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(chargeflatfee.Table, chargeflatfee.FieldID, selector), + sqlgraph.To(subscriptionitem.Table, subscriptionitem.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfee.SubscriptionItemTable, chargeflatfee.SubscriptionItemColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCustomer chains the current query on the "customer" edge. +func (_q *ChargeFlatFeeQuery) QueryCustomer() *CustomerQuery { + query := (&CustomerClient{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(chargeflatfee.Table, chargeflatfee.FieldID, selector), + sqlgraph.To(customer.Table, customer.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfee.CustomerTable, chargeflatfee.CustomerColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryFeature chains the current query on the "feature" edge. +func (_q *ChargeFlatFeeQuery) QueryFeature() *FeatureQuery { + query := (&FeatureClient{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(chargeflatfee.Table, chargeflatfee.FieldID, selector), + sqlgraph.To(dbfeature.Table, dbfeature.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfee.FeatureTable, chargeflatfee.FeatureColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryTaxCode chains the current query on the "tax_code" edge. +func (_q *ChargeFlatFeeQuery) QueryTaxCode() *TaxCodeQuery { + query := (&TaxCodeClient{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(chargeflatfee.Table, chargeflatfee.FieldID, selector), + sqlgraph.To(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfee.TaxCodeTable, chargeflatfee.TaxCodeColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ChargeFlatFee entity from the query. +// Returns a *NotFoundError when no ChargeFlatFee was found. +func (_q *ChargeFlatFeeQuery) First(ctx context.Context) (*ChargeFlatFee, 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{chargeflatfee.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ChargeFlatFeeQuery) FirstX(ctx context.Context) *ChargeFlatFee { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ChargeFlatFee ID from the query. +// Returns a *NotFoundError when no ChargeFlatFee ID was found. +func (_q *ChargeFlatFeeQuery) 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{chargeflatfee.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ChargeFlatFeeQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ChargeFlatFee entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ChargeFlatFee entity is found. +// Returns a *NotFoundError when no ChargeFlatFee entities are found. +func (_q *ChargeFlatFeeQuery) Only(ctx context.Context) (*ChargeFlatFee, 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{chargeflatfee.Label} + default: + return nil, &NotSingularError{chargeflatfee.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ChargeFlatFeeQuery) OnlyX(ctx context.Context) *ChargeFlatFee { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ChargeFlatFee ID in the query. +// Returns a *NotSingularError when more than one ChargeFlatFee ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ChargeFlatFeeQuery) 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{chargeflatfee.Label} + default: + err = &NotSingularError{chargeflatfee.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ChargeFlatFeeQuery) 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 ChargeFlatFees. +func (_q *ChargeFlatFeeQuery) All(ctx context.Context) ([]*ChargeFlatFee, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ChargeFlatFee, *ChargeFlatFeeQuery]() + return withInterceptors[[]*ChargeFlatFee](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ChargeFlatFeeQuery) AllX(ctx context.Context) []*ChargeFlatFee { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ChargeFlatFee IDs. +func (_q *ChargeFlatFeeQuery) 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(chargeflatfee.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ChargeFlatFeeQuery) 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 *ChargeFlatFeeQuery) 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[*ChargeFlatFeeQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ChargeFlatFeeQuery) 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 *ChargeFlatFeeQuery) 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 *ChargeFlatFeeQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ChargeFlatFeeQuery 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 *ChargeFlatFeeQuery) Clone() *ChargeFlatFeeQuery { + if _q == nil { + return nil + } + return &ChargeFlatFeeQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]chargeflatfee.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ChargeFlatFee{}, _q.predicates...), + withRuns: _q.withRuns.Clone(), + withCurrentRun: _q.withCurrentRun.Clone(), + withCharge: _q.withCharge.Clone(), + withIntentOverride: _q.withIntentOverride.Clone(), + withSubscription: _q.withSubscription.Clone(), + withSubscriptionPhase: _q.withSubscriptionPhase.Clone(), + withSubscriptionItem: _q.withSubscriptionItem.Clone(), + withCustomer: _q.withCustomer.Clone(), + withFeature: _q.withFeature.Clone(), + withTaxCode: _q.withTaxCode.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// 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 *ChargeFlatFeeQuery) WithRuns(opts ...func(*ChargeFlatFeeRunQuery)) *ChargeFlatFeeQuery { + query := (&ChargeFlatFeeRunClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withRuns = query + return _q +} + +// WithCurrentRun tells the query-builder to eager-load the nodes that are connected to +// the "current_run" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeFlatFeeQuery) WithCurrentRun(opts ...func(*ChargeFlatFeeRunQuery)) *ChargeFlatFeeQuery { + query := (&ChargeFlatFeeRunClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCurrentRun = query + return _q +} + +// 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 *ChargeFlatFeeQuery) WithCharge(opts ...func(*ChargeQuery)) *ChargeFlatFeeQuery { + query := (&ChargeClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCharge = query + return _q +} + +// WithIntentOverride tells the query-builder to eager-load the nodes that are connected to +// the "intent_override" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeFlatFeeQuery) WithIntentOverride(opts ...func(*ChargeFlatFeeOverrideQuery)) *ChargeFlatFeeQuery { + query := (&ChargeFlatFeeOverrideClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withIntentOverride = query + return _q +} + +// WithSubscription tells the query-builder to eager-load the nodes that are connected to +// the "subscription" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeFlatFeeQuery) WithSubscription(opts ...func(*SubscriptionQuery)) *ChargeFlatFeeQuery { + query := (&SubscriptionClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSubscription = query + return _q +} + +// WithSubscriptionPhase tells the query-builder to eager-load the nodes that are connected to +// the "subscription_phase" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeFlatFeeQuery) WithSubscriptionPhase(opts ...func(*SubscriptionPhaseQuery)) *ChargeFlatFeeQuery { + query := (&SubscriptionPhaseClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSubscriptionPhase = query + return _q +} + +// WithSubscriptionItem tells the query-builder to eager-load the nodes that are connected to +// the "subscription_item" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeFlatFeeQuery) WithSubscriptionItem(opts ...func(*SubscriptionItemQuery)) *ChargeFlatFeeQuery { + query := (&SubscriptionItemClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSubscriptionItem = query + return _q +} + +// WithCustomer tells the query-builder to eager-load the nodes that are connected to +// the "customer" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeFlatFeeQuery) WithCustomer(opts ...func(*CustomerQuery)) *ChargeFlatFeeQuery { + query := (&CustomerClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCustomer = query + return _q +} + +// WithFeature tells the query-builder to eager-load the nodes that are connected to +// the "feature" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeFlatFeeQuery) WithFeature(opts ...func(*FeatureQuery)) *ChargeFlatFeeQuery { + query := (&FeatureClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withFeature = query + return _q +} + +// WithTaxCode tells the query-builder to eager-load the nodes that are connected to +// the "tax_code" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeFlatFeeQuery) WithTaxCode(opts ...func(*TaxCodeQuery)) *ChargeFlatFeeQuery { + query := (&TaxCodeClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withTaxCode = 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 { +// CustomerID string `json:"customer_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.ChargeFlatFee.Query(). +// GroupBy(chargeflatfee.FieldCustomerID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *ChargeFlatFeeQuery) GroupBy(field string, fields ...string) *ChargeFlatFeeGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ChargeFlatFeeGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = chargeflatfee.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 { +// CustomerID string `json:"customer_id,omitempty"` +// } +// +// client.ChargeFlatFee.Query(). +// Select(chargeflatfee.FieldCustomerID). +// Scan(ctx, &v) +func (_q *ChargeFlatFeeQuery) Select(fields ...string) *ChargeFlatFeeSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ChargeFlatFeeSelect{ChargeFlatFeeQuery: _q} + sbuild.label = chargeflatfee.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ChargeFlatFeeSelect configured with the given aggregations. +func (_q *ChargeFlatFeeQuery) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ChargeFlatFeeQuery) 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 !chargeflatfee.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 *ChargeFlatFeeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ChargeFlatFee, error) { + var ( + nodes = []*ChargeFlatFee{} + _spec = _q.querySpec() + loadedTypes = [10]bool{ + _q.withRuns != nil, + _q.withCurrentRun != nil, + _q.withCharge != nil, + _q.withIntentOverride != nil, + _q.withSubscription != nil, + _q.withSubscriptionPhase != nil, + _q.withSubscriptionItem != nil, + _q.withCustomer != nil, + _q.withFeature != nil, + _q.withTaxCode != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ChargeFlatFee).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ChargeFlatFee{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.withRuns; query != nil { + if err := _q.loadRuns(ctx, query, nodes, + func(n *ChargeFlatFee) { n.Edges.Runs = []*ChargeFlatFeeRun{} }, + func(n *ChargeFlatFee, e *ChargeFlatFeeRun) { n.Edges.Runs = append(n.Edges.Runs, e) }); err != nil { + return nil, err + } + } + if query := _q.withCurrentRun; query != nil { + if err := _q.loadCurrentRun(ctx, query, nodes, nil, + func(n *ChargeFlatFee, e *ChargeFlatFeeRun) { n.Edges.CurrentRun = e }); err != nil { + return nil, err + } + } + if query := _q.withCharge; query != nil { + if err := _q.loadCharge(ctx, query, nodes, nil, + func(n *ChargeFlatFee, e *Charge) { n.Edges.Charge = e }); err != nil { + return nil, err + } + } + if query := _q.withIntentOverride; query != nil { + if err := _q.loadIntentOverride(ctx, query, nodes, nil, + func(n *ChargeFlatFee, e *ChargeFlatFeeOverride) { n.Edges.IntentOverride = e }); err != nil { + return nil, err + } + } + if query := _q.withSubscription; query != nil { + if err := _q.loadSubscription(ctx, query, nodes, nil, + func(n *ChargeFlatFee, e *Subscription) { n.Edges.Subscription = e }); err != nil { + return nil, err + } + } + if query := _q.withSubscriptionPhase; query != nil { + if err := _q.loadSubscriptionPhase(ctx, query, nodes, nil, + func(n *ChargeFlatFee, e *SubscriptionPhase) { n.Edges.SubscriptionPhase = e }); err != nil { + return nil, err + } + } + if query := _q.withSubscriptionItem; query != nil { + if err := _q.loadSubscriptionItem(ctx, query, nodes, nil, + func(n *ChargeFlatFee, e *SubscriptionItem) { n.Edges.SubscriptionItem = e }); err != nil { + return nil, err + } + } + if query := _q.withCustomer; query != nil { + if err := _q.loadCustomer(ctx, query, nodes, nil, + func(n *ChargeFlatFee, e *Customer) { n.Edges.Customer = e }); err != nil { + return nil, err + } + } + if query := _q.withFeature; query != nil { + if err := _q.loadFeature(ctx, query, nodes, nil, + func(n *ChargeFlatFee, e *Feature) { n.Edges.Feature = e }); err != nil { + return nil, err + } + } + if query := _q.withTaxCode; query != nil { + if err := _q.loadTaxCode(ctx, query, nodes, nil, + func(n *ChargeFlatFee, e *TaxCode) { n.Edges.TaxCode = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ChargeFlatFeeQuery) loadRuns(ctx context.Context, query *ChargeFlatFeeRunQuery, nodes []*ChargeFlatFee, init func(*ChargeFlatFee), assign func(*ChargeFlatFee, *ChargeFlatFeeRun)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*ChargeFlatFee) + 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(chargeflatfeerun.FieldChargeID) + } + query.Where(predicate.ChargeFlatFeeRun(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargeflatfee.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 *ChargeFlatFeeQuery) loadCurrentRun(ctx context.Context, query *ChargeFlatFeeRunQuery, nodes []*ChargeFlatFee, init func(*ChargeFlatFee), assign func(*ChargeFlatFee, *ChargeFlatFeeRun)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeFlatFee) + for i := range nodes { + if nodes[i].CurrentRealizationRunID == nil { + continue + } + fk := *nodes[i].CurrentRealizationRunID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(chargeflatfeerun.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 "current_realization_run_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeFlatFeeQuery) loadCharge(ctx context.Context, query *ChargeQuery, nodes []*ChargeFlatFee, init func(*ChargeFlatFee), assign func(*ChargeFlatFee, *Charge)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*ChargeFlatFee) + 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(charge.FieldChargeFlatFeeID) + } + query.Where(predicate.Charge(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargeflatfee.ChargeColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.ChargeFlatFeeID + if fk == nil { + return fmt.Errorf(`foreign-key "charge_flat_fee_id" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "charge_flat_fee_id" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *ChargeFlatFeeQuery) loadIntentOverride(ctx context.Context, query *ChargeFlatFeeOverrideQuery, nodes []*ChargeFlatFee, init func(*ChargeFlatFee), assign func(*ChargeFlatFee, *ChargeFlatFeeOverride)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*ChargeFlatFee) + 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(chargeflatfeeoverride.FieldChargeID) + } + query.Where(predicate.ChargeFlatFeeOverride(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargeflatfee.IntentOverrideColumn), 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 *ChargeFlatFeeQuery) loadSubscription(ctx context.Context, query *SubscriptionQuery, nodes []*ChargeFlatFee, init func(*ChargeFlatFee), assign func(*ChargeFlatFee, *Subscription)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeFlatFee) + for i := range nodes { + if nodes[i].SubscriptionID == nil { + continue + } + fk := *nodes[i].SubscriptionID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(subscription.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 "subscription_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeFlatFeeQuery) loadSubscriptionPhase(ctx context.Context, query *SubscriptionPhaseQuery, nodes []*ChargeFlatFee, init func(*ChargeFlatFee), assign func(*ChargeFlatFee, *SubscriptionPhase)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeFlatFee) + for i := range nodes { + if nodes[i].SubscriptionPhaseID == nil { + continue + } + fk := *nodes[i].SubscriptionPhaseID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(subscriptionphase.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 "subscription_phase_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeFlatFeeQuery) loadSubscriptionItem(ctx context.Context, query *SubscriptionItemQuery, nodes []*ChargeFlatFee, init func(*ChargeFlatFee), assign func(*ChargeFlatFee, *SubscriptionItem)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeFlatFee) + for i := range nodes { + if nodes[i].SubscriptionItemID == nil { + continue + } + fk := *nodes[i].SubscriptionItemID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(subscriptionitem.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 "subscription_item_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeFlatFeeQuery) loadCustomer(ctx context.Context, query *CustomerQuery, nodes []*ChargeFlatFee, init func(*ChargeFlatFee), assign func(*ChargeFlatFee, *Customer)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeFlatFee) + for i := range nodes { + fk := nodes[i].CustomerID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(customer.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 "customer_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeFlatFeeQuery) loadFeature(ctx context.Context, query *FeatureQuery, nodes []*ChargeFlatFee, init func(*ChargeFlatFee), assign func(*ChargeFlatFee, *Feature)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeFlatFee) + for i := range nodes { + if nodes[i].FeatureID == nil { + continue + } + fk := *nodes[i].FeatureID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(dbfeature.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 "feature_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeFlatFeeQuery) loadTaxCode(ctx context.Context, query *TaxCodeQuery, nodes []*ChargeFlatFee, init func(*ChargeFlatFee), assign func(*ChargeFlatFee, *TaxCode)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeFlatFee) + for i := range nodes { + fk := nodes[i].TaxCodeID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(dbtaxcode.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 "tax_code_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *ChargeFlatFeeQuery) 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 *ChargeFlatFeeQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(chargeflatfee.Table, chargeflatfee.Columns, sqlgraph.NewFieldSpec(chargeflatfee.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, chargeflatfee.FieldID) + for i := range fields { + if fields[i] != chargeflatfee.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withCurrentRun != nil { + _spec.Node.AddColumnOnce(chargeflatfee.FieldCurrentRealizationRunID) + } + if _q.withSubscription != nil { + _spec.Node.AddColumnOnce(chargeflatfee.FieldSubscriptionID) + } + if _q.withSubscriptionPhase != nil { + _spec.Node.AddColumnOnce(chargeflatfee.FieldSubscriptionPhaseID) + } + if _q.withSubscriptionItem != nil { + _spec.Node.AddColumnOnce(chargeflatfee.FieldSubscriptionItemID) + } + if _q.withCustomer != nil { + _spec.Node.AddColumnOnce(chargeflatfee.FieldCustomerID) + } + if _q.withFeature != nil { + _spec.Node.AddColumnOnce(chargeflatfee.FieldFeatureID) + } + if _q.withTaxCode != nil { + _spec.Node.AddColumnOnce(chargeflatfee.FieldTaxCodeID) + } + } + 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 *ChargeFlatFeeQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(chargeflatfee.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = chargeflatfee.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 *ChargeFlatFeeQuery) ForUpdate(opts ...sql.LockOption) *ChargeFlatFeeQuery { + 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 *ChargeFlatFeeQuery) ForShare(opts ...sql.LockOption) *ChargeFlatFeeQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ChargeFlatFeeGroupBy is the group-by builder for ChargeFlatFee entities. +type ChargeFlatFeeGroupBy struct { + selector + build *ChargeFlatFeeQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ChargeFlatFeeGroupBy) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ChargeFlatFeeGroupBy) 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[*ChargeFlatFeeQuery, *ChargeFlatFeeGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ChargeFlatFeeGroupBy) sqlScan(ctx context.Context, root *ChargeFlatFeeQuery, 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) +} + +// ChargeFlatFeeSelect is the builder for selecting fields of ChargeFlatFee entities. +type ChargeFlatFeeSelect struct { + *ChargeFlatFeeQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ChargeFlatFeeSelect) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ChargeFlatFeeSelect) 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[*ChargeFlatFeeQuery, *ChargeFlatFeeSelect](ctx, _s.ChargeFlatFeeQuery, _s, _s.inters, v) +} + +func (_s *ChargeFlatFeeSelect) sqlScan(ctx context.Context, root *ChargeFlatFeeQuery, 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/ent/db/chargeflatfee_update.go b/ent/db/chargeflatfee_update.go new file mode 100644 index 0000000000000000000000000000000000000000..72ca2ec61d2dceabcce6f189baa2fe3b35df91d1 --- /dev/null +++ b/ent/db/chargeflatfee_update.go @@ -0,0 +1,1776 @@ +// 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" + "github.com/openmeterio/openmeter/openmeter/billing/charges/flatfee" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeoverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerun" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeFlatFeeUpdate is the builder for updating ChargeFlatFee entities. +type ChargeFlatFeeUpdate struct { + config + hooks []Hook + mutation *ChargeFlatFeeMutation +} + +// Where appends a list predicates to the ChargeFlatFeeUpdate builder. +func (_u *ChargeFlatFeeUpdate) Where(ps ...predicate.ChargeFlatFee) *ChargeFlatFeeUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeFlatFeeUpdate) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeUpdate { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableServicePeriodFrom(v *time.Time) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeFlatFeeUpdate) SetServicePeriodTo(v time.Time) *ChargeFlatFeeUpdate { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableServicePeriodTo(v *time.Time) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (_u *ChargeFlatFeeUpdate) SetBillingPeriodFrom(v time.Time) *ChargeFlatFeeUpdate { + _u.mutation.SetBillingPeriodFrom(v) + return _u +} + +// SetNillableBillingPeriodFrom sets the "billing_period_from" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableBillingPeriodFrom(v *time.Time) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetBillingPeriodFrom(*v) + } + return _u +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (_u *ChargeFlatFeeUpdate) SetBillingPeriodTo(v time.Time) *ChargeFlatFeeUpdate { + _u.mutation.SetBillingPeriodTo(v) + return _u +} + +// SetNillableBillingPeriodTo sets the "billing_period_to" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableBillingPeriodTo(v *time.Time) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetBillingPeriodTo(*v) + } + return _u +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (_u *ChargeFlatFeeUpdate) SetFullServicePeriodFrom(v time.Time) *ChargeFlatFeeUpdate { + _u.mutation.SetFullServicePeriodFrom(v) + return _u +} + +// SetNillableFullServicePeriodFrom sets the "full_service_period_from" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableFullServicePeriodFrom(v *time.Time) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetFullServicePeriodFrom(*v) + } + return _u +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (_u *ChargeFlatFeeUpdate) SetFullServicePeriodTo(v time.Time) *ChargeFlatFeeUpdate { + _u.mutation.SetFullServicePeriodTo(v) + return _u +} + +// SetNillableFullServicePeriodTo sets the "full_service_period_to" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableFullServicePeriodTo(v *time.Time) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetFullServicePeriodTo(*v) + } + return _u +} + +// SetStatus sets the "status" field. +func (_u *ChargeFlatFeeUpdate) SetStatus(v meta.ChargeStatus) *ChargeFlatFeeUpdate { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableStatus(v *meta.ChargeStatus) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (_u *ChargeFlatFeeUpdate) SetSubscriptionItemID(v string) *ChargeFlatFeeUpdate { + _u.mutation.SetSubscriptionItemID(v) + return _u +} + +// SetNillableSubscriptionItemID sets the "subscription_item_id" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableSubscriptionItemID(v *string) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetSubscriptionItemID(*v) + } + return _u +} + +// ClearSubscriptionItemID clears the value of the "subscription_item_id" field. +func (_u *ChargeFlatFeeUpdate) ClearSubscriptionItemID() *ChargeFlatFeeUpdate { + _u.mutation.ClearSubscriptionItemID() + return _u +} + +// SetAdvanceAfter sets the "advance_after" field. +func (_u *ChargeFlatFeeUpdate) SetAdvanceAfter(v time.Time) *ChargeFlatFeeUpdate { + _u.mutation.SetAdvanceAfter(v) + return _u +} + +// SetNillableAdvanceAfter sets the "advance_after" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableAdvanceAfter(v *time.Time) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetAdvanceAfter(*v) + } + return _u +} + +// ClearAdvanceAfter clears the value of the "advance_after" field. +func (_u *ChargeFlatFeeUpdate) ClearAdvanceAfter() *ChargeFlatFeeUpdate { + _u.mutation.ClearAdvanceAfter() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeFlatFeeUpdate) SetAnnotations(v models.Annotations) *ChargeFlatFeeUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeFlatFeeUpdate) ClearAnnotations() *ChargeFlatFeeUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *ChargeFlatFeeUpdate) SetMetadata(v map[string]string) *ChargeFlatFeeUpdate { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *ChargeFlatFeeUpdate) ClearMetadata() *ChargeFlatFeeUpdate { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeFlatFeeUpdate) SetUpdatedAt(v time.Time) *ChargeFlatFeeUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeFlatFeeUpdate) SetDeletedAt(v time.Time) *ChargeFlatFeeUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableDeletedAt(v *time.Time) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeFlatFeeUpdate) ClearDeletedAt() *ChargeFlatFeeUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *ChargeFlatFeeUpdate) SetName(v string) *ChargeFlatFeeUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableName(v *string) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *ChargeFlatFeeUpdate) SetDescription(v string) *ChargeFlatFeeUpdate { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableDescription(v *string) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *ChargeFlatFeeUpdate) ClearDescription() *ChargeFlatFeeUpdate { + _u.mutation.ClearDescription() + return _u +} + +// SetPaymentTerm sets the "payment_term" field. +func (_u *ChargeFlatFeeUpdate) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeFlatFeeUpdate { + _u.mutation.SetPaymentTerm(v) + return _u +} + +// SetNillablePaymentTerm sets the "payment_term" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillablePaymentTerm(v *productcatalog.PaymentTermType) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetPaymentTerm(*v) + } + return _u +} + +// SetInvoiceAt sets the "invoice_at" field. +func (_u *ChargeFlatFeeUpdate) SetInvoiceAt(v time.Time) *ChargeFlatFeeUpdate { + _u.mutation.SetInvoiceAt(v) + return _u +} + +// SetNillableInvoiceAt sets the "invoice_at" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableInvoiceAt(v *time.Time) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetInvoiceAt(*v) + } + return _u +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (_u *ChargeFlatFeeUpdate) SetIntentDeletedAt(v time.Time) *ChargeFlatFeeUpdate { + _u.mutation.SetIntentDeletedAt(v) + return _u +} + +// SetNillableIntentDeletedAt sets the "intent_deleted_at" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableIntentDeletedAt(v *time.Time) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetIntentDeletedAt(*v) + } + return _u +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (_u *ChargeFlatFeeUpdate) ClearIntentDeletedAt() *ChargeFlatFeeUpdate { + _u.mutation.ClearIntentDeletedAt() + return _u +} + +// SetDiscounts sets the "discounts" field. +func (_u *ChargeFlatFeeUpdate) SetDiscounts(v *billing.Discounts) *ChargeFlatFeeUpdate { + _u.mutation.SetDiscounts(v) + return _u +} + +// ClearDiscounts clears the value of the "discounts" field. +func (_u *ChargeFlatFeeUpdate) ClearDiscounts() *ChargeFlatFeeUpdate { + _u.mutation.ClearDiscounts() + return _u +} + +// SetProRating sets the "pro_rating" field. +func (_u *ChargeFlatFeeUpdate) SetProRating(v flatfee.ProRatingModeAdapterEnum) *ChargeFlatFeeUpdate { + _u.mutation.SetProRating(v) + return _u +} + +// SetNillableProRating sets the "pro_rating" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableProRating(v *flatfee.ProRatingModeAdapterEnum) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetProRating(*v) + } + return _u +} + +// SetFeatureID sets the "feature_id" field. +func (_u *ChargeFlatFeeUpdate) SetFeatureID(v string) *ChargeFlatFeeUpdate { + _u.mutation.SetFeatureID(v) + return _u +} + +// SetNillableFeatureID sets the "feature_id" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableFeatureID(v *string) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetFeatureID(*v) + } + return _u +} + +// ClearFeatureID clears the value of the "feature_id" field. +func (_u *ChargeFlatFeeUpdate) ClearFeatureID() *ChargeFlatFeeUpdate { + _u.mutation.ClearFeatureID() + return _u +} + +// SetAmountBeforeProration sets the "amount_before_proration" field. +func (_u *ChargeFlatFeeUpdate) SetAmountBeforeProration(v alpacadecimal.Decimal) *ChargeFlatFeeUpdate { + _u.mutation.SetAmountBeforeProration(v) + return _u +} + +// SetNillableAmountBeforeProration sets the "amount_before_proration" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableAmountBeforeProration(v *alpacadecimal.Decimal) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetAmountBeforeProration(*v) + } + return _u +} + +// SetAmountAfterProration sets the "amount_after_proration" field. +func (_u *ChargeFlatFeeUpdate) SetAmountAfterProration(v alpacadecimal.Decimal) *ChargeFlatFeeUpdate { + _u.mutation.SetAmountAfterProration(v) + return _u +} + +// SetNillableAmountAfterProration sets the "amount_after_proration" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableAmountAfterProration(v *alpacadecimal.Decimal) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetAmountAfterProration(*v) + } + return _u +} + +// SetCurrentRealizationRunID sets the "current_realization_run_id" field. +func (_u *ChargeFlatFeeUpdate) SetCurrentRealizationRunID(v string) *ChargeFlatFeeUpdate { + _u.mutation.SetCurrentRealizationRunID(v) + return _u +} + +// SetNillableCurrentRealizationRunID sets the "current_realization_run_id" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableCurrentRealizationRunID(v *string) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetCurrentRealizationRunID(*v) + } + return _u +} + +// ClearCurrentRealizationRunID clears the value of the "current_realization_run_id" field. +func (_u *ChargeFlatFeeUpdate) ClearCurrentRealizationRunID() *ChargeFlatFeeUpdate { + _u.mutation.ClearCurrentRealizationRunID() + return _u +} + +// SetStatusDetailed sets the "status_detailed" field. +func (_u *ChargeFlatFeeUpdate) SetStatusDetailed(v flatfee.Status) *ChargeFlatFeeUpdate { + _u.mutation.SetStatusDetailed(v) + return _u +} + +// SetNillableStatusDetailed sets the "status_detailed" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableStatusDetailed(v *flatfee.Status) *ChargeFlatFeeUpdate { + if v != nil { + _u.SetStatusDetailed(*v) + } + return _u +} + +// AddRunIDs adds the "runs" edge to the ChargeFlatFeeRun entity by IDs. +func (_u *ChargeFlatFeeUpdate) AddRunIDs(ids ...string) *ChargeFlatFeeUpdate { + _u.mutation.AddRunIDs(ids...) + return _u +} + +// AddRuns adds the "runs" edges to the ChargeFlatFeeRun entity. +func (_u *ChargeFlatFeeUpdate) AddRuns(v ...*ChargeFlatFeeRun) *ChargeFlatFeeUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddRunIDs(ids...) +} + +// SetCurrentRunID sets the "current_run" edge to the ChargeFlatFeeRun entity by ID. +func (_u *ChargeFlatFeeUpdate) SetCurrentRunID(id string) *ChargeFlatFeeUpdate { + _u.mutation.SetCurrentRunID(id) + return _u +} + +// SetNillableCurrentRunID sets the "current_run" edge to the ChargeFlatFeeRun entity by ID if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableCurrentRunID(id *string) *ChargeFlatFeeUpdate { + if id != nil { + _u = _u.SetCurrentRunID(*id) + } + return _u +} + +// SetCurrentRun sets the "current_run" edge to the ChargeFlatFeeRun entity. +func (_u *ChargeFlatFeeUpdate) SetCurrentRun(v *ChargeFlatFeeRun) *ChargeFlatFeeUpdate { + return _u.SetCurrentRunID(v.ID) +} + +// SetIntentOverrideID sets the "intent_override" edge to the ChargeFlatFeeOverride entity by ID. +func (_u *ChargeFlatFeeUpdate) SetIntentOverrideID(id string) *ChargeFlatFeeUpdate { + _u.mutation.SetIntentOverrideID(id) + return _u +} + +// SetNillableIntentOverrideID sets the "intent_override" edge to the ChargeFlatFeeOverride entity by ID if the given value is not nil. +func (_u *ChargeFlatFeeUpdate) SetNillableIntentOverrideID(id *string) *ChargeFlatFeeUpdate { + if id != nil { + _u = _u.SetIntentOverrideID(*id) + } + return _u +} + +// SetIntentOverride sets the "intent_override" edge to the ChargeFlatFeeOverride entity. +func (_u *ChargeFlatFeeUpdate) SetIntentOverride(v *ChargeFlatFeeOverride) *ChargeFlatFeeUpdate { + return _u.SetIntentOverrideID(v.ID) +} + +// SetSubscriptionItem sets the "subscription_item" edge to the SubscriptionItem entity. +func (_u *ChargeFlatFeeUpdate) SetSubscriptionItem(v *SubscriptionItem) *ChargeFlatFeeUpdate { + return _u.SetSubscriptionItemID(v.ID) +} + +// SetFeature sets the "feature" edge to the Feature entity. +func (_u *ChargeFlatFeeUpdate) SetFeature(v *Feature) *ChargeFlatFeeUpdate { + return _u.SetFeatureID(v.ID) +} + +// Mutation returns the ChargeFlatFeeMutation object of the builder. +func (_u *ChargeFlatFeeUpdate) Mutation() *ChargeFlatFeeMutation { + return _u.mutation +} + +// ClearRuns clears all "runs" edges to the ChargeFlatFeeRun entity. +func (_u *ChargeFlatFeeUpdate) ClearRuns() *ChargeFlatFeeUpdate { + _u.mutation.ClearRuns() + return _u +} + +// RemoveRunIDs removes the "runs" edge to ChargeFlatFeeRun entities by IDs. +func (_u *ChargeFlatFeeUpdate) RemoveRunIDs(ids ...string) *ChargeFlatFeeUpdate { + _u.mutation.RemoveRunIDs(ids...) + return _u +} + +// RemoveRuns removes "runs" edges to ChargeFlatFeeRun entities. +func (_u *ChargeFlatFeeUpdate) RemoveRuns(v ...*ChargeFlatFeeRun) *ChargeFlatFeeUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveRunIDs(ids...) +} + +// ClearCurrentRun clears the "current_run" edge to the ChargeFlatFeeRun entity. +func (_u *ChargeFlatFeeUpdate) ClearCurrentRun() *ChargeFlatFeeUpdate { + _u.mutation.ClearCurrentRun() + return _u +} + +// ClearIntentOverride clears the "intent_override" edge to the ChargeFlatFeeOverride entity. +func (_u *ChargeFlatFeeUpdate) ClearIntentOverride() *ChargeFlatFeeUpdate { + _u.mutation.ClearIntentOverride() + return _u +} + +// ClearSubscriptionItem clears the "subscription_item" edge to the SubscriptionItem entity. +func (_u *ChargeFlatFeeUpdate) ClearSubscriptionItem() *ChargeFlatFeeUpdate { + _u.mutation.ClearSubscriptionItem() + return _u +} + +// ClearFeature clears the "feature" edge to the Feature entity. +func (_u *ChargeFlatFeeUpdate) ClearFeature() *ChargeFlatFeeUpdate { + _u.mutation.ClearFeature() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ChargeFlatFeeUpdate) 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 *ChargeFlatFeeUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ChargeFlatFeeUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeFlatFeeUpdate) 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 *ChargeFlatFeeUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeflatfee.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeFlatFeeUpdate) check() error { + if v, ok := _u.mutation.Status(); ok { + if err := chargeflatfee.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFee.status": %w`, err)} + } + } + if v, ok := _u.mutation.PaymentTerm(); ok { + if err := chargeflatfee.PaymentTermValidator(string(v)); err != nil { + return &ValidationError{Name: "payment_term", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFee.payment_term": %w`, err)} + } + } + 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 "ChargeFlatFee.discounts": %w`, err)} + } + } + if v, ok := _u.mutation.ProRating(); ok { + if err := chargeflatfee.ProRatingValidator(v); err != nil { + return &ValidationError{Name: "pro_rating", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFee.pro_rating": %w`, err)} + } + } + if v, ok := _u.mutation.StatusDetailed(); ok { + if err := chargeflatfee.StatusDetailedValidator(v); err != nil { + return &ValidationError{Name: "status_detailed", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFee.status_detailed": %w`, err)} + } + } + if _u.mutation.CustomerCleared() && len(_u.mutation.CustomerIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeFlatFee.customer"`) + } + if _u.mutation.TaxCodeCleared() && len(_u.mutation.TaxCodeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeFlatFee.tax_code"`) + } + return nil +} + +func (_u *ChargeFlatFeeUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeflatfee.Table, chargeflatfee.Columns, sqlgraph.NewFieldSpec(chargeflatfee.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(chargeflatfee.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeflatfee.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.BillingPeriodFrom(); ok { + _spec.SetField(chargeflatfee.FieldBillingPeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.BillingPeriodTo(); ok { + _spec.SetField(chargeflatfee.FieldBillingPeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.FullServicePeriodFrom(); ok { + _spec.SetField(chargeflatfee.FieldFullServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.FullServicePeriodTo(); ok { + _spec.SetField(chargeflatfee.FieldFullServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(chargeflatfee.FieldStatus, field.TypeEnum, value) + } + if _u.mutation.UniqueReferenceIDCleared() { + _spec.ClearField(chargeflatfee.FieldUniqueReferenceID, field.TypeString) + } + if value, ok := _u.mutation.AdvanceAfter(); ok { + _spec.SetField(chargeflatfee.FieldAdvanceAfter, field.TypeTime, value) + } + if _u.mutation.AdvanceAfterCleared() { + _spec.ClearField(chargeflatfee.FieldAdvanceAfter, field.TypeTime) + } + if _u.mutation.TaxBehaviorCleared() { + _spec.ClearField(chargeflatfee.FieldTaxBehavior, field.TypeEnum) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargeflatfee.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargeflatfee.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(chargeflatfee.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(chargeflatfee.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeflatfee.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeflatfee.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeflatfee.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(chargeflatfee.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(chargeflatfee.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(chargeflatfee.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.PaymentTerm(); ok { + _spec.SetField(chargeflatfee.FieldPaymentTerm, field.TypeString, value) + } + if value, ok := _u.mutation.InvoiceAt(); ok { + _spec.SetField(chargeflatfee.FieldInvoiceAt, field.TypeTime, value) + } + if value, ok := _u.mutation.IntentDeletedAt(); ok { + _spec.SetField(chargeflatfee.FieldIntentDeletedAt, field.TypeTime, value) + } + if _u.mutation.IntentDeletedAtCleared() { + _spec.ClearField(chargeflatfee.FieldIntentDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Discounts(); ok { + vv, err := chargeflatfee.ValueScanner.Discounts.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(chargeflatfee.FieldDiscounts, field.TypeString, vv) + } + if _u.mutation.DiscountsCleared() { + _spec.ClearField(chargeflatfee.FieldDiscounts, field.TypeString) + } + if value, ok := _u.mutation.ProRating(); ok { + _spec.SetField(chargeflatfee.FieldProRating, field.TypeEnum, value) + } + if _u.mutation.FeatureKeyCleared() { + _spec.ClearField(chargeflatfee.FieldFeatureKey, field.TypeString) + } + if value, ok := _u.mutation.AmountBeforeProration(); ok { + _spec.SetField(chargeflatfee.FieldAmountBeforeProration, field.TypeOther, value) + } + if value, ok := _u.mutation.AmountAfterProration(); ok { + _spec.SetField(chargeflatfee.FieldAmountAfterProration, field.TypeOther, value) + } + if value, ok := _u.mutation.StatusDetailed(); ok { + _spec.SetField(chargeflatfee.FieldStatusDetailed, field.TypeEnum, value) + } + if _u.mutation.RunsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeflatfee.RunsTable, + Columns: []string{chargeflatfee.RunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerun.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: chargeflatfee.RunsTable, + Columns: []string{chargeflatfee.RunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerun.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: chargeflatfee.RunsTable, + Columns: []string{chargeflatfee.RunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerun.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.CurrentRunCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: chargeflatfee.CurrentRunTable, + Columns: []string{chargeflatfee.CurrentRunColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerun.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.CurrentRunIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: chargeflatfee.CurrentRunTable, + Columns: []string{chargeflatfee.CurrentRunColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerun.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.IntentOverrideCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeflatfee.IntentOverrideTable, + Columns: []string{chargeflatfee.IntentOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeoverride.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.IntentOverrideIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeflatfee.IntentOverrideTable, + Columns: []string{chargeflatfee.IntentOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeoverride.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.SubscriptionItemCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfee.SubscriptionItemTable, + Columns: []string{chargeflatfee.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.SubscriptionItemIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfee.SubscriptionItemTable, + Columns: []string{chargeflatfee.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.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.FeatureCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfee.FeatureTable, + Columns: []string{chargeflatfee.FeatureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbfeature.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.FeatureIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfee.FeatureTable, + Columns: []string{chargeflatfee.FeatureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbfeature.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{chargeflatfee.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ChargeFlatFeeUpdateOne is the builder for updating a single ChargeFlatFee entity. +type ChargeFlatFeeUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ChargeFlatFeeMutation +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeFlatFeeUpdateOne) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeUpdateOne { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableServicePeriodFrom(v *time.Time) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeFlatFeeUpdateOne) SetServicePeriodTo(v time.Time) *ChargeFlatFeeUpdateOne { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableServicePeriodTo(v *time.Time) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (_u *ChargeFlatFeeUpdateOne) SetBillingPeriodFrom(v time.Time) *ChargeFlatFeeUpdateOne { + _u.mutation.SetBillingPeriodFrom(v) + return _u +} + +// SetNillableBillingPeriodFrom sets the "billing_period_from" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableBillingPeriodFrom(v *time.Time) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetBillingPeriodFrom(*v) + } + return _u +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (_u *ChargeFlatFeeUpdateOne) SetBillingPeriodTo(v time.Time) *ChargeFlatFeeUpdateOne { + _u.mutation.SetBillingPeriodTo(v) + return _u +} + +// SetNillableBillingPeriodTo sets the "billing_period_to" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableBillingPeriodTo(v *time.Time) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetBillingPeriodTo(*v) + } + return _u +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (_u *ChargeFlatFeeUpdateOne) SetFullServicePeriodFrom(v time.Time) *ChargeFlatFeeUpdateOne { + _u.mutation.SetFullServicePeriodFrom(v) + return _u +} + +// SetNillableFullServicePeriodFrom sets the "full_service_period_from" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableFullServicePeriodFrom(v *time.Time) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetFullServicePeriodFrom(*v) + } + return _u +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (_u *ChargeFlatFeeUpdateOne) SetFullServicePeriodTo(v time.Time) *ChargeFlatFeeUpdateOne { + _u.mutation.SetFullServicePeriodTo(v) + return _u +} + +// SetNillableFullServicePeriodTo sets the "full_service_period_to" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableFullServicePeriodTo(v *time.Time) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetFullServicePeriodTo(*v) + } + return _u +} + +// SetStatus sets the "status" field. +func (_u *ChargeFlatFeeUpdateOne) SetStatus(v meta.ChargeStatus) *ChargeFlatFeeUpdateOne { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableStatus(v *meta.ChargeStatus) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (_u *ChargeFlatFeeUpdateOne) SetSubscriptionItemID(v string) *ChargeFlatFeeUpdateOne { + _u.mutation.SetSubscriptionItemID(v) + return _u +} + +// SetNillableSubscriptionItemID sets the "subscription_item_id" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableSubscriptionItemID(v *string) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetSubscriptionItemID(*v) + } + return _u +} + +// ClearSubscriptionItemID clears the value of the "subscription_item_id" field. +func (_u *ChargeFlatFeeUpdateOne) ClearSubscriptionItemID() *ChargeFlatFeeUpdateOne { + _u.mutation.ClearSubscriptionItemID() + return _u +} + +// SetAdvanceAfter sets the "advance_after" field. +func (_u *ChargeFlatFeeUpdateOne) SetAdvanceAfter(v time.Time) *ChargeFlatFeeUpdateOne { + _u.mutation.SetAdvanceAfter(v) + return _u +} + +// SetNillableAdvanceAfter sets the "advance_after" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableAdvanceAfter(v *time.Time) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetAdvanceAfter(*v) + } + return _u +} + +// ClearAdvanceAfter clears the value of the "advance_after" field. +func (_u *ChargeFlatFeeUpdateOne) ClearAdvanceAfter() *ChargeFlatFeeUpdateOne { + _u.mutation.ClearAdvanceAfter() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeFlatFeeUpdateOne) SetAnnotations(v models.Annotations) *ChargeFlatFeeUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeFlatFeeUpdateOne) ClearAnnotations() *ChargeFlatFeeUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *ChargeFlatFeeUpdateOne) SetMetadata(v map[string]string) *ChargeFlatFeeUpdateOne { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *ChargeFlatFeeUpdateOne) ClearMetadata() *ChargeFlatFeeUpdateOne { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeFlatFeeUpdateOne) SetUpdatedAt(v time.Time) *ChargeFlatFeeUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeFlatFeeUpdateOne) SetDeletedAt(v time.Time) *ChargeFlatFeeUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableDeletedAt(v *time.Time) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeFlatFeeUpdateOne) ClearDeletedAt() *ChargeFlatFeeUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *ChargeFlatFeeUpdateOne) SetName(v string) *ChargeFlatFeeUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableName(v *string) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *ChargeFlatFeeUpdateOne) SetDescription(v string) *ChargeFlatFeeUpdateOne { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableDescription(v *string) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *ChargeFlatFeeUpdateOne) ClearDescription() *ChargeFlatFeeUpdateOne { + _u.mutation.ClearDescription() + return _u +} + +// SetPaymentTerm sets the "payment_term" field. +func (_u *ChargeFlatFeeUpdateOne) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeFlatFeeUpdateOne { + _u.mutation.SetPaymentTerm(v) + return _u +} + +// SetNillablePaymentTerm sets the "payment_term" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillablePaymentTerm(v *productcatalog.PaymentTermType) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetPaymentTerm(*v) + } + return _u +} + +// SetInvoiceAt sets the "invoice_at" field. +func (_u *ChargeFlatFeeUpdateOne) SetInvoiceAt(v time.Time) *ChargeFlatFeeUpdateOne { + _u.mutation.SetInvoiceAt(v) + return _u +} + +// SetNillableInvoiceAt sets the "invoice_at" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableInvoiceAt(v *time.Time) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetInvoiceAt(*v) + } + return _u +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (_u *ChargeFlatFeeUpdateOne) SetIntentDeletedAt(v time.Time) *ChargeFlatFeeUpdateOne { + _u.mutation.SetIntentDeletedAt(v) + return _u +} + +// SetNillableIntentDeletedAt sets the "intent_deleted_at" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableIntentDeletedAt(v *time.Time) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetIntentDeletedAt(*v) + } + return _u +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (_u *ChargeFlatFeeUpdateOne) ClearIntentDeletedAt() *ChargeFlatFeeUpdateOne { + _u.mutation.ClearIntentDeletedAt() + return _u +} + +// SetDiscounts sets the "discounts" field. +func (_u *ChargeFlatFeeUpdateOne) SetDiscounts(v *billing.Discounts) *ChargeFlatFeeUpdateOne { + _u.mutation.SetDiscounts(v) + return _u +} + +// ClearDiscounts clears the value of the "discounts" field. +func (_u *ChargeFlatFeeUpdateOne) ClearDiscounts() *ChargeFlatFeeUpdateOne { + _u.mutation.ClearDiscounts() + return _u +} + +// SetProRating sets the "pro_rating" field. +func (_u *ChargeFlatFeeUpdateOne) SetProRating(v flatfee.ProRatingModeAdapterEnum) *ChargeFlatFeeUpdateOne { + _u.mutation.SetProRating(v) + return _u +} + +// SetNillableProRating sets the "pro_rating" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableProRating(v *flatfee.ProRatingModeAdapterEnum) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetProRating(*v) + } + return _u +} + +// SetFeatureID sets the "feature_id" field. +func (_u *ChargeFlatFeeUpdateOne) SetFeatureID(v string) *ChargeFlatFeeUpdateOne { + _u.mutation.SetFeatureID(v) + return _u +} + +// SetNillableFeatureID sets the "feature_id" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableFeatureID(v *string) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetFeatureID(*v) + } + return _u +} + +// ClearFeatureID clears the value of the "feature_id" field. +func (_u *ChargeFlatFeeUpdateOne) ClearFeatureID() *ChargeFlatFeeUpdateOne { + _u.mutation.ClearFeatureID() + return _u +} + +// SetAmountBeforeProration sets the "amount_before_proration" field. +func (_u *ChargeFlatFeeUpdateOne) SetAmountBeforeProration(v alpacadecimal.Decimal) *ChargeFlatFeeUpdateOne { + _u.mutation.SetAmountBeforeProration(v) + return _u +} + +// SetNillableAmountBeforeProration sets the "amount_before_proration" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableAmountBeforeProration(v *alpacadecimal.Decimal) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetAmountBeforeProration(*v) + } + return _u +} + +// SetAmountAfterProration sets the "amount_after_proration" field. +func (_u *ChargeFlatFeeUpdateOne) SetAmountAfterProration(v alpacadecimal.Decimal) *ChargeFlatFeeUpdateOne { + _u.mutation.SetAmountAfterProration(v) + return _u +} + +// SetNillableAmountAfterProration sets the "amount_after_proration" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableAmountAfterProration(v *alpacadecimal.Decimal) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetAmountAfterProration(*v) + } + return _u +} + +// SetCurrentRealizationRunID sets the "current_realization_run_id" field. +func (_u *ChargeFlatFeeUpdateOne) SetCurrentRealizationRunID(v string) *ChargeFlatFeeUpdateOne { + _u.mutation.SetCurrentRealizationRunID(v) + return _u +} + +// SetNillableCurrentRealizationRunID sets the "current_realization_run_id" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableCurrentRealizationRunID(v *string) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetCurrentRealizationRunID(*v) + } + return _u +} + +// ClearCurrentRealizationRunID clears the value of the "current_realization_run_id" field. +func (_u *ChargeFlatFeeUpdateOne) ClearCurrentRealizationRunID() *ChargeFlatFeeUpdateOne { + _u.mutation.ClearCurrentRealizationRunID() + return _u +} + +// SetStatusDetailed sets the "status_detailed" field. +func (_u *ChargeFlatFeeUpdateOne) SetStatusDetailed(v flatfee.Status) *ChargeFlatFeeUpdateOne { + _u.mutation.SetStatusDetailed(v) + return _u +} + +// SetNillableStatusDetailed sets the "status_detailed" field if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableStatusDetailed(v *flatfee.Status) *ChargeFlatFeeUpdateOne { + if v != nil { + _u.SetStatusDetailed(*v) + } + return _u +} + +// AddRunIDs adds the "runs" edge to the ChargeFlatFeeRun entity by IDs. +func (_u *ChargeFlatFeeUpdateOne) AddRunIDs(ids ...string) *ChargeFlatFeeUpdateOne { + _u.mutation.AddRunIDs(ids...) + return _u +} + +// AddRuns adds the "runs" edges to the ChargeFlatFeeRun entity. +func (_u *ChargeFlatFeeUpdateOne) AddRuns(v ...*ChargeFlatFeeRun) *ChargeFlatFeeUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddRunIDs(ids...) +} + +// SetCurrentRunID sets the "current_run" edge to the ChargeFlatFeeRun entity by ID. +func (_u *ChargeFlatFeeUpdateOne) SetCurrentRunID(id string) *ChargeFlatFeeUpdateOne { + _u.mutation.SetCurrentRunID(id) + return _u +} + +// SetNillableCurrentRunID sets the "current_run" edge to the ChargeFlatFeeRun entity by ID if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableCurrentRunID(id *string) *ChargeFlatFeeUpdateOne { + if id != nil { + _u = _u.SetCurrentRunID(*id) + } + return _u +} + +// SetCurrentRun sets the "current_run" edge to the ChargeFlatFeeRun entity. +func (_u *ChargeFlatFeeUpdateOne) SetCurrentRun(v *ChargeFlatFeeRun) *ChargeFlatFeeUpdateOne { + return _u.SetCurrentRunID(v.ID) +} + +// SetIntentOverrideID sets the "intent_override" edge to the ChargeFlatFeeOverride entity by ID. +func (_u *ChargeFlatFeeUpdateOne) SetIntentOverrideID(id string) *ChargeFlatFeeUpdateOne { + _u.mutation.SetIntentOverrideID(id) + return _u +} + +// SetNillableIntentOverrideID sets the "intent_override" edge to the ChargeFlatFeeOverride entity by ID if the given value is not nil. +func (_u *ChargeFlatFeeUpdateOne) SetNillableIntentOverrideID(id *string) *ChargeFlatFeeUpdateOne { + if id != nil { + _u = _u.SetIntentOverrideID(*id) + } + return _u +} + +// SetIntentOverride sets the "intent_override" edge to the ChargeFlatFeeOverride entity. +func (_u *ChargeFlatFeeUpdateOne) SetIntentOverride(v *ChargeFlatFeeOverride) *ChargeFlatFeeUpdateOne { + return _u.SetIntentOverrideID(v.ID) +} + +// SetSubscriptionItem sets the "subscription_item" edge to the SubscriptionItem entity. +func (_u *ChargeFlatFeeUpdateOne) SetSubscriptionItem(v *SubscriptionItem) *ChargeFlatFeeUpdateOne { + return _u.SetSubscriptionItemID(v.ID) +} + +// SetFeature sets the "feature" edge to the Feature entity. +func (_u *ChargeFlatFeeUpdateOne) SetFeature(v *Feature) *ChargeFlatFeeUpdateOne { + return _u.SetFeatureID(v.ID) +} + +// Mutation returns the ChargeFlatFeeMutation object of the builder. +func (_u *ChargeFlatFeeUpdateOne) Mutation() *ChargeFlatFeeMutation { + return _u.mutation +} + +// ClearRuns clears all "runs" edges to the ChargeFlatFeeRun entity. +func (_u *ChargeFlatFeeUpdateOne) ClearRuns() *ChargeFlatFeeUpdateOne { + _u.mutation.ClearRuns() + return _u +} + +// RemoveRunIDs removes the "runs" edge to ChargeFlatFeeRun entities by IDs. +func (_u *ChargeFlatFeeUpdateOne) RemoveRunIDs(ids ...string) *ChargeFlatFeeUpdateOne { + _u.mutation.RemoveRunIDs(ids...) + return _u +} + +// RemoveRuns removes "runs" edges to ChargeFlatFeeRun entities. +func (_u *ChargeFlatFeeUpdateOne) RemoveRuns(v ...*ChargeFlatFeeRun) *ChargeFlatFeeUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveRunIDs(ids...) +} + +// ClearCurrentRun clears the "current_run" edge to the ChargeFlatFeeRun entity. +func (_u *ChargeFlatFeeUpdateOne) ClearCurrentRun() *ChargeFlatFeeUpdateOne { + _u.mutation.ClearCurrentRun() + return _u +} + +// ClearIntentOverride clears the "intent_override" edge to the ChargeFlatFeeOverride entity. +func (_u *ChargeFlatFeeUpdateOne) ClearIntentOverride() *ChargeFlatFeeUpdateOne { + _u.mutation.ClearIntentOverride() + return _u +} + +// ClearSubscriptionItem clears the "subscription_item" edge to the SubscriptionItem entity. +func (_u *ChargeFlatFeeUpdateOne) ClearSubscriptionItem() *ChargeFlatFeeUpdateOne { + _u.mutation.ClearSubscriptionItem() + return _u +} + +// ClearFeature clears the "feature" edge to the Feature entity. +func (_u *ChargeFlatFeeUpdateOne) ClearFeature() *ChargeFlatFeeUpdateOne { + _u.mutation.ClearFeature() + return _u +} + +// Where appends a list predicates to the ChargeFlatFeeUpdate builder. +func (_u *ChargeFlatFeeUpdateOne) Where(ps ...predicate.ChargeFlatFee) *ChargeFlatFeeUpdateOne { + _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 *ChargeFlatFeeUpdateOne) Select(field string, fields ...string) *ChargeFlatFeeUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ChargeFlatFee entity. +func (_u *ChargeFlatFeeUpdateOne) Save(ctx context.Context) (*ChargeFlatFee, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeFlatFeeUpdateOne) SaveX(ctx context.Context) *ChargeFlatFee { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ChargeFlatFeeUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeFlatFeeUpdateOne) 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 *ChargeFlatFeeUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeflatfee.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeFlatFeeUpdateOne) check() error { + if v, ok := _u.mutation.Status(); ok { + if err := chargeflatfee.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFee.status": %w`, err)} + } + } + if v, ok := _u.mutation.PaymentTerm(); ok { + if err := chargeflatfee.PaymentTermValidator(string(v)); err != nil { + return &ValidationError{Name: "payment_term", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFee.payment_term": %w`, err)} + } + } + 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 "ChargeFlatFee.discounts": %w`, err)} + } + } + if v, ok := _u.mutation.ProRating(); ok { + if err := chargeflatfee.ProRatingValidator(v); err != nil { + return &ValidationError{Name: "pro_rating", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFee.pro_rating": %w`, err)} + } + } + if v, ok := _u.mutation.StatusDetailed(); ok { + if err := chargeflatfee.StatusDetailedValidator(v); err != nil { + return &ValidationError{Name: "status_detailed", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFee.status_detailed": %w`, err)} + } + } + if _u.mutation.CustomerCleared() && len(_u.mutation.CustomerIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeFlatFee.customer"`) + } + if _u.mutation.TaxCodeCleared() && len(_u.mutation.TaxCodeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeFlatFee.tax_code"`) + } + return nil +} + +func (_u *ChargeFlatFeeUpdateOne) sqlSave(ctx context.Context) (_node *ChargeFlatFee, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeflatfee.Table, chargeflatfee.Columns, sqlgraph.NewFieldSpec(chargeflatfee.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "ChargeFlatFee.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, chargeflatfee.FieldID) + for _, f := range fields { + if !chargeflatfee.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != chargeflatfee.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(chargeflatfee.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeflatfee.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.BillingPeriodFrom(); ok { + _spec.SetField(chargeflatfee.FieldBillingPeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.BillingPeriodTo(); ok { + _spec.SetField(chargeflatfee.FieldBillingPeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.FullServicePeriodFrom(); ok { + _spec.SetField(chargeflatfee.FieldFullServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.FullServicePeriodTo(); ok { + _spec.SetField(chargeflatfee.FieldFullServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(chargeflatfee.FieldStatus, field.TypeEnum, value) + } + if _u.mutation.UniqueReferenceIDCleared() { + _spec.ClearField(chargeflatfee.FieldUniqueReferenceID, field.TypeString) + } + if value, ok := _u.mutation.AdvanceAfter(); ok { + _spec.SetField(chargeflatfee.FieldAdvanceAfter, field.TypeTime, value) + } + if _u.mutation.AdvanceAfterCleared() { + _spec.ClearField(chargeflatfee.FieldAdvanceAfter, field.TypeTime) + } + if _u.mutation.TaxBehaviorCleared() { + _spec.ClearField(chargeflatfee.FieldTaxBehavior, field.TypeEnum) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargeflatfee.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargeflatfee.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(chargeflatfee.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(chargeflatfee.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeflatfee.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeflatfee.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeflatfee.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(chargeflatfee.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(chargeflatfee.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(chargeflatfee.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.PaymentTerm(); ok { + _spec.SetField(chargeflatfee.FieldPaymentTerm, field.TypeString, value) + } + if value, ok := _u.mutation.InvoiceAt(); ok { + _spec.SetField(chargeflatfee.FieldInvoiceAt, field.TypeTime, value) + } + if value, ok := _u.mutation.IntentDeletedAt(); ok { + _spec.SetField(chargeflatfee.FieldIntentDeletedAt, field.TypeTime, value) + } + if _u.mutation.IntentDeletedAtCleared() { + _spec.ClearField(chargeflatfee.FieldIntentDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Discounts(); ok { + vv, err := chargeflatfee.ValueScanner.Discounts.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(chargeflatfee.FieldDiscounts, field.TypeString, vv) + } + if _u.mutation.DiscountsCleared() { + _spec.ClearField(chargeflatfee.FieldDiscounts, field.TypeString) + } + if value, ok := _u.mutation.ProRating(); ok { + _spec.SetField(chargeflatfee.FieldProRating, field.TypeEnum, value) + } + if _u.mutation.FeatureKeyCleared() { + _spec.ClearField(chargeflatfee.FieldFeatureKey, field.TypeString) + } + if value, ok := _u.mutation.AmountBeforeProration(); ok { + _spec.SetField(chargeflatfee.FieldAmountBeforeProration, field.TypeOther, value) + } + if value, ok := _u.mutation.AmountAfterProration(); ok { + _spec.SetField(chargeflatfee.FieldAmountAfterProration, field.TypeOther, value) + } + if value, ok := _u.mutation.StatusDetailed(); ok { + _spec.SetField(chargeflatfee.FieldStatusDetailed, field.TypeEnum, value) + } + if _u.mutation.RunsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeflatfee.RunsTable, + Columns: []string{chargeflatfee.RunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerun.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: chargeflatfee.RunsTable, + Columns: []string{chargeflatfee.RunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerun.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: chargeflatfee.RunsTable, + Columns: []string{chargeflatfee.RunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerun.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.CurrentRunCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: chargeflatfee.CurrentRunTable, + Columns: []string{chargeflatfee.CurrentRunColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerun.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.CurrentRunIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: chargeflatfee.CurrentRunTable, + Columns: []string{chargeflatfee.CurrentRunColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerun.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.IntentOverrideCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeflatfee.IntentOverrideTable, + Columns: []string{chargeflatfee.IntentOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeoverride.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.IntentOverrideIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeflatfee.IntentOverrideTable, + Columns: []string{chargeflatfee.IntentOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeoverride.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.SubscriptionItemCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfee.SubscriptionItemTable, + Columns: []string{chargeflatfee.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.SubscriptionItemIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfee.SubscriptionItemTable, + Columns: []string{chargeflatfee.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.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.FeatureCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfee.FeatureTable, + Columns: []string{chargeflatfee.FeatureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbfeature.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.FeatureIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfee.FeatureTable, + Columns: []string{chargeflatfee.FeatureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbfeature.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &ChargeFlatFee{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{chargeflatfee.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/ent/db/chargeflatfeeoverride.go b/ent/db/chargeflatfeeoverride.go new file mode 100644 index 0000000000000000000000000000000000000000..e8dab7975f1566c48fa2f8137304ff962efb0758 --- /dev/null +++ b/ent/db/chargeflatfeeoverride.go @@ -0,0 +1,415 @@ +// 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" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeoverride" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeFlatFeeOverride is the model entity for the ChargeFlatFeeOverride schema. +type ChargeFlatFeeOverride 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"` + // ChargeID holds the value of the "charge_id" field. + ChargeID string `json:"charge_id,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Description holds the value of the "description" field. + Description *string `json:"description,omitempty"` + // Metadata holds the value of the "metadata" field. + Metadata *models.Metadata `json:"metadata,omitempty"` + // TaxBehavior holds the value of the "tax_behavior" field. + // + // Deprecated: tax config overrides are not supported; use the base charge intent + TaxBehavior *productcatalog.TaxBehavior `json:"tax_behavior,omitempty"` + // TaxCodeID holds the value of the "tax_code_id" field. + // + // Deprecated: tax config overrides are not supported; use the base charge intent + TaxCodeID *string `json:"tax_code_id,omitempty"` + // IntentDeletedAt holds the value of the "intent_deleted_at" field. + IntentDeletedAt *time.Time `json:"intent_deleted_at,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"` + // FullServicePeriodFrom holds the value of the "full_service_period_from" field. + FullServicePeriodFrom time.Time `json:"full_service_period_from,omitempty"` + // FullServicePeriodTo holds the value of the "full_service_period_to" field. + FullServicePeriodTo time.Time `json:"full_service_period_to,omitempty"` + // BillingPeriodFrom holds the value of the "billing_period_from" field. + BillingPeriodFrom time.Time `json:"billing_period_from,omitempty"` + // BillingPeriodTo holds the value of the "billing_period_to" field. + BillingPeriodTo time.Time `json:"billing_period_to,omitempty"` + // InvoiceAt holds the value of the "invoice_at" field. + InvoiceAt time.Time `json:"invoice_at,omitempty"` + // FeatureKey holds the value of the "feature_key" field. + // + // Deprecated: feature key overrides are not supported; use the base flat-fee charge intent + FeatureKey *string `json:"feature_key,omitempty"` + // PaymentTerm holds the value of the "payment_term" field. + PaymentTerm productcatalog.PaymentTermType `json:"payment_term,omitempty"` + // ProRating holds the value of the "pro_rating" field. + ProRating *productcatalog.ProRatingConfig `json:"pro_rating,omitempty"` + // AmountBeforeProration holds the value of the "amount_before_proration" field. + AmountBeforeProration alpacadecimal.Decimal `json:"amount_before_proration,omitempty"` + // Discounts holds the value of the "discounts" field. + Discounts *billing.Discounts `json:"discounts,omitempty"` + // PercentageDiscounts holds the value of the "percentage_discounts" field. + // + // Deprecated: use discounts + PercentageDiscounts *billing.PercentageDiscount `json:"percentage_discounts,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ChargeFlatFeeOverrideQuery when eager-loading is set. + Edges ChargeFlatFeeOverrideEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ChargeFlatFeeOverrideEdges holds the relations/edges for other nodes in the graph. +type ChargeFlatFeeOverrideEdges struct { + // FlatFee holds the value of the flat_fee edge. + FlatFee *ChargeFlatFee `json:"flat_fee,omitempty"` + // TaxCode holds the value of the tax_code edge. + TaxCode *TaxCode `json:"tax_code,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// FlatFeeOrErr returns the FlatFee value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeFlatFeeOverrideEdges) FlatFeeOrErr() (*ChargeFlatFee, error) { + if e.FlatFee != nil { + return e.FlatFee, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: chargeflatfee.Label} + } + return nil, &NotLoadedError{edge: "flat_fee"} +} + +// TaxCodeOrErr returns the TaxCode value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeFlatFeeOverrideEdges) TaxCodeOrErr() (*TaxCode, error) { + if e.TaxCode != nil { + return e.TaxCode, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: dbtaxcode.Label} + } + return nil, &NotLoadedError{edge: "tax_code"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ChargeFlatFeeOverride) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case chargeflatfeeoverride.FieldAmountBeforeProration: + values[i] = new(alpacadecimal.Decimal) + case chargeflatfeeoverride.FieldID, chargeflatfeeoverride.FieldNamespace, chargeflatfeeoverride.FieldChargeID, chargeflatfeeoverride.FieldName, chargeflatfeeoverride.FieldDescription, chargeflatfeeoverride.FieldTaxBehavior, chargeflatfeeoverride.FieldTaxCodeID, chargeflatfeeoverride.FieldFeatureKey, chargeflatfeeoverride.FieldPaymentTerm: + values[i] = new(sql.NullString) + case chargeflatfeeoverride.FieldIntentDeletedAt, chargeflatfeeoverride.FieldServicePeriodFrom, chargeflatfeeoverride.FieldServicePeriodTo, chargeflatfeeoverride.FieldFullServicePeriodFrom, chargeflatfeeoverride.FieldFullServicePeriodTo, chargeflatfeeoverride.FieldBillingPeriodFrom, chargeflatfeeoverride.FieldBillingPeriodTo, chargeflatfeeoverride.FieldInvoiceAt: + values[i] = new(sql.NullTime) + case chargeflatfeeoverride.FieldMetadata: + values[i] = chargeflatfeeoverride.ValueScanner.Metadata.ScanValue() + case chargeflatfeeoverride.FieldProRating: + values[i] = chargeflatfeeoverride.ValueScanner.ProRating.ScanValue() + case chargeflatfeeoverride.FieldDiscounts: + values[i] = chargeflatfeeoverride.ValueScanner.Discounts.ScanValue() + case chargeflatfeeoverride.FieldPercentageDiscounts: + values[i] = chargeflatfeeoverride.ValueScanner.PercentageDiscounts.ScanValue() + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the ChargeFlatFeeOverride fields. +func (_m *ChargeFlatFeeOverride) 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 chargeflatfeeoverride.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 chargeflatfeeoverride.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 chargeflatfeeoverride.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 chargeflatfeeoverride.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case chargeflatfeeoverride.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + _m.Description = new(string) + *_m.Description = value.String + } + case chargeflatfeeoverride.FieldMetadata: + if value, err := chargeflatfeeoverride.ValueScanner.Metadata.FromValue(values[i]); err != nil { + return err + } else { + _m.Metadata = value + } + case chargeflatfeeoverride.FieldTaxBehavior: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field tax_behavior", values[i]) + } else if value.Valid { + _m.TaxBehavior = new(productcatalog.TaxBehavior) + *_m.TaxBehavior = productcatalog.TaxBehavior(value.String) + } + case chargeflatfeeoverride.FieldTaxCodeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field tax_code_id", values[i]) + } else if value.Valid { + _m.TaxCodeID = new(string) + *_m.TaxCodeID = value.String + } + case chargeflatfeeoverride.FieldIntentDeletedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field intent_deleted_at", values[i]) + } else if value.Valid { + _m.IntentDeletedAt = new(time.Time) + *_m.IntentDeletedAt = value.Time + } + case chargeflatfeeoverride.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 chargeflatfeeoverride.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 chargeflatfeeoverride.FieldFullServicePeriodFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field full_service_period_from", values[i]) + } else if value.Valid { + _m.FullServicePeriodFrom = value.Time + } + case chargeflatfeeoverride.FieldFullServicePeriodTo: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field full_service_period_to", values[i]) + } else if value.Valid { + _m.FullServicePeriodTo = value.Time + } + case chargeflatfeeoverride.FieldBillingPeriodFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field billing_period_from", values[i]) + } else if value.Valid { + _m.BillingPeriodFrom = value.Time + } + case chargeflatfeeoverride.FieldBillingPeriodTo: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field billing_period_to", values[i]) + } else if value.Valid { + _m.BillingPeriodTo = value.Time + } + case chargeflatfeeoverride.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 chargeflatfeeoverride.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 = new(string) + *_m.FeatureKey = value.String + } + case chargeflatfeeoverride.FieldPaymentTerm: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field payment_term", values[i]) + } else if value.Valid { + _m.PaymentTerm = productcatalog.PaymentTermType(value.String) + } + case chargeflatfeeoverride.FieldProRating: + if value, err := chargeflatfeeoverride.ValueScanner.ProRating.FromValue(values[i]); err != nil { + return err + } else { + _m.ProRating = value + } + case chargeflatfeeoverride.FieldAmountBeforeProration: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field amount_before_proration", values[i]) + } else if value != nil { + _m.AmountBeforeProration = *value + } + case chargeflatfeeoverride.FieldDiscounts: + if value, err := chargeflatfeeoverride.ValueScanner.Discounts.FromValue(values[i]); err != nil { + return err + } else { + _m.Discounts = value + } + case chargeflatfeeoverride.FieldPercentageDiscounts: + if value, err := chargeflatfeeoverride.ValueScanner.PercentageDiscounts.FromValue(values[i]); err != nil { + return err + } else { + _m.PercentageDiscounts = value + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the ChargeFlatFeeOverride. +// This includes values selected through modifiers, order, etc. +func (_m *ChargeFlatFeeOverride) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryFlatFee queries the "flat_fee" edge of the ChargeFlatFeeOverride entity. +func (_m *ChargeFlatFeeOverride) QueryFlatFee() *ChargeFlatFeeQuery { + return NewChargeFlatFeeOverrideClient(_m.config).QueryFlatFee(_m) +} + +// QueryTaxCode queries the "tax_code" edge of the ChargeFlatFeeOverride entity. +func (_m *ChargeFlatFeeOverride) QueryTaxCode() *TaxCodeQuery { + return NewChargeFlatFeeOverrideClient(_m.config).QueryTaxCode(_m) +} + +// Update returns a builder for updating this ChargeFlatFeeOverride. +// Note that you need to call ChargeFlatFeeOverride.Unwrap() before calling this method if this ChargeFlatFeeOverride +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ChargeFlatFeeOverride) Update() *ChargeFlatFeeOverrideUpdateOne { + return NewChargeFlatFeeOverrideClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverride) Unwrap() *ChargeFlatFeeOverride { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: ChargeFlatFeeOverride is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ChargeFlatFeeOverride) String() string { + var builder strings.Builder + builder.WriteString("ChargeFlatFeeOverride(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("charge_id=") + builder.WriteString(_m.ChargeID) + builder.WriteString(", ") + builder.WriteString("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + if v := _m.Description; v != nil { + builder.WriteString("description=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.Metadata; v != nil { + builder.WriteString("metadata=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.TaxBehavior; v != nil { + builder.WriteString("tax_behavior=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.TaxCodeID; v != nil { + builder.WriteString("tax_code_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.IntentDeletedAt; v != nil { + builder.WriteString("intent_deleted_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + 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("full_service_period_from=") + builder.WriteString(_m.FullServicePeriodFrom.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("full_service_period_to=") + builder.WriteString(_m.FullServicePeriodTo.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("billing_period_from=") + builder.WriteString(_m.BillingPeriodFrom.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("billing_period_to=") + builder.WriteString(_m.BillingPeriodTo.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("invoice_at=") + builder.WriteString(_m.InvoiceAt.Format(time.ANSIC)) + builder.WriteString(", ") + if v := _m.FeatureKey; v != nil { + builder.WriteString("feature_key=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("payment_term=") + builder.WriteString(fmt.Sprintf("%v", _m.PaymentTerm)) + builder.WriteString(", ") + builder.WriteString("pro_rating=") + builder.WriteString(fmt.Sprintf("%v", _m.ProRating)) + builder.WriteString(", ") + builder.WriteString("amount_before_proration=") + builder.WriteString(fmt.Sprintf("%v", _m.AmountBeforeProration)) + builder.WriteString(", ") + if v := _m.Discounts; v != nil { + builder.WriteString("discounts=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.PercentageDiscounts; v != nil { + builder.WriteString("percentage_discounts=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteByte(')') + return builder.String() +} + +// ChargeFlatFeeOverrides is a parsable slice of ChargeFlatFeeOverride. +type ChargeFlatFeeOverrides []*ChargeFlatFeeOverride diff --git a/ent/db/chargeflatfeeoverride/chargeflatfeeoverride.go b/ent/db/chargeflatfeeoverride/chargeflatfeeoverride.go new file mode 100644 index 0000000000000000000000000000000000000000..65e0d2d63a9592f8ae2964a8482143c6f2871c96 --- /dev/null +++ b/ent/db/chargeflatfeeoverride/chargeflatfeeoverride.go @@ -0,0 +1,279 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeflatfeeoverride + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/models" +) + +const ( + // Label holds the string label denoting the chargeflatfeeoverride type in the database. + Label = "charge_flat_fee_override" + // 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" + // FieldChargeID holds the string denoting the charge_id field in the database. + FieldChargeID = "charge_id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // FieldTaxBehavior holds the string denoting the tax_behavior field in the database. + FieldTaxBehavior = "tax_behavior" + // FieldTaxCodeID holds the string denoting the tax_code_id field in the database. + FieldTaxCodeID = "tax_code_id" + // FieldIntentDeletedAt holds the string denoting the intent_deleted_at field in the database. + FieldIntentDeletedAt = "intent_deleted_at" + // 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" + // FieldFullServicePeriodFrom holds the string denoting the full_service_period_from field in the database. + FieldFullServicePeriodFrom = "full_service_period_from" + // FieldFullServicePeriodTo holds the string denoting the full_service_period_to field in the database. + FieldFullServicePeriodTo = "full_service_period_to" + // FieldBillingPeriodFrom holds the string denoting the billing_period_from field in the database. + FieldBillingPeriodFrom = "billing_period_from" + // FieldBillingPeriodTo holds the string denoting the billing_period_to field in the database. + FieldBillingPeriodTo = "billing_period_to" + // FieldInvoiceAt holds the string denoting the invoice_at field in the database. + FieldInvoiceAt = "invoice_at" + // FieldFeatureKey holds the string denoting the feature_key field in the database. + FieldFeatureKey = "feature_key" + // FieldPaymentTerm holds the string denoting the payment_term field in the database. + FieldPaymentTerm = "payment_term" + // FieldProRating holds the string denoting the pro_rating field in the database. + FieldProRating = "pro_rating" + // FieldAmountBeforeProration holds the string denoting the amount_before_proration field in the database. + FieldAmountBeforeProration = "amount_before_proration" + // FieldDiscounts holds the string denoting the discounts field in the database. + FieldDiscounts = "discounts" + // FieldPercentageDiscounts holds the string denoting the percentage_discounts field in the database. + FieldPercentageDiscounts = "percentage_discounts" + // EdgeFlatFee holds the string denoting the flat_fee edge name in mutations. + EdgeFlatFee = "flat_fee" + // EdgeTaxCode holds the string denoting the tax_code edge name in mutations. + EdgeTaxCode = "tax_code" + // Table holds the table name of the chargeflatfeeoverride in the database. + Table = "charge_flat_fee_overrides" + // FlatFeeTable is the table that holds the flat_fee relation/edge. + FlatFeeTable = "charge_flat_fee_overrides" + // FlatFeeInverseTable is the table name for the ChargeFlatFee entity. + // It exists in this package in order to avoid circular dependency with the "chargeflatfee" package. + FlatFeeInverseTable = "charge_flat_fees" + // FlatFeeColumn is the table column denoting the flat_fee relation/edge. + FlatFeeColumn = "charge_id" + // TaxCodeTable is the table that holds the tax_code relation/edge. + TaxCodeTable = "charge_flat_fee_overrides" + // TaxCodeInverseTable is the table name for the TaxCode entity. + // It exists in this package in order to avoid circular dependency with the "dbtaxcode" package. + TaxCodeInverseTable = "tax_codes" + // TaxCodeColumn is the table column denoting the tax_code relation/edge. + TaxCodeColumn = "tax_code_id" +) + +// Columns holds all SQL columns for chargeflatfeeoverride fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldChargeID, + FieldName, + FieldDescription, + FieldMetadata, + FieldIntentDeletedAt, + FieldServicePeriodFrom, + FieldServicePeriodTo, + FieldFullServicePeriodFrom, + FieldFullServicePeriodTo, + FieldBillingPeriodFrom, + FieldBillingPeriodTo, + FieldInvoiceAt, + FieldPaymentTerm, + FieldProRating, + FieldAmountBeforeProration, + FieldDiscounts, +} + +// 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 + } + } + for _, f := range [...]string{FieldTaxBehavior, FieldTaxCodeID, FieldFeatureKey, FieldPercentageDiscounts} { + if column == f { + 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 + // NameValidator is a validator for the "name" field. It is called by the builders before save. + NameValidator func(string) error + // FeatureKeyValidator is a validator for the "feature_key" field. It is called by the builders before save. + FeatureKeyValidator func(string) error + // PaymentTermValidator is a validator for the "payment_term" field. It is called by the builders before save. + PaymentTermValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string + // ValueScanner of all ChargeFlatFeeOverride fields. + ValueScanner struct { + Metadata field.TypeValueScanner[*models.Metadata] + ProRating field.TypeValueScanner[*productcatalog.ProRatingConfig] + Discounts field.TypeValueScanner[*billing.Discounts] + PercentageDiscounts field.TypeValueScanner[*billing.PercentageDiscount] + } +) + +// OrderOption defines the ordering options for the ChargeFlatFeeOverride 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() +} + +// ByChargeID orders the results by the charge_id field. +func ByChargeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChargeID, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, opts...).ToFunc() +} + +// ByMetadata orders the results by the metadata field. +func ByMetadata(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMetadata, opts...).ToFunc() +} + +// ByTaxBehavior orders the results by the tax_behavior field. +func ByTaxBehavior(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxBehavior, opts...).ToFunc() +} + +// ByTaxCodeID orders the results by the tax_code_id field. +func ByTaxCodeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxCodeID, opts...).ToFunc() +} + +// ByIntentDeletedAt orders the results by the intent_deleted_at field. +func ByIntentDeletedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIntentDeletedAt, 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() +} + +// ByFullServicePeriodFrom orders the results by the full_service_period_from field. +func ByFullServicePeriodFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFullServicePeriodFrom, opts...).ToFunc() +} + +// ByFullServicePeriodTo orders the results by the full_service_period_to field. +func ByFullServicePeriodTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFullServicePeriodTo, opts...).ToFunc() +} + +// ByBillingPeriodFrom orders the results by the billing_period_from field. +func ByBillingPeriodFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBillingPeriodFrom, opts...).ToFunc() +} + +// ByBillingPeriodTo orders the results by the billing_period_to field. +func ByBillingPeriodTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBillingPeriodTo, opts...).ToFunc() +} + +// ByInvoiceAt orders the results by the invoice_at field. +func ByInvoiceAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoiceAt, opts...).ToFunc() +} + +// ByFeatureKey orders the results by the feature_key field. +func ByFeatureKey(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFeatureKey, opts...).ToFunc() +} + +// ByPaymentTerm orders the results by the payment_term field. +func ByPaymentTerm(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPaymentTerm, opts...).ToFunc() +} + +// ByProRating orders the results by the pro_rating field. +func ByProRating(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldProRating, opts...).ToFunc() +} + +// ByAmountBeforeProration orders the results by the amount_before_proration field. +func ByAmountBeforeProration(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAmountBeforeProration, opts...).ToFunc() +} + +// ByDiscounts orders the results by the discounts field. +func ByDiscounts(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDiscounts, opts...).ToFunc() +} + +// ByPercentageDiscounts orders the results by the percentage_discounts field. +func ByPercentageDiscounts(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPercentageDiscounts, opts...).ToFunc() +} + +// ByFlatFeeField orders the results by flat_fee field. +func ByFlatFeeField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newFlatFeeStep(), sql.OrderByField(field, opts...)) + } +} + +// ByTaxCodeField orders the results by tax_code field. +func ByTaxCodeField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTaxCodeStep(), sql.OrderByField(field, opts...)) + } +} +func newFlatFeeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(FlatFeeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, FlatFeeTable, FlatFeeColumn), + ) +} +func newTaxCodeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TaxCodeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, TaxCodeTable, TaxCodeColumn), + ) +} diff --git a/ent/db/chargeflatfeeoverride/where.go b/ent/db/chargeflatfeeoverride/where.go new file mode 100644 index 0000000000000000000000000000000000000000..2dfa5fce6a3f50ee829e83b6338d9092bf9dd986 --- /dev/null +++ b/ent/db/chargeflatfeeoverride/where.go @@ -0,0 +1,1214 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeflatfeeoverride + +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" + "github.com/openmeterio/openmeter/openmeter/productcatalog" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldNamespace, v)) +} + +// ChargeID applies equality check predicate on the "charge_id" field. It's identical to ChargeIDEQ. +func ChargeID(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldChargeID, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldName, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldDescription, v)) +} + +// TaxBehavior applies equality check predicate on the "tax_behavior" field. It's identical to TaxBehaviorEQ. +func TaxBehavior(v productcatalog.TaxBehavior) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldTaxBehavior, vc)) +} + +// TaxCodeID applies equality check predicate on the "tax_code_id" field. It's identical to TaxCodeIDEQ. +func TaxCodeID(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldTaxCodeID, v)) +} + +// IntentDeletedAt applies equality check predicate on the "intent_deleted_at" field. It's identical to IntentDeletedAtEQ. +func IntentDeletedAt(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldIntentDeletedAt, v)) +} + +// ServicePeriodFrom applies equality check predicate on the "service_period_from" field. It's identical to ServicePeriodFromEQ. +func ServicePeriodFrom(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(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.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// FullServicePeriodFrom applies equality check predicate on the "full_service_period_from" field. It's identical to FullServicePeriodFromEQ. +func FullServicePeriodFrom(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodTo applies equality check predicate on the "full_service_period_to" field. It's identical to FullServicePeriodToEQ. +func FullServicePeriodTo(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldFullServicePeriodTo, v)) +} + +// BillingPeriodFrom applies equality check predicate on the "billing_period_from" field. It's identical to BillingPeriodFromEQ. +func BillingPeriodFrom(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodTo applies equality check predicate on the "billing_period_to" field. It's identical to BillingPeriodToEQ. +func BillingPeriodTo(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldBillingPeriodTo, v)) +} + +// InvoiceAt applies equality check predicate on the "invoice_at" field. It's identical to InvoiceAtEQ. +func InvoiceAt(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldInvoiceAt, v)) +} + +// FeatureKey applies equality check predicate on the "feature_key" field. It's identical to FeatureKeyEQ. +func FeatureKey(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldFeatureKey, v)) +} + +// PaymentTerm applies equality check predicate on the "payment_term" field. It's identical to PaymentTermEQ. +func PaymentTerm(v productcatalog.PaymentTermType) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldPaymentTerm, vc)) +} + +// AmountBeforeProration applies equality check predicate on the "amount_before_proration" field. It's identical to AmountBeforeProrationEQ. +func AmountBeforeProration(v alpacadecimal.Decimal) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldAmountBeforeProration, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldContainsFold(FieldNamespace, v)) +} + +// ChargeIDEQ applies the EQ predicate on the "charge_id" field. +func ChargeIDEQ(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldChargeID, v)) +} + +// ChargeIDNEQ applies the NEQ predicate on the "charge_id" field. +func ChargeIDNEQ(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNEQ(FieldChargeID, v)) +} + +// ChargeIDIn applies the In predicate on the "charge_id" field. +func ChargeIDIn(vs ...string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIn(FieldChargeID, vs...)) +} + +// ChargeIDNotIn applies the NotIn predicate on the "charge_id" field. +func ChargeIDNotIn(vs ...string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotIn(FieldChargeID, vs...)) +} + +// ChargeIDGT applies the GT predicate on the "charge_id" field. +func ChargeIDGT(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGT(FieldChargeID, v)) +} + +// ChargeIDGTE applies the GTE predicate on the "charge_id" field. +func ChargeIDGTE(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGTE(FieldChargeID, v)) +} + +// ChargeIDLT applies the LT predicate on the "charge_id" field. +func ChargeIDLT(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLT(FieldChargeID, v)) +} + +// ChargeIDLTE applies the LTE predicate on the "charge_id" field. +func ChargeIDLTE(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLTE(FieldChargeID, v)) +} + +// ChargeIDContains applies the Contains predicate on the "charge_id" field. +func ChargeIDContains(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldContains(FieldChargeID, v)) +} + +// ChargeIDHasPrefix applies the HasPrefix predicate on the "charge_id" field. +func ChargeIDHasPrefix(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldHasPrefix(FieldChargeID, v)) +} + +// ChargeIDHasSuffix applies the HasSuffix predicate on the "charge_id" field. +func ChargeIDHasSuffix(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldHasSuffix(FieldChargeID, v)) +} + +// ChargeIDEqualFold applies the EqualFold predicate on the "charge_id" field. +func ChargeIDEqualFold(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEqualFold(FieldChargeID, v)) +} + +// ChargeIDContainsFold applies the ContainsFold predicate on the "charge_id" field. +func ChargeIDContainsFold(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldContainsFold(FieldChargeID, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldContainsFold(FieldName, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldContainsFold(FieldDescription, v)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotNull(FieldMetadata)) +} + +// TaxBehaviorEQ applies the EQ predicate on the "tax_behavior" field. +func TaxBehaviorEQ(v productcatalog.TaxBehavior) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldTaxBehavior, vc)) +} + +// TaxBehaviorNEQ applies the NEQ predicate on the "tax_behavior" field. +func TaxBehaviorNEQ(v productcatalog.TaxBehavior) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldNEQ(FieldTaxBehavior, vc)) +} + +// TaxBehaviorIn applies the In predicate on the "tax_behavior" field. +func TaxBehaviorIn(vs ...productcatalog.TaxBehavior) predicate.ChargeFlatFeeOverride { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargeFlatFeeOverride(sql.FieldIn(FieldTaxBehavior, v...)) +} + +// TaxBehaviorNotIn applies the NotIn predicate on the "tax_behavior" field. +func TaxBehaviorNotIn(vs ...productcatalog.TaxBehavior) predicate.ChargeFlatFeeOverride { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargeFlatFeeOverride(sql.FieldNotIn(FieldTaxBehavior, v...)) +} + +// TaxBehaviorGT applies the GT predicate on the "tax_behavior" field. +func TaxBehaviorGT(v productcatalog.TaxBehavior) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldGT(FieldTaxBehavior, vc)) +} + +// TaxBehaviorGTE applies the GTE predicate on the "tax_behavior" field. +func TaxBehaviorGTE(v productcatalog.TaxBehavior) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldGTE(FieldTaxBehavior, vc)) +} + +// TaxBehaviorLT applies the LT predicate on the "tax_behavior" field. +func TaxBehaviorLT(v productcatalog.TaxBehavior) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldLT(FieldTaxBehavior, vc)) +} + +// TaxBehaviorLTE applies the LTE predicate on the "tax_behavior" field. +func TaxBehaviorLTE(v productcatalog.TaxBehavior) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldLTE(FieldTaxBehavior, vc)) +} + +// TaxBehaviorContains applies the Contains predicate on the "tax_behavior" field. +func TaxBehaviorContains(v productcatalog.TaxBehavior) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldContains(FieldTaxBehavior, vc)) +} + +// TaxBehaviorHasPrefix applies the HasPrefix predicate on the "tax_behavior" field. +func TaxBehaviorHasPrefix(v productcatalog.TaxBehavior) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldHasPrefix(FieldTaxBehavior, vc)) +} + +// TaxBehaviorHasSuffix applies the HasSuffix predicate on the "tax_behavior" field. +func TaxBehaviorHasSuffix(v productcatalog.TaxBehavior) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldHasSuffix(FieldTaxBehavior, vc)) +} + +// TaxBehaviorIsNil applies the IsNil predicate on the "tax_behavior" field. +func TaxBehaviorIsNil() predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIsNull(FieldTaxBehavior)) +} + +// TaxBehaviorNotNil applies the NotNil predicate on the "tax_behavior" field. +func TaxBehaviorNotNil() predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotNull(FieldTaxBehavior)) +} + +// TaxBehaviorEqualFold applies the EqualFold predicate on the "tax_behavior" field. +func TaxBehaviorEqualFold(v productcatalog.TaxBehavior) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldEqualFold(FieldTaxBehavior, vc)) +} + +// TaxBehaviorContainsFold applies the ContainsFold predicate on the "tax_behavior" field. +func TaxBehaviorContainsFold(v productcatalog.TaxBehavior) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldContainsFold(FieldTaxBehavior, vc)) +} + +// TaxCodeIDEQ applies the EQ predicate on the "tax_code_id" field. +func TaxCodeIDEQ(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldTaxCodeID, v)) +} + +// TaxCodeIDNEQ applies the NEQ predicate on the "tax_code_id" field. +func TaxCodeIDNEQ(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNEQ(FieldTaxCodeID, v)) +} + +// TaxCodeIDIn applies the In predicate on the "tax_code_id" field. +func TaxCodeIDIn(vs ...string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIn(FieldTaxCodeID, vs...)) +} + +// TaxCodeIDNotIn applies the NotIn predicate on the "tax_code_id" field. +func TaxCodeIDNotIn(vs ...string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotIn(FieldTaxCodeID, vs...)) +} + +// TaxCodeIDGT applies the GT predicate on the "tax_code_id" field. +func TaxCodeIDGT(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGT(FieldTaxCodeID, v)) +} + +// TaxCodeIDGTE applies the GTE predicate on the "tax_code_id" field. +func TaxCodeIDGTE(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGTE(FieldTaxCodeID, v)) +} + +// TaxCodeIDLT applies the LT predicate on the "tax_code_id" field. +func TaxCodeIDLT(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLT(FieldTaxCodeID, v)) +} + +// TaxCodeIDLTE applies the LTE predicate on the "tax_code_id" field. +func TaxCodeIDLTE(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLTE(FieldTaxCodeID, v)) +} + +// TaxCodeIDContains applies the Contains predicate on the "tax_code_id" field. +func TaxCodeIDContains(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldContains(FieldTaxCodeID, v)) +} + +// TaxCodeIDHasPrefix applies the HasPrefix predicate on the "tax_code_id" field. +func TaxCodeIDHasPrefix(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldHasPrefix(FieldTaxCodeID, v)) +} + +// TaxCodeIDHasSuffix applies the HasSuffix predicate on the "tax_code_id" field. +func TaxCodeIDHasSuffix(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldHasSuffix(FieldTaxCodeID, v)) +} + +// TaxCodeIDIsNil applies the IsNil predicate on the "tax_code_id" field. +func TaxCodeIDIsNil() predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIsNull(FieldTaxCodeID)) +} + +// TaxCodeIDNotNil applies the NotNil predicate on the "tax_code_id" field. +func TaxCodeIDNotNil() predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotNull(FieldTaxCodeID)) +} + +// TaxCodeIDEqualFold applies the EqualFold predicate on the "tax_code_id" field. +func TaxCodeIDEqualFold(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEqualFold(FieldTaxCodeID, v)) +} + +// TaxCodeIDContainsFold applies the ContainsFold predicate on the "tax_code_id" field. +func TaxCodeIDContainsFold(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldContainsFold(FieldTaxCodeID, v)) +} + +// IntentDeletedAtEQ applies the EQ predicate on the "intent_deleted_at" field. +func IntentDeletedAtEQ(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtNEQ applies the NEQ predicate on the "intent_deleted_at" field. +func IntentDeletedAtNEQ(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNEQ(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtIn applies the In predicate on the "intent_deleted_at" field. +func IntentDeletedAtIn(vs ...time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIn(FieldIntentDeletedAt, vs...)) +} + +// IntentDeletedAtNotIn applies the NotIn predicate on the "intent_deleted_at" field. +func IntentDeletedAtNotIn(vs ...time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotIn(FieldIntentDeletedAt, vs...)) +} + +// IntentDeletedAtGT applies the GT predicate on the "intent_deleted_at" field. +func IntentDeletedAtGT(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGT(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtGTE applies the GTE predicate on the "intent_deleted_at" field. +func IntentDeletedAtGTE(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGTE(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtLT applies the LT predicate on the "intent_deleted_at" field. +func IntentDeletedAtLT(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLT(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtLTE applies the LTE predicate on the "intent_deleted_at" field. +func IntentDeletedAtLTE(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLTE(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtIsNil applies the IsNil predicate on the "intent_deleted_at" field. +func IntentDeletedAtIsNil() predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIsNull(FieldIntentDeletedAt)) +} + +// IntentDeletedAtNotNil applies the NotNil predicate on the "intent_deleted_at" field. +func IntentDeletedAtNotNil() predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotNull(FieldIntentDeletedAt)) +} + +// ServicePeriodFromEQ applies the EQ predicate on the "service_period_from" field. +func ServicePeriodFromEQ(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromNEQ applies the NEQ predicate on the "service_period_from" field. +func ServicePeriodFromNEQ(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromIn applies the In predicate on the "service_period_from" field. +func ServicePeriodFromIn(vs ...time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromNotIn applies the NotIn predicate on the "service_period_from" field. +func ServicePeriodFromNotIn(vs ...time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromGT applies the GT predicate on the "service_period_from" field. +func ServicePeriodFromGT(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromGTE applies the GTE predicate on the "service_period_from" field. +func ServicePeriodFromGTE(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLT applies the LT predicate on the "service_period_from" field. +func ServicePeriodFromLT(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLTE applies the LTE predicate on the "service_period_from" field. +func ServicePeriodFromLTE(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodToEQ applies the EQ predicate on the "service_period_to" field. +func ServicePeriodToEQ(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToNEQ applies the NEQ predicate on the "service_period_to" field. +func ServicePeriodToNEQ(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToIn applies the In predicate on the "service_period_to" field. +func ServicePeriodToIn(vs ...time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToNotIn applies the NotIn predicate on the "service_period_to" field. +func ServicePeriodToNotIn(vs ...time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToGT applies the GT predicate on the "service_period_to" field. +func ServicePeriodToGT(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToGTE applies the GTE predicate on the "service_period_to" field. +func ServicePeriodToGTE(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGTE(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLT applies the LT predicate on the "service_period_to" field. +func ServicePeriodToLT(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLTE applies the LTE predicate on the "service_period_to" field. +func ServicePeriodToLTE(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLTE(FieldServicePeriodTo, v)) +} + +// FullServicePeriodFromEQ applies the EQ predicate on the "full_service_period_from" field. +func FullServicePeriodFromEQ(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromNEQ applies the NEQ predicate on the "full_service_period_from" field. +func FullServicePeriodFromNEQ(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNEQ(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromIn applies the In predicate on the "full_service_period_from" field. +func FullServicePeriodFromIn(vs ...time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIn(FieldFullServicePeriodFrom, vs...)) +} + +// FullServicePeriodFromNotIn applies the NotIn predicate on the "full_service_period_from" field. +func FullServicePeriodFromNotIn(vs ...time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotIn(FieldFullServicePeriodFrom, vs...)) +} + +// FullServicePeriodFromGT applies the GT predicate on the "full_service_period_from" field. +func FullServicePeriodFromGT(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGT(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromGTE applies the GTE predicate on the "full_service_period_from" field. +func FullServicePeriodFromGTE(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGTE(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromLT applies the LT predicate on the "full_service_period_from" field. +func FullServicePeriodFromLT(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLT(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromLTE applies the LTE predicate on the "full_service_period_from" field. +func FullServicePeriodFromLTE(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLTE(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodToEQ applies the EQ predicate on the "full_service_period_to" field. +func FullServicePeriodToEQ(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToNEQ applies the NEQ predicate on the "full_service_period_to" field. +func FullServicePeriodToNEQ(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNEQ(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToIn applies the In predicate on the "full_service_period_to" field. +func FullServicePeriodToIn(vs ...time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIn(FieldFullServicePeriodTo, vs...)) +} + +// FullServicePeriodToNotIn applies the NotIn predicate on the "full_service_period_to" field. +func FullServicePeriodToNotIn(vs ...time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotIn(FieldFullServicePeriodTo, vs...)) +} + +// FullServicePeriodToGT applies the GT predicate on the "full_service_period_to" field. +func FullServicePeriodToGT(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGT(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToGTE applies the GTE predicate on the "full_service_period_to" field. +func FullServicePeriodToGTE(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGTE(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToLT applies the LT predicate on the "full_service_period_to" field. +func FullServicePeriodToLT(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLT(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToLTE applies the LTE predicate on the "full_service_period_to" field. +func FullServicePeriodToLTE(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLTE(FieldFullServicePeriodTo, v)) +} + +// BillingPeriodFromEQ applies the EQ predicate on the "billing_period_from" field. +func BillingPeriodFromEQ(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromNEQ applies the NEQ predicate on the "billing_period_from" field. +func BillingPeriodFromNEQ(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNEQ(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromIn applies the In predicate on the "billing_period_from" field. +func BillingPeriodFromIn(vs ...time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIn(FieldBillingPeriodFrom, vs...)) +} + +// BillingPeriodFromNotIn applies the NotIn predicate on the "billing_period_from" field. +func BillingPeriodFromNotIn(vs ...time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotIn(FieldBillingPeriodFrom, vs...)) +} + +// BillingPeriodFromGT applies the GT predicate on the "billing_period_from" field. +func BillingPeriodFromGT(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGT(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromGTE applies the GTE predicate on the "billing_period_from" field. +func BillingPeriodFromGTE(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGTE(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromLT applies the LT predicate on the "billing_period_from" field. +func BillingPeriodFromLT(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLT(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromLTE applies the LTE predicate on the "billing_period_from" field. +func BillingPeriodFromLTE(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLTE(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodToEQ applies the EQ predicate on the "billing_period_to" field. +func BillingPeriodToEQ(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToNEQ applies the NEQ predicate on the "billing_period_to" field. +func BillingPeriodToNEQ(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNEQ(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToIn applies the In predicate on the "billing_period_to" field. +func BillingPeriodToIn(vs ...time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIn(FieldBillingPeriodTo, vs...)) +} + +// BillingPeriodToNotIn applies the NotIn predicate on the "billing_period_to" field. +func BillingPeriodToNotIn(vs ...time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotIn(FieldBillingPeriodTo, vs...)) +} + +// BillingPeriodToGT applies the GT predicate on the "billing_period_to" field. +func BillingPeriodToGT(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGT(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToGTE applies the GTE predicate on the "billing_period_to" field. +func BillingPeriodToGTE(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGTE(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToLT applies the LT predicate on the "billing_period_to" field. +func BillingPeriodToLT(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLT(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToLTE applies the LTE predicate on the "billing_period_to" field. +func BillingPeriodToLTE(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLTE(FieldBillingPeriodTo, v)) +} + +// InvoiceAtEQ applies the EQ predicate on the "invoice_at" field. +func InvoiceAtEQ(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldInvoiceAt, v)) +} + +// InvoiceAtNEQ applies the NEQ predicate on the "invoice_at" field. +func InvoiceAtNEQ(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNEQ(FieldInvoiceAt, v)) +} + +// InvoiceAtIn applies the In predicate on the "invoice_at" field. +func InvoiceAtIn(vs ...time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIn(FieldInvoiceAt, vs...)) +} + +// InvoiceAtNotIn applies the NotIn predicate on the "invoice_at" field. +func InvoiceAtNotIn(vs ...time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotIn(FieldInvoiceAt, vs...)) +} + +// InvoiceAtGT applies the GT predicate on the "invoice_at" field. +func InvoiceAtGT(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGT(FieldInvoiceAt, v)) +} + +// InvoiceAtGTE applies the GTE predicate on the "invoice_at" field. +func InvoiceAtGTE(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGTE(FieldInvoiceAt, v)) +} + +// InvoiceAtLT applies the LT predicate on the "invoice_at" field. +func InvoiceAtLT(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLT(FieldInvoiceAt, v)) +} + +// InvoiceAtLTE applies the LTE predicate on the "invoice_at" field. +func InvoiceAtLTE(v time.Time) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLTE(FieldInvoiceAt, v)) +} + +// FeatureKeyEQ applies the EQ predicate on the "feature_key" field. +func FeatureKeyEQ(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldFeatureKey, v)) +} + +// FeatureKeyNEQ applies the NEQ predicate on the "feature_key" field. +func FeatureKeyNEQ(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNEQ(FieldFeatureKey, v)) +} + +// FeatureKeyIn applies the In predicate on the "feature_key" field. +func FeatureKeyIn(vs ...string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIn(FieldFeatureKey, vs...)) +} + +// FeatureKeyNotIn applies the NotIn predicate on the "feature_key" field. +func FeatureKeyNotIn(vs ...string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotIn(FieldFeatureKey, vs...)) +} + +// FeatureKeyGT applies the GT predicate on the "feature_key" field. +func FeatureKeyGT(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGT(FieldFeatureKey, v)) +} + +// FeatureKeyGTE applies the GTE predicate on the "feature_key" field. +func FeatureKeyGTE(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGTE(FieldFeatureKey, v)) +} + +// FeatureKeyLT applies the LT predicate on the "feature_key" field. +func FeatureKeyLT(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLT(FieldFeatureKey, v)) +} + +// FeatureKeyLTE applies the LTE predicate on the "feature_key" field. +func FeatureKeyLTE(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLTE(FieldFeatureKey, v)) +} + +// FeatureKeyContains applies the Contains predicate on the "feature_key" field. +func FeatureKeyContains(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldContains(FieldFeatureKey, v)) +} + +// FeatureKeyHasPrefix applies the HasPrefix predicate on the "feature_key" field. +func FeatureKeyHasPrefix(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldHasPrefix(FieldFeatureKey, v)) +} + +// FeatureKeyHasSuffix applies the HasSuffix predicate on the "feature_key" field. +func FeatureKeyHasSuffix(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldHasSuffix(FieldFeatureKey, v)) +} + +// FeatureKeyIsNil applies the IsNil predicate on the "feature_key" field. +func FeatureKeyIsNil() predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIsNull(FieldFeatureKey)) +} + +// FeatureKeyNotNil applies the NotNil predicate on the "feature_key" field. +func FeatureKeyNotNil() predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotNull(FieldFeatureKey)) +} + +// FeatureKeyEqualFold applies the EqualFold predicate on the "feature_key" field. +func FeatureKeyEqualFold(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEqualFold(FieldFeatureKey, v)) +} + +// FeatureKeyContainsFold applies the ContainsFold predicate on the "feature_key" field. +func FeatureKeyContainsFold(v string) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldContainsFold(FieldFeatureKey, v)) +} + +// PaymentTermEQ applies the EQ predicate on the "payment_term" field. +func PaymentTermEQ(v productcatalog.PaymentTermType) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldPaymentTerm, vc)) +} + +// PaymentTermNEQ applies the NEQ predicate on the "payment_term" field. +func PaymentTermNEQ(v productcatalog.PaymentTermType) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldNEQ(FieldPaymentTerm, vc)) +} + +// PaymentTermIn applies the In predicate on the "payment_term" field. +func PaymentTermIn(vs ...productcatalog.PaymentTermType) predicate.ChargeFlatFeeOverride { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargeFlatFeeOverride(sql.FieldIn(FieldPaymentTerm, v...)) +} + +// PaymentTermNotIn applies the NotIn predicate on the "payment_term" field. +func PaymentTermNotIn(vs ...productcatalog.PaymentTermType) predicate.ChargeFlatFeeOverride { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargeFlatFeeOverride(sql.FieldNotIn(FieldPaymentTerm, v...)) +} + +// PaymentTermGT applies the GT predicate on the "payment_term" field. +func PaymentTermGT(v productcatalog.PaymentTermType) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldGT(FieldPaymentTerm, vc)) +} + +// PaymentTermGTE applies the GTE predicate on the "payment_term" field. +func PaymentTermGTE(v productcatalog.PaymentTermType) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldGTE(FieldPaymentTerm, vc)) +} + +// PaymentTermLT applies the LT predicate on the "payment_term" field. +func PaymentTermLT(v productcatalog.PaymentTermType) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldLT(FieldPaymentTerm, vc)) +} + +// PaymentTermLTE applies the LTE predicate on the "payment_term" field. +func PaymentTermLTE(v productcatalog.PaymentTermType) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldLTE(FieldPaymentTerm, vc)) +} + +// PaymentTermContains applies the Contains predicate on the "payment_term" field. +func PaymentTermContains(v productcatalog.PaymentTermType) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldContains(FieldPaymentTerm, vc)) +} + +// PaymentTermHasPrefix applies the HasPrefix predicate on the "payment_term" field. +func PaymentTermHasPrefix(v productcatalog.PaymentTermType) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldHasPrefix(FieldPaymentTerm, vc)) +} + +// PaymentTermHasSuffix applies the HasSuffix predicate on the "payment_term" field. +func PaymentTermHasSuffix(v productcatalog.PaymentTermType) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldHasSuffix(FieldPaymentTerm, vc)) +} + +// PaymentTermEqualFold applies the EqualFold predicate on the "payment_term" field. +func PaymentTermEqualFold(v productcatalog.PaymentTermType) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldEqualFold(FieldPaymentTerm, vc)) +} + +// PaymentTermContainsFold applies the ContainsFold predicate on the "payment_term" field. +func PaymentTermContainsFold(v productcatalog.PaymentTermType) predicate.ChargeFlatFeeOverride { + vc := string(v) + return predicate.ChargeFlatFeeOverride(sql.FieldContainsFold(FieldPaymentTerm, vc)) +} + +// AmountBeforeProrationEQ applies the EQ predicate on the "amount_before_proration" field. +func AmountBeforeProrationEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldEQ(FieldAmountBeforeProration, v)) +} + +// AmountBeforeProrationNEQ applies the NEQ predicate on the "amount_before_proration" field. +func AmountBeforeProrationNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNEQ(FieldAmountBeforeProration, v)) +} + +// AmountBeforeProrationIn applies the In predicate on the "amount_before_proration" field. +func AmountBeforeProrationIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIn(FieldAmountBeforeProration, vs...)) +} + +// AmountBeforeProrationNotIn applies the NotIn predicate on the "amount_before_proration" field. +func AmountBeforeProrationNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotIn(FieldAmountBeforeProration, vs...)) +} + +// AmountBeforeProrationGT applies the GT predicate on the "amount_before_proration" field. +func AmountBeforeProrationGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGT(FieldAmountBeforeProration, v)) +} + +// AmountBeforeProrationGTE applies the GTE predicate on the "amount_before_proration" field. +func AmountBeforeProrationGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldGTE(FieldAmountBeforeProration, v)) +} + +// AmountBeforeProrationLT applies the LT predicate on the "amount_before_proration" field. +func AmountBeforeProrationLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLT(FieldAmountBeforeProration, v)) +} + +// AmountBeforeProrationLTE applies the LTE predicate on the "amount_before_proration" field. +func AmountBeforeProrationLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldLTE(FieldAmountBeforeProration, v)) +} + +// DiscountsIsNil applies the IsNil predicate on the "discounts" field. +func DiscountsIsNil() predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIsNull(FieldDiscounts)) +} + +// DiscountsNotNil applies the NotNil predicate on the "discounts" field. +func DiscountsNotNil() predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotNull(FieldDiscounts)) +} + +// PercentageDiscountsIsNil applies the IsNil predicate on the "percentage_discounts" field. +func PercentageDiscountsIsNil() predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldIsNull(FieldPercentageDiscounts)) +} + +// PercentageDiscountsNotNil applies the NotNil predicate on the "percentage_discounts" field. +func PercentageDiscountsNotNil() predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.FieldNotNull(FieldPercentageDiscounts)) +} + +// HasFlatFee applies the HasEdge predicate on the "flat_fee" edge. +func HasFlatFee() predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, FlatFeeTable, FlatFeeColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasFlatFeeWith applies the HasEdge predicate on the "flat_fee" edge with a given conditions (other predicates). +func HasFlatFeeWith(preds ...predicate.ChargeFlatFee) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(func(s *sql.Selector) { + step := newFlatFeeStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasTaxCode applies the HasEdge predicate on the "tax_code" edge. +func HasTaxCode() predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, TaxCodeTable, TaxCodeColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTaxCodeWith applies the HasEdge predicate on the "tax_code" edge with a given conditions (other predicates). +func HasTaxCodeWith(preds ...predicate.TaxCode) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(func(s *sql.Selector) { + step := newTaxCodeStep() + 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.ChargeFlatFeeOverride) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ChargeFlatFeeOverride) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ChargeFlatFeeOverride) predicate.ChargeFlatFeeOverride { + return predicate.ChargeFlatFeeOverride(sql.NotPredicates(p)) +} diff --git a/ent/db/chargeflatfeeoverride_create.go b/ent/db/chargeflatfeeoverride_create.go new file mode 100644 index 0000000000000000000000000000000000000000..28492053acadb1c968f89e0277d62ed2d7411440 --- /dev/null +++ b/ent/db/chargeflatfeeoverride_create.go @@ -0,0 +1,1789 @@ +// 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" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeoverride" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeFlatFeeOverrideCreate is the builder for creating a ChargeFlatFeeOverride entity. +type ChargeFlatFeeOverrideCreate struct { + config + mutation *ChargeFlatFeeOverrideMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *ChargeFlatFeeOverrideCreate) SetNamespace(v string) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetChargeID sets the "charge_id" field. +func (_c *ChargeFlatFeeOverrideCreate) SetChargeID(v string) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetChargeID(v) + return _c +} + +// SetName sets the "name" field. +func (_c *ChargeFlatFeeOverrideCreate) SetName(v string) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetName(v) + return _c +} + +// SetDescription sets the "description" field. +func (_c *ChargeFlatFeeOverrideCreate) SetDescription(v string) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetDescription(v) + return _c +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_c *ChargeFlatFeeOverrideCreate) SetNillableDescription(v *string) *ChargeFlatFeeOverrideCreate { + if v != nil { + _c.SetDescription(*v) + } + return _c +} + +// SetMetadata sets the "metadata" field. +func (_c *ChargeFlatFeeOverrideCreate) SetMetadata(v *models.Metadata) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetMetadata(v) + return _c +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (_c *ChargeFlatFeeOverrideCreate) SetTaxBehavior(v productcatalog.TaxBehavior) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetTaxBehavior(v) + return _c +} + +// SetNillableTaxBehavior sets the "tax_behavior" field if the given value is not nil. +func (_c *ChargeFlatFeeOverrideCreate) SetNillableTaxBehavior(v *productcatalog.TaxBehavior) *ChargeFlatFeeOverrideCreate { + if v != nil { + _c.SetTaxBehavior(*v) + } + return _c +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (_c *ChargeFlatFeeOverrideCreate) SetTaxCodeID(v string) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetTaxCodeID(v) + return _c +} + +// SetNillableTaxCodeID sets the "tax_code_id" field if the given value is not nil. +func (_c *ChargeFlatFeeOverrideCreate) SetNillableTaxCodeID(v *string) *ChargeFlatFeeOverrideCreate { + if v != nil { + _c.SetTaxCodeID(*v) + } + return _c +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (_c *ChargeFlatFeeOverrideCreate) SetIntentDeletedAt(v time.Time) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetIntentDeletedAt(v) + return _c +} + +// SetNillableIntentDeletedAt sets the "intent_deleted_at" field if the given value is not nil. +func (_c *ChargeFlatFeeOverrideCreate) SetNillableIntentDeletedAt(v *time.Time) *ChargeFlatFeeOverrideCreate { + if v != nil { + _c.SetIntentDeletedAt(*v) + } + return _c +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_c *ChargeFlatFeeOverrideCreate) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetServicePeriodFrom(v) + return _c +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_c *ChargeFlatFeeOverrideCreate) SetServicePeriodTo(v time.Time) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetServicePeriodTo(v) + return _c +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (_c *ChargeFlatFeeOverrideCreate) SetFullServicePeriodFrom(v time.Time) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetFullServicePeriodFrom(v) + return _c +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (_c *ChargeFlatFeeOverrideCreate) SetFullServicePeriodTo(v time.Time) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetFullServicePeriodTo(v) + return _c +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (_c *ChargeFlatFeeOverrideCreate) SetBillingPeriodFrom(v time.Time) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetBillingPeriodFrom(v) + return _c +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (_c *ChargeFlatFeeOverrideCreate) SetBillingPeriodTo(v time.Time) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetBillingPeriodTo(v) + return _c +} + +// SetInvoiceAt sets the "invoice_at" field. +func (_c *ChargeFlatFeeOverrideCreate) SetInvoiceAt(v time.Time) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetInvoiceAt(v) + return _c +} + +// SetFeatureKey sets the "feature_key" field. +func (_c *ChargeFlatFeeOverrideCreate) SetFeatureKey(v string) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetFeatureKey(v) + return _c +} + +// SetNillableFeatureKey sets the "feature_key" field if the given value is not nil. +func (_c *ChargeFlatFeeOverrideCreate) SetNillableFeatureKey(v *string) *ChargeFlatFeeOverrideCreate { + if v != nil { + _c.SetFeatureKey(*v) + } + return _c +} + +// SetPaymentTerm sets the "payment_term" field. +func (_c *ChargeFlatFeeOverrideCreate) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetPaymentTerm(v) + return _c +} + +// SetProRating sets the "pro_rating" field. +func (_c *ChargeFlatFeeOverrideCreate) SetProRating(v *productcatalog.ProRatingConfig) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetProRating(v) + return _c +} + +// SetAmountBeforeProration sets the "amount_before_proration" field. +func (_c *ChargeFlatFeeOverrideCreate) SetAmountBeforeProration(v alpacadecimal.Decimal) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetAmountBeforeProration(v) + return _c +} + +// SetDiscounts sets the "discounts" field. +func (_c *ChargeFlatFeeOverrideCreate) SetDiscounts(v *billing.Discounts) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetDiscounts(v) + return _c +} + +// SetPercentageDiscounts sets the "percentage_discounts" field. +func (_c *ChargeFlatFeeOverrideCreate) SetPercentageDiscounts(v *billing.PercentageDiscount) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetPercentageDiscounts(v) + return _c +} + +// SetID sets the "id" field. +func (_c *ChargeFlatFeeOverrideCreate) SetID(v string) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ChargeFlatFeeOverrideCreate) SetNillableID(v *string) *ChargeFlatFeeOverrideCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetFlatFeeID sets the "flat_fee" edge to the ChargeFlatFee entity by ID. +func (_c *ChargeFlatFeeOverrideCreate) SetFlatFeeID(id string) *ChargeFlatFeeOverrideCreate { + _c.mutation.SetFlatFeeID(id) + return _c +} + +// SetFlatFee sets the "flat_fee" edge to the ChargeFlatFee entity. +func (_c *ChargeFlatFeeOverrideCreate) SetFlatFee(v *ChargeFlatFee) *ChargeFlatFeeOverrideCreate { + return _c.SetFlatFeeID(v.ID) +} + +// SetTaxCode sets the "tax_code" edge to the TaxCode entity. +func (_c *ChargeFlatFeeOverrideCreate) SetTaxCode(v *TaxCode) *ChargeFlatFeeOverrideCreate { + return _c.SetTaxCodeID(v.ID) +} + +// Mutation returns the ChargeFlatFeeOverrideMutation object of the builder. +func (_c *ChargeFlatFeeOverrideCreate) Mutation() *ChargeFlatFeeOverrideMutation { + return _c.mutation +} + +// Save creates the ChargeFlatFeeOverride in the database. +func (_c *ChargeFlatFeeOverrideCreate) Save(ctx context.Context) (*ChargeFlatFeeOverride, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ChargeFlatFeeOverrideCreate) SaveX(ctx context.Context) *ChargeFlatFeeOverride { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeFlatFeeOverrideCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeFlatFeeOverrideCreate) 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 *ChargeFlatFeeOverrideCreate) defaults() { + if _, ok := _c.mutation.ID(); !ok { + v := chargeflatfeeoverride.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ChargeFlatFeeOverrideCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "ChargeFlatFeeOverride.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := chargeflatfeeoverride.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeOverride.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.ChargeID(); !ok { + return &ValidationError{Name: "charge_id", err: errors.New(`db: missing required field "ChargeFlatFeeOverride.charge_id"`)} + } + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "ChargeFlatFeeOverride.name"`)} + } + if v, ok := _c.mutation.Name(); ok { + if err := chargeflatfeeoverride.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeOverride.name": %w`, err)} + } + } + if v, ok := _c.mutation.TaxBehavior(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "tax_behavior", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeOverride.tax_behavior": %w`, err)} + } + } + if _, ok := _c.mutation.ServicePeriodFrom(); !ok { + return &ValidationError{Name: "service_period_from", err: errors.New(`db: missing required field "ChargeFlatFeeOverride.service_period_from"`)} + } + if _, ok := _c.mutation.ServicePeriodTo(); !ok { + return &ValidationError{Name: "service_period_to", err: errors.New(`db: missing required field "ChargeFlatFeeOverride.service_period_to"`)} + } + if _, ok := _c.mutation.FullServicePeriodFrom(); !ok { + return &ValidationError{Name: "full_service_period_from", err: errors.New(`db: missing required field "ChargeFlatFeeOverride.full_service_period_from"`)} + } + if _, ok := _c.mutation.FullServicePeriodTo(); !ok { + return &ValidationError{Name: "full_service_period_to", err: errors.New(`db: missing required field "ChargeFlatFeeOverride.full_service_period_to"`)} + } + if _, ok := _c.mutation.BillingPeriodFrom(); !ok { + return &ValidationError{Name: "billing_period_from", err: errors.New(`db: missing required field "ChargeFlatFeeOverride.billing_period_from"`)} + } + if _, ok := _c.mutation.BillingPeriodTo(); !ok { + return &ValidationError{Name: "billing_period_to", err: errors.New(`db: missing required field "ChargeFlatFeeOverride.billing_period_to"`)} + } + if _, ok := _c.mutation.InvoiceAt(); !ok { + return &ValidationError{Name: "invoice_at", err: errors.New(`db: missing required field "ChargeFlatFeeOverride.invoice_at"`)} + } + if v, ok := _c.mutation.FeatureKey(); ok { + if err := chargeflatfeeoverride.FeatureKeyValidator(v); err != nil { + return &ValidationError{Name: "feature_key", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeOverride.feature_key": %w`, err)} + } + } + if _, ok := _c.mutation.PaymentTerm(); !ok { + return &ValidationError{Name: "payment_term", err: errors.New(`db: missing required field "ChargeFlatFeeOverride.payment_term"`)} + } + if v, ok := _c.mutation.PaymentTerm(); ok { + if err := chargeflatfeeoverride.PaymentTermValidator(string(v)); err != nil { + return &ValidationError{Name: "payment_term", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeOverride.payment_term": %w`, err)} + } + } + if _, ok := _c.mutation.ProRating(); !ok { + return &ValidationError{Name: "pro_rating", err: errors.New(`db: missing required field "ChargeFlatFeeOverride.pro_rating"`)} + } + if v, ok := _c.mutation.ProRating(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "pro_rating", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeOverride.pro_rating": %w`, err)} + } + } + if _, ok := _c.mutation.AmountBeforeProration(); !ok { + return &ValidationError{Name: "amount_before_proration", err: errors.New(`db: missing required field "ChargeFlatFeeOverride.amount_before_proration"`)} + } + 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 "ChargeFlatFeeOverride.discounts": %w`, err)} + } + } + if v, ok := _c.mutation.PercentageDiscounts(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "percentage_discounts", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeOverride.percentage_discounts": %w`, err)} + } + } + if len(_c.mutation.FlatFeeIDs()) == 0 { + return &ValidationError{Name: "flat_fee", err: errors.New(`db: missing required edge "ChargeFlatFeeOverride.flat_fee"`)} + } + return nil +} + +func (_c *ChargeFlatFeeOverrideCreate) sqlSave(ctx context.Context) (*ChargeFlatFeeOverride, 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 ChargeFlatFeeOverride.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ChargeFlatFeeOverrideCreate) createSpec() (*ChargeFlatFeeOverride, *sqlgraph.CreateSpec, error) { + var ( + _node = &ChargeFlatFeeOverride{config: _c.config} + _spec = sqlgraph.NewCreateSpec(chargeflatfeeoverride.Table, sqlgraph.NewFieldSpec(chargeflatfeeoverride.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(chargeflatfeeoverride.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(chargeflatfeeoverride.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Description(); ok { + _spec.SetField(chargeflatfeeoverride.FieldDescription, field.TypeString, value) + _node.Description = &value + } + if value, ok := _c.mutation.Metadata(); ok { + vv, err := chargeflatfeeoverride.ValueScanner.Metadata.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(chargeflatfeeoverride.FieldMetadata, field.TypeString, vv) + _node.Metadata = value + } + if value, ok := _c.mutation.TaxBehavior(); ok { + _spec.SetField(chargeflatfeeoverride.FieldTaxBehavior, field.TypeString, value) + _node.TaxBehavior = &value + } + if value, ok := _c.mutation.IntentDeletedAt(); ok { + _spec.SetField(chargeflatfeeoverride.FieldIntentDeletedAt, field.TypeTime, value) + _node.IntentDeletedAt = &value + } + if value, ok := _c.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeflatfeeoverride.FieldServicePeriodFrom, field.TypeTime, value) + _node.ServicePeriodFrom = value + } + if value, ok := _c.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeflatfeeoverride.FieldServicePeriodTo, field.TypeTime, value) + _node.ServicePeriodTo = value + } + if value, ok := _c.mutation.FullServicePeriodFrom(); ok { + _spec.SetField(chargeflatfeeoverride.FieldFullServicePeriodFrom, field.TypeTime, value) + _node.FullServicePeriodFrom = value + } + if value, ok := _c.mutation.FullServicePeriodTo(); ok { + _spec.SetField(chargeflatfeeoverride.FieldFullServicePeriodTo, field.TypeTime, value) + _node.FullServicePeriodTo = value + } + if value, ok := _c.mutation.BillingPeriodFrom(); ok { + _spec.SetField(chargeflatfeeoverride.FieldBillingPeriodFrom, field.TypeTime, value) + _node.BillingPeriodFrom = value + } + if value, ok := _c.mutation.BillingPeriodTo(); ok { + _spec.SetField(chargeflatfeeoverride.FieldBillingPeriodTo, field.TypeTime, value) + _node.BillingPeriodTo = value + } + if value, ok := _c.mutation.InvoiceAt(); ok { + _spec.SetField(chargeflatfeeoverride.FieldInvoiceAt, field.TypeTime, value) + _node.InvoiceAt = value + } + if value, ok := _c.mutation.FeatureKey(); ok { + _spec.SetField(chargeflatfeeoverride.FieldFeatureKey, field.TypeString, value) + _node.FeatureKey = &value + } + if value, ok := _c.mutation.PaymentTerm(); ok { + _spec.SetField(chargeflatfeeoverride.FieldPaymentTerm, field.TypeString, value) + _node.PaymentTerm = value + } + if value, ok := _c.mutation.ProRating(); ok { + vv, err := chargeflatfeeoverride.ValueScanner.ProRating.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(chargeflatfeeoverride.FieldProRating, field.TypeString, vv) + _node.ProRating = value + } + if value, ok := _c.mutation.AmountBeforeProration(); ok { + _spec.SetField(chargeflatfeeoverride.FieldAmountBeforeProration, field.TypeOther, value) + _node.AmountBeforeProration = value + } + if value, ok := _c.mutation.Discounts(); ok { + vv, err := chargeflatfeeoverride.ValueScanner.Discounts.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(chargeflatfeeoverride.FieldDiscounts, field.TypeString, vv) + _node.Discounts = value + } + if value, ok := _c.mutation.PercentageDiscounts(); ok { + vv, err := chargeflatfeeoverride.ValueScanner.PercentageDiscounts.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(chargeflatfeeoverride.FieldPercentageDiscounts, field.TypeString, vv) + _node.PercentageDiscounts = value + } + if nodes := _c.mutation.FlatFeeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeflatfeeoverride.FlatFeeTable, + Columns: []string{chargeflatfeeoverride.FlatFeeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfee.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.TaxCodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfeeoverride.TaxCodeTable, + Columns: []string{chargeflatfeeoverride.TaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.TaxCodeID = &nodes[0] + _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.ChargeFlatFeeOverride.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.ChargeFlatFeeOverrideUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *ChargeFlatFeeOverrideCreate) OnConflict(opts ...sql.ConflictOption) *ChargeFlatFeeOverrideUpsertOne { + _c.conflict = opts + return &ChargeFlatFeeOverrideUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeFlatFeeOverride.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeFlatFeeOverrideCreate) OnConflictColumns(columns ...string) *ChargeFlatFeeOverrideUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeFlatFeeOverrideUpsertOne{ + create: _c, + } +} + +type ( + // ChargeFlatFeeOverrideUpsertOne is the builder for "upsert"-ing + // one ChargeFlatFeeOverride node. + ChargeFlatFeeOverrideUpsertOne struct { + create *ChargeFlatFeeOverrideCreate + } + + // ChargeFlatFeeOverrideUpsert is the "OnConflict" setter. + ChargeFlatFeeOverrideUpsert struct { + *sql.UpdateSet + } +) + +// SetName sets the "name" field. +func (u *ChargeFlatFeeOverrideUpsert) SetName(v string) *ChargeFlatFeeOverrideUpsert { + u.Set(chargeflatfeeoverride.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsert) UpdateName() *ChargeFlatFeeOverrideUpsert { + u.SetExcluded(chargeflatfeeoverride.FieldName) + return u +} + +// SetDescription sets the "description" field. +func (u *ChargeFlatFeeOverrideUpsert) SetDescription(v string) *ChargeFlatFeeOverrideUpsert { + u.Set(chargeflatfeeoverride.FieldDescription, v) + return u +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsert) UpdateDescription() *ChargeFlatFeeOverrideUpsert { + u.SetExcluded(chargeflatfeeoverride.FieldDescription) + return u +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeFlatFeeOverrideUpsert) ClearDescription() *ChargeFlatFeeOverrideUpsert { + u.SetNull(chargeflatfeeoverride.FieldDescription) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeFlatFeeOverrideUpsert) SetMetadata(v *models.Metadata) *ChargeFlatFeeOverrideUpsert { + u.Set(chargeflatfeeoverride.FieldMetadata, v) + return u +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsert) UpdateMetadata() *ChargeFlatFeeOverrideUpsert { + u.SetExcluded(chargeflatfeeoverride.FieldMetadata) + return u +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeFlatFeeOverrideUpsert) ClearMetadata() *ChargeFlatFeeOverrideUpsert { + u.SetNull(chargeflatfeeoverride.FieldMetadata) + return u +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (u *ChargeFlatFeeOverrideUpsert) SetTaxBehavior(v productcatalog.TaxBehavior) *ChargeFlatFeeOverrideUpsert { + u.Set(chargeflatfeeoverride.FieldTaxBehavior, v) + return u +} + +// UpdateTaxBehavior sets the "tax_behavior" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsert) UpdateTaxBehavior() *ChargeFlatFeeOverrideUpsert { + u.SetExcluded(chargeflatfeeoverride.FieldTaxBehavior) + return u +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (u *ChargeFlatFeeOverrideUpsert) ClearTaxBehavior() *ChargeFlatFeeOverrideUpsert { + u.SetNull(chargeflatfeeoverride.FieldTaxBehavior) + return u +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (u *ChargeFlatFeeOverrideUpsert) SetTaxCodeID(v string) *ChargeFlatFeeOverrideUpsert { + u.Set(chargeflatfeeoverride.FieldTaxCodeID, v) + return u +} + +// UpdateTaxCodeID sets the "tax_code_id" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsert) UpdateTaxCodeID() *ChargeFlatFeeOverrideUpsert { + u.SetExcluded(chargeflatfeeoverride.FieldTaxCodeID) + return u +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (u *ChargeFlatFeeOverrideUpsert) ClearTaxCodeID() *ChargeFlatFeeOverrideUpsert { + u.SetNull(chargeflatfeeoverride.FieldTaxCodeID) + return u +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (u *ChargeFlatFeeOverrideUpsert) SetIntentDeletedAt(v time.Time) *ChargeFlatFeeOverrideUpsert { + u.Set(chargeflatfeeoverride.FieldIntentDeletedAt, v) + return u +} + +// UpdateIntentDeletedAt sets the "intent_deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsert) UpdateIntentDeletedAt() *ChargeFlatFeeOverrideUpsert { + u.SetExcluded(chargeflatfeeoverride.FieldIntentDeletedAt) + return u +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (u *ChargeFlatFeeOverrideUpsert) ClearIntentDeletedAt() *ChargeFlatFeeOverrideUpsert { + u.SetNull(chargeflatfeeoverride.FieldIntentDeletedAt) + return u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeFlatFeeOverrideUpsert) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeOverrideUpsert { + u.Set(chargeflatfeeoverride.FieldServicePeriodFrom, v) + return u +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsert) UpdateServicePeriodFrom() *ChargeFlatFeeOverrideUpsert { + u.SetExcluded(chargeflatfeeoverride.FieldServicePeriodFrom) + return u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeFlatFeeOverrideUpsert) SetServicePeriodTo(v time.Time) *ChargeFlatFeeOverrideUpsert { + u.Set(chargeflatfeeoverride.FieldServicePeriodTo, v) + return u +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsert) UpdateServicePeriodTo() *ChargeFlatFeeOverrideUpsert { + u.SetExcluded(chargeflatfeeoverride.FieldServicePeriodTo) + return u +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (u *ChargeFlatFeeOverrideUpsert) SetFullServicePeriodFrom(v time.Time) *ChargeFlatFeeOverrideUpsert { + u.Set(chargeflatfeeoverride.FieldFullServicePeriodFrom, v) + return u +} + +// UpdateFullServicePeriodFrom sets the "full_service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsert) UpdateFullServicePeriodFrom() *ChargeFlatFeeOverrideUpsert { + u.SetExcluded(chargeflatfeeoverride.FieldFullServicePeriodFrom) + return u +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (u *ChargeFlatFeeOverrideUpsert) SetFullServicePeriodTo(v time.Time) *ChargeFlatFeeOverrideUpsert { + u.Set(chargeflatfeeoverride.FieldFullServicePeriodTo, v) + return u +} + +// UpdateFullServicePeriodTo sets the "full_service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsert) UpdateFullServicePeriodTo() *ChargeFlatFeeOverrideUpsert { + u.SetExcluded(chargeflatfeeoverride.FieldFullServicePeriodTo) + return u +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (u *ChargeFlatFeeOverrideUpsert) SetBillingPeriodFrom(v time.Time) *ChargeFlatFeeOverrideUpsert { + u.Set(chargeflatfeeoverride.FieldBillingPeriodFrom, v) + return u +} + +// UpdateBillingPeriodFrom sets the "billing_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsert) UpdateBillingPeriodFrom() *ChargeFlatFeeOverrideUpsert { + u.SetExcluded(chargeflatfeeoverride.FieldBillingPeriodFrom) + return u +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (u *ChargeFlatFeeOverrideUpsert) SetBillingPeriodTo(v time.Time) *ChargeFlatFeeOverrideUpsert { + u.Set(chargeflatfeeoverride.FieldBillingPeriodTo, v) + return u +} + +// UpdateBillingPeriodTo sets the "billing_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsert) UpdateBillingPeriodTo() *ChargeFlatFeeOverrideUpsert { + u.SetExcluded(chargeflatfeeoverride.FieldBillingPeriodTo) + return u +} + +// SetInvoiceAt sets the "invoice_at" field. +func (u *ChargeFlatFeeOverrideUpsert) SetInvoiceAt(v time.Time) *ChargeFlatFeeOverrideUpsert { + u.Set(chargeflatfeeoverride.FieldInvoiceAt, v) + return u +} + +// UpdateInvoiceAt sets the "invoice_at" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsert) UpdateInvoiceAt() *ChargeFlatFeeOverrideUpsert { + u.SetExcluded(chargeflatfeeoverride.FieldInvoiceAt) + return u +} + +// SetFeatureKey sets the "feature_key" field. +func (u *ChargeFlatFeeOverrideUpsert) SetFeatureKey(v string) *ChargeFlatFeeOverrideUpsert { + u.Set(chargeflatfeeoverride.FieldFeatureKey, v) + return u +} + +// UpdateFeatureKey sets the "feature_key" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsert) UpdateFeatureKey() *ChargeFlatFeeOverrideUpsert { + u.SetExcluded(chargeflatfeeoverride.FieldFeatureKey) + return u +} + +// ClearFeatureKey clears the value of the "feature_key" field. +func (u *ChargeFlatFeeOverrideUpsert) ClearFeatureKey() *ChargeFlatFeeOverrideUpsert { + u.SetNull(chargeflatfeeoverride.FieldFeatureKey) + return u +} + +// SetPaymentTerm sets the "payment_term" field. +func (u *ChargeFlatFeeOverrideUpsert) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeFlatFeeOverrideUpsert { + u.Set(chargeflatfeeoverride.FieldPaymentTerm, v) + return u +} + +// UpdatePaymentTerm sets the "payment_term" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsert) UpdatePaymentTerm() *ChargeFlatFeeOverrideUpsert { + u.SetExcluded(chargeflatfeeoverride.FieldPaymentTerm) + return u +} + +// SetProRating sets the "pro_rating" field. +func (u *ChargeFlatFeeOverrideUpsert) SetProRating(v *productcatalog.ProRatingConfig) *ChargeFlatFeeOverrideUpsert { + u.Set(chargeflatfeeoverride.FieldProRating, v) + return u +} + +// UpdateProRating sets the "pro_rating" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsert) UpdateProRating() *ChargeFlatFeeOverrideUpsert { + u.SetExcluded(chargeflatfeeoverride.FieldProRating) + return u +} + +// SetAmountBeforeProration sets the "amount_before_proration" field. +func (u *ChargeFlatFeeOverrideUpsert) SetAmountBeforeProration(v alpacadecimal.Decimal) *ChargeFlatFeeOverrideUpsert { + u.Set(chargeflatfeeoverride.FieldAmountBeforeProration, v) + return u +} + +// UpdateAmountBeforeProration sets the "amount_before_proration" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsert) UpdateAmountBeforeProration() *ChargeFlatFeeOverrideUpsert { + u.SetExcluded(chargeflatfeeoverride.FieldAmountBeforeProration) + return u +} + +// SetDiscounts sets the "discounts" field. +func (u *ChargeFlatFeeOverrideUpsert) SetDiscounts(v *billing.Discounts) *ChargeFlatFeeOverrideUpsert { + u.Set(chargeflatfeeoverride.FieldDiscounts, v) + return u +} + +// UpdateDiscounts sets the "discounts" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsert) UpdateDiscounts() *ChargeFlatFeeOverrideUpsert { + u.SetExcluded(chargeflatfeeoverride.FieldDiscounts) + return u +} + +// ClearDiscounts clears the value of the "discounts" field. +func (u *ChargeFlatFeeOverrideUpsert) ClearDiscounts() *ChargeFlatFeeOverrideUpsert { + u.SetNull(chargeflatfeeoverride.FieldDiscounts) + return u +} + +// SetPercentageDiscounts sets the "percentage_discounts" field. +func (u *ChargeFlatFeeOverrideUpsert) SetPercentageDiscounts(v *billing.PercentageDiscount) *ChargeFlatFeeOverrideUpsert { + u.Set(chargeflatfeeoverride.FieldPercentageDiscounts, v) + return u +} + +// UpdatePercentageDiscounts sets the "percentage_discounts" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsert) UpdatePercentageDiscounts() *ChargeFlatFeeOverrideUpsert { + u.SetExcluded(chargeflatfeeoverride.FieldPercentageDiscounts) + return u +} + +// ClearPercentageDiscounts clears the value of the "percentage_discounts" field. +func (u *ChargeFlatFeeOverrideUpsert) ClearPercentageDiscounts() *ChargeFlatFeeOverrideUpsert { + u.SetNull(chargeflatfeeoverride.FieldPercentageDiscounts) + 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.ChargeFlatFeeOverride.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeflatfeeoverride.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeFlatFeeOverrideUpsertOne) UpdateNewValues() *ChargeFlatFeeOverrideUpsertOne { + 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(chargeflatfeeoverride.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(chargeflatfeeoverride.FieldNamespace) + } + if _, exists := u.create.mutation.ChargeID(); exists { + s.SetIgnore(chargeflatfeeoverride.FieldChargeID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeFlatFeeOverride.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeFlatFeeOverrideUpsertOne) Ignore() *ChargeFlatFeeOverrideUpsertOne { + 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 *ChargeFlatFeeOverrideUpsertOne) DoNothing() *ChargeFlatFeeOverrideUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeFlatFeeOverrideCreate.OnConflict +// documentation for more info. +func (u *ChargeFlatFeeOverrideUpsertOne) Update(set func(*ChargeFlatFeeOverrideUpsert)) *ChargeFlatFeeOverrideUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeFlatFeeOverrideUpsert{UpdateSet: update}) + })) + return u +} + +// SetName sets the "name" field. +func (u *ChargeFlatFeeOverrideUpsertOne) SetName(v string) *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertOne) UpdateName() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *ChargeFlatFeeOverrideUpsertOne) SetDescription(v string) *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertOne) UpdateDescription() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeFlatFeeOverrideUpsertOne) ClearDescription() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.ClearDescription() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeFlatFeeOverrideUpsertOne) SetMetadata(v *models.Metadata) *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertOne) UpdateMetadata() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeFlatFeeOverrideUpsertOne) ClearMetadata() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.ClearMetadata() + }) +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (u *ChargeFlatFeeOverrideUpsertOne) SetTaxBehavior(v productcatalog.TaxBehavior) *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetTaxBehavior(v) + }) +} + +// UpdateTaxBehavior sets the "tax_behavior" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertOne) UpdateTaxBehavior() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateTaxBehavior() + }) +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (u *ChargeFlatFeeOverrideUpsertOne) ClearTaxBehavior() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.ClearTaxBehavior() + }) +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (u *ChargeFlatFeeOverrideUpsertOne) SetTaxCodeID(v string) *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetTaxCodeID(v) + }) +} + +// UpdateTaxCodeID sets the "tax_code_id" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertOne) UpdateTaxCodeID() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateTaxCodeID() + }) +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (u *ChargeFlatFeeOverrideUpsertOne) ClearTaxCodeID() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.ClearTaxCodeID() + }) +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (u *ChargeFlatFeeOverrideUpsertOne) SetIntentDeletedAt(v time.Time) *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetIntentDeletedAt(v) + }) +} + +// UpdateIntentDeletedAt sets the "intent_deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertOne) UpdateIntentDeletedAt() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateIntentDeletedAt() + }) +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (u *ChargeFlatFeeOverrideUpsertOne) ClearIntentDeletedAt() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.ClearIntentDeletedAt() + }) +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeFlatFeeOverrideUpsertOne) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertOne) UpdateServicePeriodFrom() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeFlatFeeOverrideUpsertOne) SetServicePeriodTo(v time.Time) *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertOne) UpdateServicePeriodTo() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (u *ChargeFlatFeeOverrideUpsertOne) SetFullServicePeriodFrom(v time.Time) *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetFullServicePeriodFrom(v) + }) +} + +// UpdateFullServicePeriodFrom sets the "full_service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertOne) UpdateFullServicePeriodFrom() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateFullServicePeriodFrom() + }) +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (u *ChargeFlatFeeOverrideUpsertOne) SetFullServicePeriodTo(v time.Time) *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetFullServicePeriodTo(v) + }) +} + +// UpdateFullServicePeriodTo sets the "full_service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertOne) UpdateFullServicePeriodTo() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateFullServicePeriodTo() + }) +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (u *ChargeFlatFeeOverrideUpsertOne) SetBillingPeriodFrom(v time.Time) *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetBillingPeriodFrom(v) + }) +} + +// UpdateBillingPeriodFrom sets the "billing_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertOne) UpdateBillingPeriodFrom() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateBillingPeriodFrom() + }) +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (u *ChargeFlatFeeOverrideUpsertOne) SetBillingPeriodTo(v time.Time) *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetBillingPeriodTo(v) + }) +} + +// UpdateBillingPeriodTo sets the "billing_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertOne) UpdateBillingPeriodTo() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateBillingPeriodTo() + }) +} + +// SetInvoiceAt sets the "invoice_at" field. +func (u *ChargeFlatFeeOverrideUpsertOne) SetInvoiceAt(v time.Time) *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetInvoiceAt(v) + }) +} + +// UpdateInvoiceAt sets the "invoice_at" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertOne) UpdateInvoiceAt() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateInvoiceAt() + }) +} + +// SetFeatureKey sets the "feature_key" field. +func (u *ChargeFlatFeeOverrideUpsertOne) SetFeatureKey(v string) *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetFeatureKey(v) + }) +} + +// UpdateFeatureKey sets the "feature_key" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertOne) UpdateFeatureKey() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateFeatureKey() + }) +} + +// ClearFeatureKey clears the value of the "feature_key" field. +func (u *ChargeFlatFeeOverrideUpsertOne) ClearFeatureKey() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.ClearFeatureKey() + }) +} + +// SetPaymentTerm sets the "payment_term" field. +func (u *ChargeFlatFeeOverrideUpsertOne) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetPaymentTerm(v) + }) +} + +// UpdatePaymentTerm sets the "payment_term" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertOne) UpdatePaymentTerm() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdatePaymentTerm() + }) +} + +// SetProRating sets the "pro_rating" field. +func (u *ChargeFlatFeeOverrideUpsertOne) SetProRating(v *productcatalog.ProRatingConfig) *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetProRating(v) + }) +} + +// UpdateProRating sets the "pro_rating" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertOne) UpdateProRating() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateProRating() + }) +} + +// SetAmountBeforeProration sets the "amount_before_proration" field. +func (u *ChargeFlatFeeOverrideUpsertOne) SetAmountBeforeProration(v alpacadecimal.Decimal) *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetAmountBeforeProration(v) + }) +} + +// UpdateAmountBeforeProration sets the "amount_before_proration" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertOne) UpdateAmountBeforeProration() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateAmountBeforeProration() + }) +} + +// SetDiscounts sets the "discounts" field. +func (u *ChargeFlatFeeOverrideUpsertOne) SetDiscounts(v *billing.Discounts) *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetDiscounts(v) + }) +} + +// UpdateDiscounts sets the "discounts" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertOne) UpdateDiscounts() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateDiscounts() + }) +} + +// ClearDiscounts clears the value of the "discounts" field. +func (u *ChargeFlatFeeOverrideUpsertOne) ClearDiscounts() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.ClearDiscounts() + }) +} + +// SetPercentageDiscounts sets the "percentage_discounts" field. +func (u *ChargeFlatFeeOverrideUpsertOne) SetPercentageDiscounts(v *billing.PercentageDiscount) *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetPercentageDiscounts(v) + }) +} + +// UpdatePercentageDiscounts sets the "percentage_discounts" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertOne) UpdatePercentageDiscounts() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdatePercentageDiscounts() + }) +} + +// ClearPercentageDiscounts clears the value of the "percentage_discounts" field. +func (u *ChargeFlatFeeOverrideUpsertOne) ClearPercentageDiscounts() *ChargeFlatFeeOverrideUpsertOne { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.ClearPercentageDiscounts() + }) +} + +// Exec executes the query. +func (u *ChargeFlatFeeOverrideUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeFlatFeeOverrideCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeFlatFeeOverrideUpsertOne) 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 *ChargeFlatFeeOverrideUpsertOne) 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: ChargeFlatFeeOverrideUpsertOne.ID is not supported by MySQL driver. Use ChargeFlatFeeOverrideUpsertOne.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 *ChargeFlatFeeOverrideUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ChargeFlatFeeOverrideCreateBulk is the builder for creating many ChargeFlatFeeOverride entities in bulk. +type ChargeFlatFeeOverrideCreateBulk struct { + config + err error + builders []*ChargeFlatFeeOverrideCreate + conflict []sql.ConflictOption +} + +// Save creates the ChargeFlatFeeOverride entities in the database. +func (_c *ChargeFlatFeeOverrideCreateBulk) Save(ctx context.Context) ([]*ChargeFlatFeeOverride, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ChargeFlatFeeOverride, 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.(*ChargeFlatFeeOverrideMutation) + 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 *ChargeFlatFeeOverrideCreateBulk) SaveX(ctx context.Context) []*ChargeFlatFeeOverride { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeFlatFeeOverrideCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeFlatFeeOverrideCreateBulk) 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.ChargeFlatFeeOverride.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.ChargeFlatFeeOverrideUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *ChargeFlatFeeOverrideCreateBulk) OnConflict(opts ...sql.ConflictOption) *ChargeFlatFeeOverrideUpsertBulk { + _c.conflict = opts + return &ChargeFlatFeeOverrideUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeFlatFeeOverride.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeFlatFeeOverrideCreateBulk) OnConflictColumns(columns ...string) *ChargeFlatFeeOverrideUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeFlatFeeOverrideUpsertBulk{ + create: _c, + } +} + +// ChargeFlatFeeOverrideUpsertBulk is the builder for "upsert"-ing +// a bulk of ChargeFlatFeeOverride nodes. +type ChargeFlatFeeOverrideUpsertBulk struct { + create *ChargeFlatFeeOverrideCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ChargeFlatFeeOverride.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeflatfeeoverride.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeFlatFeeOverrideUpsertBulk) UpdateNewValues() *ChargeFlatFeeOverrideUpsertBulk { + 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(chargeflatfeeoverride.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(chargeflatfeeoverride.FieldNamespace) + } + if _, exists := b.mutation.ChargeID(); exists { + s.SetIgnore(chargeflatfeeoverride.FieldChargeID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeFlatFeeOverride.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeFlatFeeOverrideUpsertBulk) Ignore() *ChargeFlatFeeOverrideUpsertBulk { + 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 *ChargeFlatFeeOverrideUpsertBulk) DoNothing() *ChargeFlatFeeOverrideUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeFlatFeeOverrideCreateBulk.OnConflict +// documentation for more info. +func (u *ChargeFlatFeeOverrideUpsertBulk) Update(set func(*ChargeFlatFeeOverrideUpsert)) *ChargeFlatFeeOverrideUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeFlatFeeOverrideUpsert{UpdateSet: update}) + })) + return u +} + +// SetName sets the "name" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) SetName(v string) *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertBulk) UpdateName() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) SetDescription(v string) *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertBulk) UpdateDescription() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) ClearDescription() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.ClearDescription() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) SetMetadata(v *models.Metadata) *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertBulk) UpdateMetadata() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) ClearMetadata() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.ClearMetadata() + }) +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) SetTaxBehavior(v productcatalog.TaxBehavior) *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetTaxBehavior(v) + }) +} + +// UpdateTaxBehavior sets the "tax_behavior" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertBulk) UpdateTaxBehavior() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateTaxBehavior() + }) +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) ClearTaxBehavior() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.ClearTaxBehavior() + }) +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) SetTaxCodeID(v string) *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetTaxCodeID(v) + }) +} + +// UpdateTaxCodeID sets the "tax_code_id" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertBulk) UpdateTaxCodeID() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateTaxCodeID() + }) +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) ClearTaxCodeID() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.ClearTaxCodeID() + }) +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) SetIntentDeletedAt(v time.Time) *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetIntentDeletedAt(v) + }) +} + +// UpdateIntentDeletedAt sets the "intent_deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertBulk) UpdateIntentDeletedAt() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateIntentDeletedAt() + }) +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) ClearIntentDeletedAt() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.ClearIntentDeletedAt() + }) +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertBulk) UpdateServicePeriodFrom() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) SetServicePeriodTo(v time.Time) *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertBulk) UpdateServicePeriodTo() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) SetFullServicePeriodFrom(v time.Time) *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetFullServicePeriodFrom(v) + }) +} + +// UpdateFullServicePeriodFrom sets the "full_service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertBulk) UpdateFullServicePeriodFrom() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateFullServicePeriodFrom() + }) +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) SetFullServicePeriodTo(v time.Time) *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetFullServicePeriodTo(v) + }) +} + +// UpdateFullServicePeriodTo sets the "full_service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertBulk) UpdateFullServicePeriodTo() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateFullServicePeriodTo() + }) +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) SetBillingPeriodFrom(v time.Time) *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetBillingPeriodFrom(v) + }) +} + +// UpdateBillingPeriodFrom sets the "billing_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertBulk) UpdateBillingPeriodFrom() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateBillingPeriodFrom() + }) +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) SetBillingPeriodTo(v time.Time) *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetBillingPeriodTo(v) + }) +} + +// UpdateBillingPeriodTo sets the "billing_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertBulk) UpdateBillingPeriodTo() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateBillingPeriodTo() + }) +} + +// SetInvoiceAt sets the "invoice_at" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) SetInvoiceAt(v time.Time) *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetInvoiceAt(v) + }) +} + +// UpdateInvoiceAt sets the "invoice_at" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertBulk) UpdateInvoiceAt() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateInvoiceAt() + }) +} + +// SetFeatureKey sets the "feature_key" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) SetFeatureKey(v string) *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetFeatureKey(v) + }) +} + +// UpdateFeatureKey sets the "feature_key" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertBulk) UpdateFeatureKey() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateFeatureKey() + }) +} + +// ClearFeatureKey clears the value of the "feature_key" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) ClearFeatureKey() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.ClearFeatureKey() + }) +} + +// SetPaymentTerm sets the "payment_term" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetPaymentTerm(v) + }) +} + +// UpdatePaymentTerm sets the "payment_term" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertBulk) UpdatePaymentTerm() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdatePaymentTerm() + }) +} + +// SetProRating sets the "pro_rating" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) SetProRating(v *productcatalog.ProRatingConfig) *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetProRating(v) + }) +} + +// UpdateProRating sets the "pro_rating" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertBulk) UpdateProRating() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateProRating() + }) +} + +// SetAmountBeforeProration sets the "amount_before_proration" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) SetAmountBeforeProration(v alpacadecimal.Decimal) *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetAmountBeforeProration(v) + }) +} + +// UpdateAmountBeforeProration sets the "amount_before_proration" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertBulk) UpdateAmountBeforeProration() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateAmountBeforeProration() + }) +} + +// SetDiscounts sets the "discounts" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) SetDiscounts(v *billing.Discounts) *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetDiscounts(v) + }) +} + +// UpdateDiscounts sets the "discounts" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertBulk) UpdateDiscounts() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdateDiscounts() + }) +} + +// ClearDiscounts clears the value of the "discounts" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) ClearDiscounts() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.ClearDiscounts() + }) +} + +// SetPercentageDiscounts sets the "percentage_discounts" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) SetPercentageDiscounts(v *billing.PercentageDiscount) *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.SetPercentageDiscounts(v) + }) +} + +// UpdatePercentageDiscounts sets the "percentage_discounts" field to the value that was provided on create. +func (u *ChargeFlatFeeOverrideUpsertBulk) UpdatePercentageDiscounts() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.UpdatePercentageDiscounts() + }) +} + +// ClearPercentageDiscounts clears the value of the "percentage_discounts" field. +func (u *ChargeFlatFeeOverrideUpsertBulk) ClearPercentageDiscounts() *ChargeFlatFeeOverrideUpsertBulk { + return u.Update(func(s *ChargeFlatFeeOverrideUpsert) { + s.ClearPercentageDiscounts() + }) +} + +// Exec executes the query. +func (u *ChargeFlatFeeOverrideUpsertBulk) 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 ChargeFlatFeeOverrideCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeFlatFeeOverrideCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeFlatFeeOverrideUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargeflatfeeoverride_delete.go b/ent/db/chargeflatfeeoverride_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..873cd8b1e4a192f09d6f6799d01433007bbaf54d --- /dev/null +++ b/ent/db/chargeflatfeeoverride_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/chargeflatfeeoverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeFlatFeeOverrideDelete is the builder for deleting a ChargeFlatFeeOverride entity. +type ChargeFlatFeeOverrideDelete struct { + config + hooks []Hook + mutation *ChargeFlatFeeOverrideMutation +} + +// Where appends a list predicates to the ChargeFlatFeeOverrideDelete builder. +func (_d *ChargeFlatFeeOverrideDelete) Where(ps ...predicate.ChargeFlatFeeOverride) *ChargeFlatFeeOverrideDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ChargeFlatFeeOverrideDelete) 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 *ChargeFlatFeeOverrideDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ChargeFlatFeeOverrideDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(chargeflatfeeoverride.Table, sqlgraph.NewFieldSpec(chargeflatfeeoverride.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 +} + +// ChargeFlatFeeOverrideDeleteOne is the builder for deleting a single ChargeFlatFeeOverride entity. +type ChargeFlatFeeOverrideDeleteOne struct { + _d *ChargeFlatFeeOverrideDelete +} + +// Where appends a list predicates to the ChargeFlatFeeOverrideDelete builder. +func (_d *ChargeFlatFeeOverrideDeleteOne) Where(ps ...predicate.ChargeFlatFeeOverride) *ChargeFlatFeeOverrideDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ChargeFlatFeeOverrideDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{chargeflatfeeoverride.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeFlatFeeOverrideDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargeflatfeeoverride_query.go b/ent/db/chargeflatfeeoverride_query.go new file mode 100644 index 0000000000000000000000000000000000000000..5d759c717394eddea8688a0874b06650f27bc9f9 --- /dev/null +++ b/ent/db/chargeflatfeeoverride_query.go @@ -0,0 +1,721 @@ +// 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/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeoverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" +) + +// ChargeFlatFeeOverrideQuery is the builder for querying ChargeFlatFeeOverride entities. +type ChargeFlatFeeOverrideQuery struct { + config + ctx *QueryContext + order []chargeflatfeeoverride.OrderOption + inters []Interceptor + predicates []predicate.ChargeFlatFeeOverride + withFlatFee *ChargeFlatFeeQuery + withTaxCode *TaxCodeQuery + 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 ChargeFlatFeeOverrideQuery builder. +func (_q *ChargeFlatFeeOverrideQuery) Where(ps ...predicate.ChargeFlatFeeOverride) *ChargeFlatFeeOverrideQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ChargeFlatFeeOverrideQuery) Limit(limit int) *ChargeFlatFeeOverrideQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ChargeFlatFeeOverrideQuery) Offset(offset int) *ChargeFlatFeeOverrideQuery { + _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 *ChargeFlatFeeOverrideQuery) Unique(unique bool) *ChargeFlatFeeOverrideQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ChargeFlatFeeOverrideQuery) Order(o ...chargeflatfeeoverride.OrderOption) *ChargeFlatFeeOverrideQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryFlatFee chains the current query on the "flat_fee" edge. +func (_q *ChargeFlatFeeOverrideQuery) QueryFlatFee() *ChargeFlatFeeQuery { + query := (&ChargeFlatFeeClient{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(chargeflatfeeoverride.Table, chargeflatfeeoverride.FieldID, selector), + sqlgraph.To(chargeflatfee.Table, chargeflatfee.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargeflatfeeoverride.FlatFeeTable, chargeflatfeeoverride.FlatFeeColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryTaxCode chains the current query on the "tax_code" edge. +func (_q *ChargeFlatFeeOverrideQuery) QueryTaxCode() *TaxCodeQuery { + query := (&TaxCodeClient{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(chargeflatfeeoverride.Table, chargeflatfeeoverride.FieldID, selector), + sqlgraph.To(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfeeoverride.TaxCodeTable, chargeflatfeeoverride.TaxCodeColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ChargeFlatFeeOverride entity from the query. +// Returns a *NotFoundError when no ChargeFlatFeeOverride was found. +func (_q *ChargeFlatFeeOverrideQuery) First(ctx context.Context) (*ChargeFlatFeeOverride, 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{chargeflatfeeoverride.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ChargeFlatFeeOverrideQuery) FirstX(ctx context.Context) *ChargeFlatFeeOverride { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ChargeFlatFeeOverride ID from the query. +// Returns a *NotFoundError when no ChargeFlatFeeOverride ID was found. +func (_q *ChargeFlatFeeOverrideQuery) 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{chargeflatfeeoverride.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ChargeFlatFeeOverrideQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ChargeFlatFeeOverride entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ChargeFlatFeeOverride entity is found. +// Returns a *NotFoundError when no ChargeFlatFeeOverride entities are found. +func (_q *ChargeFlatFeeOverrideQuery) Only(ctx context.Context) (*ChargeFlatFeeOverride, 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{chargeflatfeeoverride.Label} + default: + return nil, &NotSingularError{chargeflatfeeoverride.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ChargeFlatFeeOverrideQuery) OnlyX(ctx context.Context) *ChargeFlatFeeOverride { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ChargeFlatFeeOverride ID in the query. +// Returns a *NotSingularError when more than one ChargeFlatFeeOverride ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ChargeFlatFeeOverrideQuery) 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{chargeflatfeeoverride.Label} + default: + err = &NotSingularError{chargeflatfeeoverride.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ChargeFlatFeeOverrideQuery) 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 ChargeFlatFeeOverrides. +func (_q *ChargeFlatFeeOverrideQuery) All(ctx context.Context) ([]*ChargeFlatFeeOverride, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ChargeFlatFeeOverride, *ChargeFlatFeeOverrideQuery]() + return withInterceptors[[]*ChargeFlatFeeOverride](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ChargeFlatFeeOverrideQuery) AllX(ctx context.Context) []*ChargeFlatFeeOverride { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ChargeFlatFeeOverride IDs. +func (_q *ChargeFlatFeeOverrideQuery) 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(chargeflatfeeoverride.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ChargeFlatFeeOverrideQuery) 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 *ChargeFlatFeeOverrideQuery) 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[*ChargeFlatFeeOverrideQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ChargeFlatFeeOverrideQuery) 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 *ChargeFlatFeeOverrideQuery) 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 *ChargeFlatFeeOverrideQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ChargeFlatFeeOverrideQuery 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 *ChargeFlatFeeOverrideQuery) Clone() *ChargeFlatFeeOverrideQuery { + if _q == nil { + return nil + } + return &ChargeFlatFeeOverrideQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]chargeflatfeeoverride.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ChargeFlatFeeOverride{}, _q.predicates...), + withFlatFee: _q.withFlatFee.Clone(), + withTaxCode: _q.withTaxCode.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithFlatFee tells the query-builder to eager-load the nodes that are connected to +// the "flat_fee" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeFlatFeeOverrideQuery) WithFlatFee(opts ...func(*ChargeFlatFeeQuery)) *ChargeFlatFeeOverrideQuery { + query := (&ChargeFlatFeeClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withFlatFee = query + return _q +} + +// WithTaxCode tells the query-builder to eager-load the nodes that are connected to +// the "tax_code" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeFlatFeeOverrideQuery) WithTaxCode(opts ...func(*TaxCodeQuery)) *ChargeFlatFeeOverrideQuery { + query := (&TaxCodeClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withTaxCode = 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.ChargeFlatFeeOverride.Query(). +// GroupBy(chargeflatfeeoverride.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *ChargeFlatFeeOverrideQuery) GroupBy(field string, fields ...string) *ChargeFlatFeeOverrideGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ChargeFlatFeeOverrideGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = chargeflatfeeoverride.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.ChargeFlatFeeOverride.Query(). +// Select(chargeflatfeeoverride.FieldNamespace). +// Scan(ctx, &v) +func (_q *ChargeFlatFeeOverrideQuery) Select(fields ...string) *ChargeFlatFeeOverrideSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ChargeFlatFeeOverrideSelect{ChargeFlatFeeOverrideQuery: _q} + sbuild.label = chargeflatfeeoverride.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ChargeFlatFeeOverrideSelect configured with the given aggregations. +func (_q *ChargeFlatFeeOverrideQuery) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeOverrideSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ChargeFlatFeeOverrideQuery) 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 !chargeflatfeeoverride.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 *ChargeFlatFeeOverrideQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ChargeFlatFeeOverride, error) { + var ( + nodes = []*ChargeFlatFeeOverride{} + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withFlatFee != nil, + _q.withTaxCode != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ChargeFlatFeeOverride).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ChargeFlatFeeOverride{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.withFlatFee; query != nil { + if err := _q.loadFlatFee(ctx, query, nodes, nil, + func(n *ChargeFlatFeeOverride, e *ChargeFlatFee) { n.Edges.FlatFee = e }); err != nil { + return nil, err + } + } + if query := _q.withTaxCode; query != nil { + if err := _q.loadTaxCode(ctx, query, nodes, nil, + func(n *ChargeFlatFeeOverride, e *TaxCode) { n.Edges.TaxCode = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ChargeFlatFeeOverrideQuery) loadFlatFee(ctx context.Context, query *ChargeFlatFeeQuery, nodes []*ChargeFlatFeeOverride, init func(*ChargeFlatFeeOverride), assign func(*ChargeFlatFeeOverride, *ChargeFlatFee)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeFlatFeeOverride) + 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(chargeflatfee.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 *ChargeFlatFeeOverrideQuery) loadTaxCode(ctx context.Context, query *TaxCodeQuery, nodes []*ChargeFlatFeeOverride, init func(*ChargeFlatFeeOverride), assign func(*ChargeFlatFeeOverride, *TaxCode)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeFlatFeeOverride) + for i := range nodes { + if nodes[i].TaxCodeID == nil { + continue + } + fk := *nodes[i].TaxCodeID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(dbtaxcode.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 "tax_code_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *ChargeFlatFeeOverrideQuery) 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 *ChargeFlatFeeOverrideQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(chargeflatfeeoverride.Table, chargeflatfeeoverride.Columns, sqlgraph.NewFieldSpec(chargeflatfeeoverride.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, chargeflatfeeoverride.FieldID) + for i := range fields { + if fields[i] != chargeflatfeeoverride.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withFlatFee != nil { + _spec.Node.AddColumnOnce(chargeflatfeeoverride.FieldChargeID) + } + if _q.withTaxCode != nil { + _spec.Node.AddColumnOnce(chargeflatfeeoverride.FieldTaxCodeID) + } + } + 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 *ChargeFlatFeeOverrideQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(chargeflatfeeoverride.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = chargeflatfeeoverride.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 *ChargeFlatFeeOverrideQuery) ForUpdate(opts ...sql.LockOption) *ChargeFlatFeeOverrideQuery { + 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 *ChargeFlatFeeOverrideQuery) ForShare(opts ...sql.LockOption) *ChargeFlatFeeOverrideQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ChargeFlatFeeOverrideGroupBy is the group-by builder for ChargeFlatFeeOverride entities. +type ChargeFlatFeeOverrideGroupBy struct { + selector + build *ChargeFlatFeeOverrideQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ChargeFlatFeeOverrideGroupBy) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeOverrideGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ChargeFlatFeeOverrideGroupBy) 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[*ChargeFlatFeeOverrideQuery, *ChargeFlatFeeOverrideGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ChargeFlatFeeOverrideGroupBy) sqlScan(ctx context.Context, root *ChargeFlatFeeOverrideQuery, 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) +} + +// ChargeFlatFeeOverrideSelect is the builder for selecting fields of ChargeFlatFeeOverride entities. +type ChargeFlatFeeOverrideSelect struct { + *ChargeFlatFeeOverrideQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ChargeFlatFeeOverrideSelect) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeOverrideSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ChargeFlatFeeOverrideSelect) 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[*ChargeFlatFeeOverrideQuery, *ChargeFlatFeeOverrideSelect](ctx, _s.ChargeFlatFeeOverrideQuery, _s, _s.inters, v) +} + +func (_s *ChargeFlatFeeOverrideSelect) sqlScan(ctx context.Context, root *ChargeFlatFeeOverrideQuery, 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/ent/db/chargeflatfeeoverride_update.go b/ent/db/chargeflatfeeoverride_update.go new file mode 100644 index 0000000000000000000000000000000000000000..00ac0e202787e5ce4aaddbc8d8dee7358c835808 --- /dev/null +++ b/ent/db/chargeflatfeeoverride_update.go @@ -0,0 +1,1099 @@ +// 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" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeoverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeFlatFeeOverrideUpdate is the builder for updating ChargeFlatFeeOverride entities. +type ChargeFlatFeeOverrideUpdate struct { + config + hooks []Hook + mutation *ChargeFlatFeeOverrideMutation +} + +// Where appends a list predicates to the ChargeFlatFeeOverrideUpdate builder. +func (_u *ChargeFlatFeeOverrideUpdate) Where(ps ...predicate.ChargeFlatFeeOverride) *ChargeFlatFeeOverrideUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetName sets the "name" field. +func (_u *ChargeFlatFeeOverrideUpdate) SetName(v string) *ChargeFlatFeeOverrideUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdate) SetNillableName(v *string) *ChargeFlatFeeOverrideUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *ChargeFlatFeeOverrideUpdate) SetDescription(v string) *ChargeFlatFeeOverrideUpdate { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdate) SetNillableDescription(v *string) *ChargeFlatFeeOverrideUpdate { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *ChargeFlatFeeOverrideUpdate) ClearDescription() *ChargeFlatFeeOverrideUpdate { + _u.mutation.ClearDescription() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *ChargeFlatFeeOverrideUpdate) SetMetadata(v *models.Metadata) *ChargeFlatFeeOverrideUpdate { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *ChargeFlatFeeOverrideUpdate) ClearMetadata() *ChargeFlatFeeOverrideUpdate { + _u.mutation.ClearMetadata() + return _u +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (_u *ChargeFlatFeeOverrideUpdate) SetTaxBehavior(v productcatalog.TaxBehavior) *ChargeFlatFeeOverrideUpdate { + _u.mutation.SetTaxBehavior(v) + return _u +} + +// SetNillableTaxBehavior sets the "tax_behavior" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdate) SetNillableTaxBehavior(v *productcatalog.TaxBehavior) *ChargeFlatFeeOverrideUpdate { + if v != nil { + _u.SetTaxBehavior(*v) + } + return _u +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (_u *ChargeFlatFeeOverrideUpdate) ClearTaxBehavior() *ChargeFlatFeeOverrideUpdate { + _u.mutation.ClearTaxBehavior() + return _u +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (_u *ChargeFlatFeeOverrideUpdate) SetTaxCodeID(v string) *ChargeFlatFeeOverrideUpdate { + _u.mutation.SetTaxCodeID(v) + return _u +} + +// SetNillableTaxCodeID sets the "tax_code_id" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdate) SetNillableTaxCodeID(v *string) *ChargeFlatFeeOverrideUpdate { + if v != nil { + _u.SetTaxCodeID(*v) + } + return _u +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (_u *ChargeFlatFeeOverrideUpdate) ClearTaxCodeID() *ChargeFlatFeeOverrideUpdate { + _u.mutation.ClearTaxCodeID() + return _u +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (_u *ChargeFlatFeeOverrideUpdate) SetIntentDeletedAt(v time.Time) *ChargeFlatFeeOverrideUpdate { + _u.mutation.SetIntentDeletedAt(v) + return _u +} + +// SetNillableIntentDeletedAt sets the "intent_deleted_at" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdate) SetNillableIntentDeletedAt(v *time.Time) *ChargeFlatFeeOverrideUpdate { + if v != nil { + _u.SetIntentDeletedAt(*v) + } + return _u +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (_u *ChargeFlatFeeOverrideUpdate) ClearIntentDeletedAt() *ChargeFlatFeeOverrideUpdate { + _u.mutation.ClearIntentDeletedAt() + return _u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeFlatFeeOverrideUpdate) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeOverrideUpdate { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdate) SetNillableServicePeriodFrom(v *time.Time) *ChargeFlatFeeOverrideUpdate { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeFlatFeeOverrideUpdate) SetServicePeriodTo(v time.Time) *ChargeFlatFeeOverrideUpdate { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdate) SetNillableServicePeriodTo(v *time.Time) *ChargeFlatFeeOverrideUpdate { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (_u *ChargeFlatFeeOverrideUpdate) SetFullServicePeriodFrom(v time.Time) *ChargeFlatFeeOverrideUpdate { + _u.mutation.SetFullServicePeriodFrom(v) + return _u +} + +// SetNillableFullServicePeriodFrom sets the "full_service_period_from" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdate) SetNillableFullServicePeriodFrom(v *time.Time) *ChargeFlatFeeOverrideUpdate { + if v != nil { + _u.SetFullServicePeriodFrom(*v) + } + return _u +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (_u *ChargeFlatFeeOverrideUpdate) SetFullServicePeriodTo(v time.Time) *ChargeFlatFeeOverrideUpdate { + _u.mutation.SetFullServicePeriodTo(v) + return _u +} + +// SetNillableFullServicePeriodTo sets the "full_service_period_to" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdate) SetNillableFullServicePeriodTo(v *time.Time) *ChargeFlatFeeOverrideUpdate { + if v != nil { + _u.SetFullServicePeriodTo(*v) + } + return _u +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (_u *ChargeFlatFeeOverrideUpdate) SetBillingPeriodFrom(v time.Time) *ChargeFlatFeeOverrideUpdate { + _u.mutation.SetBillingPeriodFrom(v) + return _u +} + +// SetNillableBillingPeriodFrom sets the "billing_period_from" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdate) SetNillableBillingPeriodFrom(v *time.Time) *ChargeFlatFeeOverrideUpdate { + if v != nil { + _u.SetBillingPeriodFrom(*v) + } + return _u +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (_u *ChargeFlatFeeOverrideUpdate) SetBillingPeriodTo(v time.Time) *ChargeFlatFeeOverrideUpdate { + _u.mutation.SetBillingPeriodTo(v) + return _u +} + +// SetNillableBillingPeriodTo sets the "billing_period_to" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdate) SetNillableBillingPeriodTo(v *time.Time) *ChargeFlatFeeOverrideUpdate { + if v != nil { + _u.SetBillingPeriodTo(*v) + } + return _u +} + +// SetInvoiceAt sets the "invoice_at" field. +func (_u *ChargeFlatFeeOverrideUpdate) SetInvoiceAt(v time.Time) *ChargeFlatFeeOverrideUpdate { + _u.mutation.SetInvoiceAt(v) + return _u +} + +// SetNillableInvoiceAt sets the "invoice_at" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdate) SetNillableInvoiceAt(v *time.Time) *ChargeFlatFeeOverrideUpdate { + if v != nil { + _u.SetInvoiceAt(*v) + } + return _u +} + +// SetFeatureKey sets the "feature_key" field. +func (_u *ChargeFlatFeeOverrideUpdate) SetFeatureKey(v string) *ChargeFlatFeeOverrideUpdate { + _u.mutation.SetFeatureKey(v) + return _u +} + +// SetNillableFeatureKey sets the "feature_key" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdate) SetNillableFeatureKey(v *string) *ChargeFlatFeeOverrideUpdate { + if v != nil { + _u.SetFeatureKey(*v) + } + return _u +} + +// ClearFeatureKey clears the value of the "feature_key" field. +func (_u *ChargeFlatFeeOverrideUpdate) ClearFeatureKey() *ChargeFlatFeeOverrideUpdate { + _u.mutation.ClearFeatureKey() + return _u +} + +// SetPaymentTerm sets the "payment_term" field. +func (_u *ChargeFlatFeeOverrideUpdate) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeFlatFeeOverrideUpdate { + _u.mutation.SetPaymentTerm(v) + return _u +} + +// SetNillablePaymentTerm sets the "payment_term" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdate) SetNillablePaymentTerm(v *productcatalog.PaymentTermType) *ChargeFlatFeeOverrideUpdate { + if v != nil { + _u.SetPaymentTerm(*v) + } + return _u +} + +// SetProRating sets the "pro_rating" field. +func (_u *ChargeFlatFeeOverrideUpdate) SetProRating(v *productcatalog.ProRatingConfig) *ChargeFlatFeeOverrideUpdate { + _u.mutation.SetProRating(v) + return _u +} + +// SetAmountBeforeProration sets the "amount_before_proration" field. +func (_u *ChargeFlatFeeOverrideUpdate) SetAmountBeforeProration(v alpacadecimal.Decimal) *ChargeFlatFeeOverrideUpdate { + _u.mutation.SetAmountBeforeProration(v) + return _u +} + +// SetNillableAmountBeforeProration sets the "amount_before_proration" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdate) SetNillableAmountBeforeProration(v *alpacadecimal.Decimal) *ChargeFlatFeeOverrideUpdate { + if v != nil { + _u.SetAmountBeforeProration(*v) + } + return _u +} + +// SetDiscounts sets the "discounts" field. +func (_u *ChargeFlatFeeOverrideUpdate) SetDiscounts(v *billing.Discounts) *ChargeFlatFeeOverrideUpdate { + _u.mutation.SetDiscounts(v) + return _u +} + +// ClearDiscounts clears the value of the "discounts" field. +func (_u *ChargeFlatFeeOverrideUpdate) ClearDiscounts() *ChargeFlatFeeOverrideUpdate { + _u.mutation.ClearDiscounts() + return _u +} + +// SetPercentageDiscounts sets the "percentage_discounts" field. +func (_u *ChargeFlatFeeOverrideUpdate) SetPercentageDiscounts(v *billing.PercentageDiscount) *ChargeFlatFeeOverrideUpdate { + _u.mutation.SetPercentageDiscounts(v) + return _u +} + +// ClearPercentageDiscounts clears the value of the "percentage_discounts" field. +func (_u *ChargeFlatFeeOverrideUpdate) ClearPercentageDiscounts() *ChargeFlatFeeOverrideUpdate { + _u.mutation.ClearPercentageDiscounts() + return _u +} + +// SetTaxCode sets the "tax_code" edge to the TaxCode entity. +func (_u *ChargeFlatFeeOverrideUpdate) SetTaxCode(v *TaxCode) *ChargeFlatFeeOverrideUpdate { + return _u.SetTaxCodeID(v.ID) +} + +// Mutation returns the ChargeFlatFeeOverrideMutation object of the builder. +func (_u *ChargeFlatFeeOverrideUpdate) Mutation() *ChargeFlatFeeOverrideMutation { + return _u.mutation +} + +// ClearTaxCode clears the "tax_code" edge to the TaxCode entity. +func (_u *ChargeFlatFeeOverrideUpdate) ClearTaxCode() *ChargeFlatFeeOverrideUpdate { + _u.mutation.ClearTaxCode() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ChargeFlatFeeOverrideUpdate) 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 *ChargeFlatFeeOverrideUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ChargeFlatFeeOverrideUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeFlatFeeOverrideUpdate) 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 *ChargeFlatFeeOverrideUpdate) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := chargeflatfeeoverride.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeOverride.name": %w`, err)} + } + } + if v, ok := _u.mutation.TaxBehavior(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "tax_behavior", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeOverride.tax_behavior": %w`, err)} + } + } + if v, ok := _u.mutation.FeatureKey(); ok { + if err := chargeflatfeeoverride.FeatureKeyValidator(v); err != nil { + return &ValidationError{Name: "feature_key", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeOverride.feature_key": %w`, err)} + } + } + if v, ok := _u.mutation.PaymentTerm(); ok { + if err := chargeflatfeeoverride.PaymentTermValidator(string(v)); err != nil { + return &ValidationError{Name: "payment_term", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeOverride.payment_term": %w`, err)} + } + } + if v, ok := _u.mutation.ProRating(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "pro_rating", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeOverride.pro_rating": %w`, err)} + } + } + 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 "ChargeFlatFeeOverride.discounts": %w`, err)} + } + } + if v, ok := _u.mutation.PercentageDiscounts(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "percentage_discounts", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeOverride.percentage_discounts": %w`, err)} + } + } + if _u.mutation.FlatFeeCleared() && len(_u.mutation.FlatFeeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeFlatFeeOverride.flat_fee"`) + } + return nil +} + +func (_u *ChargeFlatFeeOverrideUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeflatfeeoverride.Table, chargeflatfeeoverride.Columns, sqlgraph.NewFieldSpec(chargeflatfeeoverride.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.Name(); ok { + _spec.SetField(chargeflatfeeoverride.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(chargeflatfeeoverride.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(chargeflatfeeoverride.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.Metadata(); ok { + vv, err := chargeflatfeeoverride.ValueScanner.Metadata.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(chargeflatfeeoverride.FieldMetadata, field.TypeString, vv) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(chargeflatfeeoverride.FieldMetadata, field.TypeString) + } + if value, ok := _u.mutation.TaxBehavior(); ok { + _spec.SetField(chargeflatfeeoverride.FieldTaxBehavior, field.TypeString, value) + } + if _u.mutation.TaxBehaviorCleared() { + _spec.ClearField(chargeflatfeeoverride.FieldTaxBehavior, field.TypeString) + } + if value, ok := _u.mutation.IntentDeletedAt(); ok { + _spec.SetField(chargeflatfeeoverride.FieldIntentDeletedAt, field.TypeTime, value) + } + if _u.mutation.IntentDeletedAtCleared() { + _spec.ClearField(chargeflatfeeoverride.FieldIntentDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeflatfeeoverride.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeflatfeeoverride.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.FullServicePeriodFrom(); ok { + _spec.SetField(chargeflatfeeoverride.FieldFullServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.FullServicePeriodTo(); ok { + _spec.SetField(chargeflatfeeoverride.FieldFullServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.BillingPeriodFrom(); ok { + _spec.SetField(chargeflatfeeoverride.FieldBillingPeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.BillingPeriodTo(); ok { + _spec.SetField(chargeflatfeeoverride.FieldBillingPeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.InvoiceAt(); ok { + _spec.SetField(chargeflatfeeoverride.FieldInvoiceAt, field.TypeTime, value) + } + if value, ok := _u.mutation.FeatureKey(); ok { + _spec.SetField(chargeflatfeeoverride.FieldFeatureKey, field.TypeString, value) + } + if _u.mutation.FeatureKeyCleared() { + _spec.ClearField(chargeflatfeeoverride.FieldFeatureKey, field.TypeString) + } + if value, ok := _u.mutation.PaymentTerm(); ok { + _spec.SetField(chargeflatfeeoverride.FieldPaymentTerm, field.TypeString, value) + } + if value, ok := _u.mutation.ProRating(); ok { + vv, err := chargeflatfeeoverride.ValueScanner.ProRating.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(chargeflatfeeoverride.FieldProRating, field.TypeString, vv) + } + if value, ok := _u.mutation.AmountBeforeProration(); ok { + _spec.SetField(chargeflatfeeoverride.FieldAmountBeforeProration, field.TypeOther, value) + } + if value, ok := _u.mutation.Discounts(); ok { + vv, err := chargeflatfeeoverride.ValueScanner.Discounts.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(chargeflatfeeoverride.FieldDiscounts, field.TypeString, vv) + } + if _u.mutation.DiscountsCleared() { + _spec.ClearField(chargeflatfeeoverride.FieldDiscounts, field.TypeString) + } + if value, ok := _u.mutation.PercentageDiscounts(); ok { + vv, err := chargeflatfeeoverride.ValueScanner.PercentageDiscounts.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(chargeflatfeeoverride.FieldPercentageDiscounts, field.TypeString, vv) + } + if _u.mutation.PercentageDiscountsCleared() { + _spec.ClearField(chargeflatfeeoverride.FieldPercentageDiscounts, field.TypeString) + } + if _u.mutation.TaxCodeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfeeoverride.TaxCodeTable, + Columns: []string{chargeflatfeeoverride.TaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.TaxCodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfeeoverride.TaxCodeTable, + Columns: []string{chargeflatfeeoverride.TaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.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{chargeflatfeeoverride.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ChargeFlatFeeOverrideUpdateOne is the builder for updating a single ChargeFlatFeeOverride entity. +type ChargeFlatFeeOverrideUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ChargeFlatFeeOverrideMutation +} + +// SetName sets the "name" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetName(v string) *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetNillableName(v *string) *ChargeFlatFeeOverrideUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetDescription(v string) *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetNillableDescription(v *string) *ChargeFlatFeeOverrideUpdateOne { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) ClearDescription() *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.ClearDescription() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetMetadata(v *models.Metadata) *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) ClearMetadata() *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.ClearMetadata() + return _u +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetTaxBehavior(v productcatalog.TaxBehavior) *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.SetTaxBehavior(v) + return _u +} + +// SetNillableTaxBehavior sets the "tax_behavior" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetNillableTaxBehavior(v *productcatalog.TaxBehavior) *ChargeFlatFeeOverrideUpdateOne { + if v != nil { + _u.SetTaxBehavior(*v) + } + return _u +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) ClearTaxBehavior() *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.ClearTaxBehavior() + return _u +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetTaxCodeID(v string) *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.SetTaxCodeID(v) + return _u +} + +// SetNillableTaxCodeID sets the "tax_code_id" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetNillableTaxCodeID(v *string) *ChargeFlatFeeOverrideUpdateOne { + if v != nil { + _u.SetTaxCodeID(*v) + } + return _u +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) ClearTaxCodeID() *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.ClearTaxCodeID() + return _u +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetIntentDeletedAt(v time.Time) *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.SetIntentDeletedAt(v) + return _u +} + +// SetNillableIntentDeletedAt sets the "intent_deleted_at" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetNillableIntentDeletedAt(v *time.Time) *ChargeFlatFeeOverrideUpdateOne { + if v != nil { + _u.SetIntentDeletedAt(*v) + } + return _u +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) ClearIntentDeletedAt() *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.ClearIntentDeletedAt() + return _u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetNillableServicePeriodFrom(v *time.Time) *ChargeFlatFeeOverrideUpdateOne { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetServicePeriodTo(v time.Time) *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetNillableServicePeriodTo(v *time.Time) *ChargeFlatFeeOverrideUpdateOne { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetFullServicePeriodFrom(v time.Time) *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.SetFullServicePeriodFrom(v) + return _u +} + +// SetNillableFullServicePeriodFrom sets the "full_service_period_from" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetNillableFullServicePeriodFrom(v *time.Time) *ChargeFlatFeeOverrideUpdateOne { + if v != nil { + _u.SetFullServicePeriodFrom(*v) + } + return _u +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetFullServicePeriodTo(v time.Time) *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.SetFullServicePeriodTo(v) + return _u +} + +// SetNillableFullServicePeriodTo sets the "full_service_period_to" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetNillableFullServicePeriodTo(v *time.Time) *ChargeFlatFeeOverrideUpdateOne { + if v != nil { + _u.SetFullServicePeriodTo(*v) + } + return _u +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetBillingPeriodFrom(v time.Time) *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.SetBillingPeriodFrom(v) + return _u +} + +// SetNillableBillingPeriodFrom sets the "billing_period_from" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetNillableBillingPeriodFrom(v *time.Time) *ChargeFlatFeeOverrideUpdateOne { + if v != nil { + _u.SetBillingPeriodFrom(*v) + } + return _u +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetBillingPeriodTo(v time.Time) *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.SetBillingPeriodTo(v) + return _u +} + +// SetNillableBillingPeriodTo sets the "billing_period_to" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetNillableBillingPeriodTo(v *time.Time) *ChargeFlatFeeOverrideUpdateOne { + if v != nil { + _u.SetBillingPeriodTo(*v) + } + return _u +} + +// SetInvoiceAt sets the "invoice_at" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetInvoiceAt(v time.Time) *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.SetInvoiceAt(v) + return _u +} + +// SetNillableInvoiceAt sets the "invoice_at" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetNillableInvoiceAt(v *time.Time) *ChargeFlatFeeOverrideUpdateOne { + if v != nil { + _u.SetInvoiceAt(*v) + } + return _u +} + +// SetFeatureKey sets the "feature_key" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetFeatureKey(v string) *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.SetFeatureKey(v) + return _u +} + +// SetNillableFeatureKey sets the "feature_key" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetNillableFeatureKey(v *string) *ChargeFlatFeeOverrideUpdateOne { + if v != nil { + _u.SetFeatureKey(*v) + } + return _u +} + +// ClearFeatureKey clears the value of the "feature_key" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) ClearFeatureKey() *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.ClearFeatureKey() + return _u +} + +// SetPaymentTerm sets the "payment_term" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.SetPaymentTerm(v) + return _u +} + +// SetNillablePaymentTerm sets the "payment_term" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetNillablePaymentTerm(v *productcatalog.PaymentTermType) *ChargeFlatFeeOverrideUpdateOne { + if v != nil { + _u.SetPaymentTerm(*v) + } + return _u +} + +// SetProRating sets the "pro_rating" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetProRating(v *productcatalog.ProRatingConfig) *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.SetProRating(v) + return _u +} + +// SetAmountBeforeProration sets the "amount_before_proration" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetAmountBeforeProration(v alpacadecimal.Decimal) *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.SetAmountBeforeProration(v) + return _u +} + +// SetNillableAmountBeforeProration sets the "amount_before_proration" field if the given value is not nil. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetNillableAmountBeforeProration(v *alpacadecimal.Decimal) *ChargeFlatFeeOverrideUpdateOne { + if v != nil { + _u.SetAmountBeforeProration(*v) + } + return _u +} + +// SetDiscounts sets the "discounts" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetDiscounts(v *billing.Discounts) *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.SetDiscounts(v) + return _u +} + +// ClearDiscounts clears the value of the "discounts" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) ClearDiscounts() *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.ClearDiscounts() + return _u +} + +// SetPercentageDiscounts sets the "percentage_discounts" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetPercentageDiscounts(v *billing.PercentageDiscount) *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.SetPercentageDiscounts(v) + return _u +} + +// ClearPercentageDiscounts clears the value of the "percentage_discounts" field. +func (_u *ChargeFlatFeeOverrideUpdateOne) ClearPercentageDiscounts() *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.ClearPercentageDiscounts() + return _u +} + +// SetTaxCode sets the "tax_code" edge to the TaxCode entity. +func (_u *ChargeFlatFeeOverrideUpdateOne) SetTaxCode(v *TaxCode) *ChargeFlatFeeOverrideUpdateOne { + return _u.SetTaxCodeID(v.ID) +} + +// Mutation returns the ChargeFlatFeeOverrideMutation object of the builder. +func (_u *ChargeFlatFeeOverrideUpdateOne) Mutation() *ChargeFlatFeeOverrideMutation { + return _u.mutation +} + +// ClearTaxCode clears the "tax_code" edge to the TaxCode entity. +func (_u *ChargeFlatFeeOverrideUpdateOne) ClearTaxCode() *ChargeFlatFeeOverrideUpdateOne { + _u.mutation.ClearTaxCode() + return _u +} + +// Where appends a list predicates to the ChargeFlatFeeOverrideUpdate builder. +func (_u *ChargeFlatFeeOverrideUpdateOne) Where(ps ...predicate.ChargeFlatFeeOverride) *ChargeFlatFeeOverrideUpdateOne { + _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 *ChargeFlatFeeOverrideUpdateOne) Select(field string, fields ...string) *ChargeFlatFeeOverrideUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ChargeFlatFeeOverride entity. +func (_u *ChargeFlatFeeOverrideUpdateOne) Save(ctx context.Context) (*ChargeFlatFeeOverride, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeFlatFeeOverrideUpdateOne) SaveX(ctx context.Context) *ChargeFlatFeeOverride { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ChargeFlatFeeOverrideUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeFlatFeeOverrideUpdateOne) 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 *ChargeFlatFeeOverrideUpdateOne) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := chargeflatfeeoverride.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeOverride.name": %w`, err)} + } + } + if v, ok := _u.mutation.TaxBehavior(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "tax_behavior", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeOverride.tax_behavior": %w`, err)} + } + } + if v, ok := _u.mutation.FeatureKey(); ok { + if err := chargeflatfeeoverride.FeatureKeyValidator(v); err != nil { + return &ValidationError{Name: "feature_key", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeOverride.feature_key": %w`, err)} + } + } + if v, ok := _u.mutation.PaymentTerm(); ok { + if err := chargeflatfeeoverride.PaymentTermValidator(string(v)); err != nil { + return &ValidationError{Name: "payment_term", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeOverride.payment_term": %w`, err)} + } + } + if v, ok := _u.mutation.ProRating(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "pro_rating", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeOverride.pro_rating": %w`, err)} + } + } + 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 "ChargeFlatFeeOverride.discounts": %w`, err)} + } + } + if v, ok := _u.mutation.PercentageDiscounts(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "percentage_discounts", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeOverride.percentage_discounts": %w`, err)} + } + } + if _u.mutation.FlatFeeCleared() && len(_u.mutation.FlatFeeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeFlatFeeOverride.flat_fee"`) + } + return nil +} + +func (_u *ChargeFlatFeeOverrideUpdateOne) sqlSave(ctx context.Context) (_node *ChargeFlatFeeOverride, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeflatfeeoverride.Table, chargeflatfeeoverride.Columns, sqlgraph.NewFieldSpec(chargeflatfeeoverride.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "ChargeFlatFeeOverride.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, chargeflatfeeoverride.FieldID) + for _, f := range fields { + if !chargeflatfeeoverride.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != chargeflatfeeoverride.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.Name(); ok { + _spec.SetField(chargeflatfeeoverride.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(chargeflatfeeoverride.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(chargeflatfeeoverride.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.Metadata(); ok { + vv, err := chargeflatfeeoverride.ValueScanner.Metadata.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(chargeflatfeeoverride.FieldMetadata, field.TypeString, vv) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(chargeflatfeeoverride.FieldMetadata, field.TypeString) + } + if value, ok := _u.mutation.TaxBehavior(); ok { + _spec.SetField(chargeflatfeeoverride.FieldTaxBehavior, field.TypeString, value) + } + if _u.mutation.TaxBehaviorCleared() { + _spec.ClearField(chargeflatfeeoverride.FieldTaxBehavior, field.TypeString) + } + if value, ok := _u.mutation.IntentDeletedAt(); ok { + _spec.SetField(chargeflatfeeoverride.FieldIntentDeletedAt, field.TypeTime, value) + } + if _u.mutation.IntentDeletedAtCleared() { + _spec.ClearField(chargeflatfeeoverride.FieldIntentDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeflatfeeoverride.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeflatfeeoverride.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.FullServicePeriodFrom(); ok { + _spec.SetField(chargeflatfeeoverride.FieldFullServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.FullServicePeriodTo(); ok { + _spec.SetField(chargeflatfeeoverride.FieldFullServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.BillingPeriodFrom(); ok { + _spec.SetField(chargeflatfeeoverride.FieldBillingPeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.BillingPeriodTo(); ok { + _spec.SetField(chargeflatfeeoverride.FieldBillingPeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.InvoiceAt(); ok { + _spec.SetField(chargeflatfeeoverride.FieldInvoiceAt, field.TypeTime, value) + } + if value, ok := _u.mutation.FeatureKey(); ok { + _spec.SetField(chargeflatfeeoverride.FieldFeatureKey, field.TypeString, value) + } + if _u.mutation.FeatureKeyCleared() { + _spec.ClearField(chargeflatfeeoverride.FieldFeatureKey, field.TypeString) + } + if value, ok := _u.mutation.PaymentTerm(); ok { + _spec.SetField(chargeflatfeeoverride.FieldPaymentTerm, field.TypeString, value) + } + if value, ok := _u.mutation.ProRating(); ok { + vv, err := chargeflatfeeoverride.ValueScanner.ProRating.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(chargeflatfeeoverride.FieldProRating, field.TypeString, vv) + } + if value, ok := _u.mutation.AmountBeforeProration(); ok { + _spec.SetField(chargeflatfeeoverride.FieldAmountBeforeProration, field.TypeOther, value) + } + if value, ok := _u.mutation.Discounts(); ok { + vv, err := chargeflatfeeoverride.ValueScanner.Discounts.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(chargeflatfeeoverride.FieldDiscounts, field.TypeString, vv) + } + if _u.mutation.DiscountsCleared() { + _spec.ClearField(chargeflatfeeoverride.FieldDiscounts, field.TypeString) + } + if value, ok := _u.mutation.PercentageDiscounts(); ok { + vv, err := chargeflatfeeoverride.ValueScanner.PercentageDiscounts.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(chargeflatfeeoverride.FieldPercentageDiscounts, field.TypeString, vv) + } + if _u.mutation.PercentageDiscountsCleared() { + _spec.ClearField(chargeflatfeeoverride.FieldPercentageDiscounts, field.TypeString) + } + if _u.mutation.TaxCodeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfeeoverride.TaxCodeTable, + Columns: []string{chargeflatfeeoverride.TaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.TaxCodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfeeoverride.TaxCodeTable, + Columns: []string{chargeflatfeeoverride.TaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &ChargeFlatFeeOverride{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{chargeflatfeeoverride.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/ent/db/chargeflatfeerun.go b/ent/db/chargeflatfeerun.go new file mode 100644 index 0000000000000000000000000000000000000000..e31fb3c275edb8a38b77c19305167895c24169b1 --- /dev/null +++ b/ent/db/chargeflatfeerun.go @@ -0,0 +1,487 @@ +// 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/flatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerunpayment" +) + +// ChargeFlatFeeRun is the model entity for the ChargeFlatFeeRun schema. +type ChargeFlatFeeRun 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"` + // 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"` + // ChargeID holds the value of the "charge_id" field. + ChargeID string `json:"charge_id,omitempty"` + // Type holds the value of the "type" field. + Type flatfee.RealizationRunType `json:"type,omitempty"` + // InitialType holds the value of the "initial_type" field. + InitialType flatfee.RealizationRunType `json:"initial_type,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"` + // LineID holds the value of the "line_id" field. + LineID *string `json:"line_id,omitempty"` + // InvoiceID holds the value of the "invoice_id" field. + InvoiceID *string `json:"invoice_id,omitempty"` + // AmountAfterProration holds the value of the "amount_after_proration" field. + AmountAfterProration alpacadecimal.Decimal `json:"amount_after_proration,omitempty"` + // NoFiatTransactionRequired holds the value of the "no_fiat_transaction_required" field. + NoFiatTransactionRequired bool `json:"no_fiat_transaction_required,omitempty"` + // Immutable holds the value of the "immutable" field. + Immutable bool `json:"immutable,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ChargeFlatFeeRunQuery when eager-loading is set. + Edges ChargeFlatFeeRunEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ChargeFlatFeeRunEdges holds the relations/edges for other nodes in the graph. +type ChargeFlatFeeRunEdges struct { + // FlatFee holds the value of the flat_fee edge. + FlatFee *ChargeFlatFee `json:"flat_fee,omitempty"` + // BillingInvoiceLine holds the value of the billing_invoice_line edge. + BillingInvoiceLine *BillingInvoiceLine `json:"billing_invoice_line,omitempty"` + // BillingInvoice holds the value of the billing_invoice edge. + BillingInvoice *BillingInvoice `json:"billing_invoice,omitempty"` + // CreditAllocations holds the value of the credit_allocations edge. + CreditAllocations []*ChargeFlatFeeRunCreditAllocations `json:"credit_allocations,omitempty"` + // DetailedLines holds the value of the detailed_lines edge. + DetailedLines []*ChargeFlatFeeRunDetailedLine `json:"detailed_lines,omitempty"` + // InvoicedUsage holds the value of the invoiced_usage edge. + InvoicedUsage *ChargeFlatFeeRunInvoicedUsage `json:"invoiced_usage,omitempty"` + // Payment holds the value of the payment edge. + Payment *ChargeFlatFeeRunPayment `json:"payment,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [7]bool +} + +// FlatFeeOrErr returns the FlatFee value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeFlatFeeRunEdges) FlatFeeOrErr() (*ChargeFlatFee, error) { + if e.FlatFee != nil { + return e.FlatFee, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: chargeflatfee.Label} + } + return nil, &NotLoadedError{edge: "flat_fee"} +} + +// BillingInvoiceLineOrErr returns the BillingInvoiceLine value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeFlatFeeRunEdges) BillingInvoiceLineOrErr() (*BillingInvoiceLine, error) { + if e.BillingInvoiceLine != nil { + return e.BillingInvoiceLine, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: billinginvoiceline.Label} + } + return nil, &NotLoadedError{edge: "billing_invoice_line"} +} + +// BillingInvoiceOrErr returns the BillingInvoice value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeFlatFeeRunEdges) BillingInvoiceOrErr() (*BillingInvoice, error) { + if e.BillingInvoice != nil { + return e.BillingInvoice, nil + } else if e.loadedTypes[2] { + return nil, &NotFoundError{label: billinginvoice.Label} + } + return nil, &NotLoadedError{edge: "billing_invoice"} +} + +// CreditAllocationsOrErr returns the CreditAllocations value or an error if the edge +// was not loaded in eager-loading. +func (e ChargeFlatFeeRunEdges) CreditAllocationsOrErr() ([]*ChargeFlatFeeRunCreditAllocations, error) { + if e.loadedTypes[3] { + return e.CreditAllocations, nil + } + return nil, &NotLoadedError{edge: "credit_allocations"} +} + +// DetailedLinesOrErr returns the DetailedLines value or an error if the edge +// was not loaded in eager-loading. +func (e ChargeFlatFeeRunEdges) DetailedLinesOrErr() ([]*ChargeFlatFeeRunDetailedLine, error) { + if e.loadedTypes[4] { + return e.DetailedLines, nil + } + return nil, &NotLoadedError{edge: "detailed_lines"} +} + +// 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 ChargeFlatFeeRunEdges) InvoicedUsageOrErr() (*ChargeFlatFeeRunInvoicedUsage, error) { + if e.InvoicedUsage != nil { + return e.InvoicedUsage, nil + } else if e.loadedTypes[5] { + return nil, &NotFoundError{label: chargeflatfeeruninvoicedusage.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 ChargeFlatFeeRunEdges) PaymentOrErr() (*ChargeFlatFeeRunPayment, error) { + if e.Payment != nil { + return e.Payment, nil + } else if e.loadedTypes[6] { + return nil, &NotFoundError{label: chargeflatfeerunpayment.Label} + } + return nil, &NotLoadedError{edge: "payment"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ChargeFlatFeeRun) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case chargeflatfeerun.FieldAmount, chargeflatfeerun.FieldTaxesTotal, chargeflatfeerun.FieldTaxesInclusiveTotal, chargeflatfeerun.FieldTaxesExclusiveTotal, chargeflatfeerun.FieldChargesTotal, chargeflatfeerun.FieldDiscountsTotal, chargeflatfeerun.FieldCreditsTotal, chargeflatfeerun.FieldTotal, chargeflatfeerun.FieldAmountAfterProration: + values[i] = new(alpacadecimal.Decimal) + case chargeflatfeerun.FieldNoFiatTransactionRequired, chargeflatfeerun.FieldImmutable: + values[i] = new(sql.NullBool) + case chargeflatfeerun.FieldID, chargeflatfeerun.FieldNamespace, chargeflatfeerun.FieldChargeID, chargeflatfeerun.FieldType, chargeflatfeerun.FieldInitialType, chargeflatfeerun.FieldLineID, chargeflatfeerun.FieldInvoiceID: + values[i] = new(sql.NullString) + case chargeflatfeerun.FieldCreatedAt, chargeflatfeerun.FieldUpdatedAt, chargeflatfeerun.FieldDeletedAt, chargeflatfeerun.FieldServicePeriodFrom, chargeflatfeerun.FieldServicePeriodTo: + 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 ChargeFlatFeeRun fields. +func (_m *ChargeFlatFeeRun) 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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 = flatfee.RealizationRunType(value.String) + } + case chargeflatfeerun.FieldInitialType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field initial_type", values[i]) + } else if value.Valid { + _m.InitialType = flatfee.RealizationRunType(value.String) + } + case chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.FieldInvoiceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field invoice_id", values[i]) + } else if value.Valid { + _m.InvoiceID = new(string) + *_m.InvoiceID = value.String + } + case chargeflatfeerun.FieldAmountAfterProration: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field amount_after_proration", values[i]) + } else if value != nil { + _m.AmountAfterProration = *value + } + case chargeflatfeerun.FieldNoFiatTransactionRequired: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field no_fiat_transaction_required", values[i]) + } else if value.Valid { + _m.NoFiatTransactionRequired = value.Bool + } + case chargeflatfeerun.FieldImmutable: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field immutable", values[i]) + } else if value.Valid { + _m.Immutable = value.Bool + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the ChargeFlatFeeRun. +// This includes values selected through modifiers, order, etc. +func (_m *ChargeFlatFeeRun) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryFlatFee queries the "flat_fee" edge of the ChargeFlatFeeRun entity. +func (_m *ChargeFlatFeeRun) QueryFlatFee() *ChargeFlatFeeQuery { + return NewChargeFlatFeeRunClient(_m.config).QueryFlatFee(_m) +} + +// QueryBillingInvoiceLine queries the "billing_invoice_line" edge of the ChargeFlatFeeRun entity. +func (_m *ChargeFlatFeeRun) QueryBillingInvoiceLine() *BillingInvoiceLineQuery { + return NewChargeFlatFeeRunClient(_m.config).QueryBillingInvoiceLine(_m) +} + +// QueryBillingInvoice queries the "billing_invoice" edge of the ChargeFlatFeeRun entity. +func (_m *ChargeFlatFeeRun) QueryBillingInvoice() *BillingInvoiceQuery { + return NewChargeFlatFeeRunClient(_m.config).QueryBillingInvoice(_m) +} + +// QueryCreditAllocations queries the "credit_allocations" edge of the ChargeFlatFeeRun entity. +func (_m *ChargeFlatFeeRun) QueryCreditAllocations() *ChargeFlatFeeRunCreditAllocationsQuery { + return NewChargeFlatFeeRunClient(_m.config).QueryCreditAllocations(_m) +} + +// QueryDetailedLines queries the "detailed_lines" edge of the ChargeFlatFeeRun entity. +func (_m *ChargeFlatFeeRun) QueryDetailedLines() *ChargeFlatFeeRunDetailedLineQuery { + return NewChargeFlatFeeRunClient(_m.config).QueryDetailedLines(_m) +} + +// QueryInvoicedUsage queries the "invoiced_usage" edge of the ChargeFlatFeeRun entity. +func (_m *ChargeFlatFeeRun) QueryInvoicedUsage() *ChargeFlatFeeRunInvoicedUsageQuery { + return NewChargeFlatFeeRunClient(_m.config).QueryInvoicedUsage(_m) +} + +// QueryPayment queries the "payment" edge of the ChargeFlatFeeRun entity. +func (_m *ChargeFlatFeeRun) QueryPayment() *ChargeFlatFeeRunPaymentQuery { + return NewChargeFlatFeeRunClient(_m.config).QueryPayment(_m) +} + +// Update returns a builder for updating this ChargeFlatFeeRun. +// Note that you need to call ChargeFlatFeeRun.Unwrap() before calling this method if this ChargeFlatFeeRun +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ChargeFlatFeeRun) Update() *ChargeFlatFeeRunUpdateOne { + return NewChargeFlatFeeRunClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ChargeFlatFeeRun 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 *ChargeFlatFeeRun) Unwrap() *ChargeFlatFeeRun { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: ChargeFlatFeeRun is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ChargeFlatFeeRun) String() string { + var builder strings.Builder + builder.WriteString("ChargeFlatFeeRun(") + 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("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("charge_id=") + builder.WriteString(_m.ChargeID) + builder.WriteString(", ") + builder.WriteString("type=") + builder.WriteString(fmt.Sprintf("%v", _m.Type)) + builder.WriteString(", ") + builder.WriteString("initial_type=") + builder.WriteString(fmt.Sprintf("%v", _m.InitialType)) + 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(", ") + if v := _m.LineID; v != nil { + builder.WriteString("line_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.InvoiceID; v != nil { + builder.WriteString("invoice_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("amount_after_proration=") + builder.WriteString(fmt.Sprintf("%v", _m.AmountAfterProration)) + builder.WriteString(", ") + builder.WriteString("no_fiat_transaction_required=") + builder.WriteString(fmt.Sprintf("%v", _m.NoFiatTransactionRequired)) + builder.WriteString(", ") + builder.WriteString("immutable=") + builder.WriteString(fmt.Sprintf("%v", _m.Immutable)) + builder.WriteByte(')') + return builder.String() +} + +// ChargeFlatFeeRuns is a parsable slice of ChargeFlatFeeRun. +type ChargeFlatFeeRuns []*ChargeFlatFeeRun diff --git a/ent/db/chargeflatfeerun/chargeflatfeerun.go b/ent/db/chargeflatfeerun/chargeflatfeerun.go new file mode 100644 index 0000000000000000000000000000000000000000..82d1ed5b49be250ca72cc742d1e46ae6c041a8d0 --- /dev/null +++ b/ent/db/chargeflatfeerun/chargeflatfeerun.go @@ -0,0 +1,432 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeflatfeerun + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/billing/charges/flatfee" +) + +const ( + // Label holds the string label denoting the chargeflatfeerun type in the database. + Label = "charge_flat_fee_run" + // 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" + // 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" + // 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" + // FieldInitialType holds the string denoting the initial_type field in the database. + FieldInitialType = "initial_type" + // 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" + // FieldLineID holds the string denoting the line_id field in the database. + FieldLineID = "line_id" + // FieldInvoiceID holds the string denoting the invoice_id field in the database. + FieldInvoiceID = "invoice_id" + // FieldAmountAfterProration holds the string denoting the amount_after_proration field in the database. + FieldAmountAfterProration = "amount_after_proration" + // FieldNoFiatTransactionRequired holds the string denoting the no_fiat_transaction_required field in the database. + FieldNoFiatTransactionRequired = "no_fiat_transaction_required" + // FieldImmutable holds the string denoting the immutable field in the database. + FieldImmutable = "immutable" + // EdgeFlatFee holds the string denoting the flat_fee edge name in mutations. + EdgeFlatFee = "flat_fee" + // EdgeBillingInvoiceLine holds the string denoting the billing_invoice_line edge name in mutations. + EdgeBillingInvoiceLine = "billing_invoice_line" + // EdgeBillingInvoice holds the string denoting the billing_invoice edge name in mutations. + EdgeBillingInvoice = "billing_invoice" + // EdgeCreditAllocations holds the string denoting the credit_allocations edge name in mutations. + EdgeCreditAllocations = "credit_allocations" + // EdgeDetailedLines holds the string denoting the detailed_lines edge name in mutations. + EdgeDetailedLines = "detailed_lines" + // 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 chargeflatfeerun in the database. + Table = "charge_flat_fee_runs" + // FlatFeeTable is the table that holds the flat_fee relation/edge. + FlatFeeTable = "charge_flat_fee_runs" + // FlatFeeInverseTable is the table name for the ChargeFlatFee entity. + // It exists in this package in order to avoid circular dependency with the "chargeflatfee" package. + FlatFeeInverseTable = "charge_flat_fees" + // FlatFeeColumn is the table column denoting the flat_fee relation/edge. + FlatFeeColumn = "charge_id" + // BillingInvoiceLineTable is the table that holds the billing_invoice_line relation/edge. + BillingInvoiceLineTable = "charge_flat_fee_runs" + // BillingInvoiceLineInverseTable is the table name for the BillingInvoiceLine entity. + // It exists in this package in order to avoid circular dependency with the "billinginvoiceline" package. + BillingInvoiceLineInverseTable = "billing_invoice_lines" + // BillingInvoiceLineColumn is the table column denoting the billing_invoice_line relation/edge. + BillingInvoiceLineColumn = "line_id" + // BillingInvoiceTable is the table that holds the billing_invoice relation/edge. + BillingInvoiceTable = "charge_flat_fee_runs" + // BillingInvoiceInverseTable is the table name for the BillingInvoice entity. + // It exists in this package in order to avoid circular dependency with the "billinginvoice" package. + BillingInvoiceInverseTable = "billing_invoices" + // BillingInvoiceColumn is the table column denoting the billing_invoice relation/edge. + BillingInvoiceColumn = "invoice_id" + // CreditAllocationsTable is the table that holds the credit_allocations relation/edge. + CreditAllocationsTable = "charge_flat_fee_run_credit_allocations" + // CreditAllocationsInverseTable is the table name for the ChargeFlatFeeRunCreditAllocations entity. + // It exists in this package in order to avoid circular dependency with the "chargeflatfeeruncreditallocations" package. + CreditAllocationsInverseTable = "charge_flat_fee_run_credit_allocations" + // CreditAllocationsColumn is the table column denoting the credit_allocations relation/edge. + CreditAllocationsColumn = "run_id" + // DetailedLinesTable is the table that holds the detailed_lines relation/edge. + DetailedLinesTable = "charge_flat_fee_run_detailed_lines" + // DetailedLinesInverseTable is the table name for the ChargeFlatFeeRunDetailedLine entity. + // It exists in this package in order to avoid circular dependency with the "chargeflatfeerundetailedline" package. + DetailedLinesInverseTable = "charge_flat_fee_run_detailed_lines" + // DetailedLinesColumn is the table column denoting the detailed_lines relation/edge. + DetailedLinesColumn = "run_id" + // InvoicedUsageTable is the table that holds the invoiced_usage relation/edge. + InvoicedUsageTable = "charge_flat_fee_run_invoiced_usages" + // InvoicedUsageInverseTable is the table name for the ChargeFlatFeeRunInvoicedUsage entity. + // It exists in this package in order to avoid circular dependency with the "chargeflatfeeruninvoicedusage" package. + InvoicedUsageInverseTable = "charge_flat_fee_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_flat_fee_run_payments" + // PaymentInverseTable is the table name for the ChargeFlatFeeRunPayment entity. + // It exists in this package in order to avoid circular dependency with the "chargeflatfeerunpayment" package. + PaymentInverseTable = "charge_flat_fee_run_payments" + // PaymentColumn is the table column denoting the payment relation/edge. + PaymentColumn = "run_id" +) + +// Columns holds all SQL columns for chargeflatfeerun fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldAmount, + FieldTaxesTotal, + FieldTaxesInclusiveTotal, + FieldTaxesExclusiveTotal, + FieldChargesTotal, + FieldDiscountsTotal, + FieldCreditsTotal, + FieldTotal, + FieldChargeID, + FieldType, + FieldInitialType, + FieldServicePeriodFrom, + FieldServicePeriodTo, + FieldLineID, + FieldInvoiceID, + FieldAmountAfterProration, + FieldNoFiatTransactionRequired, + FieldImmutable, +} + +// 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 + // LineIDValidator is a validator for the "line_id" field. It is called by the builders before save. + LineIDValidator func(string) error + // InvoiceIDValidator is a validator for the "invoice_id" field. It is called by the builders before save. + InvoiceIDValidator func(string) error + // 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 flatfee.RealizationRunType) error { + switch _type { + case "final_realization", "invalid_due_to_unsupported_credit_note": + return nil + default: + return fmt.Errorf("chargeflatfeerun: invalid enum value for type field: %q", _type) + } +} + +// InitialTypeValidator is a validator for the "initial_type" field enum values. It is called by the builders before save. +func InitialTypeValidator(it flatfee.RealizationRunType) error { + switch it { + case "final_realization", "invalid_due_to_unsupported_credit_note": + return nil + default: + return fmt.Errorf("chargeflatfeerun: invalid enum value for initial_type field: %q", it) + } +} + +// OrderOption defines the ordering options for the ChargeFlatFeeRun 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() +} + +// 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() +} + +// 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() +} + +// ByInitialType orders the results by the initial_type field. +func ByInitialType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInitialType, 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() +} + +// ByLineID orders the results by the line_id field. +func ByLineID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLineID, opts...).ToFunc() +} + +// ByInvoiceID orders the results by the invoice_id field. +func ByInvoiceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoiceID, opts...).ToFunc() +} + +// ByAmountAfterProration orders the results by the amount_after_proration field. +func ByAmountAfterProration(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAmountAfterProration, opts...).ToFunc() +} + +// ByNoFiatTransactionRequired orders the results by the no_fiat_transaction_required field. +func ByNoFiatTransactionRequired(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldNoFiatTransactionRequired, opts...).ToFunc() +} + +// ByImmutable orders the results by the immutable field. +func ByImmutable(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldImmutable, opts...).ToFunc() +} + +// ByFlatFeeField orders the results by flat_fee field. +func ByFlatFeeField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newFlatFeeStep(), sql.OrderByField(field, opts...)) + } +} + +// ByBillingInvoiceLineField orders the results by billing_invoice_line field. +func ByBillingInvoiceLineField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBillingInvoiceLineStep(), sql.OrderByField(field, opts...)) + } +} + +// ByBillingInvoiceField orders the results by billing_invoice field. +func ByBillingInvoiceField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBillingInvoiceStep(), 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...)...) + } +} + +// ByDetailedLinesCount orders the results by detailed_lines count. +func ByDetailedLinesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newDetailedLinesStep(), opts...) + } +} + +// ByDetailedLines orders the results by detailed_lines terms. +func ByDetailedLines(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newDetailedLinesStep(), 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 newFlatFeeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(FlatFeeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, FlatFeeTable, FlatFeeColumn), + ) +} +func newBillingInvoiceLineStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BillingInvoiceLineInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, BillingInvoiceLineTable, BillingInvoiceLineColumn), + ) +} +func newBillingInvoiceStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BillingInvoiceInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, BillingInvoiceTable, BillingInvoiceColumn), + ) +} +func newCreditAllocationsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CreditAllocationsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, CreditAllocationsTable, CreditAllocationsColumn), + ) +} +func newDetailedLinesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(DetailedLinesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, DetailedLinesTable, DetailedLinesColumn), + ) +} +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/ent/db/chargeflatfeerun/where.go b/ent/db/chargeflatfeerun/where.go new file mode 100644 index 0000000000000000000000000000000000000000..cd086f1ee3519b0cbc4853e05d75bb177ec2d365 --- /dev/null +++ b/ent/db/chargeflatfeerun/where.go @@ -0,0 +1,1274 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeflatfeerun + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/billing/charges/flatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(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.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(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.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(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.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ. +func Amount(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(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.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(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.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(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.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(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.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(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.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(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.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldCreditsTotal, v)) +} + +// Total applies equality check predicate on the "total" field. It's identical to TotalEQ. +func Total(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldTotal, v)) +} + +// ChargeID applies equality check predicate on the "charge_id" field. It's identical to ChargeIDEQ. +func ChargeID(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldChargeID, v)) +} + +// ServicePeriodFrom applies equality check predicate on the "service_period_from" field. It's identical to ServicePeriodFromEQ. +func ServicePeriodFrom(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(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.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// LineID applies equality check predicate on the "line_id" field. It's identical to LineIDEQ. +func LineID(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldLineID, v)) +} + +// InvoiceID applies equality check predicate on the "invoice_id" field. It's identical to InvoiceIDEQ. +func InvoiceID(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldInvoiceID, v)) +} + +// AmountAfterProration applies equality check predicate on the "amount_after_proration" field. It's identical to AmountAfterProrationEQ. +func AmountAfterProration(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldAmountAfterProration, v)) +} + +// NoFiatTransactionRequired applies equality check predicate on the "no_fiat_transaction_required" field. It's identical to NoFiatTransactionRequiredEQ. +func NoFiatTransactionRequired(v bool) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldNoFiatTransactionRequired, v)) +} + +// Immutable applies equality check predicate on the "immutable" field. It's identical to ImmutableEQ. +func Immutable(v bool) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldImmutable, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotNull(FieldDeletedAt)) +} + +// AmountEQ applies the EQ predicate on the "amount" field. +func AmountEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldAmount, v)) +} + +// AmountNEQ applies the NEQ predicate on the "amount" field. +func AmountNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldAmount, v)) +} + +// AmountIn applies the In predicate on the "amount" field. +func AmountIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldAmount, vs...)) +} + +// AmountNotIn applies the NotIn predicate on the "amount" field. +func AmountNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldAmount, vs...)) +} + +// AmountGT applies the GT predicate on the "amount" field. +func AmountGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGT(FieldAmount, v)) +} + +// AmountGTE applies the GTE predicate on the "amount" field. +func AmountGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGTE(FieldAmount, v)) +} + +// AmountLT applies the LT predicate on the "amount" field. +func AmountLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLT(FieldAmount, v)) +} + +// AmountLTE applies the LTE predicate on the "amount" field. +func AmountLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLTE(FieldAmount, v)) +} + +// TaxesTotalEQ applies the EQ predicate on the "taxes_total" field. +func TaxesTotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldTaxesTotal, v)) +} + +// TaxesTotalNEQ applies the NEQ predicate on the "taxes_total" field. +func TaxesTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldTaxesTotal, v)) +} + +// TaxesTotalIn applies the In predicate on the "taxes_total" field. +func TaxesTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldTaxesTotal, vs...)) +} + +// TaxesTotalNotIn applies the NotIn predicate on the "taxes_total" field. +func TaxesTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldTaxesTotal, vs...)) +} + +// TaxesTotalGT applies the GT predicate on the "taxes_total" field. +func TaxesTotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGT(FieldTaxesTotal, v)) +} + +// TaxesTotalGTE applies the GTE predicate on the "taxes_total" field. +func TaxesTotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGTE(FieldTaxesTotal, v)) +} + +// TaxesTotalLT applies the LT predicate on the "taxes_total" field. +func TaxesTotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLT(FieldTaxesTotal, v)) +} + +// TaxesTotalLTE applies the LTE predicate on the "taxes_total" field. +func TaxesTotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLTE(FieldTaxesTotal, v)) +} + +// TaxesInclusiveTotalEQ applies the EQ predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalNEQ applies the NEQ predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalIn applies the In predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldTaxesInclusiveTotal, vs...)) +} + +// TaxesInclusiveTotalNotIn applies the NotIn predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldTaxesInclusiveTotal, vs...)) +} + +// TaxesInclusiveTotalGT applies the GT predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGT(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalGTE applies the GTE predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGTE(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalLT applies the LT predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLT(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalLTE applies the LTE predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLTE(FieldTaxesInclusiveTotal, v)) +} + +// TaxesExclusiveTotalEQ applies the EQ predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalNEQ applies the NEQ predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalIn applies the In predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldTaxesExclusiveTotal, vs...)) +} + +// TaxesExclusiveTotalNotIn applies the NotIn predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldTaxesExclusiveTotal, vs...)) +} + +// TaxesExclusiveTotalGT applies the GT predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGT(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalGTE applies the GTE predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGTE(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalLT applies the LT predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLT(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalLTE applies the LTE predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLTE(FieldTaxesExclusiveTotal, v)) +} + +// ChargesTotalEQ applies the EQ predicate on the "charges_total" field. +func ChargesTotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldChargesTotal, v)) +} + +// ChargesTotalNEQ applies the NEQ predicate on the "charges_total" field. +func ChargesTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldChargesTotal, v)) +} + +// ChargesTotalIn applies the In predicate on the "charges_total" field. +func ChargesTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldChargesTotal, vs...)) +} + +// ChargesTotalNotIn applies the NotIn predicate on the "charges_total" field. +func ChargesTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldChargesTotal, vs...)) +} + +// ChargesTotalGT applies the GT predicate on the "charges_total" field. +func ChargesTotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGT(FieldChargesTotal, v)) +} + +// ChargesTotalGTE applies the GTE predicate on the "charges_total" field. +func ChargesTotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGTE(FieldChargesTotal, v)) +} + +// ChargesTotalLT applies the LT predicate on the "charges_total" field. +func ChargesTotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLT(FieldChargesTotal, v)) +} + +// ChargesTotalLTE applies the LTE predicate on the "charges_total" field. +func ChargesTotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLTE(FieldChargesTotal, v)) +} + +// DiscountsTotalEQ applies the EQ predicate on the "discounts_total" field. +func DiscountsTotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldDiscountsTotal, v)) +} + +// DiscountsTotalNEQ applies the NEQ predicate on the "discounts_total" field. +func DiscountsTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldDiscountsTotal, v)) +} + +// DiscountsTotalIn applies the In predicate on the "discounts_total" field. +func DiscountsTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldDiscountsTotal, vs...)) +} + +// DiscountsTotalNotIn applies the NotIn predicate on the "discounts_total" field. +func DiscountsTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldDiscountsTotal, vs...)) +} + +// DiscountsTotalGT applies the GT predicate on the "discounts_total" field. +func DiscountsTotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGT(FieldDiscountsTotal, v)) +} + +// DiscountsTotalGTE applies the GTE predicate on the "discounts_total" field. +func DiscountsTotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGTE(FieldDiscountsTotal, v)) +} + +// DiscountsTotalLT applies the LT predicate on the "discounts_total" field. +func DiscountsTotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLT(FieldDiscountsTotal, v)) +} + +// DiscountsTotalLTE applies the LTE predicate on the "discounts_total" field. +func DiscountsTotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLTE(FieldDiscountsTotal, v)) +} + +// CreditsTotalEQ applies the EQ predicate on the "credits_total" field. +func CreditsTotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldCreditsTotal, v)) +} + +// CreditsTotalNEQ applies the NEQ predicate on the "credits_total" field. +func CreditsTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldCreditsTotal, v)) +} + +// CreditsTotalIn applies the In predicate on the "credits_total" field. +func CreditsTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldCreditsTotal, vs...)) +} + +// CreditsTotalNotIn applies the NotIn predicate on the "credits_total" field. +func CreditsTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldCreditsTotal, vs...)) +} + +// CreditsTotalGT applies the GT predicate on the "credits_total" field. +func CreditsTotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGT(FieldCreditsTotal, v)) +} + +// CreditsTotalGTE applies the GTE predicate on the "credits_total" field. +func CreditsTotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGTE(FieldCreditsTotal, v)) +} + +// CreditsTotalLT applies the LT predicate on the "credits_total" field. +func CreditsTotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLT(FieldCreditsTotal, v)) +} + +// CreditsTotalLTE applies the LTE predicate on the "credits_total" field. +func CreditsTotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLTE(FieldCreditsTotal, v)) +} + +// TotalEQ applies the EQ predicate on the "total" field. +func TotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldTotal, v)) +} + +// TotalNEQ applies the NEQ predicate on the "total" field. +func TotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldTotal, v)) +} + +// TotalIn applies the In predicate on the "total" field. +func TotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldTotal, vs...)) +} + +// TotalNotIn applies the NotIn predicate on the "total" field. +func TotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldTotal, vs...)) +} + +// TotalGT applies the GT predicate on the "total" field. +func TotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGT(FieldTotal, v)) +} + +// TotalGTE applies the GTE predicate on the "total" field. +func TotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGTE(FieldTotal, v)) +} + +// TotalLT applies the LT predicate on the "total" field. +func TotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLT(FieldTotal, v)) +} + +// TotalLTE applies the LTE predicate on the "total" field. +func TotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLTE(FieldTotal, v)) +} + +// ChargeIDEQ applies the EQ predicate on the "charge_id" field. +func ChargeIDEQ(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldChargeID, v)) +} + +// ChargeIDNEQ applies the NEQ predicate on the "charge_id" field. +func ChargeIDNEQ(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldChargeID, v)) +} + +// ChargeIDIn applies the In predicate on the "charge_id" field. +func ChargeIDIn(vs ...string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldChargeID, vs...)) +} + +// ChargeIDNotIn applies the NotIn predicate on the "charge_id" field. +func ChargeIDNotIn(vs ...string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldChargeID, vs...)) +} + +// ChargeIDGT applies the GT predicate on the "charge_id" field. +func ChargeIDGT(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGT(FieldChargeID, v)) +} + +// ChargeIDGTE applies the GTE predicate on the "charge_id" field. +func ChargeIDGTE(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGTE(FieldChargeID, v)) +} + +// ChargeIDLT applies the LT predicate on the "charge_id" field. +func ChargeIDLT(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLT(FieldChargeID, v)) +} + +// ChargeIDLTE applies the LTE predicate on the "charge_id" field. +func ChargeIDLTE(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLTE(FieldChargeID, v)) +} + +// ChargeIDContains applies the Contains predicate on the "charge_id" field. +func ChargeIDContains(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldContains(FieldChargeID, v)) +} + +// ChargeIDHasPrefix applies the HasPrefix predicate on the "charge_id" field. +func ChargeIDHasPrefix(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldHasPrefix(FieldChargeID, v)) +} + +// ChargeIDHasSuffix applies the HasSuffix predicate on the "charge_id" field. +func ChargeIDHasSuffix(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldHasSuffix(FieldChargeID, v)) +} + +// ChargeIDEqualFold applies the EqualFold predicate on the "charge_id" field. +func ChargeIDEqualFold(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEqualFold(FieldChargeID, v)) +} + +// ChargeIDContainsFold applies the ContainsFold predicate on the "charge_id" field. +func ChargeIDContainsFold(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldContainsFold(FieldChargeID, v)) +} + +// TypeEQ applies the EQ predicate on the "type" field. +func TypeEQ(v flatfee.RealizationRunType) predicate.ChargeFlatFeeRun { + vc := v + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldType, vc)) +} + +// TypeNEQ applies the NEQ predicate on the "type" field. +func TypeNEQ(v flatfee.RealizationRunType) predicate.ChargeFlatFeeRun { + vc := v + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldType, vc)) +} + +// TypeIn applies the In predicate on the "type" field. +func TypeIn(vs ...flatfee.RealizationRunType) predicate.ChargeFlatFeeRun { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldType, v...)) +} + +// TypeNotIn applies the NotIn predicate on the "type" field. +func TypeNotIn(vs ...flatfee.RealizationRunType) predicate.ChargeFlatFeeRun { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldType, v...)) +} + +// InitialTypeEQ applies the EQ predicate on the "initial_type" field. +func InitialTypeEQ(v flatfee.RealizationRunType) predicate.ChargeFlatFeeRun { + vc := v + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldInitialType, vc)) +} + +// InitialTypeNEQ applies the NEQ predicate on the "initial_type" field. +func InitialTypeNEQ(v flatfee.RealizationRunType) predicate.ChargeFlatFeeRun { + vc := v + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldInitialType, vc)) +} + +// InitialTypeIn applies the In predicate on the "initial_type" field. +func InitialTypeIn(vs ...flatfee.RealizationRunType) predicate.ChargeFlatFeeRun { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldInitialType, v...)) +} + +// InitialTypeNotIn applies the NotIn predicate on the "initial_type" field. +func InitialTypeNotIn(vs ...flatfee.RealizationRunType) predicate.ChargeFlatFeeRun { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldInitialType, v...)) +} + +// ServicePeriodFromEQ applies the EQ predicate on the "service_period_from" field. +func ServicePeriodFromEQ(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromNEQ applies the NEQ predicate on the "service_period_from" field. +func ServicePeriodFromNEQ(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromIn applies the In predicate on the "service_period_from" field. +func ServicePeriodFromIn(vs ...time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromNotIn applies the NotIn predicate on the "service_period_from" field. +func ServicePeriodFromNotIn(vs ...time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromGT applies the GT predicate on the "service_period_from" field. +func ServicePeriodFromGT(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromGTE applies the GTE predicate on the "service_period_from" field. +func ServicePeriodFromGTE(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLT applies the LT predicate on the "service_period_from" field. +func ServicePeriodFromLT(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLTE applies the LTE predicate on the "service_period_from" field. +func ServicePeriodFromLTE(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodToEQ applies the EQ predicate on the "service_period_to" field. +func ServicePeriodToEQ(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToNEQ applies the NEQ predicate on the "service_period_to" field. +func ServicePeriodToNEQ(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToIn applies the In predicate on the "service_period_to" field. +func ServicePeriodToIn(vs ...time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToNotIn applies the NotIn predicate on the "service_period_to" field. +func ServicePeriodToNotIn(vs ...time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToGT applies the GT predicate on the "service_period_to" field. +func ServicePeriodToGT(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToGTE applies the GTE predicate on the "service_period_to" field. +func ServicePeriodToGTE(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGTE(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLT applies the LT predicate on the "service_period_to" field. +func ServicePeriodToLT(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLTE applies the LTE predicate on the "service_period_to" field. +func ServicePeriodToLTE(v time.Time) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLTE(FieldServicePeriodTo, v)) +} + +// LineIDEQ applies the EQ predicate on the "line_id" field. +func LineIDEQ(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldLineID, v)) +} + +// LineIDNEQ applies the NEQ predicate on the "line_id" field. +func LineIDNEQ(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldLineID, v)) +} + +// LineIDIn applies the In predicate on the "line_id" field. +func LineIDIn(vs ...string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldLineID, vs...)) +} + +// LineIDNotIn applies the NotIn predicate on the "line_id" field. +func LineIDNotIn(vs ...string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldLineID, vs...)) +} + +// LineIDGT applies the GT predicate on the "line_id" field. +func LineIDGT(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGT(FieldLineID, v)) +} + +// LineIDGTE applies the GTE predicate on the "line_id" field. +func LineIDGTE(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGTE(FieldLineID, v)) +} + +// LineIDLT applies the LT predicate on the "line_id" field. +func LineIDLT(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLT(FieldLineID, v)) +} + +// LineIDLTE applies the LTE predicate on the "line_id" field. +func LineIDLTE(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLTE(FieldLineID, v)) +} + +// LineIDContains applies the Contains predicate on the "line_id" field. +func LineIDContains(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldContains(FieldLineID, v)) +} + +// LineIDHasPrefix applies the HasPrefix predicate on the "line_id" field. +func LineIDHasPrefix(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldHasPrefix(FieldLineID, v)) +} + +// LineIDHasSuffix applies the HasSuffix predicate on the "line_id" field. +func LineIDHasSuffix(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldHasSuffix(FieldLineID, v)) +} + +// LineIDIsNil applies the IsNil predicate on the "line_id" field. +func LineIDIsNil() predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIsNull(FieldLineID)) +} + +// LineIDNotNil applies the NotNil predicate on the "line_id" field. +func LineIDNotNil() predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotNull(FieldLineID)) +} + +// LineIDEqualFold applies the EqualFold predicate on the "line_id" field. +func LineIDEqualFold(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEqualFold(FieldLineID, v)) +} + +// LineIDContainsFold applies the ContainsFold predicate on the "line_id" field. +func LineIDContainsFold(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldContainsFold(FieldLineID, v)) +} + +// InvoiceIDEQ applies the EQ predicate on the "invoice_id" field. +func InvoiceIDEQ(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldInvoiceID, v)) +} + +// InvoiceIDNEQ applies the NEQ predicate on the "invoice_id" field. +func InvoiceIDNEQ(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldInvoiceID, v)) +} + +// InvoiceIDIn applies the In predicate on the "invoice_id" field. +func InvoiceIDIn(vs ...string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldInvoiceID, vs...)) +} + +// InvoiceIDNotIn applies the NotIn predicate on the "invoice_id" field. +func InvoiceIDNotIn(vs ...string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldInvoiceID, vs...)) +} + +// InvoiceIDGT applies the GT predicate on the "invoice_id" field. +func InvoiceIDGT(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGT(FieldInvoiceID, v)) +} + +// InvoiceIDGTE applies the GTE predicate on the "invoice_id" field. +func InvoiceIDGTE(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGTE(FieldInvoiceID, v)) +} + +// InvoiceIDLT applies the LT predicate on the "invoice_id" field. +func InvoiceIDLT(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLT(FieldInvoiceID, v)) +} + +// InvoiceIDLTE applies the LTE predicate on the "invoice_id" field. +func InvoiceIDLTE(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLTE(FieldInvoiceID, v)) +} + +// InvoiceIDContains applies the Contains predicate on the "invoice_id" field. +func InvoiceIDContains(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldContains(FieldInvoiceID, v)) +} + +// InvoiceIDHasPrefix applies the HasPrefix predicate on the "invoice_id" field. +func InvoiceIDHasPrefix(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldHasPrefix(FieldInvoiceID, v)) +} + +// InvoiceIDHasSuffix applies the HasSuffix predicate on the "invoice_id" field. +func InvoiceIDHasSuffix(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldHasSuffix(FieldInvoiceID, v)) +} + +// InvoiceIDIsNil applies the IsNil predicate on the "invoice_id" field. +func InvoiceIDIsNil() predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIsNull(FieldInvoiceID)) +} + +// InvoiceIDNotNil applies the NotNil predicate on the "invoice_id" field. +func InvoiceIDNotNil() predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotNull(FieldInvoiceID)) +} + +// InvoiceIDEqualFold applies the EqualFold predicate on the "invoice_id" field. +func InvoiceIDEqualFold(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEqualFold(FieldInvoiceID, v)) +} + +// InvoiceIDContainsFold applies the ContainsFold predicate on the "invoice_id" field. +func InvoiceIDContainsFold(v string) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldContainsFold(FieldInvoiceID, v)) +} + +// AmountAfterProrationEQ applies the EQ predicate on the "amount_after_proration" field. +func AmountAfterProrationEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldAmountAfterProration, v)) +} + +// AmountAfterProrationNEQ applies the NEQ predicate on the "amount_after_proration" field. +func AmountAfterProrationNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldAmountAfterProration, v)) +} + +// AmountAfterProrationIn applies the In predicate on the "amount_after_proration" field. +func AmountAfterProrationIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldIn(FieldAmountAfterProration, vs...)) +} + +// AmountAfterProrationNotIn applies the NotIn predicate on the "amount_after_proration" field. +func AmountAfterProrationNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNotIn(FieldAmountAfterProration, vs...)) +} + +// AmountAfterProrationGT applies the GT predicate on the "amount_after_proration" field. +func AmountAfterProrationGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGT(FieldAmountAfterProration, v)) +} + +// AmountAfterProrationGTE applies the GTE predicate on the "amount_after_proration" field. +func AmountAfterProrationGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldGTE(FieldAmountAfterProration, v)) +} + +// AmountAfterProrationLT applies the LT predicate on the "amount_after_proration" field. +func AmountAfterProrationLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLT(FieldAmountAfterProration, v)) +} + +// AmountAfterProrationLTE applies the LTE predicate on the "amount_after_proration" field. +func AmountAfterProrationLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldLTE(FieldAmountAfterProration, v)) +} + +// NoFiatTransactionRequiredEQ applies the EQ predicate on the "no_fiat_transaction_required" field. +func NoFiatTransactionRequiredEQ(v bool) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldNoFiatTransactionRequired, v)) +} + +// NoFiatTransactionRequiredNEQ applies the NEQ predicate on the "no_fiat_transaction_required" field. +func NoFiatTransactionRequiredNEQ(v bool) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldNoFiatTransactionRequired, v)) +} + +// ImmutableEQ applies the EQ predicate on the "immutable" field. +func ImmutableEQ(v bool) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldEQ(FieldImmutable, v)) +} + +// ImmutableNEQ applies the NEQ predicate on the "immutable" field. +func ImmutableNEQ(v bool) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.FieldNEQ(FieldImmutable, v)) +} + +// HasFlatFee applies the HasEdge predicate on the "flat_fee" edge. +func HasFlatFee() predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, FlatFeeTable, FlatFeeColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasFlatFeeWith applies the HasEdge predicate on the "flat_fee" edge with a given conditions (other predicates). +func HasFlatFeeWith(preds ...predicate.ChargeFlatFee) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(func(s *sql.Selector) { + step := newFlatFeeStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasBillingInvoiceLine applies the HasEdge predicate on the "billing_invoice_line" edge. +func HasBillingInvoiceLine() predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, BillingInvoiceLineTable, BillingInvoiceLineColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBillingInvoiceLineWith applies the HasEdge predicate on the "billing_invoice_line" edge with a given conditions (other predicates). +func HasBillingInvoiceLineWith(preds ...predicate.BillingInvoiceLine) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(func(s *sql.Selector) { + step := newBillingInvoiceLineStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasBillingInvoice applies the HasEdge predicate on the "billing_invoice" edge. +func HasBillingInvoice() predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, BillingInvoiceTable, BillingInvoiceColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBillingInvoiceWith applies the HasEdge predicate on the "billing_invoice" edge with a given conditions (other predicates). +func HasBillingInvoiceWith(preds ...predicate.BillingInvoice) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(func(s *sql.Selector) { + step := newBillingInvoiceStep() + 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.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(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.ChargeFlatFeeRunCreditAllocations) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(func(s *sql.Selector) { + step := newCreditAllocationsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasDetailedLines applies the HasEdge predicate on the "detailed_lines" edge. +func HasDetailedLines() predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, DetailedLinesTable, DetailedLinesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasDetailedLinesWith applies the HasEdge predicate on the "detailed_lines" edge with a given conditions (other predicates). +func HasDetailedLinesWith(preds ...predicate.ChargeFlatFeeRunDetailedLine) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(func(s *sql.Selector) { + step := newDetailedLinesStep() + 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.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(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.ChargeFlatFeeRunInvoicedUsage) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(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.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(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.ChargeFlatFeeRunPayment) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(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.ChargeFlatFeeRun) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ChargeFlatFeeRun) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ChargeFlatFeeRun) predicate.ChargeFlatFeeRun { + return predicate.ChargeFlatFeeRun(sql.NotPredicates(p)) +} diff --git a/ent/db/chargeflatfeerun_create.go b/ent/db/chargeflatfeerun_create.go new file mode 100644 index 0000000000000000000000000000000000000000..ecb7cfa5c456592e446a6ed5a0977dd1cc5d075a --- /dev/null +++ b/ent/db/chargeflatfeerun_create.go @@ -0,0 +1,1841 @@ +// 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/flatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerundetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerunpayment" +) + +// ChargeFlatFeeRunCreate is the builder for creating a ChargeFlatFeeRun entity. +type ChargeFlatFeeRunCreate struct { + config + mutation *ChargeFlatFeeRunMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *ChargeFlatFeeRunCreate) SetNamespace(v string) *ChargeFlatFeeRunCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ChargeFlatFeeRunCreate) SetCreatedAt(v time.Time) *ChargeFlatFeeRunCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *ChargeFlatFeeRunCreate) SetNillableCreatedAt(v *time.Time) *ChargeFlatFeeRunCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *ChargeFlatFeeRunCreate) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *ChargeFlatFeeRunCreate) SetNillableUpdatedAt(v *time.Time) *ChargeFlatFeeRunCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *ChargeFlatFeeRunCreate) SetDeletedAt(v time.Time) *ChargeFlatFeeRunCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *ChargeFlatFeeRunCreate) SetNillableDeletedAt(v *time.Time) *ChargeFlatFeeRunCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetAmount sets the "amount" field. +func (_c *ChargeFlatFeeRunCreate) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_c *ChargeFlatFeeRunCreate) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunCreate { + _c.mutation.SetTaxesTotal(v) + return _c +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_c *ChargeFlatFeeRunCreate) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunCreate { + _c.mutation.SetTaxesInclusiveTotal(v) + return _c +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_c *ChargeFlatFeeRunCreate) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunCreate { + _c.mutation.SetTaxesExclusiveTotal(v) + return _c +} + +// SetChargesTotal sets the "charges_total" field. +func (_c *ChargeFlatFeeRunCreate) SetChargesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunCreate { + _c.mutation.SetChargesTotal(v) + return _c +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_c *ChargeFlatFeeRunCreate) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunCreate { + _c.mutation.SetDiscountsTotal(v) + return _c +} + +// SetCreditsTotal sets the "credits_total" field. +func (_c *ChargeFlatFeeRunCreate) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunCreate { + _c.mutation.SetCreditsTotal(v) + return _c +} + +// SetTotal sets the "total" field. +func (_c *ChargeFlatFeeRunCreate) SetTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunCreate { + _c.mutation.SetTotal(v) + return _c +} + +// SetChargeID sets the "charge_id" field. +func (_c *ChargeFlatFeeRunCreate) SetChargeID(v string) *ChargeFlatFeeRunCreate { + _c.mutation.SetChargeID(v) + return _c +} + +// SetType sets the "type" field. +func (_c *ChargeFlatFeeRunCreate) SetType(v flatfee.RealizationRunType) *ChargeFlatFeeRunCreate { + _c.mutation.SetType(v) + return _c +} + +// SetInitialType sets the "initial_type" field. +func (_c *ChargeFlatFeeRunCreate) SetInitialType(v flatfee.RealizationRunType) *ChargeFlatFeeRunCreate { + _c.mutation.SetInitialType(v) + return _c +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_c *ChargeFlatFeeRunCreate) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunCreate { + _c.mutation.SetServicePeriodFrom(v) + return _c +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_c *ChargeFlatFeeRunCreate) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunCreate { + _c.mutation.SetServicePeriodTo(v) + return _c +} + +// SetLineID sets the "line_id" field. +func (_c *ChargeFlatFeeRunCreate) SetLineID(v string) *ChargeFlatFeeRunCreate { + _c.mutation.SetLineID(v) + return _c +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_c *ChargeFlatFeeRunCreate) SetNillableLineID(v *string) *ChargeFlatFeeRunCreate { + if v != nil { + _c.SetLineID(*v) + } + return _c +} + +// SetInvoiceID sets the "invoice_id" field. +func (_c *ChargeFlatFeeRunCreate) SetInvoiceID(v string) *ChargeFlatFeeRunCreate { + _c.mutation.SetInvoiceID(v) + return _c +} + +// SetNillableInvoiceID sets the "invoice_id" field if the given value is not nil. +func (_c *ChargeFlatFeeRunCreate) SetNillableInvoiceID(v *string) *ChargeFlatFeeRunCreate { + if v != nil { + _c.SetInvoiceID(*v) + } + return _c +} + +// SetAmountAfterProration sets the "amount_after_proration" field. +func (_c *ChargeFlatFeeRunCreate) SetAmountAfterProration(v alpacadecimal.Decimal) *ChargeFlatFeeRunCreate { + _c.mutation.SetAmountAfterProration(v) + return _c +} + +// SetNoFiatTransactionRequired sets the "no_fiat_transaction_required" field. +func (_c *ChargeFlatFeeRunCreate) SetNoFiatTransactionRequired(v bool) *ChargeFlatFeeRunCreate { + _c.mutation.SetNoFiatTransactionRequired(v) + return _c +} + +// SetImmutable sets the "immutable" field. +func (_c *ChargeFlatFeeRunCreate) SetImmutable(v bool) *ChargeFlatFeeRunCreate { + _c.mutation.SetImmutable(v) + return _c +} + +// SetID sets the "id" field. +func (_c *ChargeFlatFeeRunCreate) SetID(v string) *ChargeFlatFeeRunCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ChargeFlatFeeRunCreate) SetNillableID(v *string) *ChargeFlatFeeRunCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetFlatFeeID sets the "flat_fee" edge to the ChargeFlatFee entity by ID. +func (_c *ChargeFlatFeeRunCreate) SetFlatFeeID(id string) *ChargeFlatFeeRunCreate { + _c.mutation.SetFlatFeeID(id) + return _c +} + +// SetFlatFee sets the "flat_fee" edge to the ChargeFlatFee entity. +func (_c *ChargeFlatFeeRunCreate) SetFlatFee(v *ChargeFlatFee) *ChargeFlatFeeRunCreate { + return _c.SetFlatFeeID(v.ID) +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID. +func (_c *ChargeFlatFeeRunCreate) SetBillingInvoiceLineID(id string) *ChargeFlatFeeRunCreate { + _c.mutation.SetBillingInvoiceLineID(id) + return _c +} + +// SetNillableBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID if the given value is not nil. +func (_c *ChargeFlatFeeRunCreate) SetNillableBillingInvoiceLineID(id *string) *ChargeFlatFeeRunCreate { + if id != nil { + _c = _c.SetBillingInvoiceLineID(*id) + } + return _c +} + +// SetBillingInvoiceLine sets the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_c *ChargeFlatFeeRunCreate) SetBillingInvoiceLine(v *BillingInvoiceLine) *ChargeFlatFeeRunCreate { + return _c.SetBillingInvoiceLineID(v.ID) +} + +// SetBillingInvoiceID sets the "billing_invoice" edge to the BillingInvoice entity by ID. +func (_c *ChargeFlatFeeRunCreate) SetBillingInvoiceID(id string) *ChargeFlatFeeRunCreate { + _c.mutation.SetBillingInvoiceID(id) + return _c +} + +// SetNillableBillingInvoiceID sets the "billing_invoice" edge to the BillingInvoice entity by ID if the given value is not nil. +func (_c *ChargeFlatFeeRunCreate) SetNillableBillingInvoiceID(id *string) *ChargeFlatFeeRunCreate { + if id != nil { + _c = _c.SetBillingInvoiceID(*id) + } + return _c +} + +// SetBillingInvoice sets the "billing_invoice" edge to the BillingInvoice entity. +func (_c *ChargeFlatFeeRunCreate) SetBillingInvoice(v *BillingInvoice) *ChargeFlatFeeRunCreate { + return _c.SetBillingInvoiceID(v.ID) +} + +// AddCreditAllocationIDs adds the "credit_allocations" edge to the ChargeFlatFeeRunCreditAllocations entity by IDs. +func (_c *ChargeFlatFeeRunCreate) AddCreditAllocationIDs(ids ...string) *ChargeFlatFeeRunCreate { + _c.mutation.AddCreditAllocationIDs(ids...) + return _c +} + +// AddCreditAllocations adds the "credit_allocations" edges to the ChargeFlatFeeRunCreditAllocations entity. +func (_c *ChargeFlatFeeRunCreate) AddCreditAllocations(v ...*ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddCreditAllocationIDs(ids...) +} + +// AddDetailedLineIDs adds the "detailed_lines" edge to the ChargeFlatFeeRunDetailedLine entity by IDs. +func (_c *ChargeFlatFeeRunCreate) AddDetailedLineIDs(ids ...string) *ChargeFlatFeeRunCreate { + _c.mutation.AddDetailedLineIDs(ids...) + return _c +} + +// AddDetailedLines adds the "detailed_lines" edges to the ChargeFlatFeeRunDetailedLine entity. +func (_c *ChargeFlatFeeRunCreate) AddDetailedLines(v ...*ChargeFlatFeeRunDetailedLine) *ChargeFlatFeeRunCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddDetailedLineIDs(ids...) +} + +// SetInvoicedUsageID sets the "invoiced_usage" edge to the ChargeFlatFeeRunInvoicedUsage entity by ID. +func (_c *ChargeFlatFeeRunCreate) SetInvoicedUsageID(id string) *ChargeFlatFeeRunCreate { + _c.mutation.SetInvoicedUsageID(id) + return _c +} + +// SetNillableInvoicedUsageID sets the "invoiced_usage" edge to the ChargeFlatFeeRunInvoicedUsage entity by ID if the given value is not nil. +func (_c *ChargeFlatFeeRunCreate) SetNillableInvoicedUsageID(id *string) *ChargeFlatFeeRunCreate { + if id != nil { + _c = _c.SetInvoicedUsageID(*id) + } + return _c +} + +// SetInvoicedUsage sets the "invoiced_usage" edge to the ChargeFlatFeeRunInvoicedUsage entity. +func (_c *ChargeFlatFeeRunCreate) SetInvoicedUsage(v *ChargeFlatFeeRunInvoicedUsage) *ChargeFlatFeeRunCreate { + return _c.SetInvoicedUsageID(v.ID) +} + +// SetPaymentID sets the "payment" edge to the ChargeFlatFeeRunPayment entity by ID. +func (_c *ChargeFlatFeeRunCreate) SetPaymentID(id string) *ChargeFlatFeeRunCreate { + _c.mutation.SetPaymentID(id) + return _c +} + +// SetNillablePaymentID sets the "payment" edge to the ChargeFlatFeeRunPayment entity by ID if the given value is not nil. +func (_c *ChargeFlatFeeRunCreate) SetNillablePaymentID(id *string) *ChargeFlatFeeRunCreate { + if id != nil { + _c = _c.SetPaymentID(*id) + } + return _c +} + +// SetPayment sets the "payment" edge to the ChargeFlatFeeRunPayment entity. +func (_c *ChargeFlatFeeRunCreate) SetPayment(v *ChargeFlatFeeRunPayment) *ChargeFlatFeeRunCreate { + return _c.SetPaymentID(v.ID) +} + +// Mutation returns the ChargeFlatFeeRunMutation object of the builder. +func (_c *ChargeFlatFeeRunCreate) Mutation() *ChargeFlatFeeRunMutation { + return _c.mutation +} + +// Save creates the ChargeFlatFeeRun in the database. +func (_c *ChargeFlatFeeRunCreate) Save(ctx context.Context) (*ChargeFlatFeeRun, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ChargeFlatFeeRunCreate) SaveX(ctx context.Context) *ChargeFlatFeeRun { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeFlatFeeRunCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeFlatFeeRunCreate) 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 *ChargeFlatFeeRunCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := chargeflatfeerun.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := chargeflatfeerun.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := chargeflatfeerun.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ChargeFlatFeeRunCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "ChargeFlatFeeRun.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := chargeflatfeerun.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRun.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "ChargeFlatFeeRun.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "ChargeFlatFeeRun.updated_at"`)} + } + if _, ok := _c.mutation.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`db: missing required field "ChargeFlatFeeRun.amount"`)} + } + if _, ok := _c.mutation.TaxesTotal(); !ok { + return &ValidationError{Name: "taxes_total", err: errors.New(`db: missing required field "ChargeFlatFeeRun.taxes_total"`)} + } + if _, ok := _c.mutation.TaxesInclusiveTotal(); !ok { + return &ValidationError{Name: "taxes_inclusive_total", err: errors.New(`db: missing required field "ChargeFlatFeeRun.taxes_inclusive_total"`)} + } + if _, ok := _c.mutation.TaxesExclusiveTotal(); !ok { + return &ValidationError{Name: "taxes_exclusive_total", err: errors.New(`db: missing required field "ChargeFlatFeeRun.taxes_exclusive_total"`)} + } + if _, ok := _c.mutation.ChargesTotal(); !ok { + return &ValidationError{Name: "charges_total", err: errors.New(`db: missing required field "ChargeFlatFeeRun.charges_total"`)} + } + if _, ok := _c.mutation.DiscountsTotal(); !ok { + return &ValidationError{Name: "discounts_total", err: errors.New(`db: missing required field "ChargeFlatFeeRun.discounts_total"`)} + } + if _, ok := _c.mutation.CreditsTotal(); !ok { + return &ValidationError{Name: "credits_total", err: errors.New(`db: missing required field "ChargeFlatFeeRun.credits_total"`)} + } + if _, ok := _c.mutation.Total(); !ok { + return &ValidationError{Name: "total", err: errors.New(`db: missing required field "ChargeFlatFeeRun.total"`)} + } + if _, ok := _c.mutation.ChargeID(); !ok { + return &ValidationError{Name: "charge_id", err: errors.New(`db: missing required field "ChargeFlatFeeRun.charge_id"`)} + } + if _, ok := _c.mutation.GetType(); !ok { + return &ValidationError{Name: "type", err: errors.New(`db: missing required field "ChargeFlatFeeRun.type"`)} + } + if v, ok := _c.mutation.GetType(); ok { + if err := chargeflatfeerun.TypeValidator(v); err != nil { + return &ValidationError{Name: "type", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRun.type": %w`, err)} + } + } + if _, ok := _c.mutation.InitialType(); !ok { + return &ValidationError{Name: "initial_type", err: errors.New(`db: missing required field "ChargeFlatFeeRun.initial_type"`)} + } + if v, ok := _c.mutation.InitialType(); ok { + if err := chargeflatfeerun.InitialTypeValidator(v); err != nil { + return &ValidationError{Name: "initial_type", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRun.initial_type": %w`, err)} + } + } + if _, ok := _c.mutation.ServicePeriodFrom(); !ok { + return &ValidationError{Name: "service_period_from", err: errors.New(`db: missing required field "ChargeFlatFeeRun.service_period_from"`)} + } + if _, ok := _c.mutation.ServicePeriodTo(); !ok { + return &ValidationError{Name: "service_period_to", err: errors.New(`db: missing required field "ChargeFlatFeeRun.service_period_to"`)} + } + if v, ok := _c.mutation.LineID(); ok { + if err := chargeflatfeerun.LineIDValidator(v); err != nil { + return &ValidationError{Name: "line_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRun.line_id": %w`, err)} + } + } + if v, ok := _c.mutation.InvoiceID(); ok { + if err := chargeflatfeerun.InvoiceIDValidator(v); err != nil { + return &ValidationError{Name: "invoice_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRun.invoice_id": %w`, err)} + } + } + if _, ok := _c.mutation.AmountAfterProration(); !ok { + return &ValidationError{Name: "amount_after_proration", err: errors.New(`db: missing required field "ChargeFlatFeeRun.amount_after_proration"`)} + } + if _, ok := _c.mutation.NoFiatTransactionRequired(); !ok { + return &ValidationError{Name: "no_fiat_transaction_required", err: errors.New(`db: missing required field "ChargeFlatFeeRun.no_fiat_transaction_required"`)} + } + if _, ok := _c.mutation.Immutable(); !ok { + return &ValidationError{Name: "immutable", err: errors.New(`db: missing required field "ChargeFlatFeeRun.immutable"`)} + } + if len(_c.mutation.FlatFeeIDs()) == 0 { + return &ValidationError{Name: "flat_fee", err: errors.New(`db: missing required edge "ChargeFlatFeeRun.flat_fee"`)} + } + return nil +} + +func (_c *ChargeFlatFeeRunCreate) sqlSave(ctx context.Context) (*ChargeFlatFeeRun, 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 ChargeFlatFeeRun.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ChargeFlatFeeRunCreate) createSpec() (*ChargeFlatFeeRun, *sqlgraph.CreateSpec) { + var ( + _node = &ChargeFlatFeeRun{config: _c.config} + _spec = sqlgraph.NewCreateSpec(chargeflatfeerun.Table, sqlgraph.NewFieldSpec(chargeflatfeerun.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(chargeflatfeerun.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(chargeflatfeerun.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(chargeflatfeerun.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(chargeflatfeerun.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Amount(); ok { + _spec.SetField(chargeflatfeerun.FieldAmount, field.TypeOther, value) + _node.Amount = value + } + if value, ok := _c.mutation.TaxesTotal(); ok { + _spec.SetField(chargeflatfeerun.FieldTaxesTotal, field.TypeOther, value) + _node.TaxesTotal = value + } + if value, ok := _c.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(chargeflatfeerun.FieldTaxesInclusiveTotal, field.TypeOther, value) + _node.TaxesInclusiveTotal = value + } + if value, ok := _c.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(chargeflatfeerun.FieldTaxesExclusiveTotal, field.TypeOther, value) + _node.TaxesExclusiveTotal = value + } + if value, ok := _c.mutation.ChargesTotal(); ok { + _spec.SetField(chargeflatfeerun.FieldChargesTotal, field.TypeOther, value) + _node.ChargesTotal = value + } + if value, ok := _c.mutation.DiscountsTotal(); ok { + _spec.SetField(chargeflatfeerun.FieldDiscountsTotal, field.TypeOther, value) + _node.DiscountsTotal = value + } + if value, ok := _c.mutation.CreditsTotal(); ok { + _spec.SetField(chargeflatfeerun.FieldCreditsTotal, field.TypeOther, value) + _node.CreditsTotal = value + } + if value, ok := _c.mutation.Total(); ok { + _spec.SetField(chargeflatfeerun.FieldTotal, field.TypeOther, value) + _node.Total = value + } + if value, ok := _c.mutation.GetType(); ok { + _spec.SetField(chargeflatfeerun.FieldType, field.TypeEnum, value) + _node.Type = value + } + if value, ok := _c.mutation.InitialType(); ok { + _spec.SetField(chargeflatfeerun.FieldInitialType, field.TypeEnum, value) + _node.InitialType = value + } + if value, ok := _c.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeflatfeerun.FieldServicePeriodFrom, field.TypeTime, value) + _node.ServicePeriodFrom = value + } + if value, ok := _c.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeflatfeerun.FieldServicePeriodTo, field.TypeTime, value) + _node.ServicePeriodTo = value + } + if value, ok := _c.mutation.AmountAfterProration(); ok { + _spec.SetField(chargeflatfeerun.FieldAmountAfterProration, field.TypeOther, value) + _node.AmountAfterProration = value + } + if value, ok := _c.mutation.NoFiatTransactionRequired(); ok { + _spec.SetField(chargeflatfeerun.FieldNoFiatTransactionRequired, field.TypeBool, value) + _node.NoFiatTransactionRequired = value + } + if value, ok := _c.mutation.Immutable(); ok { + _spec.SetField(chargeflatfeerun.FieldImmutable, field.TypeBool, value) + _node.Immutable = value + } + if nodes := _c.mutation.FlatFeeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfeerun.FlatFeeTable, + Columns: []string{chargeflatfeerun.FlatFeeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfee.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.BillingInvoiceLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeflatfeerun.BillingInvoiceLineTable, + Columns: []string{chargeflatfeerun.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.LineID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.BillingInvoiceIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfeerun.BillingInvoiceTable, + Columns: []string{chargeflatfeerun.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.InvoiceID = &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: chargeflatfeerun.CreditAllocationsTable, + Columns: []string{chargeflatfeerun.CreditAllocationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.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.DetailedLinesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeflatfeerun.DetailedLinesTable, + Columns: []string{chargeflatfeerun.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerundetailedline.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: chargeflatfeerun.InvoicedUsageTable, + Columns: []string{chargeflatfeerun.InvoicedUsageColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruninvoicedusage.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: chargeflatfeerun.PaymentTable, + Columns: []string{chargeflatfeerun.PaymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerunpayment.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.ChargeFlatFeeRun.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.ChargeFlatFeeRunUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *ChargeFlatFeeRunCreate) OnConflict(opts ...sql.ConflictOption) *ChargeFlatFeeRunUpsertOne { + _c.conflict = opts + return &ChargeFlatFeeRunUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeFlatFeeRun.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeFlatFeeRunCreate) OnConflictColumns(columns ...string) *ChargeFlatFeeRunUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeFlatFeeRunUpsertOne{ + create: _c, + } +} + +type ( + // ChargeFlatFeeRunUpsertOne is the builder for "upsert"-ing + // one ChargeFlatFeeRun node. + ChargeFlatFeeRunUpsertOne struct { + create *ChargeFlatFeeRunCreate + } + + // ChargeFlatFeeRunUpsert is the "OnConflict" setter. + ChargeFlatFeeRunUpsert struct { + *sql.UpdateSet + } +) + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeFlatFeeRunUpsert) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunUpsert { + u.Set(chargeflatfeerun.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsert) UpdateUpdatedAt() *ChargeFlatFeeRunUpsert { + u.SetExcluded(chargeflatfeerun.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeFlatFeeRunUpsert) SetDeletedAt(v time.Time) *ChargeFlatFeeRunUpsert { + u.Set(chargeflatfeerun.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsert) UpdateDeletedAt() *ChargeFlatFeeRunUpsert { + u.SetExcluded(chargeflatfeerun.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeFlatFeeRunUpsert) ClearDeletedAt() *ChargeFlatFeeRunUpsert { + u.SetNull(chargeflatfeerun.FieldDeletedAt) + return u +} + +// SetAmount sets the "amount" field. +func (u *ChargeFlatFeeRunUpsert) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsert { + u.Set(chargeflatfeerun.FieldAmount, v) + return u +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsert) UpdateAmount() *ChargeFlatFeeRunUpsert { + u.SetExcluded(chargeflatfeerun.FieldAmount) + return u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *ChargeFlatFeeRunUpsert) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsert { + u.Set(chargeflatfeerun.FieldTaxesTotal, v) + return u +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsert) UpdateTaxesTotal() *ChargeFlatFeeRunUpsert { + u.SetExcluded(chargeflatfeerun.FieldTaxesTotal) + return u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *ChargeFlatFeeRunUpsert) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsert { + u.Set(chargeflatfeerun.FieldTaxesInclusiveTotal, v) + return u +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsert) UpdateTaxesInclusiveTotal() *ChargeFlatFeeRunUpsert { + u.SetExcluded(chargeflatfeerun.FieldTaxesInclusiveTotal) + return u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *ChargeFlatFeeRunUpsert) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsert { + u.Set(chargeflatfeerun.FieldTaxesExclusiveTotal, v) + return u +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsert) UpdateTaxesExclusiveTotal() *ChargeFlatFeeRunUpsert { + u.SetExcluded(chargeflatfeerun.FieldTaxesExclusiveTotal) + return u +} + +// SetChargesTotal sets the "charges_total" field. +func (u *ChargeFlatFeeRunUpsert) SetChargesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsert { + u.Set(chargeflatfeerun.FieldChargesTotal, v) + return u +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsert) UpdateChargesTotal() *ChargeFlatFeeRunUpsert { + u.SetExcluded(chargeflatfeerun.FieldChargesTotal) + return u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *ChargeFlatFeeRunUpsert) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsert { + u.Set(chargeflatfeerun.FieldDiscountsTotal, v) + return u +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsert) UpdateDiscountsTotal() *ChargeFlatFeeRunUpsert { + u.SetExcluded(chargeflatfeerun.FieldDiscountsTotal) + return u +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *ChargeFlatFeeRunUpsert) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsert { + u.Set(chargeflatfeerun.FieldCreditsTotal, v) + return u +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsert) UpdateCreditsTotal() *ChargeFlatFeeRunUpsert { + u.SetExcluded(chargeflatfeerun.FieldCreditsTotal) + return u +} + +// SetTotal sets the "total" field. +func (u *ChargeFlatFeeRunUpsert) SetTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsert { + u.Set(chargeflatfeerun.FieldTotal, v) + return u +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsert) UpdateTotal() *ChargeFlatFeeRunUpsert { + u.SetExcluded(chargeflatfeerun.FieldTotal) + return u +} + +// SetType sets the "type" field. +func (u *ChargeFlatFeeRunUpsert) SetType(v flatfee.RealizationRunType) *ChargeFlatFeeRunUpsert { + u.Set(chargeflatfeerun.FieldType, v) + return u +} + +// UpdateType sets the "type" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsert) UpdateType() *ChargeFlatFeeRunUpsert { + u.SetExcluded(chargeflatfeerun.FieldType) + return u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeFlatFeeRunUpsert) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunUpsert { + u.Set(chargeflatfeerun.FieldServicePeriodFrom, v) + return u +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsert) UpdateServicePeriodFrom() *ChargeFlatFeeRunUpsert { + u.SetExcluded(chargeflatfeerun.FieldServicePeriodFrom) + return u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeFlatFeeRunUpsert) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunUpsert { + u.Set(chargeflatfeerun.FieldServicePeriodTo, v) + return u +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsert) UpdateServicePeriodTo() *ChargeFlatFeeRunUpsert { + u.SetExcluded(chargeflatfeerun.FieldServicePeriodTo) + return u +} + +// SetLineID sets the "line_id" field. +func (u *ChargeFlatFeeRunUpsert) SetLineID(v string) *ChargeFlatFeeRunUpsert { + u.Set(chargeflatfeerun.FieldLineID, v) + return u +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsert) UpdateLineID() *ChargeFlatFeeRunUpsert { + u.SetExcluded(chargeflatfeerun.FieldLineID) + return u +} + +// ClearLineID clears the value of the "line_id" field. +func (u *ChargeFlatFeeRunUpsert) ClearLineID() *ChargeFlatFeeRunUpsert { + u.SetNull(chargeflatfeerun.FieldLineID) + return u +} + +// SetInvoiceID sets the "invoice_id" field. +func (u *ChargeFlatFeeRunUpsert) SetInvoiceID(v string) *ChargeFlatFeeRunUpsert { + u.Set(chargeflatfeerun.FieldInvoiceID, v) + return u +} + +// UpdateInvoiceID sets the "invoice_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsert) UpdateInvoiceID() *ChargeFlatFeeRunUpsert { + u.SetExcluded(chargeflatfeerun.FieldInvoiceID) + return u +} + +// ClearInvoiceID clears the value of the "invoice_id" field. +func (u *ChargeFlatFeeRunUpsert) ClearInvoiceID() *ChargeFlatFeeRunUpsert { + u.SetNull(chargeflatfeerun.FieldInvoiceID) + return u +} + +// SetAmountAfterProration sets the "amount_after_proration" field. +func (u *ChargeFlatFeeRunUpsert) SetAmountAfterProration(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsert { + u.Set(chargeflatfeerun.FieldAmountAfterProration, v) + return u +} + +// UpdateAmountAfterProration sets the "amount_after_proration" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsert) UpdateAmountAfterProration() *ChargeFlatFeeRunUpsert { + u.SetExcluded(chargeflatfeerun.FieldAmountAfterProration) + return u +} + +// SetNoFiatTransactionRequired sets the "no_fiat_transaction_required" field. +func (u *ChargeFlatFeeRunUpsert) SetNoFiatTransactionRequired(v bool) *ChargeFlatFeeRunUpsert { + u.Set(chargeflatfeerun.FieldNoFiatTransactionRequired, v) + return u +} + +// UpdateNoFiatTransactionRequired sets the "no_fiat_transaction_required" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsert) UpdateNoFiatTransactionRequired() *ChargeFlatFeeRunUpsert { + u.SetExcluded(chargeflatfeerun.FieldNoFiatTransactionRequired) + return u +} + +// SetImmutable sets the "immutable" field. +func (u *ChargeFlatFeeRunUpsert) SetImmutable(v bool) *ChargeFlatFeeRunUpsert { + u.Set(chargeflatfeerun.FieldImmutable, v) + return u +} + +// UpdateImmutable sets the "immutable" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsert) UpdateImmutable() *ChargeFlatFeeRunUpsert { + u.SetExcluded(chargeflatfeerun.FieldImmutable) + 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.ChargeFlatFeeRun.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeflatfeerun.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeFlatFeeRunUpsertOne) UpdateNewValues() *ChargeFlatFeeRunUpsertOne { + 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(chargeflatfeerun.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(chargeflatfeerun.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(chargeflatfeerun.FieldCreatedAt) + } + if _, exists := u.create.mutation.ChargeID(); exists { + s.SetIgnore(chargeflatfeerun.FieldChargeID) + } + if _, exists := u.create.mutation.InitialType(); exists { + s.SetIgnore(chargeflatfeerun.FieldInitialType) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeFlatFeeRun.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeFlatFeeRunUpsertOne) Ignore() *ChargeFlatFeeRunUpsertOne { + 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 *ChargeFlatFeeRunUpsertOne) DoNothing() *ChargeFlatFeeRunUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeFlatFeeRunCreate.OnConflict +// documentation for more info. +func (u *ChargeFlatFeeRunUpsertOne) Update(set func(*ChargeFlatFeeRunUpsert)) *ChargeFlatFeeRunUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeFlatFeeRunUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeFlatFeeRunUpsertOne) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertOne) UpdateUpdatedAt() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeFlatFeeRunUpsertOne) SetDeletedAt(v time.Time) *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertOne) UpdateDeletedAt() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeFlatFeeRunUpsertOne) ClearDeletedAt() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeFlatFeeRunUpsertOne) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertOne) UpdateAmount() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateAmount() + }) +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *ChargeFlatFeeRunUpsertOne) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetTaxesTotal(v) + }) +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertOne) UpdateTaxesTotal() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateTaxesTotal() + }) +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *ChargeFlatFeeRunUpsertOne) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetTaxesInclusiveTotal(v) + }) +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertOne) UpdateTaxesInclusiveTotal() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateTaxesInclusiveTotal() + }) +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *ChargeFlatFeeRunUpsertOne) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetTaxesExclusiveTotal(v) + }) +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertOne) UpdateTaxesExclusiveTotal() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateTaxesExclusiveTotal() + }) +} + +// SetChargesTotal sets the "charges_total" field. +func (u *ChargeFlatFeeRunUpsertOne) SetChargesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetChargesTotal(v) + }) +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertOne) UpdateChargesTotal() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateChargesTotal() + }) +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *ChargeFlatFeeRunUpsertOne) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetDiscountsTotal(v) + }) +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertOne) UpdateDiscountsTotal() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateDiscountsTotal() + }) +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *ChargeFlatFeeRunUpsertOne) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetCreditsTotal(v) + }) +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertOne) UpdateCreditsTotal() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateCreditsTotal() + }) +} + +// SetTotal sets the "total" field. +func (u *ChargeFlatFeeRunUpsertOne) SetTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetTotal(v) + }) +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertOne) UpdateTotal() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateTotal() + }) +} + +// SetType sets the "type" field. +func (u *ChargeFlatFeeRunUpsertOne) SetType(v flatfee.RealizationRunType) *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetType(v) + }) +} + +// UpdateType sets the "type" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertOne) UpdateType() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateType() + }) +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeFlatFeeRunUpsertOne) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertOne) UpdateServicePeriodFrom() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeFlatFeeRunUpsertOne) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertOne) UpdateServicePeriodTo() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetLineID sets the "line_id" field. +func (u *ChargeFlatFeeRunUpsertOne) SetLineID(v string) *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetLineID(v) + }) +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertOne) UpdateLineID() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateLineID() + }) +} + +// ClearLineID clears the value of the "line_id" field. +func (u *ChargeFlatFeeRunUpsertOne) ClearLineID() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.ClearLineID() + }) +} + +// SetInvoiceID sets the "invoice_id" field. +func (u *ChargeFlatFeeRunUpsertOne) SetInvoiceID(v string) *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetInvoiceID(v) + }) +} + +// UpdateInvoiceID sets the "invoice_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertOne) UpdateInvoiceID() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateInvoiceID() + }) +} + +// ClearInvoiceID clears the value of the "invoice_id" field. +func (u *ChargeFlatFeeRunUpsertOne) ClearInvoiceID() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.ClearInvoiceID() + }) +} + +// SetAmountAfterProration sets the "amount_after_proration" field. +func (u *ChargeFlatFeeRunUpsertOne) SetAmountAfterProration(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetAmountAfterProration(v) + }) +} + +// UpdateAmountAfterProration sets the "amount_after_proration" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertOne) UpdateAmountAfterProration() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateAmountAfterProration() + }) +} + +// SetNoFiatTransactionRequired sets the "no_fiat_transaction_required" field. +func (u *ChargeFlatFeeRunUpsertOne) SetNoFiatTransactionRequired(v bool) *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetNoFiatTransactionRequired(v) + }) +} + +// UpdateNoFiatTransactionRequired sets the "no_fiat_transaction_required" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertOne) UpdateNoFiatTransactionRequired() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateNoFiatTransactionRequired() + }) +} + +// SetImmutable sets the "immutable" field. +func (u *ChargeFlatFeeRunUpsertOne) SetImmutable(v bool) *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetImmutable(v) + }) +} + +// UpdateImmutable sets the "immutable" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertOne) UpdateImmutable() *ChargeFlatFeeRunUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateImmutable() + }) +} + +// Exec executes the query. +func (u *ChargeFlatFeeRunUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeFlatFeeRunCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeFlatFeeRunUpsertOne) 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 *ChargeFlatFeeRunUpsertOne) 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: ChargeFlatFeeRunUpsertOne.ID is not supported by MySQL driver. Use ChargeFlatFeeRunUpsertOne.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 *ChargeFlatFeeRunUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ChargeFlatFeeRunCreateBulk is the builder for creating many ChargeFlatFeeRun entities in bulk. +type ChargeFlatFeeRunCreateBulk struct { + config + err error + builders []*ChargeFlatFeeRunCreate + conflict []sql.ConflictOption +} + +// Save creates the ChargeFlatFeeRun entities in the database. +func (_c *ChargeFlatFeeRunCreateBulk) Save(ctx context.Context) ([]*ChargeFlatFeeRun, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ChargeFlatFeeRun, 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.(*ChargeFlatFeeRunMutation) + 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 *ChargeFlatFeeRunCreateBulk) SaveX(ctx context.Context) []*ChargeFlatFeeRun { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeFlatFeeRunCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeFlatFeeRunCreateBulk) 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.ChargeFlatFeeRun.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.ChargeFlatFeeRunUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *ChargeFlatFeeRunCreateBulk) OnConflict(opts ...sql.ConflictOption) *ChargeFlatFeeRunUpsertBulk { + _c.conflict = opts + return &ChargeFlatFeeRunUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeFlatFeeRun.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeFlatFeeRunCreateBulk) OnConflictColumns(columns ...string) *ChargeFlatFeeRunUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeFlatFeeRunUpsertBulk{ + create: _c, + } +} + +// ChargeFlatFeeRunUpsertBulk is the builder for "upsert"-ing +// a bulk of ChargeFlatFeeRun nodes. +type ChargeFlatFeeRunUpsertBulk struct { + create *ChargeFlatFeeRunCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ChargeFlatFeeRun.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeflatfeerun.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeFlatFeeRunUpsertBulk) UpdateNewValues() *ChargeFlatFeeRunUpsertBulk { + 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(chargeflatfeerun.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(chargeflatfeerun.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(chargeflatfeerun.FieldCreatedAt) + } + if _, exists := b.mutation.ChargeID(); exists { + s.SetIgnore(chargeflatfeerun.FieldChargeID) + } + if _, exists := b.mutation.InitialType(); exists { + s.SetIgnore(chargeflatfeerun.FieldInitialType) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeFlatFeeRun.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeFlatFeeRunUpsertBulk) Ignore() *ChargeFlatFeeRunUpsertBulk { + 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 *ChargeFlatFeeRunUpsertBulk) DoNothing() *ChargeFlatFeeRunUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeFlatFeeRunCreateBulk.OnConflict +// documentation for more info. +func (u *ChargeFlatFeeRunUpsertBulk) Update(set func(*ChargeFlatFeeRunUpsert)) *ChargeFlatFeeRunUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeFlatFeeRunUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeFlatFeeRunUpsertBulk) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertBulk) UpdateUpdatedAt() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeFlatFeeRunUpsertBulk) SetDeletedAt(v time.Time) *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertBulk) UpdateDeletedAt() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeFlatFeeRunUpsertBulk) ClearDeletedAt() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeFlatFeeRunUpsertBulk) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertBulk) UpdateAmount() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateAmount() + }) +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *ChargeFlatFeeRunUpsertBulk) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetTaxesTotal(v) + }) +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertBulk) UpdateTaxesTotal() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateTaxesTotal() + }) +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *ChargeFlatFeeRunUpsertBulk) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetTaxesInclusiveTotal(v) + }) +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertBulk) UpdateTaxesInclusiveTotal() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateTaxesInclusiveTotal() + }) +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *ChargeFlatFeeRunUpsertBulk) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetTaxesExclusiveTotal(v) + }) +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertBulk) UpdateTaxesExclusiveTotal() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateTaxesExclusiveTotal() + }) +} + +// SetChargesTotal sets the "charges_total" field. +func (u *ChargeFlatFeeRunUpsertBulk) SetChargesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetChargesTotal(v) + }) +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertBulk) UpdateChargesTotal() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateChargesTotal() + }) +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *ChargeFlatFeeRunUpsertBulk) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetDiscountsTotal(v) + }) +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertBulk) UpdateDiscountsTotal() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateDiscountsTotal() + }) +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *ChargeFlatFeeRunUpsertBulk) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetCreditsTotal(v) + }) +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertBulk) UpdateCreditsTotal() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateCreditsTotal() + }) +} + +// SetTotal sets the "total" field. +func (u *ChargeFlatFeeRunUpsertBulk) SetTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetTotal(v) + }) +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertBulk) UpdateTotal() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateTotal() + }) +} + +// SetType sets the "type" field. +func (u *ChargeFlatFeeRunUpsertBulk) SetType(v flatfee.RealizationRunType) *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetType(v) + }) +} + +// UpdateType sets the "type" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertBulk) UpdateType() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateType() + }) +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeFlatFeeRunUpsertBulk) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertBulk) UpdateServicePeriodFrom() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeFlatFeeRunUpsertBulk) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertBulk) UpdateServicePeriodTo() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetLineID sets the "line_id" field. +func (u *ChargeFlatFeeRunUpsertBulk) SetLineID(v string) *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetLineID(v) + }) +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertBulk) UpdateLineID() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateLineID() + }) +} + +// ClearLineID clears the value of the "line_id" field. +func (u *ChargeFlatFeeRunUpsertBulk) ClearLineID() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.ClearLineID() + }) +} + +// SetInvoiceID sets the "invoice_id" field. +func (u *ChargeFlatFeeRunUpsertBulk) SetInvoiceID(v string) *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetInvoiceID(v) + }) +} + +// UpdateInvoiceID sets the "invoice_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertBulk) UpdateInvoiceID() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateInvoiceID() + }) +} + +// ClearInvoiceID clears the value of the "invoice_id" field. +func (u *ChargeFlatFeeRunUpsertBulk) ClearInvoiceID() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.ClearInvoiceID() + }) +} + +// SetAmountAfterProration sets the "amount_after_proration" field. +func (u *ChargeFlatFeeRunUpsertBulk) SetAmountAfterProration(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetAmountAfterProration(v) + }) +} + +// UpdateAmountAfterProration sets the "amount_after_proration" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertBulk) UpdateAmountAfterProration() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateAmountAfterProration() + }) +} + +// SetNoFiatTransactionRequired sets the "no_fiat_transaction_required" field. +func (u *ChargeFlatFeeRunUpsertBulk) SetNoFiatTransactionRequired(v bool) *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetNoFiatTransactionRequired(v) + }) +} + +// UpdateNoFiatTransactionRequired sets the "no_fiat_transaction_required" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertBulk) UpdateNoFiatTransactionRequired() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateNoFiatTransactionRequired() + }) +} + +// SetImmutable sets the "immutable" field. +func (u *ChargeFlatFeeRunUpsertBulk) SetImmutable(v bool) *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.SetImmutable(v) + }) +} + +// UpdateImmutable sets the "immutable" field to the value that was provided on create. +func (u *ChargeFlatFeeRunUpsertBulk) UpdateImmutable() *ChargeFlatFeeRunUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunUpsert) { + s.UpdateImmutable() + }) +} + +// Exec executes the query. +func (u *ChargeFlatFeeRunUpsertBulk) 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 ChargeFlatFeeRunCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeFlatFeeRunCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeFlatFeeRunUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargeflatfeerun_delete.go b/ent/db/chargeflatfeerun_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..f250d502dab706a45dd35c79e5d758fe73bb1d3a --- /dev/null +++ b/ent/db/chargeflatfeerun_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/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeFlatFeeRunDelete is the builder for deleting a ChargeFlatFeeRun entity. +type ChargeFlatFeeRunDelete struct { + config + hooks []Hook + mutation *ChargeFlatFeeRunMutation +} + +// Where appends a list predicates to the ChargeFlatFeeRunDelete builder. +func (_d *ChargeFlatFeeRunDelete) Where(ps ...predicate.ChargeFlatFeeRun) *ChargeFlatFeeRunDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ChargeFlatFeeRunDelete) 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 *ChargeFlatFeeRunDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ChargeFlatFeeRunDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(chargeflatfeerun.Table, sqlgraph.NewFieldSpec(chargeflatfeerun.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 +} + +// ChargeFlatFeeRunDeleteOne is the builder for deleting a single ChargeFlatFeeRun entity. +type ChargeFlatFeeRunDeleteOne struct { + _d *ChargeFlatFeeRunDelete +} + +// Where appends a list predicates to the ChargeFlatFeeRunDelete builder. +func (_d *ChargeFlatFeeRunDeleteOne) Where(ps ...predicate.ChargeFlatFeeRun) *ChargeFlatFeeRunDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ChargeFlatFeeRunDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{chargeflatfeerun.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeFlatFeeRunDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargeflatfeerun_query.go b/ent/db/chargeflatfeerun_query.go new file mode 100644 index 0000000000000000000000000000000000000000..1f24f7f501ba89ac1bdd7974ff045f347a4b5633 --- /dev/null +++ b/ent/db/chargeflatfeerun_query.go @@ -0,0 +1,1092 @@ +// 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/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerundetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeFlatFeeRunQuery is the builder for querying ChargeFlatFeeRun entities. +type ChargeFlatFeeRunQuery struct { + config + ctx *QueryContext + order []chargeflatfeerun.OrderOption + inters []Interceptor + predicates []predicate.ChargeFlatFeeRun + withFlatFee *ChargeFlatFeeQuery + withBillingInvoiceLine *BillingInvoiceLineQuery + withBillingInvoice *BillingInvoiceQuery + withCreditAllocations *ChargeFlatFeeRunCreditAllocationsQuery + withDetailedLines *ChargeFlatFeeRunDetailedLineQuery + withInvoicedUsage *ChargeFlatFeeRunInvoicedUsageQuery + withPayment *ChargeFlatFeeRunPaymentQuery + 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 ChargeFlatFeeRunQuery builder. +func (_q *ChargeFlatFeeRunQuery) Where(ps ...predicate.ChargeFlatFeeRun) *ChargeFlatFeeRunQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ChargeFlatFeeRunQuery) Limit(limit int) *ChargeFlatFeeRunQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ChargeFlatFeeRunQuery) Offset(offset int) *ChargeFlatFeeRunQuery { + _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 *ChargeFlatFeeRunQuery) Unique(unique bool) *ChargeFlatFeeRunQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ChargeFlatFeeRunQuery) Order(o ...chargeflatfeerun.OrderOption) *ChargeFlatFeeRunQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryFlatFee chains the current query on the "flat_fee" edge. +func (_q *ChargeFlatFeeRunQuery) QueryFlatFee() *ChargeFlatFeeQuery { + query := (&ChargeFlatFeeClient{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(chargeflatfeerun.Table, chargeflatfeerun.FieldID, selector), + sqlgraph.To(chargeflatfee.Table, chargeflatfee.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfeerun.FlatFeeTable, chargeflatfeerun.FlatFeeColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryBillingInvoiceLine chains the current query on the "billing_invoice_line" edge. +func (_q *ChargeFlatFeeRunQuery) QueryBillingInvoiceLine() *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{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(chargeflatfeerun.Table, chargeflatfeerun.FieldID, selector), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargeflatfeerun.BillingInvoiceLineTable, chargeflatfeerun.BillingInvoiceLineColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryBillingInvoice chains the current query on the "billing_invoice" edge. +func (_q *ChargeFlatFeeRunQuery) QueryBillingInvoice() *BillingInvoiceQuery { + query := (&BillingInvoiceClient{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(chargeflatfeerun.Table, chargeflatfeerun.FieldID, selector), + sqlgraph.To(billinginvoice.Table, billinginvoice.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfeerun.BillingInvoiceTable, chargeflatfeerun.BillingInvoiceColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCreditAllocations chains the current query on the "credit_allocations" edge. +func (_q *ChargeFlatFeeRunQuery) QueryCreditAllocations() *ChargeFlatFeeRunCreditAllocationsQuery { + query := (&ChargeFlatFeeRunCreditAllocationsClient{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(chargeflatfeerun.Table, chargeflatfeerun.FieldID, selector), + sqlgraph.To(chargeflatfeeruncreditallocations.Table, chargeflatfeeruncreditallocations.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, chargeflatfeerun.CreditAllocationsTable, chargeflatfeerun.CreditAllocationsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryDetailedLines chains the current query on the "detailed_lines" edge. +func (_q *ChargeFlatFeeRunQuery) QueryDetailedLines() *ChargeFlatFeeRunDetailedLineQuery { + query := (&ChargeFlatFeeRunDetailedLineClient{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(chargeflatfeerun.Table, chargeflatfeerun.FieldID, selector), + sqlgraph.To(chargeflatfeerundetailedline.Table, chargeflatfeerundetailedline.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, chargeflatfeerun.DetailedLinesTable, chargeflatfeerun.DetailedLinesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryInvoicedUsage chains the current query on the "invoiced_usage" edge. +func (_q *ChargeFlatFeeRunQuery) QueryInvoicedUsage() *ChargeFlatFeeRunInvoicedUsageQuery { + query := (&ChargeFlatFeeRunInvoicedUsageClient{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(chargeflatfeerun.Table, chargeflatfeerun.FieldID, selector), + sqlgraph.To(chargeflatfeeruninvoicedusage.Table, chargeflatfeeruninvoicedusage.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargeflatfeerun.InvoicedUsageTable, chargeflatfeerun.InvoicedUsageColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryPayment chains the current query on the "payment" edge. +func (_q *ChargeFlatFeeRunQuery) QueryPayment() *ChargeFlatFeeRunPaymentQuery { + query := (&ChargeFlatFeeRunPaymentClient{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(chargeflatfeerun.Table, chargeflatfeerun.FieldID, selector), + sqlgraph.To(chargeflatfeerunpayment.Table, chargeflatfeerunpayment.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargeflatfeerun.PaymentTable, chargeflatfeerun.PaymentColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ChargeFlatFeeRun entity from the query. +// Returns a *NotFoundError when no ChargeFlatFeeRun was found. +func (_q *ChargeFlatFeeRunQuery) First(ctx context.Context) (*ChargeFlatFeeRun, 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{chargeflatfeerun.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ChargeFlatFeeRunQuery) FirstX(ctx context.Context) *ChargeFlatFeeRun { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ChargeFlatFeeRun ID from the query. +// Returns a *NotFoundError when no ChargeFlatFeeRun ID was found. +func (_q *ChargeFlatFeeRunQuery) 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{chargeflatfeerun.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ChargeFlatFeeRunQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ChargeFlatFeeRun entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ChargeFlatFeeRun entity is found. +// Returns a *NotFoundError when no ChargeFlatFeeRun entities are found. +func (_q *ChargeFlatFeeRunQuery) Only(ctx context.Context) (*ChargeFlatFeeRun, 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{chargeflatfeerun.Label} + default: + return nil, &NotSingularError{chargeflatfeerun.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ChargeFlatFeeRunQuery) OnlyX(ctx context.Context) *ChargeFlatFeeRun { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ChargeFlatFeeRun ID in the query. +// Returns a *NotSingularError when more than one ChargeFlatFeeRun ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ChargeFlatFeeRunQuery) 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{chargeflatfeerun.Label} + default: + err = &NotSingularError{chargeflatfeerun.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ChargeFlatFeeRunQuery) 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 ChargeFlatFeeRuns. +func (_q *ChargeFlatFeeRunQuery) All(ctx context.Context) ([]*ChargeFlatFeeRun, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ChargeFlatFeeRun, *ChargeFlatFeeRunQuery]() + return withInterceptors[[]*ChargeFlatFeeRun](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ChargeFlatFeeRunQuery) AllX(ctx context.Context) []*ChargeFlatFeeRun { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ChargeFlatFeeRun IDs. +func (_q *ChargeFlatFeeRunQuery) 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(chargeflatfeerun.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ChargeFlatFeeRunQuery) 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 *ChargeFlatFeeRunQuery) 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[*ChargeFlatFeeRunQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ChargeFlatFeeRunQuery) 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 *ChargeFlatFeeRunQuery) 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 *ChargeFlatFeeRunQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ChargeFlatFeeRunQuery 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 *ChargeFlatFeeRunQuery) Clone() *ChargeFlatFeeRunQuery { + if _q == nil { + return nil + } + return &ChargeFlatFeeRunQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]chargeflatfeerun.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ChargeFlatFeeRun{}, _q.predicates...), + withFlatFee: _q.withFlatFee.Clone(), + withBillingInvoiceLine: _q.withBillingInvoiceLine.Clone(), + withBillingInvoice: _q.withBillingInvoice.Clone(), + withCreditAllocations: _q.withCreditAllocations.Clone(), + withDetailedLines: _q.withDetailedLines.Clone(), + withInvoicedUsage: _q.withInvoicedUsage.Clone(), + withPayment: _q.withPayment.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithFlatFee tells the query-builder to eager-load the nodes that are connected to +// the "flat_fee" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeFlatFeeRunQuery) WithFlatFee(opts ...func(*ChargeFlatFeeQuery)) *ChargeFlatFeeRunQuery { + query := (&ChargeFlatFeeClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withFlatFee = query + return _q +} + +// WithBillingInvoiceLine tells the query-builder to eager-load the nodes that are connected to +// the "billing_invoice_line" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeFlatFeeRunQuery) WithBillingInvoiceLine(opts ...func(*BillingInvoiceLineQuery)) *ChargeFlatFeeRunQuery { + query := (&BillingInvoiceLineClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingInvoiceLine = query + return _q +} + +// WithBillingInvoice tells the query-builder to eager-load the nodes that are connected to +// the "billing_invoice" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeFlatFeeRunQuery) WithBillingInvoice(opts ...func(*BillingInvoiceQuery)) *ChargeFlatFeeRunQuery { + query := (&BillingInvoiceClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingInvoice = 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 *ChargeFlatFeeRunQuery) WithCreditAllocations(opts ...func(*ChargeFlatFeeRunCreditAllocationsQuery)) *ChargeFlatFeeRunQuery { + query := (&ChargeFlatFeeRunCreditAllocationsClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCreditAllocations = query + return _q +} + +// WithDetailedLines tells the query-builder to eager-load the nodes that are connected to +// the "detailed_lines" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeFlatFeeRunQuery) WithDetailedLines(opts ...func(*ChargeFlatFeeRunDetailedLineQuery)) *ChargeFlatFeeRunQuery { + query := (&ChargeFlatFeeRunDetailedLineClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withDetailedLines = 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 *ChargeFlatFeeRunQuery) WithInvoicedUsage(opts ...func(*ChargeFlatFeeRunInvoicedUsageQuery)) *ChargeFlatFeeRunQuery { + query := (&ChargeFlatFeeRunInvoicedUsageClient{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 *ChargeFlatFeeRunQuery) WithPayment(opts ...func(*ChargeFlatFeeRunPaymentQuery)) *ChargeFlatFeeRunQuery { + query := (&ChargeFlatFeeRunPaymentClient{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.ChargeFlatFeeRun.Query(). +// GroupBy(chargeflatfeerun.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *ChargeFlatFeeRunQuery) GroupBy(field string, fields ...string) *ChargeFlatFeeRunGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ChargeFlatFeeRunGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = chargeflatfeerun.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.ChargeFlatFeeRun.Query(). +// Select(chargeflatfeerun.FieldNamespace). +// Scan(ctx, &v) +func (_q *ChargeFlatFeeRunQuery) Select(fields ...string) *ChargeFlatFeeRunSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ChargeFlatFeeRunSelect{ChargeFlatFeeRunQuery: _q} + sbuild.label = chargeflatfeerun.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ChargeFlatFeeRunSelect configured with the given aggregations. +func (_q *ChargeFlatFeeRunQuery) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeRunSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ChargeFlatFeeRunQuery) 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 !chargeflatfeerun.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 *ChargeFlatFeeRunQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ChargeFlatFeeRun, error) { + var ( + nodes = []*ChargeFlatFeeRun{} + _spec = _q.querySpec() + loadedTypes = [7]bool{ + _q.withFlatFee != nil, + _q.withBillingInvoiceLine != nil, + _q.withBillingInvoice != nil, + _q.withCreditAllocations != nil, + _q.withDetailedLines != nil, + _q.withInvoicedUsage != nil, + _q.withPayment != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ChargeFlatFeeRun).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ChargeFlatFeeRun{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.withFlatFee; query != nil { + if err := _q.loadFlatFee(ctx, query, nodes, nil, + func(n *ChargeFlatFeeRun, e *ChargeFlatFee) { n.Edges.FlatFee = e }); err != nil { + return nil, err + } + } + if query := _q.withBillingInvoiceLine; query != nil { + if err := _q.loadBillingInvoiceLine(ctx, query, nodes, nil, + func(n *ChargeFlatFeeRun, e *BillingInvoiceLine) { n.Edges.BillingInvoiceLine = e }); err != nil { + return nil, err + } + } + if query := _q.withBillingInvoice; query != nil { + if err := _q.loadBillingInvoice(ctx, query, nodes, nil, + func(n *ChargeFlatFeeRun, e *BillingInvoice) { n.Edges.BillingInvoice = e }); err != nil { + return nil, err + } + } + if query := _q.withCreditAllocations; query != nil { + if err := _q.loadCreditAllocations(ctx, query, nodes, + func(n *ChargeFlatFeeRun) { n.Edges.CreditAllocations = []*ChargeFlatFeeRunCreditAllocations{} }, + func(n *ChargeFlatFeeRun, e *ChargeFlatFeeRunCreditAllocations) { + n.Edges.CreditAllocations = append(n.Edges.CreditAllocations, e) + }); err != nil { + return nil, err + } + } + if query := _q.withDetailedLines; query != nil { + if err := _q.loadDetailedLines(ctx, query, nodes, + func(n *ChargeFlatFeeRun) { n.Edges.DetailedLines = []*ChargeFlatFeeRunDetailedLine{} }, + func(n *ChargeFlatFeeRun, e *ChargeFlatFeeRunDetailedLine) { + n.Edges.DetailedLines = append(n.Edges.DetailedLines, e) + }); err != nil { + return nil, err + } + } + if query := _q.withInvoicedUsage; query != nil { + if err := _q.loadInvoicedUsage(ctx, query, nodes, nil, + func(n *ChargeFlatFeeRun, e *ChargeFlatFeeRunInvoicedUsage) { 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 *ChargeFlatFeeRun, e *ChargeFlatFeeRunPayment) { n.Edges.Payment = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ChargeFlatFeeRunQuery) loadFlatFee(ctx context.Context, query *ChargeFlatFeeQuery, nodes []*ChargeFlatFeeRun, init func(*ChargeFlatFeeRun), assign func(*ChargeFlatFeeRun, *ChargeFlatFee)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeFlatFeeRun) + 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(chargeflatfee.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 *ChargeFlatFeeRunQuery) loadBillingInvoiceLine(ctx context.Context, query *BillingInvoiceLineQuery, nodes []*ChargeFlatFeeRun, init func(*ChargeFlatFeeRun), assign func(*ChargeFlatFeeRun, *BillingInvoiceLine)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeFlatFeeRun) + for i := range nodes { + if nodes[i].LineID == nil { + continue + } + fk := *nodes[i].LineID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(billinginvoiceline.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 "line_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeFlatFeeRunQuery) loadBillingInvoice(ctx context.Context, query *BillingInvoiceQuery, nodes []*ChargeFlatFeeRun, init func(*ChargeFlatFeeRun), assign func(*ChargeFlatFeeRun, *BillingInvoice)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeFlatFeeRun) + for i := range nodes { + if nodes[i].InvoiceID == nil { + continue + } + fk := *nodes[i].InvoiceID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(billinginvoice.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 "invoice_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeFlatFeeRunQuery) loadCreditAllocations(ctx context.Context, query *ChargeFlatFeeRunCreditAllocationsQuery, nodes []*ChargeFlatFeeRun, init func(*ChargeFlatFeeRun), assign func(*ChargeFlatFeeRun, *ChargeFlatFeeRunCreditAllocations)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*ChargeFlatFeeRun) + 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(chargeflatfeeruncreditallocations.FieldRunID) + } + query.Where(predicate.ChargeFlatFeeRunCreditAllocations(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargeflatfeerun.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 *ChargeFlatFeeRunQuery) loadDetailedLines(ctx context.Context, query *ChargeFlatFeeRunDetailedLineQuery, nodes []*ChargeFlatFeeRun, init func(*ChargeFlatFeeRun), assign func(*ChargeFlatFeeRun, *ChargeFlatFeeRunDetailedLine)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*ChargeFlatFeeRun) + 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(chargeflatfeerundetailedline.FieldRunID) + } + query.Where(predicate.ChargeFlatFeeRunDetailedLine(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargeflatfeerun.DetailedLinesColumn), 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 *ChargeFlatFeeRunQuery) loadInvoicedUsage(ctx context.Context, query *ChargeFlatFeeRunInvoicedUsageQuery, nodes []*ChargeFlatFeeRun, init func(*ChargeFlatFeeRun), assign func(*ChargeFlatFeeRun, *ChargeFlatFeeRunInvoicedUsage)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*ChargeFlatFeeRun) + 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(chargeflatfeeruninvoicedusage.FieldRunID) + } + query.Where(predicate.ChargeFlatFeeRunInvoicedUsage(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargeflatfeerun.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 *ChargeFlatFeeRunQuery) loadPayment(ctx context.Context, query *ChargeFlatFeeRunPaymentQuery, nodes []*ChargeFlatFeeRun, init func(*ChargeFlatFeeRun), assign func(*ChargeFlatFeeRun, *ChargeFlatFeeRunPayment)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*ChargeFlatFeeRun) + 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(chargeflatfeerunpayment.FieldRunID) + } + query.Where(predicate.ChargeFlatFeeRunPayment(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargeflatfeerun.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 *ChargeFlatFeeRunQuery) 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 *ChargeFlatFeeRunQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(chargeflatfeerun.Table, chargeflatfeerun.Columns, sqlgraph.NewFieldSpec(chargeflatfeerun.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, chargeflatfeerun.FieldID) + for i := range fields { + if fields[i] != chargeflatfeerun.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withFlatFee != nil { + _spec.Node.AddColumnOnce(chargeflatfeerun.FieldChargeID) + } + if _q.withBillingInvoiceLine != nil { + _spec.Node.AddColumnOnce(chargeflatfeerun.FieldLineID) + } + if _q.withBillingInvoice != nil { + _spec.Node.AddColumnOnce(chargeflatfeerun.FieldInvoiceID) + } + } + 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 *ChargeFlatFeeRunQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(chargeflatfeerun.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = chargeflatfeerun.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 *ChargeFlatFeeRunQuery) ForUpdate(opts ...sql.LockOption) *ChargeFlatFeeRunQuery { + 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 *ChargeFlatFeeRunQuery) ForShare(opts ...sql.LockOption) *ChargeFlatFeeRunQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ChargeFlatFeeRunGroupBy is the group-by builder for ChargeFlatFeeRun entities. +type ChargeFlatFeeRunGroupBy struct { + selector + build *ChargeFlatFeeRunQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ChargeFlatFeeRunGroupBy) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeRunGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ChargeFlatFeeRunGroupBy) 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[*ChargeFlatFeeRunQuery, *ChargeFlatFeeRunGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ChargeFlatFeeRunGroupBy) sqlScan(ctx context.Context, root *ChargeFlatFeeRunQuery, 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) +} + +// ChargeFlatFeeRunSelect is the builder for selecting fields of ChargeFlatFeeRun entities. +type ChargeFlatFeeRunSelect struct { + *ChargeFlatFeeRunQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ChargeFlatFeeRunSelect) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeRunSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ChargeFlatFeeRunSelect) 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[*ChargeFlatFeeRunQuery, *ChargeFlatFeeRunSelect](ctx, _s.ChargeFlatFeeRunQuery, _s, _s.inters, v) +} + +func (_s *ChargeFlatFeeRunSelect) sqlScan(ctx context.Context, root *ChargeFlatFeeRunQuery, 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/ent/db/chargeflatfeerun_update.go b/ent/db/chargeflatfeerun_update.go new file mode 100644 index 0000000000000000000000000000000000000000..492610b6bcffff44177ad5e0b1c36bd53a983d23 --- /dev/null +++ b/ent/db/chargeflatfeerun_update.go @@ -0,0 +1,1636 @@ +// 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/flatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerundetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeFlatFeeRunUpdate is the builder for updating ChargeFlatFeeRun entities. +type ChargeFlatFeeRunUpdate struct { + config + hooks []Hook + mutation *ChargeFlatFeeRunMutation +} + +// Where appends a list predicates to the ChargeFlatFeeRunUpdate builder. +func (_u *ChargeFlatFeeRunUpdate) Where(ps ...predicate.ChargeFlatFeeRun) *ChargeFlatFeeRunUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeFlatFeeRunUpdate) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeFlatFeeRunUpdate) SetDeletedAt(v time.Time) *ChargeFlatFeeRunUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillableDeletedAt(v *time.Time) *ChargeFlatFeeRunUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeFlatFeeRunUpdate) ClearDeletedAt() *ChargeFlatFeeRunUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeFlatFeeRunUpdate) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpdate { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeFlatFeeRunUpdate { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_u *ChargeFlatFeeRunUpdate) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpdate { + _u.mutation.SetTaxesTotal(v) + return _u +} + +// SetNillableTaxesTotal sets the "taxes_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillableTaxesTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunUpdate { + if v != nil { + _u.SetTaxesTotal(*v) + } + return _u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_u *ChargeFlatFeeRunUpdate) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpdate { + _u.mutation.SetTaxesInclusiveTotal(v) + return _u +} + +// SetNillableTaxesInclusiveTotal sets the "taxes_inclusive_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillableTaxesInclusiveTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunUpdate { + if v != nil { + _u.SetTaxesInclusiveTotal(*v) + } + return _u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_u *ChargeFlatFeeRunUpdate) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpdate { + _u.mutation.SetTaxesExclusiveTotal(v) + return _u +} + +// SetNillableTaxesExclusiveTotal sets the "taxes_exclusive_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillableTaxesExclusiveTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunUpdate { + if v != nil { + _u.SetTaxesExclusiveTotal(*v) + } + return _u +} + +// SetChargesTotal sets the "charges_total" field. +func (_u *ChargeFlatFeeRunUpdate) SetChargesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpdate { + _u.mutation.SetChargesTotal(v) + return _u +} + +// SetNillableChargesTotal sets the "charges_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillableChargesTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunUpdate { + if v != nil { + _u.SetChargesTotal(*v) + } + return _u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_u *ChargeFlatFeeRunUpdate) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpdate { + _u.mutation.SetDiscountsTotal(v) + return _u +} + +// SetNillableDiscountsTotal sets the "discounts_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillableDiscountsTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunUpdate { + if v != nil { + _u.SetDiscountsTotal(*v) + } + return _u +} + +// SetCreditsTotal sets the "credits_total" field. +func (_u *ChargeFlatFeeRunUpdate) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpdate { + _u.mutation.SetCreditsTotal(v) + return _u +} + +// SetNillableCreditsTotal sets the "credits_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillableCreditsTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunUpdate { + if v != nil { + _u.SetCreditsTotal(*v) + } + return _u +} + +// SetTotal sets the "total" field. +func (_u *ChargeFlatFeeRunUpdate) SetTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpdate { + _u.mutation.SetTotal(v) + return _u +} + +// SetNillableTotal sets the "total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillableTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunUpdate { + if v != nil { + _u.SetTotal(*v) + } + return _u +} + +// SetType sets the "type" field. +func (_u *ChargeFlatFeeRunUpdate) SetType(v flatfee.RealizationRunType) *ChargeFlatFeeRunUpdate { + _u.mutation.SetType(v) + return _u +} + +// SetNillableType sets the "type" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillableType(v *flatfee.RealizationRunType) *ChargeFlatFeeRunUpdate { + if v != nil { + _u.SetType(*v) + } + return _u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeFlatFeeRunUpdate) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunUpdate { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillableServicePeriodFrom(v *time.Time) *ChargeFlatFeeRunUpdate { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeFlatFeeRunUpdate) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunUpdate { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillableServicePeriodTo(v *time.Time) *ChargeFlatFeeRunUpdate { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetLineID sets the "line_id" field. +func (_u *ChargeFlatFeeRunUpdate) SetLineID(v string) *ChargeFlatFeeRunUpdate { + _u.mutation.SetLineID(v) + return _u +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillableLineID(v *string) *ChargeFlatFeeRunUpdate { + if v != nil { + _u.SetLineID(*v) + } + return _u +} + +// ClearLineID clears the value of the "line_id" field. +func (_u *ChargeFlatFeeRunUpdate) ClearLineID() *ChargeFlatFeeRunUpdate { + _u.mutation.ClearLineID() + return _u +} + +// SetInvoiceID sets the "invoice_id" field. +func (_u *ChargeFlatFeeRunUpdate) SetInvoiceID(v string) *ChargeFlatFeeRunUpdate { + _u.mutation.SetInvoiceID(v) + return _u +} + +// SetNillableInvoiceID sets the "invoice_id" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillableInvoiceID(v *string) *ChargeFlatFeeRunUpdate { + if v != nil { + _u.SetInvoiceID(*v) + } + return _u +} + +// ClearInvoiceID clears the value of the "invoice_id" field. +func (_u *ChargeFlatFeeRunUpdate) ClearInvoiceID() *ChargeFlatFeeRunUpdate { + _u.mutation.ClearInvoiceID() + return _u +} + +// SetAmountAfterProration sets the "amount_after_proration" field. +func (_u *ChargeFlatFeeRunUpdate) SetAmountAfterProration(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpdate { + _u.mutation.SetAmountAfterProration(v) + return _u +} + +// SetNillableAmountAfterProration sets the "amount_after_proration" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillableAmountAfterProration(v *alpacadecimal.Decimal) *ChargeFlatFeeRunUpdate { + if v != nil { + _u.SetAmountAfterProration(*v) + } + return _u +} + +// SetNoFiatTransactionRequired sets the "no_fiat_transaction_required" field. +func (_u *ChargeFlatFeeRunUpdate) SetNoFiatTransactionRequired(v bool) *ChargeFlatFeeRunUpdate { + _u.mutation.SetNoFiatTransactionRequired(v) + return _u +} + +// SetNillableNoFiatTransactionRequired sets the "no_fiat_transaction_required" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillableNoFiatTransactionRequired(v *bool) *ChargeFlatFeeRunUpdate { + if v != nil { + _u.SetNoFiatTransactionRequired(*v) + } + return _u +} + +// SetImmutable sets the "immutable" field. +func (_u *ChargeFlatFeeRunUpdate) SetImmutable(v bool) *ChargeFlatFeeRunUpdate { + _u.mutation.SetImmutable(v) + return _u +} + +// SetNillableImmutable sets the "immutable" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillableImmutable(v *bool) *ChargeFlatFeeRunUpdate { + if v != nil { + _u.SetImmutable(*v) + } + return _u +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID. +func (_u *ChargeFlatFeeRunUpdate) SetBillingInvoiceLineID(id string) *ChargeFlatFeeRunUpdate { + _u.mutation.SetBillingInvoiceLineID(id) + return _u +} + +// SetNillableBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillableBillingInvoiceLineID(id *string) *ChargeFlatFeeRunUpdate { + if id != nil { + _u = _u.SetBillingInvoiceLineID(*id) + } + return _u +} + +// SetBillingInvoiceLine sets the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *ChargeFlatFeeRunUpdate) SetBillingInvoiceLine(v *BillingInvoiceLine) *ChargeFlatFeeRunUpdate { + return _u.SetBillingInvoiceLineID(v.ID) +} + +// SetBillingInvoiceID sets the "billing_invoice" edge to the BillingInvoice entity by ID. +func (_u *ChargeFlatFeeRunUpdate) SetBillingInvoiceID(id string) *ChargeFlatFeeRunUpdate { + _u.mutation.SetBillingInvoiceID(id) + return _u +} + +// SetNillableBillingInvoiceID sets the "billing_invoice" edge to the BillingInvoice entity by ID if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillableBillingInvoiceID(id *string) *ChargeFlatFeeRunUpdate { + if id != nil { + _u = _u.SetBillingInvoiceID(*id) + } + return _u +} + +// SetBillingInvoice sets the "billing_invoice" edge to the BillingInvoice entity. +func (_u *ChargeFlatFeeRunUpdate) SetBillingInvoice(v *BillingInvoice) *ChargeFlatFeeRunUpdate { + return _u.SetBillingInvoiceID(v.ID) +} + +// AddCreditAllocationIDs adds the "credit_allocations" edge to the ChargeFlatFeeRunCreditAllocations entity by IDs. +func (_u *ChargeFlatFeeRunUpdate) AddCreditAllocationIDs(ids ...string) *ChargeFlatFeeRunUpdate { + _u.mutation.AddCreditAllocationIDs(ids...) + return _u +} + +// AddCreditAllocations adds the "credit_allocations" edges to the ChargeFlatFeeRunCreditAllocations entity. +func (_u *ChargeFlatFeeRunUpdate) AddCreditAllocations(v ...*ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddCreditAllocationIDs(ids...) +} + +// AddDetailedLineIDs adds the "detailed_lines" edge to the ChargeFlatFeeRunDetailedLine entity by IDs. +func (_u *ChargeFlatFeeRunUpdate) AddDetailedLineIDs(ids ...string) *ChargeFlatFeeRunUpdate { + _u.mutation.AddDetailedLineIDs(ids...) + return _u +} + +// AddDetailedLines adds the "detailed_lines" edges to the ChargeFlatFeeRunDetailedLine entity. +func (_u *ChargeFlatFeeRunUpdate) AddDetailedLines(v ...*ChargeFlatFeeRunDetailedLine) *ChargeFlatFeeRunUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddDetailedLineIDs(ids...) +} + +// SetInvoicedUsageID sets the "invoiced_usage" edge to the ChargeFlatFeeRunInvoicedUsage entity by ID. +func (_u *ChargeFlatFeeRunUpdate) SetInvoicedUsageID(id string) *ChargeFlatFeeRunUpdate { + _u.mutation.SetInvoicedUsageID(id) + return _u +} + +// SetNillableInvoicedUsageID sets the "invoiced_usage" edge to the ChargeFlatFeeRunInvoicedUsage entity by ID if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillableInvoicedUsageID(id *string) *ChargeFlatFeeRunUpdate { + if id != nil { + _u = _u.SetInvoicedUsageID(*id) + } + return _u +} + +// SetInvoicedUsage sets the "invoiced_usage" edge to the ChargeFlatFeeRunInvoicedUsage entity. +func (_u *ChargeFlatFeeRunUpdate) SetInvoicedUsage(v *ChargeFlatFeeRunInvoicedUsage) *ChargeFlatFeeRunUpdate { + return _u.SetInvoicedUsageID(v.ID) +} + +// SetPaymentID sets the "payment" edge to the ChargeFlatFeeRunPayment entity by ID. +func (_u *ChargeFlatFeeRunUpdate) SetPaymentID(id string) *ChargeFlatFeeRunUpdate { + _u.mutation.SetPaymentID(id) + return _u +} + +// SetNillablePaymentID sets the "payment" edge to the ChargeFlatFeeRunPayment entity by ID if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdate) SetNillablePaymentID(id *string) *ChargeFlatFeeRunUpdate { + if id != nil { + _u = _u.SetPaymentID(*id) + } + return _u +} + +// SetPayment sets the "payment" edge to the ChargeFlatFeeRunPayment entity. +func (_u *ChargeFlatFeeRunUpdate) SetPayment(v *ChargeFlatFeeRunPayment) *ChargeFlatFeeRunUpdate { + return _u.SetPaymentID(v.ID) +} + +// Mutation returns the ChargeFlatFeeRunMutation object of the builder. +func (_u *ChargeFlatFeeRunUpdate) Mutation() *ChargeFlatFeeRunMutation { + return _u.mutation +} + +// ClearBillingInvoiceLine clears the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *ChargeFlatFeeRunUpdate) ClearBillingInvoiceLine() *ChargeFlatFeeRunUpdate { + _u.mutation.ClearBillingInvoiceLine() + return _u +} + +// ClearBillingInvoice clears the "billing_invoice" edge to the BillingInvoice entity. +func (_u *ChargeFlatFeeRunUpdate) ClearBillingInvoice() *ChargeFlatFeeRunUpdate { + _u.mutation.ClearBillingInvoice() + return _u +} + +// ClearCreditAllocations clears all "credit_allocations" edges to the ChargeFlatFeeRunCreditAllocations entity. +func (_u *ChargeFlatFeeRunUpdate) ClearCreditAllocations() *ChargeFlatFeeRunUpdate { + _u.mutation.ClearCreditAllocations() + return _u +} + +// RemoveCreditAllocationIDs removes the "credit_allocations" edge to ChargeFlatFeeRunCreditAllocations entities by IDs. +func (_u *ChargeFlatFeeRunUpdate) RemoveCreditAllocationIDs(ids ...string) *ChargeFlatFeeRunUpdate { + _u.mutation.RemoveCreditAllocationIDs(ids...) + return _u +} + +// RemoveCreditAllocations removes "credit_allocations" edges to ChargeFlatFeeRunCreditAllocations entities. +func (_u *ChargeFlatFeeRunUpdate) RemoveCreditAllocations(v ...*ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveCreditAllocationIDs(ids...) +} + +// ClearDetailedLines clears all "detailed_lines" edges to the ChargeFlatFeeRunDetailedLine entity. +func (_u *ChargeFlatFeeRunUpdate) ClearDetailedLines() *ChargeFlatFeeRunUpdate { + _u.mutation.ClearDetailedLines() + return _u +} + +// RemoveDetailedLineIDs removes the "detailed_lines" edge to ChargeFlatFeeRunDetailedLine entities by IDs. +func (_u *ChargeFlatFeeRunUpdate) RemoveDetailedLineIDs(ids ...string) *ChargeFlatFeeRunUpdate { + _u.mutation.RemoveDetailedLineIDs(ids...) + return _u +} + +// RemoveDetailedLines removes "detailed_lines" edges to ChargeFlatFeeRunDetailedLine entities. +func (_u *ChargeFlatFeeRunUpdate) RemoveDetailedLines(v ...*ChargeFlatFeeRunDetailedLine) *ChargeFlatFeeRunUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveDetailedLineIDs(ids...) +} + +// ClearInvoicedUsage clears the "invoiced_usage" edge to the ChargeFlatFeeRunInvoicedUsage entity. +func (_u *ChargeFlatFeeRunUpdate) ClearInvoicedUsage() *ChargeFlatFeeRunUpdate { + _u.mutation.ClearInvoicedUsage() + return _u +} + +// ClearPayment clears the "payment" edge to the ChargeFlatFeeRunPayment entity. +func (_u *ChargeFlatFeeRunUpdate) ClearPayment() *ChargeFlatFeeRunUpdate { + _u.mutation.ClearPayment() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ChargeFlatFeeRunUpdate) 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 *ChargeFlatFeeRunUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ChargeFlatFeeRunUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeFlatFeeRunUpdate) 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 *ChargeFlatFeeRunUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeflatfeerun.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeFlatFeeRunUpdate) check() error { + if v, ok := _u.mutation.GetType(); ok { + if err := chargeflatfeerun.TypeValidator(v); err != nil { + return &ValidationError{Name: "type", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRun.type": %w`, err)} + } + } + if v, ok := _u.mutation.LineID(); ok { + if err := chargeflatfeerun.LineIDValidator(v); err != nil { + return &ValidationError{Name: "line_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRun.line_id": %w`, err)} + } + } + if v, ok := _u.mutation.InvoiceID(); ok { + if err := chargeflatfeerun.InvoiceIDValidator(v); err != nil { + return &ValidationError{Name: "invoice_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRun.invoice_id": %w`, err)} + } + } + if _u.mutation.FlatFeeCleared() && len(_u.mutation.FlatFeeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeFlatFeeRun.flat_fee"`) + } + return nil +} + +func (_u *ChargeFlatFeeRunUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeflatfeerun.Table, chargeflatfeerun.Columns, sqlgraph.NewFieldSpec(chargeflatfeerun.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(chargeflatfeerun.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeflatfeerun.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeflatfeerun.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(chargeflatfeerun.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesTotal(); ok { + _spec.SetField(chargeflatfeerun.FieldTaxesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(chargeflatfeerun.FieldTaxesInclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(chargeflatfeerun.FieldTaxesExclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.ChargesTotal(); ok { + _spec.SetField(chargeflatfeerun.FieldChargesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.DiscountsTotal(); ok { + _spec.SetField(chargeflatfeerun.FieldDiscountsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.CreditsTotal(); ok { + _spec.SetField(chargeflatfeerun.FieldCreditsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.Total(); ok { + _spec.SetField(chargeflatfeerun.FieldTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.GetType(); ok { + _spec.SetField(chargeflatfeerun.FieldType, field.TypeEnum, value) + } + if value, ok := _u.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeflatfeerun.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeflatfeerun.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.AmountAfterProration(); ok { + _spec.SetField(chargeflatfeerun.FieldAmountAfterProration, field.TypeOther, value) + } + if value, ok := _u.mutation.NoFiatTransactionRequired(); ok { + _spec.SetField(chargeflatfeerun.FieldNoFiatTransactionRequired, field.TypeBool, value) + } + if value, ok := _u.mutation.Immutable(); ok { + _spec.SetField(chargeflatfeerun.FieldImmutable, field.TypeBool, value) + } + if _u.mutation.BillingInvoiceLineCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeflatfeerun.BillingInvoiceLineTable, + Columns: []string{chargeflatfeerun.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingInvoiceLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeflatfeerun.BillingInvoiceLineTable, + Columns: []string{chargeflatfeerun.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.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.BillingInvoiceCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfeerun.BillingInvoiceTable, + Columns: []string{chargeflatfeerun.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingInvoiceIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfeerun.BillingInvoiceTable, + Columns: []string{chargeflatfeerun.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.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.CreditAllocationsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeflatfeerun.CreditAllocationsTable, + Columns: []string{chargeflatfeerun.CreditAllocationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.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: chargeflatfeerun.CreditAllocationsTable, + Columns: []string{chargeflatfeerun.CreditAllocationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.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: chargeflatfeerun.CreditAllocationsTable, + Columns: []string{chargeflatfeerun.CreditAllocationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.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.DetailedLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeflatfeerun.DetailedLinesTable, + Columns: []string{chargeflatfeerun.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerundetailedline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedDetailedLinesIDs(); len(nodes) > 0 && !_u.mutation.DetailedLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeflatfeerun.DetailedLinesTable, + Columns: []string{chargeflatfeerun.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerundetailedline.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.DetailedLinesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeflatfeerun.DetailedLinesTable, + Columns: []string{chargeflatfeerun.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerundetailedline.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: chargeflatfeerun.InvoicedUsageTable, + Columns: []string{chargeflatfeerun.InvoicedUsageColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruninvoicedusage.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: chargeflatfeerun.InvoicedUsageTable, + Columns: []string{chargeflatfeerun.InvoicedUsageColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruninvoicedusage.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: chargeflatfeerun.PaymentTable, + Columns: []string{chargeflatfeerun.PaymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerunpayment.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: chargeflatfeerun.PaymentTable, + Columns: []string{chargeflatfeerun.PaymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerunpayment.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{chargeflatfeerun.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ChargeFlatFeeRunUpdateOne is the builder for updating a single ChargeFlatFeeRun entity. +type ChargeFlatFeeRunUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ChargeFlatFeeRunMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeFlatFeeRunUpdateOne) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeFlatFeeRunUpdateOne) SetDeletedAt(v time.Time) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillableDeletedAt(v *time.Time) *ChargeFlatFeeRunUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeFlatFeeRunUpdateOne) ClearDeletedAt() *ChargeFlatFeeRunUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeFlatFeeRunUpdateOne) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeFlatFeeRunUpdateOne { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_u *ChargeFlatFeeRunUpdateOne) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetTaxesTotal(v) + return _u +} + +// SetNillableTaxesTotal sets the "taxes_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillableTaxesTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunUpdateOne { + if v != nil { + _u.SetTaxesTotal(*v) + } + return _u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_u *ChargeFlatFeeRunUpdateOne) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetTaxesInclusiveTotal(v) + return _u +} + +// SetNillableTaxesInclusiveTotal sets the "taxes_inclusive_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillableTaxesInclusiveTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunUpdateOne { + if v != nil { + _u.SetTaxesInclusiveTotal(*v) + } + return _u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_u *ChargeFlatFeeRunUpdateOne) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetTaxesExclusiveTotal(v) + return _u +} + +// SetNillableTaxesExclusiveTotal sets the "taxes_exclusive_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillableTaxesExclusiveTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunUpdateOne { + if v != nil { + _u.SetTaxesExclusiveTotal(*v) + } + return _u +} + +// SetChargesTotal sets the "charges_total" field. +func (_u *ChargeFlatFeeRunUpdateOne) SetChargesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetChargesTotal(v) + return _u +} + +// SetNillableChargesTotal sets the "charges_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillableChargesTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunUpdateOne { + if v != nil { + _u.SetChargesTotal(*v) + } + return _u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_u *ChargeFlatFeeRunUpdateOne) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetDiscountsTotal(v) + return _u +} + +// SetNillableDiscountsTotal sets the "discounts_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillableDiscountsTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunUpdateOne { + if v != nil { + _u.SetDiscountsTotal(*v) + } + return _u +} + +// SetCreditsTotal sets the "credits_total" field. +func (_u *ChargeFlatFeeRunUpdateOne) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetCreditsTotal(v) + return _u +} + +// SetNillableCreditsTotal sets the "credits_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillableCreditsTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunUpdateOne { + if v != nil { + _u.SetCreditsTotal(*v) + } + return _u +} + +// SetTotal sets the "total" field. +func (_u *ChargeFlatFeeRunUpdateOne) SetTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetTotal(v) + return _u +} + +// SetNillableTotal sets the "total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillableTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunUpdateOne { + if v != nil { + _u.SetTotal(*v) + } + return _u +} + +// SetType sets the "type" field. +func (_u *ChargeFlatFeeRunUpdateOne) SetType(v flatfee.RealizationRunType) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetType(v) + return _u +} + +// SetNillableType sets the "type" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillableType(v *flatfee.RealizationRunType) *ChargeFlatFeeRunUpdateOne { + if v != nil { + _u.SetType(*v) + } + return _u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeFlatFeeRunUpdateOne) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillableServicePeriodFrom(v *time.Time) *ChargeFlatFeeRunUpdateOne { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeFlatFeeRunUpdateOne) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillableServicePeriodTo(v *time.Time) *ChargeFlatFeeRunUpdateOne { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetLineID sets the "line_id" field. +func (_u *ChargeFlatFeeRunUpdateOne) SetLineID(v string) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetLineID(v) + return _u +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillableLineID(v *string) *ChargeFlatFeeRunUpdateOne { + if v != nil { + _u.SetLineID(*v) + } + return _u +} + +// ClearLineID clears the value of the "line_id" field. +func (_u *ChargeFlatFeeRunUpdateOne) ClearLineID() *ChargeFlatFeeRunUpdateOne { + _u.mutation.ClearLineID() + return _u +} + +// SetInvoiceID sets the "invoice_id" field. +func (_u *ChargeFlatFeeRunUpdateOne) SetInvoiceID(v string) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetInvoiceID(v) + return _u +} + +// SetNillableInvoiceID sets the "invoice_id" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillableInvoiceID(v *string) *ChargeFlatFeeRunUpdateOne { + if v != nil { + _u.SetInvoiceID(*v) + } + return _u +} + +// ClearInvoiceID clears the value of the "invoice_id" field. +func (_u *ChargeFlatFeeRunUpdateOne) ClearInvoiceID() *ChargeFlatFeeRunUpdateOne { + _u.mutation.ClearInvoiceID() + return _u +} + +// SetAmountAfterProration sets the "amount_after_proration" field. +func (_u *ChargeFlatFeeRunUpdateOne) SetAmountAfterProration(v alpacadecimal.Decimal) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetAmountAfterProration(v) + return _u +} + +// SetNillableAmountAfterProration sets the "amount_after_proration" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillableAmountAfterProration(v *alpacadecimal.Decimal) *ChargeFlatFeeRunUpdateOne { + if v != nil { + _u.SetAmountAfterProration(*v) + } + return _u +} + +// SetNoFiatTransactionRequired sets the "no_fiat_transaction_required" field. +func (_u *ChargeFlatFeeRunUpdateOne) SetNoFiatTransactionRequired(v bool) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetNoFiatTransactionRequired(v) + return _u +} + +// SetNillableNoFiatTransactionRequired sets the "no_fiat_transaction_required" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillableNoFiatTransactionRequired(v *bool) *ChargeFlatFeeRunUpdateOne { + if v != nil { + _u.SetNoFiatTransactionRequired(*v) + } + return _u +} + +// SetImmutable sets the "immutable" field. +func (_u *ChargeFlatFeeRunUpdateOne) SetImmutable(v bool) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetImmutable(v) + return _u +} + +// SetNillableImmutable sets the "immutable" field if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillableImmutable(v *bool) *ChargeFlatFeeRunUpdateOne { + if v != nil { + _u.SetImmutable(*v) + } + return _u +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID. +func (_u *ChargeFlatFeeRunUpdateOne) SetBillingInvoiceLineID(id string) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetBillingInvoiceLineID(id) + return _u +} + +// SetNillableBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillableBillingInvoiceLineID(id *string) *ChargeFlatFeeRunUpdateOne { + if id != nil { + _u = _u.SetBillingInvoiceLineID(*id) + } + return _u +} + +// SetBillingInvoiceLine sets the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *ChargeFlatFeeRunUpdateOne) SetBillingInvoiceLine(v *BillingInvoiceLine) *ChargeFlatFeeRunUpdateOne { + return _u.SetBillingInvoiceLineID(v.ID) +} + +// SetBillingInvoiceID sets the "billing_invoice" edge to the BillingInvoice entity by ID. +func (_u *ChargeFlatFeeRunUpdateOne) SetBillingInvoiceID(id string) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetBillingInvoiceID(id) + return _u +} + +// SetNillableBillingInvoiceID sets the "billing_invoice" edge to the BillingInvoice entity by ID if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillableBillingInvoiceID(id *string) *ChargeFlatFeeRunUpdateOne { + if id != nil { + _u = _u.SetBillingInvoiceID(*id) + } + return _u +} + +// SetBillingInvoice sets the "billing_invoice" edge to the BillingInvoice entity. +func (_u *ChargeFlatFeeRunUpdateOne) SetBillingInvoice(v *BillingInvoice) *ChargeFlatFeeRunUpdateOne { + return _u.SetBillingInvoiceID(v.ID) +} + +// AddCreditAllocationIDs adds the "credit_allocations" edge to the ChargeFlatFeeRunCreditAllocations entity by IDs. +func (_u *ChargeFlatFeeRunUpdateOne) AddCreditAllocationIDs(ids ...string) *ChargeFlatFeeRunUpdateOne { + _u.mutation.AddCreditAllocationIDs(ids...) + return _u +} + +// AddCreditAllocations adds the "credit_allocations" edges to the ChargeFlatFeeRunCreditAllocations entity. +func (_u *ChargeFlatFeeRunUpdateOne) AddCreditAllocations(v ...*ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddCreditAllocationIDs(ids...) +} + +// AddDetailedLineIDs adds the "detailed_lines" edge to the ChargeFlatFeeRunDetailedLine entity by IDs. +func (_u *ChargeFlatFeeRunUpdateOne) AddDetailedLineIDs(ids ...string) *ChargeFlatFeeRunUpdateOne { + _u.mutation.AddDetailedLineIDs(ids...) + return _u +} + +// AddDetailedLines adds the "detailed_lines" edges to the ChargeFlatFeeRunDetailedLine entity. +func (_u *ChargeFlatFeeRunUpdateOne) AddDetailedLines(v ...*ChargeFlatFeeRunDetailedLine) *ChargeFlatFeeRunUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddDetailedLineIDs(ids...) +} + +// SetInvoicedUsageID sets the "invoiced_usage" edge to the ChargeFlatFeeRunInvoicedUsage entity by ID. +func (_u *ChargeFlatFeeRunUpdateOne) SetInvoicedUsageID(id string) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetInvoicedUsageID(id) + return _u +} + +// SetNillableInvoicedUsageID sets the "invoiced_usage" edge to the ChargeFlatFeeRunInvoicedUsage entity by ID if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillableInvoicedUsageID(id *string) *ChargeFlatFeeRunUpdateOne { + if id != nil { + _u = _u.SetInvoicedUsageID(*id) + } + return _u +} + +// SetInvoicedUsage sets the "invoiced_usage" edge to the ChargeFlatFeeRunInvoicedUsage entity. +func (_u *ChargeFlatFeeRunUpdateOne) SetInvoicedUsage(v *ChargeFlatFeeRunInvoicedUsage) *ChargeFlatFeeRunUpdateOne { + return _u.SetInvoicedUsageID(v.ID) +} + +// SetPaymentID sets the "payment" edge to the ChargeFlatFeeRunPayment entity by ID. +func (_u *ChargeFlatFeeRunUpdateOne) SetPaymentID(id string) *ChargeFlatFeeRunUpdateOne { + _u.mutation.SetPaymentID(id) + return _u +} + +// SetNillablePaymentID sets the "payment" edge to the ChargeFlatFeeRunPayment entity by ID if the given value is not nil. +func (_u *ChargeFlatFeeRunUpdateOne) SetNillablePaymentID(id *string) *ChargeFlatFeeRunUpdateOne { + if id != nil { + _u = _u.SetPaymentID(*id) + } + return _u +} + +// SetPayment sets the "payment" edge to the ChargeFlatFeeRunPayment entity. +func (_u *ChargeFlatFeeRunUpdateOne) SetPayment(v *ChargeFlatFeeRunPayment) *ChargeFlatFeeRunUpdateOne { + return _u.SetPaymentID(v.ID) +} + +// Mutation returns the ChargeFlatFeeRunMutation object of the builder. +func (_u *ChargeFlatFeeRunUpdateOne) Mutation() *ChargeFlatFeeRunMutation { + return _u.mutation +} + +// ClearBillingInvoiceLine clears the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *ChargeFlatFeeRunUpdateOne) ClearBillingInvoiceLine() *ChargeFlatFeeRunUpdateOne { + _u.mutation.ClearBillingInvoiceLine() + return _u +} + +// ClearBillingInvoice clears the "billing_invoice" edge to the BillingInvoice entity. +func (_u *ChargeFlatFeeRunUpdateOne) ClearBillingInvoice() *ChargeFlatFeeRunUpdateOne { + _u.mutation.ClearBillingInvoice() + return _u +} + +// ClearCreditAllocations clears all "credit_allocations" edges to the ChargeFlatFeeRunCreditAllocations entity. +func (_u *ChargeFlatFeeRunUpdateOne) ClearCreditAllocations() *ChargeFlatFeeRunUpdateOne { + _u.mutation.ClearCreditAllocations() + return _u +} + +// RemoveCreditAllocationIDs removes the "credit_allocations" edge to ChargeFlatFeeRunCreditAllocations entities by IDs. +func (_u *ChargeFlatFeeRunUpdateOne) RemoveCreditAllocationIDs(ids ...string) *ChargeFlatFeeRunUpdateOne { + _u.mutation.RemoveCreditAllocationIDs(ids...) + return _u +} + +// RemoveCreditAllocations removes "credit_allocations" edges to ChargeFlatFeeRunCreditAllocations entities. +func (_u *ChargeFlatFeeRunUpdateOne) RemoveCreditAllocations(v ...*ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveCreditAllocationIDs(ids...) +} + +// ClearDetailedLines clears all "detailed_lines" edges to the ChargeFlatFeeRunDetailedLine entity. +func (_u *ChargeFlatFeeRunUpdateOne) ClearDetailedLines() *ChargeFlatFeeRunUpdateOne { + _u.mutation.ClearDetailedLines() + return _u +} + +// RemoveDetailedLineIDs removes the "detailed_lines" edge to ChargeFlatFeeRunDetailedLine entities by IDs. +func (_u *ChargeFlatFeeRunUpdateOne) RemoveDetailedLineIDs(ids ...string) *ChargeFlatFeeRunUpdateOne { + _u.mutation.RemoveDetailedLineIDs(ids...) + return _u +} + +// RemoveDetailedLines removes "detailed_lines" edges to ChargeFlatFeeRunDetailedLine entities. +func (_u *ChargeFlatFeeRunUpdateOne) RemoveDetailedLines(v ...*ChargeFlatFeeRunDetailedLine) *ChargeFlatFeeRunUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveDetailedLineIDs(ids...) +} + +// ClearInvoicedUsage clears the "invoiced_usage" edge to the ChargeFlatFeeRunInvoicedUsage entity. +func (_u *ChargeFlatFeeRunUpdateOne) ClearInvoicedUsage() *ChargeFlatFeeRunUpdateOne { + _u.mutation.ClearInvoicedUsage() + return _u +} + +// ClearPayment clears the "payment" edge to the ChargeFlatFeeRunPayment entity. +func (_u *ChargeFlatFeeRunUpdateOne) ClearPayment() *ChargeFlatFeeRunUpdateOne { + _u.mutation.ClearPayment() + return _u +} + +// Where appends a list predicates to the ChargeFlatFeeRunUpdate builder. +func (_u *ChargeFlatFeeRunUpdateOne) Where(ps ...predicate.ChargeFlatFeeRun) *ChargeFlatFeeRunUpdateOne { + _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 *ChargeFlatFeeRunUpdateOne) Select(field string, fields ...string) *ChargeFlatFeeRunUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ChargeFlatFeeRun entity. +func (_u *ChargeFlatFeeRunUpdateOne) Save(ctx context.Context) (*ChargeFlatFeeRun, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeFlatFeeRunUpdateOne) SaveX(ctx context.Context) *ChargeFlatFeeRun { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ChargeFlatFeeRunUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeFlatFeeRunUpdateOne) 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 *ChargeFlatFeeRunUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeflatfeerun.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeFlatFeeRunUpdateOne) check() error { + if v, ok := _u.mutation.GetType(); ok { + if err := chargeflatfeerun.TypeValidator(v); err != nil { + return &ValidationError{Name: "type", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRun.type": %w`, err)} + } + } + if v, ok := _u.mutation.LineID(); ok { + if err := chargeflatfeerun.LineIDValidator(v); err != nil { + return &ValidationError{Name: "line_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRun.line_id": %w`, err)} + } + } + if v, ok := _u.mutation.InvoiceID(); ok { + if err := chargeflatfeerun.InvoiceIDValidator(v); err != nil { + return &ValidationError{Name: "invoice_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRun.invoice_id": %w`, err)} + } + } + if _u.mutation.FlatFeeCleared() && len(_u.mutation.FlatFeeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeFlatFeeRun.flat_fee"`) + } + return nil +} + +func (_u *ChargeFlatFeeRunUpdateOne) sqlSave(ctx context.Context) (_node *ChargeFlatFeeRun, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeflatfeerun.Table, chargeflatfeerun.Columns, sqlgraph.NewFieldSpec(chargeflatfeerun.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "ChargeFlatFeeRun.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, chargeflatfeerun.FieldID) + for _, f := range fields { + if !chargeflatfeerun.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != chargeflatfeerun.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(chargeflatfeerun.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeflatfeerun.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeflatfeerun.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(chargeflatfeerun.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesTotal(); ok { + _spec.SetField(chargeflatfeerun.FieldTaxesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(chargeflatfeerun.FieldTaxesInclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(chargeflatfeerun.FieldTaxesExclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.ChargesTotal(); ok { + _spec.SetField(chargeflatfeerun.FieldChargesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.DiscountsTotal(); ok { + _spec.SetField(chargeflatfeerun.FieldDiscountsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.CreditsTotal(); ok { + _spec.SetField(chargeflatfeerun.FieldCreditsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.Total(); ok { + _spec.SetField(chargeflatfeerun.FieldTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.GetType(); ok { + _spec.SetField(chargeflatfeerun.FieldType, field.TypeEnum, value) + } + if value, ok := _u.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeflatfeerun.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeflatfeerun.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.AmountAfterProration(); ok { + _spec.SetField(chargeflatfeerun.FieldAmountAfterProration, field.TypeOther, value) + } + if value, ok := _u.mutation.NoFiatTransactionRequired(); ok { + _spec.SetField(chargeflatfeerun.FieldNoFiatTransactionRequired, field.TypeBool, value) + } + if value, ok := _u.mutation.Immutable(); ok { + _spec.SetField(chargeflatfeerun.FieldImmutable, field.TypeBool, value) + } + if _u.mutation.BillingInvoiceLineCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeflatfeerun.BillingInvoiceLineTable, + Columns: []string{chargeflatfeerun.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingInvoiceLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeflatfeerun.BillingInvoiceLineTable, + Columns: []string{chargeflatfeerun.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.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.BillingInvoiceCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfeerun.BillingInvoiceTable, + Columns: []string{chargeflatfeerun.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingInvoiceIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfeerun.BillingInvoiceTable, + Columns: []string{chargeflatfeerun.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.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.CreditAllocationsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeflatfeerun.CreditAllocationsTable, + Columns: []string{chargeflatfeerun.CreditAllocationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.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: chargeflatfeerun.CreditAllocationsTable, + Columns: []string{chargeflatfeerun.CreditAllocationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.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: chargeflatfeerun.CreditAllocationsTable, + Columns: []string{chargeflatfeerun.CreditAllocationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.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.DetailedLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeflatfeerun.DetailedLinesTable, + Columns: []string{chargeflatfeerun.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerundetailedline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedDetailedLinesIDs(); len(nodes) > 0 && !_u.mutation.DetailedLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeflatfeerun.DetailedLinesTable, + Columns: []string{chargeflatfeerun.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerundetailedline.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.DetailedLinesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeflatfeerun.DetailedLinesTable, + Columns: []string{chargeflatfeerun.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerundetailedline.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: chargeflatfeerun.InvoicedUsageTable, + Columns: []string{chargeflatfeerun.InvoicedUsageColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruninvoicedusage.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: chargeflatfeerun.InvoicedUsageTable, + Columns: []string{chargeflatfeerun.InvoicedUsageColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruninvoicedusage.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: chargeflatfeerun.PaymentTable, + Columns: []string{chargeflatfeerun.PaymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerunpayment.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: chargeflatfeerun.PaymentTable, + Columns: []string{chargeflatfeerun.PaymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerunpayment.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &ChargeFlatFeeRun{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{chargeflatfeerun.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/ent/db/chargeflatfeeruncreditallocations.go b/ent/db/chargeflatfeeruncreditallocations.go new file mode 100644 index 0000000000000000000000000000000000000000..ab6349fe94aebbeb132e7f14ee76bc9d86d1f56d --- /dev/null +++ b/ent/db/chargeflatfeeruncreditallocations.go @@ -0,0 +1,350 @@ +// 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/creditrealization" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeruncreditallocations" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeFlatFeeRunCreditAllocations is the model entity for the ChargeFlatFeeRunCreditAllocations schema. +type ChargeFlatFeeRunCreditAllocations 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"` + // SortHint holds the value of the "sort_hint" field. + SortHint int `json:"sort_hint,omitempty"` + // Type holds the value of the "type" field. + Type creditrealization.Type `json:"type,omitempty"` + // CorrectsRealizationID holds the value of the "corrects_realization_id" field. + CorrectsRealizationID *string `json:"corrects_realization_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 ChargeFlatFeeRunCreditAllocationsQuery when eager-loading is set. + Edges ChargeFlatFeeRunCreditAllocationsEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ChargeFlatFeeRunCreditAllocationsEdges holds the relations/edges for other nodes in the graph. +type ChargeFlatFeeRunCreditAllocationsEdges struct { + // Corrections holds the value of the corrections edge. + Corrections []*ChargeFlatFeeRunCreditAllocations `json:"corrections,omitempty"` + // Allocation holds the value of the allocation edge. + Allocation *ChargeFlatFeeRunCreditAllocations `json:"allocation,omitempty"` + // Run holds the value of the run edge. + Run *ChargeFlatFeeRun `json:"run,omitempty"` + // BillingInvoiceLine holds the value of the billing_invoice_line edge. + BillingInvoiceLine *BillingInvoiceLine `json:"billing_invoice_line,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [4]bool +} + +// CorrectionsOrErr returns the Corrections value or an error if the edge +// was not loaded in eager-loading. +func (e ChargeFlatFeeRunCreditAllocationsEdges) CorrectionsOrErr() ([]*ChargeFlatFeeRunCreditAllocations, error) { + if e.loadedTypes[0] { + return e.Corrections, nil + } + return nil, &NotLoadedError{edge: "corrections"} +} + +// AllocationOrErr returns the Allocation value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeFlatFeeRunCreditAllocationsEdges) AllocationOrErr() (*ChargeFlatFeeRunCreditAllocations, error) { + if e.Allocation != nil { + return e.Allocation, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: chargeflatfeeruncreditallocations.Label} + } + return nil, &NotLoadedError{edge: "allocation"} +} + +// 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 ChargeFlatFeeRunCreditAllocationsEdges) RunOrErr() (*ChargeFlatFeeRun, error) { + if e.Run != nil { + return e.Run, nil + } else if e.loadedTypes[2] { + return nil, &NotFoundError{label: chargeflatfeerun.Label} + } + return nil, &NotLoadedError{edge: "run"} +} + +// BillingInvoiceLineOrErr returns the BillingInvoiceLine value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeFlatFeeRunCreditAllocationsEdges) BillingInvoiceLineOrErr() (*BillingInvoiceLine, error) { + if e.BillingInvoiceLine != nil { + return e.BillingInvoiceLine, nil + } else if e.loadedTypes[3] { + return nil, &NotFoundError{label: billinginvoiceline.Label} + } + return nil, &NotLoadedError{edge: "billing_invoice_line"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ChargeFlatFeeRunCreditAllocations) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case chargeflatfeeruncreditallocations.FieldAnnotations: + values[i] = new([]byte) + case chargeflatfeeruncreditallocations.FieldAmount: + values[i] = new(alpacadecimal.Decimal) + case chargeflatfeeruncreditallocations.FieldSortHint: + values[i] = new(sql.NullInt64) + case chargeflatfeeruncreditallocations.FieldID, chargeflatfeeruncreditallocations.FieldLineID, chargeflatfeeruncreditallocations.FieldLedgerTransactionGroupID, chargeflatfeeruncreditallocations.FieldType, chargeflatfeeruncreditallocations.FieldCorrectsRealizationID, chargeflatfeeruncreditallocations.FieldNamespace, chargeflatfeeruncreditallocations.FieldRunID: + values[i] = new(sql.NullString) + case chargeflatfeeruncreditallocations.FieldServicePeriodFrom, chargeflatfeeruncreditallocations.FieldServicePeriodTo, chargeflatfeeruncreditallocations.FieldCreatedAt, chargeflatfeeruncreditallocations.FieldUpdatedAt, chargeflatfeeruncreditallocations.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 ChargeFlatFeeRunCreditAllocations fields. +func (_m *ChargeFlatFeeRunCreditAllocations) 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 chargeflatfeeruncreditallocations.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 chargeflatfeeruncreditallocations.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 chargeflatfeeruncreditallocations.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 chargeflatfeeruncreditallocations.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 chargeflatfeeruncreditallocations.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 chargeflatfeeruncreditallocations.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 chargeflatfeeruncreditallocations.FieldSortHint: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field sort_hint", values[i]) + } else if value.Valid { + _m.SortHint = int(value.Int64) + } + case chargeflatfeeruncreditallocations.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 = creditrealization.Type(value.String) + } + case chargeflatfeeruncreditallocations.FieldCorrectsRealizationID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field corrects_realization_id", values[i]) + } else if value.Valid { + _m.CorrectsRealizationID = new(string) + *_m.CorrectsRealizationID = value.String + } + case chargeflatfeeruncreditallocations.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 chargeflatfeeruncreditallocations.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 chargeflatfeeruncreditallocations.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 chargeflatfeeruncreditallocations.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 chargeflatfeeruncreditallocations.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 chargeflatfeeruncreditallocations.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 ChargeFlatFeeRunCreditAllocations. +// This includes values selected through modifiers, order, etc. +func (_m *ChargeFlatFeeRunCreditAllocations) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryCorrections queries the "corrections" edge of the ChargeFlatFeeRunCreditAllocations entity. +func (_m *ChargeFlatFeeRunCreditAllocations) QueryCorrections() *ChargeFlatFeeRunCreditAllocationsQuery { + return NewChargeFlatFeeRunCreditAllocationsClient(_m.config).QueryCorrections(_m) +} + +// QueryAllocation queries the "allocation" edge of the ChargeFlatFeeRunCreditAllocations entity. +func (_m *ChargeFlatFeeRunCreditAllocations) QueryAllocation() *ChargeFlatFeeRunCreditAllocationsQuery { + return NewChargeFlatFeeRunCreditAllocationsClient(_m.config).QueryAllocation(_m) +} + +// QueryRun queries the "run" edge of the ChargeFlatFeeRunCreditAllocations entity. +func (_m *ChargeFlatFeeRunCreditAllocations) QueryRun() *ChargeFlatFeeRunQuery { + return NewChargeFlatFeeRunCreditAllocationsClient(_m.config).QueryRun(_m) +} + +// QueryBillingInvoiceLine queries the "billing_invoice_line" edge of the ChargeFlatFeeRunCreditAllocations entity. +func (_m *ChargeFlatFeeRunCreditAllocations) QueryBillingInvoiceLine() *BillingInvoiceLineQuery { + return NewChargeFlatFeeRunCreditAllocationsClient(_m.config).QueryBillingInvoiceLine(_m) +} + +// Update returns a builder for updating this ChargeFlatFeeRunCreditAllocations. +// Note that you need to call ChargeFlatFeeRunCreditAllocations.Unwrap() before calling this method if this ChargeFlatFeeRunCreditAllocations +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ChargeFlatFeeRunCreditAllocations) Update() *ChargeFlatFeeRunCreditAllocationsUpdateOne { + return NewChargeFlatFeeRunCreditAllocationsClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ChargeFlatFeeRunCreditAllocations 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 *ChargeFlatFeeRunCreditAllocations) Unwrap() *ChargeFlatFeeRunCreditAllocations { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: ChargeFlatFeeRunCreditAllocations is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ChargeFlatFeeRunCreditAllocations) String() string { + var builder strings.Builder + builder.WriteString("ChargeFlatFeeRunCreditAllocations(") + 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("sort_hint=") + builder.WriteString(fmt.Sprintf("%v", _m.SortHint)) + builder.WriteString(", ") + builder.WriteString("type=") + builder.WriteString(fmt.Sprintf("%v", _m.Type)) + builder.WriteString(", ") + if v := _m.CorrectsRealizationID; v != nil { + builder.WriteString("corrects_realization_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("run_id=") + builder.WriteString(_m.RunID) + builder.WriteByte(')') + return builder.String() +} + +// ChargeFlatFeeRunCreditAllocationsSlice is a parsable slice of ChargeFlatFeeRunCreditAllocations. +type ChargeFlatFeeRunCreditAllocationsSlice []*ChargeFlatFeeRunCreditAllocations diff --git a/ent/db/chargeflatfeeruncreditallocations/chargeflatfeeruncreditallocations.go b/ent/db/chargeflatfeeruncreditallocations/chargeflatfeeruncreditallocations.go new file mode 100644 index 0000000000000000000000000000000000000000..e9e526e6ad60d20cd594ede04792ff728d681dbc --- /dev/null +++ b/ent/db/chargeflatfeeruncreditallocations/chargeflatfeeruncreditallocations.go @@ -0,0 +1,273 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeflatfeeruncreditallocations + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/creditrealization" +) + +const ( + // Label holds the string label denoting the chargeflatfeeruncreditallocations type in the database. + Label = "charge_flat_fee_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" + // FieldSortHint holds the string denoting the sort_hint field in the database. + FieldSortHint = "sort_hint" + // FieldType holds the string denoting the type field in the database. + FieldType = "type" + // FieldCorrectsRealizationID holds the string denoting the corrects_realization_id field in the database. + FieldCorrectsRealizationID = "corrects_realization_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" + // EdgeCorrections holds the string denoting the corrections edge name in mutations. + EdgeCorrections = "corrections" + // EdgeAllocation holds the string denoting the allocation edge name in mutations. + EdgeAllocation = "allocation" + // EdgeRun holds the string denoting the run edge name in mutations. + EdgeRun = "run" + // EdgeBillingInvoiceLine holds the string denoting the billing_invoice_line edge name in mutations. + EdgeBillingInvoiceLine = "billing_invoice_line" + // Table holds the table name of the chargeflatfeeruncreditallocations in the database. + Table = "charge_flat_fee_run_credit_allocations" + // CorrectionsTable is the table that holds the corrections relation/edge. + CorrectionsTable = "charge_flat_fee_run_credit_allocations" + // CorrectionsColumn is the table column denoting the corrections relation/edge. + CorrectionsColumn = "corrects_realization_id" + // AllocationTable is the table that holds the allocation relation/edge. + AllocationTable = "charge_flat_fee_run_credit_allocations" + // AllocationColumn is the table column denoting the allocation relation/edge. + AllocationColumn = "corrects_realization_id" + // RunTable is the table that holds the run relation/edge. + RunTable = "charge_flat_fee_run_credit_allocations" + // RunInverseTable is the table name for the ChargeFlatFeeRun entity. + // It exists in this package in order to avoid circular dependency with the "chargeflatfeerun" package. + RunInverseTable = "charge_flat_fee_runs" + // RunColumn is the table column denoting the run relation/edge. + RunColumn = "run_id" + // BillingInvoiceLineTable is the table that holds the billing_invoice_line relation/edge. + BillingInvoiceLineTable = "charge_flat_fee_run_credit_allocations" + // BillingInvoiceLineInverseTable is the table name for the BillingInvoiceLine entity. + // It exists in this package in order to avoid circular dependency with the "billinginvoiceline" package. + BillingInvoiceLineInverseTable = "billing_invoice_lines" + // BillingInvoiceLineColumn is the table column denoting the billing_invoice_line relation/edge. + BillingInvoiceLineColumn = "line_id" +) + +// Columns holds all SQL columns for chargeflatfeeruncreditallocations fields. +var Columns = []string{ + FieldID, + FieldLineID, + FieldAmount, + FieldServicePeriodFrom, + FieldServicePeriodTo, + FieldLedgerTransactionGroupID, + FieldSortHint, + FieldType, + FieldCorrectsRealizationID, + 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 + // CorrectsRealizationIDValidator is a validator for the "corrects_realization_id" field. It is called by the builders before save. + CorrectsRealizationIDValidator 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 +) + +// TypeValidator is a validator for the "type" field enum values. It is called by the builders before save. +func TypeValidator(_type creditrealization.Type) error { + switch _type { + case "allocation", "correction": + return nil + default: + return fmt.Errorf("chargeflatfeeruncreditallocations: invalid enum value for type field: %q", _type) + } +} + +// OrderOption defines the ordering options for the ChargeFlatFeeRunCreditAllocations 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() +} + +// BySortHint orders the results by the sort_hint field. +func BySortHint(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSortHint, opts...).ToFunc() +} + +// ByType orders the results by the type field. +func ByType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldType, opts...).ToFunc() +} + +// ByCorrectsRealizationID orders the results by the corrects_realization_id field. +func ByCorrectsRealizationID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCorrectsRealizationID, 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() +} + +// ByCorrectionsCount orders the results by corrections count. +func ByCorrectionsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newCorrectionsStep(), opts...) + } +} + +// ByCorrections orders the results by corrections terms. +func ByCorrections(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCorrectionsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByAllocationField orders the results by allocation field. +func ByAllocationField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newAllocationStep(), sql.OrderByField(field, opts...)) + } +} + +// 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...)) + } +} + +// ByBillingInvoiceLineField orders the results by billing_invoice_line field. +func ByBillingInvoiceLineField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBillingInvoiceLineStep(), sql.OrderByField(field, opts...)) + } +} +func newCorrectionsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, CorrectionsTable, CorrectionsColumn), + ) +} +func newAllocationStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, AllocationTable, AllocationColumn), + ) +} +func newRunStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RunInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, RunTable, RunColumn), + ) +} +func newBillingInvoiceLineStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BillingInvoiceLineInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, BillingInvoiceLineTable, BillingInvoiceLineColumn), + ) +} diff --git a/ent/db/chargeflatfeeruncreditallocations/where.go b/ent/db/chargeflatfeeruncreditallocations/where.go new file mode 100644 index 0000000000000000000000000000000000000000..416a8b2ad6b0455878751a24f93b92522f6e7106 --- /dev/null +++ b/ent/db/chargeflatfeeruncreditallocations/where.go @@ -0,0 +1,910 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeflatfeeruncreditallocations + +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/creditrealization" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldContainsFold(FieldID, id)) +} + +// LineID applies equality check predicate on the "line_id" field. It's identical to LineIDEQ. +func LineID(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldLineID, v)) +} + +// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ. +func Amount(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(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.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(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.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(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.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldLedgerTransactionGroupID, v)) +} + +// SortHint applies equality check predicate on the "sort_hint" field. It's identical to SortHintEQ. +func SortHint(v int) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldSortHint, v)) +} + +// CorrectsRealizationID applies equality check predicate on the "corrects_realization_id" field. It's identical to CorrectsRealizationIDEQ. +func CorrectsRealizationID(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldCorrectsRealizationID, v)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(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.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(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.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(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.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldDeletedAt, v)) +} + +// RunID applies equality check predicate on the "run_id" field. It's identical to RunIDEQ. +func RunID(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldRunID, v)) +} + +// LineIDEQ applies the EQ predicate on the "line_id" field. +func LineIDEQ(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldLineID, v)) +} + +// LineIDNEQ applies the NEQ predicate on the "line_id" field. +func LineIDNEQ(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNEQ(FieldLineID, v)) +} + +// LineIDIn applies the In predicate on the "line_id" field. +func LineIDIn(vs ...string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldIn(FieldLineID, vs...)) +} + +// LineIDNotIn applies the NotIn predicate on the "line_id" field. +func LineIDNotIn(vs ...string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNotIn(FieldLineID, vs...)) +} + +// LineIDGT applies the GT predicate on the "line_id" field. +func LineIDGT(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGT(FieldLineID, v)) +} + +// LineIDGTE applies the GTE predicate on the "line_id" field. +func LineIDGTE(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGTE(FieldLineID, v)) +} + +// LineIDLT applies the LT predicate on the "line_id" field. +func LineIDLT(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLT(FieldLineID, v)) +} + +// LineIDLTE applies the LTE predicate on the "line_id" field. +func LineIDLTE(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLTE(FieldLineID, v)) +} + +// LineIDContains applies the Contains predicate on the "line_id" field. +func LineIDContains(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldContains(FieldLineID, v)) +} + +// LineIDHasPrefix applies the HasPrefix predicate on the "line_id" field. +func LineIDHasPrefix(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldHasPrefix(FieldLineID, v)) +} + +// LineIDHasSuffix applies the HasSuffix predicate on the "line_id" field. +func LineIDHasSuffix(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldHasSuffix(FieldLineID, v)) +} + +// LineIDIsNil applies the IsNil predicate on the "line_id" field. +func LineIDIsNil() predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldIsNull(FieldLineID)) +} + +// LineIDNotNil applies the NotNil predicate on the "line_id" field. +func LineIDNotNil() predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNotNull(FieldLineID)) +} + +// LineIDEqualFold applies the EqualFold predicate on the "line_id" field. +func LineIDEqualFold(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEqualFold(FieldLineID, v)) +} + +// LineIDContainsFold applies the ContainsFold predicate on the "line_id" field. +func LineIDContainsFold(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldContainsFold(FieldLineID, v)) +} + +// AmountEQ applies the EQ predicate on the "amount" field. +func AmountEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldAmount, v)) +} + +// AmountNEQ applies the NEQ predicate on the "amount" field. +func AmountNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNEQ(FieldAmount, v)) +} + +// AmountIn applies the In predicate on the "amount" field. +func AmountIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldIn(FieldAmount, vs...)) +} + +// AmountNotIn applies the NotIn predicate on the "amount" field. +func AmountNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNotIn(FieldAmount, vs...)) +} + +// AmountGT applies the GT predicate on the "amount" field. +func AmountGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGT(FieldAmount, v)) +} + +// AmountGTE applies the GTE predicate on the "amount" field. +func AmountGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGTE(FieldAmount, v)) +} + +// AmountLT applies the LT predicate on the "amount" field. +func AmountLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLT(FieldAmount, v)) +} + +// AmountLTE applies the LTE predicate on the "amount" field. +func AmountLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLTE(FieldAmount, v)) +} + +// ServicePeriodFromEQ applies the EQ predicate on the "service_period_from" field. +func ServicePeriodFromEQ(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromNEQ applies the NEQ predicate on the "service_period_from" field. +func ServicePeriodFromNEQ(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromIn applies the In predicate on the "service_period_from" field. +func ServicePeriodFromIn(vs ...time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromNotIn applies the NotIn predicate on the "service_period_from" field. +func ServicePeriodFromNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNotIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromGT applies the GT predicate on the "service_period_from" field. +func ServicePeriodFromGT(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromGTE applies the GTE predicate on the "service_period_from" field. +func ServicePeriodFromGTE(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLT applies the LT predicate on the "service_period_from" field. +func ServicePeriodFromLT(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLTE applies the LTE predicate on the "service_period_from" field. +func ServicePeriodFromLTE(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodToEQ applies the EQ predicate on the "service_period_to" field. +func ServicePeriodToEQ(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToNEQ applies the NEQ predicate on the "service_period_to" field. +func ServicePeriodToNEQ(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToIn applies the In predicate on the "service_period_to" field. +func ServicePeriodToIn(vs ...time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToNotIn applies the NotIn predicate on the "service_period_to" field. +func ServicePeriodToNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNotIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToGT applies the GT predicate on the "service_period_to" field. +func ServicePeriodToGT(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToGTE applies the GTE predicate on the "service_period_to" field. +func ServicePeriodToGTE(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGTE(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLT applies the LT predicate on the "service_period_to" field. +func ServicePeriodToLT(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLTE applies the LTE predicate on the "service_period_to" field. +func ServicePeriodToLTE(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLTE(FieldServicePeriodTo, v)) +} + +// LedgerTransactionGroupIDEQ applies the EQ predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDEQ(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDNEQ applies the NEQ predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDNEQ(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNEQ(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDIn applies the In predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDIn(vs ...string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldIn(FieldLedgerTransactionGroupID, vs...)) +} + +// LedgerTransactionGroupIDNotIn applies the NotIn predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDNotIn(vs ...string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNotIn(FieldLedgerTransactionGroupID, vs...)) +} + +// LedgerTransactionGroupIDGT applies the GT predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDGT(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGT(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDGTE applies the GTE predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDGTE(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGTE(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDLT applies the LT predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDLT(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLT(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDLTE applies the LTE predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDLTE(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLTE(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDContains applies the Contains predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDContains(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldContains(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDHasPrefix applies the HasPrefix predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDHasPrefix(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldHasPrefix(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDHasSuffix applies the HasSuffix predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDHasSuffix(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldHasSuffix(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDEqualFold applies the EqualFold predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDEqualFold(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEqualFold(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDContainsFold applies the ContainsFold predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDContainsFold(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldContainsFold(FieldLedgerTransactionGroupID, v)) +} + +// SortHintEQ applies the EQ predicate on the "sort_hint" field. +func SortHintEQ(v int) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldSortHint, v)) +} + +// SortHintNEQ applies the NEQ predicate on the "sort_hint" field. +func SortHintNEQ(v int) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNEQ(FieldSortHint, v)) +} + +// SortHintIn applies the In predicate on the "sort_hint" field. +func SortHintIn(vs ...int) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldIn(FieldSortHint, vs...)) +} + +// SortHintNotIn applies the NotIn predicate on the "sort_hint" field. +func SortHintNotIn(vs ...int) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNotIn(FieldSortHint, vs...)) +} + +// SortHintGT applies the GT predicate on the "sort_hint" field. +func SortHintGT(v int) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGT(FieldSortHint, v)) +} + +// SortHintGTE applies the GTE predicate on the "sort_hint" field. +func SortHintGTE(v int) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGTE(FieldSortHint, v)) +} + +// SortHintLT applies the LT predicate on the "sort_hint" field. +func SortHintLT(v int) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLT(FieldSortHint, v)) +} + +// SortHintLTE applies the LTE predicate on the "sort_hint" field. +func SortHintLTE(v int) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLTE(FieldSortHint, v)) +} + +// TypeEQ applies the EQ predicate on the "type" field. +func TypeEQ(v creditrealization.Type) predicate.ChargeFlatFeeRunCreditAllocations { + vc := v + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldType, vc)) +} + +// TypeNEQ applies the NEQ predicate on the "type" field. +func TypeNEQ(v creditrealization.Type) predicate.ChargeFlatFeeRunCreditAllocations { + vc := v + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNEQ(FieldType, vc)) +} + +// TypeIn applies the In predicate on the "type" field. +func TypeIn(vs ...creditrealization.Type) predicate.ChargeFlatFeeRunCreditAllocations { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldIn(FieldType, v...)) +} + +// TypeNotIn applies the NotIn predicate on the "type" field. +func TypeNotIn(vs ...creditrealization.Type) predicate.ChargeFlatFeeRunCreditAllocations { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNotIn(FieldType, v...)) +} + +// CorrectsRealizationIDEQ applies the EQ predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDEQ(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldCorrectsRealizationID, v)) +} + +// CorrectsRealizationIDNEQ applies the NEQ predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDNEQ(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNEQ(FieldCorrectsRealizationID, v)) +} + +// CorrectsRealizationIDIn applies the In predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDIn(vs ...string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldIn(FieldCorrectsRealizationID, vs...)) +} + +// CorrectsRealizationIDNotIn applies the NotIn predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDNotIn(vs ...string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNotIn(FieldCorrectsRealizationID, vs...)) +} + +// CorrectsRealizationIDGT applies the GT predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDGT(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGT(FieldCorrectsRealizationID, v)) +} + +// CorrectsRealizationIDGTE applies the GTE predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDGTE(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGTE(FieldCorrectsRealizationID, v)) +} + +// CorrectsRealizationIDLT applies the LT predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDLT(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLT(FieldCorrectsRealizationID, v)) +} + +// CorrectsRealizationIDLTE applies the LTE predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDLTE(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLTE(FieldCorrectsRealizationID, v)) +} + +// CorrectsRealizationIDContains applies the Contains predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDContains(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldContains(FieldCorrectsRealizationID, v)) +} + +// CorrectsRealizationIDHasPrefix applies the HasPrefix predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDHasPrefix(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldHasPrefix(FieldCorrectsRealizationID, v)) +} + +// CorrectsRealizationIDHasSuffix applies the HasSuffix predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDHasSuffix(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldHasSuffix(FieldCorrectsRealizationID, v)) +} + +// CorrectsRealizationIDIsNil applies the IsNil predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDIsNil() predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldIsNull(FieldCorrectsRealizationID)) +} + +// CorrectsRealizationIDNotNil applies the NotNil predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDNotNil() predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNotNull(FieldCorrectsRealizationID)) +} + +// CorrectsRealizationIDEqualFold applies the EqualFold predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDEqualFold(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEqualFold(FieldCorrectsRealizationID, v)) +} + +// CorrectsRealizationIDContainsFold applies the ContainsFold predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDContainsFold(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldContainsFold(FieldCorrectsRealizationID, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNotNull(FieldDeletedAt)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNotNull(FieldAnnotations)) +} + +// RunIDEQ applies the EQ predicate on the "run_id" field. +func RunIDEQ(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEQ(FieldRunID, v)) +} + +// RunIDNEQ applies the NEQ predicate on the "run_id" field. +func RunIDNEQ(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNEQ(FieldRunID, v)) +} + +// RunIDIn applies the In predicate on the "run_id" field. +func RunIDIn(vs ...string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldIn(FieldRunID, vs...)) +} + +// RunIDNotIn applies the NotIn predicate on the "run_id" field. +func RunIDNotIn(vs ...string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldNotIn(FieldRunID, vs...)) +} + +// RunIDGT applies the GT predicate on the "run_id" field. +func RunIDGT(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGT(FieldRunID, v)) +} + +// RunIDGTE applies the GTE predicate on the "run_id" field. +func RunIDGTE(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldGTE(FieldRunID, v)) +} + +// RunIDLT applies the LT predicate on the "run_id" field. +func RunIDLT(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLT(FieldRunID, v)) +} + +// RunIDLTE applies the LTE predicate on the "run_id" field. +func RunIDLTE(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldLTE(FieldRunID, v)) +} + +// RunIDContains applies the Contains predicate on the "run_id" field. +func RunIDContains(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldContains(FieldRunID, v)) +} + +// RunIDHasPrefix applies the HasPrefix predicate on the "run_id" field. +func RunIDHasPrefix(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldHasPrefix(FieldRunID, v)) +} + +// RunIDHasSuffix applies the HasSuffix predicate on the "run_id" field. +func RunIDHasSuffix(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldHasSuffix(FieldRunID, v)) +} + +// RunIDEqualFold applies the EqualFold predicate on the "run_id" field. +func RunIDEqualFold(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldEqualFold(FieldRunID, v)) +} + +// RunIDContainsFold applies the ContainsFold predicate on the "run_id" field. +func RunIDContainsFold(v string) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.FieldContainsFold(FieldRunID, v)) +} + +// HasCorrections applies the HasEdge predicate on the "corrections" edge. +func HasCorrections() predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, CorrectionsTable, CorrectionsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCorrectionsWith applies the HasEdge predicate on the "corrections" edge with a given conditions (other predicates). +func HasCorrectionsWith(preds ...predicate.ChargeFlatFeeRunCreditAllocations) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(func(s *sql.Selector) { + step := newCorrectionsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasAllocation applies the HasEdge predicate on the "allocation" edge. +func HasAllocation() predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, AllocationTable, AllocationColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasAllocationWith applies the HasEdge predicate on the "allocation" edge with a given conditions (other predicates). +func HasAllocationWith(preds ...predicate.ChargeFlatFeeRunCreditAllocations) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(func(s *sql.Selector) { + step := newAllocationStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasRun applies the HasEdge predicate on the "run" edge. +func HasRun() predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(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.ChargeFlatFeeRun) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(func(s *sql.Selector) { + step := newRunStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasBillingInvoiceLine applies the HasEdge predicate on the "billing_invoice_line" edge. +func HasBillingInvoiceLine() predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, BillingInvoiceLineTable, BillingInvoiceLineColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBillingInvoiceLineWith applies the HasEdge predicate on the "billing_invoice_line" edge with a given conditions (other predicates). +func HasBillingInvoiceLineWith(preds ...predicate.BillingInvoiceLine) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(func(s *sql.Selector) { + step := newBillingInvoiceLineStep() + 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.ChargeFlatFeeRunCreditAllocations) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ChargeFlatFeeRunCreditAllocations) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ChargeFlatFeeRunCreditAllocations) predicate.ChargeFlatFeeRunCreditAllocations { + return predicate.ChargeFlatFeeRunCreditAllocations(sql.NotPredicates(p)) +} diff --git a/ent/db/chargeflatfeeruncreditallocations_create.go b/ent/db/chargeflatfeeruncreditallocations_create.go new file mode 100644 index 0000000000000000000000000000000000000000..9f2d4b0155074f36f0951cfe1c97cea86c703c7c --- /dev/null +++ b/ent/db/chargeflatfeeruncreditallocations_create.go @@ -0,0 +1,1309 @@ +// 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/creditrealization" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeruncreditallocations" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeFlatFeeRunCreditAllocationsCreate is the builder for creating a ChargeFlatFeeRunCreditAllocations entity. +type ChargeFlatFeeRunCreditAllocationsCreate struct { + config + mutation *ChargeFlatFeeRunCreditAllocationsMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetLineID sets the "line_id" field. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetLineID(v string) *ChargeFlatFeeRunCreditAllocationsCreate { + _c.mutation.SetLineID(v) + return _c +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetNillableLineID(v *string) *ChargeFlatFeeRunCreditAllocationsCreate { + if v != nil { + _c.SetLineID(*v) + } + return _c +} + +// SetAmount sets the "amount" field. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunCreditAllocationsCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunCreditAllocationsCreate { + _c.mutation.SetServicePeriodFrom(v) + return _c +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunCreditAllocationsCreate { + _c.mutation.SetServicePeriodTo(v) + return _c +} + +// SetLedgerTransactionGroupID sets the "ledger_transaction_group_id" field. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetLedgerTransactionGroupID(v string) *ChargeFlatFeeRunCreditAllocationsCreate { + _c.mutation.SetLedgerTransactionGroupID(v) + return _c +} + +// SetSortHint sets the "sort_hint" field. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetSortHint(v int) *ChargeFlatFeeRunCreditAllocationsCreate { + _c.mutation.SetSortHint(v) + return _c +} + +// SetType sets the "type" field. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetType(v creditrealization.Type) *ChargeFlatFeeRunCreditAllocationsCreate { + _c.mutation.SetType(v) + return _c +} + +// SetCorrectsRealizationID sets the "corrects_realization_id" field. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetCorrectsRealizationID(v string) *ChargeFlatFeeRunCreditAllocationsCreate { + _c.mutation.SetCorrectsRealizationID(v) + return _c +} + +// SetNillableCorrectsRealizationID sets the "corrects_realization_id" field if the given value is not nil. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetNillableCorrectsRealizationID(v *string) *ChargeFlatFeeRunCreditAllocationsCreate { + if v != nil { + _c.SetCorrectsRealizationID(*v) + } + return _c +} + +// SetNamespace sets the "namespace" field. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetNamespace(v string) *ChargeFlatFeeRunCreditAllocationsCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetCreatedAt(v time.Time) *ChargeFlatFeeRunCreditAllocationsCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetNillableCreatedAt(v *time.Time) *ChargeFlatFeeRunCreditAllocationsCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunCreditAllocationsCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetNillableUpdatedAt(v *time.Time) *ChargeFlatFeeRunCreditAllocationsCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetDeletedAt(v time.Time) *ChargeFlatFeeRunCreditAllocationsCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetNillableDeletedAt(v *time.Time) *ChargeFlatFeeRunCreditAllocationsCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunCreditAllocationsCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetRunID sets the "run_id" field. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetRunID(v string) *ChargeFlatFeeRunCreditAllocationsCreate { + _c.mutation.SetRunID(v) + return _c +} + +// SetID sets the "id" field. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetID(v string) *ChargeFlatFeeRunCreditAllocationsCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetNillableID(v *string) *ChargeFlatFeeRunCreditAllocationsCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// AddCorrectionIDs adds the "corrections" edge to the ChargeFlatFeeRunCreditAllocations entity by IDs. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) AddCorrectionIDs(ids ...string) *ChargeFlatFeeRunCreditAllocationsCreate { + _c.mutation.AddCorrectionIDs(ids...) + return _c +} + +// AddCorrections adds the "corrections" edges to the ChargeFlatFeeRunCreditAllocations entity. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) AddCorrections(v ...*ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunCreditAllocationsCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddCorrectionIDs(ids...) +} + +// SetAllocationID sets the "allocation" edge to the ChargeFlatFeeRunCreditAllocations entity by ID. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetAllocationID(id string) *ChargeFlatFeeRunCreditAllocationsCreate { + _c.mutation.SetAllocationID(id) + return _c +} + +// SetNillableAllocationID sets the "allocation" edge to the ChargeFlatFeeRunCreditAllocations entity by ID if the given value is not nil. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetNillableAllocationID(id *string) *ChargeFlatFeeRunCreditAllocationsCreate { + if id != nil { + _c = _c.SetAllocationID(*id) + } + return _c +} + +// SetAllocation sets the "allocation" edge to the ChargeFlatFeeRunCreditAllocations entity. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetAllocation(v *ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunCreditAllocationsCreate { + return _c.SetAllocationID(v.ID) +} + +// SetRun sets the "run" edge to the ChargeFlatFeeRun entity. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetRun(v *ChargeFlatFeeRun) *ChargeFlatFeeRunCreditAllocationsCreate { + return _c.SetRunID(v.ID) +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetBillingInvoiceLineID(id string) *ChargeFlatFeeRunCreditAllocationsCreate { + _c.mutation.SetBillingInvoiceLineID(id) + return _c +} + +// SetNillableBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID if the given value is not nil. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetNillableBillingInvoiceLineID(id *string) *ChargeFlatFeeRunCreditAllocationsCreate { + if id != nil { + _c = _c.SetBillingInvoiceLineID(*id) + } + return _c +} + +// SetBillingInvoiceLine sets the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SetBillingInvoiceLine(v *BillingInvoiceLine) *ChargeFlatFeeRunCreditAllocationsCreate { + return _c.SetBillingInvoiceLineID(v.ID) +} + +// Mutation returns the ChargeFlatFeeRunCreditAllocationsMutation object of the builder. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) Mutation() *ChargeFlatFeeRunCreditAllocationsMutation { + return _c.mutation +} + +// Save creates the ChargeFlatFeeRunCreditAllocations in the database. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) Save(ctx context.Context) (*ChargeFlatFeeRunCreditAllocations, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) SaveX(ctx context.Context) *ChargeFlatFeeRunCreditAllocations { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) 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 *ChargeFlatFeeRunCreditAllocationsCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := chargeflatfeeruncreditallocations.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := chargeflatfeeruncreditallocations.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := chargeflatfeeruncreditallocations.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) check() error { + if v, ok := _c.mutation.LineID(); ok { + if err := chargeflatfeeruncreditallocations.LineIDValidator(v); err != nil { + return &ValidationError{Name: "line_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunCreditAllocations.line_id": %w`, err)} + } + } + if _, ok := _c.mutation.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`db: missing required field "ChargeFlatFeeRunCreditAllocations.amount"`)} + } + if _, ok := _c.mutation.ServicePeriodFrom(); !ok { + return &ValidationError{Name: "service_period_from", err: errors.New(`db: missing required field "ChargeFlatFeeRunCreditAllocations.service_period_from"`)} + } + if _, ok := _c.mutation.ServicePeriodTo(); !ok { + return &ValidationError{Name: "service_period_to", err: errors.New(`db: missing required field "ChargeFlatFeeRunCreditAllocations.service_period_to"`)} + } + if _, ok := _c.mutation.LedgerTransactionGroupID(); !ok { + return &ValidationError{Name: "ledger_transaction_group_id", err: errors.New(`db: missing required field "ChargeFlatFeeRunCreditAllocations.ledger_transaction_group_id"`)} + } + if v, ok := _c.mutation.LedgerTransactionGroupID(); ok { + if err := chargeflatfeeruncreditallocations.LedgerTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "ledger_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunCreditAllocations.ledger_transaction_group_id": %w`, err)} + } + } + if _, ok := _c.mutation.SortHint(); !ok { + return &ValidationError{Name: "sort_hint", err: errors.New(`db: missing required field "ChargeFlatFeeRunCreditAllocations.sort_hint"`)} + } + if _, ok := _c.mutation.GetType(); !ok { + return &ValidationError{Name: "type", err: errors.New(`db: missing required field "ChargeFlatFeeRunCreditAllocations.type"`)} + } + if v, ok := _c.mutation.GetType(); ok { + if err := chargeflatfeeruncreditallocations.TypeValidator(v); err != nil { + return &ValidationError{Name: "type", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunCreditAllocations.type": %w`, err)} + } + } + if v, ok := _c.mutation.CorrectsRealizationID(); ok { + if err := chargeflatfeeruncreditallocations.CorrectsRealizationIDValidator(v); err != nil { + return &ValidationError{Name: "corrects_realization_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunCreditAllocations.corrects_realization_id": %w`, err)} + } + } + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "ChargeFlatFeeRunCreditAllocations.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := chargeflatfeeruncreditallocations.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunCreditAllocations.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "ChargeFlatFeeRunCreditAllocations.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "ChargeFlatFeeRunCreditAllocations.updated_at"`)} + } + if _, ok := _c.mutation.RunID(); !ok { + return &ValidationError{Name: "run_id", err: errors.New(`db: missing required field "ChargeFlatFeeRunCreditAllocations.run_id"`)} + } + if len(_c.mutation.RunIDs()) == 0 { + return &ValidationError{Name: "run", err: errors.New(`db: missing required edge "ChargeFlatFeeRunCreditAllocations.run"`)} + } + return nil +} + +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) sqlSave(ctx context.Context) (*ChargeFlatFeeRunCreditAllocations, 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 ChargeFlatFeeRunCreditAllocations.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) createSpec() (*ChargeFlatFeeRunCreditAllocations, *sqlgraph.CreateSpec) { + var ( + _node = &ChargeFlatFeeRunCreditAllocations{config: _c.config} + _spec = sqlgraph.NewCreateSpec(chargeflatfeeruncreditallocations.Table, sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.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.Amount(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldAmount, field.TypeOther, value) + _node.Amount = value + } + if value, ok := _c.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldServicePeriodFrom, field.TypeTime, value) + _node.ServicePeriodFrom = value + } + if value, ok := _c.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldServicePeriodTo, field.TypeTime, value) + _node.ServicePeriodTo = value + } + if value, ok := _c.mutation.LedgerTransactionGroupID(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldLedgerTransactionGroupID, field.TypeString, value) + _node.LedgerTransactionGroupID = value + } + if value, ok := _c.mutation.SortHint(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldSortHint, field.TypeInt, value) + _node.SortHint = value + } + if value, ok := _c.mutation.GetType(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldType, field.TypeEnum, value) + _node.Type = value + } + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if nodes := _c.mutation.CorrectionsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: chargeflatfeeruncreditallocations.CorrectionsTable, + Columns: []string{chargeflatfeeruncreditallocations.CorrectionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.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.AllocationIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: chargeflatfeeruncreditallocations.AllocationTable, + Columns: []string{chargeflatfeeruncreditallocations.AllocationColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.CorrectsRealizationID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.RunIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfeeruncreditallocations.RunTable, + Columns: []string{chargeflatfeeruncreditallocations.RunColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerun.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) + } + if nodes := _c.mutation.BillingInvoiceLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfeeruncreditallocations.BillingInvoiceLineTable, + Columns: []string{chargeflatfeeruncreditallocations.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.LineID = &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.ChargeFlatFeeRunCreditAllocations.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.ChargeFlatFeeRunCreditAllocationsUpsert) { +// SetLineID(v+v). +// }). +// Exec(ctx) +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) OnConflict(opts ...sql.ConflictOption) *ChargeFlatFeeRunCreditAllocationsUpsertOne { + _c.conflict = opts + return &ChargeFlatFeeRunCreditAllocationsUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeFlatFeeRunCreditAllocations.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeFlatFeeRunCreditAllocationsCreate) OnConflictColumns(columns ...string) *ChargeFlatFeeRunCreditAllocationsUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeFlatFeeRunCreditAllocationsUpsertOne{ + create: _c, + } +} + +type ( + // ChargeFlatFeeRunCreditAllocationsUpsertOne is the builder for "upsert"-ing + // one ChargeFlatFeeRunCreditAllocations node. + ChargeFlatFeeRunCreditAllocationsUpsertOne struct { + create *ChargeFlatFeeRunCreditAllocationsCreate + } + + // ChargeFlatFeeRunCreditAllocationsUpsert is the "OnConflict" setter. + ChargeFlatFeeRunCreditAllocationsUpsert struct { + *sql.UpdateSet + } +) + +// SetLineID sets the "line_id" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) SetLineID(v string) *ChargeFlatFeeRunCreditAllocationsUpsert { + u.Set(chargeflatfeeruncreditallocations.FieldLineID, v) + return u +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) UpdateLineID() *ChargeFlatFeeRunCreditAllocationsUpsert { + u.SetExcluded(chargeflatfeeruncreditallocations.FieldLineID) + return u +} + +// ClearLineID clears the value of the "line_id" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) ClearLineID() *ChargeFlatFeeRunCreditAllocationsUpsert { + u.SetNull(chargeflatfeeruncreditallocations.FieldLineID) + return u +} + +// SetAmount sets the "amount" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunCreditAllocationsUpsert { + u.Set(chargeflatfeeruncreditallocations.FieldAmount, v) + return u +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) UpdateAmount() *ChargeFlatFeeRunCreditAllocationsUpsert { + u.SetExcluded(chargeflatfeeruncreditallocations.FieldAmount) + return u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunCreditAllocationsUpsert { + u.Set(chargeflatfeeruncreditallocations.FieldServicePeriodFrom, v) + return u +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) UpdateServicePeriodFrom() *ChargeFlatFeeRunCreditAllocationsUpsert { + u.SetExcluded(chargeflatfeeruncreditallocations.FieldServicePeriodFrom) + return u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunCreditAllocationsUpsert { + u.Set(chargeflatfeeruncreditallocations.FieldServicePeriodTo, v) + return u +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) UpdateServicePeriodTo() *ChargeFlatFeeRunCreditAllocationsUpsert { + u.SetExcluded(chargeflatfeeruncreditallocations.FieldServicePeriodTo) + return u +} + +// SetSortHint sets the "sort_hint" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) SetSortHint(v int) *ChargeFlatFeeRunCreditAllocationsUpsert { + u.Set(chargeflatfeeruncreditallocations.FieldSortHint, v) + return u +} + +// UpdateSortHint sets the "sort_hint" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) UpdateSortHint() *ChargeFlatFeeRunCreditAllocationsUpsert { + u.SetExcluded(chargeflatfeeruncreditallocations.FieldSortHint) + return u +} + +// AddSortHint adds v to the "sort_hint" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) AddSortHint(v int) *ChargeFlatFeeRunCreditAllocationsUpsert { + u.Add(chargeflatfeeruncreditallocations.FieldSortHint, v) + return u +} + +// SetCorrectsRealizationID sets the "corrects_realization_id" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) SetCorrectsRealizationID(v string) *ChargeFlatFeeRunCreditAllocationsUpsert { + u.Set(chargeflatfeeruncreditallocations.FieldCorrectsRealizationID, v) + return u +} + +// UpdateCorrectsRealizationID sets the "corrects_realization_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) UpdateCorrectsRealizationID() *ChargeFlatFeeRunCreditAllocationsUpsert { + u.SetExcluded(chargeflatfeeruncreditallocations.FieldCorrectsRealizationID) + return u +} + +// ClearCorrectsRealizationID clears the value of the "corrects_realization_id" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) ClearCorrectsRealizationID() *ChargeFlatFeeRunCreditAllocationsUpsert { + u.SetNull(chargeflatfeeruncreditallocations.FieldCorrectsRealizationID) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunCreditAllocationsUpsert { + u.Set(chargeflatfeeruncreditallocations.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) UpdateUpdatedAt() *ChargeFlatFeeRunCreditAllocationsUpsert { + u.SetExcluded(chargeflatfeeruncreditallocations.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) SetDeletedAt(v time.Time) *ChargeFlatFeeRunCreditAllocationsUpsert { + u.Set(chargeflatfeeruncreditallocations.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) UpdateDeletedAt() *ChargeFlatFeeRunCreditAllocationsUpsert { + u.SetExcluded(chargeflatfeeruncreditallocations.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) ClearDeletedAt() *ChargeFlatFeeRunCreditAllocationsUpsert { + u.SetNull(chargeflatfeeruncreditallocations.FieldDeletedAt) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunCreditAllocationsUpsert { + u.Set(chargeflatfeeruncreditallocations.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) UpdateAnnotations() *ChargeFlatFeeRunCreditAllocationsUpsert { + u.SetExcluded(chargeflatfeeruncreditallocations.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsert) ClearAnnotations() *ChargeFlatFeeRunCreditAllocationsUpsert { + u.SetNull(chargeflatfeeruncreditallocations.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.ChargeFlatFeeRunCreditAllocations.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeflatfeeruncreditallocations.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) UpdateNewValues() *ChargeFlatFeeRunCreditAllocationsUpsertOne { + 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(chargeflatfeeruncreditallocations.FieldID) + } + if _, exists := u.create.mutation.LedgerTransactionGroupID(); exists { + s.SetIgnore(chargeflatfeeruncreditallocations.FieldLedgerTransactionGroupID) + } + if _, exists := u.create.mutation.GetType(); exists { + s.SetIgnore(chargeflatfeeruncreditallocations.FieldType) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(chargeflatfeeruncreditallocations.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(chargeflatfeeruncreditallocations.FieldCreatedAt) + } + if _, exists := u.create.mutation.RunID(); exists { + s.SetIgnore(chargeflatfeeruncreditallocations.FieldRunID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeFlatFeeRunCreditAllocations.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) Ignore() *ChargeFlatFeeRunCreditAllocationsUpsertOne { + 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 *ChargeFlatFeeRunCreditAllocationsUpsertOne) DoNothing() *ChargeFlatFeeRunCreditAllocationsUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeFlatFeeRunCreditAllocationsCreate.OnConflict +// documentation for more info. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) Update(set func(*ChargeFlatFeeRunCreditAllocationsUpsert)) *ChargeFlatFeeRunCreditAllocationsUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeFlatFeeRunCreditAllocationsUpsert{UpdateSet: update}) + })) + return u +} + +// SetLineID sets the "line_id" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) SetLineID(v string) *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.SetLineID(v) + }) +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) UpdateLineID() *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.UpdateLineID() + }) +} + +// ClearLineID clears the value of the "line_id" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) ClearLineID() *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.ClearLineID() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) UpdateAmount() *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.UpdateAmount() + }) +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) UpdateServicePeriodFrom() *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) UpdateServicePeriodTo() *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetSortHint sets the "sort_hint" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) SetSortHint(v int) *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.SetSortHint(v) + }) +} + +// AddSortHint adds v to the "sort_hint" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) AddSortHint(v int) *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.AddSortHint(v) + }) +} + +// UpdateSortHint sets the "sort_hint" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) UpdateSortHint() *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.UpdateSortHint() + }) +} + +// SetCorrectsRealizationID sets the "corrects_realization_id" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) SetCorrectsRealizationID(v string) *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.SetCorrectsRealizationID(v) + }) +} + +// UpdateCorrectsRealizationID sets the "corrects_realization_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) UpdateCorrectsRealizationID() *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.UpdateCorrectsRealizationID() + }) +} + +// ClearCorrectsRealizationID clears the value of the "corrects_realization_id" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) ClearCorrectsRealizationID() *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.ClearCorrectsRealizationID() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) UpdateUpdatedAt() *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) SetDeletedAt(v time.Time) *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) UpdateDeletedAt() *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) ClearDeletedAt() *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) UpdateAnnotations() *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) ClearAnnotations() *ChargeFlatFeeRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.ClearAnnotations() + }) +} + +// Exec executes the query. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeFlatFeeRunCreditAllocationsCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertOne) 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 *ChargeFlatFeeRunCreditAllocationsUpsertOne) 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: ChargeFlatFeeRunCreditAllocationsUpsertOne.ID is not supported by MySQL driver. Use ChargeFlatFeeRunCreditAllocationsUpsertOne.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 *ChargeFlatFeeRunCreditAllocationsUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ChargeFlatFeeRunCreditAllocationsCreateBulk is the builder for creating many ChargeFlatFeeRunCreditAllocations entities in bulk. +type ChargeFlatFeeRunCreditAllocationsCreateBulk struct { + config + err error + builders []*ChargeFlatFeeRunCreditAllocationsCreate + conflict []sql.ConflictOption +} + +// Save creates the ChargeFlatFeeRunCreditAllocations entities in the database. +func (_c *ChargeFlatFeeRunCreditAllocationsCreateBulk) Save(ctx context.Context) ([]*ChargeFlatFeeRunCreditAllocations, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ChargeFlatFeeRunCreditAllocations, 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.(*ChargeFlatFeeRunCreditAllocationsMutation) + 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 *ChargeFlatFeeRunCreditAllocationsCreateBulk) SaveX(ctx context.Context) []*ChargeFlatFeeRunCreditAllocations { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeFlatFeeRunCreditAllocationsCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeFlatFeeRunCreditAllocationsCreateBulk) 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.ChargeFlatFeeRunCreditAllocations.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.ChargeFlatFeeRunCreditAllocationsUpsert) { +// SetLineID(v+v). +// }). +// Exec(ctx) +func (_c *ChargeFlatFeeRunCreditAllocationsCreateBulk) OnConflict(opts ...sql.ConflictOption) *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + _c.conflict = opts + return &ChargeFlatFeeRunCreditAllocationsUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeFlatFeeRunCreditAllocations.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeFlatFeeRunCreditAllocationsCreateBulk) OnConflictColumns(columns ...string) *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeFlatFeeRunCreditAllocationsUpsertBulk{ + create: _c, + } +} + +// ChargeFlatFeeRunCreditAllocationsUpsertBulk is the builder for "upsert"-ing +// a bulk of ChargeFlatFeeRunCreditAllocations nodes. +type ChargeFlatFeeRunCreditAllocationsUpsertBulk struct { + create *ChargeFlatFeeRunCreditAllocationsCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ChargeFlatFeeRunCreditAllocations.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeflatfeeruncreditallocations.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) UpdateNewValues() *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + 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(chargeflatfeeruncreditallocations.FieldID) + } + if _, exists := b.mutation.LedgerTransactionGroupID(); exists { + s.SetIgnore(chargeflatfeeruncreditallocations.FieldLedgerTransactionGroupID) + } + if _, exists := b.mutation.GetType(); exists { + s.SetIgnore(chargeflatfeeruncreditallocations.FieldType) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(chargeflatfeeruncreditallocations.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(chargeflatfeeruncreditallocations.FieldCreatedAt) + } + if _, exists := b.mutation.RunID(); exists { + s.SetIgnore(chargeflatfeeruncreditallocations.FieldRunID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeFlatFeeRunCreditAllocations.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) Ignore() *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + 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 *ChargeFlatFeeRunCreditAllocationsUpsertBulk) DoNothing() *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeFlatFeeRunCreditAllocationsCreateBulk.OnConflict +// documentation for more info. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) Update(set func(*ChargeFlatFeeRunCreditAllocationsUpsert)) *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeFlatFeeRunCreditAllocationsUpsert{UpdateSet: update}) + })) + return u +} + +// SetLineID sets the "line_id" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) SetLineID(v string) *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.SetLineID(v) + }) +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) UpdateLineID() *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.UpdateLineID() + }) +} + +// ClearLineID clears the value of the "line_id" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) ClearLineID() *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.ClearLineID() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) UpdateAmount() *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.UpdateAmount() + }) +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) UpdateServicePeriodFrom() *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) UpdateServicePeriodTo() *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetSortHint sets the "sort_hint" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) SetSortHint(v int) *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.SetSortHint(v) + }) +} + +// AddSortHint adds v to the "sort_hint" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) AddSortHint(v int) *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.AddSortHint(v) + }) +} + +// UpdateSortHint sets the "sort_hint" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) UpdateSortHint() *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.UpdateSortHint() + }) +} + +// SetCorrectsRealizationID sets the "corrects_realization_id" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) SetCorrectsRealizationID(v string) *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.SetCorrectsRealizationID(v) + }) +} + +// UpdateCorrectsRealizationID sets the "corrects_realization_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) UpdateCorrectsRealizationID() *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.UpdateCorrectsRealizationID() + }) +} + +// ClearCorrectsRealizationID clears the value of the "corrects_realization_id" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) ClearCorrectsRealizationID() *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.ClearCorrectsRealizationID() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) UpdateUpdatedAt() *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) SetDeletedAt(v time.Time) *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) UpdateDeletedAt() *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) ClearDeletedAt() *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) UpdateAnnotations() *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) ClearAnnotations() *ChargeFlatFeeRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunCreditAllocationsUpsert) { + s.ClearAnnotations() + }) +} + +// Exec executes the query. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) 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 ChargeFlatFeeRunCreditAllocationsCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeFlatFeeRunCreditAllocationsCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeFlatFeeRunCreditAllocationsUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargeflatfeeruncreditallocations_delete.go b/ent/db/chargeflatfeeruncreditallocations_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..3878353c3c10bd771ecbd1292491204339f766f6 --- /dev/null +++ b/ent/db/chargeflatfeeruncreditallocations_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/chargeflatfeeruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeFlatFeeRunCreditAllocationsDelete is the builder for deleting a ChargeFlatFeeRunCreditAllocations entity. +type ChargeFlatFeeRunCreditAllocationsDelete struct { + config + hooks []Hook + mutation *ChargeFlatFeeRunCreditAllocationsMutation +} + +// Where appends a list predicates to the ChargeFlatFeeRunCreditAllocationsDelete builder. +func (_d *ChargeFlatFeeRunCreditAllocationsDelete) Where(ps ...predicate.ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunCreditAllocationsDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ChargeFlatFeeRunCreditAllocationsDelete) 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 *ChargeFlatFeeRunCreditAllocationsDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ChargeFlatFeeRunCreditAllocationsDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(chargeflatfeeruncreditallocations.Table, sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.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 +} + +// ChargeFlatFeeRunCreditAllocationsDeleteOne is the builder for deleting a single ChargeFlatFeeRunCreditAllocations entity. +type ChargeFlatFeeRunCreditAllocationsDeleteOne struct { + _d *ChargeFlatFeeRunCreditAllocationsDelete +} + +// Where appends a list predicates to the ChargeFlatFeeRunCreditAllocationsDelete builder. +func (_d *ChargeFlatFeeRunCreditAllocationsDeleteOne) Where(ps ...predicate.ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunCreditAllocationsDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ChargeFlatFeeRunCreditAllocationsDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{chargeflatfeeruncreditallocations.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeFlatFeeRunCreditAllocationsDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargeflatfeeruncreditallocations_query.go b/ent/db/chargeflatfeeruncreditallocations_query.go new file mode 100644 index 0000000000000000000000000000000000000000..6064ef8e888533931f07fd5d66adf6715bbf6b36 --- /dev/null +++ b/ent/db/chargeflatfeeruncreditallocations_query.go @@ -0,0 +1,881 @@ +// 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/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeFlatFeeRunCreditAllocationsQuery is the builder for querying ChargeFlatFeeRunCreditAllocations entities. +type ChargeFlatFeeRunCreditAllocationsQuery struct { + config + ctx *QueryContext + order []chargeflatfeeruncreditallocations.OrderOption + inters []Interceptor + predicates []predicate.ChargeFlatFeeRunCreditAllocations + withCorrections *ChargeFlatFeeRunCreditAllocationsQuery + withAllocation *ChargeFlatFeeRunCreditAllocationsQuery + withRun *ChargeFlatFeeRunQuery + withBillingInvoiceLine *BillingInvoiceLineQuery + 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 ChargeFlatFeeRunCreditAllocationsQuery builder. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) Where(ps ...predicate.ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunCreditAllocationsQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) Limit(limit int) *ChargeFlatFeeRunCreditAllocationsQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) Offset(offset int) *ChargeFlatFeeRunCreditAllocationsQuery { + _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 *ChargeFlatFeeRunCreditAllocationsQuery) Unique(unique bool) *ChargeFlatFeeRunCreditAllocationsQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) Order(o ...chargeflatfeeruncreditallocations.OrderOption) *ChargeFlatFeeRunCreditAllocationsQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryCorrections chains the current query on the "corrections" edge. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) QueryCorrections() *ChargeFlatFeeRunCreditAllocationsQuery { + query := (&ChargeFlatFeeRunCreditAllocationsClient{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(chargeflatfeeruncreditallocations.Table, chargeflatfeeruncreditallocations.FieldID, selector), + sqlgraph.To(chargeflatfeeruncreditallocations.Table, chargeflatfeeruncreditallocations.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, chargeflatfeeruncreditallocations.CorrectionsTable, chargeflatfeeruncreditallocations.CorrectionsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryAllocation chains the current query on the "allocation" edge. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) QueryAllocation() *ChargeFlatFeeRunCreditAllocationsQuery { + query := (&ChargeFlatFeeRunCreditAllocationsClient{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(chargeflatfeeruncreditallocations.Table, chargeflatfeeruncreditallocations.FieldID, selector), + sqlgraph.To(chargeflatfeeruncreditallocations.Table, chargeflatfeeruncreditallocations.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, chargeflatfeeruncreditallocations.AllocationTable, chargeflatfeeruncreditallocations.AllocationColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryRun chains the current query on the "run" edge. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) QueryRun() *ChargeFlatFeeRunQuery { + query := (&ChargeFlatFeeRunClient{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(chargeflatfeeruncreditallocations.Table, chargeflatfeeruncreditallocations.FieldID, selector), + sqlgraph.To(chargeflatfeerun.Table, chargeflatfeerun.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfeeruncreditallocations.RunTable, chargeflatfeeruncreditallocations.RunColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryBillingInvoiceLine chains the current query on the "billing_invoice_line" edge. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) QueryBillingInvoiceLine() *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{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(chargeflatfeeruncreditallocations.Table, chargeflatfeeruncreditallocations.FieldID, selector), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfeeruncreditallocations.BillingInvoiceLineTable, chargeflatfeeruncreditallocations.BillingInvoiceLineColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ChargeFlatFeeRunCreditAllocations entity from the query. +// Returns a *NotFoundError when no ChargeFlatFeeRunCreditAllocations was found. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) First(ctx context.Context) (*ChargeFlatFeeRunCreditAllocations, 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{chargeflatfeeruncreditallocations.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) FirstX(ctx context.Context) *ChargeFlatFeeRunCreditAllocations { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ChargeFlatFeeRunCreditAllocations ID from the query. +// Returns a *NotFoundError when no ChargeFlatFeeRunCreditAllocations ID was found. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) 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{chargeflatfeeruncreditallocations.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ChargeFlatFeeRunCreditAllocations entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ChargeFlatFeeRunCreditAllocations entity is found. +// Returns a *NotFoundError when no ChargeFlatFeeRunCreditAllocations entities are found. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) Only(ctx context.Context) (*ChargeFlatFeeRunCreditAllocations, 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{chargeflatfeeruncreditallocations.Label} + default: + return nil, &NotSingularError{chargeflatfeeruncreditallocations.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) OnlyX(ctx context.Context) *ChargeFlatFeeRunCreditAllocations { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ChargeFlatFeeRunCreditAllocations ID in the query. +// Returns a *NotSingularError when more than one ChargeFlatFeeRunCreditAllocations ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) 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{chargeflatfeeruncreditallocations.Label} + default: + err = &NotSingularError{chargeflatfeeruncreditallocations.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) 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 ChargeFlatFeeRunCreditAllocationsSlice. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) All(ctx context.Context) ([]*ChargeFlatFeeRunCreditAllocations, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ChargeFlatFeeRunCreditAllocations, *ChargeFlatFeeRunCreditAllocationsQuery]() + return withInterceptors[[]*ChargeFlatFeeRunCreditAllocations](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) AllX(ctx context.Context) []*ChargeFlatFeeRunCreditAllocations { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ChargeFlatFeeRunCreditAllocations IDs. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) 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(chargeflatfeeruncreditallocations.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) 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 *ChargeFlatFeeRunCreditAllocationsQuery) 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[*ChargeFlatFeeRunCreditAllocationsQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) 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 *ChargeFlatFeeRunCreditAllocationsQuery) 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 *ChargeFlatFeeRunCreditAllocationsQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ChargeFlatFeeRunCreditAllocationsQuery 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 *ChargeFlatFeeRunCreditAllocationsQuery) Clone() *ChargeFlatFeeRunCreditAllocationsQuery { + if _q == nil { + return nil + } + return &ChargeFlatFeeRunCreditAllocationsQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]chargeflatfeeruncreditallocations.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ChargeFlatFeeRunCreditAllocations{}, _q.predicates...), + withCorrections: _q.withCorrections.Clone(), + withAllocation: _q.withAllocation.Clone(), + withRun: _q.withRun.Clone(), + withBillingInvoiceLine: _q.withBillingInvoiceLine.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithCorrections tells the query-builder to eager-load the nodes that are connected to +// the "corrections" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) WithCorrections(opts ...func(*ChargeFlatFeeRunCreditAllocationsQuery)) *ChargeFlatFeeRunCreditAllocationsQuery { + query := (&ChargeFlatFeeRunCreditAllocationsClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCorrections = query + return _q +} + +// WithAllocation tells the query-builder to eager-load the nodes that are connected to +// the "allocation" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) WithAllocation(opts ...func(*ChargeFlatFeeRunCreditAllocationsQuery)) *ChargeFlatFeeRunCreditAllocationsQuery { + query := (&ChargeFlatFeeRunCreditAllocationsClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withAllocation = query + return _q +} + +// 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 *ChargeFlatFeeRunCreditAllocationsQuery) WithRun(opts ...func(*ChargeFlatFeeRunQuery)) *ChargeFlatFeeRunCreditAllocationsQuery { + query := (&ChargeFlatFeeRunClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withRun = query + return _q +} + +// WithBillingInvoiceLine tells the query-builder to eager-load the nodes that are connected to +// the "billing_invoice_line" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) WithBillingInvoiceLine(opts ...func(*BillingInvoiceLineQuery)) *ChargeFlatFeeRunCreditAllocationsQuery { + query := (&BillingInvoiceLineClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingInvoiceLine = 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.ChargeFlatFeeRunCreditAllocations.Query(). +// GroupBy(chargeflatfeeruncreditallocations.FieldLineID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) GroupBy(field string, fields ...string) *ChargeFlatFeeRunCreditAllocationsGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ChargeFlatFeeRunCreditAllocationsGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = chargeflatfeeruncreditallocations.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.ChargeFlatFeeRunCreditAllocations.Query(). +// Select(chargeflatfeeruncreditallocations.FieldLineID). +// Scan(ctx, &v) +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) Select(fields ...string) *ChargeFlatFeeRunCreditAllocationsSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ChargeFlatFeeRunCreditAllocationsSelect{ChargeFlatFeeRunCreditAllocationsQuery: _q} + sbuild.label = chargeflatfeeruncreditallocations.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ChargeFlatFeeRunCreditAllocationsSelect configured with the given aggregations. +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeRunCreditAllocationsSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) 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 !chargeflatfeeruncreditallocations.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 *ChargeFlatFeeRunCreditAllocationsQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ChargeFlatFeeRunCreditAllocations, error) { + var ( + nodes = []*ChargeFlatFeeRunCreditAllocations{} + _spec = _q.querySpec() + loadedTypes = [4]bool{ + _q.withCorrections != nil, + _q.withAllocation != nil, + _q.withRun != nil, + _q.withBillingInvoiceLine != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ChargeFlatFeeRunCreditAllocations).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ChargeFlatFeeRunCreditAllocations{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.withCorrections; query != nil { + if err := _q.loadCorrections(ctx, query, nodes, + func(n *ChargeFlatFeeRunCreditAllocations) { + n.Edges.Corrections = []*ChargeFlatFeeRunCreditAllocations{} + }, + func(n *ChargeFlatFeeRunCreditAllocations, e *ChargeFlatFeeRunCreditAllocations) { + n.Edges.Corrections = append(n.Edges.Corrections, e) + }); err != nil { + return nil, err + } + } + if query := _q.withAllocation; query != nil { + if err := _q.loadAllocation(ctx, query, nodes, nil, + func(n *ChargeFlatFeeRunCreditAllocations, e *ChargeFlatFeeRunCreditAllocations) { + n.Edges.Allocation = e + }); err != nil { + return nil, err + } + } + if query := _q.withRun; query != nil { + if err := _q.loadRun(ctx, query, nodes, nil, + func(n *ChargeFlatFeeRunCreditAllocations, e *ChargeFlatFeeRun) { n.Edges.Run = e }); err != nil { + return nil, err + } + } + if query := _q.withBillingInvoiceLine; query != nil { + if err := _q.loadBillingInvoiceLine(ctx, query, nodes, nil, + func(n *ChargeFlatFeeRunCreditAllocations, e *BillingInvoiceLine) { n.Edges.BillingInvoiceLine = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) loadCorrections(ctx context.Context, query *ChargeFlatFeeRunCreditAllocationsQuery, nodes []*ChargeFlatFeeRunCreditAllocations, init func(*ChargeFlatFeeRunCreditAllocations), assign func(*ChargeFlatFeeRunCreditAllocations, *ChargeFlatFeeRunCreditAllocations)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*ChargeFlatFeeRunCreditAllocations) + 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(chargeflatfeeruncreditallocations.FieldCorrectsRealizationID) + } + query.Where(predicate.ChargeFlatFeeRunCreditAllocations(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargeflatfeeruncreditallocations.CorrectionsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.CorrectsRealizationID + if fk == nil { + return fmt.Errorf(`foreign-key "corrects_realization_id" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "corrects_realization_id" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) loadAllocation(ctx context.Context, query *ChargeFlatFeeRunCreditAllocationsQuery, nodes []*ChargeFlatFeeRunCreditAllocations, init func(*ChargeFlatFeeRunCreditAllocations), assign func(*ChargeFlatFeeRunCreditAllocations, *ChargeFlatFeeRunCreditAllocations)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeFlatFeeRunCreditAllocations) + for i := range nodes { + if nodes[i].CorrectsRealizationID == nil { + continue + } + fk := *nodes[i].CorrectsRealizationID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(chargeflatfeeruncreditallocations.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 "corrects_realization_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) loadRun(ctx context.Context, query *ChargeFlatFeeRunQuery, nodes []*ChargeFlatFeeRunCreditAllocations, init func(*ChargeFlatFeeRunCreditAllocations), assign func(*ChargeFlatFeeRunCreditAllocations, *ChargeFlatFeeRun)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeFlatFeeRunCreditAllocations) + 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(chargeflatfeerun.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 *ChargeFlatFeeRunCreditAllocationsQuery) loadBillingInvoiceLine(ctx context.Context, query *BillingInvoiceLineQuery, nodes []*ChargeFlatFeeRunCreditAllocations, init func(*ChargeFlatFeeRunCreditAllocations), assign func(*ChargeFlatFeeRunCreditAllocations, *BillingInvoiceLine)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeFlatFeeRunCreditAllocations) + for i := range nodes { + if nodes[i].LineID == nil { + continue + } + fk := *nodes[i].LineID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(billinginvoiceline.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 "line_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *ChargeFlatFeeRunCreditAllocationsQuery) 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 *ChargeFlatFeeRunCreditAllocationsQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(chargeflatfeeruncreditallocations.Table, chargeflatfeeruncreditallocations.Columns, sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.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, chargeflatfeeruncreditallocations.FieldID) + for i := range fields { + if fields[i] != chargeflatfeeruncreditallocations.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withAllocation != nil { + _spec.Node.AddColumnOnce(chargeflatfeeruncreditallocations.FieldCorrectsRealizationID) + } + if _q.withRun != nil { + _spec.Node.AddColumnOnce(chargeflatfeeruncreditallocations.FieldRunID) + } + if _q.withBillingInvoiceLine != nil { + _spec.Node.AddColumnOnce(chargeflatfeeruncreditallocations.FieldLineID) + } + } + 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 *ChargeFlatFeeRunCreditAllocationsQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(chargeflatfeeruncreditallocations.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = chargeflatfeeruncreditallocations.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 *ChargeFlatFeeRunCreditAllocationsQuery) ForUpdate(opts ...sql.LockOption) *ChargeFlatFeeRunCreditAllocationsQuery { + 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 *ChargeFlatFeeRunCreditAllocationsQuery) ForShare(opts ...sql.LockOption) *ChargeFlatFeeRunCreditAllocationsQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ChargeFlatFeeRunCreditAllocationsGroupBy is the group-by builder for ChargeFlatFeeRunCreditAllocations entities. +type ChargeFlatFeeRunCreditAllocationsGroupBy struct { + selector + build *ChargeFlatFeeRunCreditAllocationsQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ChargeFlatFeeRunCreditAllocationsGroupBy) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeRunCreditAllocationsGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ChargeFlatFeeRunCreditAllocationsGroupBy) 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[*ChargeFlatFeeRunCreditAllocationsQuery, *ChargeFlatFeeRunCreditAllocationsGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ChargeFlatFeeRunCreditAllocationsGroupBy) sqlScan(ctx context.Context, root *ChargeFlatFeeRunCreditAllocationsQuery, 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) +} + +// ChargeFlatFeeRunCreditAllocationsSelect is the builder for selecting fields of ChargeFlatFeeRunCreditAllocations entities. +type ChargeFlatFeeRunCreditAllocationsSelect struct { + *ChargeFlatFeeRunCreditAllocationsQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ChargeFlatFeeRunCreditAllocationsSelect) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeRunCreditAllocationsSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ChargeFlatFeeRunCreditAllocationsSelect) 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[*ChargeFlatFeeRunCreditAllocationsQuery, *ChargeFlatFeeRunCreditAllocationsSelect](ctx, _s.ChargeFlatFeeRunCreditAllocationsQuery, _s, _s.inters, v) +} + +func (_s *ChargeFlatFeeRunCreditAllocationsSelect) sqlScan(ctx context.Context, root *ChargeFlatFeeRunCreditAllocationsQuery, 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/ent/db/chargeflatfeeruncreditallocations_update.go b/ent/db/chargeflatfeeruncreditallocations_update.go new file mode 100644 index 0000000000000000000000000000000000000000..020442d16e13d81c9912d280721a0496cd906967 --- /dev/null +++ b/ent/db/chargeflatfeeruncreditallocations_update.go @@ -0,0 +1,959 @@ +// 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/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeFlatFeeRunCreditAllocationsUpdate is the builder for updating ChargeFlatFeeRunCreditAllocations entities. +type ChargeFlatFeeRunCreditAllocationsUpdate struct { + config + hooks []Hook + mutation *ChargeFlatFeeRunCreditAllocationsMutation +} + +// Where appends a list predicates to the ChargeFlatFeeRunCreditAllocationsUpdate builder. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) Where(ps ...predicate.ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetLineID sets the "line_id" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetLineID(v string) *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.SetLineID(v) + return _u +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetNillableLineID(v *string) *ChargeFlatFeeRunCreditAllocationsUpdate { + if v != nil { + _u.SetLineID(*v) + } + return _u +} + +// ClearLineID clears the value of the "line_id" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) ClearLineID() *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.ClearLineID() + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeFlatFeeRunCreditAllocationsUpdate { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetNillableServicePeriodFrom(v *time.Time) *ChargeFlatFeeRunCreditAllocationsUpdate { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetNillableServicePeriodTo(v *time.Time) *ChargeFlatFeeRunCreditAllocationsUpdate { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetSortHint sets the "sort_hint" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetSortHint(v int) *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.ResetSortHint() + _u.mutation.SetSortHint(v) + return _u +} + +// SetNillableSortHint sets the "sort_hint" field if the given value is not nil. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetNillableSortHint(v *int) *ChargeFlatFeeRunCreditAllocationsUpdate { + if v != nil { + _u.SetSortHint(*v) + } + return _u +} + +// AddSortHint adds value to the "sort_hint" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) AddSortHint(v int) *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.AddSortHint(v) + return _u +} + +// SetCorrectsRealizationID sets the "corrects_realization_id" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetCorrectsRealizationID(v string) *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.SetCorrectsRealizationID(v) + return _u +} + +// SetNillableCorrectsRealizationID sets the "corrects_realization_id" field if the given value is not nil. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetNillableCorrectsRealizationID(v *string) *ChargeFlatFeeRunCreditAllocationsUpdate { + if v != nil { + _u.SetCorrectsRealizationID(*v) + } + return _u +} + +// ClearCorrectsRealizationID clears the value of the "corrects_realization_id" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) ClearCorrectsRealizationID() *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.ClearCorrectsRealizationID() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetDeletedAt(v time.Time) *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetNillableDeletedAt(v *time.Time) *ChargeFlatFeeRunCreditAllocationsUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) ClearDeletedAt() *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) ClearAnnotations() *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// AddCorrectionIDs adds the "corrections" edge to the ChargeFlatFeeRunCreditAllocations entity by IDs. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) AddCorrectionIDs(ids ...string) *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.AddCorrectionIDs(ids...) + return _u +} + +// AddCorrections adds the "corrections" edges to the ChargeFlatFeeRunCreditAllocations entity. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) AddCorrections(v ...*ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunCreditAllocationsUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddCorrectionIDs(ids...) +} + +// SetAllocationID sets the "allocation" edge to the ChargeFlatFeeRunCreditAllocations entity by ID. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetAllocationID(id string) *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.SetAllocationID(id) + return _u +} + +// SetNillableAllocationID sets the "allocation" edge to the ChargeFlatFeeRunCreditAllocations entity by ID if the given value is not nil. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetNillableAllocationID(id *string) *ChargeFlatFeeRunCreditAllocationsUpdate { + if id != nil { + _u = _u.SetAllocationID(*id) + } + return _u +} + +// SetAllocation sets the "allocation" edge to the ChargeFlatFeeRunCreditAllocations entity. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetAllocation(v *ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunCreditAllocationsUpdate { + return _u.SetAllocationID(v.ID) +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetBillingInvoiceLineID(id string) *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.SetBillingInvoiceLineID(id) + return _u +} + +// SetNillableBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID if the given value is not nil. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetNillableBillingInvoiceLineID(id *string) *ChargeFlatFeeRunCreditAllocationsUpdate { + if id != nil { + _u = _u.SetBillingInvoiceLineID(*id) + } + return _u +} + +// SetBillingInvoiceLine sets the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) SetBillingInvoiceLine(v *BillingInvoiceLine) *ChargeFlatFeeRunCreditAllocationsUpdate { + return _u.SetBillingInvoiceLineID(v.ID) +} + +// Mutation returns the ChargeFlatFeeRunCreditAllocationsMutation object of the builder. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) Mutation() *ChargeFlatFeeRunCreditAllocationsMutation { + return _u.mutation +} + +// ClearCorrections clears all "corrections" edges to the ChargeFlatFeeRunCreditAllocations entity. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) ClearCorrections() *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.ClearCorrections() + return _u +} + +// RemoveCorrectionIDs removes the "corrections" edge to ChargeFlatFeeRunCreditAllocations entities by IDs. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) RemoveCorrectionIDs(ids ...string) *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.RemoveCorrectionIDs(ids...) + return _u +} + +// RemoveCorrections removes "corrections" edges to ChargeFlatFeeRunCreditAllocations entities. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) RemoveCorrections(v ...*ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunCreditAllocationsUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveCorrectionIDs(ids...) +} + +// ClearAllocation clears the "allocation" edge to the ChargeFlatFeeRunCreditAllocations entity. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) ClearAllocation() *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.ClearAllocation() + return _u +} + +// ClearBillingInvoiceLine clears the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) ClearBillingInvoiceLine() *ChargeFlatFeeRunCreditAllocationsUpdate { + _u.mutation.ClearBillingInvoiceLine() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) 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 *ChargeFlatFeeRunCreditAllocationsUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) 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 *ChargeFlatFeeRunCreditAllocationsUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeflatfeeruncreditallocations.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) check() error { + if v, ok := _u.mutation.LineID(); ok { + if err := chargeflatfeeruncreditallocations.LineIDValidator(v); err != nil { + return &ValidationError{Name: "line_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunCreditAllocations.line_id": %w`, err)} + } + } + if v, ok := _u.mutation.CorrectsRealizationID(); ok { + if err := chargeflatfeeruncreditallocations.CorrectsRealizationIDValidator(v); err != nil { + return &ValidationError{Name: "corrects_realization_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunCreditAllocations.corrects_realization_id": %w`, err)} + } + } + if _u.mutation.RunCleared() && len(_u.mutation.RunIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeFlatFeeRunCreditAllocations.run"`) + } + return nil +} + +func (_u *ChargeFlatFeeRunCreditAllocationsUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeflatfeeruncreditallocations.Table, chargeflatfeeruncreditallocations.Columns, sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.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.Amount(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.SortHint(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldSortHint, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedSortHint(); ok { + _spec.AddField(chargeflatfeeruncreditallocations.FieldSortHint, field.TypeInt, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeflatfeeruncreditallocations.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargeflatfeeruncreditallocations.FieldAnnotations, field.TypeJSON) + } + if _u.mutation.CorrectionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: chargeflatfeeruncreditallocations.CorrectionsTable, + Columns: []string{chargeflatfeeruncreditallocations.CorrectionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedCorrectionsIDs(); len(nodes) > 0 && !_u.mutation.CorrectionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: chargeflatfeeruncreditallocations.CorrectionsTable, + Columns: []string{chargeflatfeeruncreditallocations.CorrectionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.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.CorrectionsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: chargeflatfeeruncreditallocations.CorrectionsTable, + Columns: []string{chargeflatfeeruncreditallocations.CorrectionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.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.AllocationCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: chargeflatfeeruncreditallocations.AllocationTable, + Columns: []string{chargeflatfeeruncreditallocations.AllocationColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.AllocationIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: chargeflatfeeruncreditallocations.AllocationTable, + Columns: []string{chargeflatfeeruncreditallocations.AllocationColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.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.BillingInvoiceLineCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfeeruncreditallocations.BillingInvoiceLineTable, + Columns: []string{chargeflatfeeruncreditallocations.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingInvoiceLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfeeruncreditallocations.BillingInvoiceLineTable, + Columns: []string{chargeflatfeeruncreditallocations.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.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{chargeflatfeeruncreditallocations.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ChargeFlatFeeRunCreditAllocationsUpdateOne is the builder for updating a single ChargeFlatFeeRunCreditAllocations entity. +type ChargeFlatFeeRunCreditAllocationsUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ChargeFlatFeeRunCreditAllocationsMutation +} + +// SetLineID sets the "line_id" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetLineID(v string) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.SetLineID(v) + return _u +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetNillableLineID(v *string) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + if v != nil { + _u.SetLineID(*v) + } + return _u +} + +// ClearLineID clears the value of the "line_id" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) ClearLineID() *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.ClearLineID() + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetNillableServicePeriodFrom(v *time.Time) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetNillableServicePeriodTo(v *time.Time) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetSortHint sets the "sort_hint" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetSortHint(v int) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.ResetSortHint() + _u.mutation.SetSortHint(v) + return _u +} + +// SetNillableSortHint sets the "sort_hint" field if the given value is not nil. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetNillableSortHint(v *int) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + if v != nil { + _u.SetSortHint(*v) + } + return _u +} + +// AddSortHint adds value to the "sort_hint" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) AddSortHint(v int) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.AddSortHint(v) + return _u +} + +// SetCorrectsRealizationID sets the "corrects_realization_id" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetCorrectsRealizationID(v string) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.SetCorrectsRealizationID(v) + return _u +} + +// SetNillableCorrectsRealizationID sets the "corrects_realization_id" field if the given value is not nil. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetNillableCorrectsRealizationID(v *string) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + if v != nil { + _u.SetCorrectsRealizationID(*v) + } + return _u +} + +// ClearCorrectsRealizationID clears the value of the "corrects_realization_id" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) ClearCorrectsRealizationID() *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.ClearCorrectsRealizationID() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetDeletedAt(v time.Time) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetNillableDeletedAt(v *time.Time) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) ClearDeletedAt() *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) ClearAnnotations() *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// AddCorrectionIDs adds the "corrections" edge to the ChargeFlatFeeRunCreditAllocations entity by IDs. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) AddCorrectionIDs(ids ...string) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.AddCorrectionIDs(ids...) + return _u +} + +// AddCorrections adds the "corrections" edges to the ChargeFlatFeeRunCreditAllocations entity. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) AddCorrections(v ...*ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddCorrectionIDs(ids...) +} + +// SetAllocationID sets the "allocation" edge to the ChargeFlatFeeRunCreditAllocations entity by ID. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetAllocationID(id string) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.SetAllocationID(id) + return _u +} + +// SetNillableAllocationID sets the "allocation" edge to the ChargeFlatFeeRunCreditAllocations entity by ID if the given value is not nil. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetNillableAllocationID(id *string) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + if id != nil { + _u = _u.SetAllocationID(*id) + } + return _u +} + +// SetAllocation sets the "allocation" edge to the ChargeFlatFeeRunCreditAllocations entity. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetAllocation(v *ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + return _u.SetAllocationID(v.ID) +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetBillingInvoiceLineID(id string) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.SetBillingInvoiceLineID(id) + return _u +} + +// SetNillableBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID if the given value is not nil. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetNillableBillingInvoiceLineID(id *string) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + if id != nil { + _u = _u.SetBillingInvoiceLineID(*id) + } + return _u +} + +// SetBillingInvoiceLine sets the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SetBillingInvoiceLine(v *BillingInvoiceLine) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + return _u.SetBillingInvoiceLineID(v.ID) +} + +// Mutation returns the ChargeFlatFeeRunCreditAllocationsMutation object of the builder. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) Mutation() *ChargeFlatFeeRunCreditAllocationsMutation { + return _u.mutation +} + +// ClearCorrections clears all "corrections" edges to the ChargeFlatFeeRunCreditAllocations entity. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) ClearCorrections() *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.ClearCorrections() + return _u +} + +// RemoveCorrectionIDs removes the "corrections" edge to ChargeFlatFeeRunCreditAllocations entities by IDs. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) RemoveCorrectionIDs(ids ...string) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.RemoveCorrectionIDs(ids...) + return _u +} + +// RemoveCorrections removes "corrections" edges to ChargeFlatFeeRunCreditAllocations entities. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) RemoveCorrections(v ...*ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveCorrectionIDs(ids...) +} + +// ClearAllocation clears the "allocation" edge to the ChargeFlatFeeRunCreditAllocations entity. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) ClearAllocation() *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.ClearAllocation() + return _u +} + +// ClearBillingInvoiceLine clears the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) ClearBillingInvoiceLine() *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.mutation.ClearBillingInvoiceLine() + return _u +} + +// Where appends a list predicates to the ChargeFlatFeeRunCreditAllocationsUpdate builder. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) Where(ps ...predicate.ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _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 *ChargeFlatFeeRunCreditAllocationsUpdateOne) Select(field string, fields ...string) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ChargeFlatFeeRunCreditAllocations entity. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) Save(ctx context.Context) (*ChargeFlatFeeRunCreditAllocations, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) SaveX(ctx context.Context) *ChargeFlatFeeRunCreditAllocations { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) 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 *ChargeFlatFeeRunCreditAllocationsUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeflatfeeruncreditallocations.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) check() error { + if v, ok := _u.mutation.LineID(); ok { + if err := chargeflatfeeruncreditallocations.LineIDValidator(v); err != nil { + return &ValidationError{Name: "line_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunCreditAllocations.line_id": %w`, err)} + } + } + if v, ok := _u.mutation.CorrectsRealizationID(); ok { + if err := chargeflatfeeruncreditallocations.CorrectsRealizationIDValidator(v); err != nil { + return &ValidationError{Name: "corrects_realization_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunCreditAllocations.corrects_realization_id": %w`, err)} + } + } + if _u.mutation.RunCleared() && len(_u.mutation.RunIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeFlatFeeRunCreditAllocations.run"`) + } + return nil +} + +func (_u *ChargeFlatFeeRunCreditAllocationsUpdateOne) sqlSave(ctx context.Context) (_node *ChargeFlatFeeRunCreditAllocations, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeflatfeeruncreditallocations.Table, chargeflatfeeruncreditallocations.Columns, sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "ChargeFlatFeeRunCreditAllocations.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, chargeflatfeeruncreditallocations.FieldID) + for _, f := range fields { + if !chargeflatfeeruncreditallocations.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != chargeflatfeeruncreditallocations.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.Amount(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.SortHint(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldSortHint, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedSortHint(); ok { + _spec.AddField(chargeflatfeeruncreditallocations.FieldSortHint, field.TypeInt, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeflatfeeruncreditallocations.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargeflatfeeruncreditallocations.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargeflatfeeruncreditallocations.FieldAnnotations, field.TypeJSON) + } + if _u.mutation.CorrectionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: chargeflatfeeruncreditallocations.CorrectionsTable, + Columns: []string{chargeflatfeeruncreditallocations.CorrectionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedCorrectionsIDs(); len(nodes) > 0 && !_u.mutation.CorrectionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: chargeflatfeeruncreditallocations.CorrectionsTable, + Columns: []string{chargeflatfeeruncreditallocations.CorrectionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.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.CorrectionsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: chargeflatfeeruncreditallocations.CorrectionsTable, + Columns: []string{chargeflatfeeruncreditallocations.CorrectionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.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.AllocationCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: chargeflatfeeruncreditallocations.AllocationTable, + Columns: []string{chargeflatfeeruncreditallocations.AllocationColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.AllocationIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: chargeflatfeeruncreditallocations.AllocationTable, + Columns: []string{chargeflatfeeruncreditallocations.AllocationColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeeruncreditallocations.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.BillingInvoiceLineCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfeeruncreditallocations.BillingInvoiceLineTable, + Columns: []string{chargeflatfeeruncreditallocations.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingInvoiceLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfeeruncreditallocations.BillingInvoiceLineTable, + Columns: []string{chargeflatfeeruncreditallocations.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &ChargeFlatFeeRunCreditAllocations{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{chargeflatfeeruncreditallocations.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/ent/db/chargeflatfeerundetailedline.go b/ent/db/chargeflatfeerundetailedline.go new file mode 100644 index 0000000000000000000000000000000000000000..34294356c4a40ca4d04f52a46f609b9bbc719464 --- /dev/null +++ b/ent/db/chargeflatfeerundetailedline.go @@ -0,0 +1,476 @@ +// 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/models/creditsapplied" + "github.com/openmeterio/openmeter/openmeter/billing/models/stddetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerundetailedline" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeFlatFeeRunDetailedLine is the model entity for the ChargeFlatFeeRunDetailedLine schema. +type ChargeFlatFeeRunDetailedLine struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // Currency holds the value of the "currency" field. + Currency currencyx.Code `json:"currency,omitempty"` + // ServicePeriodStart holds the value of the "service_period_start" field. + ServicePeriodStart time.Time `json:"service_period_start,omitempty"` + // ServicePeriodEnd holds the value of the "service_period_end" field. + ServicePeriodEnd time.Time `json:"service_period_end,omitempty"` + // Quantity holds the value of the "quantity" field. + Quantity alpacadecimal.Decimal `json:"quantity,omitempty"` + // InvoicingAppExternalID holds the value of the "invoicing_app_external_id" field. + InvoicingAppExternalID *string `json:"invoicing_app_external_id,omitempty"` + // ChildUniqueReferenceID holds the value of the "child_unique_reference_id" field. + ChildUniqueReferenceID string `json:"child_unique_reference_id,omitempty"` + // PerUnitAmount holds the value of the "per_unit_amount" field. + PerUnitAmount alpacadecimal.Decimal `json:"per_unit_amount,omitempty"` + // Category holds the value of the "category" field. + Category stddetailedline.Category `json:"category,omitempty"` + // PaymentTerm holds the value of the "payment_term" field. + PaymentTerm productcatalog.PaymentTermType `json:"payment_term,omitempty"` + // Index holds the value of the "index" field. + Index *int `json:"index,omitempty"` + // CreditsApplied holds the value of the "credits_applied" field. + CreditsApplied *creditsapplied.CreditsApplied `json:"credits_applied,omitempty"` + // Annotations holds the value of the "annotations" field. + // + // Deprecated: Field "annotations" was marked as deprecated in the schema. + Annotations models.Annotations `json:"annotations,omitempty"` + // Namespace holds the value of the "namespace" field. + Namespace string `json:"namespace,omitempty"` + // Metadata holds the value of the "metadata" field. + // + // Deprecated: Field "metadata" was marked as deprecated in the schema. + Metadata map[string]string `json:"metadata,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"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Description holds the value of the "description" field. + Description *string `json:"description,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"` + // PricerReferenceID holds the value of the "pricer_reference_id" field. + PricerReferenceID string `json:"pricer_reference_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ChargeFlatFeeRunDetailedLineQuery when eager-loading is set. + Edges ChargeFlatFeeRunDetailedLineEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ChargeFlatFeeRunDetailedLineEdges holds the relations/edges for other nodes in the graph. +type ChargeFlatFeeRunDetailedLineEdges struct { + // Run holds the value of the run edge. + Run *ChargeFlatFeeRun `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 ChargeFlatFeeRunDetailedLineEdges) RunOrErr() (*ChargeFlatFeeRun, error) { + if e.Run != nil { + return e.Run, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: chargeflatfeerun.Label} + } + return nil, &NotLoadedError{edge: "run"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ChargeFlatFeeRunDetailedLine) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case chargeflatfeerundetailedline.FieldCreditsApplied, chargeflatfeerundetailedline.FieldAnnotations, chargeflatfeerundetailedline.FieldMetadata: + values[i] = new([]byte) + case chargeflatfeerundetailedline.FieldQuantity, chargeflatfeerundetailedline.FieldPerUnitAmount, chargeflatfeerundetailedline.FieldAmount, chargeflatfeerundetailedline.FieldTaxesTotal, chargeflatfeerundetailedline.FieldTaxesInclusiveTotal, chargeflatfeerundetailedline.FieldTaxesExclusiveTotal, chargeflatfeerundetailedline.FieldChargesTotal, chargeflatfeerundetailedline.FieldDiscountsTotal, chargeflatfeerundetailedline.FieldCreditsTotal, chargeflatfeerundetailedline.FieldTotal: + values[i] = new(alpacadecimal.Decimal) + case chargeflatfeerundetailedline.FieldIndex: + values[i] = new(sql.NullInt64) + case chargeflatfeerundetailedline.FieldID, chargeflatfeerundetailedline.FieldCurrency, chargeflatfeerundetailedline.FieldInvoicingAppExternalID, chargeflatfeerundetailedline.FieldChildUniqueReferenceID, chargeflatfeerundetailedline.FieldCategory, chargeflatfeerundetailedline.FieldPaymentTerm, chargeflatfeerundetailedline.FieldNamespace, chargeflatfeerundetailedline.FieldName, chargeflatfeerundetailedline.FieldDescription, chargeflatfeerundetailedline.FieldRunID, chargeflatfeerundetailedline.FieldPricerReferenceID: + values[i] = new(sql.NullString) + case chargeflatfeerundetailedline.FieldServicePeriodStart, chargeflatfeerundetailedline.FieldServicePeriodEnd, chargeflatfeerundetailedline.FieldCreatedAt, chargeflatfeerundetailedline.FieldUpdatedAt, chargeflatfeerundetailedline.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 ChargeFlatFeeRunDetailedLine fields. +func (_m *ChargeFlatFeeRunDetailedLine) 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 chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.FieldCurrency: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field currency", values[i]) + } else if value.Valid { + _m.Currency = currencyx.Code(value.String) + } + case chargeflatfeerundetailedline.FieldServicePeriodStart: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field service_period_start", values[i]) + } else if value.Valid { + _m.ServicePeriodStart = value.Time + } + case chargeflatfeerundetailedline.FieldServicePeriodEnd: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field service_period_end", values[i]) + } else if value.Valid { + _m.ServicePeriodEnd = value.Time + } + case chargeflatfeerundetailedline.FieldQuantity: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field quantity", values[i]) + } else if value != nil { + _m.Quantity = *value + } + case chargeflatfeerundetailedline.FieldInvoicingAppExternalID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field invoicing_app_external_id", values[i]) + } else if value.Valid { + _m.InvoicingAppExternalID = new(string) + *_m.InvoicingAppExternalID = value.String + } + case chargeflatfeerundetailedline.FieldChildUniqueReferenceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field child_unique_reference_id", values[i]) + } else if value.Valid { + _m.ChildUniqueReferenceID = value.String + } + case chargeflatfeerundetailedline.FieldPerUnitAmount: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field per_unit_amount", values[i]) + } else if value != nil { + _m.PerUnitAmount = *value + } + case chargeflatfeerundetailedline.FieldCategory: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field category", values[i]) + } else if value.Valid { + _m.Category = stddetailedline.Category(value.String) + } + case chargeflatfeerundetailedline.FieldPaymentTerm: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field payment_term", values[i]) + } else if value.Valid { + _m.PaymentTerm = productcatalog.PaymentTermType(value.String) + } + case chargeflatfeerundetailedline.FieldIndex: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field index", values[i]) + } else if value.Valid { + _m.Index = new(int) + *_m.Index = int(value.Int64) + } + case chargeflatfeerundetailedline.FieldCreditsApplied: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field credits_applied", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.CreditsApplied); err != nil { + return fmt.Errorf("unmarshal field credits_applied: %w", err) + } + } + case chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.FieldMetadata: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field metadata", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Metadata); err != nil { + return fmt.Errorf("unmarshal field metadata: %w", err) + } + } + case chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case chargeflatfeerundetailedline.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + _m.Description = new(string) + *_m.Description = value.String + } + case chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.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 + } + case chargeflatfeerundetailedline.FieldPricerReferenceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field pricer_reference_id", values[i]) + } else if value.Valid { + _m.PricerReferenceID = 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 ChargeFlatFeeRunDetailedLine. +// This includes values selected through modifiers, order, etc. +func (_m *ChargeFlatFeeRunDetailedLine) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryRun queries the "run" edge of the ChargeFlatFeeRunDetailedLine entity. +func (_m *ChargeFlatFeeRunDetailedLine) QueryRun() *ChargeFlatFeeRunQuery { + return NewChargeFlatFeeRunDetailedLineClient(_m.config).QueryRun(_m) +} + +// Update returns a builder for updating this ChargeFlatFeeRunDetailedLine. +// Note that you need to call ChargeFlatFeeRunDetailedLine.Unwrap() before calling this method if this ChargeFlatFeeRunDetailedLine +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ChargeFlatFeeRunDetailedLine) Update() *ChargeFlatFeeRunDetailedLineUpdateOne { + return NewChargeFlatFeeRunDetailedLineClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLine) Unwrap() *ChargeFlatFeeRunDetailedLine { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: ChargeFlatFeeRunDetailedLine is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ChargeFlatFeeRunDetailedLine) String() string { + var builder strings.Builder + builder.WriteString("ChargeFlatFeeRunDetailedLine(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("currency=") + builder.WriteString(fmt.Sprintf("%v", _m.Currency)) + builder.WriteString(", ") + builder.WriteString("service_period_start=") + builder.WriteString(_m.ServicePeriodStart.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("service_period_end=") + builder.WriteString(_m.ServicePeriodEnd.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("quantity=") + builder.WriteString(fmt.Sprintf("%v", _m.Quantity)) + builder.WriteString(", ") + if v := _m.InvoicingAppExternalID; v != nil { + builder.WriteString("invoicing_app_external_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("child_unique_reference_id=") + builder.WriteString(_m.ChildUniqueReferenceID) + builder.WriteString(", ") + builder.WriteString("per_unit_amount=") + builder.WriteString(fmt.Sprintf("%v", _m.PerUnitAmount)) + builder.WriteString(", ") + builder.WriteString("category=") + builder.WriteString(fmt.Sprintf("%v", _m.Category)) + builder.WriteString(", ") + builder.WriteString("payment_term=") + builder.WriteString(fmt.Sprintf("%v", _m.PaymentTerm)) + builder.WriteString(", ") + if v := _m.Index; v != nil { + builder.WriteString("index=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + builder.WriteString("credits_applied=") + builder.WriteString(fmt.Sprintf("%v", _m.CreditsApplied)) + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + builder.WriteString(", ") + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("metadata=") + builder.WriteString(fmt.Sprintf("%v", _m.Metadata)) + 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("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + if v := _m.Description; v != nil { + builder.WriteString("description=") + builder.WriteString(*v) + } + 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.WriteString(", ") + builder.WriteString("pricer_reference_id=") + builder.WriteString(_m.PricerReferenceID) + builder.WriteByte(')') + return builder.String() +} + +// ChargeFlatFeeRunDetailedLines is a parsable slice of ChargeFlatFeeRunDetailedLine. +type ChargeFlatFeeRunDetailedLines []*ChargeFlatFeeRunDetailedLine diff --git a/ent/db/chargeflatfeerundetailedline/chargeflatfeerundetailedline.go b/ent/db/chargeflatfeerundetailedline/chargeflatfeerundetailedline.go new file mode 100644 index 0000000000000000000000000000000000000000..34668b791c9605e8976a3c9a3bd604e16dbf1cef --- /dev/null +++ b/ent/db/chargeflatfeerundetailedline/chargeflatfeerundetailedline.go @@ -0,0 +1,331 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeflatfeerundetailedline + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/billing/models/stddetailedline" + "github.com/openmeterio/openmeter/openmeter/productcatalog" +) + +const ( + // Label holds the string label denoting the chargeflatfeerundetailedline type in the database. + Label = "charge_flat_fee_run_detailed_line" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldCurrency holds the string denoting the currency field in the database. + FieldCurrency = "currency" + // FieldServicePeriodStart holds the string denoting the service_period_start field in the database. + FieldServicePeriodStart = "service_period_start" + // FieldServicePeriodEnd holds the string denoting the service_period_end field in the database. + FieldServicePeriodEnd = "service_period_end" + // FieldQuantity holds the string denoting the quantity field in the database. + FieldQuantity = "quantity" + // FieldInvoicingAppExternalID holds the string denoting the invoicing_app_external_id field in the database. + FieldInvoicingAppExternalID = "invoicing_app_external_id" + // FieldChildUniqueReferenceID holds the string denoting the child_unique_reference_id field in the database. + FieldChildUniqueReferenceID = "child_unique_reference_id" + // FieldPerUnitAmount holds the string denoting the per_unit_amount field in the database. + FieldPerUnitAmount = "per_unit_amount" + // FieldCategory holds the string denoting the category field in the database. + FieldCategory = "category" + // FieldPaymentTerm holds the string denoting the payment_term field in the database. + FieldPaymentTerm = "payment_term" + // FieldIndex holds the string denoting the index field in the database. + FieldIndex = "index" + // FieldCreditsApplied holds the string denoting the credits_applied field in the database. + FieldCreditsApplied = "credits_applied" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // FieldNamespace holds the string denoting the namespace field in the database. + FieldNamespace = "namespace" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // 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" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // 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" + // FieldPricerReferenceID holds the string denoting the pricer_reference_id field in the database. + FieldPricerReferenceID = "pricer_reference_id" + // EdgeRun holds the string denoting the run edge name in mutations. + EdgeRun = "run" + // Table holds the table name of the chargeflatfeerundetailedline in the database. + Table = "charge_flat_fee_run_detailed_lines" + // RunTable is the table that holds the run relation/edge. + RunTable = "charge_flat_fee_run_detailed_lines" + // RunInverseTable is the table name for the ChargeFlatFeeRun entity. + // It exists in this package in order to avoid circular dependency with the "chargeflatfeerun" package. + RunInverseTable = "charge_flat_fee_runs" + // RunColumn is the table column denoting the run relation/edge. + RunColumn = "run_id" +) + +// Columns holds all SQL columns for chargeflatfeerundetailedline fields. +var Columns = []string{ + FieldID, + FieldCurrency, + FieldServicePeriodStart, + FieldServicePeriodEnd, + FieldQuantity, + FieldInvoicingAppExternalID, + FieldChildUniqueReferenceID, + FieldPerUnitAmount, + FieldCategory, + FieldPaymentTerm, + FieldIndex, + FieldCreditsApplied, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldName, + FieldDescription, + FieldAmount, + FieldTaxesTotal, + FieldTaxesInclusiveTotal, + FieldTaxesExclusiveTotal, + FieldChargesTotal, + FieldDiscountsTotal, + FieldCreditsTotal, + FieldTotal, + FieldRunID, + FieldPricerReferenceID, +} + +// 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 + } + } + for _, f := range [...]string{FieldAnnotations, FieldMetadata} { + if column == f { + return true + } + } + return false +} + +var ( + // CurrencyValidator is a validator for the "currency" field. It is called by the builders before save. + CurrencyValidator func(string) error + // ChildUniqueReferenceIDValidator is a validator for the "child_unique_reference_id" field. It is called by the builders before save. + ChildUniqueReferenceIDValidator 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 + // PricerReferenceIDValidator is a validator for the "pricer_reference_id" field. It is called by the builders before save. + PricerReferenceIDValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +const DefaultCategory stddetailedline.Category = "regular" + +// CategoryValidator is a validator for the "category" field enum values. It is called by the builders before save. +func CategoryValidator(c stddetailedline.Category) error { + switch c { + case "regular", "commitment": + return nil + default: + return fmt.Errorf("chargeflatfeerundetailedline: invalid enum value for category field: %q", c) + } +} + +const DefaultPaymentTerm productcatalog.PaymentTermType = "in_advance" + +// PaymentTermValidator is a validator for the "payment_term" field enum values. It is called by the builders before save. +func PaymentTermValidator(pt productcatalog.PaymentTermType) error { + switch pt { + case "in_advance", "in_arrears": + return nil + default: + return fmt.Errorf("chargeflatfeerundetailedline: invalid enum value for payment_term field: %q", pt) + } +} + +// OrderOption defines the ordering options for the ChargeFlatFeeRunDetailedLine 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() +} + +// ByCurrency orders the results by the currency field. +func ByCurrency(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCurrency, opts...).ToFunc() +} + +// ByServicePeriodStart orders the results by the service_period_start field. +func ByServicePeriodStart(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldServicePeriodStart, opts...).ToFunc() +} + +// ByServicePeriodEnd orders the results by the service_period_end field. +func ByServicePeriodEnd(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldServicePeriodEnd, opts...).ToFunc() +} + +// ByQuantity orders the results by the quantity field. +func ByQuantity(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldQuantity, opts...).ToFunc() +} + +// ByInvoicingAppExternalID orders the results by the invoicing_app_external_id field. +func ByInvoicingAppExternalID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoicingAppExternalID, opts...).ToFunc() +} + +// ByChildUniqueReferenceID orders the results by the child_unique_reference_id field. +func ByChildUniqueReferenceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChildUniqueReferenceID, opts...).ToFunc() +} + +// ByPerUnitAmount orders the results by the per_unit_amount field. +func ByPerUnitAmount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPerUnitAmount, opts...).ToFunc() +} + +// ByCategory orders the results by the category field. +func ByCategory(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCategory, opts...).ToFunc() +} + +// ByPaymentTerm orders the results by the payment_term field. +func ByPaymentTerm(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPaymentTerm, opts...).ToFunc() +} + +// ByIndex orders the results by the index field. +func ByIndex(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIndex, 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() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, 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() +} + +// ByPricerReferenceID orders the results by the pricer_reference_id field. +func ByPricerReferenceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPricerReferenceID, 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/ent/db/chargeflatfeerundetailedline/where.go b/ent/db/chargeflatfeerundetailedline/where.go new file mode 100644 index 0000000000000000000000000000000000000000..25d01ec65f98f3019b7d6d704c1e68a1985e0599 --- /dev/null +++ b/ent/db/chargeflatfeerundetailedline/where.go @@ -0,0 +1,1538 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeflatfeerundetailedline + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/billing/models/stddetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldContainsFold(FieldID, id)) +} + +// Currency applies equality check predicate on the "currency" field. It's identical to CurrencyEQ. +func Currency(v currencyx.Code) predicate.ChargeFlatFeeRunDetailedLine { + vc := string(v) + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldCurrency, vc)) +} + +// ServicePeriodStart applies equality check predicate on the "service_period_start" field. It's identical to ServicePeriodStartEQ. +func ServicePeriodStart(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldServicePeriodStart, v)) +} + +// ServicePeriodEnd applies equality check predicate on the "service_period_end" field. It's identical to ServicePeriodEndEQ. +func ServicePeriodEnd(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldServicePeriodEnd, v)) +} + +// Quantity applies equality check predicate on the "quantity" field. It's identical to QuantityEQ. +func Quantity(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldQuantity, v)) +} + +// InvoicingAppExternalID applies equality check predicate on the "invoicing_app_external_id" field. It's identical to InvoicingAppExternalIDEQ. +func InvoicingAppExternalID(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldInvoicingAppExternalID, v)) +} + +// ChildUniqueReferenceID applies equality check predicate on the "child_unique_reference_id" field. It's identical to ChildUniqueReferenceIDEQ. +func ChildUniqueReferenceID(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldChildUniqueReferenceID, v)) +} + +// PerUnitAmount applies equality check predicate on the "per_unit_amount" field. It's identical to PerUnitAmountEQ. +func PerUnitAmount(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldPerUnitAmount, v)) +} + +// Index applies equality check predicate on the "index" field. It's identical to IndexEQ. +func Index(v int) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldIndex, v)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(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.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(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.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(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.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldName, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldDescription, v)) +} + +// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ. +func Amount(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(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.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(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.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(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.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(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.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(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.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(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.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldCreditsTotal, v)) +} + +// Total applies equality check predicate on the "total" field. It's identical to TotalEQ. +func Total(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldTotal, v)) +} + +// RunID applies equality check predicate on the "run_id" field. It's identical to RunIDEQ. +func RunID(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldRunID, v)) +} + +// PricerReferenceID applies equality check predicate on the "pricer_reference_id" field. It's identical to PricerReferenceIDEQ. +func PricerReferenceID(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldPricerReferenceID, v)) +} + +// CurrencyEQ applies the EQ predicate on the "currency" field. +func CurrencyEQ(v currencyx.Code) predicate.ChargeFlatFeeRunDetailedLine { + vc := string(v) + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldCurrency, vc)) +} + +// CurrencyNEQ applies the NEQ predicate on the "currency" field. +func CurrencyNEQ(v currencyx.Code) predicate.ChargeFlatFeeRunDetailedLine { + vc := string(v) + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldCurrency, vc)) +} + +// CurrencyIn applies the In predicate on the "currency" field. +func CurrencyIn(vs ...currencyx.Code) predicate.ChargeFlatFeeRunDetailedLine { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldCurrency, v...)) +} + +// CurrencyNotIn applies the NotIn predicate on the "currency" field. +func CurrencyNotIn(vs ...currencyx.Code) predicate.ChargeFlatFeeRunDetailedLine { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldCurrency, v...)) +} + +// CurrencyGT applies the GT predicate on the "currency" field. +func CurrencyGT(v currencyx.Code) predicate.ChargeFlatFeeRunDetailedLine { + vc := string(v) + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldCurrency, vc)) +} + +// CurrencyGTE applies the GTE predicate on the "currency" field. +func CurrencyGTE(v currencyx.Code) predicate.ChargeFlatFeeRunDetailedLine { + vc := string(v) + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldCurrency, vc)) +} + +// CurrencyLT applies the LT predicate on the "currency" field. +func CurrencyLT(v currencyx.Code) predicate.ChargeFlatFeeRunDetailedLine { + vc := string(v) + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldCurrency, vc)) +} + +// CurrencyLTE applies the LTE predicate on the "currency" field. +func CurrencyLTE(v currencyx.Code) predicate.ChargeFlatFeeRunDetailedLine { + vc := string(v) + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldCurrency, vc)) +} + +// CurrencyContains applies the Contains predicate on the "currency" field. +func CurrencyContains(v currencyx.Code) predicate.ChargeFlatFeeRunDetailedLine { + vc := string(v) + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldContains(FieldCurrency, vc)) +} + +// CurrencyHasPrefix applies the HasPrefix predicate on the "currency" field. +func CurrencyHasPrefix(v currencyx.Code) predicate.ChargeFlatFeeRunDetailedLine { + vc := string(v) + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldHasPrefix(FieldCurrency, vc)) +} + +// CurrencyHasSuffix applies the HasSuffix predicate on the "currency" field. +func CurrencyHasSuffix(v currencyx.Code) predicate.ChargeFlatFeeRunDetailedLine { + vc := string(v) + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldHasSuffix(FieldCurrency, vc)) +} + +// CurrencyEqualFold applies the EqualFold predicate on the "currency" field. +func CurrencyEqualFold(v currencyx.Code) predicate.ChargeFlatFeeRunDetailedLine { + vc := string(v) + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEqualFold(FieldCurrency, vc)) +} + +// CurrencyContainsFold applies the ContainsFold predicate on the "currency" field. +func CurrencyContainsFold(v currencyx.Code) predicate.ChargeFlatFeeRunDetailedLine { + vc := string(v) + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldContainsFold(FieldCurrency, vc)) +} + +// ServicePeriodStartEQ applies the EQ predicate on the "service_period_start" field. +func ServicePeriodStartEQ(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldServicePeriodStart, v)) +} + +// ServicePeriodStartNEQ applies the NEQ predicate on the "service_period_start" field. +func ServicePeriodStartNEQ(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldServicePeriodStart, v)) +} + +// ServicePeriodStartIn applies the In predicate on the "service_period_start" field. +func ServicePeriodStartIn(vs ...time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldServicePeriodStart, vs...)) +} + +// ServicePeriodStartNotIn applies the NotIn predicate on the "service_period_start" field. +func ServicePeriodStartNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldServicePeriodStart, vs...)) +} + +// ServicePeriodStartGT applies the GT predicate on the "service_period_start" field. +func ServicePeriodStartGT(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldServicePeriodStart, v)) +} + +// ServicePeriodStartGTE applies the GTE predicate on the "service_period_start" field. +func ServicePeriodStartGTE(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldServicePeriodStart, v)) +} + +// ServicePeriodStartLT applies the LT predicate on the "service_period_start" field. +func ServicePeriodStartLT(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldServicePeriodStart, v)) +} + +// ServicePeriodStartLTE applies the LTE predicate on the "service_period_start" field. +func ServicePeriodStartLTE(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldServicePeriodStart, v)) +} + +// ServicePeriodEndEQ applies the EQ predicate on the "service_period_end" field. +func ServicePeriodEndEQ(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldServicePeriodEnd, v)) +} + +// ServicePeriodEndNEQ applies the NEQ predicate on the "service_period_end" field. +func ServicePeriodEndNEQ(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldServicePeriodEnd, v)) +} + +// ServicePeriodEndIn applies the In predicate on the "service_period_end" field. +func ServicePeriodEndIn(vs ...time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldServicePeriodEnd, vs...)) +} + +// ServicePeriodEndNotIn applies the NotIn predicate on the "service_period_end" field. +func ServicePeriodEndNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldServicePeriodEnd, vs...)) +} + +// ServicePeriodEndGT applies the GT predicate on the "service_period_end" field. +func ServicePeriodEndGT(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldServicePeriodEnd, v)) +} + +// ServicePeriodEndGTE applies the GTE predicate on the "service_period_end" field. +func ServicePeriodEndGTE(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldServicePeriodEnd, v)) +} + +// ServicePeriodEndLT applies the LT predicate on the "service_period_end" field. +func ServicePeriodEndLT(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldServicePeriodEnd, v)) +} + +// ServicePeriodEndLTE applies the LTE predicate on the "service_period_end" field. +func ServicePeriodEndLTE(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldServicePeriodEnd, v)) +} + +// QuantityEQ applies the EQ predicate on the "quantity" field. +func QuantityEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldQuantity, v)) +} + +// QuantityNEQ applies the NEQ predicate on the "quantity" field. +func QuantityNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldQuantity, v)) +} + +// QuantityIn applies the In predicate on the "quantity" field. +func QuantityIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldQuantity, vs...)) +} + +// QuantityNotIn applies the NotIn predicate on the "quantity" field. +func QuantityNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldQuantity, vs...)) +} + +// QuantityGT applies the GT predicate on the "quantity" field. +func QuantityGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldQuantity, v)) +} + +// QuantityGTE applies the GTE predicate on the "quantity" field. +func QuantityGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldQuantity, v)) +} + +// QuantityLT applies the LT predicate on the "quantity" field. +func QuantityLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldQuantity, v)) +} + +// QuantityLTE applies the LTE predicate on the "quantity" field. +func QuantityLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldQuantity, v)) +} + +// InvoicingAppExternalIDEQ applies the EQ predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDEQ(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDNEQ applies the NEQ predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDNEQ(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDIn applies the In predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDIn(vs ...string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldInvoicingAppExternalID, vs...)) +} + +// InvoicingAppExternalIDNotIn applies the NotIn predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDNotIn(vs ...string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldInvoicingAppExternalID, vs...)) +} + +// InvoicingAppExternalIDGT applies the GT predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDGT(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDGTE applies the GTE predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDGTE(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDLT applies the LT predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDLT(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDLTE applies the LTE predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDLTE(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDContains applies the Contains predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDContains(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldContains(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDHasPrefix applies the HasPrefix predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDHasPrefix(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldHasPrefix(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDHasSuffix applies the HasSuffix predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDHasSuffix(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldHasSuffix(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDIsNil applies the IsNil predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDIsNil() predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIsNull(FieldInvoicingAppExternalID)) +} + +// InvoicingAppExternalIDNotNil applies the NotNil predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDNotNil() predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotNull(FieldInvoicingAppExternalID)) +} + +// InvoicingAppExternalIDEqualFold applies the EqualFold predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDEqualFold(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEqualFold(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDContainsFold applies the ContainsFold predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDContainsFold(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldContainsFold(FieldInvoicingAppExternalID, v)) +} + +// ChildUniqueReferenceIDEQ applies the EQ predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDEQ(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDNEQ applies the NEQ predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDNEQ(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDIn applies the In predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDIn(vs ...string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldChildUniqueReferenceID, vs...)) +} + +// ChildUniqueReferenceIDNotIn applies the NotIn predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDNotIn(vs ...string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldChildUniqueReferenceID, vs...)) +} + +// ChildUniqueReferenceIDGT applies the GT predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDGT(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDGTE applies the GTE predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDGTE(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDLT applies the LT predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDLT(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDLTE applies the LTE predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDLTE(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDContains applies the Contains predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDContains(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldContains(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDHasPrefix applies the HasPrefix predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDHasPrefix(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldHasPrefix(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDHasSuffix applies the HasSuffix predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDHasSuffix(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldHasSuffix(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDEqualFold applies the EqualFold predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDEqualFold(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEqualFold(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDContainsFold applies the ContainsFold predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDContainsFold(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldContainsFold(FieldChildUniqueReferenceID, v)) +} + +// PerUnitAmountEQ applies the EQ predicate on the "per_unit_amount" field. +func PerUnitAmountEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldPerUnitAmount, v)) +} + +// PerUnitAmountNEQ applies the NEQ predicate on the "per_unit_amount" field. +func PerUnitAmountNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldPerUnitAmount, v)) +} + +// PerUnitAmountIn applies the In predicate on the "per_unit_amount" field. +func PerUnitAmountIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldPerUnitAmount, vs...)) +} + +// PerUnitAmountNotIn applies the NotIn predicate on the "per_unit_amount" field. +func PerUnitAmountNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldPerUnitAmount, vs...)) +} + +// PerUnitAmountGT applies the GT predicate on the "per_unit_amount" field. +func PerUnitAmountGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldPerUnitAmount, v)) +} + +// PerUnitAmountGTE applies the GTE predicate on the "per_unit_amount" field. +func PerUnitAmountGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldPerUnitAmount, v)) +} + +// PerUnitAmountLT applies the LT predicate on the "per_unit_amount" field. +func PerUnitAmountLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldPerUnitAmount, v)) +} + +// PerUnitAmountLTE applies the LTE predicate on the "per_unit_amount" field. +func PerUnitAmountLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldPerUnitAmount, v)) +} + +// CategoryEQ applies the EQ predicate on the "category" field. +func CategoryEQ(v stddetailedline.Category) predicate.ChargeFlatFeeRunDetailedLine { + vc := v + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldCategory, vc)) +} + +// CategoryNEQ applies the NEQ predicate on the "category" field. +func CategoryNEQ(v stddetailedline.Category) predicate.ChargeFlatFeeRunDetailedLine { + vc := v + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldCategory, vc)) +} + +// CategoryIn applies the In predicate on the "category" field. +func CategoryIn(vs ...stddetailedline.Category) predicate.ChargeFlatFeeRunDetailedLine { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldCategory, v...)) +} + +// CategoryNotIn applies the NotIn predicate on the "category" field. +func CategoryNotIn(vs ...stddetailedline.Category) predicate.ChargeFlatFeeRunDetailedLine { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldCategory, v...)) +} + +// PaymentTermEQ applies the EQ predicate on the "payment_term" field. +func PaymentTermEQ(v productcatalog.PaymentTermType) predicate.ChargeFlatFeeRunDetailedLine { + vc := v + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldPaymentTerm, vc)) +} + +// PaymentTermNEQ applies the NEQ predicate on the "payment_term" field. +func PaymentTermNEQ(v productcatalog.PaymentTermType) predicate.ChargeFlatFeeRunDetailedLine { + vc := v + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldPaymentTerm, vc)) +} + +// PaymentTermIn applies the In predicate on the "payment_term" field. +func PaymentTermIn(vs ...productcatalog.PaymentTermType) predicate.ChargeFlatFeeRunDetailedLine { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldPaymentTerm, v...)) +} + +// PaymentTermNotIn applies the NotIn predicate on the "payment_term" field. +func PaymentTermNotIn(vs ...productcatalog.PaymentTermType) predicate.ChargeFlatFeeRunDetailedLine { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldPaymentTerm, v...)) +} + +// IndexEQ applies the EQ predicate on the "index" field. +func IndexEQ(v int) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldIndex, v)) +} + +// IndexNEQ applies the NEQ predicate on the "index" field. +func IndexNEQ(v int) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldIndex, v)) +} + +// IndexIn applies the In predicate on the "index" field. +func IndexIn(vs ...int) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldIndex, vs...)) +} + +// IndexNotIn applies the NotIn predicate on the "index" field. +func IndexNotIn(vs ...int) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldIndex, vs...)) +} + +// IndexGT applies the GT predicate on the "index" field. +func IndexGT(v int) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldIndex, v)) +} + +// IndexGTE applies the GTE predicate on the "index" field. +func IndexGTE(v int) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldIndex, v)) +} + +// IndexLT applies the LT predicate on the "index" field. +func IndexLT(v int) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldIndex, v)) +} + +// IndexLTE applies the LTE predicate on the "index" field. +func IndexLTE(v int) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldIndex, v)) +} + +// IndexIsNil applies the IsNil predicate on the "index" field. +func IndexIsNil() predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIsNull(FieldIndex)) +} + +// IndexNotNil applies the NotNil predicate on the "index" field. +func IndexNotNil() predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotNull(FieldIndex)) +} + +// CreditsAppliedIsNil applies the IsNil predicate on the "credits_applied" field. +func CreditsAppliedIsNil() predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIsNull(FieldCreditsApplied)) +} + +// CreditsAppliedNotNil applies the NotNil predicate on the "credits_applied" field. +func CreditsAppliedNotNil() predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotNull(FieldCreditsApplied)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotNull(FieldAnnotations)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldContainsFold(FieldNamespace, v)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotNull(FieldMetadata)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotNull(FieldDeletedAt)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldContainsFold(FieldName, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldContainsFold(FieldDescription, v)) +} + +// AmountEQ applies the EQ predicate on the "amount" field. +func AmountEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldAmount, v)) +} + +// AmountNEQ applies the NEQ predicate on the "amount" field. +func AmountNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldAmount, v)) +} + +// AmountIn applies the In predicate on the "amount" field. +func AmountIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldAmount, vs...)) +} + +// AmountNotIn applies the NotIn predicate on the "amount" field. +func AmountNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldAmount, vs...)) +} + +// AmountGT applies the GT predicate on the "amount" field. +func AmountGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldAmount, v)) +} + +// AmountGTE applies the GTE predicate on the "amount" field. +func AmountGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldAmount, v)) +} + +// AmountLT applies the LT predicate on the "amount" field. +func AmountLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldAmount, v)) +} + +// AmountLTE applies the LTE predicate on the "amount" field. +func AmountLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldAmount, v)) +} + +// TaxesTotalEQ applies the EQ predicate on the "taxes_total" field. +func TaxesTotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldTaxesTotal, v)) +} + +// TaxesTotalNEQ applies the NEQ predicate on the "taxes_total" field. +func TaxesTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldTaxesTotal, v)) +} + +// TaxesTotalIn applies the In predicate on the "taxes_total" field. +func TaxesTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldTaxesTotal, vs...)) +} + +// TaxesTotalNotIn applies the NotIn predicate on the "taxes_total" field. +func TaxesTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldTaxesTotal, vs...)) +} + +// TaxesTotalGT applies the GT predicate on the "taxes_total" field. +func TaxesTotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldTaxesTotal, v)) +} + +// TaxesTotalGTE applies the GTE predicate on the "taxes_total" field. +func TaxesTotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldTaxesTotal, v)) +} + +// TaxesTotalLT applies the LT predicate on the "taxes_total" field. +func TaxesTotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldTaxesTotal, v)) +} + +// TaxesTotalLTE applies the LTE predicate on the "taxes_total" field. +func TaxesTotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldTaxesTotal, v)) +} + +// TaxesInclusiveTotalEQ applies the EQ predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalNEQ applies the NEQ predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalIn applies the In predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldTaxesInclusiveTotal, vs...)) +} + +// TaxesInclusiveTotalNotIn applies the NotIn predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldTaxesInclusiveTotal, vs...)) +} + +// TaxesInclusiveTotalGT applies the GT predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalGTE applies the GTE predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalLT applies the LT predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalLTE applies the LTE predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldTaxesInclusiveTotal, v)) +} + +// TaxesExclusiveTotalEQ applies the EQ predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalNEQ applies the NEQ predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalIn applies the In predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldTaxesExclusiveTotal, vs...)) +} + +// TaxesExclusiveTotalNotIn applies the NotIn predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldTaxesExclusiveTotal, vs...)) +} + +// TaxesExclusiveTotalGT applies the GT predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalGTE applies the GTE predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalLT applies the LT predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalLTE applies the LTE predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldTaxesExclusiveTotal, v)) +} + +// ChargesTotalEQ applies the EQ predicate on the "charges_total" field. +func ChargesTotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldChargesTotal, v)) +} + +// ChargesTotalNEQ applies the NEQ predicate on the "charges_total" field. +func ChargesTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldChargesTotal, v)) +} + +// ChargesTotalIn applies the In predicate on the "charges_total" field. +func ChargesTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldChargesTotal, vs...)) +} + +// ChargesTotalNotIn applies the NotIn predicate on the "charges_total" field. +func ChargesTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldChargesTotal, vs...)) +} + +// ChargesTotalGT applies the GT predicate on the "charges_total" field. +func ChargesTotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldChargesTotal, v)) +} + +// ChargesTotalGTE applies the GTE predicate on the "charges_total" field. +func ChargesTotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldChargesTotal, v)) +} + +// ChargesTotalLT applies the LT predicate on the "charges_total" field. +func ChargesTotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldChargesTotal, v)) +} + +// ChargesTotalLTE applies the LTE predicate on the "charges_total" field. +func ChargesTotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldChargesTotal, v)) +} + +// DiscountsTotalEQ applies the EQ predicate on the "discounts_total" field. +func DiscountsTotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldDiscountsTotal, v)) +} + +// DiscountsTotalNEQ applies the NEQ predicate on the "discounts_total" field. +func DiscountsTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldDiscountsTotal, v)) +} + +// DiscountsTotalIn applies the In predicate on the "discounts_total" field. +func DiscountsTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldDiscountsTotal, vs...)) +} + +// DiscountsTotalNotIn applies the NotIn predicate on the "discounts_total" field. +func DiscountsTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldDiscountsTotal, vs...)) +} + +// DiscountsTotalGT applies the GT predicate on the "discounts_total" field. +func DiscountsTotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldDiscountsTotal, v)) +} + +// DiscountsTotalGTE applies the GTE predicate on the "discounts_total" field. +func DiscountsTotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldDiscountsTotal, v)) +} + +// DiscountsTotalLT applies the LT predicate on the "discounts_total" field. +func DiscountsTotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldDiscountsTotal, v)) +} + +// DiscountsTotalLTE applies the LTE predicate on the "discounts_total" field. +func DiscountsTotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldDiscountsTotal, v)) +} + +// CreditsTotalEQ applies the EQ predicate on the "credits_total" field. +func CreditsTotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldCreditsTotal, v)) +} + +// CreditsTotalNEQ applies the NEQ predicate on the "credits_total" field. +func CreditsTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldCreditsTotal, v)) +} + +// CreditsTotalIn applies the In predicate on the "credits_total" field. +func CreditsTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldCreditsTotal, vs...)) +} + +// CreditsTotalNotIn applies the NotIn predicate on the "credits_total" field. +func CreditsTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldCreditsTotal, vs...)) +} + +// CreditsTotalGT applies the GT predicate on the "credits_total" field. +func CreditsTotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldCreditsTotal, v)) +} + +// CreditsTotalGTE applies the GTE predicate on the "credits_total" field. +func CreditsTotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldCreditsTotal, v)) +} + +// CreditsTotalLT applies the LT predicate on the "credits_total" field. +func CreditsTotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldCreditsTotal, v)) +} + +// CreditsTotalLTE applies the LTE predicate on the "credits_total" field. +func CreditsTotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldCreditsTotal, v)) +} + +// TotalEQ applies the EQ predicate on the "total" field. +func TotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldTotal, v)) +} + +// TotalNEQ applies the NEQ predicate on the "total" field. +func TotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldTotal, v)) +} + +// TotalIn applies the In predicate on the "total" field. +func TotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldTotal, vs...)) +} + +// TotalNotIn applies the NotIn predicate on the "total" field. +func TotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldTotal, vs...)) +} + +// TotalGT applies the GT predicate on the "total" field. +func TotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldTotal, v)) +} + +// TotalGTE applies the GTE predicate on the "total" field. +func TotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldTotal, v)) +} + +// TotalLT applies the LT predicate on the "total" field. +func TotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldTotal, v)) +} + +// TotalLTE applies the LTE predicate on the "total" field. +func TotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldTotal, v)) +} + +// RunIDEQ applies the EQ predicate on the "run_id" field. +func RunIDEQ(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldRunID, v)) +} + +// RunIDNEQ applies the NEQ predicate on the "run_id" field. +func RunIDNEQ(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldRunID, v)) +} + +// RunIDIn applies the In predicate on the "run_id" field. +func RunIDIn(vs ...string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldRunID, vs...)) +} + +// RunIDNotIn applies the NotIn predicate on the "run_id" field. +func RunIDNotIn(vs ...string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldRunID, vs...)) +} + +// RunIDGT applies the GT predicate on the "run_id" field. +func RunIDGT(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldRunID, v)) +} + +// RunIDGTE applies the GTE predicate on the "run_id" field. +func RunIDGTE(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldRunID, v)) +} + +// RunIDLT applies the LT predicate on the "run_id" field. +func RunIDLT(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldRunID, v)) +} + +// RunIDLTE applies the LTE predicate on the "run_id" field. +func RunIDLTE(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldRunID, v)) +} + +// RunIDContains applies the Contains predicate on the "run_id" field. +func RunIDContains(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldContains(FieldRunID, v)) +} + +// RunIDHasPrefix applies the HasPrefix predicate on the "run_id" field. +func RunIDHasPrefix(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldHasPrefix(FieldRunID, v)) +} + +// RunIDHasSuffix applies the HasSuffix predicate on the "run_id" field. +func RunIDHasSuffix(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldHasSuffix(FieldRunID, v)) +} + +// RunIDEqualFold applies the EqualFold predicate on the "run_id" field. +func RunIDEqualFold(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEqualFold(FieldRunID, v)) +} + +// RunIDContainsFold applies the ContainsFold predicate on the "run_id" field. +func RunIDContainsFold(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldContainsFold(FieldRunID, v)) +} + +// PricerReferenceIDEQ applies the EQ predicate on the "pricer_reference_id" field. +func PricerReferenceIDEQ(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEQ(FieldPricerReferenceID, v)) +} + +// PricerReferenceIDNEQ applies the NEQ predicate on the "pricer_reference_id" field. +func PricerReferenceIDNEQ(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNEQ(FieldPricerReferenceID, v)) +} + +// PricerReferenceIDIn applies the In predicate on the "pricer_reference_id" field. +func PricerReferenceIDIn(vs ...string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldIn(FieldPricerReferenceID, vs...)) +} + +// PricerReferenceIDNotIn applies the NotIn predicate on the "pricer_reference_id" field. +func PricerReferenceIDNotIn(vs ...string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldNotIn(FieldPricerReferenceID, vs...)) +} + +// PricerReferenceIDGT applies the GT predicate on the "pricer_reference_id" field. +func PricerReferenceIDGT(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGT(FieldPricerReferenceID, v)) +} + +// PricerReferenceIDGTE applies the GTE predicate on the "pricer_reference_id" field. +func PricerReferenceIDGTE(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldGTE(FieldPricerReferenceID, v)) +} + +// PricerReferenceIDLT applies the LT predicate on the "pricer_reference_id" field. +func PricerReferenceIDLT(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLT(FieldPricerReferenceID, v)) +} + +// PricerReferenceIDLTE applies the LTE predicate on the "pricer_reference_id" field. +func PricerReferenceIDLTE(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldLTE(FieldPricerReferenceID, v)) +} + +// PricerReferenceIDContains applies the Contains predicate on the "pricer_reference_id" field. +func PricerReferenceIDContains(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldContains(FieldPricerReferenceID, v)) +} + +// PricerReferenceIDHasPrefix applies the HasPrefix predicate on the "pricer_reference_id" field. +func PricerReferenceIDHasPrefix(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldHasPrefix(FieldPricerReferenceID, v)) +} + +// PricerReferenceIDHasSuffix applies the HasSuffix predicate on the "pricer_reference_id" field. +func PricerReferenceIDHasSuffix(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldHasSuffix(FieldPricerReferenceID, v)) +} + +// PricerReferenceIDEqualFold applies the EqualFold predicate on the "pricer_reference_id" field. +func PricerReferenceIDEqualFold(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldEqualFold(FieldPricerReferenceID, v)) +} + +// PricerReferenceIDContainsFold applies the ContainsFold predicate on the "pricer_reference_id" field. +func PricerReferenceIDContainsFold(v string) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.FieldContainsFold(FieldPricerReferenceID, v)) +} + +// HasRun applies the HasEdge predicate on the "run" edge. +func HasRun() predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(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.ChargeFlatFeeRun) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(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.ChargeFlatFeeRunDetailedLine) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ChargeFlatFeeRunDetailedLine) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ChargeFlatFeeRunDetailedLine) predicate.ChargeFlatFeeRunDetailedLine { + return predicate.ChargeFlatFeeRunDetailedLine(sql.NotPredicates(p)) +} diff --git a/ent/db/chargeflatfeerundetailedline_create.go b/ent/db/chargeflatfeerundetailedline_create.go new file mode 100644 index 0000000000000000000000000000000000000000..64c0cd9b19af894e0a0b3876493f2f955fad6f81 --- /dev/null +++ b/ent/db/chargeflatfeerundetailedline_create.go @@ -0,0 +1,2138 @@ +// 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/models/creditsapplied" + "github.com/openmeterio/openmeter/openmeter/billing/models/stddetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerundetailedline" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeFlatFeeRunDetailedLineCreate is the builder for creating a ChargeFlatFeeRunDetailedLine entity. +type ChargeFlatFeeRunDetailedLineCreate struct { + config + mutation *ChargeFlatFeeRunDetailedLineMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetCurrency sets the "currency" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetCurrency(v currencyx.Code) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetCurrency(v) + return _c +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetServicePeriodStart(v time.Time) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetServicePeriodStart(v) + return _c +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetServicePeriodEnd(v time.Time) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetServicePeriodEnd(v) + return _c +} + +// SetQuantity sets the "quantity" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetQuantity(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetQuantity(v) + return _c +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetInvoicingAppExternalID(v string) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetInvoicingAppExternalID(v) + return _c +} + +// SetNillableInvoicingAppExternalID sets the "invoicing_app_external_id" field if the given value is not nil. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetNillableInvoicingAppExternalID(v *string) *ChargeFlatFeeRunDetailedLineCreate { + if v != nil { + _c.SetInvoicingAppExternalID(*v) + } + return _c +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetChildUniqueReferenceID(v string) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetChildUniqueReferenceID(v) + return _c +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetPerUnitAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetPerUnitAmount(v) + return _c +} + +// SetCategory sets the "category" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetCategory(v stddetailedline.Category) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetCategory(v) + return _c +} + +// SetNillableCategory sets the "category" field if the given value is not nil. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetNillableCategory(v *stddetailedline.Category) *ChargeFlatFeeRunDetailedLineCreate { + if v != nil { + _c.SetCategory(*v) + } + return _c +} + +// SetPaymentTerm sets the "payment_term" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetPaymentTerm(v) + return _c +} + +// SetNillablePaymentTerm sets the "payment_term" field if the given value is not nil. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetNillablePaymentTerm(v *productcatalog.PaymentTermType) *ChargeFlatFeeRunDetailedLineCreate { + if v != nil { + _c.SetPaymentTerm(*v) + } + return _c +} + +// SetIndex sets the "index" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetIndex(v int) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetIndex(v) + return _c +} + +// SetNillableIndex sets the "index" field if the given value is not nil. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetNillableIndex(v *int) *ChargeFlatFeeRunDetailedLineCreate { + if v != nil { + _c.SetIndex(*v) + } + return _c +} + +// SetCreditsApplied sets the "credits_applied" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetCreditsApplied(v *creditsapplied.CreditsApplied) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetCreditsApplied(v) + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetNamespace sets the "namespace" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetNamespace(v string) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetMetadata sets the "metadata" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetMetadata(v map[string]string) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetMetadata(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetCreatedAt(v time.Time) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetNillableCreatedAt(v *time.Time) *ChargeFlatFeeRunDetailedLineCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetNillableUpdatedAt(v *time.Time) *ChargeFlatFeeRunDetailedLineCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetDeletedAt(v time.Time) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetNillableDeletedAt(v *time.Time) *ChargeFlatFeeRunDetailedLineCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetName sets the "name" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetName(v string) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetName(v) + return _c +} + +// SetDescription sets the "description" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetDescription(v string) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetDescription(v) + return _c +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetNillableDescription(v *string) *ChargeFlatFeeRunDetailedLineCreate { + if v != nil { + _c.SetDescription(*v) + } + return _c +} + +// SetAmount sets the "amount" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetTaxesTotal(v) + return _c +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetTaxesInclusiveTotal(v) + return _c +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetTaxesExclusiveTotal(v) + return _c +} + +// SetChargesTotal sets the "charges_total" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetChargesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetChargesTotal(v) + return _c +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetDiscountsTotal(v) + return _c +} + +// SetCreditsTotal sets the "credits_total" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetCreditsTotal(v) + return _c +} + +// SetTotal sets the "total" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetTotal(v) + return _c +} + +// SetRunID sets the "run_id" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetRunID(v string) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetRunID(v) + return _c +} + +// SetPricerReferenceID sets the "pricer_reference_id" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetPricerReferenceID(v string) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetPricerReferenceID(v) + return _c +} + +// SetID sets the "id" field. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetID(v string) *ChargeFlatFeeRunDetailedLineCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetNillableID(v *string) *ChargeFlatFeeRunDetailedLineCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetRun sets the "run" edge to the ChargeFlatFeeRun entity. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SetRun(v *ChargeFlatFeeRun) *ChargeFlatFeeRunDetailedLineCreate { + return _c.SetRunID(v.ID) +} + +// Mutation returns the ChargeFlatFeeRunDetailedLineMutation object of the builder. +func (_c *ChargeFlatFeeRunDetailedLineCreate) Mutation() *ChargeFlatFeeRunDetailedLineMutation { + return _c.mutation +} + +// Save creates the ChargeFlatFeeRunDetailedLine in the database. +func (_c *ChargeFlatFeeRunDetailedLineCreate) Save(ctx context.Context) (*ChargeFlatFeeRunDetailedLine, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ChargeFlatFeeRunDetailedLineCreate) SaveX(ctx context.Context) *ChargeFlatFeeRunDetailedLine { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeFlatFeeRunDetailedLineCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeFlatFeeRunDetailedLineCreate) 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 *ChargeFlatFeeRunDetailedLineCreate) defaults() { + if _, ok := _c.mutation.Category(); !ok { + v := chargeflatfeerundetailedline.DefaultCategory + _c.mutation.SetCategory(v) + } + if _, ok := _c.mutation.PaymentTerm(); !ok { + v := chargeflatfeerundetailedline.DefaultPaymentTerm + _c.mutation.SetPaymentTerm(v) + } + if _, ok := _c.mutation.CreatedAt(); !ok { + v := chargeflatfeerundetailedline.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := chargeflatfeerundetailedline.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := chargeflatfeerundetailedline.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ChargeFlatFeeRunDetailedLineCreate) check() error { + if _, ok := _c.mutation.Currency(); !ok { + return &ValidationError{Name: "currency", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.currency"`)} + } + if v, ok := _c.mutation.Currency(); ok { + if err := chargeflatfeerundetailedline.CurrencyValidator(string(v)); err != nil { + return &ValidationError{Name: "currency", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunDetailedLine.currency": %w`, err)} + } + } + if _, ok := _c.mutation.ServicePeriodStart(); !ok { + return &ValidationError{Name: "service_period_start", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.service_period_start"`)} + } + if _, ok := _c.mutation.ServicePeriodEnd(); !ok { + return &ValidationError{Name: "service_period_end", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.service_period_end"`)} + } + if _, ok := _c.mutation.Quantity(); !ok { + return &ValidationError{Name: "quantity", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.quantity"`)} + } + if _, ok := _c.mutation.ChildUniqueReferenceID(); !ok { + return &ValidationError{Name: "child_unique_reference_id", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.child_unique_reference_id"`)} + } + if v, ok := _c.mutation.ChildUniqueReferenceID(); ok { + if err := chargeflatfeerundetailedline.ChildUniqueReferenceIDValidator(v); err != nil { + return &ValidationError{Name: "child_unique_reference_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunDetailedLine.child_unique_reference_id": %w`, err)} + } + } + if _, ok := _c.mutation.PerUnitAmount(); !ok { + return &ValidationError{Name: "per_unit_amount", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.per_unit_amount"`)} + } + if _, ok := _c.mutation.Category(); !ok { + return &ValidationError{Name: "category", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.category"`)} + } + if v, ok := _c.mutation.Category(); ok { + if err := chargeflatfeerundetailedline.CategoryValidator(v); err != nil { + return &ValidationError{Name: "category", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunDetailedLine.category": %w`, err)} + } + } + if _, ok := _c.mutation.PaymentTerm(); !ok { + return &ValidationError{Name: "payment_term", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.payment_term"`)} + } + if v, ok := _c.mutation.PaymentTerm(); ok { + if err := chargeflatfeerundetailedline.PaymentTermValidator(v); err != nil { + return &ValidationError{Name: "payment_term", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunDetailedLine.payment_term": %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 "ChargeFlatFeeRunDetailedLine.credits_applied": %w`, err)} + } + } + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := chargeflatfeerundetailedline.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunDetailedLine.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.updated_at"`)} + } + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.name"`)} + } + if _, ok := _c.mutation.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.amount"`)} + } + if _, ok := _c.mutation.TaxesTotal(); !ok { + return &ValidationError{Name: "taxes_total", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.taxes_total"`)} + } + if _, ok := _c.mutation.TaxesInclusiveTotal(); !ok { + return &ValidationError{Name: "taxes_inclusive_total", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.taxes_inclusive_total"`)} + } + if _, ok := _c.mutation.TaxesExclusiveTotal(); !ok { + return &ValidationError{Name: "taxes_exclusive_total", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.taxes_exclusive_total"`)} + } + if _, ok := _c.mutation.ChargesTotal(); !ok { + return &ValidationError{Name: "charges_total", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.charges_total"`)} + } + if _, ok := _c.mutation.DiscountsTotal(); !ok { + return &ValidationError{Name: "discounts_total", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.discounts_total"`)} + } + if _, ok := _c.mutation.CreditsTotal(); !ok { + return &ValidationError{Name: "credits_total", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.credits_total"`)} + } + if _, ok := _c.mutation.Total(); !ok { + return &ValidationError{Name: "total", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.total"`)} + } + if _, ok := _c.mutation.RunID(); !ok { + return &ValidationError{Name: "run_id", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.run_id"`)} + } + if _, ok := _c.mutation.PricerReferenceID(); !ok { + return &ValidationError{Name: "pricer_reference_id", err: errors.New(`db: missing required field "ChargeFlatFeeRunDetailedLine.pricer_reference_id"`)} + } + if v, ok := _c.mutation.PricerReferenceID(); ok { + if err := chargeflatfeerundetailedline.PricerReferenceIDValidator(v); err != nil { + return &ValidationError{Name: "pricer_reference_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunDetailedLine.pricer_reference_id": %w`, err)} + } + } + if len(_c.mutation.RunIDs()) == 0 { + return &ValidationError{Name: "run", err: errors.New(`db: missing required edge "ChargeFlatFeeRunDetailedLine.run"`)} + } + return nil +} + +func (_c *ChargeFlatFeeRunDetailedLineCreate) sqlSave(ctx context.Context) (*ChargeFlatFeeRunDetailedLine, 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 ChargeFlatFeeRunDetailedLine.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ChargeFlatFeeRunDetailedLineCreate) createSpec() (*ChargeFlatFeeRunDetailedLine, *sqlgraph.CreateSpec) { + var ( + _node = &ChargeFlatFeeRunDetailedLine{config: _c.config} + _spec = sqlgraph.NewCreateSpec(chargeflatfeerundetailedline.Table, sqlgraph.NewFieldSpec(chargeflatfeerundetailedline.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.Currency(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldCurrency, field.TypeString, value) + _node.Currency = value + } + if value, ok := _c.mutation.ServicePeriodStart(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldServicePeriodStart, field.TypeTime, value) + _node.ServicePeriodStart = value + } + if value, ok := _c.mutation.ServicePeriodEnd(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldServicePeriodEnd, field.TypeTime, value) + _node.ServicePeriodEnd = value + } + if value, ok := _c.mutation.Quantity(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldQuantity, field.TypeOther, value) + _node.Quantity = value + } + if value, ok := _c.mutation.InvoicingAppExternalID(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldInvoicingAppExternalID, field.TypeString, value) + _node.InvoicingAppExternalID = &value + } + if value, ok := _c.mutation.ChildUniqueReferenceID(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldChildUniqueReferenceID, field.TypeString, value) + _node.ChildUniqueReferenceID = value + } + if value, ok := _c.mutation.PerUnitAmount(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldPerUnitAmount, field.TypeOther, value) + _node.PerUnitAmount = value + } + if value, ok := _c.mutation.Category(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldCategory, field.TypeEnum, value) + _node.Category = value + } + if value, ok := _c.mutation.PaymentTerm(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldPaymentTerm, field.TypeEnum, value) + _node.PaymentTerm = value + } + if value, ok := _c.mutation.Index(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldIndex, field.TypeInt, value) + _node.Index = &value + } + if value, ok := _c.mutation.CreditsApplied(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldCreditsApplied, field.TypeJSON, value) + _node.CreditsApplied = value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Metadata(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldMetadata, field.TypeJSON, value) + _node.Metadata = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Description(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldDescription, field.TypeString, value) + _node.Description = &value + } + if value, ok := _c.mutation.Amount(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldAmount, field.TypeOther, value) + _node.Amount = value + } + if value, ok := _c.mutation.TaxesTotal(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldTaxesTotal, field.TypeOther, value) + _node.TaxesTotal = value + } + if value, ok := _c.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldTaxesInclusiveTotal, field.TypeOther, value) + _node.TaxesInclusiveTotal = value + } + if value, ok := _c.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldTaxesExclusiveTotal, field.TypeOther, value) + _node.TaxesExclusiveTotal = value + } + if value, ok := _c.mutation.ChargesTotal(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldChargesTotal, field.TypeOther, value) + _node.ChargesTotal = value + } + if value, ok := _c.mutation.DiscountsTotal(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldDiscountsTotal, field.TypeOther, value) + _node.DiscountsTotal = value + } + if value, ok := _c.mutation.CreditsTotal(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldCreditsTotal, field.TypeOther, value) + _node.CreditsTotal = value + } + if value, ok := _c.mutation.Total(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldTotal, field.TypeOther, value) + _node.Total = value + } + if value, ok := _c.mutation.PricerReferenceID(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldPricerReferenceID, field.TypeString, value) + _node.PricerReferenceID = value + } + if nodes := _c.mutation.RunIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeflatfeerundetailedline.RunTable, + Columns: []string{chargeflatfeerundetailedline.RunColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerun.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.ChargeFlatFeeRunDetailedLine.Create(). +// SetCurrency(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.ChargeFlatFeeRunDetailedLineUpsert) { +// SetCurrency(v+v). +// }). +// Exec(ctx) +func (_c *ChargeFlatFeeRunDetailedLineCreate) OnConflict(opts ...sql.ConflictOption) *ChargeFlatFeeRunDetailedLineUpsertOne { + _c.conflict = opts + return &ChargeFlatFeeRunDetailedLineUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeFlatFeeRunDetailedLine.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeFlatFeeRunDetailedLineCreate) OnConflictColumns(columns ...string) *ChargeFlatFeeRunDetailedLineUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeFlatFeeRunDetailedLineUpsertOne{ + create: _c, + } +} + +type ( + // ChargeFlatFeeRunDetailedLineUpsertOne is the builder for "upsert"-ing + // one ChargeFlatFeeRunDetailedLine node. + ChargeFlatFeeRunDetailedLineUpsertOne struct { + create *ChargeFlatFeeRunDetailedLineCreate + } + + // ChargeFlatFeeRunDetailedLineUpsert is the "OnConflict" setter. + ChargeFlatFeeRunDetailedLineUpsert struct { + *sql.UpdateSet + } +) + +// SetServicePeriodStart sets the "service_period_start" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetServicePeriodStart(v time.Time) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldServicePeriodStart, v) + return u +} + +// UpdateServicePeriodStart sets the "service_period_start" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateServicePeriodStart() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldServicePeriodStart) + return u +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetServicePeriodEnd(v time.Time) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldServicePeriodEnd, v) + return u +} + +// UpdateServicePeriodEnd sets the "service_period_end" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateServicePeriodEnd() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldServicePeriodEnd) + return u +} + +// SetQuantity sets the "quantity" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetQuantity(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldQuantity, v) + return u +} + +// UpdateQuantity sets the "quantity" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateQuantity() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldQuantity) + return u +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetInvoicingAppExternalID(v string) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldInvoicingAppExternalID, v) + return u +} + +// UpdateInvoicingAppExternalID sets the "invoicing_app_external_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateInvoicingAppExternalID() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldInvoicingAppExternalID) + return u +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) ClearInvoicingAppExternalID() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetNull(chargeflatfeerundetailedline.FieldInvoicingAppExternalID) + return u +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetChildUniqueReferenceID(v string) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldChildUniqueReferenceID, v) + return u +} + +// UpdateChildUniqueReferenceID sets the "child_unique_reference_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateChildUniqueReferenceID() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldChildUniqueReferenceID) + return u +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetPerUnitAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldPerUnitAmount, v) + return u +} + +// UpdatePerUnitAmount sets the "per_unit_amount" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdatePerUnitAmount() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldPerUnitAmount) + return u +} + +// SetCategory sets the "category" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetCategory(v stddetailedline.Category) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldCategory, v) + return u +} + +// UpdateCategory sets the "category" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateCategory() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldCategory) + return u +} + +// SetPaymentTerm sets the "payment_term" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldPaymentTerm, v) + return u +} + +// UpdatePaymentTerm sets the "payment_term" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdatePaymentTerm() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldPaymentTerm) + return u +} + +// SetIndex sets the "index" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetIndex(v int) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldIndex, v) + return u +} + +// UpdateIndex sets the "index" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateIndex() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldIndex) + return u +} + +// AddIndex adds v to the "index" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) AddIndex(v int) *ChargeFlatFeeRunDetailedLineUpsert { + u.Add(chargeflatfeerundetailedline.FieldIndex, v) + return u +} + +// ClearIndex clears the value of the "index" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) ClearIndex() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetNull(chargeflatfeerundetailedline.FieldIndex) + return u +} + +// SetCreditsApplied sets the "credits_applied" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetCreditsApplied(v *creditsapplied.CreditsApplied) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldCreditsApplied, v) + return u +} + +// UpdateCreditsApplied sets the "credits_applied" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateCreditsApplied() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldCreditsApplied) + return u +} + +// ClearCreditsApplied clears the value of the "credits_applied" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) ClearCreditsApplied() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetNull(chargeflatfeerundetailedline.FieldCreditsApplied) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateAnnotations() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) ClearAnnotations() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetNull(chargeflatfeerundetailedline.FieldAnnotations) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetMetadata(v map[string]string) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldMetadata, v) + return u +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateMetadata() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldMetadata) + return u +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) ClearMetadata() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetNull(chargeflatfeerundetailedline.FieldMetadata) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateUpdatedAt() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetDeletedAt(v time.Time) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateDeletedAt() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) ClearDeletedAt() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetNull(chargeflatfeerundetailedline.FieldDeletedAt) + return u +} + +// SetName sets the "name" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetName(v string) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateName() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldName) + return u +} + +// SetDescription sets the "description" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetDescription(v string) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldDescription, v) + return u +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateDescription() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldDescription) + return u +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) ClearDescription() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetNull(chargeflatfeerundetailedline.FieldDescription) + return u +} + +// SetAmount sets the "amount" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldAmount, v) + return u +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateAmount() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldAmount) + return u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldTaxesTotal, v) + return u +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateTaxesTotal() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldTaxesTotal) + return u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldTaxesInclusiveTotal, v) + return u +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateTaxesInclusiveTotal() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldTaxesInclusiveTotal) + return u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldTaxesExclusiveTotal, v) + return u +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateTaxesExclusiveTotal() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldTaxesExclusiveTotal) + return u +} + +// SetChargesTotal sets the "charges_total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetChargesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldChargesTotal, v) + return u +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateChargesTotal() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldChargesTotal) + return u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldDiscountsTotal, v) + return u +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateDiscountsTotal() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldDiscountsTotal) + return u +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldCreditsTotal, v) + return u +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateCreditsTotal() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldCreditsTotal) + return u +} + +// SetTotal sets the "total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldTotal, v) + return u +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdateTotal() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldTotal) + return u +} + +// SetPricerReferenceID sets the "pricer_reference_id" field. +func (u *ChargeFlatFeeRunDetailedLineUpsert) SetPricerReferenceID(v string) *ChargeFlatFeeRunDetailedLineUpsert { + u.Set(chargeflatfeerundetailedline.FieldPricerReferenceID, v) + return u +} + +// UpdatePricerReferenceID sets the "pricer_reference_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsert) UpdatePricerReferenceID() *ChargeFlatFeeRunDetailedLineUpsert { + u.SetExcluded(chargeflatfeerundetailedline.FieldPricerReferenceID) + 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.ChargeFlatFeeRunDetailedLine.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeflatfeerundetailedline.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateNewValues() *ChargeFlatFeeRunDetailedLineUpsertOne { + 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(chargeflatfeerundetailedline.FieldID) + } + if _, exists := u.create.mutation.Currency(); exists { + s.SetIgnore(chargeflatfeerundetailedline.FieldCurrency) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(chargeflatfeerundetailedline.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(chargeflatfeerundetailedline.FieldCreatedAt) + } + if _, exists := u.create.mutation.RunID(); exists { + s.SetIgnore(chargeflatfeerundetailedline.FieldRunID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeFlatFeeRunDetailedLine.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) Ignore() *ChargeFlatFeeRunDetailedLineUpsertOne { + 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 *ChargeFlatFeeRunDetailedLineUpsertOne) DoNothing() *ChargeFlatFeeRunDetailedLineUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeFlatFeeRunDetailedLineCreate.OnConflict +// documentation for more info. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) Update(set func(*ChargeFlatFeeRunDetailedLineUpsert)) *ChargeFlatFeeRunDetailedLineUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeFlatFeeRunDetailedLineUpsert{UpdateSet: update}) + })) + return u +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetServicePeriodStart(v time.Time) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetServicePeriodStart(v) + }) +} + +// UpdateServicePeriodStart sets the "service_period_start" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateServicePeriodStart() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateServicePeriodStart() + }) +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetServicePeriodEnd(v time.Time) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetServicePeriodEnd(v) + }) +} + +// UpdateServicePeriodEnd sets the "service_period_end" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateServicePeriodEnd() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateServicePeriodEnd() + }) +} + +// SetQuantity sets the "quantity" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetQuantity(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetQuantity(v) + }) +} + +// UpdateQuantity sets the "quantity" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateQuantity() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateQuantity() + }) +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetInvoicingAppExternalID(v string) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetInvoicingAppExternalID(v) + }) +} + +// UpdateInvoicingAppExternalID sets the "invoicing_app_external_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateInvoicingAppExternalID() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateInvoicingAppExternalID() + }) +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) ClearInvoicingAppExternalID() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.ClearInvoicingAppExternalID() + }) +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetChildUniqueReferenceID(v string) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetChildUniqueReferenceID(v) + }) +} + +// UpdateChildUniqueReferenceID sets the "child_unique_reference_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateChildUniqueReferenceID() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateChildUniqueReferenceID() + }) +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetPerUnitAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetPerUnitAmount(v) + }) +} + +// UpdatePerUnitAmount sets the "per_unit_amount" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdatePerUnitAmount() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdatePerUnitAmount() + }) +} + +// SetCategory sets the "category" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetCategory(v stddetailedline.Category) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetCategory(v) + }) +} + +// UpdateCategory sets the "category" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateCategory() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateCategory() + }) +} + +// SetPaymentTerm sets the "payment_term" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetPaymentTerm(v) + }) +} + +// UpdatePaymentTerm sets the "payment_term" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdatePaymentTerm() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdatePaymentTerm() + }) +} + +// SetIndex sets the "index" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetIndex(v int) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetIndex(v) + }) +} + +// AddIndex adds v to the "index" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) AddIndex(v int) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.AddIndex(v) + }) +} + +// UpdateIndex sets the "index" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateIndex() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateIndex() + }) +} + +// ClearIndex clears the value of the "index" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) ClearIndex() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.ClearIndex() + }) +} + +// SetCreditsApplied sets the "credits_applied" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetCreditsApplied(v *creditsapplied.CreditsApplied) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetCreditsApplied(v) + }) +} + +// UpdateCreditsApplied sets the "credits_applied" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateCreditsApplied() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateCreditsApplied() + }) +} + +// ClearCreditsApplied clears the value of the "credits_applied" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) ClearCreditsApplied() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.ClearCreditsApplied() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateAnnotations() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) ClearAnnotations() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.ClearAnnotations() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetMetadata(v map[string]string) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateMetadata() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) ClearMetadata() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateUpdatedAt() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetDeletedAt(v time.Time) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateDeletedAt() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) ClearDeletedAt() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetName(v string) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateName() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetDescription(v string) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateDescription() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) ClearDescription() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.ClearDescription() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateAmount() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateAmount() + }) +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetTaxesTotal(v) + }) +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateTaxesTotal() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateTaxesTotal() + }) +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetTaxesInclusiveTotal(v) + }) +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateTaxesInclusiveTotal() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateTaxesInclusiveTotal() + }) +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetTaxesExclusiveTotal(v) + }) +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateTaxesExclusiveTotal() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateTaxesExclusiveTotal() + }) +} + +// SetChargesTotal sets the "charges_total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetChargesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetChargesTotal(v) + }) +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateChargesTotal() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateChargesTotal() + }) +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetDiscountsTotal(v) + }) +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateDiscountsTotal() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateDiscountsTotal() + }) +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetCreditsTotal(v) + }) +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateCreditsTotal() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateCreditsTotal() + }) +} + +// SetTotal sets the "total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetTotal(v) + }) +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdateTotal() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateTotal() + }) +} + +// SetPricerReferenceID sets the "pricer_reference_id" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) SetPricerReferenceID(v string) *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetPricerReferenceID(v) + }) +} + +// UpdatePricerReferenceID sets the "pricer_reference_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) UpdatePricerReferenceID() *ChargeFlatFeeRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdatePricerReferenceID() + }) +} + +// Exec executes the query. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeFlatFeeRunDetailedLineCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeFlatFeeRunDetailedLineUpsertOne) 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 *ChargeFlatFeeRunDetailedLineUpsertOne) 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: ChargeFlatFeeRunDetailedLineUpsertOne.ID is not supported by MySQL driver. Use ChargeFlatFeeRunDetailedLineUpsertOne.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 *ChargeFlatFeeRunDetailedLineUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ChargeFlatFeeRunDetailedLineCreateBulk is the builder for creating many ChargeFlatFeeRunDetailedLine entities in bulk. +type ChargeFlatFeeRunDetailedLineCreateBulk struct { + config + err error + builders []*ChargeFlatFeeRunDetailedLineCreate + conflict []sql.ConflictOption +} + +// Save creates the ChargeFlatFeeRunDetailedLine entities in the database. +func (_c *ChargeFlatFeeRunDetailedLineCreateBulk) Save(ctx context.Context) ([]*ChargeFlatFeeRunDetailedLine, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ChargeFlatFeeRunDetailedLine, 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.(*ChargeFlatFeeRunDetailedLineMutation) + 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 *ChargeFlatFeeRunDetailedLineCreateBulk) SaveX(ctx context.Context) []*ChargeFlatFeeRunDetailedLine { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeFlatFeeRunDetailedLineCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeFlatFeeRunDetailedLineCreateBulk) 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.ChargeFlatFeeRunDetailedLine.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.ChargeFlatFeeRunDetailedLineUpsert) { +// SetCurrency(v+v). +// }). +// Exec(ctx) +func (_c *ChargeFlatFeeRunDetailedLineCreateBulk) OnConflict(opts ...sql.ConflictOption) *ChargeFlatFeeRunDetailedLineUpsertBulk { + _c.conflict = opts + return &ChargeFlatFeeRunDetailedLineUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeFlatFeeRunDetailedLine.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeFlatFeeRunDetailedLineCreateBulk) OnConflictColumns(columns ...string) *ChargeFlatFeeRunDetailedLineUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeFlatFeeRunDetailedLineUpsertBulk{ + create: _c, + } +} + +// ChargeFlatFeeRunDetailedLineUpsertBulk is the builder for "upsert"-ing +// a bulk of ChargeFlatFeeRunDetailedLine nodes. +type ChargeFlatFeeRunDetailedLineUpsertBulk struct { + create *ChargeFlatFeeRunDetailedLineCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ChargeFlatFeeRunDetailedLine.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeflatfeerundetailedline.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateNewValues() *ChargeFlatFeeRunDetailedLineUpsertBulk { + 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(chargeflatfeerundetailedline.FieldID) + } + if _, exists := b.mutation.Currency(); exists { + s.SetIgnore(chargeflatfeerundetailedline.FieldCurrency) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(chargeflatfeerundetailedline.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(chargeflatfeerundetailedline.FieldCreatedAt) + } + if _, exists := b.mutation.RunID(); exists { + s.SetIgnore(chargeflatfeerundetailedline.FieldRunID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeFlatFeeRunDetailedLine.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) Ignore() *ChargeFlatFeeRunDetailedLineUpsertBulk { + 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 *ChargeFlatFeeRunDetailedLineUpsertBulk) DoNothing() *ChargeFlatFeeRunDetailedLineUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeFlatFeeRunDetailedLineCreateBulk.OnConflict +// documentation for more info. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) Update(set func(*ChargeFlatFeeRunDetailedLineUpsert)) *ChargeFlatFeeRunDetailedLineUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeFlatFeeRunDetailedLineUpsert{UpdateSet: update}) + })) + return u +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetServicePeriodStart(v time.Time) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetServicePeriodStart(v) + }) +} + +// UpdateServicePeriodStart sets the "service_period_start" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateServicePeriodStart() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateServicePeriodStart() + }) +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetServicePeriodEnd(v time.Time) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetServicePeriodEnd(v) + }) +} + +// UpdateServicePeriodEnd sets the "service_period_end" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateServicePeriodEnd() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateServicePeriodEnd() + }) +} + +// SetQuantity sets the "quantity" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetQuantity(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetQuantity(v) + }) +} + +// UpdateQuantity sets the "quantity" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateQuantity() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateQuantity() + }) +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetInvoicingAppExternalID(v string) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetInvoicingAppExternalID(v) + }) +} + +// UpdateInvoicingAppExternalID sets the "invoicing_app_external_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateInvoicingAppExternalID() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateInvoicingAppExternalID() + }) +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) ClearInvoicingAppExternalID() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.ClearInvoicingAppExternalID() + }) +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetChildUniqueReferenceID(v string) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetChildUniqueReferenceID(v) + }) +} + +// UpdateChildUniqueReferenceID sets the "child_unique_reference_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateChildUniqueReferenceID() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateChildUniqueReferenceID() + }) +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetPerUnitAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetPerUnitAmount(v) + }) +} + +// UpdatePerUnitAmount sets the "per_unit_amount" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdatePerUnitAmount() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdatePerUnitAmount() + }) +} + +// SetCategory sets the "category" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetCategory(v stddetailedline.Category) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetCategory(v) + }) +} + +// UpdateCategory sets the "category" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateCategory() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateCategory() + }) +} + +// SetPaymentTerm sets the "payment_term" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetPaymentTerm(v) + }) +} + +// UpdatePaymentTerm sets the "payment_term" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdatePaymentTerm() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdatePaymentTerm() + }) +} + +// SetIndex sets the "index" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetIndex(v int) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetIndex(v) + }) +} + +// AddIndex adds v to the "index" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) AddIndex(v int) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.AddIndex(v) + }) +} + +// UpdateIndex sets the "index" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateIndex() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateIndex() + }) +} + +// ClearIndex clears the value of the "index" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) ClearIndex() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.ClearIndex() + }) +} + +// SetCreditsApplied sets the "credits_applied" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetCreditsApplied(v *creditsapplied.CreditsApplied) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetCreditsApplied(v) + }) +} + +// UpdateCreditsApplied sets the "credits_applied" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateCreditsApplied() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateCreditsApplied() + }) +} + +// ClearCreditsApplied clears the value of the "credits_applied" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) ClearCreditsApplied() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.ClearCreditsApplied() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateAnnotations() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) ClearAnnotations() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.ClearAnnotations() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetMetadata(v map[string]string) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateMetadata() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) ClearMetadata() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateUpdatedAt() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetDeletedAt(v time.Time) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateDeletedAt() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) ClearDeletedAt() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetName(v string) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateName() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetDescription(v string) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateDescription() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) ClearDescription() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.ClearDescription() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateAmount() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateAmount() + }) +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetTaxesTotal(v) + }) +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateTaxesTotal() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateTaxesTotal() + }) +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetTaxesInclusiveTotal(v) + }) +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateTaxesInclusiveTotal() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateTaxesInclusiveTotal() + }) +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetTaxesExclusiveTotal(v) + }) +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateTaxesExclusiveTotal() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateTaxesExclusiveTotal() + }) +} + +// SetChargesTotal sets the "charges_total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetChargesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetChargesTotal(v) + }) +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateChargesTotal() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateChargesTotal() + }) +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetDiscountsTotal(v) + }) +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateDiscountsTotal() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateDiscountsTotal() + }) +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetCreditsTotal(v) + }) +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateCreditsTotal() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateCreditsTotal() + }) +} + +// SetTotal sets the "total" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetTotal(v) + }) +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdateTotal() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdateTotal() + }) +} + +// SetPricerReferenceID sets the "pricer_reference_id" field. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) SetPricerReferenceID(v string) *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.SetPricerReferenceID(v) + }) +} + +// UpdatePricerReferenceID sets the "pricer_reference_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) UpdatePricerReferenceID() *ChargeFlatFeeRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunDetailedLineUpsert) { + s.UpdatePricerReferenceID() + }) +} + +// Exec executes the query. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) 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 ChargeFlatFeeRunDetailedLineCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeFlatFeeRunDetailedLineCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeFlatFeeRunDetailedLineUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargeflatfeerundetailedline_delete.go b/ent/db/chargeflatfeerundetailedline_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..0fe55f6c03c6604dfc7382dea6c288274759ea81 --- /dev/null +++ b/ent/db/chargeflatfeerundetailedline_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/chargeflatfeerundetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeFlatFeeRunDetailedLineDelete is the builder for deleting a ChargeFlatFeeRunDetailedLine entity. +type ChargeFlatFeeRunDetailedLineDelete struct { + config + hooks []Hook + mutation *ChargeFlatFeeRunDetailedLineMutation +} + +// Where appends a list predicates to the ChargeFlatFeeRunDetailedLineDelete builder. +func (_d *ChargeFlatFeeRunDetailedLineDelete) Where(ps ...predicate.ChargeFlatFeeRunDetailedLine) *ChargeFlatFeeRunDetailedLineDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ChargeFlatFeeRunDetailedLineDelete) 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 *ChargeFlatFeeRunDetailedLineDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ChargeFlatFeeRunDetailedLineDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(chargeflatfeerundetailedline.Table, sqlgraph.NewFieldSpec(chargeflatfeerundetailedline.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 +} + +// ChargeFlatFeeRunDetailedLineDeleteOne is the builder for deleting a single ChargeFlatFeeRunDetailedLine entity. +type ChargeFlatFeeRunDetailedLineDeleteOne struct { + _d *ChargeFlatFeeRunDetailedLineDelete +} + +// Where appends a list predicates to the ChargeFlatFeeRunDetailedLineDelete builder. +func (_d *ChargeFlatFeeRunDetailedLineDeleteOne) Where(ps ...predicate.ChargeFlatFeeRunDetailedLine) *ChargeFlatFeeRunDetailedLineDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ChargeFlatFeeRunDetailedLineDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{chargeflatfeerundetailedline.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeFlatFeeRunDetailedLineDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargeflatfeerundetailedline_query.go b/ent/db/chargeflatfeerundetailedline_query.go new file mode 100644 index 0000000000000000000000000000000000000000..85abd75b19c634262c6666c61ca0760aa43b49e5 --- /dev/null +++ b/ent/db/chargeflatfeerundetailedline_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/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerundetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeFlatFeeRunDetailedLineQuery is the builder for querying ChargeFlatFeeRunDetailedLine entities. +type ChargeFlatFeeRunDetailedLineQuery struct { + config + ctx *QueryContext + order []chargeflatfeerundetailedline.OrderOption + inters []Interceptor + predicates []predicate.ChargeFlatFeeRunDetailedLine + withRun *ChargeFlatFeeRunQuery + 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 ChargeFlatFeeRunDetailedLineQuery builder. +func (_q *ChargeFlatFeeRunDetailedLineQuery) Where(ps ...predicate.ChargeFlatFeeRunDetailedLine) *ChargeFlatFeeRunDetailedLineQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ChargeFlatFeeRunDetailedLineQuery) Limit(limit int) *ChargeFlatFeeRunDetailedLineQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ChargeFlatFeeRunDetailedLineQuery) Offset(offset int) *ChargeFlatFeeRunDetailedLineQuery { + _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 *ChargeFlatFeeRunDetailedLineQuery) Unique(unique bool) *ChargeFlatFeeRunDetailedLineQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ChargeFlatFeeRunDetailedLineQuery) Order(o ...chargeflatfeerundetailedline.OrderOption) *ChargeFlatFeeRunDetailedLineQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryRun chains the current query on the "run" edge. +func (_q *ChargeFlatFeeRunDetailedLineQuery) QueryRun() *ChargeFlatFeeRunQuery { + query := (&ChargeFlatFeeRunClient{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(chargeflatfeerundetailedline.Table, chargeflatfeerundetailedline.FieldID, selector), + sqlgraph.To(chargeflatfeerun.Table, chargeflatfeerun.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfeerundetailedline.RunTable, chargeflatfeerundetailedline.RunColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ChargeFlatFeeRunDetailedLine entity from the query. +// Returns a *NotFoundError when no ChargeFlatFeeRunDetailedLine was found. +func (_q *ChargeFlatFeeRunDetailedLineQuery) First(ctx context.Context) (*ChargeFlatFeeRunDetailedLine, 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{chargeflatfeerundetailedline.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ChargeFlatFeeRunDetailedLineQuery) FirstX(ctx context.Context) *ChargeFlatFeeRunDetailedLine { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ChargeFlatFeeRunDetailedLine ID from the query. +// Returns a *NotFoundError when no ChargeFlatFeeRunDetailedLine ID was found. +func (_q *ChargeFlatFeeRunDetailedLineQuery) 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{chargeflatfeerundetailedline.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ChargeFlatFeeRunDetailedLineQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ChargeFlatFeeRunDetailedLine entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ChargeFlatFeeRunDetailedLine entity is found. +// Returns a *NotFoundError when no ChargeFlatFeeRunDetailedLine entities are found. +func (_q *ChargeFlatFeeRunDetailedLineQuery) Only(ctx context.Context) (*ChargeFlatFeeRunDetailedLine, 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{chargeflatfeerundetailedline.Label} + default: + return nil, &NotSingularError{chargeflatfeerundetailedline.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ChargeFlatFeeRunDetailedLineQuery) OnlyX(ctx context.Context) *ChargeFlatFeeRunDetailedLine { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ChargeFlatFeeRunDetailedLine ID in the query. +// Returns a *NotSingularError when more than one ChargeFlatFeeRunDetailedLine ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ChargeFlatFeeRunDetailedLineQuery) 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{chargeflatfeerundetailedline.Label} + default: + err = &NotSingularError{chargeflatfeerundetailedline.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ChargeFlatFeeRunDetailedLineQuery) 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 ChargeFlatFeeRunDetailedLines. +func (_q *ChargeFlatFeeRunDetailedLineQuery) All(ctx context.Context) ([]*ChargeFlatFeeRunDetailedLine, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ChargeFlatFeeRunDetailedLine, *ChargeFlatFeeRunDetailedLineQuery]() + return withInterceptors[[]*ChargeFlatFeeRunDetailedLine](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ChargeFlatFeeRunDetailedLineQuery) AllX(ctx context.Context) []*ChargeFlatFeeRunDetailedLine { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ChargeFlatFeeRunDetailedLine IDs. +func (_q *ChargeFlatFeeRunDetailedLineQuery) 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(chargeflatfeerundetailedline.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ChargeFlatFeeRunDetailedLineQuery) 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 *ChargeFlatFeeRunDetailedLineQuery) 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[*ChargeFlatFeeRunDetailedLineQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ChargeFlatFeeRunDetailedLineQuery) 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 *ChargeFlatFeeRunDetailedLineQuery) 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 *ChargeFlatFeeRunDetailedLineQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ChargeFlatFeeRunDetailedLineQuery 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 *ChargeFlatFeeRunDetailedLineQuery) Clone() *ChargeFlatFeeRunDetailedLineQuery { + if _q == nil { + return nil + } + return &ChargeFlatFeeRunDetailedLineQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]chargeflatfeerundetailedline.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ChargeFlatFeeRunDetailedLine{}, _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 *ChargeFlatFeeRunDetailedLineQuery) WithRun(opts ...func(*ChargeFlatFeeRunQuery)) *ChargeFlatFeeRunDetailedLineQuery { + query := (&ChargeFlatFeeRunClient{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 { +// Currency currencyx.Code `json:"currency,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.ChargeFlatFeeRunDetailedLine.Query(). +// GroupBy(chargeflatfeerundetailedline.FieldCurrency). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *ChargeFlatFeeRunDetailedLineQuery) GroupBy(field string, fields ...string) *ChargeFlatFeeRunDetailedLineGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ChargeFlatFeeRunDetailedLineGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = chargeflatfeerundetailedline.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 { +// Currency currencyx.Code `json:"currency,omitempty"` +// } +// +// client.ChargeFlatFeeRunDetailedLine.Query(). +// Select(chargeflatfeerundetailedline.FieldCurrency). +// Scan(ctx, &v) +func (_q *ChargeFlatFeeRunDetailedLineQuery) Select(fields ...string) *ChargeFlatFeeRunDetailedLineSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ChargeFlatFeeRunDetailedLineSelect{ChargeFlatFeeRunDetailedLineQuery: _q} + sbuild.label = chargeflatfeerundetailedline.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ChargeFlatFeeRunDetailedLineSelect configured with the given aggregations. +func (_q *ChargeFlatFeeRunDetailedLineQuery) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeRunDetailedLineSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ChargeFlatFeeRunDetailedLineQuery) 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 !chargeflatfeerundetailedline.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 *ChargeFlatFeeRunDetailedLineQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ChargeFlatFeeRunDetailedLine, error) { + var ( + nodes = []*ChargeFlatFeeRunDetailedLine{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withRun != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ChargeFlatFeeRunDetailedLine).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ChargeFlatFeeRunDetailedLine{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 *ChargeFlatFeeRunDetailedLine, e *ChargeFlatFeeRun) { n.Edges.Run = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ChargeFlatFeeRunDetailedLineQuery) loadRun(ctx context.Context, query *ChargeFlatFeeRunQuery, nodes []*ChargeFlatFeeRunDetailedLine, init func(*ChargeFlatFeeRunDetailedLine), assign func(*ChargeFlatFeeRunDetailedLine, *ChargeFlatFeeRun)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeFlatFeeRunDetailedLine) + 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(chargeflatfeerun.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 *ChargeFlatFeeRunDetailedLineQuery) 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 *ChargeFlatFeeRunDetailedLineQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(chargeflatfeerundetailedline.Table, chargeflatfeerundetailedline.Columns, sqlgraph.NewFieldSpec(chargeflatfeerundetailedline.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, chargeflatfeerundetailedline.FieldID) + for i := range fields { + if fields[i] != chargeflatfeerundetailedline.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withRun != nil { + _spec.Node.AddColumnOnce(chargeflatfeerundetailedline.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 *ChargeFlatFeeRunDetailedLineQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(chargeflatfeerundetailedline.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = chargeflatfeerundetailedline.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 *ChargeFlatFeeRunDetailedLineQuery) ForUpdate(opts ...sql.LockOption) *ChargeFlatFeeRunDetailedLineQuery { + 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 *ChargeFlatFeeRunDetailedLineQuery) ForShare(opts ...sql.LockOption) *ChargeFlatFeeRunDetailedLineQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ChargeFlatFeeRunDetailedLineGroupBy is the group-by builder for ChargeFlatFeeRunDetailedLine entities. +type ChargeFlatFeeRunDetailedLineGroupBy struct { + selector + build *ChargeFlatFeeRunDetailedLineQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ChargeFlatFeeRunDetailedLineGroupBy) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeRunDetailedLineGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ChargeFlatFeeRunDetailedLineGroupBy) 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[*ChargeFlatFeeRunDetailedLineQuery, *ChargeFlatFeeRunDetailedLineGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ChargeFlatFeeRunDetailedLineGroupBy) sqlScan(ctx context.Context, root *ChargeFlatFeeRunDetailedLineQuery, 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) +} + +// ChargeFlatFeeRunDetailedLineSelect is the builder for selecting fields of ChargeFlatFeeRunDetailedLine entities. +type ChargeFlatFeeRunDetailedLineSelect struct { + *ChargeFlatFeeRunDetailedLineQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ChargeFlatFeeRunDetailedLineSelect) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeRunDetailedLineSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ChargeFlatFeeRunDetailedLineSelect) 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[*ChargeFlatFeeRunDetailedLineQuery, *ChargeFlatFeeRunDetailedLineSelect](ctx, _s.ChargeFlatFeeRunDetailedLineQuery, _s, _s.inters, v) +} + +func (_s *ChargeFlatFeeRunDetailedLineSelect) sqlScan(ctx context.Context, root *ChargeFlatFeeRunDetailedLineQuery, 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/ent/db/chargeflatfeerundetailedline_update.go b/ent/db/chargeflatfeerundetailedline_update.go new file mode 100644 index 0000000000000000000000000000000000000000..50d51f3a64cff4f48efe244d31e96221211144d7 --- /dev/null +++ b/ent/db/chargeflatfeerundetailedline_update.go @@ -0,0 +1,1203 @@ +// 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/models/creditsapplied" + "github.com/openmeterio/openmeter/openmeter/billing/models/stddetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerundetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeFlatFeeRunDetailedLineUpdate is the builder for updating ChargeFlatFeeRunDetailedLine entities. +type ChargeFlatFeeRunDetailedLineUpdate struct { + config + hooks []Hook + mutation *ChargeFlatFeeRunDetailedLineMutation +} + +// Where appends a list predicates to the ChargeFlatFeeRunDetailedLineUpdate builder. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) Where(ps ...predicate.ChargeFlatFeeRunDetailedLine) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetServicePeriodStart(v time.Time) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetServicePeriodStart(v) + return _u +} + +// SetNillableServicePeriodStart sets the "service_period_start" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillableServicePeriodStart(v *time.Time) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetServicePeriodStart(*v) + } + return _u +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetServicePeriodEnd(v time.Time) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetServicePeriodEnd(v) + return _u +} + +// SetNillableServicePeriodEnd sets the "service_period_end" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillableServicePeriodEnd(v *time.Time) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetServicePeriodEnd(*v) + } + return _u +} + +// SetQuantity sets the "quantity" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetQuantity(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetQuantity(v) + return _u +} + +// SetNillableQuantity sets the "quantity" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillableQuantity(v *alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetQuantity(*v) + } + return _u +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetInvoicingAppExternalID(v string) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetInvoicingAppExternalID(v) + return _u +} + +// SetNillableInvoicingAppExternalID sets the "invoicing_app_external_id" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillableInvoicingAppExternalID(v *string) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetInvoicingAppExternalID(*v) + } + return _u +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) ClearInvoicingAppExternalID() *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.ClearInvoicingAppExternalID() + return _u +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetChildUniqueReferenceID(v string) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetChildUniqueReferenceID(v) + return _u +} + +// SetNillableChildUniqueReferenceID sets the "child_unique_reference_id" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillableChildUniqueReferenceID(v *string) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetChildUniqueReferenceID(*v) + } + return _u +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetPerUnitAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetPerUnitAmount(v) + return _u +} + +// SetNillablePerUnitAmount sets the "per_unit_amount" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillablePerUnitAmount(v *alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetPerUnitAmount(*v) + } + return _u +} + +// SetCategory sets the "category" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetCategory(v stddetailedline.Category) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetCategory(v) + return _u +} + +// SetNillableCategory sets the "category" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillableCategory(v *stddetailedline.Category) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetCategory(*v) + } + return _u +} + +// SetPaymentTerm sets the "payment_term" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetPaymentTerm(v) + return _u +} + +// SetNillablePaymentTerm sets the "payment_term" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillablePaymentTerm(v *productcatalog.PaymentTermType) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetPaymentTerm(*v) + } + return _u +} + +// SetIndex sets the "index" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetIndex(v int) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.ResetIndex() + _u.mutation.SetIndex(v) + return _u +} + +// SetNillableIndex sets the "index" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillableIndex(v *int) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetIndex(*v) + } + return _u +} + +// AddIndex adds value to the "index" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) AddIndex(v int) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.AddIndex(v) + return _u +} + +// ClearIndex clears the value of the "index" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) ClearIndex() *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.ClearIndex() + return _u +} + +// SetCreditsApplied sets the "credits_applied" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetCreditsApplied(v *creditsapplied.CreditsApplied) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetCreditsApplied(v) + return _u +} + +// ClearCreditsApplied clears the value of the "credits_applied" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) ClearCreditsApplied() *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.ClearCreditsApplied() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) ClearAnnotations() *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetMetadata(v map[string]string) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) ClearMetadata() *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetDeletedAt(v time.Time) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillableDeletedAt(v *time.Time) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) ClearDeletedAt() *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetName(v string) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillableName(v *string) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetDescription(v string) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillableDescription(v *string) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) ClearDescription() *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.ClearDescription() + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetTaxesTotal(v) + return _u +} + +// SetNillableTaxesTotal sets the "taxes_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillableTaxesTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetTaxesTotal(*v) + } + return _u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetTaxesInclusiveTotal(v) + return _u +} + +// SetNillableTaxesInclusiveTotal sets the "taxes_inclusive_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillableTaxesInclusiveTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetTaxesInclusiveTotal(*v) + } + return _u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetTaxesExclusiveTotal(v) + return _u +} + +// SetNillableTaxesExclusiveTotal sets the "taxes_exclusive_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillableTaxesExclusiveTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetTaxesExclusiveTotal(*v) + } + return _u +} + +// SetChargesTotal sets the "charges_total" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetChargesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetChargesTotal(v) + return _u +} + +// SetNillableChargesTotal sets the "charges_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillableChargesTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetChargesTotal(*v) + } + return _u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetDiscountsTotal(v) + return _u +} + +// SetNillableDiscountsTotal sets the "discounts_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillableDiscountsTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetDiscountsTotal(*v) + } + return _u +} + +// SetCreditsTotal sets the "credits_total" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetCreditsTotal(v) + return _u +} + +// SetNillableCreditsTotal sets the "credits_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillableCreditsTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetCreditsTotal(*v) + } + return _u +} + +// SetTotal sets the "total" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetTotal(v) + return _u +} + +// SetNillableTotal sets the "total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillableTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetTotal(*v) + } + return _u +} + +// SetPricerReferenceID sets the "pricer_reference_id" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetPricerReferenceID(v string) *ChargeFlatFeeRunDetailedLineUpdate { + _u.mutation.SetPricerReferenceID(v) + return _u +} + +// SetNillablePricerReferenceID sets the "pricer_reference_id" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) SetNillablePricerReferenceID(v *string) *ChargeFlatFeeRunDetailedLineUpdate { + if v != nil { + _u.SetPricerReferenceID(*v) + } + return _u +} + +// Mutation returns the ChargeFlatFeeRunDetailedLineMutation object of the builder. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) Mutation() *ChargeFlatFeeRunDetailedLineMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) 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 *ChargeFlatFeeRunDetailedLineUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) 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 *ChargeFlatFeeRunDetailedLineUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeflatfeerundetailedline.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeFlatFeeRunDetailedLineUpdate) check() error { + if v, ok := _u.mutation.ChildUniqueReferenceID(); ok { + if err := chargeflatfeerundetailedline.ChildUniqueReferenceIDValidator(v); err != nil { + return &ValidationError{Name: "child_unique_reference_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunDetailedLine.child_unique_reference_id": %w`, err)} + } + } + if v, ok := _u.mutation.Category(); ok { + if err := chargeflatfeerundetailedline.CategoryValidator(v); err != nil { + return &ValidationError{Name: "category", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunDetailedLine.category": %w`, err)} + } + } + if v, ok := _u.mutation.PaymentTerm(); ok { + if err := chargeflatfeerundetailedline.PaymentTermValidator(v); err != nil { + return &ValidationError{Name: "payment_term", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunDetailedLine.payment_term": %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 "ChargeFlatFeeRunDetailedLine.credits_applied": %w`, err)} + } + } + if v, ok := _u.mutation.PricerReferenceID(); ok { + if err := chargeflatfeerundetailedline.PricerReferenceIDValidator(v); err != nil { + return &ValidationError{Name: "pricer_reference_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunDetailedLine.pricer_reference_id": %w`, err)} + } + } + if _u.mutation.RunCleared() && len(_u.mutation.RunIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeFlatFeeRunDetailedLine.run"`) + } + return nil +} + +func (_u *ChargeFlatFeeRunDetailedLineUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeflatfeerundetailedline.Table, chargeflatfeerundetailedline.Columns, sqlgraph.NewFieldSpec(chargeflatfeerundetailedline.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.ServicePeriodStart(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldServicePeriodStart, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodEnd(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldServicePeriodEnd, field.TypeTime, value) + } + if value, ok := _u.mutation.Quantity(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldQuantity, field.TypeOther, value) + } + if value, ok := _u.mutation.InvoicingAppExternalID(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldInvoicingAppExternalID, field.TypeString, value) + } + if _u.mutation.InvoicingAppExternalIDCleared() { + _spec.ClearField(chargeflatfeerundetailedline.FieldInvoicingAppExternalID, field.TypeString) + } + if value, ok := _u.mutation.ChildUniqueReferenceID(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldChildUniqueReferenceID, field.TypeString, value) + } + if value, ok := _u.mutation.PerUnitAmount(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldPerUnitAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.Category(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldCategory, field.TypeEnum, value) + } + if value, ok := _u.mutation.PaymentTerm(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldPaymentTerm, field.TypeEnum, value) + } + if value, ok := _u.mutation.Index(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldIndex, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedIndex(); ok { + _spec.AddField(chargeflatfeerundetailedline.FieldIndex, field.TypeInt, value) + } + if _u.mutation.IndexCleared() { + _spec.ClearField(chargeflatfeerundetailedline.FieldIndex, field.TypeInt) + } + if value, ok := _u.mutation.CreditsApplied(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldCreditsApplied, field.TypeJSON, value) + } + if _u.mutation.CreditsAppliedCleared() { + _spec.ClearField(chargeflatfeerundetailedline.FieldCreditsApplied, field.TypeJSON) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargeflatfeerundetailedline.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(chargeflatfeerundetailedline.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeflatfeerundetailedline.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(chargeflatfeerundetailedline.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesTotal(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldTaxesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldTaxesInclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldTaxesExclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.ChargesTotal(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldChargesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.DiscountsTotal(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldDiscountsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.CreditsTotal(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldCreditsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.Total(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.PricerReferenceID(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldPricerReferenceID, field.TypeString, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{chargeflatfeerundetailedline.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ChargeFlatFeeRunDetailedLineUpdateOne is the builder for updating a single ChargeFlatFeeRunDetailedLine entity. +type ChargeFlatFeeRunDetailedLineUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ChargeFlatFeeRunDetailedLineMutation +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetServicePeriodStart(v time.Time) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetServicePeriodStart(v) + return _u +} + +// SetNillableServicePeriodStart sets the "service_period_start" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillableServicePeriodStart(v *time.Time) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetServicePeriodStart(*v) + } + return _u +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetServicePeriodEnd(v time.Time) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetServicePeriodEnd(v) + return _u +} + +// SetNillableServicePeriodEnd sets the "service_period_end" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillableServicePeriodEnd(v *time.Time) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetServicePeriodEnd(*v) + } + return _u +} + +// SetQuantity sets the "quantity" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetQuantity(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetQuantity(v) + return _u +} + +// SetNillableQuantity sets the "quantity" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillableQuantity(v *alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetQuantity(*v) + } + return _u +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetInvoicingAppExternalID(v string) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetInvoicingAppExternalID(v) + return _u +} + +// SetNillableInvoicingAppExternalID sets the "invoicing_app_external_id" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillableInvoicingAppExternalID(v *string) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetInvoicingAppExternalID(*v) + } + return _u +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) ClearInvoicingAppExternalID() *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.ClearInvoicingAppExternalID() + return _u +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetChildUniqueReferenceID(v string) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetChildUniqueReferenceID(v) + return _u +} + +// SetNillableChildUniqueReferenceID sets the "child_unique_reference_id" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillableChildUniqueReferenceID(v *string) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetChildUniqueReferenceID(*v) + } + return _u +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetPerUnitAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetPerUnitAmount(v) + return _u +} + +// SetNillablePerUnitAmount sets the "per_unit_amount" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillablePerUnitAmount(v *alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetPerUnitAmount(*v) + } + return _u +} + +// SetCategory sets the "category" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetCategory(v stddetailedline.Category) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetCategory(v) + return _u +} + +// SetNillableCategory sets the "category" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillableCategory(v *stddetailedline.Category) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetCategory(*v) + } + return _u +} + +// SetPaymentTerm sets the "payment_term" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetPaymentTerm(v) + return _u +} + +// SetNillablePaymentTerm sets the "payment_term" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillablePaymentTerm(v *productcatalog.PaymentTermType) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetPaymentTerm(*v) + } + return _u +} + +// SetIndex sets the "index" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetIndex(v int) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.ResetIndex() + _u.mutation.SetIndex(v) + return _u +} + +// SetNillableIndex sets the "index" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillableIndex(v *int) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetIndex(*v) + } + return _u +} + +// AddIndex adds value to the "index" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) AddIndex(v int) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.AddIndex(v) + return _u +} + +// ClearIndex clears the value of the "index" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) ClearIndex() *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.ClearIndex() + return _u +} + +// SetCreditsApplied sets the "credits_applied" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetCreditsApplied(v *creditsapplied.CreditsApplied) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetCreditsApplied(v) + return _u +} + +// ClearCreditsApplied clears the value of the "credits_applied" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) ClearCreditsApplied() *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.ClearCreditsApplied() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) ClearAnnotations() *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetMetadata(v map[string]string) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) ClearMetadata() *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetDeletedAt(v time.Time) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillableDeletedAt(v *time.Time) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) ClearDeletedAt() *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetName(v string) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillableName(v *string) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetDescription(v string) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillableDescription(v *string) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) ClearDescription() *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.ClearDescription() + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetTaxesTotal(v) + return _u +} + +// SetNillableTaxesTotal sets the "taxes_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillableTaxesTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetTaxesTotal(*v) + } + return _u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetTaxesInclusiveTotal(v) + return _u +} + +// SetNillableTaxesInclusiveTotal sets the "taxes_inclusive_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillableTaxesInclusiveTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetTaxesInclusiveTotal(*v) + } + return _u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetTaxesExclusiveTotal(v) + return _u +} + +// SetNillableTaxesExclusiveTotal sets the "taxes_exclusive_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillableTaxesExclusiveTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetTaxesExclusiveTotal(*v) + } + return _u +} + +// SetChargesTotal sets the "charges_total" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetChargesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetChargesTotal(v) + return _u +} + +// SetNillableChargesTotal sets the "charges_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillableChargesTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetChargesTotal(*v) + } + return _u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetDiscountsTotal(v) + return _u +} + +// SetNillableDiscountsTotal sets the "discounts_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillableDiscountsTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetDiscountsTotal(*v) + } + return _u +} + +// SetCreditsTotal sets the "credits_total" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetCreditsTotal(v) + return _u +} + +// SetNillableCreditsTotal sets the "credits_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillableCreditsTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetCreditsTotal(*v) + } + return _u +} + +// SetTotal sets the "total" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetTotal(v) + return _u +} + +// SetNillableTotal sets the "total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillableTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetTotal(*v) + } + return _u +} + +// SetPricerReferenceID sets the "pricer_reference_id" field. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetPricerReferenceID(v string) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.mutation.SetPricerReferenceID(v) + return _u +} + +// SetNillablePricerReferenceID sets the "pricer_reference_id" field if the given value is not nil. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SetNillablePricerReferenceID(v *string) *ChargeFlatFeeRunDetailedLineUpdateOne { + if v != nil { + _u.SetPricerReferenceID(*v) + } + return _u +} + +// Mutation returns the ChargeFlatFeeRunDetailedLineMutation object of the builder. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) Mutation() *ChargeFlatFeeRunDetailedLineMutation { + return _u.mutation +} + +// Where appends a list predicates to the ChargeFlatFeeRunDetailedLineUpdate builder. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) Where(ps ...predicate.ChargeFlatFeeRunDetailedLine) *ChargeFlatFeeRunDetailedLineUpdateOne { + _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 *ChargeFlatFeeRunDetailedLineUpdateOne) Select(field string, fields ...string) *ChargeFlatFeeRunDetailedLineUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ChargeFlatFeeRunDetailedLine entity. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) Save(ctx context.Context) (*ChargeFlatFeeRunDetailedLine, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) SaveX(ctx context.Context) *ChargeFlatFeeRunDetailedLine { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) 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 *ChargeFlatFeeRunDetailedLineUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeflatfeerundetailedline.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) check() error { + if v, ok := _u.mutation.ChildUniqueReferenceID(); ok { + if err := chargeflatfeerundetailedline.ChildUniqueReferenceIDValidator(v); err != nil { + return &ValidationError{Name: "child_unique_reference_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunDetailedLine.child_unique_reference_id": %w`, err)} + } + } + if v, ok := _u.mutation.Category(); ok { + if err := chargeflatfeerundetailedline.CategoryValidator(v); err != nil { + return &ValidationError{Name: "category", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunDetailedLine.category": %w`, err)} + } + } + if v, ok := _u.mutation.PaymentTerm(); ok { + if err := chargeflatfeerundetailedline.PaymentTermValidator(v); err != nil { + return &ValidationError{Name: "payment_term", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunDetailedLine.payment_term": %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 "ChargeFlatFeeRunDetailedLine.credits_applied": %w`, err)} + } + } + if v, ok := _u.mutation.PricerReferenceID(); ok { + if err := chargeflatfeerundetailedline.PricerReferenceIDValidator(v); err != nil { + return &ValidationError{Name: "pricer_reference_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunDetailedLine.pricer_reference_id": %w`, err)} + } + } + if _u.mutation.RunCleared() && len(_u.mutation.RunIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeFlatFeeRunDetailedLine.run"`) + } + return nil +} + +func (_u *ChargeFlatFeeRunDetailedLineUpdateOne) sqlSave(ctx context.Context) (_node *ChargeFlatFeeRunDetailedLine, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeflatfeerundetailedline.Table, chargeflatfeerundetailedline.Columns, sqlgraph.NewFieldSpec(chargeflatfeerundetailedline.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "ChargeFlatFeeRunDetailedLine.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, chargeflatfeerundetailedline.FieldID) + for _, f := range fields { + if !chargeflatfeerundetailedline.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != chargeflatfeerundetailedline.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.ServicePeriodStart(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldServicePeriodStart, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodEnd(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldServicePeriodEnd, field.TypeTime, value) + } + if value, ok := _u.mutation.Quantity(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldQuantity, field.TypeOther, value) + } + if value, ok := _u.mutation.InvoicingAppExternalID(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldInvoicingAppExternalID, field.TypeString, value) + } + if _u.mutation.InvoicingAppExternalIDCleared() { + _spec.ClearField(chargeflatfeerundetailedline.FieldInvoicingAppExternalID, field.TypeString) + } + if value, ok := _u.mutation.ChildUniqueReferenceID(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldChildUniqueReferenceID, field.TypeString, value) + } + if value, ok := _u.mutation.PerUnitAmount(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldPerUnitAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.Category(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldCategory, field.TypeEnum, value) + } + if value, ok := _u.mutation.PaymentTerm(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldPaymentTerm, field.TypeEnum, value) + } + if value, ok := _u.mutation.Index(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldIndex, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedIndex(); ok { + _spec.AddField(chargeflatfeerundetailedline.FieldIndex, field.TypeInt, value) + } + if _u.mutation.IndexCleared() { + _spec.ClearField(chargeflatfeerundetailedline.FieldIndex, field.TypeInt) + } + if value, ok := _u.mutation.CreditsApplied(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldCreditsApplied, field.TypeJSON, value) + } + if _u.mutation.CreditsAppliedCleared() { + _spec.ClearField(chargeflatfeerundetailedline.FieldCreditsApplied, field.TypeJSON) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargeflatfeerundetailedline.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(chargeflatfeerundetailedline.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeflatfeerundetailedline.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(chargeflatfeerundetailedline.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesTotal(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldTaxesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldTaxesInclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldTaxesExclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.ChargesTotal(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldChargesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.DiscountsTotal(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldDiscountsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.CreditsTotal(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldCreditsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.Total(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.PricerReferenceID(); ok { + _spec.SetField(chargeflatfeerundetailedline.FieldPricerReferenceID, field.TypeString, value) + } + _node = &ChargeFlatFeeRunDetailedLine{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{chargeflatfeerundetailedline.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/ent/db/chargeflatfeeruninvoicedusage.go b/ent/db/chargeflatfeeruninvoicedusage.go new file mode 100644 index 0000000000000000000000000000000000000000..2b789310e2fee9e8d76698cdbbbf16c5286d5a9e --- /dev/null +++ b/ent/db/chargeflatfeeruninvoicedusage.go @@ -0,0 +1,324 @@ +// 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/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeruninvoicedusage" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeFlatFeeRunInvoicedUsage is the model entity for the ChargeFlatFeeRunInvoicedUsage schema. +type ChargeFlatFeeRunInvoicedUsage struct { + config `json:"-"` + // ID of the ent. + ID string `json:"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"` + // 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 ChargeFlatFeeRunInvoicedUsageQuery when eager-loading is set. + Edges ChargeFlatFeeRunInvoicedUsageEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ChargeFlatFeeRunInvoicedUsageEdges holds the relations/edges for other nodes in the graph. +type ChargeFlatFeeRunInvoicedUsageEdges struct { + // Run holds the value of the run edge. + Run *ChargeFlatFeeRun `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 ChargeFlatFeeRunInvoicedUsageEdges) RunOrErr() (*ChargeFlatFeeRun, error) { + if e.Run != nil { + return e.Run, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: chargeflatfeerun.Label} + } + return nil, &NotLoadedError{edge: "run"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ChargeFlatFeeRunInvoicedUsage) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case chargeflatfeeruninvoicedusage.FieldAnnotations: + values[i] = new([]byte) + case chargeflatfeeruninvoicedusage.FieldAmount, chargeflatfeeruninvoicedusage.FieldTaxesTotal, chargeflatfeeruninvoicedusage.FieldTaxesInclusiveTotal, chargeflatfeeruninvoicedusage.FieldTaxesExclusiveTotal, chargeflatfeeruninvoicedusage.FieldChargesTotal, chargeflatfeeruninvoicedusage.FieldDiscountsTotal, chargeflatfeeruninvoicedusage.FieldCreditsTotal, chargeflatfeeruninvoicedusage.FieldTotal: + values[i] = new(alpacadecimal.Decimal) + case chargeflatfeeruninvoicedusage.FieldID, chargeflatfeeruninvoicedusage.FieldLedgerTransactionGroupID, chargeflatfeeruninvoicedusage.FieldNamespace, chargeflatfeeruninvoicedusage.FieldRunID: + values[i] = new(sql.NullString) + case chargeflatfeeruninvoicedusage.FieldServicePeriodFrom, chargeflatfeeruninvoicedusage.FieldServicePeriodTo, chargeflatfeeruninvoicedusage.FieldCreatedAt, chargeflatfeeruninvoicedusage.FieldUpdatedAt, chargeflatfeeruninvoicedusage.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 ChargeFlatFeeRunInvoicedUsage fields. +func (_m *ChargeFlatFeeRunInvoicedUsage) 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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 ChargeFlatFeeRunInvoicedUsage. +// This includes values selected through modifiers, order, etc. +func (_m *ChargeFlatFeeRunInvoicedUsage) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryRun queries the "run" edge of the ChargeFlatFeeRunInvoicedUsage entity. +func (_m *ChargeFlatFeeRunInvoicedUsage) QueryRun() *ChargeFlatFeeRunQuery { + return NewChargeFlatFeeRunInvoicedUsageClient(_m.config).QueryRun(_m) +} + +// Update returns a builder for updating this ChargeFlatFeeRunInvoicedUsage. +// Note that you need to call ChargeFlatFeeRunInvoicedUsage.Unwrap() before calling this method if this ChargeFlatFeeRunInvoicedUsage +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ChargeFlatFeeRunInvoicedUsage) Update() *ChargeFlatFeeRunInvoicedUsageUpdateOne { + return NewChargeFlatFeeRunInvoicedUsageClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsage) Unwrap() *ChargeFlatFeeRunInvoicedUsage { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: ChargeFlatFeeRunInvoicedUsage is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ChargeFlatFeeRunInvoicedUsage) String() string { + var builder strings.Builder + builder.WriteString("ChargeFlatFeeRunInvoicedUsage(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + 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(", ") + 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() +} + +// ChargeFlatFeeRunInvoicedUsages is a parsable slice of ChargeFlatFeeRunInvoicedUsage. +type ChargeFlatFeeRunInvoicedUsages []*ChargeFlatFeeRunInvoicedUsage diff --git a/ent/db/chargeflatfeeruninvoicedusage/chargeflatfeeruninvoicedusage.go b/ent/db/chargeflatfeeruninvoicedusage/chargeflatfeeruninvoicedusage.go new file mode 100644 index 0000000000000000000000000000000000000000..8a9f874c22a2e4d5114933973307d9249831c2d2 --- /dev/null +++ b/ent/db/chargeflatfeeruninvoicedusage/chargeflatfeeruninvoicedusage.go @@ -0,0 +1,211 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeflatfeeruninvoicedusage + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the chargeflatfeeruninvoicedusage type in the database. + Label = "charge_flat_fee_run_invoiced_usage" + // FieldID holds the string denoting the id field in the database. + FieldID = "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" + // 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 chargeflatfeeruninvoicedusage in the database. + Table = "charge_flat_fee_run_invoiced_usages" + // RunTable is the table that holds the run relation/edge. + RunTable = "charge_flat_fee_run_invoiced_usages" + // RunInverseTable is the table name for the ChargeFlatFeeRun entity. + // It exists in this package in order to avoid circular dependency with the "chargeflatfeerun" package. + RunInverseTable = "charge_flat_fee_runs" + // RunColumn is the table column denoting the run relation/edge. + RunColumn = "run_id" +) + +// Columns holds all SQL columns for chargeflatfeeruninvoicedusage fields. +var Columns = []string{ + FieldID, + FieldServicePeriodFrom, + FieldServicePeriodTo, + 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 ( + // 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 ChargeFlatFeeRunInvoicedUsage 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() +} + +// 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() +} + +// 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/ent/db/chargeflatfeeruninvoicedusage/where.go b/ent/db/chargeflatfeeruninvoicedusage/where.go new file mode 100644 index 0000000000000000000000000000000000000000..f74cdb511a790dd11d0819a2f91bcf383a974878 --- /dev/null +++ b/ent/db/chargeflatfeeruninvoicedusage/where.go @@ -0,0 +1,930 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeflatfeeruninvoicedusage + +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.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldContainsFold(FieldID, id)) +} + +// ServicePeriodFrom applies equality check predicate on the "service_period_from" field. It's identical to ServicePeriodFromEQ. +func ServicePeriodFrom(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(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.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(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.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldLedgerTransactionGroupID, v)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(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.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(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.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(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.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ. +func Amount(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(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.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(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.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(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.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(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.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(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.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(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.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldCreditsTotal, v)) +} + +// Total applies equality check predicate on the "total" field. It's identical to TotalEQ. +func Total(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldTotal, v)) +} + +// RunID applies equality check predicate on the "run_id" field. It's identical to RunIDEQ. +func RunID(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldRunID, v)) +} + +// ServicePeriodFromEQ applies the EQ predicate on the "service_period_from" field. +func ServicePeriodFromEQ(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromNEQ applies the NEQ predicate on the "service_period_from" field. +func ServicePeriodFromNEQ(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromIn applies the In predicate on the "service_period_from" field. +func ServicePeriodFromIn(vs ...time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromNotIn applies the NotIn predicate on the "service_period_from" field. +func ServicePeriodFromNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNotIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromGT applies the GT predicate on the "service_period_from" field. +func ServicePeriodFromGT(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromGTE applies the GTE predicate on the "service_period_from" field. +func ServicePeriodFromGTE(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLT applies the LT predicate on the "service_period_from" field. +func ServicePeriodFromLT(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLTE applies the LTE predicate on the "service_period_from" field. +func ServicePeriodFromLTE(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodToEQ applies the EQ predicate on the "service_period_to" field. +func ServicePeriodToEQ(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToNEQ applies the NEQ predicate on the "service_period_to" field. +func ServicePeriodToNEQ(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToIn applies the In predicate on the "service_period_to" field. +func ServicePeriodToIn(vs ...time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToNotIn applies the NotIn predicate on the "service_period_to" field. +func ServicePeriodToNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNotIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToGT applies the GT predicate on the "service_period_to" field. +func ServicePeriodToGT(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToGTE applies the GTE predicate on the "service_period_to" field. +func ServicePeriodToGTE(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGTE(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLT applies the LT predicate on the "service_period_to" field. +func ServicePeriodToLT(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLTE applies the LTE predicate on the "service_period_to" field. +func ServicePeriodToLTE(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLTE(FieldServicePeriodTo, v)) +} + +// LedgerTransactionGroupIDEQ applies the EQ predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDEQ(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDNEQ applies the NEQ predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDNEQ(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNEQ(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDIn applies the In predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDIn(vs ...string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldIn(FieldLedgerTransactionGroupID, vs...)) +} + +// LedgerTransactionGroupIDNotIn applies the NotIn predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDNotIn(vs ...string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNotIn(FieldLedgerTransactionGroupID, vs...)) +} + +// LedgerTransactionGroupIDGT applies the GT predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDGT(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGT(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDGTE applies the GTE predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDGTE(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGTE(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDLT applies the LT predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDLT(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLT(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDLTE applies the LTE predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDLTE(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLTE(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDContains applies the Contains predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDContains(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldContains(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDHasPrefix applies the HasPrefix predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDHasPrefix(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldHasPrefix(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDHasSuffix applies the HasSuffix predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDHasSuffix(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldHasSuffix(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDIsNil applies the IsNil predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDIsNil() predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldIsNull(FieldLedgerTransactionGroupID)) +} + +// LedgerTransactionGroupIDNotNil applies the NotNil predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDNotNil() predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNotNull(FieldLedgerTransactionGroupID)) +} + +// LedgerTransactionGroupIDEqualFold applies the EqualFold predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDEqualFold(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEqualFold(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDContainsFold applies the ContainsFold predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDContainsFold(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldContainsFold(FieldLedgerTransactionGroupID, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNotNull(FieldDeletedAt)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNotNull(FieldAnnotations)) +} + +// AmountEQ applies the EQ predicate on the "amount" field. +func AmountEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldAmount, v)) +} + +// AmountNEQ applies the NEQ predicate on the "amount" field. +func AmountNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNEQ(FieldAmount, v)) +} + +// AmountIn applies the In predicate on the "amount" field. +func AmountIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldIn(FieldAmount, vs...)) +} + +// AmountNotIn applies the NotIn predicate on the "amount" field. +func AmountNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNotIn(FieldAmount, vs...)) +} + +// AmountGT applies the GT predicate on the "amount" field. +func AmountGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGT(FieldAmount, v)) +} + +// AmountGTE applies the GTE predicate on the "amount" field. +func AmountGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGTE(FieldAmount, v)) +} + +// AmountLT applies the LT predicate on the "amount" field. +func AmountLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLT(FieldAmount, v)) +} + +// AmountLTE applies the LTE predicate on the "amount" field. +func AmountLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLTE(FieldAmount, v)) +} + +// TaxesTotalEQ applies the EQ predicate on the "taxes_total" field. +func TaxesTotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldTaxesTotal, v)) +} + +// TaxesTotalNEQ applies the NEQ predicate on the "taxes_total" field. +func TaxesTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNEQ(FieldTaxesTotal, v)) +} + +// TaxesTotalIn applies the In predicate on the "taxes_total" field. +func TaxesTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldIn(FieldTaxesTotal, vs...)) +} + +// TaxesTotalNotIn applies the NotIn predicate on the "taxes_total" field. +func TaxesTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNotIn(FieldTaxesTotal, vs...)) +} + +// TaxesTotalGT applies the GT predicate on the "taxes_total" field. +func TaxesTotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGT(FieldTaxesTotal, v)) +} + +// TaxesTotalGTE applies the GTE predicate on the "taxes_total" field. +func TaxesTotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGTE(FieldTaxesTotal, v)) +} + +// TaxesTotalLT applies the LT predicate on the "taxes_total" field. +func TaxesTotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLT(FieldTaxesTotal, v)) +} + +// TaxesTotalLTE applies the LTE predicate on the "taxes_total" field. +func TaxesTotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLTE(FieldTaxesTotal, v)) +} + +// TaxesInclusiveTotalEQ applies the EQ predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalNEQ applies the NEQ predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNEQ(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalIn applies the In predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldIn(FieldTaxesInclusiveTotal, vs...)) +} + +// TaxesInclusiveTotalNotIn applies the NotIn predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNotIn(FieldTaxesInclusiveTotal, vs...)) +} + +// TaxesInclusiveTotalGT applies the GT predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGT(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalGTE applies the GTE predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGTE(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalLT applies the LT predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLT(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalLTE applies the LTE predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLTE(FieldTaxesInclusiveTotal, v)) +} + +// TaxesExclusiveTotalEQ applies the EQ predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalNEQ applies the NEQ predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNEQ(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalIn applies the In predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldIn(FieldTaxesExclusiveTotal, vs...)) +} + +// TaxesExclusiveTotalNotIn applies the NotIn predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNotIn(FieldTaxesExclusiveTotal, vs...)) +} + +// TaxesExclusiveTotalGT applies the GT predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGT(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalGTE applies the GTE predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGTE(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalLT applies the LT predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLT(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalLTE applies the LTE predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLTE(FieldTaxesExclusiveTotal, v)) +} + +// ChargesTotalEQ applies the EQ predicate on the "charges_total" field. +func ChargesTotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldChargesTotal, v)) +} + +// ChargesTotalNEQ applies the NEQ predicate on the "charges_total" field. +func ChargesTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNEQ(FieldChargesTotal, v)) +} + +// ChargesTotalIn applies the In predicate on the "charges_total" field. +func ChargesTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldIn(FieldChargesTotal, vs...)) +} + +// ChargesTotalNotIn applies the NotIn predicate on the "charges_total" field. +func ChargesTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNotIn(FieldChargesTotal, vs...)) +} + +// ChargesTotalGT applies the GT predicate on the "charges_total" field. +func ChargesTotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGT(FieldChargesTotal, v)) +} + +// ChargesTotalGTE applies the GTE predicate on the "charges_total" field. +func ChargesTotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGTE(FieldChargesTotal, v)) +} + +// ChargesTotalLT applies the LT predicate on the "charges_total" field. +func ChargesTotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLT(FieldChargesTotal, v)) +} + +// ChargesTotalLTE applies the LTE predicate on the "charges_total" field. +func ChargesTotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLTE(FieldChargesTotal, v)) +} + +// DiscountsTotalEQ applies the EQ predicate on the "discounts_total" field. +func DiscountsTotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldDiscountsTotal, v)) +} + +// DiscountsTotalNEQ applies the NEQ predicate on the "discounts_total" field. +func DiscountsTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNEQ(FieldDiscountsTotal, v)) +} + +// DiscountsTotalIn applies the In predicate on the "discounts_total" field. +func DiscountsTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldIn(FieldDiscountsTotal, vs...)) +} + +// DiscountsTotalNotIn applies the NotIn predicate on the "discounts_total" field. +func DiscountsTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNotIn(FieldDiscountsTotal, vs...)) +} + +// DiscountsTotalGT applies the GT predicate on the "discounts_total" field. +func DiscountsTotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGT(FieldDiscountsTotal, v)) +} + +// DiscountsTotalGTE applies the GTE predicate on the "discounts_total" field. +func DiscountsTotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGTE(FieldDiscountsTotal, v)) +} + +// DiscountsTotalLT applies the LT predicate on the "discounts_total" field. +func DiscountsTotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLT(FieldDiscountsTotal, v)) +} + +// DiscountsTotalLTE applies the LTE predicate on the "discounts_total" field. +func DiscountsTotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLTE(FieldDiscountsTotal, v)) +} + +// CreditsTotalEQ applies the EQ predicate on the "credits_total" field. +func CreditsTotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldCreditsTotal, v)) +} + +// CreditsTotalNEQ applies the NEQ predicate on the "credits_total" field. +func CreditsTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNEQ(FieldCreditsTotal, v)) +} + +// CreditsTotalIn applies the In predicate on the "credits_total" field. +func CreditsTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldIn(FieldCreditsTotal, vs...)) +} + +// CreditsTotalNotIn applies the NotIn predicate on the "credits_total" field. +func CreditsTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNotIn(FieldCreditsTotal, vs...)) +} + +// CreditsTotalGT applies the GT predicate on the "credits_total" field. +func CreditsTotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGT(FieldCreditsTotal, v)) +} + +// CreditsTotalGTE applies the GTE predicate on the "credits_total" field. +func CreditsTotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGTE(FieldCreditsTotal, v)) +} + +// CreditsTotalLT applies the LT predicate on the "credits_total" field. +func CreditsTotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLT(FieldCreditsTotal, v)) +} + +// CreditsTotalLTE applies the LTE predicate on the "credits_total" field. +func CreditsTotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLTE(FieldCreditsTotal, v)) +} + +// TotalEQ applies the EQ predicate on the "total" field. +func TotalEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldTotal, v)) +} + +// TotalNEQ applies the NEQ predicate on the "total" field. +func TotalNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNEQ(FieldTotal, v)) +} + +// TotalIn applies the In predicate on the "total" field. +func TotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldIn(FieldTotal, vs...)) +} + +// TotalNotIn applies the NotIn predicate on the "total" field. +func TotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNotIn(FieldTotal, vs...)) +} + +// TotalGT applies the GT predicate on the "total" field. +func TotalGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGT(FieldTotal, v)) +} + +// TotalGTE applies the GTE predicate on the "total" field. +func TotalGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGTE(FieldTotal, v)) +} + +// TotalLT applies the LT predicate on the "total" field. +func TotalLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLT(FieldTotal, v)) +} + +// TotalLTE applies the LTE predicate on the "total" field. +func TotalLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLTE(FieldTotal, v)) +} + +// RunIDEQ applies the EQ predicate on the "run_id" field. +func RunIDEQ(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEQ(FieldRunID, v)) +} + +// RunIDNEQ applies the NEQ predicate on the "run_id" field. +func RunIDNEQ(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNEQ(FieldRunID, v)) +} + +// RunIDIn applies the In predicate on the "run_id" field. +func RunIDIn(vs ...string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldIn(FieldRunID, vs...)) +} + +// RunIDNotIn applies the NotIn predicate on the "run_id" field. +func RunIDNotIn(vs ...string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldNotIn(FieldRunID, vs...)) +} + +// RunIDGT applies the GT predicate on the "run_id" field. +func RunIDGT(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGT(FieldRunID, v)) +} + +// RunIDGTE applies the GTE predicate on the "run_id" field. +func RunIDGTE(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldGTE(FieldRunID, v)) +} + +// RunIDLT applies the LT predicate on the "run_id" field. +func RunIDLT(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLT(FieldRunID, v)) +} + +// RunIDLTE applies the LTE predicate on the "run_id" field. +func RunIDLTE(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldLTE(FieldRunID, v)) +} + +// RunIDContains applies the Contains predicate on the "run_id" field. +func RunIDContains(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldContains(FieldRunID, v)) +} + +// RunIDHasPrefix applies the HasPrefix predicate on the "run_id" field. +func RunIDHasPrefix(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldHasPrefix(FieldRunID, v)) +} + +// RunIDHasSuffix applies the HasSuffix predicate on the "run_id" field. +func RunIDHasSuffix(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldHasSuffix(FieldRunID, v)) +} + +// RunIDEqualFold applies the EqualFold predicate on the "run_id" field. +func RunIDEqualFold(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldEqualFold(FieldRunID, v)) +} + +// RunIDContainsFold applies the ContainsFold predicate on the "run_id" field. +func RunIDContainsFold(v string) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.FieldContainsFold(FieldRunID, v)) +} + +// HasRun applies the HasEdge predicate on the "run" edge. +func HasRun() predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(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.ChargeFlatFeeRun) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(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.ChargeFlatFeeRunInvoicedUsage) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ChargeFlatFeeRunInvoicedUsage) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ChargeFlatFeeRunInvoicedUsage) predicate.ChargeFlatFeeRunInvoicedUsage { + return predicate.ChargeFlatFeeRunInvoicedUsage(sql.NotPredicates(p)) +} diff --git a/ent/db/chargeflatfeeruninvoicedusage_create.go b/ent/db/chargeflatfeeruninvoicedusage_create.go new file mode 100644 index 0000000000000000000000000000000000000000..6e9d0a34bb6a2d7d9db0a8f9fc9119c8c36604fe --- /dev/null +++ b/ent/db/chargeflatfeeruninvoicedusage_create.go @@ -0,0 +1,1379 @@ +// 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/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeruninvoicedusage" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeFlatFeeRunInvoicedUsageCreate is the builder for creating a ChargeFlatFeeRunInvoicedUsage entity. +type ChargeFlatFeeRunInvoicedUsageCreate struct { + config + mutation *ChargeFlatFeeRunInvoicedUsageMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunInvoicedUsageCreate { + _c.mutation.SetServicePeriodFrom(v) + return _c +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunInvoicedUsageCreate { + _c.mutation.SetServicePeriodTo(v) + return _c +} + +// SetLedgerTransactionGroupID sets the "ledger_transaction_group_id" field. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetLedgerTransactionGroupID(v string) *ChargeFlatFeeRunInvoicedUsageCreate { + _c.mutation.SetLedgerTransactionGroupID(v) + return _c +} + +// SetNillableLedgerTransactionGroupID sets the "ledger_transaction_group_id" field if the given value is not nil. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetNillableLedgerTransactionGroupID(v *string) *ChargeFlatFeeRunInvoicedUsageCreate { + if v != nil { + _c.SetLedgerTransactionGroupID(*v) + } + return _c +} + +// SetNamespace sets the "namespace" field. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetNamespace(v string) *ChargeFlatFeeRunInvoicedUsageCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetCreatedAt(v time.Time) *ChargeFlatFeeRunInvoicedUsageCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetNillableCreatedAt(v *time.Time) *ChargeFlatFeeRunInvoicedUsageCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunInvoicedUsageCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetNillableUpdatedAt(v *time.Time) *ChargeFlatFeeRunInvoicedUsageCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetDeletedAt(v time.Time) *ChargeFlatFeeRunInvoicedUsageCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetNillableDeletedAt(v *time.Time) *ChargeFlatFeeRunInvoicedUsageCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunInvoicedUsageCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetAmount sets the "amount" field. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageCreate { + _c.mutation.SetTaxesTotal(v) + return _c +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageCreate { + _c.mutation.SetTaxesInclusiveTotal(v) + return _c +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageCreate { + _c.mutation.SetTaxesExclusiveTotal(v) + return _c +} + +// SetChargesTotal sets the "charges_total" field. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetChargesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageCreate { + _c.mutation.SetChargesTotal(v) + return _c +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageCreate { + _c.mutation.SetDiscountsTotal(v) + return _c +} + +// SetCreditsTotal sets the "credits_total" field. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageCreate { + _c.mutation.SetCreditsTotal(v) + return _c +} + +// SetTotal sets the "total" field. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageCreate { + _c.mutation.SetTotal(v) + return _c +} + +// SetRunID sets the "run_id" field. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetRunID(v string) *ChargeFlatFeeRunInvoicedUsageCreate { + _c.mutation.SetRunID(v) + return _c +} + +// SetID sets the "id" field. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetID(v string) *ChargeFlatFeeRunInvoicedUsageCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetNillableID(v *string) *ChargeFlatFeeRunInvoicedUsageCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetRun sets the "run" edge to the ChargeFlatFeeRun entity. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SetRun(v *ChargeFlatFeeRun) *ChargeFlatFeeRunInvoicedUsageCreate { + return _c.SetRunID(v.ID) +} + +// Mutation returns the ChargeFlatFeeRunInvoicedUsageMutation object of the builder. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) Mutation() *ChargeFlatFeeRunInvoicedUsageMutation { + return _c.mutation +} + +// Save creates the ChargeFlatFeeRunInvoicedUsage in the database. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) Save(ctx context.Context) (*ChargeFlatFeeRunInvoicedUsage, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) SaveX(ctx context.Context) *ChargeFlatFeeRunInvoicedUsage { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) 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 *ChargeFlatFeeRunInvoicedUsageCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := chargeflatfeeruninvoicedusage.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := chargeflatfeeruninvoicedusage.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := chargeflatfeeruninvoicedusage.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) check() error { + if _, ok := _c.mutation.ServicePeriodFrom(); !ok { + return &ValidationError{Name: "service_period_from", err: errors.New(`db: missing required field "ChargeFlatFeeRunInvoicedUsage.service_period_from"`)} + } + if _, ok := _c.mutation.ServicePeriodTo(); !ok { + return &ValidationError{Name: "service_period_to", err: errors.New(`db: missing required field "ChargeFlatFeeRunInvoicedUsage.service_period_to"`)} + } + if v, ok := _c.mutation.LedgerTransactionGroupID(); ok { + if err := chargeflatfeeruninvoicedusage.LedgerTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "ledger_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunInvoicedUsage.ledger_transaction_group_id": %w`, err)} + } + } + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "ChargeFlatFeeRunInvoicedUsage.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := chargeflatfeeruninvoicedusage.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunInvoicedUsage.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "ChargeFlatFeeRunInvoicedUsage.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "ChargeFlatFeeRunInvoicedUsage.updated_at"`)} + } + if _, ok := _c.mutation.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`db: missing required field "ChargeFlatFeeRunInvoicedUsage.amount"`)} + } + if _, ok := _c.mutation.TaxesTotal(); !ok { + return &ValidationError{Name: "taxes_total", err: errors.New(`db: missing required field "ChargeFlatFeeRunInvoicedUsage.taxes_total"`)} + } + if _, ok := _c.mutation.TaxesInclusiveTotal(); !ok { + return &ValidationError{Name: "taxes_inclusive_total", err: errors.New(`db: missing required field "ChargeFlatFeeRunInvoicedUsage.taxes_inclusive_total"`)} + } + if _, ok := _c.mutation.TaxesExclusiveTotal(); !ok { + return &ValidationError{Name: "taxes_exclusive_total", err: errors.New(`db: missing required field "ChargeFlatFeeRunInvoicedUsage.taxes_exclusive_total"`)} + } + if _, ok := _c.mutation.ChargesTotal(); !ok { + return &ValidationError{Name: "charges_total", err: errors.New(`db: missing required field "ChargeFlatFeeRunInvoicedUsage.charges_total"`)} + } + if _, ok := _c.mutation.DiscountsTotal(); !ok { + return &ValidationError{Name: "discounts_total", err: errors.New(`db: missing required field "ChargeFlatFeeRunInvoicedUsage.discounts_total"`)} + } + if _, ok := _c.mutation.CreditsTotal(); !ok { + return &ValidationError{Name: "credits_total", err: errors.New(`db: missing required field "ChargeFlatFeeRunInvoicedUsage.credits_total"`)} + } + if _, ok := _c.mutation.Total(); !ok { + return &ValidationError{Name: "total", err: errors.New(`db: missing required field "ChargeFlatFeeRunInvoicedUsage.total"`)} + } + if _, ok := _c.mutation.RunID(); !ok { + return &ValidationError{Name: "run_id", err: errors.New(`db: missing required field "ChargeFlatFeeRunInvoicedUsage.run_id"`)} + } + if len(_c.mutation.RunIDs()) == 0 { + return &ValidationError{Name: "run", err: errors.New(`db: missing required edge "ChargeFlatFeeRunInvoicedUsage.run"`)} + } + return nil +} + +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) sqlSave(ctx context.Context) (*ChargeFlatFeeRunInvoicedUsage, 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 ChargeFlatFeeRunInvoicedUsage.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) createSpec() (*ChargeFlatFeeRunInvoicedUsage, *sqlgraph.CreateSpec) { + var ( + _node = &ChargeFlatFeeRunInvoicedUsage{config: _c.config} + _spec = sqlgraph.NewCreateSpec(chargeflatfeeruninvoicedusage.Table, sqlgraph.NewFieldSpec(chargeflatfeeruninvoicedusage.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.ServicePeriodFrom(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldServicePeriodFrom, field.TypeTime, value) + _node.ServicePeriodFrom = value + } + if value, ok := _c.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldServicePeriodTo, field.TypeTime, value) + _node.ServicePeriodTo = value + } + if value, ok := _c.mutation.LedgerTransactionGroupID(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldLedgerTransactionGroupID, field.TypeString, value) + _node.LedgerTransactionGroupID = &value + } + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.Amount(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldAmount, field.TypeOther, value) + _node.Amount = value + } + if value, ok := _c.mutation.TaxesTotal(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldTaxesTotal, field.TypeOther, value) + _node.TaxesTotal = value + } + if value, ok := _c.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldTaxesInclusiveTotal, field.TypeOther, value) + _node.TaxesInclusiveTotal = value + } + if value, ok := _c.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldTaxesExclusiveTotal, field.TypeOther, value) + _node.TaxesExclusiveTotal = value + } + if value, ok := _c.mutation.ChargesTotal(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldChargesTotal, field.TypeOther, value) + _node.ChargesTotal = value + } + if value, ok := _c.mutation.DiscountsTotal(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldDiscountsTotal, field.TypeOther, value) + _node.DiscountsTotal = value + } + if value, ok := _c.mutation.CreditsTotal(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldCreditsTotal, field.TypeOther, value) + _node.CreditsTotal = value + } + if value, ok := _c.mutation.Total(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldTotal, field.TypeOther, value) + _node.Total = value + } + if nodes := _c.mutation.RunIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeflatfeeruninvoicedusage.RunTable, + Columns: []string{chargeflatfeeruninvoicedusage.RunColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerun.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.ChargeFlatFeeRunInvoicedUsage.Create(). +// SetServicePeriodFrom(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.ChargeFlatFeeRunInvoicedUsageUpsert) { +// SetServicePeriodFrom(v+v). +// }). +// Exec(ctx) +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) OnConflict(opts ...sql.ConflictOption) *ChargeFlatFeeRunInvoicedUsageUpsertOne { + _c.conflict = opts + return &ChargeFlatFeeRunInvoicedUsageUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeFlatFeeRunInvoicedUsage.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeFlatFeeRunInvoicedUsageCreate) OnConflictColumns(columns ...string) *ChargeFlatFeeRunInvoicedUsageUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeFlatFeeRunInvoicedUsageUpsertOne{ + create: _c, + } +} + +type ( + // ChargeFlatFeeRunInvoicedUsageUpsertOne is the builder for "upsert"-ing + // one ChargeFlatFeeRunInvoicedUsage node. + ChargeFlatFeeRunInvoicedUsageUpsertOne struct { + create *ChargeFlatFeeRunInvoicedUsageCreate + } + + // ChargeFlatFeeRunInvoicedUsageUpsert is the "OnConflict" setter. + ChargeFlatFeeRunInvoicedUsageUpsert struct { + *sql.UpdateSet + } +) + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunInvoicedUsageUpsert { + u.Set(chargeflatfeeruninvoicedusage.FieldServicePeriodFrom, v) + return u +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) UpdateServicePeriodFrom() *ChargeFlatFeeRunInvoicedUsageUpsert { + u.SetExcluded(chargeflatfeeruninvoicedusage.FieldServicePeriodFrom) + return u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunInvoicedUsageUpsert { + u.Set(chargeflatfeeruninvoicedusage.FieldServicePeriodTo, v) + return u +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) UpdateServicePeriodTo() *ChargeFlatFeeRunInvoicedUsageUpsert { + u.SetExcluded(chargeflatfeeruninvoicedusage.FieldServicePeriodTo) + return u +} + +// SetLedgerTransactionGroupID sets the "ledger_transaction_group_id" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) SetLedgerTransactionGroupID(v string) *ChargeFlatFeeRunInvoicedUsageUpsert { + u.Set(chargeflatfeeruninvoicedusage.FieldLedgerTransactionGroupID, v) + return u +} + +// UpdateLedgerTransactionGroupID sets the "ledger_transaction_group_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) UpdateLedgerTransactionGroupID() *ChargeFlatFeeRunInvoicedUsageUpsert { + u.SetExcluded(chargeflatfeeruninvoicedusage.FieldLedgerTransactionGroupID) + return u +} + +// ClearLedgerTransactionGroupID clears the value of the "ledger_transaction_group_id" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) ClearLedgerTransactionGroupID() *ChargeFlatFeeRunInvoicedUsageUpsert { + u.SetNull(chargeflatfeeruninvoicedusage.FieldLedgerTransactionGroupID) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunInvoicedUsageUpsert { + u.Set(chargeflatfeeruninvoicedusage.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) UpdateUpdatedAt() *ChargeFlatFeeRunInvoicedUsageUpsert { + u.SetExcluded(chargeflatfeeruninvoicedusage.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) SetDeletedAt(v time.Time) *ChargeFlatFeeRunInvoicedUsageUpsert { + u.Set(chargeflatfeeruninvoicedusage.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) UpdateDeletedAt() *ChargeFlatFeeRunInvoicedUsageUpsert { + u.SetExcluded(chargeflatfeeruninvoicedusage.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) ClearDeletedAt() *ChargeFlatFeeRunInvoicedUsageUpsert { + u.SetNull(chargeflatfeeruninvoicedusage.FieldDeletedAt) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunInvoicedUsageUpsert { + u.Set(chargeflatfeeruninvoicedusage.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) UpdateAnnotations() *ChargeFlatFeeRunInvoicedUsageUpsert { + u.SetExcluded(chargeflatfeeruninvoicedusage.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) ClearAnnotations() *ChargeFlatFeeRunInvoicedUsageUpsert { + u.SetNull(chargeflatfeeruninvoicedusage.FieldAnnotations) + return u +} + +// SetAmount sets the "amount" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsert { + u.Set(chargeflatfeeruninvoicedusage.FieldAmount, v) + return u +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) UpdateAmount() *ChargeFlatFeeRunInvoicedUsageUpsert { + u.SetExcluded(chargeflatfeeruninvoicedusage.FieldAmount) + return u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsert { + u.Set(chargeflatfeeruninvoicedusage.FieldTaxesTotal, v) + return u +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) UpdateTaxesTotal() *ChargeFlatFeeRunInvoicedUsageUpsert { + u.SetExcluded(chargeflatfeeruninvoicedusage.FieldTaxesTotal) + return u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsert { + u.Set(chargeflatfeeruninvoicedusage.FieldTaxesInclusiveTotal, v) + return u +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) UpdateTaxesInclusiveTotal() *ChargeFlatFeeRunInvoicedUsageUpsert { + u.SetExcluded(chargeflatfeeruninvoicedusage.FieldTaxesInclusiveTotal) + return u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsert { + u.Set(chargeflatfeeruninvoicedusage.FieldTaxesExclusiveTotal, v) + return u +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) UpdateTaxesExclusiveTotal() *ChargeFlatFeeRunInvoicedUsageUpsert { + u.SetExcluded(chargeflatfeeruninvoicedusage.FieldTaxesExclusiveTotal) + return u +} + +// SetChargesTotal sets the "charges_total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) SetChargesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsert { + u.Set(chargeflatfeeruninvoicedusage.FieldChargesTotal, v) + return u +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) UpdateChargesTotal() *ChargeFlatFeeRunInvoicedUsageUpsert { + u.SetExcluded(chargeflatfeeruninvoicedusage.FieldChargesTotal) + return u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsert { + u.Set(chargeflatfeeruninvoicedusage.FieldDiscountsTotal, v) + return u +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) UpdateDiscountsTotal() *ChargeFlatFeeRunInvoicedUsageUpsert { + u.SetExcluded(chargeflatfeeruninvoicedusage.FieldDiscountsTotal) + return u +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsert { + u.Set(chargeflatfeeruninvoicedusage.FieldCreditsTotal, v) + return u +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) UpdateCreditsTotal() *ChargeFlatFeeRunInvoicedUsageUpsert { + u.SetExcluded(chargeflatfeeruninvoicedusage.FieldCreditsTotal) + return u +} + +// SetTotal sets the "total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) SetTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsert { + u.Set(chargeflatfeeruninvoicedusage.FieldTotal, v) + return u +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsert) UpdateTotal() *ChargeFlatFeeRunInvoicedUsageUpsert { + u.SetExcluded(chargeflatfeeruninvoicedusage.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.ChargeFlatFeeRunInvoicedUsage.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeflatfeeruninvoicedusage.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) UpdateNewValues() *ChargeFlatFeeRunInvoicedUsageUpsertOne { + 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(chargeflatfeeruninvoicedusage.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(chargeflatfeeruninvoicedusage.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(chargeflatfeeruninvoicedusage.FieldCreatedAt) + } + if _, exists := u.create.mutation.RunID(); exists { + s.SetIgnore(chargeflatfeeruninvoicedusage.FieldRunID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeFlatFeeRunInvoicedUsage.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) Ignore() *ChargeFlatFeeRunInvoicedUsageUpsertOne { + 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 *ChargeFlatFeeRunInvoicedUsageUpsertOne) DoNothing() *ChargeFlatFeeRunInvoicedUsageUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeFlatFeeRunInvoicedUsageCreate.OnConflict +// documentation for more info. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) Update(set func(*ChargeFlatFeeRunInvoicedUsageUpsert)) *ChargeFlatFeeRunInvoicedUsageUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeFlatFeeRunInvoicedUsageUpsert{UpdateSet: update}) + })) + return u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) UpdateServicePeriodFrom() *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) UpdateServicePeriodTo() *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetLedgerTransactionGroupID sets the "ledger_transaction_group_id" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) SetLedgerTransactionGroupID(v string) *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetLedgerTransactionGroupID(v) + }) +} + +// UpdateLedgerTransactionGroupID sets the "ledger_transaction_group_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) UpdateLedgerTransactionGroupID() *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateLedgerTransactionGroupID() + }) +} + +// ClearLedgerTransactionGroupID clears the value of the "ledger_transaction_group_id" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) ClearLedgerTransactionGroupID() *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.ClearLedgerTransactionGroupID() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) UpdateUpdatedAt() *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) SetDeletedAt(v time.Time) *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) UpdateDeletedAt() *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) ClearDeletedAt() *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) UpdateAnnotations() *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) ClearAnnotations() *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.ClearAnnotations() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) UpdateAmount() *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateAmount() + }) +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetTaxesTotal(v) + }) +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) UpdateTaxesTotal() *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateTaxesTotal() + }) +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetTaxesInclusiveTotal(v) + }) +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) UpdateTaxesInclusiveTotal() *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateTaxesInclusiveTotal() + }) +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetTaxesExclusiveTotal(v) + }) +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) UpdateTaxesExclusiveTotal() *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateTaxesExclusiveTotal() + }) +} + +// SetChargesTotal sets the "charges_total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) SetChargesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetChargesTotal(v) + }) +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) UpdateChargesTotal() *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateChargesTotal() + }) +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetDiscountsTotal(v) + }) +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) UpdateDiscountsTotal() *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateDiscountsTotal() + }) +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetCreditsTotal(v) + }) +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) UpdateCreditsTotal() *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateCreditsTotal() + }) +} + +// SetTotal sets the "total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) SetTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetTotal(v) + }) +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) UpdateTotal() *ChargeFlatFeeRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateTotal() + }) +} + +// Exec executes the query. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeFlatFeeRunInvoicedUsageCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertOne) 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 *ChargeFlatFeeRunInvoicedUsageUpsertOne) 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: ChargeFlatFeeRunInvoicedUsageUpsertOne.ID is not supported by MySQL driver. Use ChargeFlatFeeRunInvoicedUsageUpsertOne.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 *ChargeFlatFeeRunInvoicedUsageUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ChargeFlatFeeRunInvoicedUsageCreateBulk is the builder for creating many ChargeFlatFeeRunInvoicedUsage entities in bulk. +type ChargeFlatFeeRunInvoicedUsageCreateBulk struct { + config + err error + builders []*ChargeFlatFeeRunInvoicedUsageCreate + conflict []sql.ConflictOption +} + +// Save creates the ChargeFlatFeeRunInvoicedUsage entities in the database. +func (_c *ChargeFlatFeeRunInvoicedUsageCreateBulk) Save(ctx context.Context) ([]*ChargeFlatFeeRunInvoicedUsage, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ChargeFlatFeeRunInvoicedUsage, 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.(*ChargeFlatFeeRunInvoicedUsageMutation) + 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 *ChargeFlatFeeRunInvoicedUsageCreateBulk) SaveX(ctx context.Context) []*ChargeFlatFeeRunInvoicedUsage { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeFlatFeeRunInvoicedUsageCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeFlatFeeRunInvoicedUsageCreateBulk) 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.ChargeFlatFeeRunInvoicedUsage.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.ChargeFlatFeeRunInvoicedUsageUpsert) { +// SetServicePeriodFrom(v+v). +// }). +// Exec(ctx) +func (_c *ChargeFlatFeeRunInvoicedUsageCreateBulk) OnConflict(opts ...sql.ConflictOption) *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + _c.conflict = opts + return &ChargeFlatFeeRunInvoicedUsageUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeFlatFeeRunInvoicedUsage.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeFlatFeeRunInvoicedUsageCreateBulk) OnConflictColumns(columns ...string) *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeFlatFeeRunInvoicedUsageUpsertBulk{ + create: _c, + } +} + +// ChargeFlatFeeRunInvoicedUsageUpsertBulk is the builder for "upsert"-ing +// a bulk of ChargeFlatFeeRunInvoicedUsage nodes. +type ChargeFlatFeeRunInvoicedUsageUpsertBulk struct { + create *ChargeFlatFeeRunInvoicedUsageCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ChargeFlatFeeRunInvoicedUsage.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeflatfeeruninvoicedusage.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) UpdateNewValues() *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + 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(chargeflatfeeruninvoicedusage.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(chargeflatfeeruninvoicedusage.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(chargeflatfeeruninvoicedusage.FieldCreatedAt) + } + if _, exists := b.mutation.RunID(); exists { + s.SetIgnore(chargeflatfeeruninvoicedusage.FieldRunID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeFlatFeeRunInvoicedUsage.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) Ignore() *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + 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 *ChargeFlatFeeRunInvoicedUsageUpsertBulk) DoNothing() *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeFlatFeeRunInvoicedUsageCreateBulk.OnConflict +// documentation for more info. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) Update(set func(*ChargeFlatFeeRunInvoicedUsageUpsert)) *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeFlatFeeRunInvoicedUsageUpsert{UpdateSet: update}) + })) + return u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) UpdateServicePeriodFrom() *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) UpdateServicePeriodTo() *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetLedgerTransactionGroupID sets the "ledger_transaction_group_id" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) SetLedgerTransactionGroupID(v string) *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetLedgerTransactionGroupID(v) + }) +} + +// UpdateLedgerTransactionGroupID sets the "ledger_transaction_group_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) UpdateLedgerTransactionGroupID() *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateLedgerTransactionGroupID() + }) +} + +// ClearLedgerTransactionGroupID clears the value of the "ledger_transaction_group_id" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) ClearLedgerTransactionGroupID() *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.ClearLedgerTransactionGroupID() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) UpdateUpdatedAt() *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) SetDeletedAt(v time.Time) *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) UpdateDeletedAt() *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) ClearDeletedAt() *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) UpdateAnnotations() *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) ClearAnnotations() *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.ClearAnnotations() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) UpdateAmount() *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateAmount() + }) +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetTaxesTotal(v) + }) +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) UpdateTaxesTotal() *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateTaxesTotal() + }) +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetTaxesInclusiveTotal(v) + }) +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) UpdateTaxesInclusiveTotal() *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateTaxesInclusiveTotal() + }) +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetTaxesExclusiveTotal(v) + }) +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) UpdateTaxesExclusiveTotal() *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateTaxesExclusiveTotal() + }) +} + +// SetChargesTotal sets the "charges_total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) SetChargesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetChargesTotal(v) + }) +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) UpdateChargesTotal() *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateChargesTotal() + }) +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetDiscountsTotal(v) + }) +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) UpdateDiscountsTotal() *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateDiscountsTotal() + }) +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetCreditsTotal(v) + }) +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) UpdateCreditsTotal() *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateCreditsTotal() + }) +} + +// SetTotal sets the "total" field. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) SetTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.SetTotal(v) + }) +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) UpdateTotal() *ChargeFlatFeeRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunInvoicedUsageUpsert) { + s.UpdateTotal() + }) +} + +// Exec executes the query. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) 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 ChargeFlatFeeRunInvoicedUsageCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeFlatFeeRunInvoicedUsageCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeFlatFeeRunInvoicedUsageUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargeflatfeeruninvoicedusage_delete.go b/ent/db/chargeflatfeeruninvoicedusage_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..2a7a16301f65fb834295f3f59e4854f61b90b174 --- /dev/null +++ b/ent/db/chargeflatfeeruninvoicedusage_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/chargeflatfeeruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeFlatFeeRunInvoicedUsageDelete is the builder for deleting a ChargeFlatFeeRunInvoicedUsage entity. +type ChargeFlatFeeRunInvoicedUsageDelete struct { + config + hooks []Hook + mutation *ChargeFlatFeeRunInvoicedUsageMutation +} + +// Where appends a list predicates to the ChargeFlatFeeRunInvoicedUsageDelete builder. +func (_d *ChargeFlatFeeRunInvoicedUsageDelete) Where(ps ...predicate.ChargeFlatFeeRunInvoicedUsage) *ChargeFlatFeeRunInvoicedUsageDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ChargeFlatFeeRunInvoicedUsageDelete) 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 *ChargeFlatFeeRunInvoicedUsageDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ChargeFlatFeeRunInvoicedUsageDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(chargeflatfeeruninvoicedusage.Table, sqlgraph.NewFieldSpec(chargeflatfeeruninvoicedusage.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 +} + +// ChargeFlatFeeRunInvoicedUsageDeleteOne is the builder for deleting a single ChargeFlatFeeRunInvoicedUsage entity. +type ChargeFlatFeeRunInvoicedUsageDeleteOne struct { + _d *ChargeFlatFeeRunInvoicedUsageDelete +} + +// Where appends a list predicates to the ChargeFlatFeeRunInvoicedUsageDelete builder. +func (_d *ChargeFlatFeeRunInvoicedUsageDeleteOne) Where(ps ...predicate.ChargeFlatFeeRunInvoicedUsage) *ChargeFlatFeeRunInvoicedUsageDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ChargeFlatFeeRunInvoicedUsageDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{chargeflatfeeruninvoicedusage.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeFlatFeeRunInvoicedUsageDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargeflatfeeruninvoicedusage_query.go b/ent/db/chargeflatfeeruninvoicedusage_query.go new file mode 100644 index 0000000000000000000000000000000000000000..7780744192d722ba9d5e42c19994c9239562dfab --- /dev/null +++ b/ent/db/chargeflatfeeruninvoicedusage_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/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeFlatFeeRunInvoicedUsageQuery is the builder for querying ChargeFlatFeeRunInvoicedUsage entities. +type ChargeFlatFeeRunInvoicedUsageQuery struct { + config + ctx *QueryContext + order []chargeflatfeeruninvoicedusage.OrderOption + inters []Interceptor + predicates []predicate.ChargeFlatFeeRunInvoicedUsage + withRun *ChargeFlatFeeRunQuery + 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 ChargeFlatFeeRunInvoicedUsageQuery builder. +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) Where(ps ...predicate.ChargeFlatFeeRunInvoicedUsage) *ChargeFlatFeeRunInvoicedUsageQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) Limit(limit int) *ChargeFlatFeeRunInvoicedUsageQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) Offset(offset int) *ChargeFlatFeeRunInvoicedUsageQuery { + _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 *ChargeFlatFeeRunInvoicedUsageQuery) Unique(unique bool) *ChargeFlatFeeRunInvoicedUsageQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) Order(o ...chargeflatfeeruninvoicedusage.OrderOption) *ChargeFlatFeeRunInvoicedUsageQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryRun chains the current query on the "run" edge. +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) QueryRun() *ChargeFlatFeeRunQuery { + query := (&ChargeFlatFeeRunClient{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(chargeflatfeeruninvoicedusage.Table, chargeflatfeeruninvoicedusage.FieldID, selector), + sqlgraph.To(chargeflatfeerun.Table, chargeflatfeerun.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargeflatfeeruninvoicedusage.RunTable, chargeflatfeeruninvoicedusage.RunColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ChargeFlatFeeRunInvoicedUsage entity from the query. +// Returns a *NotFoundError when no ChargeFlatFeeRunInvoicedUsage was found. +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) First(ctx context.Context) (*ChargeFlatFeeRunInvoicedUsage, 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{chargeflatfeeruninvoicedusage.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) FirstX(ctx context.Context) *ChargeFlatFeeRunInvoicedUsage { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ChargeFlatFeeRunInvoicedUsage ID from the query. +// Returns a *NotFoundError when no ChargeFlatFeeRunInvoicedUsage ID was found. +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) 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{chargeflatfeeruninvoicedusage.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ChargeFlatFeeRunInvoicedUsage entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ChargeFlatFeeRunInvoicedUsage entity is found. +// Returns a *NotFoundError when no ChargeFlatFeeRunInvoicedUsage entities are found. +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) Only(ctx context.Context) (*ChargeFlatFeeRunInvoicedUsage, 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{chargeflatfeeruninvoicedusage.Label} + default: + return nil, &NotSingularError{chargeflatfeeruninvoicedusage.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) OnlyX(ctx context.Context) *ChargeFlatFeeRunInvoicedUsage { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ChargeFlatFeeRunInvoicedUsage ID in the query. +// Returns a *NotSingularError when more than one ChargeFlatFeeRunInvoicedUsage ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) 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{chargeflatfeeruninvoicedusage.Label} + default: + err = &NotSingularError{chargeflatfeeruninvoicedusage.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) 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 ChargeFlatFeeRunInvoicedUsages. +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) All(ctx context.Context) ([]*ChargeFlatFeeRunInvoicedUsage, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ChargeFlatFeeRunInvoicedUsage, *ChargeFlatFeeRunInvoicedUsageQuery]() + return withInterceptors[[]*ChargeFlatFeeRunInvoicedUsage](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) AllX(ctx context.Context) []*ChargeFlatFeeRunInvoicedUsage { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ChargeFlatFeeRunInvoicedUsage IDs. +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) 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(chargeflatfeeruninvoicedusage.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) 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 *ChargeFlatFeeRunInvoicedUsageQuery) 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[*ChargeFlatFeeRunInvoicedUsageQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) 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 *ChargeFlatFeeRunInvoicedUsageQuery) 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 *ChargeFlatFeeRunInvoicedUsageQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ChargeFlatFeeRunInvoicedUsageQuery 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 *ChargeFlatFeeRunInvoicedUsageQuery) Clone() *ChargeFlatFeeRunInvoicedUsageQuery { + if _q == nil { + return nil + } + return &ChargeFlatFeeRunInvoicedUsageQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]chargeflatfeeruninvoicedusage.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ChargeFlatFeeRunInvoicedUsage{}, _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 *ChargeFlatFeeRunInvoicedUsageQuery) WithRun(opts ...func(*ChargeFlatFeeRunQuery)) *ChargeFlatFeeRunInvoicedUsageQuery { + query := (&ChargeFlatFeeRunClient{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 { +// ServicePeriodFrom time.Time `json:"service_period_from,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.ChargeFlatFeeRunInvoicedUsage.Query(). +// GroupBy(chargeflatfeeruninvoicedusage.FieldServicePeriodFrom). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) GroupBy(field string, fields ...string) *ChargeFlatFeeRunInvoicedUsageGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ChargeFlatFeeRunInvoicedUsageGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = chargeflatfeeruninvoicedusage.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 { +// ServicePeriodFrom time.Time `json:"service_period_from,omitempty"` +// } +// +// client.ChargeFlatFeeRunInvoicedUsage.Query(). +// Select(chargeflatfeeruninvoicedusage.FieldServicePeriodFrom). +// Scan(ctx, &v) +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) Select(fields ...string) *ChargeFlatFeeRunInvoicedUsageSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ChargeFlatFeeRunInvoicedUsageSelect{ChargeFlatFeeRunInvoicedUsageQuery: _q} + sbuild.label = chargeflatfeeruninvoicedusage.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ChargeFlatFeeRunInvoicedUsageSelect configured with the given aggregations. +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeRunInvoicedUsageSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) 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 !chargeflatfeeruninvoicedusage.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 *ChargeFlatFeeRunInvoicedUsageQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ChargeFlatFeeRunInvoicedUsage, error) { + var ( + nodes = []*ChargeFlatFeeRunInvoicedUsage{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withRun != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ChargeFlatFeeRunInvoicedUsage).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ChargeFlatFeeRunInvoicedUsage{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 *ChargeFlatFeeRunInvoicedUsage, e *ChargeFlatFeeRun) { n.Edges.Run = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ChargeFlatFeeRunInvoicedUsageQuery) loadRun(ctx context.Context, query *ChargeFlatFeeRunQuery, nodes []*ChargeFlatFeeRunInvoicedUsage, init func(*ChargeFlatFeeRunInvoicedUsage), assign func(*ChargeFlatFeeRunInvoicedUsage, *ChargeFlatFeeRun)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeFlatFeeRunInvoicedUsage) + 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(chargeflatfeerun.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 *ChargeFlatFeeRunInvoicedUsageQuery) 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 *ChargeFlatFeeRunInvoicedUsageQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(chargeflatfeeruninvoicedusage.Table, chargeflatfeeruninvoicedusage.Columns, sqlgraph.NewFieldSpec(chargeflatfeeruninvoicedusage.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, chargeflatfeeruninvoicedusage.FieldID) + for i := range fields { + if fields[i] != chargeflatfeeruninvoicedusage.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withRun != nil { + _spec.Node.AddColumnOnce(chargeflatfeeruninvoicedusage.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 *ChargeFlatFeeRunInvoicedUsageQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(chargeflatfeeruninvoicedusage.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = chargeflatfeeruninvoicedusage.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 *ChargeFlatFeeRunInvoicedUsageQuery) ForUpdate(opts ...sql.LockOption) *ChargeFlatFeeRunInvoicedUsageQuery { + 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 *ChargeFlatFeeRunInvoicedUsageQuery) ForShare(opts ...sql.LockOption) *ChargeFlatFeeRunInvoicedUsageQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ChargeFlatFeeRunInvoicedUsageGroupBy is the group-by builder for ChargeFlatFeeRunInvoicedUsage entities. +type ChargeFlatFeeRunInvoicedUsageGroupBy struct { + selector + build *ChargeFlatFeeRunInvoicedUsageQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ChargeFlatFeeRunInvoicedUsageGroupBy) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeRunInvoicedUsageGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ChargeFlatFeeRunInvoicedUsageGroupBy) 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[*ChargeFlatFeeRunInvoicedUsageQuery, *ChargeFlatFeeRunInvoicedUsageGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ChargeFlatFeeRunInvoicedUsageGroupBy) sqlScan(ctx context.Context, root *ChargeFlatFeeRunInvoicedUsageQuery, 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) +} + +// ChargeFlatFeeRunInvoicedUsageSelect is the builder for selecting fields of ChargeFlatFeeRunInvoicedUsage entities. +type ChargeFlatFeeRunInvoicedUsageSelect struct { + *ChargeFlatFeeRunInvoicedUsageQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ChargeFlatFeeRunInvoicedUsageSelect) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeRunInvoicedUsageSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ChargeFlatFeeRunInvoicedUsageSelect) 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[*ChargeFlatFeeRunInvoicedUsageQuery, *ChargeFlatFeeRunInvoicedUsageSelect](ctx, _s.ChargeFlatFeeRunInvoicedUsageQuery, _s, _s.inters, v) +} + +func (_s *ChargeFlatFeeRunInvoicedUsageSelect) sqlScan(ctx context.Context, root *ChargeFlatFeeRunInvoicedUsageQuery, 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/ent/db/chargeflatfeeruninvoicedusage_update.go b/ent/db/chargeflatfeeruninvoicedusage_update.go new file mode 100644 index 0000000000000000000000000000000000000000..e190dad2101d3a1c515fac0ccbd5910339e47ffc --- /dev/null +++ b/ent/db/chargeflatfeeruninvoicedusage_update.go @@ -0,0 +1,726 @@ +// 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/chargeflatfeeruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeFlatFeeRunInvoicedUsageUpdate is the builder for updating ChargeFlatFeeRunInvoicedUsage entities. +type ChargeFlatFeeRunInvoicedUsageUpdate struct { + config + hooks []Hook + mutation *ChargeFlatFeeRunInvoicedUsageMutation +} + +// Where appends a list predicates to the ChargeFlatFeeRunInvoicedUsageUpdate builder. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) Where(ps ...predicate.ChargeFlatFeeRunInvoicedUsage) *ChargeFlatFeeRunInvoicedUsageUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunInvoicedUsageUpdate { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetNillableServicePeriodFrom(v *time.Time) *ChargeFlatFeeRunInvoicedUsageUpdate { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunInvoicedUsageUpdate { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetNillableServicePeriodTo(v *time.Time) *ChargeFlatFeeRunInvoicedUsageUpdate { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetLedgerTransactionGroupID sets the "ledger_transaction_group_id" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetLedgerTransactionGroupID(v string) *ChargeFlatFeeRunInvoicedUsageUpdate { + _u.mutation.SetLedgerTransactionGroupID(v) + return _u +} + +// SetNillableLedgerTransactionGroupID sets the "ledger_transaction_group_id" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetNillableLedgerTransactionGroupID(v *string) *ChargeFlatFeeRunInvoicedUsageUpdate { + if v != nil { + _u.SetLedgerTransactionGroupID(*v) + } + return _u +} + +// ClearLedgerTransactionGroupID clears the value of the "ledger_transaction_group_id" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) ClearLedgerTransactionGroupID() *ChargeFlatFeeRunInvoicedUsageUpdate { + _u.mutation.ClearLedgerTransactionGroupID() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunInvoicedUsageUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetDeletedAt(v time.Time) *ChargeFlatFeeRunInvoicedUsageUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetNillableDeletedAt(v *time.Time) *ChargeFlatFeeRunInvoicedUsageUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) ClearDeletedAt() *ChargeFlatFeeRunInvoicedUsageUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunInvoicedUsageUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) ClearAnnotations() *ChargeFlatFeeRunInvoicedUsageUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdate { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdate { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdate { + _u.mutation.SetTaxesTotal(v) + return _u +} + +// SetNillableTaxesTotal sets the "taxes_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetNillableTaxesTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdate { + if v != nil { + _u.SetTaxesTotal(*v) + } + return _u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdate { + _u.mutation.SetTaxesInclusiveTotal(v) + return _u +} + +// SetNillableTaxesInclusiveTotal sets the "taxes_inclusive_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetNillableTaxesInclusiveTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdate { + if v != nil { + _u.SetTaxesInclusiveTotal(*v) + } + return _u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdate { + _u.mutation.SetTaxesExclusiveTotal(v) + return _u +} + +// SetNillableTaxesExclusiveTotal sets the "taxes_exclusive_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetNillableTaxesExclusiveTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdate { + if v != nil { + _u.SetTaxesExclusiveTotal(*v) + } + return _u +} + +// SetChargesTotal sets the "charges_total" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetChargesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdate { + _u.mutation.SetChargesTotal(v) + return _u +} + +// SetNillableChargesTotal sets the "charges_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetNillableChargesTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdate { + if v != nil { + _u.SetChargesTotal(*v) + } + return _u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdate { + _u.mutation.SetDiscountsTotal(v) + return _u +} + +// SetNillableDiscountsTotal sets the "discounts_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetNillableDiscountsTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdate { + if v != nil { + _u.SetDiscountsTotal(*v) + } + return _u +} + +// SetCreditsTotal sets the "credits_total" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdate { + _u.mutation.SetCreditsTotal(v) + return _u +} + +// SetNillableCreditsTotal sets the "credits_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetNillableCreditsTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdate { + if v != nil { + _u.SetCreditsTotal(*v) + } + return _u +} + +// SetTotal sets the "total" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdate { + _u.mutation.SetTotal(v) + return _u +} + +// SetNillableTotal sets the "total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) SetNillableTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdate { + if v != nil { + _u.SetTotal(*v) + } + return _u +} + +// Mutation returns the ChargeFlatFeeRunInvoicedUsageMutation object of the builder. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) Mutation() *ChargeFlatFeeRunInvoicedUsageMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) 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 *ChargeFlatFeeRunInvoicedUsageUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) 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 *ChargeFlatFeeRunInvoicedUsageUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeflatfeeruninvoicedusage.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) check() error { + if v, ok := _u.mutation.LedgerTransactionGroupID(); ok { + if err := chargeflatfeeruninvoicedusage.LedgerTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "ledger_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunInvoicedUsage.ledger_transaction_group_id": %w`, err)} + } + } + if _u.mutation.RunCleared() && len(_u.mutation.RunIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeFlatFeeRunInvoicedUsage.run"`) + } + return nil +} + +func (_u *ChargeFlatFeeRunInvoicedUsageUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeflatfeeruninvoicedusage.Table, chargeflatfeeruninvoicedusage.Columns, sqlgraph.NewFieldSpec(chargeflatfeeruninvoicedusage.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(chargeflatfeeruninvoicedusage.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.LedgerTransactionGroupID(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldLedgerTransactionGroupID, field.TypeString, value) + } + if _u.mutation.LedgerTransactionGroupIDCleared() { + _spec.ClearField(chargeflatfeeruninvoicedusage.FieldLedgerTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeflatfeeruninvoicedusage.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargeflatfeeruninvoicedusage.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesTotal(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldTaxesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldTaxesInclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldTaxesExclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.ChargesTotal(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldChargesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.DiscountsTotal(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldDiscountsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.CreditsTotal(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldCreditsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.Total(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldTotal, field.TypeOther, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{chargeflatfeeruninvoicedusage.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ChargeFlatFeeRunInvoicedUsageUpdateOne is the builder for updating a single ChargeFlatFeeRunInvoicedUsage entity. +type ChargeFlatFeeRunInvoicedUsageUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ChargeFlatFeeRunInvoicedUsageMutation +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetNillableServicePeriodFrom(v *time.Time) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetNillableServicePeriodTo(v *time.Time) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetLedgerTransactionGroupID sets the "ledger_transaction_group_id" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetLedgerTransactionGroupID(v string) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + _u.mutation.SetLedgerTransactionGroupID(v) + return _u +} + +// SetNillableLedgerTransactionGroupID sets the "ledger_transaction_group_id" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetNillableLedgerTransactionGroupID(v *string) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetLedgerTransactionGroupID(*v) + } + return _u +} + +// ClearLedgerTransactionGroupID clears the value of the "ledger_transaction_group_id" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) ClearLedgerTransactionGroupID() *ChargeFlatFeeRunInvoicedUsageUpdateOne { + _u.mutation.ClearLedgerTransactionGroupID() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetDeletedAt(v time.Time) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetNillableDeletedAt(v *time.Time) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) ClearDeletedAt() *ChargeFlatFeeRunInvoicedUsageUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) ClearAnnotations() *ChargeFlatFeeRunInvoicedUsageUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + _u.mutation.SetTaxesTotal(v) + return _u +} + +// SetNillableTaxesTotal sets the "taxes_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetNillableTaxesTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetTaxesTotal(*v) + } + return _u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + _u.mutation.SetTaxesInclusiveTotal(v) + return _u +} + +// SetNillableTaxesInclusiveTotal sets the "taxes_inclusive_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetNillableTaxesInclusiveTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetTaxesInclusiveTotal(*v) + } + return _u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + _u.mutation.SetTaxesExclusiveTotal(v) + return _u +} + +// SetNillableTaxesExclusiveTotal sets the "taxes_exclusive_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetNillableTaxesExclusiveTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetTaxesExclusiveTotal(*v) + } + return _u +} + +// SetChargesTotal sets the "charges_total" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetChargesTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + _u.mutation.SetChargesTotal(v) + return _u +} + +// SetNillableChargesTotal sets the "charges_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetNillableChargesTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetChargesTotal(*v) + } + return _u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + _u.mutation.SetDiscountsTotal(v) + return _u +} + +// SetNillableDiscountsTotal sets the "discounts_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetNillableDiscountsTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetDiscountsTotal(*v) + } + return _u +} + +// SetCreditsTotal sets the "credits_total" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + _u.mutation.SetCreditsTotal(v) + return _u +} + +// SetNillableCreditsTotal sets the "credits_total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetNillableCreditsTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetCreditsTotal(*v) + } + return _u +} + +// SetTotal sets the "total" field. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetTotal(v alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + _u.mutation.SetTotal(v) + return _u +} + +// SetNillableTotal sets the "total" field if the given value is not nil. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SetNillableTotal(v *alpacadecimal.Decimal) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetTotal(*v) + } + return _u +} + +// Mutation returns the ChargeFlatFeeRunInvoicedUsageMutation object of the builder. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) Mutation() *ChargeFlatFeeRunInvoicedUsageMutation { + return _u.mutation +} + +// Where appends a list predicates to the ChargeFlatFeeRunInvoicedUsageUpdate builder. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) Where(ps ...predicate.ChargeFlatFeeRunInvoicedUsage) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + _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 *ChargeFlatFeeRunInvoicedUsageUpdateOne) Select(field string, fields ...string) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ChargeFlatFeeRunInvoicedUsage entity. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) Save(ctx context.Context) (*ChargeFlatFeeRunInvoicedUsage, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) SaveX(ctx context.Context) *ChargeFlatFeeRunInvoicedUsage { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) 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 *ChargeFlatFeeRunInvoicedUsageUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeflatfeeruninvoicedusage.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) check() error { + if v, ok := _u.mutation.LedgerTransactionGroupID(); ok { + if err := chargeflatfeeruninvoicedusage.LedgerTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "ledger_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunInvoicedUsage.ledger_transaction_group_id": %w`, err)} + } + } + if _u.mutation.RunCleared() && len(_u.mutation.RunIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeFlatFeeRunInvoicedUsage.run"`) + } + return nil +} + +func (_u *ChargeFlatFeeRunInvoicedUsageUpdateOne) sqlSave(ctx context.Context) (_node *ChargeFlatFeeRunInvoicedUsage, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeflatfeeruninvoicedusage.Table, chargeflatfeeruninvoicedusage.Columns, sqlgraph.NewFieldSpec(chargeflatfeeruninvoicedusage.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "ChargeFlatFeeRunInvoicedUsage.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, chargeflatfeeruninvoicedusage.FieldID) + for _, f := range fields { + if !chargeflatfeeruninvoicedusage.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != chargeflatfeeruninvoicedusage.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(chargeflatfeeruninvoicedusage.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.LedgerTransactionGroupID(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldLedgerTransactionGroupID, field.TypeString, value) + } + if _u.mutation.LedgerTransactionGroupIDCleared() { + _spec.ClearField(chargeflatfeeruninvoicedusage.FieldLedgerTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeflatfeeruninvoicedusage.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargeflatfeeruninvoicedusage.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesTotal(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldTaxesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldTaxesInclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldTaxesExclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.ChargesTotal(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldChargesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.DiscountsTotal(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldDiscountsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.CreditsTotal(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldCreditsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.Total(); ok { + _spec.SetField(chargeflatfeeruninvoicedusage.FieldTotal, field.TypeOther, value) + } + _node = &ChargeFlatFeeRunInvoicedUsage{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{chargeflatfeeruninvoicedusage.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/ent/db/chargeflatfeerunpayment.go b/ent/db/chargeflatfeerunpayment.go new file mode 100644 index 0000000000000000000000000000000000000000..fcbaf590ce578f16a0db347e13f7e515f685a58f --- /dev/null +++ b/ent/db/chargeflatfeerunpayment.go @@ -0,0 +1,342 @@ +// 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/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerunpayment" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeFlatFeeRunPayment is the model entity for the ChargeFlatFeeRunPayment schema. +type ChargeFlatFeeRunPayment 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"` + // InvoiceID holds the value of the "invoice_id" field. + InvoiceID string `json:"invoice_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 ChargeFlatFeeRunPaymentQuery when eager-loading is set. + Edges ChargeFlatFeeRunPaymentEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ChargeFlatFeeRunPaymentEdges holds the relations/edges for other nodes in the graph. +type ChargeFlatFeeRunPaymentEdges struct { + // BillingInvoiceLine holds the value of the billing_invoice_line edge. + BillingInvoiceLine *BillingInvoiceLine `json:"billing_invoice_line,omitempty"` + // Run holds the value of the run edge. + Run *ChargeFlatFeeRun `json:"run,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// BillingInvoiceLineOrErr returns the BillingInvoiceLine value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeFlatFeeRunPaymentEdges) BillingInvoiceLineOrErr() (*BillingInvoiceLine, error) { + if e.BillingInvoiceLine != nil { + return e.BillingInvoiceLine, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: billinginvoiceline.Label} + } + return nil, &NotLoadedError{edge: "billing_invoice_line"} +} + +// 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 ChargeFlatFeeRunPaymentEdges) RunOrErr() (*ChargeFlatFeeRun, error) { + if e.Run != nil { + return e.Run, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: chargeflatfeerun.Label} + } + return nil, &NotLoadedError{edge: "run"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ChargeFlatFeeRunPayment) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case chargeflatfeerunpayment.FieldAnnotations: + values[i] = new([]byte) + case chargeflatfeerunpayment.FieldAmount: + values[i] = new(alpacadecimal.Decimal) + case chargeflatfeerunpayment.FieldID, chargeflatfeerunpayment.FieldLineID, chargeflatfeerunpayment.FieldInvoiceID, chargeflatfeerunpayment.FieldStatus, chargeflatfeerunpayment.FieldAuthorizedTransactionGroupID, chargeflatfeerunpayment.FieldSettledTransactionGroupID, chargeflatfeerunpayment.FieldNamespace, chargeflatfeerunpayment.FieldRunID: + values[i] = new(sql.NullString) + case chargeflatfeerunpayment.FieldServicePeriodFrom, chargeflatfeerunpayment.FieldServicePeriodTo, chargeflatfeerunpayment.FieldAuthorizedAt, chargeflatfeerunpayment.FieldSettledAt, chargeflatfeerunpayment.FieldCreatedAt, chargeflatfeerunpayment.FieldUpdatedAt, chargeflatfeerunpayment.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 ChargeFlatFeeRunPayment fields. +func (_m *ChargeFlatFeeRunPayment) 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 chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 chargeflatfeerunpayment.FieldInvoiceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field invoice_id", values[i]) + } else if value.Valid { + _m.InvoiceID = value.String + } + case chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 ChargeFlatFeeRunPayment. +// This includes values selected through modifiers, order, etc. +func (_m *ChargeFlatFeeRunPayment) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryBillingInvoiceLine queries the "billing_invoice_line" edge of the ChargeFlatFeeRunPayment entity. +func (_m *ChargeFlatFeeRunPayment) QueryBillingInvoiceLine() *BillingInvoiceLineQuery { + return NewChargeFlatFeeRunPaymentClient(_m.config).QueryBillingInvoiceLine(_m) +} + +// QueryRun queries the "run" edge of the ChargeFlatFeeRunPayment entity. +func (_m *ChargeFlatFeeRunPayment) QueryRun() *ChargeFlatFeeRunQuery { + return NewChargeFlatFeeRunPaymentClient(_m.config).QueryRun(_m) +} + +// Update returns a builder for updating this ChargeFlatFeeRunPayment. +// Note that you need to call ChargeFlatFeeRunPayment.Unwrap() before calling this method if this ChargeFlatFeeRunPayment +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ChargeFlatFeeRunPayment) Update() *ChargeFlatFeeRunPaymentUpdateOne { + return NewChargeFlatFeeRunPaymentClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ChargeFlatFeeRunPayment 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 *ChargeFlatFeeRunPayment) Unwrap() *ChargeFlatFeeRunPayment { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: ChargeFlatFeeRunPayment is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ChargeFlatFeeRunPayment) String() string { + var builder strings.Builder + builder.WriteString("ChargeFlatFeeRunPayment(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("line_id=") + builder.WriteString(_m.LineID) + builder.WriteString(", ") + builder.WriteString("invoice_id=") + builder.WriteString(_m.InvoiceID) + 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() +} + +// ChargeFlatFeeRunPayments is a parsable slice of ChargeFlatFeeRunPayment. +type ChargeFlatFeeRunPayments []*ChargeFlatFeeRunPayment diff --git a/ent/db/chargeflatfeerunpayment/chargeflatfeerunpayment.go b/ent/db/chargeflatfeerunpayment/chargeflatfeerunpayment.go new file mode 100644 index 0000000000000000000000000000000000000000..d9a1c3831a49f4f48d715d29ea06bc7cfbe8bd77 --- /dev/null +++ b/ent/db/chargeflatfeerunpayment/chargeflatfeerunpayment.go @@ -0,0 +1,240 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeflatfeerunpayment + +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 chargeflatfeerunpayment type in the database. + Label = "charge_flat_fee_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" + // FieldInvoiceID holds the string denoting the invoice_id field in the database. + FieldInvoiceID = "invoice_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" + // EdgeBillingInvoiceLine holds the string denoting the billing_invoice_line edge name in mutations. + EdgeBillingInvoiceLine = "billing_invoice_line" + // EdgeRun holds the string denoting the run edge name in mutations. + EdgeRun = "run" + // Table holds the table name of the chargeflatfeerunpayment in the database. + Table = "charge_flat_fee_run_payments" + // BillingInvoiceLineTable is the table that holds the billing_invoice_line relation/edge. + BillingInvoiceLineTable = "charge_flat_fee_run_payments" + // BillingInvoiceLineInverseTable is the table name for the BillingInvoiceLine entity. + // It exists in this package in order to avoid circular dependency with the "billinginvoiceline" package. + BillingInvoiceLineInverseTable = "billing_invoice_lines" + // BillingInvoiceLineColumn is the table column denoting the billing_invoice_line relation/edge. + BillingInvoiceLineColumn = "line_id" + // RunTable is the table that holds the run relation/edge. + RunTable = "charge_flat_fee_run_payments" + // RunInverseTable is the table name for the ChargeFlatFeeRun entity. + // It exists in this package in order to avoid circular dependency with the "chargeflatfeerun" package. + RunInverseTable = "charge_flat_fee_runs" + // RunColumn is the table column denoting the run relation/edge. + RunColumn = "run_id" +) + +// Columns holds all SQL columns for chargeflatfeerunpayment fields. +var Columns = []string{ + FieldID, + FieldLineID, + FieldInvoiceID, + 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("chargeflatfeerunpayment: invalid enum value for status field: %q", s) + } +} + +// OrderOption defines the ordering options for the ChargeFlatFeeRunPayment 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() +} + +// ByInvoiceID orders the results by the invoice_id field. +func ByInvoiceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoiceID, 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() +} + +// ByBillingInvoiceLineField orders the results by billing_invoice_line field. +func ByBillingInvoiceLineField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBillingInvoiceLineStep(), sql.OrderByField(field, opts...)) + } +} + +// 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 newBillingInvoiceLineStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BillingInvoiceLineInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, BillingInvoiceLineTable, BillingInvoiceLineColumn), + ) +} +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/ent/db/chargeflatfeerunpayment/where.go b/ent/db/chargeflatfeerunpayment/where.go new file mode 100644 index 0000000000000000000000000000000000000000..b4176cdace05ae020762702db911ae5facc4b2fa --- /dev/null +++ b/ent/db/chargeflatfeerunpayment/where.go @@ -0,0 +1,999 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeflatfeerunpayment + +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.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldContainsFold(FieldID, id)) +} + +// LineID applies equality check predicate on the "line_id" field. It's identical to LineIDEQ. +func LineID(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldLineID, v)) +} + +// InvoiceID applies equality check predicate on the "invoice_id" field. It's identical to InvoiceIDEQ. +func InvoiceID(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldInvoiceID, v)) +} + +// ServicePeriodFrom applies equality check predicate on the "service_period_from" field. It's identical to ServicePeriodFromEQ. +func ServicePeriodFrom(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(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.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ. +func Amount(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(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.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(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.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(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.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(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.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldSettledAt, v)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(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.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(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.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(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.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldDeletedAt, v)) +} + +// RunID applies equality check predicate on the "run_id" field. It's identical to RunIDEQ. +func RunID(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldRunID, v)) +} + +// LineIDEQ applies the EQ predicate on the "line_id" field. +func LineIDEQ(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldLineID, v)) +} + +// LineIDNEQ applies the NEQ predicate on the "line_id" field. +func LineIDNEQ(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNEQ(FieldLineID, v)) +} + +// LineIDIn applies the In predicate on the "line_id" field. +func LineIDIn(vs ...string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIn(FieldLineID, vs...)) +} + +// LineIDNotIn applies the NotIn predicate on the "line_id" field. +func LineIDNotIn(vs ...string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotIn(FieldLineID, vs...)) +} + +// LineIDGT applies the GT predicate on the "line_id" field. +func LineIDGT(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGT(FieldLineID, v)) +} + +// LineIDGTE applies the GTE predicate on the "line_id" field. +func LineIDGTE(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGTE(FieldLineID, v)) +} + +// LineIDLT applies the LT predicate on the "line_id" field. +func LineIDLT(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLT(FieldLineID, v)) +} + +// LineIDLTE applies the LTE predicate on the "line_id" field. +func LineIDLTE(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLTE(FieldLineID, v)) +} + +// LineIDContains applies the Contains predicate on the "line_id" field. +func LineIDContains(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldContains(FieldLineID, v)) +} + +// LineIDHasPrefix applies the HasPrefix predicate on the "line_id" field. +func LineIDHasPrefix(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldHasPrefix(FieldLineID, v)) +} + +// LineIDHasSuffix applies the HasSuffix predicate on the "line_id" field. +func LineIDHasSuffix(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldHasSuffix(FieldLineID, v)) +} + +// LineIDEqualFold applies the EqualFold predicate on the "line_id" field. +func LineIDEqualFold(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEqualFold(FieldLineID, v)) +} + +// LineIDContainsFold applies the ContainsFold predicate on the "line_id" field. +func LineIDContainsFold(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldContainsFold(FieldLineID, v)) +} + +// InvoiceIDEQ applies the EQ predicate on the "invoice_id" field. +func InvoiceIDEQ(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldInvoiceID, v)) +} + +// InvoiceIDNEQ applies the NEQ predicate on the "invoice_id" field. +func InvoiceIDNEQ(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNEQ(FieldInvoiceID, v)) +} + +// InvoiceIDIn applies the In predicate on the "invoice_id" field. +func InvoiceIDIn(vs ...string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIn(FieldInvoiceID, vs...)) +} + +// InvoiceIDNotIn applies the NotIn predicate on the "invoice_id" field. +func InvoiceIDNotIn(vs ...string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotIn(FieldInvoiceID, vs...)) +} + +// InvoiceIDGT applies the GT predicate on the "invoice_id" field. +func InvoiceIDGT(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGT(FieldInvoiceID, v)) +} + +// InvoiceIDGTE applies the GTE predicate on the "invoice_id" field. +func InvoiceIDGTE(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGTE(FieldInvoiceID, v)) +} + +// InvoiceIDLT applies the LT predicate on the "invoice_id" field. +func InvoiceIDLT(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLT(FieldInvoiceID, v)) +} + +// InvoiceIDLTE applies the LTE predicate on the "invoice_id" field. +func InvoiceIDLTE(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLTE(FieldInvoiceID, v)) +} + +// InvoiceIDContains applies the Contains predicate on the "invoice_id" field. +func InvoiceIDContains(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldContains(FieldInvoiceID, v)) +} + +// InvoiceIDHasPrefix applies the HasPrefix predicate on the "invoice_id" field. +func InvoiceIDHasPrefix(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldHasPrefix(FieldInvoiceID, v)) +} + +// InvoiceIDHasSuffix applies the HasSuffix predicate on the "invoice_id" field. +func InvoiceIDHasSuffix(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldHasSuffix(FieldInvoiceID, v)) +} + +// InvoiceIDEqualFold applies the EqualFold predicate on the "invoice_id" field. +func InvoiceIDEqualFold(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEqualFold(FieldInvoiceID, v)) +} + +// InvoiceIDContainsFold applies the ContainsFold predicate on the "invoice_id" field. +func InvoiceIDContainsFold(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldContainsFold(FieldInvoiceID, v)) +} + +// ServicePeriodFromEQ applies the EQ predicate on the "service_period_from" field. +func ServicePeriodFromEQ(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromNEQ applies the NEQ predicate on the "service_period_from" field. +func ServicePeriodFromNEQ(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromIn applies the In predicate on the "service_period_from" field. +func ServicePeriodFromIn(vs ...time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromNotIn applies the NotIn predicate on the "service_period_from" field. +func ServicePeriodFromNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromGT applies the GT predicate on the "service_period_from" field. +func ServicePeriodFromGT(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromGTE applies the GTE predicate on the "service_period_from" field. +func ServicePeriodFromGTE(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLT applies the LT predicate on the "service_period_from" field. +func ServicePeriodFromLT(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLTE applies the LTE predicate on the "service_period_from" field. +func ServicePeriodFromLTE(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodToEQ applies the EQ predicate on the "service_period_to" field. +func ServicePeriodToEQ(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToNEQ applies the NEQ predicate on the "service_period_to" field. +func ServicePeriodToNEQ(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToIn applies the In predicate on the "service_period_to" field. +func ServicePeriodToIn(vs ...time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToNotIn applies the NotIn predicate on the "service_period_to" field. +func ServicePeriodToNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToGT applies the GT predicate on the "service_period_to" field. +func ServicePeriodToGT(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToGTE applies the GTE predicate on the "service_period_to" field. +func ServicePeriodToGTE(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGTE(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLT applies the LT predicate on the "service_period_to" field. +func ServicePeriodToLT(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLTE applies the LTE predicate on the "service_period_to" field. +func ServicePeriodToLTE(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLTE(FieldServicePeriodTo, v)) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v payment.Status) predicate.ChargeFlatFeeRunPayment { + vc := v + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldStatus, vc)) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v payment.Status) predicate.ChargeFlatFeeRunPayment { + vc := v + return predicate.ChargeFlatFeeRunPayment(sql.FieldNEQ(FieldStatus, vc)) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...payment.Status) predicate.ChargeFlatFeeRunPayment { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFeeRunPayment(sql.FieldIn(FieldStatus, v...)) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...payment.Status) predicate.ChargeFlatFeeRunPayment { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotIn(FieldStatus, v...)) +} + +// AmountEQ applies the EQ predicate on the "amount" field. +func AmountEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldAmount, v)) +} + +// AmountNEQ applies the NEQ predicate on the "amount" field. +func AmountNEQ(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNEQ(FieldAmount, v)) +} + +// AmountIn applies the In predicate on the "amount" field. +func AmountIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIn(FieldAmount, vs...)) +} + +// AmountNotIn applies the NotIn predicate on the "amount" field. +func AmountNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotIn(FieldAmount, vs...)) +} + +// AmountGT applies the GT predicate on the "amount" field. +func AmountGT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGT(FieldAmount, v)) +} + +// AmountGTE applies the GTE predicate on the "amount" field. +func AmountGTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGTE(FieldAmount, v)) +} + +// AmountLT applies the LT predicate on the "amount" field. +func AmountLT(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLT(FieldAmount, v)) +} + +// AmountLTE applies the LTE predicate on the "amount" field. +func AmountLTE(v alpacadecimal.Decimal) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLTE(FieldAmount, v)) +} + +// AuthorizedTransactionGroupIDEQ applies the EQ predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDEQ(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDNEQ applies the NEQ predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDNEQ(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNEQ(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDIn applies the In predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDIn(vs ...string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIn(FieldAuthorizedTransactionGroupID, vs...)) +} + +// AuthorizedTransactionGroupIDNotIn applies the NotIn predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDNotIn(vs ...string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotIn(FieldAuthorizedTransactionGroupID, vs...)) +} + +// AuthorizedTransactionGroupIDGT applies the GT predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDGT(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGT(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDGTE applies the GTE predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDGTE(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGTE(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDLT applies the LT predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDLT(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLT(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDLTE applies the LTE predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDLTE(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLTE(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDContains applies the Contains predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDContains(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldContains(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDHasPrefix applies the HasPrefix predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDHasPrefix(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldHasPrefix(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDHasSuffix applies the HasSuffix predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDHasSuffix(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldHasSuffix(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDIsNil applies the IsNil predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDIsNil() predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIsNull(FieldAuthorizedTransactionGroupID)) +} + +// AuthorizedTransactionGroupIDNotNil applies the NotNil predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDNotNil() predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotNull(FieldAuthorizedTransactionGroupID)) +} + +// AuthorizedTransactionGroupIDEqualFold applies the EqualFold predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDEqualFold(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEqualFold(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDContainsFold applies the ContainsFold predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDContainsFold(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldContainsFold(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedAtEQ applies the EQ predicate on the "authorized_at" field. +func AuthorizedAtEQ(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldAuthorizedAt, v)) +} + +// AuthorizedAtNEQ applies the NEQ predicate on the "authorized_at" field. +func AuthorizedAtNEQ(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNEQ(FieldAuthorizedAt, v)) +} + +// AuthorizedAtIn applies the In predicate on the "authorized_at" field. +func AuthorizedAtIn(vs ...time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIn(FieldAuthorizedAt, vs...)) +} + +// AuthorizedAtNotIn applies the NotIn predicate on the "authorized_at" field. +func AuthorizedAtNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotIn(FieldAuthorizedAt, vs...)) +} + +// AuthorizedAtGT applies the GT predicate on the "authorized_at" field. +func AuthorizedAtGT(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGT(FieldAuthorizedAt, v)) +} + +// AuthorizedAtGTE applies the GTE predicate on the "authorized_at" field. +func AuthorizedAtGTE(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGTE(FieldAuthorizedAt, v)) +} + +// AuthorizedAtLT applies the LT predicate on the "authorized_at" field. +func AuthorizedAtLT(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLT(FieldAuthorizedAt, v)) +} + +// AuthorizedAtLTE applies the LTE predicate on the "authorized_at" field. +func AuthorizedAtLTE(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLTE(FieldAuthorizedAt, v)) +} + +// AuthorizedAtIsNil applies the IsNil predicate on the "authorized_at" field. +func AuthorizedAtIsNil() predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIsNull(FieldAuthorizedAt)) +} + +// AuthorizedAtNotNil applies the NotNil predicate on the "authorized_at" field. +func AuthorizedAtNotNil() predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotNull(FieldAuthorizedAt)) +} + +// SettledTransactionGroupIDEQ applies the EQ predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDEQ(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDNEQ applies the NEQ predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDNEQ(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNEQ(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDIn applies the In predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDIn(vs ...string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIn(FieldSettledTransactionGroupID, vs...)) +} + +// SettledTransactionGroupIDNotIn applies the NotIn predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDNotIn(vs ...string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotIn(FieldSettledTransactionGroupID, vs...)) +} + +// SettledTransactionGroupIDGT applies the GT predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDGT(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGT(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDGTE applies the GTE predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDGTE(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGTE(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDLT applies the LT predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDLT(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLT(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDLTE applies the LTE predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDLTE(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLTE(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDContains applies the Contains predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDContains(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldContains(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDHasPrefix applies the HasPrefix predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDHasPrefix(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldHasPrefix(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDHasSuffix applies the HasSuffix predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDHasSuffix(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldHasSuffix(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDIsNil applies the IsNil predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDIsNil() predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIsNull(FieldSettledTransactionGroupID)) +} + +// SettledTransactionGroupIDNotNil applies the NotNil predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDNotNil() predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotNull(FieldSettledTransactionGroupID)) +} + +// SettledTransactionGroupIDEqualFold applies the EqualFold predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDEqualFold(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEqualFold(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDContainsFold applies the ContainsFold predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDContainsFold(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldContainsFold(FieldSettledTransactionGroupID, v)) +} + +// SettledAtEQ applies the EQ predicate on the "settled_at" field. +func SettledAtEQ(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldSettledAt, v)) +} + +// SettledAtNEQ applies the NEQ predicate on the "settled_at" field. +func SettledAtNEQ(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNEQ(FieldSettledAt, v)) +} + +// SettledAtIn applies the In predicate on the "settled_at" field. +func SettledAtIn(vs ...time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIn(FieldSettledAt, vs...)) +} + +// SettledAtNotIn applies the NotIn predicate on the "settled_at" field. +func SettledAtNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotIn(FieldSettledAt, vs...)) +} + +// SettledAtGT applies the GT predicate on the "settled_at" field. +func SettledAtGT(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGT(FieldSettledAt, v)) +} + +// SettledAtGTE applies the GTE predicate on the "settled_at" field. +func SettledAtGTE(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGTE(FieldSettledAt, v)) +} + +// SettledAtLT applies the LT predicate on the "settled_at" field. +func SettledAtLT(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLT(FieldSettledAt, v)) +} + +// SettledAtLTE applies the LTE predicate on the "settled_at" field. +func SettledAtLTE(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLTE(FieldSettledAt, v)) +} + +// SettledAtIsNil applies the IsNil predicate on the "settled_at" field. +func SettledAtIsNil() predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIsNull(FieldSettledAt)) +} + +// SettledAtNotNil applies the NotNil predicate on the "settled_at" field. +func SettledAtNotNil() predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotNull(FieldSettledAt)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotNull(FieldDeletedAt)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotNull(FieldAnnotations)) +} + +// RunIDEQ applies the EQ predicate on the "run_id" field. +func RunIDEQ(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEQ(FieldRunID, v)) +} + +// RunIDNEQ applies the NEQ predicate on the "run_id" field. +func RunIDNEQ(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNEQ(FieldRunID, v)) +} + +// RunIDIn applies the In predicate on the "run_id" field. +func RunIDIn(vs ...string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldIn(FieldRunID, vs...)) +} + +// RunIDNotIn applies the NotIn predicate on the "run_id" field. +func RunIDNotIn(vs ...string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldNotIn(FieldRunID, vs...)) +} + +// RunIDGT applies the GT predicate on the "run_id" field. +func RunIDGT(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGT(FieldRunID, v)) +} + +// RunIDGTE applies the GTE predicate on the "run_id" field. +func RunIDGTE(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldGTE(FieldRunID, v)) +} + +// RunIDLT applies the LT predicate on the "run_id" field. +func RunIDLT(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLT(FieldRunID, v)) +} + +// RunIDLTE applies the LTE predicate on the "run_id" field. +func RunIDLTE(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldLTE(FieldRunID, v)) +} + +// RunIDContains applies the Contains predicate on the "run_id" field. +func RunIDContains(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldContains(FieldRunID, v)) +} + +// RunIDHasPrefix applies the HasPrefix predicate on the "run_id" field. +func RunIDHasPrefix(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldHasPrefix(FieldRunID, v)) +} + +// RunIDHasSuffix applies the HasSuffix predicate on the "run_id" field. +func RunIDHasSuffix(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldHasSuffix(FieldRunID, v)) +} + +// RunIDEqualFold applies the EqualFold predicate on the "run_id" field. +func RunIDEqualFold(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldEqualFold(FieldRunID, v)) +} + +// RunIDContainsFold applies the ContainsFold predicate on the "run_id" field. +func RunIDContainsFold(v string) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.FieldContainsFold(FieldRunID, v)) +} + +// HasBillingInvoiceLine applies the HasEdge predicate on the "billing_invoice_line" edge. +func HasBillingInvoiceLine() predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, BillingInvoiceLineTable, BillingInvoiceLineColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBillingInvoiceLineWith applies the HasEdge predicate on the "billing_invoice_line" edge with a given conditions (other predicates). +func HasBillingInvoiceLineWith(preds ...predicate.BillingInvoiceLine) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(func(s *sql.Selector) { + step := newBillingInvoiceLineStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasRun applies the HasEdge predicate on the "run" edge. +func HasRun() predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(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.ChargeFlatFeeRun) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(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.ChargeFlatFeeRunPayment) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ChargeFlatFeeRunPayment) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ChargeFlatFeeRunPayment) predicate.ChargeFlatFeeRunPayment { + return predicate.ChargeFlatFeeRunPayment(sql.NotPredicates(p)) +} diff --git a/ent/db/chargeflatfeerunpayment_create.go b/ent/db/chargeflatfeerunpayment_create.go new file mode 100644 index 0000000000000000000000000000000000000000..60b614004c65f03dfc05f565137d0032d2667fc0 --- /dev/null +++ b/ent/db/chargeflatfeerunpayment_create.go @@ -0,0 +1,1372 @@ +// 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/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerunpayment" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeFlatFeeRunPaymentCreate is the builder for creating a ChargeFlatFeeRunPayment entity. +type ChargeFlatFeeRunPaymentCreate struct { + config + mutation *ChargeFlatFeeRunPaymentMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetLineID sets the "line_id" field. +func (_c *ChargeFlatFeeRunPaymentCreate) SetLineID(v string) *ChargeFlatFeeRunPaymentCreate { + _c.mutation.SetLineID(v) + return _c +} + +// SetInvoiceID sets the "invoice_id" field. +func (_c *ChargeFlatFeeRunPaymentCreate) SetInvoiceID(v string) *ChargeFlatFeeRunPaymentCreate { + _c.mutation.SetInvoiceID(v) + return _c +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_c *ChargeFlatFeeRunPaymentCreate) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunPaymentCreate { + _c.mutation.SetServicePeriodFrom(v) + return _c +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_c *ChargeFlatFeeRunPaymentCreate) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunPaymentCreate { + _c.mutation.SetServicePeriodTo(v) + return _c +} + +// SetStatus sets the "status" field. +func (_c *ChargeFlatFeeRunPaymentCreate) SetStatus(v payment.Status) *ChargeFlatFeeRunPaymentCreate { + _c.mutation.SetStatus(v) + return _c +} + +// SetAmount sets the "amount" field. +func (_c *ChargeFlatFeeRunPaymentCreate) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunPaymentCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (_c *ChargeFlatFeeRunPaymentCreate) SetAuthorizedTransactionGroupID(v string) *ChargeFlatFeeRunPaymentCreate { + _c.mutation.SetAuthorizedTransactionGroupID(v) + return _c +} + +// SetNillableAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field if the given value is not nil. +func (_c *ChargeFlatFeeRunPaymentCreate) SetNillableAuthorizedTransactionGroupID(v *string) *ChargeFlatFeeRunPaymentCreate { + if v != nil { + _c.SetAuthorizedTransactionGroupID(*v) + } + return _c +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (_c *ChargeFlatFeeRunPaymentCreate) SetAuthorizedAt(v time.Time) *ChargeFlatFeeRunPaymentCreate { + _c.mutation.SetAuthorizedAt(v) + return _c +} + +// SetNillableAuthorizedAt sets the "authorized_at" field if the given value is not nil. +func (_c *ChargeFlatFeeRunPaymentCreate) SetNillableAuthorizedAt(v *time.Time) *ChargeFlatFeeRunPaymentCreate { + if v != nil { + _c.SetAuthorizedAt(*v) + } + return _c +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (_c *ChargeFlatFeeRunPaymentCreate) SetSettledTransactionGroupID(v string) *ChargeFlatFeeRunPaymentCreate { + _c.mutation.SetSettledTransactionGroupID(v) + return _c +} + +// SetNillableSettledTransactionGroupID sets the "settled_transaction_group_id" field if the given value is not nil. +func (_c *ChargeFlatFeeRunPaymentCreate) SetNillableSettledTransactionGroupID(v *string) *ChargeFlatFeeRunPaymentCreate { + if v != nil { + _c.SetSettledTransactionGroupID(*v) + } + return _c +} + +// SetSettledAt sets the "settled_at" field. +func (_c *ChargeFlatFeeRunPaymentCreate) SetSettledAt(v time.Time) *ChargeFlatFeeRunPaymentCreate { + _c.mutation.SetSettledAt(v) + return _c +} + +// SetNillableSettledAt sets the "settled_at" field if the given value is not nil. +func (_c *ChargeFlatFeeRunPaymentCreate) SetNillableSettledAt(v *time.Time) *ChargeFlatFeeRunPaymentCreate { + if v != nil { + _c.SetSettledAt(*v) + } + return _c +} + +// SetNamespace sets the "namespace" field. +func (_c *ChargeFlatFeeRunPaymentCreate) SetNamespace(v string) *ChargeFlatFeeRunPaymentCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ChargeFlatFeeRunPaymentCreate) SetCreatedAt(v time.Time) *ChargeFlatFeeRunPaymentCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *ChargeFlatFeeRunPaymentCreate) SetNillableCreatedAt(v *time.Time) *ChargeFlatFeeRunPaymentCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *ChargeFlatFeeRunPaymentCreate) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunPaymentCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *ChargeFlatFeeRunPaymentCreate) SetNillableUpdatedAt(v *time.Time) *ChargeFlatFeeRunPaymentCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *ChargeFlatFeeRunPaymentCreate) SetDeletedAt(v time.Time) *ChargeFlatFeeRunPaymentCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *ChargeFlatFeeRunPaymentCreate) SetNillableDeletedAt(v *time.Time) *ChargeFlatFeeRunPaymentCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *ChargeFlatFeeRunPaymentCreate) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunPaymentCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetRunID sets the "run_id" field. +func (_c *ChargeFlatFeeRunPaymentCreate) SetRunID(v string) *ChargeFlatFeeRunPaymentCreate { + _c.mutation.SetRunID(v) + return _c +} + +// SetID sets the "id" field. +func (_c *ChargeFlatFeeRunPaymentCreate) SetID(v string) *ChargeFlatFeeRunPaymentCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ChargeFlatFeeRunPaymentCreate) SetNillableID(v *string) *ChargeFlatFeeRunPaymentCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID. +func (_c *ChargeFlatFeeRunPaymentCreate) SetBillingInvoiceLineID(id string) *ChargeFlatFeeRunPaymentCreate { + _c.mutation.SetBillingInvoiceLineID(id) + return _c +} + +// SetBillingInvoiceLine sets the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_c *ChargeFlatFeeRunPaymentCreate) SetBillingInvoiceLine(v *BillingInvoiceLine) *ChargeFlatFeeRunPaymentCreate { + return _c.SetBillingInvoiceLineID(v.ID) +} + +// SetRun sets the "run" edge to the ChargeFlatFeeRun entity. +func (_c *ChargeFlatFeeRunPaymentCreate) SetRun(v *ChargeFlatFeeRun) *ChargeFlatFeeRunPaymentCreate { + return _c.SetRunID(v.ID) +} + +// Mutation returns the ChargeFlatFeeRunPaymentMutation object of the builder. +func (_c *ChargeFlatFeeRunPaymentCreate) Mutation() *ChargeFlatFeeRunPaymentMutation { + return _c.mutation +} + +// Save creates the ChargeFlatFeeRunPayment in the database. +func (_c *ChargeFlatFeeRunPaymentCreate) Save(ctx context.Context) (*ChargeFlatFeeRunPayment, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ChargeFlatFeeRunPaymentCreate) SaveX(ctx context.Context) *ChargeFlatFeeRunPayment { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeFlatFeeRunPaymentCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeFlatFeeRunPaymentCreate) 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 *ChargeFlatFeeRunPaymentCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := chargeflatfeerunpayment.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := chargeflatfeerunpayment.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := chargeflatfeerunpayment.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ChargeFlatFeeRunPaymentCreate) check() error { + if _, ok := _c.mutation.LineID(); !ok { + return &ValidationError{Name: "line_id", err: errors.New(`db: missing required field "ChargeFlatFeeRunPayment.line_id"`)} + } + if _, ok := _c.mutation.InvoiceID(); !ok { + return &ValidationError{Name: "invoice_id", err: errors.New(`db: missing required field "ChargeFlatFeeRunPayment.invoice_id"`)} + } + if _, ok := _c.mutation.ServicePeriodFrom(); !ok { + return &ValidationError{Name: "service_period_from", err: errors.New(`db: missing required field "ChargeFlatFeeRunPayment.service_period_from"`)} + } + if _, ok := _c.mutation.ServicePeriodTo(); !ok { + return &ValidationError{Name: "service_period_to", err: errors.New(`db: missing required field "ChargeFlatFeeRunPayment.service_period_to"`)} + } + if _, ok := _c.mutation.Status(); !ok { + return &ValidationError{Name: "status", err: errors.New(`db: missing required field "ChargeFlatFeeRunPayment.status"`)} + } + if v, ok := _c.mutation.Status(); ok { + if err := chargeflatfeerunpayment.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunPayment.status": %w`, err)} + } + } + if _, ok := _c.mutation.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`db: missing required field "ChargeFlatFeeRunPayment.amount"`)} + } + if v, ok := _c.mutation.AuthorizedTransactionGroupID(); ok { + if err := chargeflatfeerunpayment.AuthorizedTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "authorized_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunPayment.authorized_transaction_group_id": %w`, err)} + } + } + if v, ok := _c.mutation.SettledTransactionGroupID(); ok { + if err := chargeflatfeerunpayment.SettledTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "settled_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunPayment.settled_transaction_group_id": %w`, err)} + } + } + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "ChargeFlatFeeRunPayment.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := chargeflatfeerunpayment.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunPayment.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "ChargeFlatFeeRunPayment.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "ChargeFlatFeeRunPayment.updated_at"`)} + } + if _, ok := _c.mutation.RunID(); !ok { + return &ValidationError{Name: "run_id", err: errors.New(`db: missing required field "ChargeFlatFeeRunPayment.run_id"`)} + } + if len(_c.mutation.BillingInvoiceLineIDs()) == 0 { + return &ValidationError{Name: "billing_invoice_line", err: errors.New(`db: missing required edge "ChargeFlatFeeRunPayment.billing_invoice_line"`)} + } + if len(_c.mutation.RunIDs()) == 0 { + return &ValidationError{Name: "run", err: errors.New(`db: missing required edge "ChargeFlatFeeRunPayment.run"`)} + } + return nil +} + +func (_c *ChargeFlatFeeRunPaymentCreate) sqlSave(ctx context.Context) (*ChargeFlatFeeRunPayment, 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 ChargeFlatFeeRunPayment.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ChargeFlatFeeRunPaymentCreate) createSpec() (*ChargeFlatFeeRunPayment, *sqlgraph.CreateSpec) { + var ( + _node = &ChargeFlatFeeRunPayment{config: _c.config} + _spec = sqlgraph.NewCreateSpec(chargeflatfeerunpayment.Table, sqlgraph.NewFieldSpec(chargeflatfeerunpayment.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.InvoiceID(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldInvoiceID, field.TypeString, value) + _node.InvoiceID = value + } + if value, ok := _c.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldServicePeriodFrom, field.TypeTime, value) + _node.ServicePeriodFrom = value + } + if value, ok := _c.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldServicePeriodTo, field.TypeTime, value) + _node.ServicePeriodTo = value + } + if value, ok := _c.mutation.Status(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldStatus, field.TypeEnum, value) + _node.Status = value + } + if value, ok := _c.mutation.Amount(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldAmount, field.TypeOther, value) + _node.Amount = value + } + if value, ok := _c.mutation.AuthorizedTransactionGroupID(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldAuthorizedTransactionGroupID, field.TypeString, value) + _node.AuthorizedTransactionGroupID = &value + } + if value, ok := _c.mutation.AuthorizedAt(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldAuthorizedAt, field.TypeTime, value) + _node.AuthorizedAt = &value + } + if value, ok := _c.mutation.SettledTransactionGroupID(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldSettledTransactionGroupID, field.TypeString, value) + _node.SettledTransactionGroupID = &value + } + if value, ok := _c.mutation.SettledAt(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldSettledAt, field.TypeTime, value) + _node.SettledAt = &value + } + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if nodes := _c.mutation.BillingInvoiceLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeflatfeerunpayment.BillingInvoiceLineTable, + Columns: []string{chargeflatfeerunpayment.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.LineID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.RunIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeflatfeerunpayment.RunTable, + Columns: []string{chargeflatfeerunpayment.RunColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfeerun.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.ChargeFlatFeeRunPayment.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.ChargeFlatFeeRunPaymentUpsert) { +// SetLineID(v+v). +// }). +// Exec(ctx) +func (_c *ChargeFlatFeeRunPaymentCreate) OnConflict(opts ...sql.ConflictOption) *ChargeFlatFeeRunPaymentUpsertOne { + _c.conflict = opts + return &ChargeFlatFeeRunPaymentUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeFlatFeeRunPayment.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeFlatFeeRunPaymentCreate) OnConflictColumns(columns ...string) *ChargeFlatFeeRunPaymentUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeFlatFeeRunPaymentUpsertOne{ + create: _c, + } +} + +type ( + // ChargeFlatFeeRunPaymentUpsertOne is the builder for "upsert"-ing + // one ChargeFlatFeeRunPayment node. + ChargeFlatFeeRunPaymentUpsertOne struct { + create *ChargeFlatFeeRunPaymentCreate + } + + // ChargeFlatFeeRunPaymentUpsert is the "OnConflict" setter. + ChargeFlatFeeRunPaymentUpsert struct { + *sql.UpdateSet + } +) + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeFlatFeeRunPaymentUpsert) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunPaymentUpsert { + u.Set(chargeflatfeerunpayment.FieldServicePeriodFrom, v) + return u +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsert) UpdateServicePeriodFrom() *ChargeFlatFeeRunPaymentUpsert { + u.SetExcluded(chargeflatfeerunpayment.FieldServicePeriodFrom) + return u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeFlatFeeRunPaymentUpsert) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunPaymentUpsert { + u.Set(chargeflatfeerunpayment.FieldServicePeriodTo, v) + return u +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsert) UpdateServicePeriodTo() *ChargeFlatFeeRunPaymentUpsert { + u.SetExcluded(chargeflatfeerunpayment.FieldServicePeriodTo) + return u +} + +// SetStatus sets the "status" field. +func (u *ChargeFlatFeeRunPaymentUpsert) SetStatus(v payment.Status) *ChargeFlatFeeRunPaymentUpsert { + u.Set(chargeflatfeerunpayment.FieldStatus, v) + return u +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsert) UpdateStatus() *ChargeFlatFeeRunPaymentUpsert { + u.SetExcluded(chargeflatfeerunpayment.FieldStatus) + return u +} + +// SetAmount sets the "amount" field. +func (u *ChargeFlatFeeRunPaymentUpsert) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunPaymentUpsert { + u.Set(chargeflatfeerunpayment.FieldAmount, v) + return u +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsert) UpdateAmount() *ChargeFlatFeeRunPaymentUpsert { + u.SetExcluded(chargeflatfeerunpayment.FieldAmount) + return u +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (u *ChargeFlatFeeRunPaymentUpsert) SetAuthorizedTransactionGroupID(v string) *ChargeFlatFeeRunPaymentUpsert { + u.Set(chargeflatfeerunpayment.FieldAuthorizedTransactionGroupID, v) + return u +} + +// UpdateAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsert) UpdateAuthorizedTransactionGroupID() *ChargeFlatFeeRunPaymentUpsert { + u.SetExcluded(chargeflatfeerunpayment.FieldAuthorizedTransactionGroupID) + return u +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (u *ChargeFlatFeeRunPaymentUpsert) ClearAuthorizedTransactionGroupID() *ChargeFlatFeeRunPaymentUpsert { + u.SetNull(chargeflatfeerunpayment.FieldAuthorizedTransactionGroupID) + return u +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (u *ChargeFlatFeeRunPaymentUpsert) SetAuthorizedAt(v time.Time) *ChargeFlatFeeRunPaymentUpsert { + u.Set(chargeflatfeerunpayment.FieldAuthorizedAt, v) + return u +} + +// UpdateAuthorizedAt sets the "authorized_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsert) UpdateAuthorizedAt() *ChargeFlatFeeRunPaymentUpsert { + u.SetExcluded(chargeflatfeerunpayment.FieldAuthorizedAt) + return u +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (u *ChargeFlatFeeRunPaymentUpsert) ClearAuthorizedAt() *ChargeFlatFeeRunPaymentUpsert { + u.SetNull(chargeflatfeerunpayment.FieldAuthorizedAt) + return u +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (u *ChargeFlatFeeRunPaymentUpsert) SetSettledTransactionGroupID(v string) *ChargeFlatFeeRunPaymentUpsert { + u.Set(chargeflatfeerunpayment.FieldSettledTransactionGroupID, v) + return u +} + +// UpdateSettledTransactionGroupID sets the "settled_transaction_group_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsert) UpdateSettledTransactionGroupID() *ChargeFlatFeeRunPaymentUpsert { + u.SetExcluded(chargeflatfeerunpayment.FieldSettledTransactionGroupID) + return u +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (u *ChargeFlatFeeRunPaymentUpsert) ClearSettledTransactionGroupID() *ChargeFlatFeeRunPaymentUpsert { + u.SetNull(chargeflatfeerunpayment.FieldSettledTransactionGroupID) + return u +} + +// SetSettledAt sets the "settled_at" field. +func (u *ChargeFlatFeeRunPaymentUpsert) SetSettledAt(v time.Time) *ChargeFlatFeeRunPaymentUpsert { + u.Set(chargeflatfeerunpayment.FieldSettledAt, v) + return u +} + +// UpdateSettledAt sets the "settled_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsert) UpdateSettledAt() *ChargeFlatFeeRunPaymentUpsert { + u.SetExcluded(chargeflatfeerunpayment.FieldSettledAt) + return u +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (u *ChargeFlatFeeRunPaymentUpsert) ClearSettledAt() *ChargeFlatFeeRunPaymentUpsert { + u.SetNull(chargeflatfeerunpayment.FieldSettledAt) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeFlatFeeRunPaymentUpsert) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunPaymentUpsert { + u.Set(chargeflatfeerunpayment.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsert) UpdateUpdatedAt() *ChargeFlatFeeRunPaymentUpsert { + u.SetExcluded(chargeflatfeerunpayment.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeFlatFeeRunPaymentUpsert) SetDeletedAt(v time.Time) *ChargeFlatFeeRunPaymentUpsert { + u.Set(chargeflatfeerunpayment.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsert) UpdateDeletedAt() *ChargeFlatFeeRunPaymentUpsert { + u.SetExcluded(chargeflatfeerunpayment.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeFlatFeeRunPaymentUpsert) ClearDeletedAt() *ChargeFlatFeeRunPaymentUpsert { + u.SetNull(chargeflatfeerunpayment.FieldDeletedAt) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeFlatFeeRunPaymentUpsert) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunPaymentUpsert { + u.Set(chargeflatfeerunpayment.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsert) UpdateAnnotations() *ChargeFlatFeeRunPaymentUpsert { + u.SetExcluded(chargeflatfeerunpayment.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeFlatFeeRunPaymentUpsert) ClearAnnotations() *ChargeFlatFeeRunPaymentUpsert { + u.SetNull(chargeflatfeerunpayment.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.ChargeFlatFeeRunPayment.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeflatfeerunpayment.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeFlatFeeRunPaymentUpsertOne) UpdateNewValues() *ChargeFlatFeeRunPaymentUpsertOne { + 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(chargeflatfeerunpayment.FieldID) + } + if _, exists := u.create.mutation.LineID(); exists { + s.SetIgnore(chargeflatfeerunpayment.FieldLineID) + } + if _, exists := u.create.mutation.InvoiceID(); exists { + s.SetIgnore(chargeflatfeerunpayment.FieldInvoiceID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(chargeflatfeerunpayment.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(chargeflatfeerunpayment.FieldCreatedAt) + } + if _, exists := u.create.mutation.RunID(); exists { + s.SetIgnore(chargeflatfeerunpayment.FieldRunID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeFlatFeeRunPayment.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeFlatFeeRunPaymentUpsertOne) Ignore() *ChargeFlatFeeRunPaymentUpsertOne { + 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 *ChargeFlatFeeRunPaymentUpsertOne) DoNothing() *ChargeFlatFeeRunPaymentUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeFlatFeeRunPaymentCreate.OnConflict +// documentation for more info. +func (u *ChargeFlatFeeRunPaymentUpsertOne) Update(set func(*ChargeFlatFeeRunPaymentUpsert)) *ChargeFlatFeeRunPaymentUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeFlatFeeRunPaymentUpsert{UpdateSet: update}) + })) + return u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeFlatFeeRunPaymentUpsertOne) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertOne) UpdateServicePeriodFrom() *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeFlatFeeRunPaymentUpsertOne) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertOne) UpdateServicePeriodTo() *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetStatus sets the "status" field. +func (u *ChargeFlatFeeRunPaymentUpsertOne) SetStatus(v payment.Status) *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertOne) UpdateStatus() *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateStatus() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeFlatFeeRunPaymentUpsertOne) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertOne) UpdateAmount() *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateAmount() + }) +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (u *ChargeFlatFeeRunPaymentUpsertOne) SetAuthorizedTransactionGroupID(v string) *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetAuthorizedTransactionGroupID(v) + }) +} + +// UpdateAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertOne) UpdateAuthorizedTransactionGroupID() *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateAuthorizedTransactionGroupID() + }) +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (u *ChargeFlatFeeRunPaymentUpsertOne) ClearAuthorizedTransactionGroupID() *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.ClearAuthorizedTransactionGroupID() + }) +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (u *ChargeFlatFeeRunPaymentUpsertOne) SetAuthorizedAt(v time.Time) *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetAuthorizedAt(v) + }) +} + +// UpdateAuthorizedAt sets the "authorized_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertOne) UpdateAuthorizedAt() *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateAuthorizedAt() + }) +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (u *ChargeFlatFeeRunPaymentUpsertOne) ClearAuthorizedAt() *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.ClearAuthorizedAt() + }) +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (u *ChargeFlatFeeRunPaymentUpsertOne) SetSettledTransactionGroupID(v string) *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetSettledTransactionGroupID(v) + }) +} + +// UpdateSettledTransactionGroupID sets the "settled_transaction_group_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertOne) UpdateSettledTransactionGroupID() *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateSettledTransactionGroupID() + }) +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (u *ChargeFlatFeeRunPaymentUpsertOne) ClearSettledTransactionGroupID() *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.ClearSettledTransactionGroupID() + }) +} + +// SetSettledAt sets the "settled_at" field. +func (u *ChargeFlatFeeRunPaymentUpsertOne) SetSettledAt(v time.Time) *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetSettledAt(v) + }) +} + +// UpdateSettledAt sets the "settled_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertOne) UpdateSettledAt() *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateSettledAt() + }) +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (u *ChargeFlatFeeRunPaymentUpsertOne) ClearSettledAt() *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.ClearSettledAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeFlatFeeRunPaymentUpsertOne) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertOne) UpdateUpdatedAt() *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeFlatFeeRunPaymentUpsertOne) SetDeletedAt(v time.Time) *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertOne) UpdateDeletedAt() *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeFlatFeeRunPaymentUpsertOne) ClearDeletedAt() *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeFlatFeeRunPaymentUpsertOne) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertOne) UpdateAnnotations() *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeFlatFeeRunPaymentUpsertOne) ClearAnnotations() *ChargeFlatFeeRunPaymentUpsertOne { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.ClearAnnotations() + }) +} + +// Exec executes the query. +func (u *ChargeFlatFeeRunPaymentUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeFlatFeeRunPaymentCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeFlatFeeRunPaymentUpsertOne) 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 *ChargeFlatFeeRunPaymentUpsertOne) 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: ChargeFlatFeeRunPaymentUpsertOne.ID is not supported by MySQL driver. Use ChargeFlatFeeRunPaymentUpsertOne.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 *ChargeFlatFeeRunPaymentUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ChargeFlatFeeRunPaymentCreateBulk is the builder for creating many ChargeFlatFeeRunPayment entities in bulk. +type ChargeFlatFeeRunPaymentCreateBulk struct { + config + err error + builders []*ChargeFlatFeeRunPaymentCreate + conflict []sql.ConflictOption +} + +// Save creates the ChargeFlatFeeRunPayment entities in the database. +func (_c *ChargeFlatFeeRunPaymentCreateBulk) Save(ctx context.Context) ([]*ChargeFlatFeeRunPayment, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ChargeFlatFeeRunPayment, 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.(*ChargeFlatFeeRunPaymentMutation) + 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 *ChargeFlatFeeRunPaymentCreateBulk) SaveX(ctx context.Context) []*ChargeFlatFeeRunPayment { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeFlatFeeRunPaymentCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeFlatFeeRunPaymentCreateBulk) 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.ChargeFlatFeeRunPayment.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.ChargeFlatFeeRunPaymentUpsert) { +// SetLineID(v+v). +// }). +// Exec(ctx) +func (_c *ChargeFlatFeeRunPaymentCreateBulk) OnConflict(opts ...sql.ConflictOption) *ChargeFlatFeeRunPaymentUpsertBulk { + _c.conflict = opts + return &ChargeFlatFeeRunPaymentUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeFlatFeeRunPayment.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeFlatFeeRunPaymentCreateBulk) OnConflictColumns(columns ...string) *ChargeFlatFeeRunPaymentUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeFlatFeeRunPaymentUpsertBulk{ + create: _c, + } +} + +// ChargeFlatFeeRunPaymentUpsertBulk is the builder for "upsert"-ing +// a bulk of ChargeFlatFeeRunPayment nodes. +type ChargeFlatFeeRunPaymentUpsertBulk struct { + create *ChargeFlatFeeRunPaymentCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ChargeFlatFeeRunPayment.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeflatfeerunpayment.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeFlatFeeRunPaymentUpsertBulk) UpdateNewValues() *ChargeFlatFeeRunPaymentUpsertBulk { + 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(chargeflatfeerunpayment.FieldID) + } + if _, exists := b.mutation.LineID(); exists { + s.SetIgnore(chargeflatfeerunpayment.FieldLineID) + } + if _, exists := b.mutation.InvoiceID(); exists { + s.SetIgnore(chargeflatfeerunpayment.FieldInvoiceID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(chargeflatfeerunpayment.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(chargeflatfeerunpayment.FieldCreatedAt) + } + if _, exists := b.mutation.RunID(); exists { + s.SetIgnore(chargeflatfeerunpayment.FieldRunID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeFlatFeeRunPayment.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeFlatFeeRunPaymentUpsertBulk) Ignore() *ChargeFlatFeeRunPaymentUpsertBulk { + 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 *ChargeFlatFeeRunPaymentUpsertBulk) DoNothing() *ChargeFlatFeeRunPaymentUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeFlatFeeRunPaymentCreateBulk.OnConflict +// documentation for more info. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) Update(set func(*ChargeFlatFeeRunPaymentUpsert)) *ChargeFlatFeeRunPaymentUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeFlatFeeRunPaymentUpsert{UpdateSet: update}) + })) + return u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) UpdateServicePeriodFrom() *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) UpdateServicePeriodTo() *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetStatus sets the "status" field. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) SetStatus(v payment.Status) *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) UpdateStatus() *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateStatus() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) UpdateAmount() *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateAmount() + }) +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) SetAuthorizedTransactionGroupID(v string) *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetAuthorizedTransactionGroupID(v) + }) +} + +// UpdateAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) UpdateAuthorizedTransactionGroupID() *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateAuthorizedTransactionGroupID() + }) +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) ClearAuthorizedTransactionGroupID() *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.ClearAuthorizedTransactionGroupID() + }) +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) SetAuthorizedAt(v time.Time) *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetAuthorizedAt(v) + }) +} + +// UpdateAuthorizedAt sets the "authorized_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) UpdateAuthorizedAt() *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateAuthorizedAt() + }) +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) ClearAuthorizedAt() *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.ClearAuthorizedAt() + }) +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) SetSettledTransactionGroupID(v string) *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetSettledTransactionGroupID(v) + }) +} + +// UpdateSettledTransactionGroupID sets the "settled_transaction_group_id" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) UpdateSettledTransactionGroupID() *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateSettledTransactionGroupID() + }) +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) ClearSettledTransactionGroupID() *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.ClearSettledTransactionGroupID() + }) +} + +// SetSettledAt sets the "settled_at" field. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) SetSettledAt(v time.Time) *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetSettledAt(v) + }) +} + +// UpdateSettledAt sets the "settled_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) UpdateSettledAt() *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateSettledAt() + }) +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) ClearSettledAt() *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.ClearSettledAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) UpdateUpdatedAt() *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) SetDeletedAt(v time.Time) *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) UpdateDeletedAt() *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) ClearDeletedAt() *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) UpdateAnnotations() *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) ClearAnnotations() *ChargeFlatFeeRunPaymentUpsertBulk { + return u.Update(func(s *ChargeFlatFeeRunPaymentUpsert) { + s.ClearAnnotations() + }) +} + +// Exec executes the query. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) 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 ChargeFlatFeeRunPaymentCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeFlatFeeRunPaymentCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeFlatFeeRunPaymentUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargeflatfeerunpayment_delete.go b/ent/db/chargeflatfeerunpayment_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..44d38964952a090c46bdb58ab04a277373310f1f --- /dev/null +++ b/ent/db/chargeflatfeerunpayment_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/chargeflatfeerunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeFlatFeeRunPaymentDelete is the builder for deleting a ChargeFlatFeeRunPayment entity. +type ChargeFlatFeeRunPaymentDelete struct { + config + hooks []Hook + mutation *ChargeFlatFeeRunPaymentMutation +} + +// Where appends a list predicates to the ChargeFlatFeeRunPaymentDelete builder. +func (_d *ChargeFlatFeeRunPaymentDelete) Where(ps ...predicate.ChargeFlatFeeRunPayment) *ChargeFlatFeeRunPaymentDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ChargeFlatFeeRunPaymentDelete) 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 *ChargeFlatFeeRunPaymentDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ChargeFlatFeeRunPaymentDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(chargeflatfeerunpayment.Table, sqlgraph.NewFieldSpec(chargeflatfeerunpayment.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 +} + +// ChargeFlatFeeRunPaymentDeleteOne is the builder for deleting a single ChargeFlatFeeRunPayment entity. +type ChargeFlatFeeRunPaymentDeleteOne struct { + _d *ChargeFlatFeeRunPaymentDelete +} + +// Where appends a list predicates to the ChargeFlatFeeRunPaymentDelete builder. +func (_d *ChargeFlatFeeRunPaymentDeleteOne) Where(ps ...predicate.ChargeFlatFeeRunPayment) *ChargeFlatFeeRunPaymentDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ChargeFlatFeeRunPaymentDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{chargeflatfeerunpayment.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeFlatFeeRunPaymentDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargeflatfeerunpayment_query.go b/ent/db/chargeflatfeerunpayment_query.go new file mode 100644 index 0000000000000000000000000000000000000000..aa60e8054ab75b83da439b122302e221282b502b --- /dev/null +++ b/ent/db/chargeflatfeerunpayment_query.go @@ -0,0 +1,718 @@ +// 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/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeFlatFeeRunPaymentQuery is the builder for querying ChargeFlatFeeRunPayment entities. +type ChargeFlatFeeRunPaymentQuery struct { + config + ctx *QueryContext + order []chargeflatfeerunpayment.OrderOption + inters []Interceptor + predicates []predicate.ChargeFlatFeeRunPayment + withBillingInvoiceLine *BillingInvoiceLineQuery + withRun *ChargeFlatFeeRunQuery + 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 ChargeFlatFeeRunPaymentQuery builder. +func (_q *ChargeFlatFeeRunPaymentQuery) Where(ps ...predicate.ChargeFlatFeeRunPayment) *ChargeFlatFeeRunPaymentQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ChargeFlatFeeRunPaymentQuery) Limit(limit int) *ChargeFlatFeeRunPaymentQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ChargeFlatFeeRunPaymentQuery) Offset(offset int) *ChargeFlatFeeRunPaymentQuery { + _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 *ChargeFlatFeeRunPaymentQuery) Unique(unique bool) *ChargeFlatFeeRunPaymentQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ChargeFlatFeeRunPaymentQuery) Order(o ...chargeflatfeerunpayment.OrderOption) *ChargeFlatFeeRunPaymentQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryBillingInvoiceLine chains the current query on the "billing_invoice_line" edge. +func (_q *ChargeFlatFeeRunPaymentQuery) QueryBillingInvoiceLine() *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{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(chargeflatfeerunpayment.Table, chargeflatfeerunpayment.FieldID, selector), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargeflatfeerunpayment.BillingInvoiceLineTable, chargeflatfeerunpayment.BillingInvoiceLineColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryRun chains the current query on the "run" edge. +func (_q *ChargeFlatFeeRunPaymentQuery) QueryRun() *ChargeFlatFeeRunQuery { + query := (&ChargeFlatFeeRunClient{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(chargeflatfeerunpayment.Table, chargeflatfeerunpayment.FieldID, selector), + sqlgraph.To(chargeflatfeerun.Table, chargeflatfeerun.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargeflatfeerunpayment.RunTable, chargeflatfeerunpayment.RunColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ChargeFlatFeeRunPayment entity from the query. +// Returns a *NotFoundError when no ChargeFlatFeeRunPayment was found. +func (_q *ChargeFlatFeeRunPaymentQuery) First(ctx context.Context) (*ChargeFlatFeeRunPayment, 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{chargeflatfeerunpayment.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ChargeFlatFeeRunPaymentQuery) FirstX(ctx context.Context) *ChargeFlatFeeRunPayment { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ChargeFlatFeeRunPayment ID from the query. +// Returns a *NotFoundError when no ChargeFlatFeeRunPayment ID was found. +func (_q *ChargeFlatFeeRunPaymentQuery) 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{chargeflatfeerunpayment.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ChargeFlatFeeRunPaymentQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ChargeFlatFeeRunPayment entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ChargeFlatFeeRunPayment entity is found. +// Returns a *NotFoundError when no ChargeFlatFeeRunPayment entities are found. +func (_q *ChargeFlatFeeRunPaymentQuery) Only(ctx context.Context) (*ChargeFlatFeeRunPayment, 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{chargeflatfeerunpayment.Label} + default: + return nil, &NotSingularError{chargeflatfeerunpayment.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ChargeFlatFeeRunPaymentQuery) OnlyX(ctx context.Context) *ChargeFlatFeeRunPayment { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ChargeFlatFeeRunPayment ID in the query. +// Returns a *NotSingularError when more than one ChargeFlatFeeRunPayment ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ChargeFlatFeeRunPaymentQuery) 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{chargeflatfeerunpayment.Label} + default: + err = &NotSingularError{chargeflatfeerunpayment.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ChargeFlatFeeRunPaymentQuery) 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 ChargeFlatFeeRunPayments. +func (_q *ChargeFlatFeeRunPaymentQuery) All(ctx context.Context) ([]*ChargeFlatFeeRunPayment, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ChargeFlatFeeRunPayment, *ChargeFlatFeeRunPaymentQuery]() + return withInterceptors[[]*ChargeFlatFeeRunPayment](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ChargeFlatFeeRunPaymentQuery) AllX(ctx context.Context) []*ChargeFlatFeeRunPayment { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ChargeFlatFeeRunPayment IDs. +func (_q *ChargeFlatFeeRunPaymentQuery) 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(chargeflatfeerunpayment.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ChargeFlatFeeRunPaymentQuery) 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 *ChargeFlatFeeRunPaymentQuery) 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[*ChargeFlatFeeRunPaymentQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ChargeFlatFeeRunPaymentQuery) 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 *ChargeFlatFeeRunPaymentQuery) 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 *ChargeFlatFeeRunPaymentQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ChargeFlatFeeRunPaymentQuery 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 *ChargeFlatFeeRunPaymentQuery) Clone() *ChargeFlatFeeRunPaymentQuery { + if _q == nil { + return nil + } + return &ChargeFlatFeeRunPaymentQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]chargeflatfeerunpayment.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ChargeFlatFeeRunPayment{}, _q.predicates...), + withBillingInvoiceLine: _q.withBillingInvoiceLine.Clone(), + withRun: _q.withRun.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithBillingInvoiceLine tells the query-builder to eager-load the nodes that are connected to +// the "billing_invoice_line" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeFlatFeeRunPaymentQuery) WithBillingInvoiceLine(opts ...func(*BillingInvoiceLineQuery)) *ChargeFlatFeeRunPaymentQuery { + query := (&BillingInvoiceLineClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingInvoiceLine = query + return _q +} + +// 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 *ChargeFlatFeeRunPaymentQuery) WithRun(opts ...func(*ChargeFlatFeeRunQuery)) *ChargeFlatFeeRunPaymentQuery { + query := (&ChargeFlatFeeRunClient{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.ChargeFlatFeeRunPayment.Query(). +// GroupBy(chargeflatfeerunpayment.FieldLineID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *ChargeFlatFeeRunPaymentQuery) GroupBy(field string, fields ...string) *ChargeFlatFeeRunPaymentGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ChargeFlatFeeRunPaymentGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = chargeflatfeerunpayment.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.ChargeFlatFeeRunPayment.Query(). +// Select(chargeflatfeerunpayment.FieldLineID). +// Scan(ctx, &v) +func (_q *ChargeFlatFeeRunPaymentQuery) Select(fields ...string) *ChargeFlatFeeRunPaymentSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ChargeFlatFeeRunPaymentSelect{ChargeFlatFeeRunPaymentQuery: _q} + sbuild.label = chargeflatfeerunpayment.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ChargeFlatFeeRunPaymentSelect configured with the given aggregations. +func (_q *ChargeFlatFeeRunPaymentQuery) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeRunPaymentSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ChargeFlatFeeRunPaymentQuery) 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 !chargeflatfeerunpayment.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 *ChargeFlatFeeRunPaymentQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ChargeFlatFeeRunPayment, error) { + var ( + nodes = []*ChargeFlatFeeRunPayment{} + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withBillingInvoiceLine != nil, + _q.withRun != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ChargeFlatFeeRunPayment).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ChargeFlatFeeRunPayment{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.withBillingInvoiceLine; query != nil { + if err := _q.loadBillingInvoiceLine(ctx, query, nodes, nil, + func(n *ChargeFlatFeeRunPayment, e *BillingInvoiceLine) { n.Edges.BillingInvoiceLine = e }); err != nil { + return nil, err + } + } + if query := _q.withRun; query != nil { + if err := _q.loadRun(ctx, query, nodes, nil, + func(n *ChargeFlatFeeRunPayment, e *ChargeFlatFeeRun) { n.Edges.Run = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ChargeFlatFeeRunPaymentQuery) loadBillingInvoiceLine(ctx context.Context, query *BillingInvoiceLineQuery, nodes []*ChargeFlatFeeRunPayment, init func(*ChargeFlatFeeRunPayment), assign func(*ChargeFlatFeeRunPayment, *BillingInvoiceLine)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeFlatFeeRunPayment) + for i := range nodes { + fk := nodes[i].LineID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(billinginvoiceline.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 "line_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeFlatFeeRunPaymentQuery) loadRun(ctx context.Context, query *ChargeFlatFeeRunQuery, nodes []*ChargeFlatFeeRunPayment, init func(*ChargeFlatFeeRunPayment), assign func(*ChargeFlatFeeRunPayment, *ChargeFlatFeeRun)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeFlatFeeRunPayment) + 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(chargeflatfeerun.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 *ChargeFlatFeeRunPaymentQuery) 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 *ChargeFlatFeeRunPaymentQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(chargeflatfeerunpayment.Table, chargeflatfeerunpayment.Columns, sqlgraph.NewFieldSpec(chargeflatfeerunpayment.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, chargeflatfeerunpayment.FieldID) + for i := range fields { + if fields[i] != chargeflatfeerunpayment.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withBillingInvoiceLine != nil { + _spec.Node.AddColumnOnce(chargeflatfeerunpayment.FieldLineID) + } + if _q.withRun != nil { + _spec.Node.AddColumnOnce(chargeflatfeerunpayment.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 *ChargeFlatFeeRunPaymentQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(chargeflatfeerunpayment.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = chargeflatfeerunpayment.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 *ChargeFlatFeeRunPaymentQuery) ForUpdate(opts ...sql.LockOption) *ChargeFlatFeeRunPaymentQuery { + 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 *ChargeFlatFeeRunPaymentQuery) ForShare(opts ...sql.LockOption) *ChargeFlatFeeRunPaymentQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ChargeFlatFeeRunPaymentGroupBy is the group-by builder for ChargeFlatFeeRunPayment entities. +type ChargeFlatFeeRunPaymentGroupBy struct { + selector + build *ChargeFlatFeeRunPaymentQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ChargeFlatFeeRunPaymentGroupBy) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeRunPaymentGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ChargeFlatFeeRunPaymentGroupBy) 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[*ChargeFlatFeeRunPaymentQuery, *ChargeFlatFeeRunPaymentGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ChargeFlatFeeRunPaymentGroupBy) sqlScan(ctx context.Context, root *ChargeFlatFeeRunPaymentQuery, 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) +} + +// ChargeFlatFeeRunPaymentSelect is the builder for selecting fields of ChargeFlatFeeRunPayment entities. +type ChargeFlatFeeRunPaymentSelect struct { + *ChargeFlatFeeRunPaymentQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ChargeFlatFeeRunPaymentSelect) Aggregate(fns ...AggregateFunc) *ChargeFlatFeeRunPaymentSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ChargeFlatFeeRunPaymentSelect) 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[*ChargeFlatFeeRunPaymentQuery, *ChargeFlatFeeRunPaymentSelect](ctx, _s.ChargeFlatFeeRunPaymentQuery, _s, _s.inters, v) +} + +func (_s *ChargeFlatFeeRunPaymentSelect) sqlScan(ctx context.Context, root *ChargeFlatFeeRunPaymentQuery, 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/ent/db/chargeflatfeerunpayment_update.go b/ent/db/chargeflatfeerunpayment_update.go new file mode 100644 index 0000000000000000000000000000000000000000..adba997191074afba81e99e0b579ee2c18405db5 --- /dev/null +++ b/ent/db/chargeflatfeerunpayment_update.go @@ -0,0 +1,705 @@ +// 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/chargeflatfeerunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeFlatFeeRunPaymentUpdate is the builder for updating ChargeFlatFeeRunPayment entities. +type ChargeFlatFeeRunPaymentUpdate struct { + config + hooks []Hook + mutation *ChargeFlatFeeRunPaymentMutation +} + +// Where appends a list predicates to the ChargeFlatFeeRunPaymentUpdate builder. +func (_u *ChargeFlatFeeRunPaymentUpdate) Where(ps ...predicate.ChargeFlatFeeRunPayment) *ChargeFlatFeeRunPaymentUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeFlatFeeRunPaymentUpdate) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunPaymentUpdate { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeFlatFeeRunPaymentUpdate) SetNillableServicePeriodFrom(v *time.Time) *ChargeFlatFeeRunPaymentUpdate { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeFlatFeeRunPaymentUpdate) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunPaymentUpdate { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeFlatFeeRunPaymentUpdate) SetNillableServicePeriodTo(v *time.Time) *ChargeFlatFeeRunPaymentUpdate { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetStatus sets the "status" field. +func (_u *ChargeFlatFeeRunPaymentUpdate) SetStatus(v payment.Status) *ChargeFlatFeeRunPaymentUpdate { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *ChargeFlatFeeRunPaymentUpdate) SetNillableStatus(v *payment.Status) *ChargeFlatFeeRunPaymentUpdate { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeFlatFeeRunPaymentUpdate) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunPaymentUpdate { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeFlatFeeRunPaymentUpdate) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeFlatFeeRunPaymentUpdate { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (_u *ChargeFlatFeeRunPaymentUpdate) SetAuthorizedTransactionGroupID(v string) *ChargeFlatFeeRunPaymentUpdate { + _u.mutation.SetAuthorizedTransactionGroupID(v) + return _u +} + +// SetNillableAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field if the given value is not nil. +func (_u *ChargeFlatFeeRunPaymentUpdate) SetNillableAuthorizedTransactionGroupID(v *string) *ChargeFlatFeeRunPaymentUpdate { + if v != nil { + _u.SetAuthorizedTransactionGroupID(*v) + } + return _u +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (_u *ChargeFlatFeeRunPaymentUpdate) ClearAuthorizedTransactionGroupID() *ChargeFlatFeeRunPaymentUpdate { + _u.mutation.ClearAuthorizedTransactionGroupID() + return _u +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (_u *ChargeFlatFeeRunPaymentUpdate) SetAuthorizedAt(v time.Time) *ChargeFlatFeeRunPaymentUpdate { + _u.mutation.SetAuthorizedAt(v) + return _u +} + +// SetNillableAuthorizedAt sets the "authorized_at" field if the given value is not nil. +func (_u *ChargeFlatFeeRunPaymentUpdate) SetNillableAuthorizedAt(v *time.Time) *ChargeFlatFeeRunPaymentUpdate { + if v != nil { + _u.SetAuthorizedAt(*v) + } + return _u +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (_u *ChargeFlatFeeRunPaymentUpdate) ClearAuthorizedAt() *ChargeFlatFeeRunPaymentUpdate { + _u.mutation.ClearAuthorizedAt() + return _u +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (_u *ChargeFlatFeeRunPaymentUpdate) SetSettledTransactionGroupID(v string) *ChargeFlatFeeRunPaymentUpdate { + _u.mutation.SetSettledTransactionGroupID(v) + return _u +} + +// SetNillableSettledTransactionGroupID sets the "settled_transaction_group_id" field if the given value is not nil. +func (_u *ChargeFlatFeeRunPaymentUpdate) SetNillableSettledTransactionGroupID(v *string) *ChargeFlatFeeRunPaymentUpdate { + if v != nil { + _u.SetSettledTransactionGroupID(*v) + } + return _u +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (_u *ChargeFlatFeeRunPaymentUpdate) ClearSettledTransactionGroupID() *ChargeFlatFeeRunPaymentUpdate { + _u.mutation.ClearSettledTransactionGroupID() + return _u +} + +// SetSettledAt sets the "settled_at" field. +func (_u *ChargeFlatFeeRunPaymentUpdate) SetSettledAt(v time.Time) *ChargeFlatFeeRunPaymentUpdate { + _u.mutation.SetSettledAt(v) + return _u +} + +// SetNillableSettledAt sets the "settled_at" field if the given value is not nil. +func (_u *ChargeFlatFeeRunPaymentUpdate) SetNillableSettledAt(v *time.Time) *ChargeFlatFeeRunPaymentUpdate { + if v != nil { + _u.SetSettledAt(*v) + } + return _u +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (_u *ChargeFlatFeeRunPaymentUpdate) ClearSettledAt() *ChargeFlatFeeRunPaymentUpdate { + _u.mutation.ClearSettledAt() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeFlatFeeRunPaymentUpdate) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunPaymentUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeFlatFeeRunPaymentUpdate) SetDeletedAt(v time.Time) *ChargeFlatFeeRunPaymentUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeFlatFeeRunPaymentUpdate) SetNillableDeletedAt(v *time.Time) *ChargeFlatFeeRunPaymentUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeFlatFeeRunPaymentUpdate) ClearDeletedAt() *ChargeFlatFeeRunPaymentUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeFlatFeeRunPaymentUpdate) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunPaymentUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeFlatFeeRunPaymentUpdate) ClearAnnotations() *ChargeFlatFeeRunPaymentUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// Mutation returns the ChargeFlatFeeRunPaymentMutation object of the builder. +func (_u *ChargeFlatFeeRunPaymentUpdate) Mutation() *ChargeFlatFeeRunPaymentMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ChargeFlatFeeRunPaymentUpdate) 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 *ChargeFlatFeeRunPaymentUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ChargeFlatFeeRunPaymentUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeFlatFeeRunPaymentUpdate) 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 *ChargeFlatFeeRunPaymentUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeflatfeerunpayment.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeFlatFeeRunPaymentUpdate) check() error { + if v, ok := _u.mutation.Status(); ok { + if err := chargeflatfeerunpayment.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunPayment.status": %w`, err)} + } + } + if v, ok := _u.mutation.AuthorizedTransactionGroupID(); ok { + if err := chargeflatfeerunpayment.AuthorizedTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "authorized_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunPayment.authorized_transaction_group_id": %w`, err)} + } + } + if v, ok := _u.mutation.SettledTransactionGroupID(); ok { + if err := chargeflatfeerunpayment.SettledTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "settled_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunPayment.settled_transaction_group_id": %w`, err)} + } + } + if _u.mutation.BillingInvoiceLineCleared() && len(_u.mutation.BillingInvoiceLineIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeFlatFeeRunPayment.billing_invoice_line"`) + } + if _u.mutation.RunCleared() && len(_u.mutation.RunIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeFlatFeeRunPayment.run"`) + } + return nil +} + +func (_u *ChargeFlatFeeRunPaymentUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeflatfeerunpayment.Table, chargeflatfeerunpayment.Columns, sqlgraph.NewFieldSpec(chargeflatfeerunpayment.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(chargeflatfeerunpayment.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldStatus, field.TypeEnum, value) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.AuthorizedTransactionGroupID(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldAuthorizedTransactionGroupID, field.TypeString, value) + } + if _u.mutation.AuthorizedTransactionGroupIDCleared() { + _spec.ClearField(chargeflatfeerunpayment.FieldAuthorizedTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.AuthorizedAt(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldAuthorizedAt, field.TypeTime, value) + } + if _u.mutation.AuthorizedAtCleared() { + _spec.ClearField(chargeflatfeerunpayment.FieldAuthorizedAt, field.TypeTime) + } + if value, ok := _u.mutation.SettledTransactionGroupID(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldSettledTransactionGroupID, field.TypeString, value) + } + if _u.mutation.SettledTransactionGroupIDCleared() { + _spec.ClearField(chargeflatfeerunpayment.FieldSettledTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.SettledAt(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldSettledAt, field.TypeTime, value) + } + if _u.mutation.SettledAtCleared() { + _spec.ClearField(chargeflatfeerunpayment.FieldSettledAt, field.TypeTime) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeflatfeerunpayment.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargeflatfeerunpayment.FieldAnnotations, field.TypeJSON) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{chargeflatfeerunpayment.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ChargeFlatFeeRunPaymentUpdateOne is the builder for updating a single ChargeFlatFeeRunPayment entity. +type ChargeFlatFeeRunPaymentUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ChargeFlatFeeRunPaymentMutation +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SetServicePeriodFrom(v time.Time) *ChargeFlatFeeRunPaymentUpdateOne { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SetNillableServicePeriodFrom(v *time.Time) *ChargeFlatFeeRunPaymentUpdateOne { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SetServicePeriodTo(v time.Time) *ChargeFlatFeeRunPaymentUpdateOne { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SetNillableServicePeriodTo(v *time.Time) *ChargeFlatFeeRunPaymentUpdateOne { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetStatus sets the "status" field. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SetStatus(v payment.Status) *ChargeFlatFeeRunPaymentUpdateOne { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SetNillableStatus(v *payment.Status) *ChargeFlatFeeRunPaymentUpdateOne { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SetAmount(v alpacadecimal.Decimal) *ChargeFlatFeeRunPaymentUpdateOne { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeFlatFeeRunPaymentUpdateOne { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SetAuthorizedTransactionGroupID(v string) *ChargeFlatFeeRunPaymentUpdateOne { + _u.mutation.SetAuthorizedTransactionGroupID(v) + return _u +} + +// SetNillableAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field if the given value is not nil. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SetNillableAuthorizedTransactionGroupID(v *string) *ChargeFlatFeeRunPaymentUpdateOne { + if v != nil { + _u.SetAuthorizedTransactionGroupID(*v) + } + return _u +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) ClearAuthorizedTransactionGroupID() *ChargeFlatFeeRunPaymentUpdateOne { + _u.mutation.ClearAuthorizedTransactionGroupID() + return _u +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SetAuthorizedAt(v time.Time) *ChargeFlatFeeRunPaymentUpdateOne { + _u.mutation.SetAuthorizedAt(v) + return _u +} + +// SetNillableAuthorizedAt sets the "authorized_at" field if the given value is not nil. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SetNillableAuthorizedAt(v *time.Time) *ChargeFlatFeeRunPaymentUpdateOne { + if v != nil { + _u.SetAuthorizedAt(*v) + } + return _u +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) ClearAuthorizedAt() *ChargeFlatFeeRunPaymentUpdateOne { + _u.mutation.ClearAuthorizedAt() + return _u +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SetSettledTransactionGroupID(v string) *ChargeFlatFeeRunPaymentUpdateOne { + _u.mutation.SetSettledTransactionGroupID(v) + return _u +} + +// SetNillableSettledTransactionGroupID sets the "settled_transaction_group_id" field if the given value is not nil. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SetNillableSettledTransactionGroupID(v *string) *ChargeFlatFeeRunPaymentUpdateOne { + if v != nil { + _u.SetSettledTransactionGroupID(*v) + } + return _u +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) ClearSettledTransactionGroupID() *ChargeFlatFeeRunPaymentUpdateOne { + _u.mutation.ClearSettledTransactionGroupID() + return _u +} + +// SetSettledAt sets the "settled_at" field. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SetSettledAt(v time.Time) *ChargeFlatFeeRunPaymentUpdateOne { + _u.mutation.SetSettledAt(v) + return _u +} + +// SetNillableSettledAt sets the "settled_at" field if the given value is not nil. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SetNillableSettledAt(v *time.Time) *ChargeFlatFeeRunPaymentUpdateOne { + if v != nil { + _u.SetSettledAt(*v) + } + return _u +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) ClearSettledAt() *ChargeFlatFeeRunPaymentUpdateOne { + _u.mutation.ClearSettledAt() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SetUpdatedAt(v time.Time) *ChargeFlatFeeRunPaymentUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SetDeletedAt(v time.Time) *ChargeFlatFeeRunPaymentUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SetNillableDeletedAt(v *time.Time) *ChargeFlatFeeRunPaymentUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) ClearDeletedAt() *ChargeFlatFeeRunPaymentUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SetAnnotations(v models.Annotations) *ChargeFlatFeeRunPaymentUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) ClearAnnotations() *ChargeFlatFeeRunPaymentUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// Mutation returns the ChargeFlatFeeRunPaymentMutation object of the builder. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) Mutation() *ChargeFlatFeeRunPaymentMutation { + return _u.mutation +} + +// Where appends a list predicates to the ChargeFlatFeeRunPaymentUpdate builder. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) Where(ps ...predicate.ChargeFlatFeeRunPayment) *ChargeFlatFeeRunPaymentUpdateOne { + _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 *ChargeFlatFeeRunPaymentUpdateOne) Select(field string, fields ...string) *ChargeFlatFeeRunPaymentUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ChargeFlatFeeRunPayment entity. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) Save(ctx context.Context) (*ChargeFlatFeeRunPayment, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) SaveX(ctx context.Context) *ChargeFlatFeeRunPayment { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) 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 *ChargeFlatFeeRunPaymentUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeflatfeerunpayment.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeFlatFeeRunPaymentUpdateOne) check() error { + if v, ok := _u.mutation.Status(); ok { + if err := chargeflatfeerunpayment.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunPayment.status": %w`, err)} + } + } + if v, ok := _u.mutation.AuthorizedTransactionGroupID(); ok { + if err := chargeflatfeerunpayment.AuthorizedTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "authorized_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunPayment.authorized_transaction_group_id": %w`, err)} + } + } + if v, ok := _u.mutation.SettledTransactionGroupID(); ok { + if err := chargeflatfeerunpayment.SettledTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "settled_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeFlatFeeRunPayment.settled_transaction_group_id": %w`, err)} + } + } + if _u.mutation.BillingInvoiceLineCleared() && len(_u.mutation.BillingInvoiceLineIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeFlatFeeRunPayment.billing_invoice_line"`) + } + if _u.mutation.RunCleared() && len(_u.mutation.RunIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeFlatFeeRunPayment.run"`) + } + return nil +} + +func (_u *ChargeFlatFeeRunPaymentUpdateOne) sqlSave(ctx context.Context) (_node *ChargeFlatFeeRunPayment, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeflatfeerunpayment.Table, chargeflatfeerunpayment.Columns, sqlgraph.NewFieldSpec(chargeflatfeerunpayment.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "ChargeFlatFeeRunPayment.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, chargeflatfeerunpayment.FieldID) + for _, f := range fields { + if !chargeflatfeerunpayment.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != chargeflatfeerunpayment.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(chargeflatfeerunpayment.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldStatus, field.TypeEnum, value) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.AuthorizedTransactionGroupID(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldAuthorizedTransactionGroupID, field.TypeString, value) + } + if _u.mutation.AuthorizedTransactionGroupIDCleared() { + _spec.ClearField(chargeflatfeerunpayment.FieldAuthorizedTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.AuthorizedAt(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldAuthorizedAt, field.TypeTime, value) + } + if _u.mutation.AuthorizedAtCleared() { + _spec.ClearField(chargeflatfeerunpayment.FieldAuthorizedAt, field.TypeTime) + } + if value, ok := _u.mutation.SettledTransactionGroupID(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldSettledTransactionGroupID, field.TypeString, value) + } + if _u.mutation.SettledTransactionGroupIDCleared() { + _spec.ClearField(chargeflatfeerunpayment.FieldSettledTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.SettledAt(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldSettledAt, field.TypeTime, value) + } + if _u.mutation.SettledAtCleared() { + _spec.ClearField(chargeflatfeerunpayment.FieldSettledAt, field.TypeTime) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeflatfeerunpayment.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargeflatfeerunpayment.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargeflatfeerunpayment.FieldAnnotations, field.TypeJSON) + } + _node = &ChargeFlatFeeRunPayment{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{chargeflatfeerunpayment.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/ent/db/chargessearchv1.go b/ent/db/chargessearchv1.go new file mode 100644 index 0000000000000000000000000000000000000000..5d21cdc0ec9ac0f1fe522e437560f7d459bc0fe4 --- /dev/null +++ b/ent/db/chargessearchv1.go @@ -0,0 +1,424 @@ +// 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/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargessearchv1" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargesSearchV1 is the model entity for the ChargesSearchV1 schema. +type ChargesSearchV1 struct { + config `json:"-"` + // Type holds the value of the "type" field. + Type meta.ChargeType `json:"type,omitempty"` + // BaseIntentDeletedAt holds the value of the "base_intent_deleted_at" field. + BaseIntentDeletedAt *time.Time `json:"base_intent_deleted_at,omitempty"` + // CustomerID holds the value of the "customer_id" field. + CustomerID string `json:"customer_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"` + // BillingPeriodFrom holds the value of the "billing_period_from" field. + BillingPeriodFrom time.Time `json:"billing_period_from,omitempty"` + // BillingPeriodTo holds the value of the "billing_period_to" field. + BillingPeriodTo time.Time `json:"billing_period_to,omitempty"` + // FullServicePeriodFrom holds the value of the "full_service_period_from" field. + FullServicePeriodFrom time.Time `json:"full_service_period_from,omitempty"` + // FullServicePeriodTo holds the value of the "full_service_period_to" field. + FullServicePeriodTo time.Time `json:"full_service_period_to,omitempty"` + // Status holds the value of the "status" field. + Status meta.ChargeStatus `json:"status,omitempty"` + // UniqueReferenceID holds the value of the "unique_reference_id" field. + UniqueReferenceID *string `json:"unique_reference_id,omitempty"` + // Currency holds the value of the "currency" field. + Currency currencyx.Code `json:"currency,omitempty"` + // ManagedBy holds the value of the "managed_by" field. + ManagedBy billing.InvoiceLineManagedBy `json:"managed_by,omitempty"` + // SubscriptionID holds the value of the "subscription_id" field. + SubscriptionID *string `json:"subscription_id,omitempty"` + // SubscriptionPhaseID holds the value of the "subscription_phase_id" field. + SubscriptionPhaseID *string `json:"subscription_phase_id,omitempty"` + // SubscriptionItemID holds the value of the "subscription_item_id" field. + SubscriptionItemID *string `json:"subscription_item_id,omitempty"` + // AdvanceAfter holds the value of the "advance_after" field. + AdvanceAfter *time.Time `json:"advance_after,omitempty"` + // TaxCodeID holds the value of the "tax_code_id" field. + TaxCodeID string `json:"tax_code_id,omitempty"` + // TaxBehavior holds the value of the "tax_behavior" field. + TaxBehavior *productcatalog.TaxBehavior `json:"tax_behavior,omitempty"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,omitempty"` + // ID holds the value of the "id" field. + ID string `json:"id,omitempty"` + // Namespace holds the value of the "namespace" field. + Namespace string `json:"namespace,omitempty"` + // Metadata holds the value of the "metadata" field. + Metadata map[string]string `json:"metadata,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"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Description holds the value of the "description" field. + Description *string `json:"description,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ChargesSearchV1) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case chargessearchv1.FieldAnnotations, chargessearchv1.FieldMetadata: + values[i] = new([]byte) + case chargessearchv1.FieldType, chargessearchv1.FieldCustomerID, chargessearchv1.FieldStatus, chargessearchv1.FieldUniqueReferenceID, chargessearchv1.FieldCurrency, chargessearchv1.FieldManagedBy, chargessearchv1.FieldSubscriptionID, chargessearchv1.FieldSubscriptionPhaseID, chargessearchv1.FieldSubscriptionItemID, chargessearchv1.FieldTaxCodeID, chargessearchv1.FieldTaxBehavior, chargessearchv1.FieldID, chargessearchv1.FieldNamespace, chargessearchv1.FieldName, chargessearchv1.FieldDescription: + values[i] = new(sql.NullString) + case chargessearchv1.FieldBaseIntentDeletedAt, chargessearchv1.FieldServicePeriodFrom, chargessearchv1.FieldServicePeriodTo, chargessearchv1.FieldBillingPeriodFrom, chargessearchv1.FieldBillingPeriodTo, chargessearchv1.FieldFullServicePeriodFrom, chargessearchv1.FieldFullServicePeriodTo, chargessearchv1.FieldAdvanceAfter, chargessearchv1.FieldCreatedAt, chargessearchv1.FieldUpdatedAt, chargessearchv1.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 ChargesSearchV1 fields. +func (_m *ChargesSearchV1) 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 chargessearchv1.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 = meta.ChargeType(value.String) + } + case chargessearchv1.FieldBaseIntentDeletedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field base_intent_deleted_at", values[i]) + } else if value.Valid { + _m.BaseIntentDeletedAt = new(time.Time) + *_m.BaseIntentDeletedAt = value.Time + } + case chargessearchv1.FieldCustomerID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field customer_id", values[i]) + } else if value.Valid { + _m.CustomerID = value.String + } + case chargessearchv1.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 chargessearchv1.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 chargessearchv1.FieldBillingPeriodFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field billing_period_from", values[i]) + } else if value.Valid { + _m.BillingPeriodFrom = value.Time + } + case chargessearchv1.FieldBillingPeriodTo: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field billing_period_to", values[i]) + } else if value.Valid { + _m.BillingPeriodTo = value.Time + } + case chargessearchv1.FieldFullServicePeriodFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field full_service_period_from", values[i]) + } else if value.Valid { + _m.FullServicePeriodFrom = value.Time + } + case chargessearchv1.FieldFullServicePeriodTo: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field full_service_period_to", values[i]) + } else if value.Valid { + _m.FullServicePeriodTo = value.Time + } + case chargessearchv1.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 = meta.ChargeStatus(value.String) + } + case chargessearchv1.FieldUniqueReferenceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field unique_reference_id", values[i]) + } else if value.Valid { + _m.UniqueReferenceID = new(string) + *_m.UniqueReferenceID = value.String + } + case chargessearchv1.FieldCurrency: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field currency", values[i]) + } else if value.Valid { + _m.Currency = currencyx.Code(value.String) + } + case chargessearchv1.FieldManagedBy: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field managed_by", values[i]) + } else if value.Valid { + _m.ManagedBy = billing.InvoiceLineManagedBy(value.String) + } + case chargessearchv1.FieldSubscriptionID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field subscription_id", values[i]) + } else if value.Valid { + _m.SubscriptionID = new(string) + *_m.SubscriptionID = value.String + } + case chargessearchv1.FieldSubscriptionPhaseID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field subscription_phase_id", values[i]) + } else if value.Valid { + _m.SubscriptionPhaseID = new(string) + *_m.SubscriptionPhaseID = value.String + } + case chargessearchv1.FieldSubscriptionItemID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field subscription_item_id", values[i]) + } else if value.Valid { + _m.SubscriptionItemID = new(string) + *_m.SubscriptionItemID = value.String + } + case chargessearchv1.FieldAdvanceAfter: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field advance_after", values[i]) + } else if value.Valid { + _m.AdvanceAfter = new(time.Time) + *_m.AdvanceAfter = value.Time + } + case chargessearchv1.FieldTaxCodeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field tax_code_id", values[i]) + } else if value.Valid { + _m.TaxCodeID = value.String + } + case chargessearchv1.FieldTaxBehavior: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field tax_behavior", values[i]) + } else if value.Valid { + _m.TaxBehavior = new(productcatalog.TaxBehavior) + *_m.TaxBehavior = productcatalog.TaxBehavior(value.String) + } + case chargessearchv1.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 chargessearchv1.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 chargessearchv1.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 chargessearchv1.FieldMetadata: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field metadata", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Metadata); err != nil { + return fmt.Errorf("unmarshal field metadata: %w", err) + } + } + case chargessearchv1.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 chargessearchv1.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 chargessearchv1.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 chargessearchv1.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case chargessearchv1.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + _m.Description = new(string) + *_m.Description = 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 ChargesSearchV1. +// This includes values selected through modifiers, order, etc. +func (_m *ChargesSearchV1) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Unwrap unwraps the ChargesSearchV1 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 *ChargesSearchV1) Unwrap() *ChargesSearchV1 { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: ChargesSearchV1 is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ChargesSearchV1) String() string { + var builder strings.Builder + builder.WriteString("ChargesSearchV1(") + builder.WriteString("type=") + builder.WriteString(fmt.Sprintf("%v", _m.Type)) + builder.WriteString(", ") + if v := _m.BaseIntentDeletedAt; v != nil { + builder.WriteString("base_intent_deleted_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + builder.WriteString("customer_id=") + builder.WriteString(_m.CustomerID) + 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("billing_period_from=") + builder.WriteString(_m.BillingPeriodFrom.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("billing_period_to=") + builder.WriteString(_m.BillingPeriodTo.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("full_service_period_from=") + builder.WriteString(_m.FullServicePeriodFrom.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("full_service_period_to=") + builder.WriteString(_m.FullServicePeriodTo.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("status=") + builder.WriteString(fmt.Sprintf("%v", _m.Status)) + builder.WriteString(", ") + if v := _m.UniqueReferenceID; v != nil { + builder.WriteString("unique_reference_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("currency=") + builder.WriteString(fmt.Sprintf("%v", _m.Currency)) + builder.WriteString(", ") + builder.WriteString("managed_by=") + builder.WriteString(fmt.Sprintf("%v", _m.ManagedBy)) + builder.WriteString(", ") + if v := _m.SubscriptionID; v != nil { + builder.WriteString("subscription_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SubscriptionPhaseID; v != nil { + builder.WriteString("subscription_phase_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SubscriptionItemID; v != nil { + builder.WriteString("subscription_item_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.AdvanceAfter; v != nil { + builder.WriteString("advance_after=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + builder.WriteString("tax_code_id=") + builder.WriteString(_m.TaxCodeID) + builder.WriteString(", ") + if v := _m.TaxBehavior; v != nil { + builder.WriteString("tax_behavior=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + builder.WriteString(", ") + builder.WriteString("id=") + builder.WriteString(_m.ID) + builder.WriteString(", ") + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("metadata=") + builder.WriteString(fmt.Sprintf("%v", _m.Metadata)) + 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("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + if v := _m.Description; v != nil { + builder.WriteString("description=") + builder.WriteString(*v) + } + builder.WriteByte(')') + return builder.String() +} + +// ChargesSearchV1s is a parsable slice of ChargesSearchV1. +type ChargesSearchV1s []*ChargesSearchV1 diff --git a/ent/db/chargessearchv1/chargessearchv1.go b/ent/db/chargessearchv1/chargessearchv1.go new file mode 100644 index 0000000000000000000000000000000000000000..c047e99631188d7661ab66a2cd9076f2ed8a4204 --- /dev/null +++ b/ent/db/chargessearchv1/chargessearchv1.go @@ -0,0 +1,300 @@ +// Code generated by ent, DO NOT EDIT. + +package chargessearchv1 + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "github.com/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/productcatalog" +) + +const ( + // Label holds the string label denoting the chargessearchv1 type in the database. + Label = "charges_search_v1" + // FieldType holds the string denoting the type field in the database. + FieldType = "type" + // FieldBaseIntentDeletedAt holds the string denoting the base_intent_deleted_at field in the database. + FieldBaseIntentDeletedAt = "base_intent_deleted_at" + // FieldCustomerID holds the string denoting the customer_id field in the database. + FieldCustomerID = "customer_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" + // FieldBillingPeriodFrom holds the string denoting the billing_period_from field in the database. + FieldBillingPeriodFrom = "billing_period_from" + // FieldBillingPeriodTo holds the string denoting the billing_period_to field in the database. + FieldBillingPeriodTo = "billing_period_to" + // FieldFullServicePeriodFrom holds the string denoting the full_service_period_from field in the database. + FieldFullServicePeriodFrom = "full_service_period_from" + // FieldFullServicePeriodTo holds the string denoting the full_service_period_to field in the database. + FieldFullServicePeriodTo = "full_service_period_to" + // FieldStatus holds the string denoting the status field in the database. + FieldStatus = "status" + // FieldUniqueReferenceID holds the string denoting the unique_reference_id field in the database. + FieldUniqueReferenceID = "unique_reference_id" + // FieldCurrency holds the string denoting the currency field in the database. + FieldCurrency = "currency" + // FieldManagedBy holds the string denoting the managed_by field in the database. + FieldManagedBy = "managed_by" + // FieldSubscriptionID holds the string denoting the subscription_id field in the database. + FieldSubscriptionID = "subscription_id" + // FieldSubscriptionPhaseID holds the string denoting the subscription_phase_id field in the database. + FieldSubscriptionPhaseID = "subscription_phase_id" + // FieldSubscriptionItemID holds the string denoting the subscription_item_id field in the database. + FieldSubscriptionItemID = "subscription_item_id" + // FieldAdvanceAfter holds the string denoting the advance_after field in the database. + FieldAdvanceAfter = "advance_after" + // FieldTaxCodeID holds the string denoting the tax_code_id field in the database. + FieldTaxCodeID = "tax_code_id" + // FieldTaxBehavior holds the string denoting the tax_behavior field in the database. + FieldTaxBehavior = "tax_behavior" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // 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" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // 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" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // Table holds the table name of the chargessearchv1 in the database. + Table = "charges_search_v1s" +) + +// Columns holds all SQL columns for chargessearchv1 fields. +var Columns = []string{ + FieldType, + FieldBaseIntentDeletedAt, + FieldCustomerID, + FieldServicePeriodFrom, + FieldServicePeriodTo, + FieldBillingPeriodFrom, + FieldBillingPeriodTo, + FieldFullServicePeriodFrom, + FieldFullServicePeriodTo, + FieldStatus, + FieldUniqueReferenceID, + FieldCurrency, + FieldManagedBy, + FieldSubscriptionID, + FieldSubscriptionPhaseID, + FieldSubscriptionItemID, + FieldAdvanceAfter, + FieldTaxCodeID, + FieldTaxBehavior, + FieldAnnotations, + FieldID, + FieldNamespace, + FieldMetadata, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldName, + FieldDescription, +} + +// 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 ( + // CustomerIDValidator is a validator for the "customer_id" field. It is called by the builders before save. + CustomerIDValidator func(string) error + // CurrencyValidator is a validator for the "currency" field. It is called by the builders before save. + CurrencyValidator func(string) error + // TaxCodeIDValidator is a validator for the "tax_code_id" field. It is called by the builders before save. + TaxCodeIDValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string + // 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 +) + +// StatusValidator is a validator for the "status" field enum values. It is called by the builders before save. +func StatusValidator(s meta.ChargeStatus) error { + switch s { + case "created", "active", "final", "deleted": + return nil + default: + return fmt.Errorf("chargessearchv1: invalid enum value for status field: %q", s) + } +} + +// ManagedByValidator is a validator for the "managed_by" field enum values. It is called by the builders before save. +func ManagedByValidator(mb billing.InvoiceLineManagedBy) error { + switch mb { + case "subscription", "system", "manual": + return nil + default: + return fmt.Errorf("chargessearchv1: invalid enum value for managed_by field: %q", mb) + } +} + +// TaxBehaviorValidator is a validator for the "tax_behavior" field enum values. It is called by the builders before save. +func TaxBehaviorValidator(tb productcatalog.TaxBehavior) error { + switch tb { + case "inclusive", "exclusive": + return nil + default: + return fmt.Errorf("chargessearchv1: invalid enum value for tax_behavior field: %q", tb) + } +} + +// OrderOption defines the ordering options for the ChargesSearchV1 queries. +type OrderOption func(*sql.Selector) + +// ByType orders the results by the type field. +func ByType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldType, opts...).ToFunc() +} + +// ByBaseIntentDeletedAt orders the results by the base_intent_deleted_at field. +func ByBaseIntentDeletedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBaseIntentDeletedAt, opts...).ToFunc() +} + +// ByCustomerID orders the results by the customer_id field. +func ByCustomerID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCustomerID, 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() +} + +// ByBillingPeriodFrom orders the results by the billing_period_from field. +func ByBillingPeriodFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBillingPeriodFrom, opts...).ToFunc() +} + +// ByBillingPeriodTo orders the results by the billing_period_to field. +func ByBillingPeriodTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBillingPeriodTo, opts...).ToFunc() +} + +// ByFullServicePeriodFrom orders the results by the full_service_period_from field. +func ByFullServicePeriodFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFullServicePeriodFrom, opts...).ToFunc() +} + +// ByFullServicePeriodTo orders the results by the full_service_period_to field. +func ByFullServicePeriodTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFullServicePeriodTo, opts...).ToFunc() +} + +// ByStatus orders the results by the status field. +func ByStatus(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStatus, opts...).ToFunc() +} + +// ByUniqueReferenceID orders the results by the unique_reference_id field. +func ByUniqueReferenceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUniqueReferenceID, opts...).ToFunc() +} + +// ByCurrency orders the results by the currency field. +func ByCurrency(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCurrency, opts...).ToFunc() +} + +// ByManagedBy orders the results by the managed_by field. +func ByManagedBy(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldManagedBy, opts...).ToFunc() +} + +// BySubscriptionID orders the results by the subscription_id field. +func BySubscriptionID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSubscriptionID, opts...).ToFunc() +} + +// BySubscriptionPhaseID orders the results by the subscription_phase_id field. +func BySubscriptionPhaseID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSubscriptionPhaseID, opts...).ToFunc() +} + +// BySubscriptionItemID orders the results by the subscription_item_id field. +func BySubscriptionItemID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSubscriptionItemID, opts...).ToFunc() +} + +// ByAdvanceAfter orders the results by the advance_after field. +func ByAdvanceAfter(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAdvanceAfter, opts...).ToFunc() +} + +// ByTaxCodeID orders the results by the tax_code_id field. +func ByTaxCodeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxCodeID, opts...).ToFunc() +} + +// ByTaxBehavior orders the results by the tax_behavior field. +func ByTaxBehavior(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxBehavior, opts...).ToFunc() +} + +// 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() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, opts...).ToFunc() +} diff --git a/ent/db/chargessearchv1/where.go b/ent/db/chargessearchv1/where.go new file mode 100644 index 0000000000000000000000000000000000000000..c7c4edb5278dcd6b14b402b78cb15178780d6c41 --- /dev/null +++ b/ent/db/chargessearchv1/where.go @@ -0,0 +1,1589 @@ +// Code generated by ent, DO NOT EDIT. + +package chargessearchv1 + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "github.com/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" +) + +// Type applies equality check predicate on the "type" field. It's identical to TypeEQ. +func Type(v meta.ChargeType) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldEQ(FieldType, vc)) +} + +// BaseIntentDeletedAt applies equality check predicate on the "base_intent_deleted_at" field. It's identical to BaseIntentDeletedAtEQ. +func BaseIntentDeletedAt(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldBaseIntentDeletedAt, v)) +} + +// CustomerID applies equality check predicate on the "customer_id" field. It's identical to CustomerIDEQ. +func CustomerID(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldCustomerID, v)) +} + +// ServicePeriodFrom applies equality check predicate on the "service_period_from" field. It's identical to ServicePeriodFromEQ. +func ServicePeriodFrom(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(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.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// BillingPeriodFrom applies equality check predicate on the "billing_period_from" field. It's identical to BillingPeriodFromEQ. +func BillingPeriodFrom(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodTo applies equality check predicate on the "billing_period_to" field. It's identical to BillingPeriodToEQ. +func BillingPeriodTo(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldBillingPeriodTo, v)) +} + +// FullServicePeriodFrom applies equality check predicate on the "full_service_period_from" field. It's identical to FullServicePeriodFromEQ. +func FullServicePeriodFrom(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodTo applies equality check predicate on the "full_service_period_to" field. It's identical to FullServicePeriodToEQ. +func FullServicePeriodTo(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldFullServicePeriodTo, v)) +} + +// UniqueReferenceID applies equality check predicate on the "unique_reference_id" field. It's identical to UniqueReferenceIDEQ. +func UniqueReferenceID(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldUniqueReferenceID, v)) +} + +// Currency applies equality check predicate on the "currency" field. It's identical to CurrencyEQ. +func Currency(v currencyx.Code) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldEQ(FieldCurrency, vc)) +} + +// SubscriptionID applies equality check predicate on the "subscription_id" field. It's identical to SubscriptionIDEQ. +func SubscriptionID(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldSubscriptionID, v)) +} + +// SubscriptionPhaseID applies equality check predicate on the "subscription_phase_id" field. It's identical to SubscriptionPhaseIDEQ. +func SubscriptionPhaseID(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionItemID applies equality check predicate on the "subscription_item_id" field. It's identical to SubscriptionItemIDEQ. +func SubscriptionItemID(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldSubscriptionItemID, v)) +} + +// AdvanceAfter applies equality check predicate on the "advance_after" field. It's identical to AdvanceAfterEQ. +func AdvanceAfter(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldAdvanceAfter, v)) +} + +// TaxCodeID applies equality check predicate on the "tax_code_id" field. It's identical to TaxCodeIDEQ. +func TaxCodeID(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldTaxCodeID, v)) +} + +// ID applies equality check predicate on the "id" field. It's identical to IDEQ. +func ID(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldID, v)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(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.ChargesSearchV1 { + return predicate.ChargesSearchV1(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.ChargesSearchV1 { + return predicate.ChargesSearchV1(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.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldName, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldDescription, v)) +} + +// TypeEQ applies the EQ predicate on the "type" field. +func TypeEQ(v meta.ChargeType) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldEQ(FieldType, vc)) +} + +// TypeNEQ applies the NEQ predicate on the "type" field. +func TypeNEQ(v meta.ChargeType) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldType, vc)) +} + +// TypeIn applies the In predicate on the "type" field. +func TypeIn(vs ...meta.ChargeType) predicate.ChargesSearchV1 { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargesSearchV1(sql.FieldIn(FieldType, v...)) +} + +// TypeNotIn applies the NotIn predicate on the "type" field. +func TypeNotIn(vs ...meta.ChargeType) predicate.ChargesSearchV1 { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldType, v...)) +} + +// TypeGT applies the GT predicate on the "type" field. +func TypeGT(v meta.ChargeType) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldGT(FieldType, vc)) +} + +// TypeGTE applies the GTE predicate on the "type" field. +func TypeGTE(v meta.ChargeType) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldGTE(FieldType, vc)) +} + +// TypeLT applies the LT predicate on the "type" field. +func TypeLT(v meta.ChargeType) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldLT(FieldType, vc)) +} + +// TypeLTE applies the LTE predicate on the "type" field. +func TypeLTE(v meta.ChargeType) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldLTE(FieldType, vc)) +} + +// TypeContains applies the Contains predicate on the "type" field. +func TypeContains(v meta.ChargeType) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldContains(FieldType, vc)) +} + +// TypeHasPrefix applies the HasPrefix predicate on the "type" field. +func TypeHasPrefix(v meta.ChargeType) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldHasPrefix(FieldType, vc)) +} + +// TypeHasSuffix applies the HasSuffix predicate on the "type" field. +func TypeHasSuffix(v meta.ChargeType) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldHasSuffix(FieldType, vc)) +} + +// TypeEqualFold applies the EqualFold predicate on the "type" field. +func TypeEqualFold(v meta.ChargeType) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldEqualFold(FieldType, vc)) +} + +// TypeContainsFold applies the ContainsFold predicate on the "type" field. +func TypeContainsFold(v meta.ChargeType) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldContainsFold(FieldType, vc)) +} + +// BaseIntentDeletedAtEQ applies the EQ predicate on the "base_intent_deleted_at" field. +func BaseIntentDeletedAtEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldBaseIntentDeletedAt, v)) +} + +// BaseIntentDeletedAtNEQ applies the NEQ predicate on the "base_intent_deleted_at" field. +func BaseIntentDeletedAtNEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldBaseIntentDeletedAt, v)) +} + +// BaseIntentDeletedAtIn applies the In predicate on the "base_intent_deleted_at" field. +func BaseIntentDeletedAtIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldBaseIntentDeletedAt, vs...)) +} + +// BaseIntentDeletedAtNotIn applies the NotIn predicate on the "base_intent_deleted_at" field. +func BaseIntentDeletedAtNotIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldBaseIntentDeletedAt, vs...)) +} + +// BaseIntentDeletedAtGT applies the GT predicate on the "base_intent_deleted_at" field. +func BaseIntentDeletedAtGT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldBaseIntentDeletedAt, v)) +} + +// BaseIntentDeletedAtGTE applies the GTE predicate on the "base_intent_deleted_at" field. +func BaseIntentDeletedAtGTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldBaseIntentDeletedAt, v)) +} + +// BaseIntentDeletedAtLT applies the LT predicate on the "base_intent_deleted_at" field. +func BaseIntentDeletedAtLT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldBaseIntentDeletedAt, v)) +} + +// BaseIntentDeletedAtLTE applies the LTE predicate on the "base_intent_deleted_at" field. +func BaseIntentDeletedAtLTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldBaseIntentDeletedAt, v)) +} + +// BaseIntentDeletedAtIsNil applies the IsNil predicate on the "base_intent_deleted_at" field. +func BaseIntentDeletedAtIsNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIsNull(FieldBaseIntentDeletedAt)) +} + +// BaseIntentDeletedAtNotNil applies the NotNil predicate on the "base_intent_deleted_at" field. +func BaseIntentDeletedAtNotNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotNull(FieldBaseIntentDeletedAt)) +} + +// CustomerIDEQ applies the EQ predicate on the "customer_id" field. +func CustomerIDEQ(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldCustomerID, v)) +} + +// CustomerIDNEQ applies the NEQ predicate on the "customer_id" field. +func CustomerIDNEQ(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldCustomerID, v)) +} + +// CustomerIDIn applies the In predicate on the "customer_id" field. +func CustomerIDIn(vs ...string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldCustomerID, vs...)) +} + +// CustomerIDNotIn applies the NotIn predicate on the "customer_id" field. +func CustomerIDNotIn(vs ...string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldCustomerID, vs...)) +} + +// CustomerIDGT applies the GT predicate on the "customer_id" field. +func CustomerIDGT(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldCustomerID, v)) +} + +// CustomerIDGTE applies the GTE predicate on the "customer_id" field. +func CustomerIDGTE(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldCustomerID, v)) +} + +// CustomerIDLT applies the LT predicate on the "customer_id" field. +func CustomerIDLT(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldCustomerID, v)) +} + +// CustomerIDLTE applies the LTE predicate on the "customer_id" field. +func CustomerIDLTE(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldCustomerID, v)) +} + +// CustomerIDContains applies the Contains predicate on the "customer_id" field. +func CustomerIDContains(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldContains(FieldCustomerID, v)) +} + +// CustomerIDHasPrefix applies the HasPrefix predicate on the "customer_id" field. +func CustomerIDHasPrefix(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldHasPrefix(FieldCustomerID, v)) +} + +// CustomerIDHasSuffix applies the HasSuffix predicate on the "customer_id" field. +func CustomerIDHasSuffix(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldHasSuffix(FieldCustomerID, v)) +} + +// CustomerIDEqualFold applies the EqualFold predicate on the "customer_id" field. +func CustomerIDEqualFold(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEqualFold(FieldCustomerID, v)) +} + +// CustomerIDContainsFold applies the ContainsFold predicate on the "customer_id" field. +func CustomerIDContainsFold(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldContainsFold(FieldCustomerID, v)) +} + +// ServicePeriodFromEQ applies the EQ predicate on the "service_period_from" field. +func ServicePeriodFromEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromNEQ applies the NEQ predicate on the "service_period_from" field. +func ServicePeriodFromNEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromIn applies the In predicate on the "service_period_from" field. +func ServicePeriodFromIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromNotIn applies the NotIn predicate on the "service_period_from" field. +func ServicePeriodFromNotIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromGT applies the GT predicate on the "service_period_from" field. +func ServicePeriodFromGT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromGTE applies the GTE predicate on the "service_period_from" field. +func ServicePeriodFromGTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLT applies the LT predicate on the "service_period_from" field. +func ServicePeriodFromLT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLTE applies the LTE predicate on the "service_period_from" field. +func ServicePeriodFromLTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodToEQ applies the EQ predicate on the "service_period_to" field. +func ServicePeriodToEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToNEQ applies the NEQ predicate on the "service_period_to" field. +func ServicePeriodToNEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToIn applies the In predicate on the "service_period_to" field. +func ServicePeriodToIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToNotIn applies the NotIn predicate on the "service_period_to" field. +func ServicePeriodToNotIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToGT applies the GT predicate on the "service_period_to" field. +func ServicePeriodToGT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToGTE applies the GTE predicate on the "service_period_to" field. +func ServicePeriodToGTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLT applies the LT predicate on the "service_period_to" field. +func ServicePeriodToLT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLTE applies the LTE predicate on the "service_period_to" field. +func ServicePeriodToLTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldServicePeriodTo, v)) +} + +// BillingPeriodFromEQ applies the EQ predicate on the "billing_period_from" field. +func BillingPeriodFromEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromNEQ applies the NEQ predicate on the "billing_period_from" field. +func BillingPeriodFromNEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromIn applies the In predicate on the "billing_period_from" field. +func BillingPeriodFromIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldBillingPeriodFrom, vs...)) +} + +// BillingPeriodFromNotIn applies the NotIn predicate on the "billing_period_from" field. +func BillingPeriodFromNotIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldBillingPeriodFrom, vs...)) +} + +// BillingPeriodFromGT applies the GT predicate on the "billing_period_from" field. +func BillingPeriodFromGT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromGTE applies the GTE predicate on the "billing_period_from" field. +func BillingPeriodFromGTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromLT applies the LT predicate on the "billing_period_from" field. +func BillingPeriodFromLT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromLTE applies the LTE predicate on the "billing_period_from" field. +func BillingPeriodFromLTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodToEQ applies the EQ predicate on the "billing_period_to" field. +func BillingPeriodToEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToNEQ applies the NEQ predicate on the "billing_period_to" field. +func BillingPeriodToNEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToIn applies the In predicate on the "billing_period_to" field. +func BillingPeriodToIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldBillingPeriodTo, vs...)) +} + +// BillingPeriodToNotIn applies the NotIn predicate on the "billing_period_to" field. +func BillingPeriodToNotIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldBillingPeriodTo, vs...)) +} + +// BillingPeriodToGT applies the GT predicate on the "billing_period_to" field. +func BillingPeriodToGT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToGTE applies the GTE predicate on the "billing_period_to" field. +func BillingPeriodToGTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToLT applies the LT predicate on the "billing_period_to" field. +func BillingPeriodToLT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToLTE applies the LTE predicate on the "billing_period_to" field. +func BillingPeriodToLTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldBillingPeriodTo, v)) +} + +// FullServicePeriodFromEQ applies the EQ predicate on the "full_service_period_from" field. +func FullServicePeriodFromEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromNEQ applies the NEQ predicate on the "full_service_period_from" field. +func FullServicePeriodFromNEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromIn applies the In predicate on the "full_service_period_from" field. +func FullServicePeriodFromIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldFullServicePeriodFrom, vs...)) +} + +// FullServicePeriodFromNotIn applies the NotIn predicate on the "full_service_period_from" field. +func FullServicePeriodFromNotIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldFullServicePeriodFrom, vs...)) +} + +// FullServicePeriodFromGT applies the GT predicate on the "full_service_period_from" field. +func FullServicePeriodFromGT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromGTE applies the GTE predicate on the "full_service_period_from" field. +func FullServicePeriodFromGTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromLT applies the LT predicate on the "full_service_period_from" field. +func FullServicePeriodFromLT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromLTE applies the LTE predicate on the "full_service_period_from" field. +func FullServicePeriodFromLTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodToEQ applies the EQ predicate on the "full_service_period_to" field. +func FullServicePeriodToEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToNEQ applies the NEQ predicate on the "full_service_period_to" field. +func FullServicePeriodToNEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToIn applies the In predicate on the "full_service_period_to" field. +func FullServicePeriodToIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldFullServicePeriodTo, vs...)) +} + +// FullServicePeriodToNotIn applies the NotIn predicate on the "full_service_period_to" field. +func FullServicePeriodToNotIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldFullServicePeriodTo, vs...)) +} + +// FullServicePeriodToGT applies the GT predicate on the "full_service_period_to" field. +func FullServicePeriodToGT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToGTE applies the GTE predicate on the "full_service_period_to" field. +func FullServicePeriodToGTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToLT applies the LT predicate on the "full_service_period_to" field. +func FullServicePeriodToLT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToLTE applies the LTE predicate on the "full_service_period_to" field. +func FullServicePeriodToLTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldFullServicePeriodTo, v)) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v meta.ChargeStatus) predicate.ChargesSearchV1 { + vc := v + return predicate.ChargesSearchV1(sql.FieldEQ(FieldStatus, vc)) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v meta.ChargeStatus) predicate.ChargesSearchV1 { + vc := v + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldStatus, vc)) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...meta.ChargeStatus) predicate.ChargesSearchV1 { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargesSearchV1(sql.FieldIn(FieldStatus, v...)) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...meta.ChargeStatus) predicate.ChargesSearchV1 { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldStatus, v...)) +} + +// UniqueReferenceIDEQ applies the EQ predicate on the "unique_reference_id" field. +func UniqueReferenceIDEQ(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDNEQ applies the NEQ predicate on the "unique_reference_id" field. +func UniqueReferenceIDNEQ(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDIn applies the In predicate on the "unique_reference_id" field. +func UniqueReferenceIDIn(vs ...string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldUniqueReferenceID, vs...)) +} + +// UniqueReferenceIDNotIn applies the NotIn predicate on the "unique_reference_id" field. +func UniqueReferenceIDNotIn(vs ...string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldUniqueReferenceID, vs...)) +} + +// UniqueReferenceIDGT applies the GT predicate on the "unique_reference_id" field. +func UniqueReferenceIDGT(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDGTE applies the GTE predicate on the "unique_reference_id" field. +func UniqueReferenceIDGTE(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDLT applies the LT predicate on the "unique_reference_id" field. +func UniqueReferenceIDLT(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDLTE applies the LTE predicate on the "unique_reference_id" field. +func UniqueReferenceIDLTE(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDContains applies the Contains predicate on the "unique_reference_id" field. +func UniqueReferenceIDContains(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldContains(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDHasPrefix applies the HasPrefix predicate on the "unique_reference_id" field. +func UniqueReferenceIDHasPrefix(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldHasPrefix(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDHasSuffix applies the HasSuffix predicate on the "unique_reference_id" field. +func UniqueReferenceIDHasSuffix(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldHasSuffix(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDIsNil applies the IsNil predicate on the "unique_reference_id" field. +func UniqueReferenceIDIsNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIsNull(FieldUniqueReferenceID)) +} + +// UniqueReferenceIDNotNil applies the NotNil predicate on the "unique_reference_id" field. +func UniqueReferenceIDNotNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotNull(FieldUniqueReferenceID)) +} + +// UniqueReferenceIDEqualFold applies the EqualFold predicate on the "unique_reference_id" field. +func UniqueReferenceIDEqualFold(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEqualFold(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDContainsFold applies the ContainsFold predicate on the "unique_reference_id" field. +func UniqueReferenceIDContainsFold(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldContainsFold(FieldUniqueReferenceID, v)) +} + +// CurrencyEQ applies the EQ predicate on the "currency" field. +func CurrencyEQ(v currencyx.Code) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldEQ(FieldCurrency, vc)) +} + +// CurrencyNEQ applies the NEQ predicate on the "currency" field. +func CurrencyNEQ(v currencyx.Code) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldCurrency, vc)) +} + +// CurrencyIn applies the In predicate on the "currency" field. +func CurrencyIn(vs ...currencyx.Code) predicate.ChargesSearchV1 { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargesSearchV1(sql.FieldIn(FieldCurrency, v...)) +} + +// CurrencyNotIn applies the NotIn predicate on the "currency" field. +func CurrencyNotIn(vs ...currencyx.Code) predicate.ChargesSearchV1 { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldCurrency, v...)) +} + +// CurrencyGT applies the GT predicate on the "currency" field. +func CurrencyGT(v currencyx.Code) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldGT(FieldCurrency, vc)) +} + +// CurrencyGTE applies the GTE predicate on the "currency" field. +func CurrencyGTE(v currencyx.Code) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldGTE(FieldCurrency, vc)) +} + +// CurrencyLT applies the LT predicate on the "currency" field. +func CurrencyLT(v currencyx.Code) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldLT(FieldCurrency, vc)) +} + +// CurrencyLTE applies the LTE predicate on the "currency" field. +func CurrencyLTE(v currencyx.Code) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldLTE(FieldCurrency, vc)) +} + +// CurrencyContains applies the Contains predicate on the "currency" field. +func CurrencyContains(v currencyx.Code) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldContains(FieldCurrency, vc)) +} + +// CurrencyHasPrefix applies the HasPrefix predicate on the "currency" field. +func CurrencyHasPrefix(v currencyx.Code) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldHasPrefix(FieldCurrency, vc)) +} + +// CurrencyHasSuffix applies the HasSuffix predicate on the "currency" field. +func CurrencyHasSuffix(v currencyx.Code) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldHasSuffix(FieldCurrency, vc)) +} + +// CurrencyEqualFold applies the EqualFold predicate on the "currency" field. +func CurrencyEqualFold(v currencyx.Code) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldEqualFold(FieldCurrency, vc)) +} + +// CurrencyContainsFold applies the ContainsFold predicate on the "currency" field. +func CurrencyContainsFold(v currencyx.Code) predicate.ChargesSearchV1 { + vc := string(v) + return predicate.ChargesSearchV1(sql.FieldContainsFold(FieldCurrency, vc)) +} + +// ManagedByEQ applies the EQ predicate on the "managed_by" field. +func ManagedByEQ(v billing.InvoiceLineManagedBy) predicate.ChargesSearchV1 { + vc := v + return predicate.ChargesSearchV1(sql.FieldEQ(FieldManagedBy, vc)) +} + +// ManagedByNEQ applies the NEQ predicate on the "managed_by" field. +func ManagedByNEQ(v billing.InvoiceLineManagedBy) predicate.ChargesSearchV1 { + vc := v + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldManagedBy, vc)) +} + +// ManagedByIn applies the In predicate on the "managed_by" field. +func ManagedByIn(vs ...billing.InvoiceLineManagedBy) predicate.ChargesSearchV1 { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargesSearchV1(sql.FieldIn(FieldManagedBy, v...)) +} + +// ManagedByNotIn applies the NotIn predicate on the "managed_by" field. +func ManagedByNotIn(vs ...billing.InvoiceLineManagedBy) predicate.ChargesSearchV1 { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldManagedBy, v...)) +} + +// SubscriptionIDEQ applies the EQ predicate on the "subscription_id" field. +func SubscriptionIDEQ(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldSubscriptionID, v)) +} + +// SubscriptionIDNEQ applies the NEQ predicate on the "subscription_id" field. +func SubscriptionIDNEQ(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldSubscriptionID, v)) +} + +// SubscriptionIDIn applies the In predicate on the "subscription_id" field. +func SubscriptionIDIn(vs ...string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldSubscriptionID, vs...)) +} + +// SubscriptionIDNotIn applies the NotIn predicate on the "subscription_id" field. +func SubscriptionIDNotIn(vs ...string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldSubscriptionID, vs...)) +} + +// SubscriptionIDGT applies the GT predicate on the "subscription_id" field. +func SubscriptionIDGT(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldSubscriptionID, v)) +} + +// SubscriptionIDGTE applies the GTE predicate on the "subscription_id" field. +func SubscriptionIDGTE(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldSubscriptionID, v)) +} + +// SubscriptionIDLT applies the LT predicate on the "subscription_id" field. +func SubscriptionIDLT(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldSubscriptionID, v)) +} + +// SubscriptionIDLTE applies the LTE predicate on the "subscription_id" field. +func SubscriptionIDLTE(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldSubscriptionID, v)) +} + +// SubscriptionIDContains applies the Contains predicate on the "subscription_id" field. +func SubscriptionIDContains(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldContains(FieldSubscriptionID, v)) +} + +// SubscriptionIDHasPrefix applies the HasPrefix predicate on the "subscription_id" field. +func SubscriptionIDHasPrefix(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldHasPrefix(FieldSubscriptionID, v)) +} + +// SubscriptionIDHasSuffix applies the HasSuffix predicate on the "subscription_id" field. +func SubscriptionIDHasSuffix(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldHasSuffix(FieldSubscriptionID, v)) +} + +// SubscriptionIDIsNil applies the IsNil predicate on the "subscription_id" field. +func SubscriptionIDIsNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIsNull(FieldSubscriptionID)) +} + +// SubscriptionIDNotNil applies the NotNil predicate on the "subscription_id" field. +func SubscriptionIDNotNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotNull(FieldSubscriptionID)) +} + +// SubscriptionIDEqualFold applies the EqualFold predicate on the "subscription_id" field. +func SubscriptionIDEqualFold(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEqualFold(FieldSubscriptionID, v)) +} + +// SubscriptionIDContainsFold applies the ContainsFold predicate on the "subscription_id" field. +func SubscriptionIDContainsFold(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldContainsFold(FieldSubscriptionID, v)) +} + +// SubscriptionPhaseIDEQ applies the EQ predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDEQ(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDNEQ applies the NEQ predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDNEQ(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDIn applies the In predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDIn(vs ...string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldSubscriptionPhaseID, vs...)) +} + +// SubscriptionPhaseIDNotIn applies the NotIn predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDNotIn(vs ...string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldSubscriptionPhaseID, vs...)) +} + +// SubscriptionPhaseIDGT applies the GT predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDGT(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDGTE applies the GTE predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDGTE(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDLT applies the LT predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDLT(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDLTE applies the LTE predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDLTE(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDContains applies the Contains predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDContains(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldContains(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDHasPrefix applies the HasPrefix predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDHasPrefix(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldHasPrefix(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDHasSuffix applies the HasSuffix predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDHasSuffix(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldHasSuffix(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDIsNil applies the IsNil predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDIsNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIsNull(FieldSubscriptionPhaseID)) +} + +// SubscriptionPhaseIDNotNil applies the NotNil predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDNotNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotNull(FieldSubscriptionPhaseID)) +} + +// SubscriptionPhaseIDEqualFold applies the EqualFold predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDEqualFold(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEqualFold(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDContainsFold applies the ContainsFold predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDContainsFold(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldContainsFold(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionItemIDEQ applies the EQ predicate on the "subscription_item_id" field. +func SubscriptionItemIDEQ(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDNEQ applies the NEQ predicate on the "subscription_item_id" field. +func SubscriptionItemIDNEQ(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDIn applies the In predicate on the "subscription_item_id" field. +func SubscriptionItemIDIn(vs ...string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldSubscriptionItemID, vs...)) +} + +// SubscriptionItemIDNotIn applies the NotIn predicate on the "subscription_item_id" field. +func SubscriptionItemIDNotIn(vs ...string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldSubscriptionItemID, vs...)) +} + +// SubscriptionItemIDGT applies the GT predicate on the "subscription_item_id" field. +func SubscriptionItemIDGT(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDGTE applies the GTE predicate on the "subscription_item_id" field. +func SubscriptionItemIDGTE(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDLT applies the LT predicate on the "subscription_item_id" field. +func SubscriptionItemIDLT(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDLTE applies the LTE predicate on the "subscription_item_id" field. +func SubscriptionItemIDLTE(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDContains applies the Contains predicate on the "subscription_item_id" field. +func SubscriptionItemIDContains(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldContains(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDHasPrefix applies the HasPrefix predicate on the "subscription_item_id" field. +func SubscriptionItemIDHasPrefix(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldHasPrefix(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDHasSuffix applies the HasSuffix predicate on the "subscription_item_id" field. +func SubscriptionItemIDHasSuffix(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldHasSuffix(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDIsNil applies the IsNil predicate on the "subscription_item_id" field. +func SubscriptionItemIDIsNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIsNull(FieldSubscriptionItemID)) +} + +// SubscriptionItemIDNotNil applies the NotNil predicate on the "subscription_item_id" field. +func SubscriptionItemIDNotNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotNull(FieldSubscriptionItemID)) +} + +// SubscriptionItemIDEqualFold applies the EqualFold predicate on the "subscription_item_id" field. +func SubscriptionItemIDEqualFold(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEqualFold(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDContainsFold applies the ContainsFold predicate on the "subscription_item_id" field. +func SubscriptionItemIDContainsFold(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldContainsFold(FieldSubscriptionItemID, v)) +} + +// AdvanceAfterEQ applies the EQ predicate on the "advance_after" field. +func AdvanceAfterEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldAdvanceAfter, v)) +} + +// AdvanceAfterNEQ applies the NEQ predicate on the "advance_after" field. +func AdvanceAfterNEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldAdvanceAfter, v)) +} + +// AdvanceAfterIn applies the In predicate on the "advance_after" field. +func AdvanceAfterIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldAdvanceAfter, vs...)) +} + +// AdvanceAfterNotIn applies the NotIn predicate on the "advance_after" field. +func AdvanceAfterNotIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldAdvanceAfter, vs...)) +} + +// AdvanceAfterGT applies the GT predicate on the "advance_after" field. +func AdvanceAfterGT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldAdvanceAfter, v)) +} + +// AdvanceAfterGTE applies the GTE predicate on the "advance_after" field. +func AdvanceAfterGTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldAdvanceAfter, v)) +} + +// AdvanceAfterLT applies the LT predicate on the "advance_after" field. +func AdvanceAfterLT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldAdvanceAfter, v)) +} + +// AdvanceAfterLTE applies the LTE predicate on the "advance_after" field. +func AdvanceAfterLTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldAdvanceAfter, v)) +} + +// AdvanceAfterIsNil applies the IsNil predicate on the "advance_after" field. +func AdvanceAfterIsNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIsNull(FieldAdvanceAfter)) +} + +// AdvanceAfterNotNil applies the NotNil predicate on the "advance_after" field. +func AdvanceAfterNotNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotNull(FieldAdvanceAfter)) +} + +// TaxCodeIDEQ applies the EQ predicate on the "tax_code_id" field. +func TaxCodeIDEQ(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldTaxCodeID, v)) +} + +// TaxCodeIDNEQ applies the NEQ predicate on the "tax_code_id" field. +func TaxCodeIDNEQ(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldTaxCodeID, v)) +} + +// TaxCodeIDIn applies the In predicate on the "tax_code_id" field. +func TaxCodeIDIn(vs ...string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldTaxCodeID, vs...)) +} + +// TaxCodeIDNotIn applies the NotIn predicate on the "tax_code_id" field. +func TaxCodeIDNotIn(vs ...string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldTaxCodeID, vs...)) +} + +// TaxCodeIDGT applies the GT predicate on the "tax_code_id" field. +func TaxCodeIDGT(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldTaxCodeID, v)) +} + +// TaxCodeIDGTE applies the GTE predicate on the "tax_code_id" field. +func TaxCodeIDGTE(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldTaxCodeID, v)) +} + +// TaxCodeIDLT applies the LT predicate on the "tax_code_id" field. +func TaxCodeIDLT(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldTaxCodeID, v)) +} + +// TaxCodeIDLTE applies the LTE predicate on the "tax_code_id" field. +func TaxCodeIDLTE(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldTaxCodeID, v)) +} + +// TaxCodeIDContains applies the Contains predicate on the "tax_code_id" field. +func TaxCodeIDContains(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldContains(FieldTaxCodeID, v)) +} + +// TaxCodeIDHasPrefix applies the HasPrefix predicate on the "tax_code_id" field. +func TaxCodeIDHasPrefix(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldHasPrefix(FieldTaxCodeID, v)) +} + +// TaxCodeIDHasSuffix applies the HasSuffix predicate on the "tax_code_id" field. +func TaxCodeIDHasSuffix(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldHasSuffix(FieldTaxCodeID, v)) +} + +// TaxCodeIDEqualFold applies the EqualFold predicate on the "tax_code_id" field. +func TaxCodeIDEqualFold(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEqualFold(FieldTaxCodeID, v)) +} + +// TaxCodeIDContainsFold applies the ContainsFold predicate on the "tax_code_id" field. +func TaxCodeIDContainsFold(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldContainsFold(FieldTaxCodeID, v)) +} + +// TaxBehaviorEQ applies the EQ predicate on the "tax_behavior" field. +func TaxBehaviorEQ(v productcatalog.TaxBehavior) predicate.ChargesSearchV1 { + vc := v + return predicate.ChargesSearchV1(sql.FieldEQ(FieldTaxBehavior, vc)) +} + +// TaxBehaviorNEQ applies the NEQ predicate on the "tax_behavior" field. +func TaxBehaviorNEQ(v productcatalog.TaxBehavior) predicate.ChargesSearchV1 { + vc := v + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldTaxBehavior, vc)) +} + +// TaxBehaviorIn applies the In predicate on the "tax_behavior" field. +func TaxBehaviorIn(vs ...productcatalog.TaxBehavior) predicate.ChargesSearchV1 { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargesSearchV1(sql.FieldIn(FieldTaxBehavior, v...)) +} + +// TaxBehaviorNotIn applies the NotIn predicate on the "tax_behavior" field. +func TaxBehaviorNotIn(vs ...productcatalog.TaxBehavior) predicate.ChargesSearchV1 { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldTaxBehavior, v...)) +} + +// TaxBehaviorIsNil applies the IsNil predicate on the "tax_behavior" field. +func TaxBehaviorIsNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIsNull(FieldTaxBehavior)) +} + +// TaxBehaviorNotNil applies the NotNil predicate on the "tax_behavior" field. +func TaxBehaviorNotNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotNull(FieldTaxBehavior)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotNull(FieldAnnotations)) +} + +// IDEQ applies the EQ predicate on the "id" field. +func IDEQ(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldID, v)) +} + +// IDNEQ applies the NEQ predicate on the "id" field. +func IDNEQ(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldID, v)) +} + +// IDIn applies the In predicate on the "id" field. +func IDIn(vs ...string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldID, vs...)) +} + +// IDNotIn applies the NotIn predicate on the "id" field. +func IDNotIn(vs ...string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldID, vs...)) +} + +// IDGT applies the GT predicate on the "id" field. +func IDGT(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldID, v)) +} + +// IDGTE applies the GTE predicate on the "id" field. +func IDGTE(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldID, v)) +} + +// IDLT applies the LT predicate on the "id" field. +func IDLT(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldID, v)) +} + +// IDLTE applies the LTE predicate on the "id" field. +func IDLTE(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldID, v)) +} + +// IDEqualFold applies the EqualFold predicate on the "id" field. +func IDEqualFold(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEqualFold(FieldID, v)) +} + +// IDContainsFold applies the ContainsFold predicate on the "id" field. +func IDContainsFold(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldContainsFold(FieldID, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldContainsFold(FieldNamespace, v)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotNull(FieldMetadata)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotNull(FieldDeletedAt)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldContainsFold(FieldName, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.FieldContainsFold(FieldDescription, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.ChargesSearchV1) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ChargesSearchV1) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ChargesSearchV1) predicate.ChargesSearchV1 { + return predicate.ChargesSearchV1(sql.NotPredicates(p)) +} diff --git a/ent/db/chargessearchv1_query.go b/ent/db/chargessearchv1_query.go new file mode 100644 index 0000000000000000000000000000000000000000..cdec9cb980641fd410448c0cb9c4295069d74d82 --- /dev/null +++ b/ent/db/chargessearchv1_query.go @@ -0,0 +1,488 @@ +// 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" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargessearchv1" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargesSearchV1Query is the builder for querying ChargesSearchV1 entities. +type ChargesSearchV1Query struct { + config + ctx *QueryContext + order []chargessearchv1.OrderOption + inters []Interceptor + predicates []predicate.ChargesSearchV1 + 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 ChargesSearchV1Query builder. +func (_q *ChargesSearchV1Query) Where(ps ...predicate.ChargesSearchV1) *ChargesSearchV1Query { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ChargesSearchV1Query) Limit(limit int) *ChargesSearchV1Query { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ChargesSearchV1Query) Offset(offset int) *ChargesSearchV1Query { + _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 *ChargesSearchV1Query) Unique(unique bool) *ChargesSearchV1Query { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ChargesSearchV1Query) Order(o ...chargessearchv1.OrderOption) *ChargesSearchV1Query { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first ChargesSearchV1 entity from the query. +// Returns a *NotFoundError when no ChargesSearchV1 was found. +func (_q *ChargesSearchV1Query) First(ctx context.Context) (*ChargesSearchV1, 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{chargessearchv1.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ChargesSearchV1Query) FirstX(ctx context.Context) *ChargesSearchV1 { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// Only returns a single ChargesSearchV1 entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ChargesSearchV1 entity is found. +// Returns a *NotFoundError when no ChargesSearchV1 entities are found. +func (_q *ChargesSearchV1Query) Only(ctx context.Context) (*ChargesSearchV1, 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{chargessearchv1.Label} + default: + return nil, &NotSingularError{chargessearchv1.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ChargesSearchV1Query) OnlyX(ctx context.Context) *ChargesSearchV1 { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// All executes the query and returns a list of ChargesSearchV1s. +func (_q *ChargesSearchV1Query) All(ctx context.Context) ([]*ChargesSearchV1, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ChargesSearchV1, *ChargesSearchV1Query]() + return withInterceptors[[]*ChargesSearchV1](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ChargesSearchV1Query) AllX(ctx context.Context) []*ChargesSearchV1 { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// Count returns the count of the given query. +func (_q *ChargesSearchV1Query) 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[*ChargesSearchV1Query](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ChargesSearchV1Query) 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 *ChargesSearchV1Query) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.First(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 *ChargesSearchV1Query) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ChargesSearchV1Query 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 *ChargesSearchV1Query) Clone() *ChargesSearchV1Query { + if _q == nil { + return nil + } + return &ChargesSearchV1Query{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]chargessearchv1.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ChargesSearchV1{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// 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 { +// Type meta.ChargeType `json:"type,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.ChargesSearchV1.Query(). +// GroupBy(chargessearchv1.FieldType). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *ChargesSearchV1Query) GroupBy(field string, fields ...string) *ChargesSearchV1GroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ChargesSearchV1GroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = chargessearchv1.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 { +// Type meta.ChargeType `json:"type,omitempty"` +// } +// +// client.ChargesSearchV1.Query(). +// Select(chargessearchv1.FieldType). +// Scan(ctx, &v) +func (_q *ChargesSearchV1Query) Select(fields ...string) *ChargesSearchV1Select { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ChargesSearchV1Select{ChargesSearchV1Query: _q} + sbuild.label = chargessearchv1.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ChargesSearchV1Select configured with the given aggregations. +func (_q *ChargesSearchV1Query) Aggregate(fns ...AggregateFunc) *ChargesSearchV1Select { + return _q.Select().Aggregate(fns...) +} + +func (_q *ChargesSearchV1Query) 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 !chargessearchv1.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 *ChargesSearchV1Query) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ChargesSearchV1, error) { + var ( + nodes = []*ChargesSearchV1{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ChargesSearchV1).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ChargesSearchV1{config: _q.config} + nodes = append(nodes, node) + 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 + } + return nodes, nil +} + +func (_q *ChargesSearchV1Query) 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 *ChargesSearchV1Query) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(chargessearchv1.Table, chargessearchv1.Columns, nil) + _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)) + for i := range fields { + _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 *ChargesSearchV1Query) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(chargessearchv1.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = chargessearchv1.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 *ChargesSearchV1Query) ForUpdate(opts ...sql.LockOption) *ChargesSearchV1Query { + 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 *ChargesSearchV1Query) ForShare(opts ...sql.LockOption) *ChargesSearchV1Query { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ChargesSearchV1GroupBy is the group-by builder for ChargesSearchV1 entities. +type ChargesSearchV1GroupBy struct { + selector + build *ChargesSearchV1Query +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ChargesSearchV1GroupBy) Aggregate(fns ...AggregateFunc) *ChargesSearchV1GroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ChargesSearchV1GroupBy) 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[*ChargesSearchV1Query, *ChargesSearchV1GroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ChargesSearchV1GroupBy) sqlScan(ctx context.Context, root *ChargesSearchV1Query, 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) +} + +// ChargesSearchV1Select is the builder for selecting fields of ChargesSearchV1 entities. +type ChargesSearchV1Select struct { + *ChargesSearchV1Query + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ChargesSearchV1Select) Aggregate(fns ...AggregateFunc) *ChargesSearchV1Select { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ChargesSearchV1Select) 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[*ChargesSearchV1Query, *ChargesSearchV1Select](ctx, _s.ChargesSearchV1Query, _s, _s.inters, v) +} + +func (_s *ChargesSearchV1Select) sqlScan(ctx context.Context, root *ChargesSearchV1Query, 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/ent/db/chargeusagebased.go b/ent/db/chargeusagebased.go new file mode 100644 index 0000000000000000000000000000000000000000..ce2c0d8eb36bf435e23c1d2959d29ec2797cff2c --- /dev/null +++ b/ent/db/chargeusagebased.go @@ -0,0 +1,755 @@ +// 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/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedoverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/openmeter/ent/db/customer" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionphase" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeUsageBased is the model entity for the ChargeUsageBased schema. +type ChargeUsageBased struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // CustomerID holds the value of the "customer_id" field. + CustomerID string `json:"customer_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"` + // BillingPeriodFrom holds the value of the "billing_period_from" field. + BillingPeriodFrom time.Time `json:"billing_period_from,omitempty"` + // BillingPeriodTo holds the value of the "billing_period_to" field. + BillingPeriodTo time.Time `json:"billing_period_to,omitempty"` + // FullServicePeriodFrom holds the value of the "full_service_period_from" field. + FullServicePeriodFrom time.Time `json:"full_service_period_from,omitempty"` + // FullServicePeriodTo holds the value of the "full_service_period_to" field. + FullServicePeriodTo time.Time `json:"full_service_period_to,omitempty"` + // Status holds the value of the "status" field. + Status meta.ChargeStatus `json:"status,omitempty"` + // UniqueReferenceID holds the value of the "unique_reference_id" field. + UniqueReferenceID *string `json:"unique_reference_id,omitempty"` + // Currency holds the value of the "currency" field. + Currency currencyx.Code `json:"currency,omitempty"` + // ManagedBy holds the value of the "managed_by" field. + ManagedBy billing.InvoiceLineManagedBy `json:"managed_by,omitempty"` + // SubscriptionID holds the value of the "subscription_id" field. + SubscriptionID *string `json:"subscription_id,omitempty"` + // SubscriptionPhaseID holds the value of the "subscription_phase_id" field. + SubscriptionPhaseID *string `json:"subscription_phase_id,omitempty"` + // SubscriptionItemID holds the value of the "subscription_item_id" field. + SubscriptionItemID *string `json:"subscription_item_id,omitempty"` + // AdvanceAfter holds the value of the "advance_after" field. + AdvanceAfter *time.Time `json:"advance_after,omitempty"` + // TaxCodeID holds the value of the "tax_code_id" field. + TaxCodeID string `json:"tax_code_id,omitempty"` + // TaxBehavior holds the value of the "tax_behavior" field. + TaxBehavior *productcatalog.TaxBehavior `json:"tax_behavior,omitempty"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,omitempty"` + // Namespace holds the value of the "namespace" field. + Namespace string `json:"namespace,omitempty"` + // Metadata holds the value of the "metadata" field. + Metadata map[string]string `json:"metadata,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"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Description holds the value of the "description" field. + Description *string `json:"description,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"` + // IntentDeletedAt holds the value of the "intent_deleted_at" field. + IntentDeletedAt *time.Time `json:"intent_deleted_at,omitempty"` + // Discounts holds the value of the "discounts" field. + Discounts *billing.Discounts `json:"discounts,omitempty"` + // FeatureKey holds the value of the "feature_key" field. + FeatureKey string `json:"feature_key,omitempty"` + // FeatureID holds the value of the "feature_id" field. + FeatureID string `json:"feature_id,omitempty"` + // RatingEngine holds the value of the "rating_engine" field. + RatingEngine usagebased.RatingEngine `json:"rating_engine,omitempty"` + // Price holds the value of the "price" field. + Price *productcatalog.Price `json:"price,omitempty"` + // UnitConfig holds the value of the "unit_config" field. + UnitConfig *productcatalog.UnitConfig `json:"unit_config,omitempty"` + // CurrentRealizationRunID holds the value of the "current_realization_run_id" field. + CurrentRealizationRunID *string `json:"current_realization_run_id,omitempty"` + // StatusDetailed holds the value of the "status_detailed" field. + StatusDetailed usagebased.Status `json:"status_detailed,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 { + // Runs holds the value of the runs edge. + Runs []*ChargeUsageBasedRuns `json:"runs,omitempty"` + // DetailedLines holds the value of the detailed_lines edge. + DetailedLines []*ChargeUsageBasedRunDetailedLine `json:"detailed_lines,omitempty"` + // CurrentRun holds the value of the current_run edge. + CurrentRun *ChargeUsageBasedRuns `json:"current_run,omitempty"` + // Charge holds the value of the charge edge. + Charge *Charge `json:"charge,omitempty"` + // IntentOverride holds the value of the intent_override edge. + IntentOverride *ChargeUsageBasedOverride `json:"intent_override,omitempty"` + // Subscription holds the value of the subscription edge. + Subscription *Subscription `json:"subscription,omitempty"` + // SubscriptionPhase holds the value of the subscription_phase edge. + SubscriptionPhase *SubscriptionPhase `json:"subscription_phase,omitempty"` + // SubscriptionItem holds the value of the subscription_item edge. + SubscriptionItem *SubscriptionItem `json:"subscription_item,omitempty"` + // Customer holds the value of the customer edge. + Customer *Customer `json:"customer,omitempty"` + // Feature holds the value of the feature edge. + Feature *Feature `json:"feature,omitempty"` + // TaxCode holds the value of the tax_code edge. + TaxCode *TaxCode `json:"tax_code,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [11]bool +} + +// 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[0] { + return e.Runs, nil + } + return nil, &NotLoadedError{edge: "runs"} +} + +// DetailedLinesOrErr returns the DetailedLines value or an error if the edge +// was not loaded in eager-loading. +func (e ChargeUsageBasedEdges) DetailedLinesOrErr() ([]*ChargeUsageBasedRunDetailedLine, error) { + if e.loadedTypes[1] { + return e.DetailedLines, nil + } + return nil, &NotLoadedError{edge: "detailed_lines"} +} + +// CurrentRunOrErr returns the CurrentRun value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedEdges) CurrentRunOrErr() (*ChargeUsageBasedRuns, error) { + if e.CurrentRun != nil { + return e.CurrentRun, nil + } else if e.loadedTypes[2] { + return nil, &NotFoundError{label: chargeusagebasedruns.Label} + } + return nil, &NotLoadedError{edge: "current_run"} +} + +// 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[3] { + return nil, &NotFoundError{label: charge.Label} + } + return nil, &NotLoadedError{edge: "charge"} +} + +// IntentOverrideOrErr returns the IntentOverride value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedEdges) IntentOverrideOrErr() (*ChargeUsageBasedOverride, error) { + if e.IntentOverride != nil { + return e.IntentOverride, nil + } else if e.loadedTypes[4] { + return nil, &NotFoundError{label: chargeusagebasedoverride.Label} + } + return nil, &NotLoadedError{edge: "intent_override"} +} + +// SubscriptionOrErr returns the Subscription value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedEdges) SubscriptionOrErr() (*Subscription, error) { + if e.Subscription != nil { + return e.Subscription, nil + } else if e.loadedTypes[5] { + return nil, &NotFoundError{label: subscription.Label} + } + return nil, &NotLoadedError{edge: "subscription"} +} + +// SubscriptionPhaseOrErr returns the SubscriptionPhase value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedEdges) SubscriptionPhaseOrErr() (*SubscriptionPhase, error) { + if e.SubscriptionPhase != nil { + return e.SubscriptionPhase, nil + } else if e.loadedTypes[6] { + return nil, &NotFoundError{label: subscriptionphase.Label} + } + return nil, &NotLoadedError{edge: "subscription_phase"} +} + +// SubscriptionItemOrErr returns the SubscriptionItem value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedEdges) SubscriptionItemOrErr() (*SubscriptionItem, error) { + if e.SubscriptionItem != nil { + return e.SubscriptionItem, nil + } else if e.loadedTypes[7] { + return nil, &NotFoundError{label: subscriptionitem.Label} + } + return nil, &NotLoadedError{edge: "subscription_item"} +} + +// CustomerOrErr returns the Customer value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedEdges) CustomerOrErr() (*Customer, error) { + if e.Customer != nil { + return e.Customer, nil + } else if e.loadedTypes[8] { + return nil, &NotFoundError{label: customer.Label} + } + return nil, &NotLoadedError{edge: "customer"} +} + +// FeatureOrErr returns the Feature value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedEdges) FeatureOrErr() (*Feature, error) { + if e.Feature != nil { + return e.Feature, nil + } else if e.loadedTypes[9] { + return nil, &NotFoundError{label: dbfeature.Label} + } + return nil, &NotLoadedError{edge: "feature"} +} + +// TaxCodeOrErr returns the TaxCode value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedEdges) TaxCodeOrErr() (*TaxCode, error) { + if e.TaxCode != nil { + return e.TaxCode, nil + } else if e.loadedTypes[10] { + return nil, &NotFoundError{label: dbtaxcode.Label} + } + return nil, &NotLoadedError{edge: "tax_code"} +} + +// 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.FieldAnnotations, chargeusagebased.FieldMetadata: + values[i] = new([]byte) + case chargeusagebased.FieldID, chargeusagebased.FieldCustomerID, chargeusagebased.FieldStatus, chargeusagebased.FieldUniqueReferenceID, chargeusagebased.FieldCurrency, chargeusagebased.FieldManagedBy, chargeusagebased.FieldSubscriptionID, chargeusagebased.FieldSubscriptionPhaseID, chargeusagebased.FieldSubscriptionItemID, chargeusagebased.FieldTaxCodeID, chargeusagebased.FieldTaxBehavior, chargeusagebased.FieldNamespace, chargeusagebased.FieldName, chargeusagebased.FieldDescription, chargeusagebased.FieldSettlementMode, chargeusagebased.FieldFeatureKey, chargeusagebased.FieldFeatureID, chargeusagebased.FieldRatingEngine, chargeusagebased.FieldCurrentRealizationRunID, chargeusagebased.FieldStatusDetailed: + values[i] = new(sql.NullString) + case chargeusagebased.FieldServicePeriodFrom, chargeusagebased.FieldServicePeriodTo, chargeusagebased.FieldBillingPeriodFrom, chargeusagebased.FieldBillingPeriodTo, chargeusagebased.FieldFullServicePeriodFrom, chargeusagebased.FieldFullServicePeriodTo, chargeusagebased.FieldAdvanceAfter, chargeusagebased.FieldCreatedAt, chargeusagebased.FieldUpdatedAt, chargeusagebased.FieldDeletedAt, chargeusagebased.FieldInvoiceAt, chargeusagebased.FieldIntentDeletedAt: + values[i] = new(sql.NullTime) + case chargeusagebased.FieldDiscounts: + values[i] = chargeusagebased.ValueScanner.Discounts.ScanValue() + case chargeusagebased.FieldPrice: + values[i] = chargeusagebased.ValueScanner.Price.ScanValue() + case chargeusagebased.FieldUnitConfig: + values[i] = chargeusagebased.ValueScanner.UnitConfig.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.FieldCustomerID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field customer_id", values[i]) + } else if value.Valid { + _m.CustomerID = value.String + } + case chargeusagebased.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 chargeusagebased.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 chargeusagebased.FieldBillingPeriodFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field billing_period_from", values[i]) + } else if value.Valid { + _m.BillingPeriodFrom = value.Time + } + case chargeusagebased.FieldBillingPeriodTo: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field billing_period_to", values[i]) + } else if value.Valid { + _m.BillingPeriodTo = value.Time + } + case chargeusagebased.FieldFullServicePeriodFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field full_service_period_from", values[i]) + } else if value.Valid { + _m.FullServicePeriodFrom = value.Time + } + case chargeusagebased.FieldFullServicePeriodTo: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field full_service_period_to", values[i]) + } else if value.Valid { + _m.FullServicePeriodTo = value.Time + } + case chargeusagebased.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 = meta.ChargeStatus(value.String) + } + case chargeusagebased.FieldUniqueReferenceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field unique_reference_id", values[i]) + } else if value.Valid { + _m.UniqueReferenceID = new(string) + *_m.UniqueReferenceID = value.String + } + case chargeusagebased.FieldCurrency: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field currency", values[i]) + } else if value.Valid { + _m.Currency = currencyx.Code(value.String) + } + case chargeusagebased.FieldManagedBy: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field managed_by", values[i]) + } else if value.Valid { + _m.ManagedBy = billing.InvoiceLineManagedBy(value.String) + } + case chargeusagebased.FieldSubscriptionID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field subscription_id", values[i]) + } else if value.Valid { + _m.SubscriptionID = new(string) + *_m.SubscriptionID = value.String + } + case chargeusagebased.FieldSubscriptionPhaseID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field subscription_phase_id", values[i]) + } else if value.Valid { + _m.SubscriptionPhaseID = new(string) + *_m.SubscriptionPhaseID = value.String + } + case chargeusagebased.FieldSubscriptionItemID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field subscription_item_id", values[i]) + } else if value.Valid { + _m.SubscriptionItemID = new(string) + *_m.SubscriptionItemID = value.String + } + case chargeusagebased.FieldAdvanceAfter: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field advance_after", values[i]) + } else if value.Valid { + _m.AdvanceAfter = new(time.Time) + *_m.AdvanceAfter = value.Time + } + case chargeusagebased.FieldTaxCodeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field tax_code_id", values[i]) + } else if value.Valid { + _m.TaxCodeID = value.String + } + case chargeusagebased.FieldTaxBehavior: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field tax_behavior", values[i]) + } else if value.Valid { + _m.TaxBehavior = new(productcatalog.TaxBehavior) + *_m.TaxBehavior = productcatalog.TaxBehavior(value.String) + } + case chargeusagebased.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 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.FieldMetadata: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field metadata", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Metadata); err != nil { + return fmt.Errorf("unmarshal field metadata: %w", err) + } + } + case chargeusagebased.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 chargeusagebased.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 chargeusagebased.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 chargeusagebased.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case chargeusagebased.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + _m.Description = new(string) + *_m.Description = 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.FieldIntentDeletedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field intent_deleted_at", values[i]) + } else if value.Valid { + _m.IntentDeletedAt = new(time.Time) + *_m.IntentDeletedAt = value.Time + } + 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.FieldFeatureID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field feature_id", values[i]) + } else if value.Valid { + _m.FeatureID = value.String + } + case chargeusagebased.FieldRatingEngine: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field rating_engine", values[i]) + } else if value.Valid { + _m.RatingEngine = usagebased.RatingEngine(value.String) + } + case chargeusagebased.FieldPrice: + if value, err := chargeusagebased.ValueScanner.Price.FromValue(values[i]); err != nil { + return err + } else { + _m.Price = value + } + case chargeusagebased.FieldUnitConfig: + if value, err := chargeusagebased.ValueScanner.UnitConfig.FromValue(values[i]); err != nil { + return err + } else { + _m.UnitConfig = value + } + case chargeusagebased.FieldCurrentRealizationRunID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field current_realization_run_id", values[i]) + } else if value.Valid { + _m.CurrentRealizationRunID = new(string) + *_m.CurrentRealizationRunID = value.String + } + case chargeusagebased.FieldStatusDetailed: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field status_detailed", values[i]) + } else if value.Valid { + _m.StatusDetailed = usagebased.Status(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 ChargeUsageBased. +// This includes values selected through modifiers, order, etc. +func (_m *ChargeUsageBased) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryRuns queries the "runs" edge of the ChargeUsageBased entity. +func (_m *ChargeUsageBased) QueryRuns() *ChargeUsageBasedRunsQuery { + return NewChargeUsageBasedClient(_m.config).QueryRuns(_m) +} + +// QueryDetailedLines queries the "detailed_lines" edge of the ChargeUsageBased entity. +func (_m *ChargeUsageBased) QueryDetailedLines() *ChargeUsageBasedRunDetailedLineQuery { + return NewChargeUsageBasedClient(_m.config).QueryDetailedLines(_m) +} + +// QueryCurrentRun queries the "current_run" edge of the ChargeUsageBased entity. +func (_m *ChargeUsageBased) QueryCurrentRun() *ChargeUsageBasedRunsQuery { + return NewChargeUsageBasedClient(_m.config).QueryCurrentRun(_m) +} + +// QueryCharge queries the "charge" edge of the ChargeUsageBased entity. +func (_m *ChargeUsageBased) QueryCharge() *ChargeQuery { + return NewChargeUsageBasedClient(_m.config).QueryCharge(_m) +} + +// QueryIntentOverride queries the "intent_override" edge of the ChargeUsageBased entity. +func (_m *ChargeUsageBased) QueryIntentOverride() *ChargeUsageBasedOverrideQuery { + return NewChargeUsageBasedClient(_m.config).QueryIntentOverride(_m) +} + +// QuerySubscription queries the "subscription" edge of the ChargeUsageBased entity. +func (_m *ChargeUsageBased) QuerySubscription() *SubscriptionQuery { + return NewChargeUsageBasedClient(_m.config).QuerySubscription(_m) +} + +// QuerySubscriptionPhase queries the "subscription_phase" edge of the ChargeUsageBased entity. +func (_m *ChargeUsageBased) QuerySubscriptionPhase() *SubscriptionPhaseQuery { + return NewChargeUsageBasedClient(_m.config).QuerySubscriptionPhase(_m) +} + +// QuerySubscriptionItem queries the "subscription_item" edge of the ChargeUsageBased entity. +func (_m *ChargeUsageBased) QuerySubscriptionItem() *SubscriptionItemQuery { + return NewChargeUsageBasedClient(_m.config).QuerySubscriptionItem(_m) +} + +// QueryCustomer queries the "customer" edge of the ChargeUsageBased entity. +func (_m *ChargeUsageBased) QueryCustomer() *CustomerQuery { + return NewChargeUsageBasedClient(_m.config).QueryCustomer(_m) +} + +// QueryFeature queries the "feature" edge of the ChargeUsageBased entity. +func (_m *ChargeUsageBased) QueryFeature() *FeatureQuery { + return NewChargeUsageBasedClient(_m.config).QueryFeature(_m) +} + +// QueryTaxCode queries the "tax_code" edge of the ChargeUsageBased entity. +func (_m *ChargeUsageBased) QueryTaxCode() *TaxCodeQuery { + return NewChargeUsageBasedClient(_m.config).QueryTaxCode(_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("customer_id=") + builder.WriteString(_m.CustomerID) + 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("billing_period_from=") + builder.WriteString(_m.BillingPeriodFrom.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("billing_period_to=") + builder.WriteString(_m.BillingPeriodTo.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("full_service_period_from=") + builder.WriteString(_m.FullServicePeriodFrom.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("full_service_period_to=") + builder.WriteString(_m.FullServicePeriodTo.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("status=") + builder.WriteString(fmt.Sprintf("%v", _m.Status)) + builder.WriteString(", ") + if v := _m.UniqueReferenceID; v != nil { + builder.WriteString("unique_reference_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("currency=") + builder.WriteString(fmt.Sprintf("%v", _m.Currency)) + builder.WriteString(", ") + builder.WriteString("managed_by=") + builder.WriteString(fmt.Sprintf("%v", _m.ManagedBy)) + builder.WriteString(", ") + if v := _m.SubscriptionID; v != nil { + builder.WriteString("subscription_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SubscriptionPhaseID; v != nil { + builder.WriteString("subscription_phase_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SubscriptionItemID; v != nil { + builder.WriteString("subscription_item_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.AdvanceAfter; v != nil { + builder.WriteString("advance_after=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + builder.WriteString("tax_code_id=") + builder.WriteString(_m.TaxCodeID) + builder.WriteString(", ") + if v := _m.TaxBehavior; v != nil { + builder.WriteString("tax_behavior=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + builder.WriteString(", ") + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("metadata=") + builder.WriteString(fmt.Sprintf("%v", _m.Metadata)) + 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("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + if v := _m.Description; v != nil { + builder.WriteString("description=") + builder.WriteString(*v) + } + 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.IntentDeletedAt; v != nil { + builder.WriteString("intent_deleted_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + 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("feature_id=") + builder.WriteString(_m.FeatureID) + builder.WriteString(", ") + builder.WriteString("rating_engine=") + builder.WriteString(fmt.Sprintf("%v", _m.RatingEngine)) + builder.WriteString(", ") + builder.WriteString("price=") + builder.WriteString(fmt.Sprintf("%v", _m.Price)) + builder.WriteString(", ") + if v := _m.UnitConfig; v != nil { + builder.WriteString("unit_config=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.CurrentRealizationRunID; v != nil { + builder.WriteString("current_realization_run_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("status_detailed=") + builder.WriteString(fmt.Sprintf("%v", _m.StatusDetailed)) + builder.WriteByte(')') + return builder.String() +} + +// ChargeUsageBaseds is a parsable slice of ChargeUsageBased. +type ChargeUsageBaseds []*ChargeUsageBased diff --git a/ent/db/chargeusagebased/chargeusagebased.go b/ent/db/chargeusagebased/chargeusagebased.go new file mode 100644 index 0000000000000000000000000000000000000000..e973f2784e5679370d42d9026f3221582c0e4804 --- /dev/null +++ b/ent/db/chargeusagebased/chargeusagebased.go @@ -0,0 +1,682 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeusagebased + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" + "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" + // FieldCustomerID holds the string denoting the customer_id field in the database. + FieldCustomerID = "customer_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" + // FieldBillingPeriodFrom holds the string denoting the billing_period_from field in the database. + FieldBillingPeriodFrom = "billing_period_from" + // FieldBillingPeriodTo holds the string denoting the billing_period_to field in the database. + FieldBillingPeriodTo = "billing_period_to" + // FieldFullServicePeriodFrom holds the string denoting the full_service_period_from field in the database. + FieldFullServicePeriodFrom = "full_service_period_from" + // FieldFullServicePeriodTo holds the string denoting the full_service_period_to field in the database. + FieldFullServicePeriodTo = "full_service_period_to" + // FieldStatus holds the string denoting the status field in the database. + FieldStatus = "status" + // FieldUniqueReferenceID holds the string denoting the unique_reference_id field in the database. + FieldUniqueReferenceID = "unique_reference_id" + // FieldCurrency holds the string denoting the currency field in the database. + FieldCurrency = "currency" + // FieldManagedBy holds the string denoting the managed_by field in the database. + FieldManagedBy = "managed_by" + // FieldSubscriptionID holds the string denoting the subscription_id field in the database. + FieldSubscriptionID = "subscription_id" + // FieldSubscriptionPhaseID holds the string denoting the subscription_phase_id field in the database. + FieldSubscriptionPhaseID = "subscription_phase_id" + // FieldSubscriptionItemID holds the string denoting the subscription_item_id field in the database. + FieldSubscriptionItemID = "subscription_item_id" + // FieldAdvanceAfter holds the string denoting the advance_after field in the database. + FieldAdvanceAfter = "advance_after" + // FieldTaxCodeID holds the string denoting the tax_code_id field in the database. + FieldTaxCodeID = "tax_code_id" + // FieldTaxBehavior holds the string denoting the tax_behavior field in the database. + FieldTaxBehavior = "tax_behavior" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // FieldNamespace holds the string denoting the namespace field in the database. + FieldNamespace = "namespace" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // 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" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // 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" + // FieldIntentDeletedAt holds the string denoting the intent_deleted_at field in the database. + FieldIntentDeletedAt = "intent_deleted_at" + // 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" + // FieldFeatureID holds the string denoting the feature_id field in the database. + FieldFeatureID = "feature_id" + // FieldRatingEngine holds the string denoting the rating_engine field in the database. + FieldRatingEngine = "rating_engine" + // FieldPrice holds the string denoting the price field in the database. + FieldPrice = "price" + // FieldUnitConfig holds the string denoting the unit_config field in the database. + FieldUnitConfig = "unit_config" + // FieldCurrentRealizationRunID holds the string denoting the current_realization_run_id field in the database. + FieldCurrentRealizationRunID = "current_realization_run_id" + // FieldStatusDetailed holds the string denoting the status_detailed field in the database. + FieldStatusDetailed = "status_detailed" + // EdgeRuns holds the string denoting the runs edge name in mutations. + EdgeRuns = "runs" + // EdgeDetailedLines holds the string denoting the detailed_lines edge name in mutations. + EdgeDetailedLines = "detailed_lines" + // EdgeCurrentRun holds the string denoting the current_run edge name in mutations. + EdgeCurrentRun = "current_run" + // EdgeCharge holds the string denoting the charge edge name in mutations. + EdgeCharge = "charge" + // EdgeIntentOverride holds the string denoting the intent_override edge name in mutations. + EdgeIntentOverride = "intent_override" + // EdgeSubscription holds the string denoting the subscription edge name in mutations. + EdgeSubscription = "subscription" + // EdgeSubscriptionPhase holds the string denoting the subscription_phase edge name in mutations. + EdgeSubscriptionPhase = "subscription_phase" + // EdgeSubscriptionItem holds the string denoting the subscription_item edge name in mutations. + EdgeSubscriptionItem = "subscription_item" + // EdgeCustomer holds the string denoting the customer edge name in mutations. + EdgeCustomer = "customer" + // EdgeFeature holds the string denoting the feature edge name in mutations. + EdgeFeature = "feature" + // EdgeTaxCode holds the string denoting the tax_code edge name in mutations. + EdgeTaxCode = "tax_code" + // Table holds the table name of the chargeusagebased in the database. + Table = "charge_usage_based" + // 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" + // DetailedLinesTable is the table that holds the detailed_lines relation/edge. + DetailedLinesTable = "charge_usage_based_run_detailed_line" + // DetailedLinesInverseTable is the table name for the ChargeUsageBasedRunDetailedLine entity. + // It exists in this package in order to avoid circular dependency with the "chargeusagebasedrundetailedline" package. + DetailedLinesInverseTable = "charge_usage_based_run_detailed_line" + // DetailedLinesColumn is the table column denoting the detailed_lines relation/edge. + DetailedLinesColumn = "charge_id" + // CurrentRunTable is the table that holds the current_run relation/edge. + CurrentRunTable = "charge_usage_based" + // CurrentRunInverseTable is the table name for the ChargeUsageBasedRuns entity. + // It exists in this package in order to avoid circular dependency with the "chargeusagebasedruns" package. + CurrentRunInverseTable = "charge_usage_based_runs" + // CurrentRunColumn is the table column denoting the current_run relation/edge. + CurrentRunColumn = "current_realization_run_id" + // ChargeTable is the table that holds the charge relation/edge. + ChargeTable = "charges" + // 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 = "charge_usage_based_id" + // IntentOverrideTable is the table that holds the intent_override relation/edge. + IntentOverrideTable = "charge_usage_based_overrides" + // IntentOverrideInverseTable is the table name for the ChargeUsageBasedOverride entity. + // It exists in this package in order to avoid circular dependency with the "chargeusagebasedoverride" package. + IntentOverrideInverseTable = "charge_usage_based_overrides" + // IntentOverrideColumn is the table column denoting the intent_override relation/edge. + IntentOverrideColumn = "charge_id" + // SubscriptionTable is the table that holds the subscription relation/edge. + SubscriptionTable = "charge_usage_based" + // SubscriptionInverseTable is the table name for the Subscription entity. + // It exists in this package in order to avoid circular dependency with the "subscription" package. + SubscriptionInverseTable = "subscriptions" + // SubscriptionColumn is the table column denoting the subscription relation/edge. + SubscriptionColumn = "subscription_id" + // SubscriptionPhaseTable is the table that holds the subscription_phase relation/edge. + SubscriptionPhaseTable = "charge_usage_based" + // SubscriptionPhaseInverseTable is the table name for the SubscriptionPhase entity. + // It exists in this package in order to avoid circular dependency with the "subscriptionphase" package. + SubscriptionPhaseInverseTable = "subscription_phases" + // SubscriptionPhaseColumn is the table column denoting the subscription_phase relation/edge. + SubscriptionPhaseColumn = "subscription_phase_id" + // SubscriptionItemTable is the table that holds the subscription_item relation/edge. + SubscriptionItemTable = "charge_usage_based" + // SubscriptionItemInverseTable is the table name for the SubscriptionItem entity. + // It exists in this package in order to avoid circular dependency with the "subscriptionitem" package. + SubscriptionItemInverseTable = "subscription_items" + // SubscriptionItemColumn is the table column denoting the subscription_item relation/edge. + SubscriptionItemColumn = "subscription_item_id" + // CustomerTable is the table that holds the customer relation/edge. + CustomerTable = "charge_usage_based" + // CustomerInverseTable is the table name for the Customer entity. + // It exists in this package in order to avoid circular dependency with the "customer" package. + CustomerInverseTable = "customers" + // CustomerColumn is the table column denoting the customer relation/edge. + CustomerColumn = "customer_id" + // FeatureTable is the table that holds the feature relation/edge. + FeatureTable = "charge_usage_based" + // FeatureInverseTable is the table name for the Feature entity. + // It exists in this package in order to avoid circular dependency with the "dbfeature" package. + FeatureInverseTable = "features" + // FeatureColumn is the table column denoting the feature relation/edge. + FeatureColumn = "feature_id" + // TaxCodeTable is the table that holds the tax_code relation/edge. + TaxCodeTable = "charge_usage_based" + // TaxCodeInverseTable is the table name for the TaxCode entity. + // It exists in this package in order to avoid circular dependency with the "dbtaxcode" package. + TaxCodeInverseTable = "tax_codes" + // TaxCodeColumn is the table column denoting the tax_code relation/edge. + TaxCodeColumn = "tax_code_id" +) + +// Columns holds all SQL columns for chargeusagebased fields. +var Columns = []string{ + FieldID, + FieldCustomerID, + FieldServicePeriodFrom, + FieldServicePeriodTo, + FieldBillingPeriodFrom, + FieldBillingPeriodTo, + FieldFullServicePeriodFrom, + FieldFullServicePeriodTo, + FieldStatus, + FieldUniqueReferenceID, + FieldCurrency, + FieldManagedBy, + FieldSubscriptionID, + FieldSubscriptionPhaseID, + FieldSubscriptionItemID, + FieldAdvanceAfter, + FieldTaxCodeID, + FieldTaxBehavior, + FieldAnnotations, + FieldNamespace, + FieldMetadata, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldName, + FieldDescription, + FieldInvoiceAt, + FieldSettlementMode, + FieldIntentDeletedAt, + FieldDiscounts, + FieldFeatureKey, + FieldFeatureID, + FieldRatingEngine, + FieldPrice, + FieldUnitConfig, + FieldCurrentRealizationRunID, + FieldStatusDetailed, +} + +// 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 ( + // CustomerIDValidator is a validator for the "customer_id" field. It is called by the builders before save. + CustomerIDValidator func(string) error + // CurrencyValidator is a validator for the "currency" field. It is called by the builders before save. + CurrencyValidator func(string) error + // TaxCodeIDValidator is a validator for the "tax_code_id" field. It is called by the builders before save. + TaxCodeIDValidator 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 + // FeatureKeyValidator is a validator for the "feature_key" field. It is called by the builders before save. + FeatureKeyValidator func(string) error + // FeatureIDValidator is a validator for the "feature_id" field. It is called by the builders before save. + FeatureIDValidator 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[*billing.Discounts] + Price field.TypeValueScanner[*productcatalog.Price] + UnitConfig field.TypeValueScanner[*productcatalog.UnitConfig] + } +) + +// StatusValidator is a validator for the "status" field enum values. It is called by the builders before save. +func StatusValidator(s meta.ChargeStatus) error { + switch s { + case "created", "active", "final", "deleted": + return nil + default: + return fmt.Errorf("chargeusagebased: invalid enum value for status field: %q", s) + } +} + +// ManagedByValidator is a validator for the "managed_by" field enum values. It is called by the builders before save. +func ManagedByValidator(mb billing.InvoiceLineManagedBy) error { + switch mb { + case "subscription", "system", "manual": + return nil + default: + return fmt.Errorf("chargeusagebased: invalid enum value for managed_by field: %q", mb) + } +} + +// TaxBehaviorValidator is a validator for the "tax_behavior" field enum values. It is called by the builders before save. +func TaxBehaviorValidator(tb productcatalog.TaxBehavior) error { + switch tb { + case "inclusive", "exclusive": + return nil + default: + return fmt.Errorf("chargeusagebased: invalid enum value for tax_behavior field: %q", tb) + } +} + +// 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 "credit_then_invoice", "credit_only": + return nil + default: + return fmt.Errorf("chargeusagebased: invalid enum value for settlement_mode field: %q", sm) + } +} + +// RatingEngineValidator is a validator for the "rating_engine" field enum values. It is called by the builders before save. +func RatingEngineValidator(re usagebased.RatingEngine) error { + switch re { + case "delta", "period_preserving": + return nil + default: + return fmt.Errorf("chargeusagebased: invalid enum value for rating_engine field: %q", re) + } +} + +// StatusDetailedValidator is a validator for the "status_detailed" field enum values. It is called by the builders before save. +func StatusDetailedValidator(sd usagebased.Status) error { + switch sd { + case "created", "active", "active.realization.started", "active.realization.waiting_for_collection", "active.realization.processing", "active.realization.issuing", "active.realization.completed", "active.awaiting_payment_settlement", "final", "deleted": + return nil + default: + return fmt.Errorf("chargeusagebased: invalid enum value for status_detailed field: %q", sd) + } +} + +// 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() +} + +// ByCustomerID orders the results by the customer_id field. +func ByCustomerID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCustomerID, 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() +} + +// ByBillingPeriodFrom orders the results by the billing_period_from field. +func ByBillingPeriodFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBillingPeriodFrom, opts...).ToFunc() +} + +// ByBillingPeriodTo orders the results by the billing_period_to field. +func ByBillingPeriodTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBillingPeriodTo, opts...).ToFunc() +} + +// ByFullServicePeriodFrom orders the results by the full_service_period_from field. +func ByFullServicePeriodFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFullServicePeriodFrom, opts...).ToFunc() +} + +// ByFullServicePeriodTo orders the results by the full_service_period_to field. +func ByFullServicePeriodTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFullServicePeriodTo, opts...).ToFunc() +} + +// ByStatus orders the results by the status field. +func ByStatus(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStatus, opts...).ToFunc() +} + +// ByUniqueReferenceID orders the results by the unique_reference_id field. +func ByUniqueReferenceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUniqueReferenceID, opts...).ToFunc() +} + +// ByCurrency orders the results by the currency field. +func ByCurrency(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCurrency, opts...).ToFunc() +} + +// ByManagedBy orders the results by the managed_by field. +func ByManagedBy(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldManagedBy, opts...).ToFunc() +} + +// BySubscriptionID orders the results by the subscription_id field. +func BySubscriptionID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSubscriptionID, opts...).ToFunc() +} + +// BySubscriptionPhaseID orders the results by the subscription_phase_id field. +func BySubscriptionPhaseID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSubscriptionPhaseID, opts...).ToFunc() +} + +// BySubscriptionItemID orders the results by the subscription_item_id field. +func BySubscriptionItemID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSubscriptionItemID, opts...).ToFunc() +} + +// ByAdvanceAfter orders the results by the advance_after field. +func ByAdvanceAfter(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAdvanceAfter, opts...).ToFunc() +} + +// ByTaxCodeID orders the results by the tax_code_id field. +func ByTaxCodeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxCodeID, opts...).ToFunc() +} + +// ByTaxBehavior orders the results by the tax_behavior field. +func ByTaxBehavior(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxBehavior, 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() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, 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() +} + +// ByIntentDeletedAt orders the results by the intent_deleted_at field. +func ByIntentDeletedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIntentDeletedAt, 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() +} + +// ByFeatureID orders the results by the feature_id field. +func ByFeatureID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFeatureID, opts...).ToFunc() +} + +// ByRatingEngine orders the results by the rating_engine field. +func ByRatingEngine(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRatingEngine, opts...).ToFunc() +} + +// ByPrice orders the results by the price field. +func ByPrice(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPrice, opts...).ToFunc() +} + +// ByUnitConfig orders the results by the unit_config field. +func ByUnitConfig(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUnitConfig, opts...).ToFunc() +} + +// ByCurrentRealizationRunID orders the results by the current_realization_run_id field. +func ByCurrentRealizationRunID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCurrentRealizationRunID, opts...).ToFunc() +} + +// ByStatusDetailed orders the results by the status_detailed field. +func ByStatusDetailed(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStatusDetailed, opts...).ToFunc() +} + +// 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...)...) + } +} + +// ByDetailedLinesCount orders the results by detailed_lines count. +func ByDetailedLinesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newDetailedLinesStep(), opts...) + } +} + +// ByDetailedLines orders the results by detailed_lines terms. +func ByDetailedLines(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newDetailedLinesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByCurrentRunField orders the results by current_run field. +func ByCurrentRunField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCurrentRunStep(), sql.OrderByField(field, opts...)) + } +} + +// 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...)) + } +} + +// ByIntentOverrideField orders the results by intent_override field. +func ByIntentOverrideField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newIntentOverrideStep(), sql.OrderByField(field, opts...)) + } +} + +// BySubscriptionField orders the results by subscription field. +func BySubscriptionField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubscriptionStep(), sql.OrderByField(field, opts...)) + } +} + +// BySubscriptionPhaseField orders the results by subscription_phase field. +func BySubscriptionPhaseField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubscriptionPhaseStep(), sql.OrderByField(field, opts...)) + } +} + +// BySubscriptionItemField orders the results by subscription_item field. +func BySubscriptionItemField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubscriptionItemStep(), sql.OrderByField(field, opts...)) + } +} + +// ByCustomerField orders the results by customer field. +func ByCustomerField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCustomerStep(), sql.OrderByField(field, opts...)) + } +} + +// ByFeatureField orders the results by feature field. +func ByFeatureField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newFeatureStep(), sql.OrderByField(field, opts...)) + } +} + +// ByTaxCodeField orders the results by tax_code field. +func ByTaxCodeField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTaxCodeStep(), sql.OrderByField(field, opts...)) + } +} +func newRunsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RunsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, RunsTable, RunsColumn), + ) +} +func newDetailedLinesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(DetailedLinesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, DetailedLinesTable, DetailedLinesColumn), + ) +} +func newCurrentRunStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CurrentRunInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, CurrentRunTable, CurrentRunColumn), + ) +} +func newChargeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ChargeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, ChargeTable, ChargeColumn), + ) +} +func newIntentOverrideStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(IntentOverrideInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, IntentOverrideTable, IntentOverrideColumn), + ) +} +func newSubscriptionStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SubscriptionInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionTable, SubscriptionColumn), + ) +} +func newSubscriptionPhaseStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SubscriptionPhaseInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionPhaseTable, SubscriptionPhaseColumn), + ) +} +func newSubscriptionItemStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SubscriptionItemInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionItemTable, SubscriptionItemColumn), + ) +} +func newCustomerStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CustomerInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, CustomerTable, CustomerColumn), + ) +} +func newFeatureStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(FeatureInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, FeatureTable, FeatureColumn), + ) +} +func newTaxCodeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TaxCodeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, TaxCodeTable, TaxCodeColumn), + ) +} diff --git a/ent/db/chargeusagebased/where.go b/ent/db/chargeusagebased/where.go new file mode 100644 index 0000000000000000000000000000000000000000..906c6ff475467d8742069d88f298729d5784c206 --- /dev/null +++ b/ent/db/chargeusagebased/where.go @@ -0,0 +1,2129 @@ +// 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/billing" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" +) + +// 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)) +} + +// CustomerID applies equality check predicate on the "customer_id" field. It's identical to CustomerIDEQ. +func CustomerID(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldCustomerID, v)) +} + +// ServicePeriodFrom applies equality check predicate on the "service_period_from" field. It's identical to ServicePeriodFromEQ. +func ServicePeriodFrom(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(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.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// BillingPeriodFrom applies equality check predicate on the "billing_period_from" field. It's identical to BillingPeriodFromEQ. +func BillingPeriodFrom(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodTo applies equality check predicate on the "billing_period_to" field. It's identical to BillingPeriodToEQ. +func BillingPeriodTo(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldBillingPeriodTo, v)) +} + +// FullServicePeriodFrom applies equality check predicate on the "full_service_period_from" field. It's identical to FullServicePeriodFromEQ. +func FullServicePeriodFrom(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodTo applies equality check predicate on the "full_service_period_to" field. It's identical to FullServicePeriodToEQ. +func FullServicePeriodTo(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldFullServicePeriodTo, v)) +} + +// UniqueReferenceID applies equality check predicate on the "unique_reference_id" field. It's identical to UniqueReferenceIDEQ. +func UniqueReferenceID(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldUniqueReferenceID, v)) +} + +// Currency applies equality check predicate on the "currency" field. It's identical to CurrencyEQ. +func Currency(v currencyx.Code) predicate.ChargeUsageBased { + vc := string(v) + return predicate.ChargeUsageBased(sql.FieldEQ(FieldCurrency, vc)) +} + +// SubscriptionID applies equality check predicate on the "subscription_id" field. It's identical to SubscriptionIDEQ. +func SubscriptionID(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldSubscriptionID, v)) +} + +// SubscriptionPhaseID applies equality check predicate on the "subscription_phase_id" field. It's identical to SubscriptionPhaseIDEQ. +func SubscriptionPhaseID(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionItemID applies equality check predicate on the "subscription_item_id" field. It's identical to SubscriptionItemIDEQ. +func SubscriptionItemID(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldSubscriptionItemID, v)) +} + +// AdvanceAfter applies equality check predicate on the "advance_after" field. It's identical to AdvanceAfterEQ. +func AdvanceAfter(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldAdvanceAfter, v)) +} + +// TaxCodeID applies equality check predicate on the "tax_code_id" field. It's identical to TaxCodeIDEQ. +func TaxCodeID(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldTaxCodeID, v)) +} + +// 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)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(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.ChargeUsageBased { + return predicate.ChargeUsageBased(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.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldName, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldDescription, 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)) +} + +// IntentDeletedAt applies equality check predicate on the "intent_deleted_at" field. It's identical to IntentDeletedAtEQ. +func IntentDeletedAt(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldIntentDeletedAt, 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)) +} + +// FeatureID applies equality check predicate on the "feature_id" field. It's identical to FeatureIDEQ. +func FeatureID(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldFeatureID, v)) +} + +// CurrentRealizationRunID applies equality check predicate on the "current_realization_run_id" field. It's identical to CurrentRealizationRunIDEQ. +func CurrentRealizationRunID(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldCurrentRealizationRunID, v)) +} + +// CustomerIDEQ applies the EQ predicate on the "customer_id" field. +func CustomerIDEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldCustomerID, v)) +} + +// CustomerIDNEQ applies the NEQ predicate on the "customer_id" field. +func CustomerIDNEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldCustomerID, v)) +} + +// CustomerIDIn applies the In predicate on the "customer_id" field. +func CustomerIDIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldCustomerID, vs...)) +} + +// CustomerIDNotIn applies the NotIn predicate on the "customer_id" field. +func CustomerIDNotIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldCustomerID, vs...)) +} + +// CustomerIDGT applies the GT predicate on the "customer_id" field. +func CustomerIDGT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldCustomerID, v)) +} + +// CustomerIDGTE applies the GTE predicate on the "customer_id" field. +func CustomerIDGTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldCustomerID, v)) +} + +// CustomerIDLT applies the LT predicate on the "customer_id" field. +func CustomerIDLT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldCustomerID, v)) +} + +// CustomerIDLTE applies the LTE predicate on the "customer_id" field. +func CustomerIDLTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldCustomerID, v)) +} + +// CustomerIDContains applies the Contains predicate on the "customer_id" field. +func CustomerIDContains(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContains(FieldCustomerID, v)) +} + +// CustomerIDHasPrefix applies the HasPrefix predicate on the "customer_id" field. +func CustomerIDHasPrefix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasPrefix(FieldCustomerID, v)) +} + +// CustomerIDHasSuffix applies the HasSuffix predicate on the "customer_id" field. +func CustomerIDHasSuffix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasSuffix(FieldCustomerID, v)) +} + +// CustomerIDEqualFold applies the EqualFold predicate on the "customer_id" field. +func CustomerIDEqualFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEqualFold(FieldCustomerID, v)) +} + +// CustomerIDContainsFold applies the ContainsFold predicate on the "customer_id" field. +func CustomerIDContainsFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContainsFold(FieldCustomerID, v)) +} + +// ServicePeriodFromEQ applies the EQ predicate on the "service_period_from" field. +func ServicePeriodFromEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromNEQ applies the NEQ predicate on the "service_period_from" field. +func ServicePeriodFromNEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromIn applies the In predicate on the "service_period_from" field. +func ServicePeriodFromIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromNotIn applies the NotIn predicate on the "service_period_from" field. +func ServicePeriodFromNotIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromGT applies the GT predicate on the "service_period_from" field. +func ServicePeriodFromGT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromGTE applies the GTE predicate on the "service_period_from" field. +func ServicePeriodFromGTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLT applies the LT predicate on the "service_period_from" field. +func ServicePeriodFromLT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLTE applies the LTE predicate on the "service_period_from" field. +func ServicePeriodFromLTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodToEQ applies the EQ predicate on the "service_period_to" field. +func ServicePeriodToEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToNEQ applies the NEQ predicate on the "service_period_to" field. +func ServicePeriodToNEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToIn applies the In predicate on the "service_period_to" field. +func ServicePeriodToIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToNotIn applies the NotIn predicate on the "service_period_to" field. +func ServicePeriodToNotIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToGT applies the GT predicate on the "service_period_to" field. +func ServicePeriodToGT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToGTE applies the GTE predicate on the "service_period_to" field. +func ServicePeriodToGTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLT applies the LT predicate on the "service_period_to" field. +func ServicePeriodToLT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLTE applies the LTE predicate on the "service_period_to" field. +func ServicePeriodToLTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldServicePeriodTo, v)) +} + +// BillingPeriodFromEQ applies the EQ predicate on the "billing_period_from" field. +func BillingPeriodFromEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromNEQ applies the NEQ predicate on the "billing_period_from" field. +func BillingPeriodFromNEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromIn applies the In predicate on the "billing_period_from" field. +func BillingPeriodFromIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldBillingPeriodFrom, vs...)) +} + +// BillingPeriodFromNotIn applies the NotIn predicate on the "billing_period_from" field. +func BillingPeriodFromNotIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldBillingPeriodFrom, vs...)) +} + +// BillingPeriodFromGT applies the GT predicate on the "billing_period_from" field. +func BillingPeriodFromGT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromGTE applies the GTE predicate on the "billing_period_from" field. +func BillingPeriodFromGTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromLT applies the LT predicate on the "billing_period_from" field. +func BillingPeriodFromLT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromLTE applies the LTE predicate on the "billing_period_from" field. +func BillingPeriodFromLTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodToEQ applies the EQ predicate on the "billing_period_to" field. +func BillingPeriodToEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToNEQ applies the NEQ predicate on the "billing_period_to" field. +func BillingPeriodToNEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToIn applies the In predicate on the "billing_period_to" field. +func BillingPeriodToIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldBillingPeriodTo, vs...)) +} + +// BillingPeriodToNotIn applies the NotIn predicate on the "billing_period_to" field. +func BillingPeriodToNotIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldBillingPeriodTo, vs...)) +} + +// BillingPeriodToGT applies the GT predicate on the "billing_period_to" field. +func BillingPeriodToGT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToGTE applies the GTE predicate on the "billing_period_to" field. +func BillingPeriodToGTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToLT applies the LT predicate on the "billing_period_to" field. +func BillingPeriodToLT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToLTE applies the LTE predicate on the "billing_period_to" field. +func BillingPeriodToLTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldBillingPeriodTo, v)) +} + +// FullServicePeriodFromEQ applies the EQ predicate on the "full_service_period_from" field. +func FullServicePeriodFromEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromNEQ applies the NEQ predicate on the "full_service_period_from" field. +func FullServicePeriodFromNEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromIn applies the In predicate on the "full_service_period_from" field. +func FullServicePeriodFromIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldFullServicePeriodFrom, vs...)) +} + +// FullServicePeriodFromNotIn applies the NotIn predicate on the "full_service_period_from" field. +func FullServicePeriodFromNotIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldFullServicePeriodFrom, vs...)) +} + +// FullServicePeriodFromGT applies the GT predicate on the "full_service_period_from" field. +func FullServicePeriodFromGT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromGTE applies the GTE predicate on the "full_service_period_from" field. +func FullServicePeriodFromGTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromLT applies the LT predicate on the "full_service_period_from" field. +func FullServicePeriodFromLT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromLTE applies the LTE predicate on the "full_service_period_from" field. +func FullServicePeriodFromLTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodToEQ applies the EQ predicate on the "full_service_period_to" field. +func FullServicePeriodToEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToNEQ applies the NEQ predicate on the "full_service_period_to" field. +func FullServicePeriodToNEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToIn applies the In predicate on the "full_service_period_to" field. +func FullServicePeriodToIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldFullServicePeriodTo, vs...)) +} + +// FullServicePeriodToNotIn applies the NotIn predicate on the "full_service_period_to" field. +func FullServicePeriodToNotIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldFullServicePeriodTo, vs...)) +} + +// FullServicePeriodToGT applies the GT predicate on the "full_service_period_to" field. +func FullServicePeriodToGT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToGTE applies the GTE predicate on the "full_service_period_to" field. +func FullServicePeriodToGTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToLT applies the LT predicate on the "full_service_period_to" field. +func FullServicePeriodToLT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToLTE applies the LTE predicate on the "full_service_period_to" field. +func FullServicePeriodToLTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldFullServicePeriodTo, v)) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v meta.ChargeStatus) predicate.ChargeUsageBased { + vc := v + return predicate.ChargeUsageBased(sql.FieldEQ(FieldStatus, vc)) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v meta.ChargeStatus) predicate.ChargeUsageBased { + vc := v + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldStatus, vc)) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...meta.ChargeStatus) predicate.ChargeUsageBased { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBased(sql.FieldIn(FieldStatus, v...)) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...meta.ChargeStatus) predicate.ChargeUsageBased { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldStatus, v...)) +} + +// UniqueReferenceIDEQ applies the EQ predicate on the "unique_reference_id" field. +func UniqueReferenceIDEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDNEQ applies the NEQ predicate on the "unique_reference_id" field. +func UniqueReferenceIDNEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDIn applies the In predicate on the "unique_reference_id" field. +func UniqueReferenceIDIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldUniqueReferenceID, vs...)) +} + +// UniqueReferenceIDNotIn applies the NotIn predicate on the "unique_reference_id" field. +func UniqueReferenceIDNotIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldUniqueReferenceID, vs...)) +} + +// UniqueReferenceIDGT applies the GT predicate on the "unique_reference_id" field. +func UniqueReferenceIDGT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDGTE applies the GTE predicate on the "unique_reference_id" field. +func UniqueReferenceIDGTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDLT applies the LT predicate on the "unique_reference_id" field. +func UniqueReferenceIDLT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDLTE applies the LTE predicate on the "unique_reference_id" field. +func UniqueReferenceIDLTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDContains applies the Contains predicate on the "unique_reference_id" field. +func UniqueReferenceIDContains(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContains(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDHasPrefix applies the HasPrefix predicate on the "unique_reference_id" field. +func UniqueReferenceIDHasPrefix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasPrefix(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDHasSuffix applies the HasSuffix predicate on the "unique_reference_id" field. +func UniqueReferenceIDHasSuffix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasSuffix(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDIsNil applies the IsNil predicate on the "unique_reference_id" field. +func UniqueReferenceIDIsNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIsNull(FieldUniqueReferenceID)) +} + +// UniqueReferenceIDNotNil applies the NotNil predicate on the "unique_reference_id" field. +func UniqueReferenceIDNotNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotNull(FieldUniqueReferenceID)) +} + +// UniqueReferenceIDEqualFold applies the EqualFold predicate on the "unique_reference_id" field. +func UniqueReferenceIDEqualFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEqualFold(FieldUniqueReferenceID, v)) +} + +// UniqueReferenceIDContainsFold applies the ContainsFold predicate on the "unique_reference_id" field. +func UniqueReferenceIDContainsFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContainsFold(FieldUniqueReferenceID, v)) +} + +// CurrencyEQ applies the EQ predicate on the "currency" field. +func CurrencyEQ(v currencyx.Code) predicate.ChargeUsageBased { + vc := string(v) + return predicate.ChargeUsageBased(sql.FieldEQ(FieldCurrency, vc)) +} + +// CurrencyNEQ applies the NEQ predicate on the "currency" field. +func CurrencyNEQ(v currencyx.Code) predicate.ChargeUsageBased { + vc := string(v) + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldCurrency, vc)) +} + +// CurrencyIn applies the In predicate on the "currency" field. +func CurrencyIn(vs ...currencyx.Code) predicate.ChargeUsageBased { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargeUsageBased(sql.FieldIn(FieldCurrency, v...)) +} + +// CurrencyNotIn applies the NotIn predicate on the "currency" field. +func CurrencyNotIn(vs ...currencyx.Code) predicate.ChargeUsageBased { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldCurrency, v...)) +} + +// CurrencyGT applies the GT predicate on the "currency" field. +func CurrencyGT(v currencyx.Code) predicate.ChargeUsageBased { + vc := string(v) + return predicate.ChargeUsageBased(sql.FieldGT(FieldCurrency, vc)) +} + +// CurrencyGTE applies the GTE predicate on the "currency" field. +func CurrencyGTE(v currencyx.Code) predicate.ChargeUsageBased { + vc := string(v) + return predicate.ChargeUsageBased(sql.FieldGTE(FieldCurrency, vc)) +} + +// CurrencyLT applies the LT predicate on the "currency" field. +func CurrencyLT(v currencyx.Code) predicate.ChargeUsageBased { + vc := string(v) + return predicate.ChargeUsageBased(sql.FieldLT(FieldCurrency, vc)) +} + +// CurrencyLTE applies the LTE predicate on the "currency" field. +func CurrencyLTE(v currencyx.Code) predicate.ChargeUsageBased { + vc := string(v) + return predicate.ChargeUsageBased(sql.FieldLTE(FieldCurrency, vc)) +} + +// CurrencyContains applies the Contains predicate on the "currency" field. +func CurrencyContains(v currencyx.Code) predicate.ChargeUsageBased { + vc := string(v) + return predicate.ChargeUsageBased(sql.FieldContains(FieldCurrency, vc)) +} + +// CurrencyHasPrefix applies the HasPrefix predicate on the "currency" field. +func CurrencyHasPrefix(v currencyx.Code) predicate.ChargeUsageBased { + vc := string(v) + return predicate.ChargeUsageBased(sql.FieldHasPrefix(FieldCurrency, vc)) +} + +// CurrencyHasSuffix applies the HasSuffix predicate on the "currency" field. +func CurrencyHasSuffix(v currencyx.Code) predicate.ChargeUsageBased { + vc := string(v) + return predicate.ChargeUsageBased(sql.FieldHasSuffix(FieldCurrency, vc)) +} + +// CurrencyEqualFold applies the EqualFold predicate on the "currency" field. +func CurrencyEqualFold(v currencyx.Code) predicate.ChargeUsageBased { + vc := string(v) + return predicate.ChargeUsageBased(sql.FieldEqualFold(FieldCurrency, vc)) +} + +// CurrencyContainsFold applies the ContainsFold predicate on the "currency" field. +func CurrencyContainsFold(v currencyx.Code) predicate.ChargeUsageBased { + vc := string(v) + return predicate.ChargeUsageBased(sql.FieldContainsFold(FieldCurrency, vc)) +} + +// ManagedByEQ applies the EQ predicate on the "managed_by" field. +func ManagedByEQ(v billing.InvoiceLineManagedBy) predicate.ChargeUsageBased { + vc := v + return predicate.ChargeUsageBased(sql.FieldEQ(FieldManagedBy, vc)) +} + +// ManagedByNEQ applies the NEQ predicate on the "managed_by" field. +func ManagedByNEQ(v billing.InvoiceLineManagedBy) predicate.ChargeUsageBased { + vc := v + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldManagedBy, vc)) +} + +// ManagedByIn applies the In predicate on the "managed_by" field. +func ManagedByIn(vs ...billing.InvoiceLineManagedBy) predicate.ChargeUsageBased { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBased(sql.FieldIn(FieldManagedBy, v...)) +} + +// ManagedByNotIn applies the NotIn predicate on the "managed_by" field. +func ManagedByNotIn(vs ...billing.InvoiceLineManagedBy) predicate.ChargeUsageBased { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldManagedBy, v...)) +} + +// SubscriptionIDEQ applies the EQ predicate on the "subscription_id" field. +func SubscriptionIDEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldSubscriptionID, v)) +} + +// SubscriptionIDNEQ applies the NEQ predicate on the "subscription_id" field. +func SubscriptionIDNEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldSubscriptionID, v)) +} + +// SubscriptionIDIn applies the In predicate on the "subscription_id" field. +func SubscriptionIDIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldSubscriptionID, vs...)) +} + +// SubscriptionIDNotIn applies the NotIn predicate on the "subscription_id" field. +func SubscriptionIDNotIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldSubscriptionID, vs...)) +} + +// SubscriptionIDGT applies the GT predicate on the "subscription_id" field. +func SubscriptionIDGT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldSubscriptionID, v)) +} + +// SubscriptionIDGTE applies the GTE predicate on the "subscription_id" field. +func SubscriptionIDGTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldSubscriptionID, v)) +} + +// SubscriptionIDLT applies the LT predicate on the "subscription_id" field. +func SubscriptionIDLT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldSubscriptionID, v)) +} + +// SubscriptionIDLTE applies the LTE predicate on the "subscription_id" field. +func SubscriptionIDLTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldSubscriptionID, v)) +} + +// SubscriptionIDContains applies the Contains predicate on the "subscription_id" field. +func SubscriptionIDContains(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContains(FieldSubscriptionID, v)) +} + +// SubscriptionIDHasPrefix applies the HasPrefix predicate on the "subscription_id" field. +func SubscriptionIDHasPrefix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasPrefix(FieldSubscriptionID, v)) +} + +// SubscriptionIDHasSuffix applies the HasSuffix predicate on the "subscription_id" field. +func SubscriptionIDHasSuffix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasSuffix(FieldSubscriptionID, v)) +} + +// SubscriptionIDIsNil applies the IsNil predicate on the "subscription_id" field. +func SubscriptionIDIsNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIsNull(FieldSubscriptionID)) +} + +// SubscriptionIDNotNil applies the NotNil predicate on the "subscription_id" field. +func SubscriptionIDNotNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotNull(FieldSubscriptionID)) +} + +// SubscriptionIDEqualFold applies the EqualFold predicate on the "subscription_id" field. +func SubscriptionIDEqualFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEqualFold(FieldSubscriptionID, v)) +} + +// SubscriptionIDContainsFold applies the ContainsFold predicate on the "subscription_id" field. +func SubscriptionIDContainsFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContainsFold(FieldSubscriptionID, v)) +} + +// SubscriptionPhaseIDEQ applies the EQ predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDNEQ applies the NEQ predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDNEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDIn applies the In predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldSubscriptionPhaseID, vs...)) +} + +// SubscriptionPhaseIDNotIn applies the NotIn predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDNotIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldSubscriptionPhaseID, vs...)) +} + +// SubscriptionPhaseIDGT applies the GT predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDGT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDGTE applies the GTE predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDGTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDLT applies the LT predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDLT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDLTE applies the LTE predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDLTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDContains applies the Contains predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDContains(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContains(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDHasPrefix applies the HasPrefix predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDHasPrefix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasPrefix(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDHasSuffix applies the HasSuffix predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDHasSuffix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasSuffix(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDIsNil applies the IsNil predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDIsNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIsNull(FieldSubscriptionPhaseID)) +} + +// SubscriptionPhaseIDNotNil applies the NotNil predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDNotNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotNull(FieldSubscriptionPhaseID)) +} + +// SubscriptionPhaseIDEqualFold applies the EqualFold predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDEqualFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEqualFold(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionPhaseIDContainsFold applies the ContainsFold predicate on the "subscription_phase_id" field. +func SubscriptionPhaseIDContainsFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContainsFold(FieldSubscriptionPhaseID, v)) +} + +// SubscriptionItemIDEQ applies the EQ predicate on the "subscription_item_id" field. +func SubscriptionItemIDEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDNEQ applies the NEQ predicate on the "subscription_item_id" field. +func SubscriptionItemIDNEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDIn applies the In predicate on the "subscription_item_id" field. +func SubscriptionItemIDIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldSubscriptionItemID, vs...)) +} + +// SubscriptionItemIDNotIn applies the NotIn predicate on the "subscription_item_id" field. +func SubscriptionItemIDNotIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldSubscriptionItemID, vs...)) +} + +// SubscriptionItemIDGT applies the GT predicate on the "subscription_item_id" field. +func SubscriptionItemIDGT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDGTE applies the GTE predicate on the "subscription_item_id" field. +func SubscriptionItemIDGTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDLT applies the LT predicate on the "subscription_item_id" field. +func SubscriptionItemIDLT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDLTE applies the LTE predicate on the "subscription_item_id" field. +func SubscriptionItemIDLTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDContains applies the Contains predicate on the "subscription_item_id" field. +func SubscriptionItemIDContains(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContains(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDHasPrefix applies the HasPrefix predicate on the "subscription_item_id" field. +func SubscriptionItemIDHasPrefix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasPrefix(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDHasSuffix applies the HasSuffix predicate on the "subscription_item_id" field. +func SubscriptionItemIDHasSuffix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasSuffix(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDIsNil applies the IsNil predicate on the "subscription_item_id" field. +func SubscriptionItemIDIsNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIsNull(FieldSubscriptionItemID)) +} + +// SubscriptionItemIDNotNil applies the NotNil predicate on the "subscription_item_id" field. +func SubscriptionItemIDNotNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotNull(FieldSubscriptionItemID)) +} + +// SubscriptionItemIDEqualFold applies the EqualFold predicate on the "subscription_item_id" field. +func SubscriptionItemIDEqualFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEqualFold(FieldSubscriptionItemID, v)) +} + +// SubscriptionItemIDContainsFold applies the ContainsFold predicate on the "subscription_item_id" field. +func SubscriptionItemIDContainsFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContainsFold(FieldSubscriptionItemID, v)) +} + +// AdvanceAfterEQ applies the EQ predicate on the "advance_after" field. +func AdvanceAfterEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldAdvanceAfter, v)) +} + +// AdvanceAfterNEQ applies the NEQ predicate on the "advance_after" field. +func AdvanceAfterNEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldAdvanceAfter, v)) +} + +// AdvanceAfterIn applies the In predicate on the "advance_after" field. +func AdvanceAfterIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldAdvanceAfter, vs...)) +} + +// AdvanceAfterNotIn applies the NotIn predicate on the "advance_after" field. +func AdvanceAfterNotIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldAdvanceAfter, vs...)) +} + +// AdvanceAfterGT applies the GT predicate on the "advance_after" field. +func AdvanceAfterGT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldAdvanceAfter, v)) +} + +// AdvanceAfterGTE applies the GTE predicate on the "advance_after" field. +func AdvanceAfterGTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldAdvanceAfter, v)) +} + +// AdvanceAfterLT applies the LT predicate on the "advance_after" field. +func AdvanceAfterLT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldAdvanceAfter, v)) +} + +// AdvanceAfterLTE applies the LTE predicate on the "advance_after" field. +func AdvanceAfterLTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldAdvanceAfter, v)) +} + +// AdvanceAfterIsNil applies the IsNil predicate on the "advance_after" field. +func AdvanceAfterIsNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIsNull(FieldAdvanceAfter)) +} + +// AdvanceAfterNotNil applies the NotNil predicate on the "advance_after" field. +func AdvanceAfterNotNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotNull(FieldAdvanceAfter)) +} + +// TaxCodeIDEQ applies the EQ predicate on the "tax_code_id" field. +func TaxCodeIDEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldTaxCodeID, v)) +} + +// TaxCodeIDNEQ applies the NEQ predicate on the "tax_code_id" field. +func TaxCodeIDNEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldTaxCodeID, v)) +} + +// TaxCodeIDIn applies the In predicate on the "tax_code_id" field. +func TaxCodeIDIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldTaxCodeID, vs...)) +} + +// TaxCodeIDNotIn applies the NotIn predicate on the "tax_code_id" field. +func TaxCodeIDNotIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldTaxCodeID, vs...)) +} + +// TaxCodeIDGT applies the GT predicate on the "tax_code_id" field. +func TaxCodeIDGT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldTaxCodeID, v)) +} + +// TaxCodeIDGTE applies the GTE predicate on the "tax_code_id" field. +func TaxCodeIDGTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldTaxCodeID, v)) +} + +// TaxCodeIDLT applies the LT predicate on the "tax_code_id" field. +func TaxCodeIDLT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldTaxCodeID, v)) +} + +// TaxCodeIDLTE applies the LTE predicate on the "tax_code_id" field. +func TaxCodeIDLTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldTaxCodeID, v)) +} + +// TaxCodeIDContains applies the Contains predicate on the "tax_code_id" field. +func TaxCodeIDContains(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContains(FieldTaxCodeID, v)) +} + +// TaxCodeIDHasPrefix applies the HasPrefix predicate on the "tax_code_id" field. +func TaxCodeIDHasPrefix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasPrefix(FieldTaxCodeID, v)) +} + +// TaxCodeIDHasSuffix applies the HasSuffix predicate on the "tax_code_id" field. +func TaxCodeIDHasSuffix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasSuffix(FieldTaxCodeID, v)) +} + +// TaxCodeIDEqualFold applies the EqualFold predicate on the "tax_code_id" field. +func TaxCodeIDEqualFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEqualFold(FieldTaxCodeID, v)) +} + +// TaxCodeIDContainsFold applies the ContainsFold predicate on the "tax_code_id" field. +func TaxCodeIDContainsFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContainsFold(FieldTaxCodeID, v)) +} + +// TaxBehaviorEQ applies the EQ predicate on the "tax_behavior" field. +func TaxBehaviorEQ(v productcatalog.TaxBehavior) predicate.ChargeUsageBased { + vc := v + return predicate.ChargeUsageBased(sql.FieldEQ(FieldTaxBehavior, vc)) +} + +// TaxBehaviorNEQ applies the NEQ predicate on the "tax_behavior" field. +func TaxBehaviorNEQ(v productcatalog.TaxBehavior) predicate.ChargeUsageBased { + vc := v + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldTaxBehavior, vc)) +} + +// TaxBehaviorIn applies the In predicate on the "tax_behavior" field. +func TaxBehaviorIn(vs ...productcatalog.TaxBehavior) predicate.ChargeUsageBased { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBased(sql.FieldIn(FieldTaxBehavior, v...)) +} + +// TaxBehaviorNotIn applies the NotIn predicate on the "tax_behavior" field. +func TaxBehaviorNotIn(vs ...productcatalog.TaxBehavior) predicate.ChargeUsageBased { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldTaxBehavior, v...)) +} + +// TaxBehaviorIsNil applies the IsNil predicate on the "tax_behavior" field. +func TaxBehaviorIsNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIsNull(FieldTaxBehavior)) +} + +// TaxBehaviorNotNil applies the NotNil predicate on the "tax_behavior" field. +func TaxBehaviorNotNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotNull(FieldTaxBehavior)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotNull(FieldAnnotations)) +} + +// 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)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotNull(FieldMetadata)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotNull(FieldDeletedAt)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContainsFold(FieldName, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContainsFold(FieldDescription, 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...)) +} + +// IntentDeletedAtEQ applies the EQ predicate on the "intent_deleted_at" field. +func IntentDeletedAtEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtNEQ applies the NEQ predicate on the "intent_deleted_at" field. +func IntentDeletedAtNEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtIn applies the In predicate on the "intent_deleted_at" field. +func IntentDeletedAtIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldIntentDeletedAt, vs...)) +} + +// IntentDeletedAtNotIn applies the NotIn predicate on the "intent_deleted_at" field. +func IntentDeletedAtNotIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldIntentDeletedAt, vs...)) +} + +// IntentDeletedAtGT applies the GT predicate on the "intent_deleted_at" field. +func IntentDeletedAtGT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtGTE applies the GTE predicate on the "intent_deleted_at" field. +func IntentDeletedAtGTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtLT applies the LT predicate on the "intent_deleted_at" field. +func IntentDeletedAtLT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtLTE applies the LTE predicate on the "intent_deleted_at" field. +func IntentDeletedAtLTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtIsNil applies the IsNil predicate on the "intent_deleted_at" field. +func IntentDeletedAtIsNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIsNull(FieldIntentDeletedAt)) +} + +// IntentDeletedAtNotNil applies the NotNil predicate on the "intent_deleted_at" field. +func IntentDeletedAtNotNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotNull(FieldIntentDeletedAt)) +} + +// 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)) +} + +// FeatureIDEQ applies the EQ predicate on the "feature_id" field. +func FeatureIDEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldFeatureID, v)) +} + +// FeatureIDNEQ applies the NEQ predicate on the "feature_id" field. +func FeatureIDNEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldFeatureID, v)) +} + +// FeatureIDIn applies the In predicate on the "feature_id" field. +func FeatureIDIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldFeatureID, vs...)) +} + +// FeatureIDNotIn applies the NotIn predicate on the "feature_id" field. +func FeatureIDNotIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldFeatureID, vs...)) +} + +// FeatureIDGT applies the GT predicate on the "feature_id" field. +func FeatureIDGT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldFeatureID, v)) +} + +// FeatureIDGTE applies the GTE predicate on the "feature_id" field. +func FeatureIDGTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldFeatureID, v)) +} + +// FeatureIDLT applies the LT predicate on the "feature_id" field. +func FeatureIDLT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldFeatureID, v)) +} + +// FeatureIDLTE applies the LTE predicate on the "feature_id" field. +func FeatureIDLTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldFeatureID, v)) +} + +// FeatureIDContains applies the Contains predicate on the "feature_id" field. +func FeatureIDContains(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContains(FieldFeatureID, v)) +} + +// FeatureIDHasPrefix applies the HasPrefix predicate on the "feature_id" field. +func FeatureIDHasPrefix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasPrefix(FieldFeatureID, v)) +} + +// FeatureIDHasSuffix applies the HasSuffix predicate on the "feature_id" field. +func FeatureIDHasSuffix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasSuffix(FieldFeatureID, v)) +} + +// FeatureIDEqualFold applies the EqualFold predicate on the "feature_id" field. +func FeatureIDEqualFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEqualFold(FieldFeatureID, v)) +} + +// FeatureIDContainsFold applies the ContainsFold predicate on the "feature_id" field. +func FeatureIDContainsFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContainsFold(FieldFeatureID, v)) +} + +// RatingEngineEQ applies the EQ predicate on the "rating_engine" field. +func RatingEngineEQ(v usagebased.RatingEngine) predicate.ChargeUsageBased { + vc := v + return predicate.ChargeUsageBased(sql.FieldEQ(FieldRatingEngine, vc)) +} + +// RatingEngineNEQ applies the NEQ predicate on the "rating_engine" field. +func RatingEngineNEQ(v usagebased.RatingEngine) predicate.ChargeUsageBased { + vc := v + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldRatingEngine, vc)) +} + +// RatingEngineIn applies the In predicate on the "rating_engine" field. +func RatingEngineIn(vs ...usagebased.RatingEngine) predicate.ChargeUsageBased { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBased(sql.FieldIn(FieldRatingEngine, v...)) +} + +// RatingEngineNotIn applies the NotIn predicate on the "rating_engine" field. +func RatingEngineNotIn(vs ...usagebased.RatingEngine) predicate.ChargeUsageBased { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldRatingEngine, v...)) +} + +// UnitConfigIsNil applies the IsNil predicate on the "unit_config" field. +func UnitConfigIsNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIsNull(FieldUnitConfig)) +} + +// UnitConfigNotNil applies the NotNil predicate on the "unit_config" field. +func UnitConfigNotNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotNull(FieldUnitConfig)) +} + +// CurrentRealizationRunIDEQ applies the EQ predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldCurrentRealizationRunID, v)) +} + +// CurrentRealizationRunIDNEQ applies the NEQ predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDNEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldCurrentRealizationRunID, v)) +} + +// CurrentRealizationRunIDIn applies the In predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldCurrentRealizationRunID, vs...)) +} + +// CurrentRealizationRunIDNotIn applies the NotIn predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDNotIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldCurrentRealizationRunID, vs...)) +} + +// CurrentRealizationRunIDGT applies the GT predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDGT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldCurrentRealizationRunID, v)) +} + +// CurrentRealizationRunIDGTE applies the GTE predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDGTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldCurrentRealizationRunID, v)) +} + +// CurrentRealizationRunIDLT applies the LT predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDLT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldCurrentRealizationRunID, v)) +} + +// CurrentRealizationRunIDLTE applies the LTE predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDLTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldCurrentRealizationRunID, v)) +} + +// CurrentRealizationRunIDContains applies the Contains predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDContains(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContains(FieldCurrentRealizationRunID, v)) +} + +// CurrentRealizationRunIDHasPrefix applies the HasPrefix predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDHasPrefix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasPrefix(FieldCurrentRealizationRunID, v)) +} + +// CurrentRealizationRunIDHasSuffix applies the HasSuffix predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDHasSuffix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasSuffix(FieldCurrentRealizationRunID, v)) +} + +// CurrentRealizationRunIDIsNil applies the IsNil predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDIsNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIsNull(FieldCurrentRealizationRunID)) +} + +// CurrentRealizationRunIDNotNil applies the NotNil predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDNotNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotNull(FieldCurrentRealizationRunID)) +} + +// CurrentRealizationRunIDEqualFold applies the EqualFold predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDEqualFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEqualFold(FieldCurrentRealizationRunID, v)) +} + +// CurrentRealizationRunIDContainsFold applies the ContainsFold predicate on the "current_realization_run_id" field. +func CurrentRealizationRunIDContainsFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContainsFold(FieldCurrentRealizationRunID, v)) +} + +// StatusDetailedEQ applies the EQ predicate on the "status_detailed" field. +func StatusDetailedEQ(v usagebased.Status) predicate.ChargeUsageBased { + vc := v + return predicate.ChargeUsageBased(sql.FieldEQ(FieldStatusDetailed, vc)) +} + +// StatusDetailedNEQ applies the NEQ predicate on the "status_detailed" field. +func StatusDetailedNEQ(v usagebased.Status) predicate.ChargeUsageBased { + vc := v + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldStatusDetailed, vc)) +} + +// StatusDetailedIn applies the In predicate on the "status_detailed" field. +func StatusDetailedIn(vs ...usagebased.Status) predicate.ChargeUsageBased { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBased(sql.FieldIn(FieldStatusDetailed, v...)) +} + +// StatusDetailedNotIn applies the NotIn predicate on the "status_detailed" field. +func StatusDetailedNotIn(vs ...usagebased.Status) predicate.ChargeUsageBased { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldStatusDetailed, v...)) +} + +// 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) + } + }) + }) +} + +// HasDetailedLines applies the HasEdge predicate on the "detailed_lines" edge. +func HasDetailedLines() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, DetailedLinesTable, DetailedLinesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasDetailedLinesWith applies the HasEdge predicate on the "detailed_lines" edge with a given conditions (other predicates). +func HasDetailedLinesWith(preds ...predicate.ChargeUsageBasedRunDetailedLine) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := newDetailedLinesStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasCurrentRun applies the HasEdge predicate on the "current_run" edge. +func HasCurrentRun() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, CurrentRunTable, CurrentRunColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCurrentRunWith applies the HasEdge predicate on the "current_run" edge with a given conditions (other predicates). +func HasCurrentRunWith(preds ...predicate.ChargeUsageBasedRuns) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := newCurrentRunStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// 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, false, 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) + } + }) + }) +} + +// HasIntentOverride applies the HasEdge predicate on the "intent_override" edge. +func HasIntentOverride() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, IntentOverrideTable, IntentOverrideColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasIntentOverrideWith applies the HasEdge predicate on the "intent_override" edge with a given conditions (other predicates). +func HasIntentOverrideWith(preds ...predicate.ChargeUsageBasedOverride) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := newIntentOverrideStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSubscription applies the HasEdge predicate on the "subscription" edge. +func HasSubscription() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionTable, SubscriptionColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubscriptionWith applies the HasEdge predicate on the "subscription" edge with a given conditions (other predicates). +func HasSubscriptionWith(preds ...predicate.Subscription) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := newSubscriptionStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSubscriptionPhase applies the HasEdge predicate on the "subscription_phase" edge. +func HasSubscriptionPhase() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionPhaseTable, SubscriptionPhaseColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubscriptionPhaseWith applies the HasEdge predicate on the "subscription_phase" edge with a given conditions (other predicates). +func HasSubscriptionPhaseWith(preds ...predicate.SubscriptionPhase) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := newSubscriptionPhaseStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSubscriptionItem applies the HasEdge predicate on the "subscription_item" edge. +func HasSubscriptionItem() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubscriptionItemTable, SubscriptionItemColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubscriptionItemWith applies the HasEdge predicate on the "subscription_item" edge with a given conditions (other predicates). +func HasSubscriptionItemWith(preds ...predicate.SubscriptionItem) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := newSubscriptionItemStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasCustomer applies the HasEdge predicate on the "customer" edge. +func HasCustomer() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, CustomerTable, CustomerColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCustomerWith applies the HasEdge predicate on the "customer" edge with a given conditions (other predicates). +func HasCustomerWith(preds ...predicate.Customer) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := newCustomerStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasFeature applies the HasEdge predicate on the "feature" edge. +func HasFeature() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, FeatureTable, FeatureColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasFeatureWith applies the HasEdge predicate on the "feature" edge with a given conditions (other predicates). +func HasFeatureWith(preds ...predicate.Feature) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := newFeatureStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasTaxCode applies the HasEdge predicate on the "tax_code" edge. +func HasTaxCode() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, TaxCodeTable, TaxCodeColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTaxCodeWith applies the HasEdge predicate on the "tax_code" edge with a given conditions (other predicates). +func HasTaxCodeWith(preds ...predicate.TaxCode) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := newTaxCodeStep() + 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/ent/db/chargeusagebased_create.go b/ent/db/chargeusagebased_create.go new file mode 100644 index 0000000000000000000000000000000000000000..55801f77974246ab12a72b446ab925a9bf3d6b47 --- /dev/null +++ b/ent/db/chargeusagebased_create.go @@ -0,0 +1,2607 @@ +// 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/billing" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedoverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrundetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/openmeter/ent/db/customer" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionphase" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeUsageBasedCreate is the builder for creating a ChargeUsageBased entity. +type ChargeUsageBasedCreate struct { + config + mutation *ChargeUsageBasedMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetCustomerID sets the "customer_id" field. +func (_c *ChargeUsageBasedCreate) SetCustomerID(v string) *ChargeUsageBasedCreate { + _c.mutation.SetCustomerID(v) + return _c +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_c *ChargeUsageBasedCreate) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedCreate { + _c.mutation.SetServicePeriodFrom(v) + return _c +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_c *ChargeUsageBasedCreate) SetServicePeriodTo(v time.Time) *ChargeUsageBasedCreate { + _c.mutation.SetServicePeriodTo(v) + return _c +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (_c *ChargeUsageBasedCreate) SetBillingPeriodFrom(v time.Time) *ChargeUsageBasedCreate { + _c.mutation.SetBillingPeriodFrom(v) + return _c +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (_c *ChargeUsageBasedCreate) SetBillingPeriodTo(v time.Time) *ChargeUsageBasedCreate { + _c.mutation.SetBillingPeriodTo(v) + return _c +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (_c *ChargeUsageBasedCreate) SetFullServicePeriodFrom(v time.Time) *ChargeUsageBasedCreate { + _c.mutation.SetFullServicePeriodFrom(v) + return _c +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (_c *ChargeUsageBasedCreate) SetFullServicePeriodTo(v time.Time) *ChargeUsageBasedCreate { + _c.mutation.SetFullServicePeriodTo(v) + return _c +} + +// SetStatus sets the "status" field. +func (_c *ChargeUsageBasedCreate) SetStatus(v meta.ChargeStatus) *ChargeUsageBasedCreate { + _c.mutation.SetStatus(v) + return _c +} + +// SetUniqueReferenceID sets the "unique_reference_id" field. +func (_c *ChargeUsageBasedCreate) SetUniqueReferenceID(v string) *ChargeUsageBasedCreate { + _c.mutation.SetUniqueReferenceID(v) + return _c +} + +// SetNillableUniqueReferenceID sets the "unique_reference_id" field if the given value is not nil. +func (_c *ChargeUsageBasedCreate) SetNillableUniqueReferenceID(v *string) *ChargeUsageBasedCreate { + if v != nil { + _c.SetUniqueReferenceID(*v) + } + return _c +} + +// SetCurrency sets the "currency" field. +func (_c *ChargeUsageBasedCreate) SetCurrency(v currencyx.Code) *ChargeUsageBasedCreate { + _c.mutation.SetCurrency(v) + return _c +} + +// SetManagedBy sets the "managed_by" field. +func (_c *ChargeUsageBasedCreate) SetManagedBy(v billing.InvoiceLineManagedBy) *ChargeUsageBasedCreate { + _c.mutation.SetManagedBy(v) + return _c +} + +// SetSubscriptionID sets the "subscription_id" field. +func (_c *ChargeUsageBasedCreate) SetSubscriptionID(v string) *ChargeUsageBasedCreate { + _c.mutation.SetSubscriptionID(v) + return _c +} + +// SetNillableSubscriptionID sets the "subscription_id" field if the given value is not nil. +func (_c *ChargeUsageBasedCreate) SetNillableSubscriptionID(v *string) *ChargeUsageBasedCreate { + if v != nil { + _c.SetSubscriptionID(*v) + } + return _c +} + +// SetSubscriptionPhaseID sets the "subscription_phase_id" field. +func (_c *ChargeUsageBasedCreate) SetSubscriptionPhaseID(v string) *ChargeUsageBasedCreate { + _c.mutation.SetSubscriptionPhaseID(v) + return _c +} + +// SetNillableSubscriptionPhaseID sets the "subscription_phase_id" field if the given value is not nil. +func (_c *ChargeUsageBasedCreate) SetNillableSubscriptionPhaseID(v *string) *ChargeUsageBasedCreate { + if v != nil { + _c.SetSubscriptionPhaseID(*v) + } + return _c +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (_c *ChargeUsageBasedCreate) SetSubscriptionItemID(v string) *ChargeUsageBasedCreate { + _c.mutation.SetSubscriptionItemID(v) + return _c +} + +// SetNillableSubscriptionItemID sets the "subscription_item_id" field if the given value is not nil. +func (_c *ChargeUsageBasedCreate) SetNillableSubscriptionItemID(v *string) *ChargeUsageBasedCreate { + if v != nil { + _c.SetSubscriptionItemID(*v) + } + return _c +} + +// SetAdvanceAfter sets the "advance_after" field. +func (_c *ChargeUsageBasedCreate) SetAdvanceAfter(v time.Time) *ChargeUsageBasedCreate { + _c.mutation.SetAdvanceAfter(v) + return _c +} + +// SetNillableAdvanceAfter sets the "advance_after" field if the given value is not nil. +func (_c *ChargeUsageBasedCreate) SetNillableAdvanceAfter(v *time.Time) *ChargeUsageBasedCreate { + if v != nil { + _c.SetAdvanceAfter(*v) + } + return _c +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (_c *ChargeUsageBasedCreate) SetTaxCodeID(v string) *ChargeUsageBasedCreate { + _c.mutation.SetTaxCodeID(v) + return _c +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (_c *ChargeUsageBasedCreate) SetTaxBehavior(v productcatalog.TaxBehavior) *ChargeUsageBasedCreate { + _c.mutation.SetTaxBehavior(v) + return _c +} + +// SetNillableTaxBehavior sets the "tax_behavior" field if the given value is not nil. +func (_c *ChargeUsageBasedCreate) SetNillableTaxBehavior(v *productcatalog.TaxBehavior) *ChargeUsageBasedCreate { + if v != nil { + _c.SetTaxBehavior(*v) + } + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *ChargeUsageBasedCreate) SetAnnotations(v models.Annotations) *ChargeUsageBasedCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetNamespace sets the "namespace" field. +func (_c *ChargeUsageBasedCreate) SetNamespace(v string) *ChargeUsageBasedCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetMetadata sets the "metadata" field. +func (_c *ChargeUsageBasedCreate) SetMetadata(v map[string]string) *ChargeUsageBasedCreate { + _c.mutation.SetMetadata(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ChargeUsageBasedCreate) SetCreatedAt(v time.Time) *ChargeUsageBasedCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *ChargeUsageBasedCreate) SetNillableCreatedAt(v *time.Time) *ChargeUsageBasedCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *ChargeUsageBasedCreate) SetUpdatedAt(v time.Time) *ChargeUsageBasedCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *ChargeUsageBasedCreate) SetNillableUpdatedAt(v *time.Time) *ChargeUsageBasedCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *ChargeUsageBasedCreate) SetDeletedAt(v time.Time) *ChargeUsageBasedCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *ChargeUsageBasedCreate) SetNillableDeletedAt(v *time.Time) *ChargeUsageBasedCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetName sets the "name" field. +func (_c *ChargeUsageBasedCreate) SetName(v string) *ChargeUsageBasedCreate { + _c.mutation.SetName(v) + return _c +} + +// SetDescription sets the "description" field. +func (_c *ChargeUsageBasedCreate) SetDescription(v string) *ChargeUsageBasedCreate { + _c.mutation.SetDescription(v) + return _c +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_c *ChargeUsageBasedCreate) SetNillableDescription(v *string) *ChargeUsageBasedCreate { + if v != nil { + _c.SetDescription(*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 +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (_c *ChargeUsageBasedCreate) SetIntentDeletedAt(v time.Time) *ChargeUsageBasedCreate { + _c.mutation.SetIntentDeletedAt(v) + return _c +} + +// SetNillableIntentDeletedAt sets the "intent_deleted_at" field if the given value is not nil. +func (_c *ChargeUsageBasedCreate) SetNillableIntentDeletedAt(v *time.Time) *ChargeUsageBasedCreate { + if v != nil { + _c.SetIntentDeletedAt(*v) + } + return _c +} + +// SetDiscounts sets the "discounts" field. +func (_c *ChargeUsageBasedCreate) SetDiscounts(v *billing.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 +} + +// SetFeatureID sets the "feature_id" field. +func (_c *ChargeUsageBasedCreate) SetFeatureID(v string) *ChargeUsageBasedCreate { + _c.mutation.SetFeatureID(v) + return _c +} + +// SetRatingEngine sets the "rating_engine" field. +func (_c *ChargeUsageBasedCreate) SetRatingEngine(v usagebased.RatingEngine) *ChargeUsageBasedCreate { + _c.mutation.SetRatingEngine(v) + return _c +} + +// SetPrice sets the "price" field. +func (_c *ChargeUsageBasedCreate) SetPrice(v *productcatalog.Price) *ChargeUsageBasedCreate { + _c.mutation.SetPrice(v) + return _c +} + +// SetUnitConfig sets the "unit_config" field. +func (_c *ChargeUsageBasedCreate) SetUnitConfig(v *productcatalog.UnitConfig) *ChargeUsageBasedCreate { + _c.mutation.SetUnitConfig(v) + return _c +} + +// SetCurrentRealizationRunID sets the "current_realization_run_id" field. +func (_c *ChargeUsageBasedCreate) SetCurrentRealizationRunID(v string) *ChargeUsageBasedCreate { + _c.mutation.SetCurrentRealizationRunID(v) + return _c +} + +// SetNillableCurrentRealizationRunID sets the "current_realization_run_id" field if the given value is not nil. +func (_c *ChargeUsageBasedCreate) SetNillableCurrentRealizationRunID(v *string) *ChargeUsageBasedCreate { + if v != nil { + _c.SetCurrentRealizationRunID(*v) + } + return _c +} + +// SetStatusDetailed sets the "status_detailed" field. +func (_c *ChargeUsageBasedCreate) SetStatusDetailed(v usagebased.Status) *ChargeUsageBasedCreate { + _c.mutation.SetStatusDetailed(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 +} + +// 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...) +} + +// AddDetailedLineIDs adds the "detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity by IDs. +func (_c *ChargeUsageBasedCreate) AddDetailedLineIDs(ids ...string) *ChargeUsageBasedCreate { + _c.mutation.AddDetailedLineIDs(ids...) + return _c +} + +// AddDetailedLines adds the "detailed_lines" edges to the ChargeUsageBasedRunDetailedLine entity. +func (_c *ChargeUsageBasedCreate) AddDetailedLines(v ...*ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddDetailedLineIDs(ids...) +} + +// SetCurrentRunID sets the "current_run" edge to the ChargeUsageBasedRuns entity by ID. +func (_c *ChargeUsageBasedCreate) SetCurrentRunID(id string) *ChargeUsageBasedCreate { + _c.mutation.SetCurrentRunID(id) + return _c +} + +// SetNillableCurrentRunID sets the "current_run" edge to the ChargeUsageBasedRuns entity by ID if the given value is not nil. +func (_c *ChargeUsageBasedCreate) SetNillableCurrentRunID(id *string) *ChargeUsageBasedCreate { + if id != nil { + _c = _c.SetCurrentRunID(*id) + } + return _c +} + +// SetCurrentRun sets the "current_run" edge to the ChargeUsageBasedRuns entity. +func (_c *ChargeUsageBasedCreate) SetCurrentRun(v *ChargeUsageBasedRuns) *ChargeUsageBasedCreate { + return _c.SetCurrentRunID(v.ID) +} + +// SetChargeID sets the "charge" edge to the Charge entity by ID. +func (_c *ChargeUsageBasedCreate) SetChargeID(id string) *ChargeUsageBasedCreate { + _c.mutation.SetChargeID(id) + return _c +} + +// SetNillableChargeID sets the "charge" edge to the Charge entity by ID if the given value is not nil. +func (_c *ChargeUsageBasedCreate) SetNillableChargeID(id *string) *ChargeUsageBasedCreate { + if id != nil { + _c = _c.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) +} + +// SetIntentOverrideID sets the "intent_override" edge to the ChargeUsageBasedOverride entity by ID. +func (_c *ChargeUsageBasedCreate) SetIntentOverrideID(id string) *ChargeUsageBasedCreate { + _c.mutation.SetIntentOverrideID(id) + return _c +} + +// SetNillableIntentOverrideID sets the "intent_override" edge to the ChargeUsageBasedOverride entity by ID if the given value is not nil. +func (_c *ChargeUsageBasedCreate) SetNillableIntentOverrideID(id *string) *ChargeUsageBasedCreate { + if id != nil { + _c = _c.SetIntentOverrideID(*id) + } + return _c +} + +// SetIntentOverride sets the "intent_override" edge to the ChargeUsageBasedOverride entity. +func (_c *ChargeUsageBasedCreate) SetIntentOverride(v *ChargeUsageBasedOverride) *ChargeUsageBasedCreate { + return _c.SetIntentOverrideID(v.ID) +} + +// SetSubscription sets the "subscription" edge to the Subscription entity. +func (_c *ChargeUsageBasedCreate) SetSubscription(v *Subscription) *ChargeUsageBasedCreate { + return _c.SetSubscriptionID(v.ID) +} + +// SetSubscriptionPhase sets the "subscription_phase" edge to the SubscriptionPhase entity. +func (_c *ChargeUsageBasedCreate) SetSubscriptionPhase(v *SubscriptionPhase) *ChargeUsageBasedCreate { + return _c.SetSubscriptionPhaseID(v.ID) +} + +// SetSubscriptionItem sets the "subscription_item" edge to the SubscriptionItem entity. +func (_c *ChargeUsageBasedCreate) SetSubscriptionItem(v *SubscriptionItem) *ChargeUsageBasedCreate { + return _c.SetSubscriptionItemID(v.ID) +} + +// SetCustomer sets the "customer" edge to the Customer entity. +func (_c *ChargeUsageBasedCreate) SetCustomer(v *Customer) *ChargeUsageBasedCreate { + return _c.SetCustomerID(v.ID) +} + +// SetFeature sets the "feature" edge to the Feature entity. +func (_c *ChargeUsageBasedCreate) SetFeature(v *Feature) *ChargeUsageBasedCreate { + return _c.SetFeatureID(v.ID) +} + +// SetTaxCode sets the "tax_code" edge to the TaxCode entity. +func (_c *ChargeUsageBasedCreate) SetTaxCode(v *TaxCode) *ChargeUsageBasedCreate { + return _c.SetTaxCodeID(v.ID) +} + +// 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.CreatedAt(); !ok { + v := chargeusagebased.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := chargeusagebased.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + 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.CustomerID(); !ok { + return &ValidationError{Name: "customer_id", err: errors.New(`db: missing required field "ChargeUsageBased.customer_id"`)} + } + if v, ok := _c.mutation.CustomerID(); ok { + if err := chargeusagebased.CustomerIDValidator(v); err != nil { + return &ValidationError{Name: "customer_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.customer_id": %w`, err)} + } + } + if _, ok := _c.mutation.ServicePeriodFrom(); !ok { + return &ValidationError{Name: "service_period_from", err: errors.New(`db: missing required field "ChargeUsageBased.service_period_from"`)} + } + if _, ok := _c.mutation.ServicePeriodTo(); !ok { + return &ValidationError{Name: "service_period_to", err: errors.New(`db: missing required field "ChargeUsageBased.service_period_to"`)} + } + if _, ok := _c.mutation.BillingPeriodFrom(); !ok { + return &ValidationError{Name: "billing_period_from", err: errors.New(`db: missing required field "ChargeUsageBased.billing_period_from"`)} + } + if _, ok := _c.mutation.BillingPeriodTo(); !ok { + return &ValidationError{Name: "billing_period_to", err: errors.New(`db: missing required field "ChargeUsageBased.billing_period_to"`)} + } + if _, ok := _c.mutation.FullServicePeriodFrom(); !ok { + return &ValidationError{Name: "full_service_period_from", err: errors.New(`db: missing required field "ChargeUsageBased.full_service_period_from"`)} + } + if _, ok := _c.mutation.FullServicePeriodTo(); !ok { + return &ValidationError{Name: "full_service_period_to", err: errors.New(`db: missing required field "ChargeUsageBased.full_service_period_to"`)} + } + if _, ok := _c.mutation.Status(); !ok { + return &ValidationError{Name: "status", err: errors.New(`db: missing required field "ChargeUsageBased.status"`)} + } + if v, ok := _c.mutation.Status(); ok { + if err := chargeusagebased.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.status": %w`, err)} + } + } + if _, ok := _c.mutation.Currency(); !ok { + return &ValidationError{Name: "currency", err: errors.New(`db: missing required field "ChargeUsageBased.currency"`)} + } + if v, ok := _c.mutation.Currency(); ok { + if err := chargeusagebased.CurrencyValidator(string(v)); err != nil { + return &ValidationError{Name: "currency", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.currency": %w`, err)} + } + } + if _, ok := _c.mutation.ManagedBy(); !ok { + return &ValidationError{Name: "managed_by", err: errors.New(`db: missing required field "ChargeUsageBased.managed_by"`)} + } + if v, ok := _c.mutation.ManagedBy(); ok { + if err := chargeusagebased.ManagedByValidator(v); err != nil { + return &ValidationError{Name: "managed_by", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.managed_by": %w`, err)} + } + } + if _, ok := _c.mutation.TaxCodeID(); !ok { + return &ValidationError{Name: "tax_code_id", err: errors.New(`db: missing required field "ChargeUsageBased.tax_code_id"`)} + } + if v, ok := _c.mutation.TaxCodeID(); ok { + if err := chargeusagebased.TaxCodeIDValidator(v); err != nil { + return &ValidationError{Name: "tax_code_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.tax_code_id": %w`, err)} + } + } + if v, ok := _c.mutation.TaxBehavior(); ok { + if err := chargeusagebased.TaxBehaviorValidator(v); err != nil { + return &ValidationError{Name: "tax_behavior", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.tax_behavior": %w`, err)} + } + } + 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.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "ChargeUsageBased.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "ChargeUsageBased.updated_at"`)} + } + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "ChargeUsageBased.name"`)} + } + 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.FeatureID(); !ok { + return &ValidationError{Name: "feature_id", err: errors.New(`db: missing required field "ChargeUsageBased.feature_id"`)} + } + if v, ok := _c.mutation.FeatureID(); ok { + if err := chargeusagebased.FeatureIDValidator(v); err != nil { + return &ValidationError{Name: "feature_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.feature_id": %w`, err)} + } + } + if _, ok := _c.mutation.RatingEngine(); !ok { + return &ValidationError{Name: "rating_engine", err: errors.New(`db: missing required field "ChargeUsageBased.rating_engine"`)} + } + if v, ok := _c.mutation.RatingEngine(); ok { + if err := chargeusagebased.RatingEngineValidator(v); err != nil { + return &ValidationError{Name: "rating_engine", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.rating_engine": %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 v, ok := _c.mutation.UnitConfig(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "unit_config", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.unit_config": %w`, err)} + } + } + if _, ok := _c.mutation.StatusDetailed(); !ok { + return &ValidationError{Name: "status_detailed", err: errors.New(`db: missing required field "ChargeUsageBased.status_detailed"`)} + } + if v, ok := _c.mutation.StatusDetailed(); ok { + if err := chargeusagebased.StatusDetailedValidator(v); err != nil { + return &ValidationError{Name: "status_detailed", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.status_detailed": %w`, err)} + } + } + if len(_c.mutation.CustomerIDs()) == 0 { + return &ValidationError{Name: "customer", err: errors.New(`db: missing required edge "ChargeUsageBased.customer"`)} + } + if len(_c.mutation.FeatureIDs()) == 0 { + return &ValidationError{Name: "feature", err: errors.New(`db: missing required edge "ChargeUsageBased.feature"`)} + } + if len(_c.mutation.TaxCodeIDs()) == 0 { + return &ValidationError{Name: "tax_code", err: errors.New(`db: missing required edge "ChargeUsageBased.tax_code"`)} + } + 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.ServicePeriodFrom(); ok { + _spec.SetField(chargeusagebased.FieldServicePeriodFrom, field.TypeTime, value) + _node.ServicePeriodFrom = value + } + if value, ok := _c.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeusagebased.FieldServicePeriodTo, field.TypeTime, value) + _node.ServicePeriodTo = value + } + if value, ok := _c.mutation.BillingPeriodFrom(); ok { + _spec.SetField(chargeusagebased.FieldBillingPeriodFrom, field.TypeTime, value) + _node.BillingPeriodFrom = value + } + if value, ok := _c.mutation.BillingPeriodTo(); ok { + _spec.SetField(chargeusagebased.FieldBillingPeriodTo, field.TypeTime, value) + _node.BillingPeriodTo = value + } + if value, ok := _c.mutation.FullServicePeriodFrom(); ok { + _spec.SetField(chargeusagebased.FieldFullServicePeriodFrom, field.TypeTime, value) + _node.FullServicePeriodFrom = value + } + if value, ok := _c.mutation.FullServicePeriodTo(); ok { + _spec.SetField(chargeusagebased.FieldFullServicePeriodTo, field.TypeTime, value) + _node.FullServicePeriodTo = value + } + if value, ok := _c.mutation.Status(); ok { + _spec.SetField(chargeusagebased.FieldStatus, field.TypeEnum, value) + _node.Status = value + } + if value, ok := _c.mutation.UniqueReferenceID(); ok { + _spec.SetField(chargeusagebased.FieldUniqueReferenceID, field.TypeString, value) + _node.UniqueReferenceID = &value + } + if value, ok := _c.mutation.Currency(); ok { + _spec.SetField(chargeusagebased.FieldCurrency, field.TypeString, value) + _node.Currency = value + } + if value, ok := _c.mutation.ManagedBy(); ok { + _spec.SetField(chargeusagebased.FieldManagedBy, field.TypeEnum, value) + _node.ManagedBy = value + } + if value, ok := _c.mutation.AdvanceAfter(); ok { + _spec.SetField(chargeusagebased.FieldAdvanceAfter, field.TypeTime, value) + _node.AdvanceAfter = &value + } + if value, ok := _c.mutation.TaxBehavior(); ok { + _spec.SetField(chargeusagebased.FieldTaxBehavior, field.TypeEnum, value) + _node.TaxBehavior = &value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(chargeusagebased.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(chargeusagebased.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Metadata(); ok { + _spec.SetField(chargeusagebased.FieldMetadata, field.TypeJSON, value) + _node.Metadata = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(chargeusagebased.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(chargeusagebased.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(chargeusagebased.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(chargeusagebased.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Description(); ok { + _spec.SetField(chargeusagebased.FieldDescription, field.TypeString, value) + _node.Description = &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.IntentDeletedAt(); ok { + _spec.SetField(chargeusagebased.FieldIntentDeletedAt, field.TypeTime, value) + _node.IntentDeletedAt = &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.RatingEngine(); ok { + _spec.SetField(chargeusagebased.FieldRatingEngine, field.TypeEnum, value) + _node.RatingEngine = 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 value, ok := _c.mutation.UnitConfig(); ok { + vv, err := chargeusagebased.ValueScanner.UnitConfig.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(chargeusagebased.FieldUnitConfig, field.TypeString, vv) + _node.UnitConfig = value + } + if value, ok := _c.mutation.StatusDetailed(); ok { + _spec.SetField(chargeusagebased.FieldStatusDetailed, field.TypeEnum, value) + _node.StatusDetailed = value + } + 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) + } + if nodes := _c.mutation.DetailedLinesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebased.DetailedLinesTable, + Columns: []string{chargeusagebased.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.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.CurrentRunIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: chargeusagebased.CurrentRunTable, + Columns: []string{chargeusagebased.CurrentRunColumn}, + 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.CurrentRealizationRunID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.ChargeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + 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 = append(_spec.Edges, edge) + } + if nodes := _c.mutation.IntentOverrideIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeusagebased.IntentOverrideTable, + Columns: []string{chargeusagebased.IntentOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedoverride.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.SubscriptionIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebased.SubscriptionTable, + Columns: []string{chargeusagebased.SubscriptionColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscription.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.SubscriptionID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.SubscriptionPhaseIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebased.SubscriptionPhaseTable, + Columns: []string{chargeusagebased.SubscriptionPhaseColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionphase.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.SubscriptionPhaseID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.SubscriptionItemIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebased.SubscriptionItemTable, + Columns: []string{chargeusagebased.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.SubscriptionItemID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.CustomerIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebased.CustomerTable, + Columns: []string{chargeusagebased.CustomerColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(customer.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.CustomerID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.FeatureIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebased.FeatureTable, + Columns: []string{chargeusagebased.FeatureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbfeature.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.FeatureID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.TaxCodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebased.TaxCodeTable, + Columns: []string{chargeusagebased.TaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.TaxCodeID = nodes[0] + _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(). +// SetCustomerID(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) { +// SetCustomerID(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 + } +) + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeUsageBasedUpsert) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldServicePeriodFrom, v) + return u +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateServicePeriodFrom() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldServicePeriodFrom) + return u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeUsageBasedUpsert) SetServicePeriodTo(v time.Time) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldServicePeriodTo, v) + return u +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateServicePeriodTo() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldServicePeriodTo) + return u +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (u *ChargeUsageBasedUpsert) SetBillingPeriodFrom(v time.Time) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldBillingPeriodFrom, v) + return u +} + +// UpdateBillingPeriodFrom sets the "billing_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateBillingPeriodFrom() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldBillingPeriodFrom) + return u +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (u *ChargeUsageBasedUpsert) SetBillingPeriodTo(v time.Time) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldBillingPeriodTo, v) + return u +} + +// UpdateBillingPeriodTo sets the "billing_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateBillingPeriodTo() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldBillingPeriodTo) + return u +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (u *ChargeUsageBasedUpsert) SetFullServicePeriodFrom(v time.Time) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldFullServicePeriodFrom, v) + return u +} + +// UpdateFullServicePeriodFrom sets the "full_service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateFullServicePeriodFrom() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldFullServicePeriodFrom) + return u +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (u *ChargeUsageBasedUpsert) SetFullServicePeriodTo(v time.Time) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldFullServicePeriodTo, v) + return u +} + +// UpdateFullServicePeriodTo sets the "full_service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateFullServicePeriodTo() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldFullServicePeriodTo) + return u +} + +// SetStatus sets the "status" field. +func (u *ChargeUsageBasedUpsert) SetStatus(v meta.ChargeStatus) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldStatus, v) + return u +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateStatus() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldStatus) + return u +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (u *ChargeUsageBasedUpsert) SetSubscriptionItemID(v string) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldSubscriptionItemID, v) + return u +} + +// UpdateSubscriptionItemID sets the "subscription_item_id" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateSubscriptionItemID() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldSubscriptionItemID) + return u +} + +// ClearSubscriptionItemID clears the value of the "subscription_item_id" field. +func (u *ChargeUsageBasedUpsert) ClearSubscriptionItemID() *ChargeUsageBasedUpsert { + u.SetNull(chargeusagebased.FieldSubscriptionItemID) + return u +} + +// SetAdvanceAfter sets the "advance_after" field. +func (u *ChargeUsageBasedUpsert) SetAdvanceAfter(v time.Time) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldAdvanceAfter, v) + return u +} + +// UpdateAdvanceAfter sets the "advance_after" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateAdvanceAfter() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldAdvanceAfter) + return u +} + +// ClearAdvanceAfter clears the value of the "advance_after" field. +func (u *ChargeUsageBasedUpsert) ClearAdvanceAfter() *ChargeUsageBasedUpsert { + u.SetNull(chargeusagebased.FieldAdvanceAfter) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeUsageBasedUpsert) SetAnnotations(v models.Annotations) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateAnnotations() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeUsageBasedUpsert) ClearAnnotations() *ChargeUsageBasedUpsert { + u.SetNull(chargeusagebased.FieldAnnotations) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeUsageBasedUpsert) SetMetadata(v map[string]string) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldMetadata, v) + return u +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateMetadata() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldMetadata) + return u +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeUsageBasedUpsert) ClearMetadata() *ChargeUsageBasedUpsert { + u.SetNull(chargeusagebased.FieldMetadata) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeUsageBasedUpsert) SetUpdatedAt(v time.Time) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateUpdatedAt() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUsageBasedUpsert) SetDeletedAt(v time.Time) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateDeletedAt() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUsageBasedUpsert) ClearDeletedAt() *ChargeUsageBasedUpsert { + u.SetNull(chargeusagebased.FieldDeletedAt) + return u +} + +// SetName sets the "name" field. +func (u *ChargeUsageBasedUpsert) SetName(v string) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateName() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldName) + return u +} + +// SetDescription sets the "description" field. +func (u *ChargeUsageBasedUpsert) SetDescription(v string) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldDescription, v) + return u +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateDescription() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldDescription) + return u +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeUsageBasedUpsert) ClearDescription() *ChargeUsageBasedUpsert { + u.SetNull(chargeusagebased.FieldDescription) + return u +} + +// SetInvoiceAt sets the "invoice_at" field. +func (u *ChargeUsageBasedUpsert) SetInvoiceAt(v time.Time) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldInvoiceAt, v) + return u +} + +// UpdateInvoiceAt sets the "invoice_at" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateInvoiceAt() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldInvoiceAt) + return u +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (u *ChargeUsageBasedUpsert) SetIntentDeletedAt(v time.Time) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldIntentDeletedAt, v) + return u +} + +// UpdateIntentDeletedAt sets the "intent_deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateIntentDeletedAt() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldIntentDeletedAt) + return u +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (u *ChargeUsageBasedUpsert) ClearIntentDeletedAt() *ChargeUsageBasedUpsert { + u.SetNull(chargeusagebased.FieldIntentDeletedAt) + return u +} + +// SetDiscounts sets the "discounts" field. +func (u *ChargeUsageBasedUpsert) SetDiscounts(v *billing.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 +} + +// SetFeatureID sets the "feature_id" field. +func (u *ChargeUsageBasedUpsert) SetFeatureID(v string) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldFeatureID, v) + return u +} + +// UpdateFeatureID sets the "feature_id" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateFeatureID() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldFeatureID) + return u +} + +// SetRatingEngine sets the "rating_engine" field. +func (u *ChargeUsageBasedUpsert) SetRatingEngine(v usagebased.RatingEngine) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldRatingEngine, v) + return u +} + +// UpdateRatingEngine sets the "rating_engine" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateRatingEngine() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldRatingEngine) + return u +} + +// SetPrice sets the "price" field. +func (u *ChargeUsageBasedUpsert) SetPrice(v *productcatalog.Price) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldPrice, v) + return u +} + +// UpdatePrice sets the "price" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdatePrice() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldPrice) + return u +} + +// SetUnitConfig sets the "unit_config" field. +func (u *ChargeUsageBasedUpsert) SetUnitConfig(v *productcatalog.UnitConfig) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldUnitConfig, v) + return u +} + +// UpdateUnitConfig sets the "unit_config" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateUnitConfig() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldUnitConfig) + return u +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (u *ChargeUsageBasedUpsert) ClearUnitConfig() *ChargeUsageBasedUpsert { + u.SetNull(chargeusagebased.FieldUnitConfig) + return u +} + +// SetCurrentRealizationRunID sets the "current_realization_run_id" field. +func (u *ChargeUsageBasedUpsert) SetCurrentRealizationRunID(v string) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldCurrentRealizationRunID, v) + return u +} + +// UpdateCurrentRealizationRunID sets the "current_realization_run_id" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateCurrentRealizationRunID() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldCurrentRealizationRunID) + return u +} + +// ClearCurrentRealizationRunID clears the value of the "current_realization_run_id" field. +func (u *ChargeUsageBasedUpsert) ClearCurrentRealizationRunID() *ChargeUsageBasedUpsert { + u.SetNull(chargeusagebased.FieldCurrentRealizationRunID) + return u +} + +// SetStatusDetailed sets the "status_detailed" field. +func (u *ChargeUsageBasedUpsert) SetStatusDetailed(v usagebased.Status) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldStatusDetailed, v) + return u +} + +// UpdateStatusDetailed sets the "status_detailed" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateStatusDetailed() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldStatusDetailed) + 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.CustomerID(); exists { + s.SetIgnore(chargeusagebased.FieldCustomerID) + } + if _, exists := u.create.mutation.UniqueReferenceID(); exists { + s.SetIgnore(chargeusagebased.FieldUniqueReferenceID) + } + if _, exists := u.create.mutation.Currency(); exists { + s.SetIgnore(chargeusagebased.FieldCurrency) + } + if _, exists := u.create.mutation.ManagedBy(); exists { + s.SetIgnore(chargeusagebased.FieldManagedBy) + } + if _, exists := u.create.mutation.SubscriptionID(); exists { + s.SetIgnore(chargeusagebased.FieldSubscriptionID) + } + if _, exists := u.create.mutation.SubscriptionPhaseID(); exists { + s.SetIgnore(chargeusagebased.FieldSubscriptionPhaseID) + } + if _, exists := u.create.mutation.TaxCodeID(); exists { + s.SetIgnore(chargeusagebased.FieldTaxCodeID) + } + if _, exists := u.create.mutation.TaxBehavior(); exists { + s.SetIgnore(chargeusagebased.FieldTaxBehavior) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(chargeusagebased.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(chargeusagebased.FieldCreatedAt) + } + if _, exists := u.create.mutation.SettlementMode(); exists { + s.SetIgnore(chargeusagebased.FieldSettlementMode) + } + if _, exists := u.create.mutation.FeatureKey(); exists { + s.SetIgnore(chargeusagebased.FieldFeatureKey) + } + })) + 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 +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeUsageBasedUpsertOne) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateServicePeriodFrom() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeUsageBasedUpsertOne) SetServicePeriodTo(v time.Time) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateServicePeriodTo() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (u *ChargeUsageBasedUpsertOne) SetBillingPeriodFrom(v time.Time) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetBillingPeriodFrom(v) + }) +} + +// UpdateBillingPeriodFrom sets the "billing_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateBillingPeriodFrom() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateBillingPeriodFrom() + }) +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (u *ChargeUsageBasedUpsertOne) SetBillingPeriodTo(v time.Time) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetBillingPeriodTo(v) + }) +} + +// UpdateBillingPeriodTo sets the "billing_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateBillingPeriodTo() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateBillingPeriodTo() + }) +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (u *ChargeUsageBasedUpsertOne) SetFullServicePeriodFrom(v time.Time) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetFullServicePeriodFrom(v) + }) +} + +// UpdateFullServicePeriodFrom sets the "full_service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateFullServicePeriodFrom() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateFullServicePeriodFrom() + }) +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (u *ChargeUsageBasedUpsertOne) SetFullServicePeriodTo(v time.Time) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetFullServicePeriodTo(v) + }) +} + +// UpdateFullServicePeriodTo sets the "full_service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateFullServicePeriodTo() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateFullServicePeriodTo() + }) +} + +// SetStatus sets the "status" field. +func (u *ChargeUsageBasedUpsertOne) SetStatus(v meta.ChargeStatus) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateStatus() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateStatus() + }) +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (u *ChargeUsageBasedUpsertOne) SetSubscriptionItemID(v string) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetSubscriptionItemID(v) + }) +} + +// UpdateSubscriptionItemID sets the "subscription_item_id" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateSubscriptionItemID() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateSubscriptionItemID() + }) +} + +// ClearSubscriptionItemID clears the value of the "subscription_item_id" field. +func (u *ChargeUsageBasedUpsertOne) ClearSubscriptionItemID() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.ClearSubscriptionItemID() + }) +} + +// SetAdvanceAfter sets the "advance_after" field. +func (u *ChargeUsageBasedUpsertOne) SetAdvanceAfter(v time.Time) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetAdvanceAfter(v) + }) +} + +// UpdateAdvanceAfter sets the "advance_after" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateAdvanceAfter() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateAdvanceAfter() + }) +} + +// ClearAdvanceAfter clears the value of the "advance_after" field. +func (u *ChargeUsageBasedUpsertOne) ClearAdvanceAfter() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.ClearAdvanceAfter() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeUsageBasedUpsertOne) SetAnnotations(v models.Annotations) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateAnnotations() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeUsageBasedUpsertOne) ClearAnnotations() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.ClearAnnotations() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeUsageBasedUpsertOne) SetMetadata(v map[string]string) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateMetadata() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeUsageBasedUpsertOne) ClearMetadata() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeUsageBasedUpsertOne) SetUpdatedAt(v time.Time) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateUpdatedAt() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUsageBasedUpsertOne) SetDeletedAt(v time.Time) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateDeletedAt() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUsageBasedUpsertOne) ClearDeletedAt() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *ChargeUsageBasedUpsertOne) SetName(v string) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateName() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *ChargeUsageBasedUpsertOne) SetDescription(v string) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateDescription() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeUsageBasedUpsertOne) ClearDescription() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.ClearDescription() + }) +} + +// SetInvoiceAt sets the "invoice_at" field. +func (u *ChargeUsageBasedUpsertOne) SetInvoiceAt(v time.Time) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetInvoiceAt(v) + }) +} + +// UpdateInvoiceAt sets the "invoice_at" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateInvoiceAt() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateInvoiceAt() + }) +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (u *ChargeUsageBasedUpsertOne) SetIntentDeletedAt(v time.Time) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetIntentDeletedAt(v) + }) +} + +// UpdateIntentDeletedAt sets the "intent_deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateIntentDeletedAt() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateIntentDeletedAt() + }) +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (u *ChargeUsageBasedUpsertOne) ClearIntentDeletedAt() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.ClearIntentDeletedAt() + }) +} + +// SetDiscounts sets the "discounts" field. +func (u *ChargeUsageBasedUpsertOne) SetDiscounts(v *billing.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() + }) +} + +// SetFeatureID sets the "feature_id" field. +func (u *ChargeUsageBasedUpsertOne) SetFeatureID(v string) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetFeatureID(v) + }) +} + +// UpdateFeatureID sets the "feature_id" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateFeatureID() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateFeatureID() + }) +} + +// SetRatingEngine sets the "rating_engine" field. +func (u *ChargeUsageBasedUpsertOne) SetRatingEngine(v usagebased.RatingEngine) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetRatingEngine(v) + }) +} + +// UpdateRatingEngine sets the "rating_engine" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateRatingEngine() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateRatingEngine() + }) +} + +// SetPrice sets the "price" field. +func (u *ChargeUsageBasedUpsertOne) SetPrice(v *productcatalog.Price) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetPrice(v) + }) +} + +// UpdatePrice sets the "price" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdatePrice() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdatePrice() + }) +} + +// SetUnitConfig sets the "unit_config" field. +func (u *ChargeUsageBasedUpsertOne) SetUnitConfig(v *productcatalog.UnitConfig) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetUnitConfig(v) + }) +} + +// UpdateUnitConfig sets the "unit_config" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateUnitConfig() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateUnitConfig() + }) +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (u *ChargeUsageBasedUpsertOne) ClearUnitConfig() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.ClearUnitConfig() + }) +} + +// SetCurrentRealizationRunID sets the "current_realization_run_id" field. +func (u *ChargeUsageBasedUpsertOne) SetCurrentRealizationRunID(v string) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetCurrentRealizationRunID(v) + }) +} + +// UpdateCurrentRealizationRunID sets the "current_realization_run_id" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateCurrentRealizationRunID() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateCurrentRealizationRunID() + }) +} + +// ClearCurrentRealizationRunID clears the value of the "current_realization_run_id" field. +func (u *ChargeUsageBasedUpsertOne) ClearCurrentRealizationRunID() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.ClearCurrentRealizationRunID() + }) +} + +// SetStatusDetailed sets the "status_detailed" field. +func (u *ChargeUsageBasedUpsertOne) SetStatusDetailed(v usagebased.Status) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetStatusDetailed(v) + }) +} + +// UpdateStatusDetailed sets the "status_detailed" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateStatusDetailed() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateStatusDetailed() + }) +} + +// 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) { +// SetCustomerID(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.CustomerID(); exists { + s.SetIgnore(chargeusagebased.FieldCustomerID) + } + if _, exists := b.mutation.UniqueReferenceID(); exists { + s.SetIgnore(chargeusagebased.FieldUniqueReferenceID) + } + if _, exists := b.mutation.Currency(); exists { + s.SetIgnore(chargeusagebased.FieldCurrency) + } + if _, exists := b.mutation.ManagedBy(); exists { + s.SetIgnore(chargeusagebased.FieldManagedBy) + } + if _, exists := b.mutation.SubscriptionID(); exists { + s.SetIgnore(chargeusagebased.FieldSubscriptionID) + } + if _, exists := b.mutation.SubscriptionPhaseID(); exists { + s.SetIgnore(chargeusagebased.FieldSubscriptionPhaseID) + } + if _, exists := b.mutation.TaxCodeID(); exists { + s.SetIgnore(chargeusagebased.FieldTaxCodeID) + } + if _, exists := b.mutation.TaxBehavior(); exists { + s.SetIgnore(chargeusagebased.FieldTaxBehavior) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(chargeusagebased.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(chargeusagebased.FieldCreatedAt) + } + if _, exists := b.mutation.SettlementMode(); exists { + s.SetIgnore(chargeusagebased.FieldSettlementMode) + } + if _, exists := b.mutation.FeatureKey(); exists { + s.SetIgnore(chargeusagebased.FieldFeatureKey) + } + } + })) + 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 +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeUsageBasedUpsertBulk) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateServicePeriodFrom() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeUsageBasedUpsertBulk) SetServicePeriodTo(v time.Time) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateServicePeriodTo() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (u *ChargeUsageBasedUpsertBulk) SetBillingPeriodFrom(v time.Time) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetBillingPeriodFrom(v) + }) +} + +// UpdateBillingPeriodFrom sets the "billing_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateBillingPeriodFrom() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateBillingPeriodFrom() + }) +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (u *ChargeUsageBasedUpsertBulk) SetBillingPeriodTo(v time.Time) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetBillingPeriodTo(v) + }) +} + +// UpdateBillingPeriodTo sets the "billing_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateBillingPeriodTo() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateBillingPeriodTo() + }) +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (u *ChargeUsageBasedUpsertBulk) SetFullServicePeriodFrom(v time.Time) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetFullServicePeriodFrom(v) + }) +} + +// UpdateFullServicePeriodFrom sets the "full_service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateFullServicePeriodFrom() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateFullServicePeriodFrom() + }) +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (u *ChargeUsageBasedUpsertBulk) SetFullServicePeriodTo(v time.Time) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetFullServicePeriodTo(v) + }) +} + +// UpdateFullServicePeriodTo sets the "full_service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateFullServicePeriodTo() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateFullServicePeriodTo() + }) +} + +// SetStatus sets the "status" field. +func (u *ChargeUsageBasedUpsertBulk) SetStatus(v meta.ChargeStatus) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateStatus() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateStatus() + }) +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (u *ChargeUsageBasedUpsertBulk) SetSubscriptionItemID(v string) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetSubscriptionItemID(v) + }) +} + +// UpdateSubscriptionItemID sets the "subscription_item_id" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateSubscriptionItemID() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateSubscriptionItemID() + }) +} + +// ClearSubscriptionItemID clears the value of the "subscription_item_id" field. +func (u *ChargeUsageBasedUpsertBulk) ClearSubscriptionItemID() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.ClearSubscriptionItemID() + }) +} + +// SetAdvanceAfter sets the "advance_after" field. +func (u *ChargeUsageBasedUpsertBulk) SetAdvanceAfter(v time.Time) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetAdvanceAfter(v) + }) +} + +// UpdateAdvanceAfter sets the "advance_after" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateAdvanceAfter() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateAdvanceAfter() + }) +} + +// ClearAdvanceAfter clears the value of the "advance_after" field. +func (u *ChargeUsageBasedUpsertBulk) ClearAdvanceAfter() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.ClearAdvanceAfter() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeUsageBasedUpsertBulk) SetAnnotations(v models.Annotations) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateAnnotations() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeUsageBasedUpsertBulk) ClearAnnotations() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.ClearAnnotations() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeUsageBasedUpsertBulk) SetMetadata(v map[string]string) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateMetadata() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeUsageBasedUpsertBulk) ClearMetadata() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeUsageBasedUpsertBulk) SetUpdatedAt(v time.Time) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateUpdatedAt() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUsageBasedUpsertBulk) SetDeletedAt(v time.Time) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateDeletedAt() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUsageBasedUpsertBulk) ClearDeletedAt() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *ChargeUsageBasedUpsertBulk) SetName(v string) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateName() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *ChargeUsageBasedUpsertBulk) SetDescription(v string) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateDescription() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeUsageBasedUpsertBulk) ClearDescription() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.ClearDescription() + }) +} + +// SetInvoiceAt sets the "invoice_at" field. +func (u *ChargeUsageBasedUpsertBulk) SetInvoiceAt(v time.Time) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetInvoiceAt(v) + }) +} + +// UpdateInvoiceAt sets the "invoice_at" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateInvoiceAt() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateInvoiceAt() + }) +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (u *ChargeUsageBasedUpsertBulk) SetIntentDeletedAt(v time.Time) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetIntentDeletedAt(v) + }) +} + +// UpdateIntentDeletedAt sets the "intent_deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateIntentDeletedAt() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateIntentDeletedAt() + }) +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (u *ChargeUsageBasedUpsertBulk) ClearIntentDeletedAt() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.ClearIntentDeletedAt() + }) +} + +// SetDiscounts sets the "discounts" field. +func (u *ChargeUsageBasedUpsertBulk) SetDiscounts(v *billing.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() + }) +} + +// SetFeatureID sets the "feature_id" field. +func (u *ChargeUsageBasedUpsertBulk) SetFeatureID(v string) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetFeatureID(v) + }) +} + +// UpdateFeatureID sets the "feature_id" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateFeatureID() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateFeatureID() + }) +} + +// SetRatingEngine sets the "rating_engine" field. +func (u *ChargeUsageBasedUpsertBulk) SetRatingEngine(v usagebased.RatingEngine) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetRatingEngine(v) + }) +} + +// UpdateRatingEngine sets the "rating_engine" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateRatingEngine() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateRatingEngine() + }) +} + +// SetPrice sets the "price" field. +func (u *ChargeUsageBasedUpsertBulk) SetPrice(v *productcatalog.Price) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetPrice(v) + }) +} + +// UpdatePrice sets the "price" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdatePrice() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdatePrice() + }) +} + +// SetUnitConfig sets the "unit_config" field. +func (u *ChargeUsageBasedUpsertBulk) SetUnitConfig(v *productcatalog.UnitConfig) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetUnitConfig(v) + }) +} + +// UpdateUnitConfig sets the "unit_config" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateUnitConfig() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateUnitConfig() + }) +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (u *ChargeUsageBasedUpsertBulk) ClearUnitConfig() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.ClearUnitConfig() + }) +} + +// SetCurrentRealizationRunID sets the "current_realization_run_id" field. +func (u *ChargeUsageBasedUpsertBulk) SetCurrentRealizationRunID(v string) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetCurrentRealizationRunID(v) + }) +} + +// UpdateCurrentRealizationRunID sets the "current_realization_run_id" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateCurrentRealizationRunID() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateCurrentRealizationRunID() + }) +} + +// ClearCurrentRealizationRunID clears the value of the "current_realization_run_id" field. +func (u *ChargeUsageBasedUpsertBulk) ClearCurrentRealizationRunID() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.ClearCurrentRealizationRunID() + }) +} + +// SetStatusDetailed sets the "status_detailed" field. +func (u *ChargeUsageBasedUpsertBulk) SetStatusDetailed(v usagebased.Status) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetStatusDetailed(v) + }) +} + +// UpdateStatusDetailed sets the "status_detailed" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateStatusDetailed() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateStatusDetailed() + }) +} + +// 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/ent/db/chargeusagebased_delete.go b/ent/db/chargeusagebased_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..41b4836f88cf5356ea56eb1b1a09e1ffd0afe717 --- /dev/null +++ b/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/ent/db/chargeusagebased_query.go b/ent/db/chargeusagebased_query.go new file mode 100644 index 0000000000000000000000000000000000000000..2ab635ab86786f813040eb634cddb0bf13446810 --- /dev/null +++ b/ent/db/chargeusagebased_query.go @@ -0,0 +1,1398 @@ +// 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/chargeusagebasedoverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrundetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/openmeter/ent/db/customer" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionphase" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" +) + +// ChargeUsageBasedQuery is the builder for querying ChargeUsageBased entities. +type ChargeUsageBasedQuery struct { + config + ctx *QueryContext + order []chargeusagebased.OrderOption + inters []Interceptor + predicates []predicate.ChargeUsageBased + withRuns *ChargeUsageBasedRunsQuery + withDetailedLines *ChargeUsageBasedRunDetailedLineQuery + withCurrentRun *ChargeUsageBasedRunsQuery + withCharge *ChargeQuery + withIntentOverride *ChargeUsageBasedOverrideQuery + withSubscription *SubscriptionQuery + withSubscriptionPhase *SubscriptionPhaseQuery + withSubscriptionItem *SubscriptionItemQuery + withCustomer *CustomerQuery + withFeature *FeatureQuery + withTaxCode *TaxCodeQuery + 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 +} + +// 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 +} + +// QueryDetailedLines chains the current query on the "detailed_lines" edge. +func (_q *ChargeUsageBasedQuery) QueryDetailedLines() *ChargeUsageBasedRunDetailedLineQuery { + query := (&ChargeUsageBasedRunDetailedLineClient{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(chargeusagebasedrundetailedline.Table, chargeusagebasedrundetailedline.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, chargeusagebased.DetailedLinesTable, chargeusagebased.DetailedLinesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCurrentRun chains the current query on the "current_run" edge. +func (_q *ChargeUsageBasedQuery) QueryCurrentRun() *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.M2O, false, chargeusagebased.CurrentRunTable, chargeusagebased.CurrentRunColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// 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, false, chargeusagebased.ChargeTable, chargeusagebased.ChargeColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryIntentOverride chains the current query on the "intent_override" edge. +func (_q *ChargeUsageBasedQuery) QueryIntentOverride() *ChargeUsageBasedOverrideQuery { + query := (&ChargeUsageBasedOverrideClient{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(chargeusagebasedoverride.Table, chargeusagebasedoverride.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargeusagebased.IntentOverrideTable, chargeusagebased.IntentOverrideColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySubscription chains the current query on the "subscription" edge. +func (_q *ChargeUsageBasedQuery) QuerySubscription() *SubscriptionQuery { + query := (&SubscriptionClient{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(subscription.Table, subscription.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebased.SubscriptionTable, chargeusagebased.SubscriptionColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySubscriptionPhase chains the current query on the "subscription_phase" edge. +func (_q *ChargeUsageBasedQuery) QuerySubscriptionPhase() *SubscriptionPhaseQuery { + query := (&SubscriptionPhaseClient{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(subscriptionphase.Table, subscriptionphase.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebased.SubscriptionPhaseTable, chargeusagebased.SubscriptionPhaseColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySubscriptionItem chains the current query on the "subscription_item" edge. +func (_q *ChargeUsageBasedQuery) QuerySubscriptionItem() *SubscriptionItemQuery { + query := (&SubscriptionItemClient{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(subscriptionitem.Table, subscriptionitem.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebased.SubscriptionItemTable, chargeusagebased.SubscriptionItemColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCustomer chains the current query on the "customer" edge. +func (_q *ChargeUsageBasedQuery) QueryCustomer() *CustomerQuery { + query := (&CustomerClient{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(customer.Table, customer.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebased.CustomerTable, chargeusagebased.CustomerColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryFeature chains the current query on the "feature" edge. +func (_q *ChargeUsageBasedQuery) QueryFeature() *FeatureQuery { + query := (&FeatureClient{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(dbfeature.Table, dbfeature.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebased.FeatureTable, chargeusagebased.FeatureColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryTaxCode chains the current query on the "tax_code" edge. +func (_q *ChargeUsageBasedQuery) QueryTaxCode() *TaxCodeQuery { + query := (&TaxCodeClient{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(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebased.TaxCodeTable, chargeusagebased.TaxCodeColumn), + ) + 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...), + withRuns: _q.withRuns.Clone(), + withDetailedLines: _q.withDetailedLines.Clone(), + withCurrentRun: _q.withCurrentRun.Clone(), + withCharge: _q.withCharge.Clone(), + withIntentOverride: _q.withIntentOverride.Clone(), + withSubscription: _q.withSubscription.Clone(), + withSubscriptionPhase: _q.withSubscriptionPhase.Clone(), + withSubscriptionItem: _q.withSubscriptionItem.Clone(), + withCustomer: _q.withCustomer.Clone(), + withFeature: _q.withFeature.Clone(), + withTaxCode: _q.withTaxCode.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// 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 +} + +// WithDetailedLines tells the query-builder to eager-load the nodes that are connected to +// the "detailed_lines" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedQuery) WithDetailedLines(opts ...func(*ChargeUsageBasedRunDetailedLineQuery)) *ChargeUsageBasedQuery { + query := (&ChargeUsageBasedRunDetailedLineClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withDetailedLines = query + return _q +} + +// WithCurrentRun tells the query-builder to eager-load the nodes that are connected to +// the "current_run" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedQuery) WithCurrentRun(opts ...func(*ChargeUsageBasedRunsQuery)) *ChargeUsageBasedQuery { + query := (&ChargeUsageBasedRunsClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCurrentRun = query + return _q +} + +// 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 +} + +// WithIntentOverride tells the query-builder to eager-load the nodes that are connected to +// the "intent_override" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedQuery) WithIntentOverride(opts ...func(*ChargeUsageBasedOverrideQuery)) *ChargeUsageBasedQuery { + query := (&ChargeUsageBasedOverrideClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withIntentOverride = query + return _q +} + +// WithSubscription tells the query-builder to eager-load the nodes that are connected to +// the "subscription" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedQuery) WithSubscription(opts ...func(*SubscriptionQuery)) *ChargeUsageBasedQuery { + query := (&SubscriptionClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSubscription = query + return _q +} + +// WithSubscriptionPhase tells the query-builder to eager-load the nodes that are connected to +// the "subscription_phase" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedQuery) WithSubscriptionPhase(opts ...func(*SubscriptionPhaseQuery)) *ChargeUsageBasedQuery { + query := (&SubscriptionPhaseClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSubscriptionPhase = query + return _q +} + +// WithSubscriptionItem tells the query-builder to eager-load the nodes that are connected to +// the "subscription_item" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedQuery) WithSubscriptionItem(opts ...func(*SubscriptionItemQuery)) *ChargeUsageBasedQuery { + query := (&SubscriptionItemClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSubscriptionItem = query + return _q +} + +// WithCustomer tells the query-builder to eager-load the nodes that are connected to +// the "customer" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedQuery) WithCustomer(opts ...func(*CustomerQuery)) *ChargeUsageBasedQuery { + query := (&CustomerClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCustomer = query + return _q +} + +// WithFeature tells the query-builder to eager-load the nodes that are connected to +// the "feature" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedQuery) WithFeature(opts ...func(*FeatureQuery)) *ChargeUsageBasedQuery { + query := (&FeatureClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withFeature = query + return _q +} + +// WithTaxCode tells the query-builder to eager-load the nodes that are connected to +// the "tax_code" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedQuery) WithTaxCode(opts ...func(*TaxCodeQuery)) *ChargeUsageBasedQuery { + query := (&TaxCodeClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withTaxCode = 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 { +// CustomerID string `json:"customer_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.ChargeUsageBased.Query(). +// GroupBy(chargeusagebased.FieldCustomerID). +// 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 { +// CustomerID string `json:"customer_id,omitempty"` +// } +// +// client.ChargeUsageBased.Query(). +// Select(chargeusagebased.FieldCustomerID). +// 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 = [11]bool{ + _q.withRuns != nil, + _q.withDetailedLines != nil, + _q.withCurrentRun != nil, + _q.withCharge != nil, + _q.withIntentOverride != nil, + _q.withSubscription != nil, + _q.withSubscriptionPhase != nil, + _q.withSubscriptionItem != nil, + _q.withCustomer != nil, + _q.withFeature != nil, + _q.withTaxCode != 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.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 + } + } + if query := _q.withDetailedLines; query != nil { + if err := _q.loadDetailedLines(ctx, query, nodes, + func(n *ChargeUsageBased) { n.Edges.DetailedLines = []*ChargeUsageBasedRunDetailedLine{} }, + func(n *ChargeUsageBased, e *ChargeUsageBasedRunDetailedLine) { + n.Edges.DetailedLines = append(n.Edges.DetailedLines, e) + }); err != nil { + return nil, err + } + } + if query := _q.withCurrentRun; query != nil { + if err := _q.loadCurrentRun(ctx, query, nodes, nil, + func(n *ChargeUsageBased, e *ChargeUsageBasedRuns) { n.Edges.CurrentRun = e }); err != nil { + return nil, err + } + } + 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.withIntentOverride; query != nil { + if err := _q.loadIntentOverride(ctx, query, nodes, nil, + func(n *ChargeUsageBased, e *ChargeUsageBasedOverride) { n.Edges.IntentOverride = e }); err != nil { + return nil, err + } + } + if query := _q.withSubscription; query != nil { + if err := _q.loadSubscription(ctx, query, nodes, nil, + func(n *ChargeUsageBased, e *Subscription) { n.Edges.Subscription = e }); err != nil { + return nil, err + } + } + if query := _q.withSubscriptionPhase; query != nil { + if err := _q.loadSubscriptionPhase(ctx, query, nodes, nil, + func(n *ChargeUsageBased, e *SubscriptionPhase) { n.Edges.SubscriptionPhase = e }); err != nil { + return nil, err + } + } + if query := _q.withSubscriptionItem; query != nil { + if err := _q.loadSubscriptionItem(ctx, query, nodes, nil, + func(n *ChargeUsageBased, e *SubscriptionItem) { n.Edges.SubscriptionItem = e }); err != nil { + return nil, err + } + } + if query := _q.withCustomer; query != nil { + if err := _q.loadCustomer(ctx, query, nodes, nil, + func(n *ChargeUsageBased, e *Customer) { n.Edges.Customer = e }); err != nil { + return nil, err + } + } + if query := _q.withFeature; query != nil { + if err := _q.loadFeature(ctx, query, nodes, nil, + func(n *ChargeUsageBased, e *Feature) { n.Edges.Feature = e }); err != nil { + return nil, err + } + } + if query := _q.withTaxCode; query != nil { + if err := _q.loadTaxCode(ctx, query, nodes, nil, + func(n *ChargeUsageBased, e *TaxCode) { n.Edges.TaxCode = e }); err != nil { + return nil, err + } + } + return nodes, 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) loadDetailedLines(ctx context.Context, query *ChargeUsageBasedRunDetailedLineQuery, nodes []*ChargeUsageBased, init func(*ChargeUsageBased), assign func(*ChargeUsageBased, *ChargeUsageBasedRunDetailedLine)) 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(chargeusagebasedrundetailedline.FieldChargeID) + } + query.Where(predicate.ChargeUsageBasedRunDetailedLine(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargeusagebased.DetailedLinesColumn), 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) loadCurrentRun(ctx context.Context, query *ChargeUsageBasedRunsQuery, nodes []*ChargeUsageBased, init func(*ChargeUsageBased), assign func(*ChargeUsageBased, *ChargeUsageBasedRuns)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBased) + for i := range nodes { + if nodes[i].CurrentRealizationRunID == nil { + continue + } + fk := *nodes[i].CurrentRealizationRunID + 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 "current_realization_run_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeUsageBasedQuery) loadCharge(ctx context.Context, query *ChargeQuery, nodes []*ChargeUsageBased, init func(*ChargeUsageBased), assign func(*ChargeUsageBased, *Charge)) 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 len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(charge.FieldChargeUsageBasedID) + } + query.Where(predicate.Charge(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargeusagebased.ChargeColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.ChargeUsageBasedID + if fk == nil { + return fmt.Errorf(`foreign-key "charge_usage_based_id" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "charge_usage_based_id" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *ChargeUsageBasedQuery) loadIntentOverride(ctx context.Context, query *ChargeUsageBasedOverrideQuery, nodes []*ChargeUsageBased, init func(*ChargeUsageBased), assign func(*ChargeUsageBased, *ChargeUsageBasedOverride)) 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 len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(chargeusagebasedoverride.FieldChargeID) + } + query.Where(predicate.ChargeUsageBasedOverride(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargeusagebased.IntentOverrideColumn), 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) loadSubscription(ctx context.Context, query *SubscriptionQuery, nodes []*ChargeUsageBased, init func(*ChargeUsageBased), assign func(*ChargeUsageBased, *Subscription)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBased) + for i := range nodes { + if nodes[i].SubscriptionID == nil { + continue + } + fk := *nodes[i].SubscriptionID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(subscription.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 "subscription_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeUsageBasedQuery) loadSubscriptionPhase(ctx context.Context, query *SubscriptionPhaseQuery, nodes []*ChargeUsageBased, init func(*ChargeUsageBased), assign func(*ChargeUsageBased, *SubscriptionPhase)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBased) + for i := range nodes { + if nodes[i].SubscriptionPhaseID == nil { + continue + } + fk := *nodes[i].SubscriptionPhaseID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(subscriptionphase.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 "subscription_phase_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeUsageBasedQuery) loadSubscriptionItem(ctx context.Context, query *SubscriptionItemQuery, nodes []*ChargeUsageBased, init func(*ChargeUsageBased), assign func(*ChargeUsageBased, *SubscriptionItem)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBased) + for i := range nodes { + if nodes[i].SubscriptionItemID == nil { + continue + } + fk := *nodes[i].SubscriptionItemID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(subscriptionitem.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 "subscription_item_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeUsageBasedQuery) loadCustomer(ctx context.Context, query *CustomerQuery, nodes []*ChargeUsageBased, init func(*ChargeUsageBased), assign func(*ChargeUsageBased, *Customer)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBased) + for i := range nodes { + fk := nodes[i].CustomerID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(customer.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 "customer_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeUsageBasedQuery) loadFeature(ctx context.Context, query *FeatureQuery, nodes []*ChargeUsageBased, init func(*ChargeUsageBased), assign func(*ChargeUsageBased, *Feature)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBased) + for i := range nodes { + fk := nodes[i].FeatureID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(dbfeature.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 "feature_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeUsageBasedQuery) loadTaxCode(ctx context.Context, query *TaxCodeQuery, nodes []*ChargeUsageBased, init func(*ChargeUsageBased), assign func(*ChargeUsageBased, *TaxCode)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBased) + for i := range nodes { + fk := nodes[i].TaxCodeID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(dbtaxcode.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 "tax_code_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], 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 _q.withCurrentRun != nil { + _spec.Node.AddColumnOnce(chargeusagebased.FieldCurrentRealizationRunID) + } + if _q.withSubscription != nil { + _spec.Node.AddColumnOnce(chargeusagebased.FieldSubscriptionID) + } + if _q.withSubscriptionPhase != nil { + _spec.Node.AddColumnOnce(chargeusagebased.FieldSubscriptionPhaseID) + } + if _q.withSubscriptionItem != nil { + _spec.Node.AddColumnOnce(chargeusagebased.FieldSubscriptionItemID) + } + if _q.withCustomer != nil { + _spec.Node.AddColumnOnce(chargeusagebased.FieldCustomerID) + } + if _q.withFeature != nil { + _spec.Node.AddColumnOnce(chargeusagebased.FieldFeatureID) + } + if _q.withTaxCode != nil { + _spec.Node.AddColumnOnce(chargeusagebased.FieldTaxCodeID) + } + } + 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/ent/db/chargeusagebased_update.go b/ent/db/chargeusagebased_update.go new file mode 100644 index 0000000000000000000000000000000000000000..c08233f21a15f8a323445e7e063acf2f0503583d --- /dev/null +++ b/ent/db/chargeusagebased_update.go @@ -0,0 +1,1914 @@ +// 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/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedoverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrundetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/models" +) + +// 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 +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeUsageBasedUpdate) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedUpdate { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdate) SetNillableServicePeriodFrom(v *time.Time) *ChargeUsageBasedUpdate { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeUsageBasedUpdate) SetServicePeriodTo(v time.Time) *ChargeUsageBasedUpdate { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdate) SetNillableServicePeriodTo(v *time.Time) *ChargeUsageBasedUpdate { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (_u *ChargeUsageBasedUpdate) SetBillingPeriodFrom(v time.Time) *ChargeUsageBasedUpdate { + _u.mutation.SetBillingPeriodFrom(v) + return _u +} + +// SetNillableBillingPeriodFrom sets the "billing_period_from" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdate) SetNillableBillingPeriodFrom(v *time.Time) *ChargeUsageBasedUpdate { + if v != nil { + _u.SetBillingPeriodFrom(*v) + } + return _u +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (_u *ChargeUsageBasedUpdate) SetBillingPeriodTo(v time.Time) *ChargeUsageBasedUpdate { + _u.mutation.SetBillingPeriodTo(v) + return _u +} + +// SetNillableBillingPeriodTo sets the "billing_period_to" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdate) SetNillableBillingPeriodTo(v *time.Time) *ChargeUsageBasedUpdate { + if v != nil { + _u.SetBillingPeriodTo(*v) + } + return _u +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (_u *ChargeUsageBasedUpdate) SetFullServicePeriodFrom(v time.Time) *ChargeUsageBasedUpdate { + _u.mutation.SetFullServicePeriodFrom(v) + return _u +} + +// SetNillableFullServicePeriodFrom sets the "full_service_period_from" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdate) SetNillableFullServicePeriodFrom(v *time.Time) *ChargeUsageBasedUpdate { + if v != nil { + _u.SetFullServicePeriodFrom(*v) + } + return _u +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (_u *ChargeUsageBasedUpdate) SetFullServicePeriodTo(v time.Time) *ChargeUsageBasedUpdate { + _u.mutation.SetFullServicePeriodTo(v) + return _u +} + +// SetNillableFullServicePeriodTo sets the "full_service_period_to" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdate) SetNillableFullServicePeriodTo(v *time.Time) *ChargeUsageBasedUpdate { + if v != nil { + _u.SetFullServicePeriodTo(*v) + } + return _u +} + +// SetStatus sets the "status" field. +func (_u *ChargeUsageBasedUpdate) SetStatus(v meta.ChargeStatus) *ChargeUsageBasedUpdate { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdate) SetNillableStatus(v *meta.ChargeStatus) *ChargeUsageBasedUpdate { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (_u *ChargeUsageBasedUpdate) SetSubscriptionItemID(v string) *ChargeUsageBasedUpdate { + _u.mutation.SetSubscriptionItemID(v) + return _u +} + +// SetNillableSubscriptionItemID sets the "subscription_item_id" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdate) SetNillableSubscriptionItemID(v *string) *ChargeUsageBasedUpdate { + if v != nil { + _u.SetSubscriptionItemID(*v) + } + return _u +} + +// ClearSubscriptionItemID clears the value of the "subscription_item_id" field. +func (_u *ChargeUsageBasedUpdate) ClearSubscriptionItemID() *ChargeUsageBasedUpdate { + _u.mutation.ClearSubscriptionItemID() + return _u +} + +// SetAdvanceAfter sets the "advance_after" field. +func (_u *ChargeUsageBasedUpdate) SetAdvanceAfter(v time.Time) *ChargeUsageBasedUpdate { + _u.mutation.SetAdvanceAfter(v) + return _u +} + +// SetNillableAdvanceAfter sets the "advance_after" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdate) SetNillableAdvanceAfter(v *time.Time) *ChargeUsageBasedUpdate { + if v != nil { + _u.SetAdvanceAfter(*v) + } + return _u +} + +// ClearAdvanceAfter clears the value of the "advance_after" field. +func (_u *ChargeUsageBasedUpdate) ClearAdvanceAfter() *ChargeUsageBasedUpdate { + _u.mutation.ClearAdvanceAfter() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeUsageBasedUpdate) SetAnnotations(v models.Annotations) *ChargeUsageBasedUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeUsageBasedUpdate) ClearAnnotations() *ChargeUsageBasedUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *ChargeUsageBasedUpdate) SetMetadata(v map[string]string) *ChargeUsageBasedUpdate { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *ChargeUsageBasedUpdate) ClearMetadata() *ChargeUsageBasedUpdate { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeUsageBasedUpdate) SetUpdatedAt(v time.Time) *ChargeUsageBasedUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeUsageBasedUpdate) SetDeletedAt(v time.Time) *ChargeUsageBasedUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdate) SetNillableDeletedAt(v *time.Time) *ChargeUsageBasedUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeUsageBasedUpdate) ClearDeletedAt() *ChargeUsageBasedUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *ChargeUsageBasedUpdate) SetName(v string) *ChargeUsageBasedUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdate) SetNillableName(v *string) *ChargeUsageBasedUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *ChargeUsageBasedUpdate) SetDescription(v string) *ChargeUsageBasedUpdate { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdate) SetNillableDescription(v *string) *ChargeUsageBasedUpdate { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *ChargeUsageBasedUpdate) ClearDescription() *ChargeUsageBasedUpdate { + _u.mutation.ClearDescription() + return _u +} + +// SetInvoiceAt sets the "invoice_at" field. +func (_u *ChargeUsageBasedUpdate) SetInvoiceAt(v time.Time) *ChargeUsageBasedUpdate { + _u.mutation.SetInvoiceAt(v) + return _u +} + +// SetNillableInvoiceAt sets the "invoice_at" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdate) SetNillableInvoiceAt(v *time.Time) *ChargeUsageBasedUpdate { + if v != nil { + _u.SetInvoiceAt(*v) + } + return _u +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (_u *ChargeUsageBasedUpdate) SetIntentDeletedAt(v time.Time) *ChargeUsageBasedUpdate { + _u.mutation.SetIntentDeletedAt(v) + return _u +} + +// SetNillableIntentDeletedAt sets the "intent_deleted_at" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdate) SetNillableIntentDeletedAt(v *time.Time) *ChargeUsageBasedUpdate { + if v != nil { + _u.SetIntentDeletedAt(*v) + } + return _u +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (_u *ChargeUsageBasedUpdate) ClearIntentDeletedAt() *ChargeUsageBasedUpdate { + _u.mutation.ClearIntentDeletedAt() + return _u +} + +// SetDiscounts sets the "discounts" field. +func (_u *ChargeUsageBasedUpdate) SetDiscounts(v *billing.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 +} + +// SetFeatureID sets the "feature_id" field. +func (_u *ChargeUsageBasedUpdate) SetFeatureID(v string) *ChargeUsageBasedUpdate { + _u.mutation.SetFeatureID(v) + return _u +} + +// SetNillableFeatureID sets the "feature_id" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdate) SetNillableFeatureID(v *string) *ChargeUsageBasedUpdate { + if v != nil { + _u.SetFeatureID(*v) + } + return _u +} + +// SetRatingEngine sets the "rating_engine" field. +func (_u *ChargeUsageBasedUpdate) SetRatingEngine(v usagebased.RatingEngine) *ChargeUsageBasedUpdate { + _u.mutation.SetRatingEngine(v) + return _u +} + +// SetNillableRatingEngine sets the "rating_engine" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdate) SetNillableRatingEngine(v *usagebased.RatingEngine) *ChargeUsageBasedUpdate { + if v != nil { + _u.SetRatingEngine(*v) + } + return _u +} + +// SetPrice sets the "price" field. +func (_u *ChargeUsageBasedUpdate) SetPrice(v *productcatalog.Price) *ChargeUsageBasedUpdate { + _u.mutation.SetPrice(v) + return _u +} + +// SetUnitConfig sets the "unit_config" field. +func (_u *ChargeUsageBasedUpdate) SetUnitConfig(v *productcatalog.UnitConfig) *ChargeUsageBasedUpdate { + _u.mutation.SetUnitConfig(v) + return _u +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (_u *ChargeUsageBasedUpdate) ClearUnitConfig() *ChargeUsageBasedUpdate { + _u.mutation.ClearUnitConfig() + return _u +} + +// SetCurrentRealizationRunID sets the "current_realization_run_id" field. +func (_u *ChargeUsageBasedUpdate) SetCurrentRealizationRunID(v string) *ChargeUsageBasedUpdate { + _u.mutation.SetCurrentRealizationRunID(v) + return _u +} + +// SetNillableCurrentRealizationRunID sets the "current_realization_run_id" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdate) SetNillableCurrentRealizationRunID(v *string) *ChargeUsageBasedUpdate { + if v != nil { + _u.SetCurrentRealizationRunID(*v) + } + return _u +} + +// ClearCurrentRealizationRunID clears the value of the "current_realization_run_id" field. +func (_u *ChargeUsageBasedUpdate) ClearCurrentRealizationRunID() *ChargeUsageBasedUpdate { + _u.mutation.ClearCurrentRealizationRunID() + return _u +} + +// SetStatusDetailed sets the "status_detailed" field. +func (_u *ChargeUsageBasedUpdate) SetStatusDetailed(v usagebased.Status) *ChargeUsageBasedUpdate { + _u.mutation.SetStatusDetailed(v) + return _u +} + +// SetNillableStatusDetailed sets the "status_detailed" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdate) SetNillableStatusDetailed(v *usagebased.Status) *ChargeUsageBasedUpdate { + if v != nil { + _u.SetStatusDetailed(*v) + } + return _u +} + +// 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...) +} + +// AddDetailedLineIDs adds the "detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity by IDs. +func (_u *ChargeUsageBasedUpdate) AddDetailedLineIDs(ids ...string) *ChargeUsageBasedUpdate { + _u.mutation.AddDetailedLineIDs(ids...) + return _u +} + +// AddDetailedLines adds the "detailed_lines" edges to the ChargeUsageBasedRunDetailedLine entity. +func (_u *ChargeUsageBasedUpdate) AddDetailedLines(v ...*ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddDetailedLineIDs(ids...) +} + +// SetCurrentRunID sets the "current_run" edge to the ChargeUsageBasedRuns entity by ID. +func (_u *ChargeUsageBasedUpdate) SetCurrentRunID(id string) *ChargeUsageBasedUpdate { + _u.mutation.SetCurrentRunID(id) + return _u +} + +// SetNillableCurrentRunID sets the "current_run" edge to the ChargeUsageBasedRuns entity by ID if the given value is not nil. +func (_u *ChargeUsageBasedUpdate) SetNillableCurrentRunID(id *string) *ChargeUsageBasedUpdate { + if id != nil { + _u = _u.SetCurrentRunID(*id) + } + return _u +} + +// SetCurrentRun sets the "current_run" edge to the ChargeUsageBasedRuns entity. +func (_u *ChargeUsageBasedUpdate) SetCurrentRun(v *ChargeUsageBasedRuns) *ChargeUsageBasedUpdate { + return _u.SetCurrentRunID(v.ID) +} + +// SetIntentOverrideID sets the "intent_override" edge to the ChargeUsageBasedOverride entity by ID. +func (_u *ChargeUsageBasedUpdate) SetIntentOverrideID(id string) *ChargeUsageBasedUpdate { + _u.mutation.SetIntentOverrideID(id) + return _u +} + +// SetNillableIntentOverrideID sets the "intent_override" edge to the ChargeUsageBasedOverride entity by ID if the given value is not nil. +func (_u *ChargeUsageBasedUpdate) SetNillableIntentOverrideID(id *string) *ChargeUsageBasedUpdate { + if id != nil { + _u = _u.SetIntentOverrideID(*id) + } + return _u +} + +// SetIntentOverride sets the "intent_override" edge to the ChargeUsageBasedOverride entity. +func (_u *ChargeUsageBasedUpdate) SetIntentOverride(v *ChargeUsageBasedOverride) *ChargeUsageBasedUpdate { + return _u.SetIntentOverrideID(v.ID) +} + +// SetSubscriptionItem sets the "subscription_item" edge to the SubscriptionItem entity. +func (_u *ChargeUsageBasedUpdate) SetSubscriptionItem(v *SubscriptionItem) *ChargeUsageBasedUpdate { + return _u.SetSubscriptionItemID(v.ID) +} + +// SetFeature sets the "feature" edge to the Feature entity. +func (_u *ChargeUsageBasedUpdate) SetFeature(v *Feature) *ChargeUsageBasedUpdate { + return _u.SetFeatureID(v.ID) +} + +// Mutation returns the ChargeUsageBasedMutation object of the builder. +func (_u *ChargeUsageBasedUpdate) Mutation() *ChargeUsageBasedMutation { + return _u.mutation +} + +// 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...) +} + +// ClearDetailedLines clears all "detailed_lines" edges to the ChargeUsageBasedRunDetailedLine entity. +func (_u *ChargeUsageBasedUpdate) ClearDetailedLines() *ChargeUsageBasedUpdate { + _u.mutation.ClearDetailedLines() + return _u +} + +// RemoveDetailedLineIDs removes the "detailed_lines" edge to ChargeUsageBasedRunDetailedLine entities by IDs. +func (_u *ChargeUsageBasedUpdate) RemoveDetailedLineIDs(ids ...string) *ChargeUsageBasedUpdate { + _u.mutation.RemoveDetailedLineIDs(ids...) + return _u +} + +// RemoveDetailedLines removes "detailed_lines" edges to ChargeUsageBasedRunDetailedLine entities. +func (_u *ChargeUsageBasedUpdate) RemoveDetailedLines(v ...*ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveDetailedLineIDs(ids...) +} + +// ClearCurrentRun clears the "current_run" edge to the ChargeUsageBasedRuns entity. +func (_u *ChargeUsageBasedUpdate) ClearCurrentRun() *ChargeUsageBasedUpdate { + _u.mutation.ClearCurrentRun() + return _u +} + +// ClearIntentOverride clears the "intent_override" edge to the ChargeUsageBasedOverride entity. +func (_u *ChargeUsageBasedUpdate) ClearIntentOverride() *ChargeUsageBasedUpdate { + _u.mutation.ClearIntentOverride() + return _u +} + +// ClearSubscriptionItem clears the "subscription_item" edge to the SubscriptionItem entity. +func (_u *ChargeUsageBasedUpdate) ClearSubscriptionItem() *ChargeUsageBasedUpdate { + _u.mutation.ClearSubscriptionItem() + return _u +} + +// ClearFeature clears the "feature" edge to the Feature entity. +func (_u *ChargeUsageBasedUpdate) ClearFeature() *ChargeUsageBasedUpdate { + _u.mutation.ClearFeature() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ChargeUsageBasedUpdate) 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 *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) + } +} + +// defaults sets the default values of the builder before save. +func (_u *ChargeUsageBasedUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeusagebased.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeUsageBasedUpdate) check() error { + if v, ok := _u.mutation.Status(); ok { + if err := chargeusagebased.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.status": %w`, err)} + } + } + 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 v, ok := _u.mutation.FeatureID(); ok { + if err := chargeusagebased.FeatureIDValidator(v); err != nil { + return &ValidationError{Name: "feature_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.feature_id": %w`, err)} + } + } + if v, ok := _u.mutation.RatingEngine(); ok { + if err := chargeusagebased.RatingEngineValidator(v); err != nil { + return &ValidationError{Name: "rating_engine", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.rating_engine": %w`, err)} + } + } + if v, ok := _u.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 v, ok := _u.mutation.UnitConfig(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "unit_config", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.unit_config": %w`, err)} + } + } + if v, ok := _u.mutation.StatusDetailed(); ok { + if err := chargeusagebased.StatusDetailedValidator(v); err != nil { + return &ValidationError{Name: "status_detailed", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.status_detailed": %w`, err)} + } + } + if _u.mutation.CustomerCleared() && len(_u.mutation.CustomerIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBased.customer"`) + } + if _u.mutation.FeatureCleared() && len(_u.mutation.FeatureIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBased.feature"`) + } + if _u.mutation.TaxCodeCleared() && len(_u.mutation.TaxCodeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBased.tax_code"`) + } + 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.ServicePeriodFrom(); ok { + _spec.SetField(chargeusagebased.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeusagebased.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.BillingPeriodFrom(); ok { + _spec.SetField(chargeusagebased.FieldBillingPeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.BillingPeriodTo(); ok { + _spec.SetField(chargeusagebased.FieldBillingPeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.FullServicePeriodFrom(); ok { + _spec.SetField(chargeusagebased.FieldFullServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.FullServicePeriodTo(); ok { + _spec.SetField(chargeusagebased.FieldFullServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(chargeusagebased.FieldStatus, field.TypeEnum, value) + } + if _u.mutation.UniqueReferenceIDCleared() { + _spec.ClearField(chargeusagebased.FieldUniqueReferenceID, field.TypeString) + } + if value, ok := _u.mutation.AdvanceAfter(); ok { + _spec.SetField(chargeusagebased.FieldAdvanceAfter, field.TypeTime, value) + } + if _u.mutation.AdvanceAfterCleared() { + _spec.ClearField(chargeusagebased.FieldAdvanceAfter, field.TypeTime) + } + if _u.mutation.TaxBehaviorCleared() { + _spec.ClearField(chargeusagebased.FieldTaxBehavior, field.TypeEnum) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargeusagebased.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargeusagebased.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(chargeusagebased.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(chargeusagebased.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeusagebased.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeusagebased.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeusagebased.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(chargeusagebased.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(chargeusagebased.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(chargeusagebased.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.InvoiceAt(); ok { + _spec.SetField(chargeusagebased.FieldInvoiceAt, field.TypeTime, value) + } + if value, ok := _u.mutation.IntentDeletedAt(); ok { + _spec.SetField(chargeusagebased.FieldIntentDeletedAt, field.TypeTime, value) + } + if _u.mutation.IntentDeletedAtCleared() { + _spec.ClearField(chargeusagebased.FieldIntentDeletedAt, field.TypeTime) + } + 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 value, ok := _u.mutation.RatingEngine(); ok { + _spec.SetField(chargeusagebased.FieldRatingEngine, field.TypeEnum, value) + } + if value, ok := _u.mutation.Price(); ok { + vv, err := chargeusagebased.ValueScanner.Price.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(chargeusagebased.FieldPrice, field.TypeString, vv) + } + if value, ok := _u.mutation.UnitConfig(); ok { + vv, err := chargeusagebased.ValueScanner.UnitConfig.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(chargeusagebased.FieldUnitConfig, field.TypeString, vv) + } + if _u.mutation.UnitConfigCleared() { + _spec.ClearField(chargeusagebased.FieldUnitConfig, field.TypeString) + } + if value, ok := _u.mutation.StatusDetailed(); ok { + _spec.SetField(chargeusagebased.FieldStatusDetailed, field.TypeEnum, value) + } + 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 _u.mutation.DetailedLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebased.DetailedLinesTable, + Columns: []string{chargeusagebased.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedDetailedLinesIDs(); len(nodes) > 0 && !_u.mutation.DetailedLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebased.DetailedLinesTable, + Columns: []string{chargeusagebased.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.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.DetailedLinesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebased.DetailedLinesTable, + Columns: []string{chargeusagebased.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.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.CurrentRunCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: chargeusagebased.CurrentRunTable, + Columns: []string{chargeusagebased.CurrentRunColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.CurrentRunIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: chargeusagebased.CurrentRunTable, + Columns: []string{chargeusagebased.CurrentRunColumn}, + 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 _u.mutation.IntentOverrideCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeusagebased.IntentOverrideTable, + Columns: []string{chargeusagebased.IntentOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedoverride.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.IntentOverrideIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeusagebased.IntentOverrideTable, + Columns: []string{chargeusagebased.IntentOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedoverride.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.SubscriptionItemCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebased.SubscriptionItemTable, + Columns: []string{chargeusagebased.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.SubscriptionItemIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebased.SubscriptionItemTable, + Columns: []string{chargeusagebased.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.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.FeatureCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebased.FeatureTable, + Columns: []string{chargeusagebased.FeatureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbfeature.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.FeatureIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebased.FeatureTable, + Columns: []string{chargeusagebased.FeatureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbfeature.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 +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeUsageBasedUpdateOne) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedUpdateOne { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdateOne) SetNillableServicePeriodFrom(v *time.Time) *ChargeUsageBasedUpdateOne { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeUsageBasedUpdateOne) SetServicePeriodTo(v time.Time) *ChargeUsageBasedUpdateOne { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdateOne) SetNillableServicePeriodTo(v *time.Time) *ChargeUsageBasedUpdateOne { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (_u *ChargeUsageBasedUpdateOne) SetBillingPeriodFrom(v time.Time) *ChargeUsageBasedUpdateOne { + _u.mutation.SetBillingPeriodFrom(v) + return _u +} + +// SetNillableBillingPeriodFrom sets the "billing_period_from" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdateOne) SetNillableBillingPeriodFrom(v *time.Time) *ChargeUsageBasedUpdateOne { + if v != nil { + _u.SetBillingPeriodFrom(*v) + } + return _u +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (_u *ChargeUsageBasedUpdateOne) SetBillingPeriodTo(v time.Time) *ChargeUsageBasedUpdateOne { + _u.mutation.SetBillingPeriodTo(v) + return _u +} + +// SetNillableBillingPeriodTo sets the "billing_period_to" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdateOne) SetNillableBillingPeriodTo(v *time.Time) *ChargeUsageBasedUpdateOne { + if v != nil { + _u.SetBillingPeriodTo(*v) + } + return _u +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (_u *ChargeUsageBasedUpdateOne) SetFullServicePeriodFrom(v time.Time) *ChargeUsageBasedUpdateOne { + _u.mutation.SetFullServicePeriodFrom(v) + return _u +} + +// SetNillableFullServicePeriodFrom sets the "full_service_period_from" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdateOne) SetNillableFullServicePeriodFrom(v *time.Time) *ChargeUsageBasedUpdateOne { + if v != nil { + _u.SetFullServicePeriodFrom(*v) + } + return _u +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (_u *ChargeUsageBasedUpdateOne) SetFullServicePeriodTo(v time.Time) *ChargeUsageBasedUpdateOne { + _u.mutation.SetFullServicePeriodTo(v) + return _u +} + +// SetNillableFullServicePeriodTo sets the "full_service_period_to" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdateOne) SetNillableFullServicePeriodTo(v *time.Time) *ChargeUsageBasedUpdateOne { + if v != nil { + _u.SetFullServicePeriodTo(*v) + } + return _u +} + +// SetStatus sets the "status" field. +func (_u *ChargeUsageBasedUpdateOne) SetStatus(v meta.ChargeStatus) *ChargeUsageBasedUpdateOne { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdateOne) SetNillableStatus(v *meta.ChargeStatus) *ChargeUsageBasedUpdateOne { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (_u *ChargeUsageBasedUpdateOne) SetSubscriptionItemID(v string) *ChargeUsageBasedUpdateOne { + _u.mutation.SetSubscriptionItemID(v) + return _u +} + +// SetNillableSubscriptionItemID sets the "subscription_item_id" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdateOne) SetNillableSubscriptionItemID(v *string) *ChargeUsageBasedUpdateOne { + if v != nil { + _u.SetSubscriptionItemID(*v) + } + return _u +} + +// ClearSubscriptionItemID clears the value of the "subscription_item_id" field. +func (_u *ChargeUsageBasedUpdateOne) ClearSubscriptionItemID() *ChargeUsageBasedUpdateOne { + _u.mutation.ClearSubscriptionItemID() + return _u +} + +// SetAdvanceAfter sets the "advance_after" field. +func (_u *ChargeUsageBasedUpdateOne) SetAdvanceAfter(v time.Time) *ChargeUsageBasedUpdateOne { + _u.mutation.SetAdvanceAfter(v) + return _u +} + +// SetNillableAdvanceAfter sets the "advance_after" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdateOne) SetNillableAdvanceAfter(v *time.Time) *ChargeUsageBasedUpdateOne { + if v != nil { + _u.SetAdvanceAfter(*v) + } + return _u +} + +// ClearAdvanceAfter clears the value of the "advance_after" field. +func (_u *ChargeUsageBasedUpdateOne) ClearAdvanceAfter() *ChargeUsageBasedUpdateOne { + _u.mutation.ClearAdvanceAfter() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeUsageBasedUpdateOne) SetAnnotations(v models.Annotations) *ChargeUsageBasedUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeUsageBasedUpdateOne) ClearAnnotations() *ChargeUsageBasedUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *ChargeUsageBasedUpdateOne) SetMetadata(v map[string]string) *ChargeUsageBasedUpdateOne { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *ChargeUsageBasedUpdateOne) ClearMetadata() *ChargeUsageBasedUpdateOne { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeUsageBasedUpdateOne) SetUpdatedAt(v time.Time) *ChargeUsageBasedUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeUsageBasedUpdateOne) SetDeletedAt(v time.Time) *ChargeUsageBasedUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdateOne) SetNillableDeletedAt(v *time.Time) *ChargeUsageBasedUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeUsageBasedUpdateOne) ClearDeletedAt() *ChargeUsageBasedUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *ChargeUsageBasedUpdateOne) SetName(v string) *ChargeUsageBasedUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdateOne) SetNillableName(v *string) *ChargeUsageBasedUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *ChargeUsageBasedUpdateOne) SetDescription(v string) *ChargeUsageBasedUpdateOne { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdateOne) SetNillableDescription(v *string) *ChargeUsageBasedUpdateOne { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *ChargeUsageBasedUpdateOne) ClearDescription() *ChargeUsageBasedUpdateOne { + _u.mutation.ClearDescription() + return _u +} + +// SetInvoiceAt sets the "invoice_at" field. +func (_u *ChargeUsageBasedUpdateOne) SetInvoiceAt(v time.Time) *ChargeUsageBasedUpdateOne { + _u.mutation.SetInvoiceAt(v) + return _u +} + +// SetNillableInvoiceAt sets the "invoice_at" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdateOne) SetNillableInvoiceAt(v *time.Time) *ChargeUsageBasedUpdateOne { + if v != nil { + _u.SetInvoiceAt(*v) + } + return _u +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (_u *ChargeUsageBasedUpdateOne) SetIntentDeletedAt(v time.Time) *ChargeUsageBasedUpdateOne { + _u.mutation.SetIntentDeletedAt(v) + return _u +} + +// SetNillableIntentDeletedAt sets the "intent_deleted_at" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdateOne) SetNillableIntentDeletedAt(v *time.Time) *ChargeUsageBasedUpdateOne { + if v != nil { + _u.SetIntentDeletedAt(*v) + } + return _u +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (_u *ChargeUsageBasedUpdateOne) ClearIntentDeletedAt() *ChargeUsageBasedUpdateOne { + _u.mutation.ClearIntentDeletedAt() + return _u +} + +// SetDiscounts sets the "discounts" field. +func (_u *ChargeUsageBasedUpdateOne) SetDiscounts(v *billing.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 +} + +// SetFeatureID sets the "feature_id" field. +func (_u *ChargeUsageBasedUpdateOne) SetFeatureID(v string) *ChargeUsageBasedUpdateOne { + _u.mutation.SetFeatureID(v) + return _u +} + +// SetNillableFeatureID sets the "feature_id" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdateOne) SetNillableFeatureID(v *string) *ChargeUsageBasedUpdateOne { + if v != nil { + _u.SetFeatureID(*v) + } + return _u +} + +// SetRatingEngine sets the "rating_engine" field. +func (_u *ChargeUsageBasedUpdateOne) SetRatingEngine(v usagebased.RatingEngine) *ChargeUsageBasedUpdateOne { + _u.mutation.SetRatingEngine(v) + return _u +} + +// SetNillableRatingEngine sets the "rating_engine" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdateOne) SetNillableRatingEngine(v *usagebased.RatingEngine) *ChargeUsageBasedUpdateOne { + if v != nil { + _u.SetRatingEngine(*v) + } + return _u +} + +// SetPrice sets the "price" field. +func (_u *ChargeUsageBasedUpdateOne) SetPrice(v *productcatalog.Price) *ChargeUsageBasedUpdateOne { + _u.mutation.SetPrice(v) + return _u +} + +// SetUnitConfig sets the "unit_config" field. +func (_u *ChargeUsageBasedUpdateOne) SetUnitConfig(v *productcatalog.UnitConfig) *ChargeUsageBasedUpdateOne { + _u.mutation.SetUnitConfig(v) + return _u +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (_u *ChargeUsageBasedUpdateOne) ClearUnitConfig() *ChargeUsageBasedUpdateOne { + _u.mutation.ClearUnitConfig() + return _u +} + +// SetCurrentRealizationRunID sets the "current_realization_run_id" field. +func (_u *ChargeUsageBasedUpdateOne) SetCurrentRealizationRunID(v string) *ChargeUsageBasedUpdateOne { + _u.mutation.SetCurrentRealizationRunID(v) + return _u +} + +// SetNillableCurrentRealizationRunID sets the "current_realization_run_id" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdateOne) SetNillableCurrentRealizationRunID(v *string) *ChargeUsageBasedUpdateOne { + if v != nil { + _u.SetCurrentRealizationRunID(*v) + } + return _u +} + +// ClearCurrentRealizationRunID clears the value of the "current_realization_run_id" field. +func (_u *ChargeUsageBasedUpdateOne) ClearCurrentRealizationRunID() *ChargeUsageBasedUpdateOne { + _u.mutation.ClearCurrentRealizationRunID() + return _u +} + +// SetStatusDetailed sets the "status_detailed" field. +func (_u *ChargeUsageBasedUpdateOne) SetStatusDetailed(v usagebased.Status) *ChargeUsageBasedUpdateOne { + _u.mutation.SetStatusDetailed(v) + return _u +} + +// SetNillableStatusDetailed sets the "status_detailed" field if the given value is not nil. +func (_u *ChargeUsageBasedUpdateOne) SetNillableStatusDetailed(v *usagebased.Status) *ChargeUsageBasedUpdateOne { + if v != nil { + _u.SetStatusDetailed(*v) + } + return _u +} + +// 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...) +} + +// AddDetailedLineIDs adds the "detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity by IDs. +func (_u *ChargeUsageBasedUpdateOne) AddDetailedLineIDs(ids ...string) *ChargeUsageBasedUpdateOne { + _u.mutation.AddDetailedLineIDs(ids...) + return _u +} + +// AddDetailedLines adds the "detailed_lines" edges to the ChargeUsageBasedRunDetailedLine entity. +func (_u *ChargeUsageBasedUpdateOne) AddDetailedLines(v ...*ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddDetailedLineIDs(ids...) +} + +// SetCurrentRunID sets the "current_run" edge to the ChargeUsageBasedRuns entity by ID. +func (_u *ChargeUsageBasedUpdateOne) SetCurrentRunID(id string) *ChargeUsageBasedUpdateOne { + _u.mutation.SetCurrentRunID(id) + return _u +} + +// SetNillableCurrentRunID sets the "current_run" edge to the ChargeUsageBasedRuns entity by ID if the given value is not nil. +func (_u *ChargeUsageBasedUpdateOne) SetNillableCurrentRunID(id *string) *ChargeUsageBasedUpdateOne { + if id != nil { + _u = _u.SetCurrentRunID(*id) + } + return _u +} + +// SetCurrentRun sets the "current_run" edge to the ChargeUsageBasedRuns entity. +func (_u *ChargeUsageBasedUpdateOne) SetCurrentRun(v *ChargeUsageBasedRuns) *ChargeUsageBasedUpdateOne { + return _u.SetCurrentRunID(v.ID) +} + +// SetIntentOverrideID sets the "intent_override" edge to the ChargeUsageBasedOverride entity by ID. +func (_u *ChargeUsageBasedUpdateOne) SetIntentOverrideID(id string) *ChargeUsageBasedUpdateOne { + _u.mutation.SetIntentOverrideID(id) + return _u +} + +// SetNillableIntentOverrideID sets the "intent_override" edge to the ChargeUsageBasedOverride entity by ID if the given value is not nil. +func (_u *ChargeUsageBasedUpdateOne) SetNillableIntentOverrideID(id *string) *ChargeUsageBasedUpdateOne { + if id != nil { + _u = _u.SetIntentOverrideID(*id) + } + return _u +} + +// SetIntentOverride sets the "intent_override" edge to the ChargeUsageBasedOverride entity. +func (_u *ChargeUsageBasedUpdateOne) SetIntentOverride(v *ChargeUsageBasedOverride) *ChargeUsageBasedUpdateOne { + return _u.SetIntentOverrideID(v.ID) +} + +// SetSubscriptionItem sets the "subscription_item" edge to the SubscriptionItem entity. +func (_u *ChargeUsageBasedUpdateOne) SetSubscriptionItem(v *SubscriptionItem) *ChargeUsageBasedUpdateOne { + return _u.SetSubscriptionItemID(v.ID) +} + +// SetFeature sets the "feature" edge to the Feature entity. +func (_u *ChargeUsageBasedUpdateOne) SetFeature(v *Feature) *ChargeUsageBasedUpdateOne { + return _u.SetFeatureID(v.ID) +} + +// Mutation returns the ChargeUsageBasedMutation object of the builder. +func (_u *ChargeUsageBasedUpdateOne) Mutation() *ChargeUsageBasedMutation { + return _u.mutation +} + +// 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...) +} + +// ClearDetailedLines clears all "detailed_lines" edges to the ChargeUsageBasedRunDetailedLine entity. +func (_u *ChargeUsageBasedUpdateOne) ClearDetailedLines() *ChargeUsageBasedUpdateOne { + _u.mutation.ClearDetailedLines() + return _u +} + +// RemoveDetailedLineIDs removes the "detailed_lines" edge to ChargeUsageBasedRunDetailedLine entities by IDs. +func (_u *ChargeUsageBasedUpdateOne) RemoveDetailedLineIDs(ids ...string) *ChargeUsageBasedUpdateOne { + _u.mutation.RemoveDetailedLineIDs(ids...) + return _u +} + +// RemoveDetailedLines removes "detailed_lines" edges to ChargeUsageBasedRunDetailedLine entities. +func (_u *ChargeUsageBasedUpdateOne) RemoveDetailedLines(v ...*ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveDetailedLineIDs(ids...) +} + +// ClearCurrentRun clears the "current_run" edge to the ChargeUsageBasedRuns entity. +func (_u *ChargeUsageBasedUpdateOne) ClearCurrentRun() *ChargeUsageBasedUpdateOne { + _u.mutation.ClearCurrentRun() + return _u +} + +// ClearIntentOverride clears the "intent_override" edge to the ChargeUsageBasedOverride entity. +func (_u *ChargeUsageBasedUpdateOne) ClearIntentOverride() *ChargeUsageBasedUpdateOne { + _u.mutation.ClearIntentOverride() + return _u +} + +// ClearSubscriptionItem clears the "subscription_item" edge to the SubscriptionItem entity. +func (_u *ChargeUsageBasedUpdateOne) ClearSubscriptionItem() *ChargeUsageBasedUpdateOne { + _u.mutation.ClearSubscriptionItem() + return _u +} + +// ClearFeature clears the "feature" edge to the Feature entity. +func (_u *ChargeUsageBasedUpdateOne) ClearFeature() *ChargeUsageBasedUpdateOne { + _u.mutation.ClearFeature() + return _u +} + +// 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) { + _u.defaults() + 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) + } +} + +// defaults sets the default values of the builder before save. +func (_u *ChargeUsageBasedUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeusagebased.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeUsageBasedUpdateOne) check() error { + if v, ok := _u.mutation.Status(); ok { + if err := chargeusagebased.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.status": %w`, err)} + } + } + 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 v, ok := _u.mutation.FeatureID(); ok { + if err := chargeusagebased.FeatureIDValidator(v); err != nil { + return &ValidationError{Name: "feature_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.feature_id": %w`, err)} + } + } + if v, ok := _u.mutation.RatingEngine(); ok { + if err := chargeusagebased.RatingEngineValidator(v); err != nil { + return &ValidationError{Name: "rating_engine", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.rating_engine": %w`, err)} + } + } + if v, ok := _u.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 v, ok := _u.mutation.UnitConfig(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "unit_config", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.unit_config": %w`, err)} + } + } + if v, ok := _u.mutation.StatusDetailed(); ok { + if err := chargeusagebased.StatusDetailedValidator(v); err != nil { + return &ValidationError{Name: "status_detailed", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.status_detailed": %w`, err)} + } + } + if _u.mutation.CustomerCleared() && len(_u.mutation.CustomerIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBased.customer"`) + } + if _u.mutation.FeatureCleared() && len(_u.mutation.FeatureIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBased.feature"`) + } + if _u.mutation.TaxCodeCleared() && len(_u.mutation.TaxCodeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBased.tax_code"`) + } + 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.ServicePeriodFrom(); ok { + _spec.SetField(chargeusagebased.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeusagebased.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.BillingPeriodFrom(); ok { + _spec.SetField(chargeusagebased.FieldBillingPeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.BillingPeriodTo(); ok { + _spec.SetField(chargeusagebased.FieldBillingPeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.FullServicePeriodFrom(); ok { + _spec.SetField(chargeusagebased.FieldFullServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.FullServicePeriodTo(); ok { + _spec.SetField(chargeusagebased.FieldFullServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(chargeusagebased.FieldStatus, field.TypeEnum, value) + } + if _u.mutation.UniqueReferenceIDCleared() { + _spec.ClearField(chargeusagebased.FieldUniqueReferenceID, field.TypeString) + } + if value, ok := _u.mutation.AdvanceAfter(); ok { + _spec.SetField(chargeusagebased.FieldAdvanceAfter, field.TypeTime, value) + } + if _u.mutation.AdvanceAfterCleared() { + _spec.ClearField(chargeusagebased.FieldAdvanceAfter, field.TypeTime) + } + if _u.mutation.TaxBehaviorCleared() { + _spec.ClearField(chargeusagebased.FieldTaxBehavior, field.TypeEnum) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargeusagebased.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargeusagebased.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(chargeusagebased.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(chargeusagebased.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeusagebased.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeusagebased.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeusagebased.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(chargeusagebased.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(chargeusagebased.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(chargeusagebased.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.InvoiceAt(); ok { + _spec.SetField(chargeusagebased.FieldInvoiceAt, field.TypeTime, value) + } + if value, ok := _u.mutation.IntentDeletedAt(); ok { + _spec.SetField(chargeusagebased.FieldIntentDeletedAt, field.TypeTime, value) + } + if _u.mutation.IntentDeletedAtCleared() { + _spec.ClearField(chargeusagebased.FieldIntentDeletedAt, field.TypeTime) + } + 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 value, ok := _u.mutation.RatingEngine(); ok { + _spec.SetField(chargeusagebased.FieldRatingEngine, field.TypeEnum, value) + } + if value, ok := _u.mutation.Price(); ok { + vv, err := chargeusagebased.ValueScanner.Price.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(chargeusagebased.FieldPrice, field.TypeString, vv) + } + if value, ok := _u.mutation.UnitConfig(); ok { + vv, err := chargeusagebased.ValueScanner.UnitConfig.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(chargeusagebased.FieldUnitConfig, field.TypeString, vv) + } + if _u.mutation.UnitConfigCleared() { + _spec.ClearField(chargeusagebased.FieldUnitConfig, field.TypeString) + } + if value, ok := _u.mutation.StatusDetailed(); ok { + _spec.SetField(chargeusagebased.FieldStatusDetailed, field.TypeEnum, value) + } + 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 _u.mutation.DetailedLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebased.DetailedLinesTable, + Columns: []string{chargeusagebased.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedDetailedLinesIDs(); len(nodes) > 0 && !_u.mutation.DetailedLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebased.DetailedLinesTable, + Columns: []string{chargeusagebased.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.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.DetailedLinesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebased.DetailedLinesTable, + Columns: []string{chargeusagebased.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.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.CurrentRunCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: chargeusagebased.CurrentRunTable, + Columns: []string{chargeusagebased.CurrentRunColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.CurrentRunIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: chargeusagebased.CurrentRunTable, + Columns: []string{chargeusagebased.CurrentRunColumn}, + 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 _u.mutation.IntentOverrideCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeusagebased.IntentOverrideTable, + Columns: []string{chargeusagebased.IntentOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedoverride.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.IntentOverrideIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeusagebased.IntentOverrideTable, + Columns: []string{chargeusagebased.IntentOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedoverride.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.SubscriptionItemCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebased.SubscriptionItemTable, + Columns: []string{chargeusagebased.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.SubscriptionItemIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebased.SubscriptionItemTable, + Columns: []string{chargeusagebased.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.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.FeatureCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebased.FeatureTable, + Columns: []string{chargeusagebased.FeatureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbfeature.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.FeatureIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebased.FeatureTable, + Columns: []string{chargeusagebased.FeatureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbfeature.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/ent/db/chargeusagebasedoverride.go b/ent/db/chargeusagebasedoverride.go new file mode 100644 index 0000000000000000000000000000000000000000..e84fb934f555f95117a4b66c167eca447ca05469 --- /dev/null +++ b/ent/db/chargeusagebasedoverride.go @@ -0,0 +1,386 @@ +// 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/billing" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedoverride" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeUsageBasedOverride is the model entity for the ChargeUsageBasedOverride schema. +type ChargeUsageBasedOverride 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"` + // ChargeID holds the value of the "charge_id" field. + ChargeID string `json:"charge_id,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Description holds the value of the "description" field. + Description *string `json:"description,omitempty"` + // Metadata holds the value of the "metadata" field. + Metadata *models.Metadata `json:"metadata,omitempty"` + // TaxBehavior holds the value of the "tax_behavior" field. + // + // Deprecated: tax config overrides are not supported; use the base charge intent + TaxBehavior *productcatalog.TaxBehavior `json:"tax_behavior,omitempty"` + // TaxCodeID holds the value of the "tax_code_id" field. + // + // Deprecated: tax config overrides are not supported; use the base charge intent + TaxCodeID *string `json:"tax_code_id,omitempty"` + // IntentDeletedAt holds the value of the "intent_deleted_at" field. + IntentDeletedAt *time.Time `json:"intent_deleted_at,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"` + // FullServicePeriodFrom holds the value of the "full_service_period_from" field. + FullServicePeriodFrom time.Time `json:"full_service_period_from,omitempty"` + // FullServicePeriodTo holds the value of the "full_service_period_to" field. + FullServicePeriodTo time.Time `json:"full_service_period_to,omitempty"` + // BillingPeriodFrom holds the value of the "billing_period_from" field. + BillingPeriodFrom time.Time `json:"billing_period_from,omitempty"` + // BillingPeriodTo holds the value of the "billing_period_to" field. + BillingPeriodTo time.Time `json:"billing_period_to,omitempty"` + // InvoiceAt holds the value of the "invoice_at" field. + InvoiceAt time.Time `json:"invoice_at,omitempty"` + // FeatureKey holds the value of the "feature_key" field. + // + // Deprecated: feature key overrides are not supported; use the base usage-based charge intent + FeatureKey *string `json:"feature_key,omitempty"` + // Price holds the value of the "price" field. + Price *productcatalog.Price `json:"price,omitempty"` + // Discounts holds the value of the "discounts" field. + Discounts *billing.Discounts `json:"discounts,omitempty"` + // UnitConfig holds the value of the "unit_config" field. + UnitConfig *productcatalog.UnitConfig `json:"unit_config,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ChargeUsageBasedOverrideQuery when eager-loading is set. + Edges ChargeUsageBasedOverrideEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ChargeUsageBasedOverrideEdges holds the relations/edges for other nodes in the graph. +type ChargeUsageBasedOverrideEdges struct { + // UsageBased holds the value of the usage_based edge. + UsageBased *ChargeUsageBased `json:"usage_based,omitempty"` + // TaxCode holds the value of the tax_code edge. + TaxCode *TaxCode `json:"tax_code,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]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 ChargeUsageBasedOverrideEdges) 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"} +} + +// TaxCodeOrErr returns the TaxCode value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedOverrideEdges) TaxCodeOrErr() (*TaxCode, error) { + if e.TaxCode != nil { + return e.TaxCode, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: dbtaxcode.Label} + } + return nil, &NotLoadedError{edge: "tax_code"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ChargeUsageBasedOverride) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case chargeusagebasedoverride.FieldID, chargeusagebasedoverride.FieldNamespace, chargeusagebasedoverride.FieldChargeID, chargeusagebasedoverride.FieldName, chargeusagebasedoverride.FieldDescription, chargeusagebasedoverride.FieldTaxBehavior, chargeusagebasedoverride.FieldTaxCodeID, chargeusagebasedoverride.FieldFeatureKey: + values[i] = new(sql.NullString) + case chargeusagebasedoverride.FieldIntentDeletedAt, chargeusagebasedoverride.FieldServicePeriodFrom, chargeusagebasedoverride.FieldServicePeriodTo, chargeusagebasedoverride.FieldFullServicePeriodFrom, chargeusagebasedoverride.FieldFullServicePeriodTo, chargeusagebasedoverride.FieldBillingPeriodFrom, chargeusagebasedoverride.FieldBillingPeriodTo, chargeusagebasedoverride.FieldInvoiceAt: + values[i] = new(sql.NullTime) + case chargeusagebasedoverride.FieldMetadata: + values[i] = chargeusagebasedoverride.ValueScanner.Metadata.ScanValue() + case chargeusagebasedoverride.FieldPrice: + values[i] = chargeusagebasedoverride.ValueScanner.Price.ScanValue() + case chargeusagebasedoverride.FieldDiscounts: + values[i] = chargeusagebasedoverride.ValueScanner.Discounts.ScanValue() + case chargeusagebasedoverride.FieldUnitConfig: + values[i] = chargeusagebasedoverride.ValueScanner.UnitConfig.ScanValue() + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the ChargeUsageBasedOverride fields. +func (_m *ChargeUsageBasedOverride) 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 chargeusagebasedoverride.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 chargeusagebasedoverride.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 chargeusagebasedoverride.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 chargeusagebasedoverride.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case chargeusagebasedoverride.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + _m.Description = new(string) + *_m.Description = value.String + } + case chargeusagebasedoverride.FieldMetadata: + if value, err := chargeusagebasedoverride.ValueScanner.Metadata.FromValue(values[i]); err != nil { + return err + } else { + _m.Metadata = value + } + case chargeusagebasedoverride.FieldTaxBehavior: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field tax_behavior", values[i]) + } else if value.Valid { + _m.TaxBehavior = new(productcatalog.TaxBehavior) + *_m.TaxBehavior = productcatalog.TaxBehavior(value.String) + } + case chargeusagebasedoverride.FieldTaxCodeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field tax_code_id", values[i]) + } else if value.Valid { + _m.TaxCodeID = new(string) + *_m.TaxCodeID = value.String + } + case chargeusagebasedoverride.FieldIntentDeletedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field intent_deleted_at", values[i]) + } else if value.Valid { + _m.IntentDeletedAt = new(time.Time) + *_m.IntentDeletedAt = value.Time + } + case chargeusagebasedoverride.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 chargeusagebasedoverride.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 chargeusagebasedoverride.FieldFullServicePeriodFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field full_service_period_from", values[i]) + } else if value.Valid { + _m.FullServicePeriodFrom = value.Time + } + case chargeusagebasedoverride.FieldFullServicePeriodTo: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field full_service_period_to", values[i]) + } else if value.Valid { + _m.FullServicePeriodTo = value.Time + } + case chargeusagebasedoverride.FieldBillingPeriodFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field billing_period_from", values[i]) + } else if value.Valid { + _m.BillingPeriodFrom = value.Time + } + case chargeusagebasedoverride.FieldBillingPeriodTo: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field billing_period_to", values[i]) + } else if value.Valid { + _m.BillingPeriodTo = value.Time + } + case chargeusagebasedoverride.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 chargeusagebasedoverride.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 = new(string) + *_m.FeatureKey = value.String + } + case chargeusagebasedoverride.FieldPrice: + if value, err := chargeusagebasedoverride.ValueScanner.Price.FromValue(values[i]); err != nil { + return err + } else { + _m.Price = value + } + case chargeusagebasedoverride.FieldDiscounts: + if value, err := chargeusagebasedoverride.ValueScanner.Discounts.FromValue(values[i]); err != nil { + return err + } else { + _m.Discounts = value + } + case chargeusagebasedoverride.FieldUnitConfig: + if value, err := chargeusagebasedoverride.ValueScanner.UnitConfig.FromValue(values[i]); err != nil { + return err + } else { + _m.UnitConfig = value + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the ChargeUsageBasedOverride. +// This includes values selected through modifiers, order, etc. +func (_m *ChargeUsageBasedOverride) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryUsageBased queries the "usage_based" edge of the ChargeUsageBasedOverride entity. +func (_m *ChargeUsageBasedOverride) QueryUsageBased() *ChargeUsageBasedQuery { + return NewChargeUsageBasedOverrideClient(_m.config).QueryUsageBased(_m) +} + +// QueryTaxCode queries the "tax_code" edge of the ChargeUsageBasedOverride entity. +func (_m *ChargeUsageBasedOverride) QueryTaxCode() *TaxCodeQuery { + return NewChargeUsageBasedOverrideClient(_m.config).QueryTaxCode(_m) +} + +// Update returns a builder for updating this ChargeUsageBasedOverride. +// Note that you need to call ChargeUsageBasedOverride.Unwrap() before calling this method if this ChargeUsageBasedOverride +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ChargeUsageBasedOverride) Update() *ChargeUsageBasedOverrideUpdateOne { + return NewChargeUsageBasedOverrideClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ChargeUsageBasedOverride 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 *ChargeUsageBasedOverride) Unwrap() *ChargeUsageBasedOverride { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: ChargeUsageBasedOverride is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ChargeUsageBasedOverride) String() string { + var builder strings.Builder + builder.WriteString("ChargeUsageBasedOverride(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("charge_id=") + builder.WriteString(_m.ChargeID) + builder.WriteString(", ") + builder.WriteString("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + if v := _m.Description; v != nil { + builder.WriteString("description=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.Metadata; v != nil { + builder.WriteString("metadata=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.TaxBehavior; v != nil { + builder.WriteString("tax_behavior=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.TaxCodeID; v != nil { + builder.WriteString("tax_code_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.IntentDeletedAt; v != nil { + builder.WriteString("intent_deleted_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + 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("full_service_period_from=") + builder.WriteString(_m.FullServicePeriodFrom.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("full_service_period_to=") + builder.WriteString(_m.FullServicePeriodTo.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("billing_period_from=") + builder.WriteString(_m.BillingPeriodFrom.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("billing_period_to=") + builder.WriteString(_m.BillingPeriodTo.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("invoice_at=") + builder.WriteString(_m.InvoiceAt.Format(time.ANSIC)) + builder.WriteString(", ") + if v := _m.FeatureKey; v != nil { + builder.WriteString("feature_key=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("price=") + builder.WriteString(fmt.Sprintf("%v", _m.Price)) + builder.WriteString(", ") + builder.WriteString("discounts=") + builder.WriteString(fmt.Sprintf("%v", _m.Discounts)) + builder.WriteString(", ") + if v := _m.UnitConfig; v != nil { + builder.WriteString("unit_config=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteByte(')') + return builder.String() +} + +// ChargeUsageBasedOverrides is a parsable slice of ChargeUsageBasedOverride. +type ChargeUsageBasedOverrides []*ChargeUsageBasedOverride diff --git a/ent/db/chargeusagebasedoverride/chargeusagebasedoverride.go b/ent/db/chargeusagebasedoverride/chargeusagebasedoverride.go new file mode 100644 index 0000000000000000000000000000000000000000..ac1231528a51dd7febf2df889176e56c64a76749 --- /dev/null +++ b/ent/db/chargeusagebasedoverride/chargeusagebasedoverride.go @@ -0,0 +1,262 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeusagebasedoverride + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/models" +) + +const ( + // Label holds the string label denoting the chargeusagebasedoverride type in the database. + Label = "charge_usage_based_override" + // 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" + // FieldChargeID holds the string denoting the charge_id field in the database. + FieldChargeID = "charge_id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // FieldTaxBehavior holds the string denoting the tax_behavior field in the database. + FieldTaxBehavior = "tax_behavior" + // FieldTaxCodeID holds the string denoting the tax_code_id field in the database. + FieldTaxCodeID = "tax_code_id" + // FieldIntentDeletedAt holds the string denoting the intent_deleted_at field in the database. + FieldIntentDeletedAt = "intent_deleted_at" + // 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" + // FieldFullServicePeriodFrom holds the string denoting the full_service_period_from field in the database. + FieldFullServicePeriodFrom = "full_service_period_from" + // FieldFullServicePeriodTo holds the string denoting the full_service_period_to field in the database. + FieldFullServicePeriodTo = "full_service_period_to" + // FieldBillingPeriodFrom holds the string denoting the billing_period_from field in the database. + FieldBillingPeriodFrom = "billing_period_from" + // FieldBillingPeriodTo holds the string denoting the billing_period_to field in the database. + FieldBillingPeriodTo = "billing_period_to" + // FieldInvoiceAt holds the string denoting the invoice_at field in the database. + FieldInvoiceAt = "invoice_at" + // 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" + // FieldDiscounts holds the string denoting the discounts field in the database. + FieldDiscounts = "discounts" + // FieldUnitConfig holds the string denoting the unit_config field in the database. + FieldUnitConfig = "unit_config" + // EdgeUsageBased holds the string denoting the usage_based edge name in mutations. + EdgeUsageBased = "usage_based" + // EdgeTaxCode holds the string denoting the tax_code edge name in mutations. + EdgeTaxCode = "tax_code" + // Table holds the table name of the chargeusagebasedoverride in the database. + Table = "charge_usage_based_overrides" + // UsageBasedTable is the table that holds the usage_based relation/edge. + UsageBasedTable = "charge_usage_based_overrides" + // 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" + // TaxCodeTable is the table that holds the tax_code relation/edge. + TaxCodeTable = "charge_usage_based_overrides" + // TaxCodeInverseTable is the table name for the TaxCode entity. + // It exists in this package in order to avoid circular dependency with the "dbtaxcode" package. + TaxCodeInverseTable = "tax_codes" + // TaxCodeColumn is the table column denoting the tax_code relation/edge. + TaxCodeColumn = "tax_code_id" +) + +// Columns holds all SQL columns for chargeusagebasedoverride fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldChargeID, + FieldName, + FieldDescription, + FieldMetadata, + FieldIntentDeletedAt, + FieldServicePeriodFrom, + FieldServicePeriodTo, + FieldFullServicePeriodFrom, + FieldFullServicePeriodTo, + FieldBillingPeriodFrom, + FieldBillingPeriodTo, + FieldInvoiceAt, + FieldPrice, + FieldDiscounts, + FieldUnitConfig, +} + +// 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 + } + } + for _, f := range [...]string{FieldTaxBehavior, FieldTaxCodeID, FieldFeatureKey} { + if column == f { + 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 + // NameValidator is a validator for the "name" field. It is called by the builders before save. + NameValidator 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 ChargeUsageBasedOverride fields. + ValueScanner struct { + Metadata field.TypeValueScanner[*models.Metadata] + Price field.TypeValueScanner[*productcatalog.Price] + Discounts field.TypeValueScanner[*billing.Discounts] + UnitConfig field.TypeValueScanner[*productcatalog.UnitConfig] + } +) + +// OrderOption defines the ordering options for the ChargeUsageBasedOverride 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() +} + +// ByChargeID orders the results by the charge_id field. +func ByChargeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChargeID, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, opts...).ToFunc() +} + +// ByMetadata orders the results by the metadata field. +func ByMetadata(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMetadata, opts...).ToFunc() +} + +// ByTaxBehavior orders the results by the tax_behavior field. +func ByTaxBehavior(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxBehavior, opts...).ToFunc() +} + +// ByTaxCodeID orders the results by the tax_code_id field. +func ByTaxCodeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxCodeID, opts...).ToFunc() +} + +// ByIntentDeletedAt orders the results by the intent_deleted_at field. +func ByIntentDeletedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIntentDeletedAt, 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() +} + +// ByFullServicePeriodFrom orders the results by the full_service_period_from field. +func ByFullServicePeriodFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFullServicePeriodFrom, opts...).ToFunc() +} + +// ByFullServicePeriodTo orders the results by the full_service_period_to field. +func ByFullServicePeriodTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFullServicePeriodTo, opts...).ToFunc() +} + +// ByBillingPeriodFrom orders the results by the billing_period_from field. +func ByBillingPeriodFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBillingPeriodFrom, opts...).ToFunc() +} + +// ByBillingPeriodTo orders the results by the billing_period_to field. +func ByBillingPeriodTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBillingPeriodTo, opts...).ToFunc() +} + +// ByInvoiceAt orders the results by the invoice_at field. +func ByInvoiceAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoiceAt, 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() +} + +// ByDiscounts orders the results by the discounts field. +func ByDiscounts(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDiscounts, opts...).ToFunc() +} + +// ByUnitConfig orders the results by the unit_config field. +func ByUnitConfig(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUnitConfig, 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...)) + } +} + +// ByTaxCodeField orders the results by tax_code field. +func ByTaxCodeField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTaxCodeStep(), sql.OrderByField(field, opts...)) + } +} +func newUsageBasedStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UsageBasedInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, UsageBasedTable, UsageBasedColumn), + ) +} +func newTaxCodeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TaxCodeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, TaxCodeTable, TaxCodeColumn), + ) +} diff --git a/ent/db/chargeusagebasedoverride/where.go b/ent/db/chargeusagebasedoverride/where.go new file mode 100644 index 0000000000000000000000000000000000000000..8b7bc7d0be2d9a03da4a35acaf8a658089f1a385 --- /dev/null +++ b/ent/db/chargeusagebasedoverride/where.go @@ -0,0 +1,1068 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeusagebasedoverride + +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.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldNamespace, v)) +} + +// ChargeID applies equality check predicate on the "charge_id" field. It's identical to ChargeIDEQ. +func ChargeID(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldChargeID, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldName, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldDescription, v)) +} + +// TaxBehavior applies equality check predicate on the "tax_behavior" field. It's identical to TaxBehaviorEQ. +func TaxBehavior(v productcatalog.TaxBehavior) predicate.ChargeUsageBasedOverride { + vc := string(v) + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldTaxBehavior, vc)) +} + +// TaxCodeID applies equality check predicate on the "tax_code_id" field. It's identical to TaxCodeIDEQ. +func TaxCodeID(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldTaxCodeID, v)) +} + +// IntentDeletedAt applies equality check predicate on the "intent_deleted_at" field. It's identical to IntentDeletedAtEQ. +func IntentDeletedAt(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldIntentDeletedAt, v)) +} + +// ServicePeriodFrom applies equality check predicate on the "service_period_from" field. It's identical to ServicePeriodFromEQ. +func ServicePeriodFrom(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(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.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// FullServicePeriodFrom applies equality check predicate on the "full_service_period_from" field. It's identical to FullServicePeriodFromEQ. +func FullServicePeriodFrom(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodTo applies equality check predicate on the "full_service_period_to" field. It's identical to FullServicePeriodToEQ. +func FullServicePeriodTo(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldFullServicePeriodTo, v)) +} + +// BillingPeriodFrom applies equality check predicate on the "billing_period_from" field. It's identical to BillingPeriodFromEQ. +func BillingPeriodFrom(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodTo applies equality check predicate on the "billing_period_to" field. It's identical to BillingPeriodToEQ. +func BillingPeriodTo(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldBillingPeriodTo, v)) +} + +// InvoiceAt applies equality check predicate on the "invoice_at" field. It's identical to InvoiceAtEQ. +func InvoiceAt(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldInvoiceAt, v)) +} + +// FeatureKey applies equality check predicate on the "feature_key" field. It's identical to FeatureKeyEQ. +func FeatureKey(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldFeatureKey, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldContainsFold(FieldNamespace, v)) +} + +// ChargeIDEQ applies the EQ predicate on the "charge_id" field. +func ChargeIDEQ(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldChargeID, v)) +} + +// ChargeIDNEQ applies the NEQ predicate on the "charge_id" field. +func ChargeIDNEQ(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNEQ(FieldChargeID, v)) +} + +// ChargeIDIn applies the In predicate on the "charge_id" field. +func ChargeIDIn(vs ...string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIn(FieldChargeID, vs...)) +} + +// ChargeIDNotIn applies the NotIn predicate on the "charge_id" field. +func ChargeIDNotIn(vs ...string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotIn(FieldChargeID, vs...)) +} + +// ChargeIDGT applies the GT predicate on the "charge_id" field. +func ChargeIDGT(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGT(FieldChargeID, v)) +} + +// ChargeIDGTE applies the GTE predicate on the "charge_id" field. +func ChargeIDGTE(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGTE(FieldChargeID, v)) +} + +// ChargeIDLT applies the LT predicate on the "charge_id" field. +func ChargeIDLT(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLT(FieldChargeID, v)) +} + +// ChargeIDLTE applies the LTE predicate on the "charge_id" field. +func ChargeIDLTE(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLTE(FieldChargeID, v)) +} + +// ChargeIDContains applies the Contains predicate on the "charge_id" field. +func ChargeIDContains(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldContains(FieldChargeID, v)) +} + +// ChargeIDHasPrefix applies the HasPrefix predicate on the "charge_id" field. +func ChargeIDHasPrefix(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldHasPrefix(FieldChargeID, v)) +} + +// ChargeIDHasSuffix applies the HasSuffix predicate on the "charge_id" field. +func ChargeIDHasSuffix(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldHasSuffix(FieldChargeID, v)) +} + +// ChargeIDEqualFold applies the EqualFold predicate on the "charge_id" field. +func ChargeIDEqualFold(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEqualFold(FieldChargeID, v)) +} + +// ChargeIDContainsFold applies the ContainsFold predicate on the "charge_id" field. +func ChargeIDContainsFold(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldContainsFold(FieldChargeID, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldContainsFold(FieldName, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldContainsFold(FieldDescription, v)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotNull(FieldMetadata)) +} + +// TaxBehaviorEQ applies the EQ predicate on the "tax_behavior" field. +func TaxBehaviorEQ(v productcatalog.TaxBehavior) predicate.ChargeUsageBasedOverride { + vc := string(v) + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldTaxBehavior, vc)) +} + +// TaxBehaviorNEQ applies the NEQ predicate on the "tax_behavior" field. +func TaxBehaviorNEQ(v productcatalog.TaxBehavior) predicate.ChargeUsageBasedOverride { + vc := string(v) + return predicate.ChargeUsageBasedOverride(sql.FieldNEQ(FieldTaxBehavior, vc)) +} + +// TaxBehaviorIn applies the In predicate on the "tax_behavior" field. +func TaxBehaviorIn(vs ...productcatalog.TaxBehavior) predicate.ChargeUsageBasedOverride { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargeUsageBasedOverride(sql.FieldIn(FieldTaxBehavior, v...)) +} + +// TaxBehaviorNotIn applies the NotIn predicate on the "tax_behavior" field. +func TaxBehaviorNotIn(vs ...productcatalog.TaxBehavior) predicate.ChargeUsageBasedOverride { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargeUsageBasedOverride(sql.FieldNotIn(FieldTaxBehavior, v...)) +} + +// TaxBehaviorGT applies the GT predicate on the "tax_behavior" field. +func TaxBehaviorGT(v productcatalog.TaxBehavior) predicate.ChargeUsageBasedOverride { + vc := string(v) + return predicate.ChargeUsageBasedOverride(sql.FieldGT(FieldTaxBehavior, vc)) +} + +// TaxBehaviorGTE applies the GTE predicate on the "tax_behavior" field. +func TaxBehaviorGTE(v productcatalog.TaxBehavior) predicate.ChargeUsageBasedOverride { + vc := string(v) + return predicate.ChargeUsageBasedOverride(sql.FieldGTE(FieldTaxBehavior, vc)) +} + +// TaxBehaviorLT applies the LT predicate on the "tax_behavior" field. +func TaxBehaviorLT(v productcatalog.TaxBehavior) predicate.ChargeUsageBasedOverride { + vc := string(v) + return predicate.ChargeUsageBasedOverride(sql.FieldLT(FieldTaxBehavior, vc)) +} + +// TaxBehaviorLTE applies the LTE predicate on the "tax_behavior" field. +func TaxBehaviorLTE(v productcatalog.TaxBehavior) predicate.ChargeUsageBasedOverride { + vc := string(v) + return predicate.ChargeUsageBasedOverride(sql.FieldLTE(FieldTaxBehavior, vc)) +} + +// TaxBehaviorContains applies the Contains predicate on the "tax_behavior" field. +func TaxBehaviorContains(v productcatalog.TaxBehavior) predicate.ChargeUsageBasedOverride { + vc := string(v) + return predicate.ChargeUsageBasedOverride(sql.FieldContains(FieldTaxBehavior, vc)) +} + +// TaxBehaviorHasPrefix applies the HasPrefix predicate on the "tax_behavior" field. +func TaxBehaviorHasPrefix(v productcatalog.TaxBehavior) predicate.ChargeUsageBasedOverride { + vc := string(v) + return predicate.ChargeUsageBasedOverride(sql.FieldHasPrefix(FieldTaxBehavior, vc)) +} + +// TaxBehaviorHasSuffix applies the HasSuffix predicate on the "tax_behavior" field. +func TaxBehaviorHasSuffix(v productcatalog.TaxBehavior) predicate.ChargeUsageBasedOverride { + vc := string(v) + return predicate.ChargeUsageBasedOverride(sql.FieldHasSuffix(FieldTaxBehavior, vc)) +} + +// TaxBehaviorIsNil applies the IsNil predicate on the "tax_behavior" field. +func TaxBehaviorIsNil() predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIsNull(FieldTaxBehavior)) +} + +// TaxBehaviorNotNil applies the NotNil predicate on the "tax_behavior" field. +func TaxBehaviorNotNil() predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotNull(FieldTaxBehavior)) +} + +// TaxBehaviorEqualFold applies the EqualFold predicate on the "tax_behavior" field. +func TaxBehaviorEqualFold(v productcatalog.TaxBehavior) predicate.ChargeUsageBasedOverride { + vc := string(v) + return predicate.ChargeUsageBasedOverride(sql.FieldEqualFold(FieldTaxBehavior, vc)) +} + +// TaxBehaviorContainsFold applies the ContainsFold predicate on the "tax_behavior" field. +func TaxBehaviorContainsFold(v productcatalog.TaxBehavior) predicate.ChargeUsageBasedOverride { + vc := string(v) + return predicate.ChargeUsageBasedOverride(sql.FieldContainsFold(FieldTaxBehavior, vc)) +} + +// TaxCodeIDEQ applies the EQ predicate on the "tax_code_id" field. +func TaxCodeIDEQ(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldTaxCodeID, v)) +} + +// TaxCodeIDNEQ applies the NEQ predicate on the "tax_code_id" field. +func TaxCodeIDNEQ(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNEQ(FieldTaxCodeID, v)) +} + +// TaxCodeIDIn applies the In predicate on the "tax_code_id" field. +func TaxCodeIDIn(vs ...string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIn(FieldTaxCodeID, vs...)) +} + +// TaxCodeIDNotIn applies the NotIn predicate on the "tax_code_id" field. +func TaxCodeIDNotIn(vs ...string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotIn(FieldTaxCodeID, vs...)) +} + +// TaxCodeIDGT applies the GT predicate on the "tax_code_id" field. +func TaxCodeIDGT(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGT(FieldTaxCodeID, v)) +} + +// TaxCodeIDGTE applies the GTE predicate on the "tax_code_id" field. +func TaxCodeIDGTE(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGTE(FieldTaxCodeID, v)) +} + +// TaxCodeIDLT applies the LT predicate on the "tax_code_id" field. +func TaxCodeIDLT(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLT(FieldTaxCodeID, v)) +} + +// TaxCodeIDLTE applies the LTE predicate on the "tax_code_id" field. +func TaxCodeIDLTE(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLTE(FieldTaxCodeID, v)) +} + +// TaxCodeIDContains applies the Contains predicate on the "tax_code_id" field. +func TaxCodeIDContains(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldContains(FieldTaxCodeID, v)) +} + +// TaxCodeIDHasPrefix applies the HasPrefix predicate on the "tax_code_id" field. +func TaxCodeIDHasPrefix(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldHasPrefix(FieldTaxCodeID, v)) +} + +// TaxCodeIDHasSuffix applies the HasSuffix predicate on the "tax_code_id" field. +func TaxCodeIDHasSuffix(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldHasSuffix(FieldTaxCodeID, v)) +} + +// TaxCodeIDIsNil applies the IsNil predicate on the "tax_code_id" field. +func TaxCodeIDIsNil() predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIsNull(FieldTaxCodeID)) +} + +// TaxCodeIDNotNil applies the NotNil predicate on the "tax_code_id" field. +func TaxCodeIDNotNil() predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotNull(FieldTaxCodeID)) +} + +// TaxCodeIDEqualFold applies the EqualFold predicate on the "tax_code_id" field. +func TaxCodeIDEqualFold(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEqualFold(FieldTaxCodeID, v)) +} + +// TaxCodeIDContainsFold applies the ContainsFold predicate on the "tax_code_id" field. +func TaxCodeIDContainsFold(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldContainsFold(FieldTaxCodeID, v)) +} + +// IntentDeletedAtEQ applies the EQ predicate on the "intent_deleted_at" field. +func IntentDeletedAtEQ(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtNEQ applies the NEQ predicate on the "intent_deleted_at" field. +func IntentDeletedAtNEQ(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNEQ(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtIn applies the In predicate on the "intent_deleted_at" field. +func IntentDeletedAtIn(vs ...time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIn(FieldIntentDeletedAt, vs...)) +} + +// IntentDeletedAtNotIn applies the NotIn predicate on the "intent_deleted_at" field. +func IntentDeletedAtNotIn(vs ...time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotIn(FieldIntentDeletedAt, vs...)) +} + +// IntentDeletedAtGT applies the GT predicate on the "intent_deleted_at" field. +func IntentDeletedAtGT(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGT(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtGTE applies the GTE predicate on the "intent_deleted_at" field. +func IntentDeletedAtGTE(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGTE(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtLT applies the LT predicate on the "intent_deleted_at" field. +func IntentDeletedAtLT(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLT(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtLTE applies the LTE predicate on the "intent_deleted_at" field. +func IntentDeletedAtLTE(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLTE(FieldIntentDeletedAt, v)) +} + +// IntentDeletedAtIsNil applies the IsNil predicate on the "intent_deleted_at" field. +func IntentDeletedAtIsNil() predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIsNull(FieldIntentDeletedAt)) +} + +// IntentDeletedAtNotNil applies the NotNil predicate on the "intent_deleted_at" field. +func IntentDeletedAtNotNil() predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotNull(FieldIntentDeletedAt)) +} + +// ServicePeriodFromEQ applies the EQ predicate on the "service_period_from" field. +func ServicePeriodFromEQ(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromNEQ applies the NEQ predicate on the "service_period_from" field. +func ServicePeriodFromNEQ(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromIn applies the In predicate on the "service_period_from" field. +func ServicePeriodFromIn(vs ...time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromNotIn applies the NotIn predicate on the "service_period_from" field. +func ServicePeriodFromNotIn(vs ...time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromGT applies the GT predicate on the "service_period_from" field. +func ServicePeriodFromGT(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromGTE applies the GTE predicate on the "service_period_from" field. +func ServicePeriodFromGTE(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLT applies the LT predicate on the "service_period_from" field. +func ServicePeriodFromLT(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLTE applies the LTE predicate on the "service_period_from" field. +func ServicePeriodFromLTE(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodToEQ applies the EQ predicate on the "service_period_to" field. +func ServicePeriodToEQ(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToNEQ applies the NEQ predicate on the "service_period_to" field. +func ServicePeriodToNEQ(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToIn applies the In predicate on the "service_period_to" field. +func ServicePeriodToIn(vs ...time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToNotIn applies the NotIn predicate on the "service_period_to" field. +func ServicePeriodToNotIn(vs ...time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToGT applies the GT predicate on the "service_period_to" field. +func ServicePeriodToGT(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToGTE applies the GTE predicate on the "service_period_to" field. +func ServicePeriodToGTE(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGTE(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLT applies the LT predicate on the "service_period_to" field. +func ServicePeriodToLT(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLTE applies the LTE predicate on the "service_period_to" field. +func ServicePeriodToLTE(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLTE(FieldServicePeriodTo, v)) +} + +// FullServicePeriodFromEQ applies the EQ predicate on the "full_service_period_from" field. +func FullServicePeriodFromEQ(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromNEQ applies the NEQ predicate on the "full_service_period_from" field. +func FullServicePeriodFromNEQ(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNEQ(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromIn applies the In predicate on the "full_service_period_from" field. +func FullServicePeriodFromIn(vs ...time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIn(FieldFullServicePeriodFrom, vs...)) +} + +// FullServicePeriodFromNotIn applies the NotIn predicate on the "full_service_period_from" field. +func FullServicePeriodFromNotIn(vs ...time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotIn(FieldFullServicePeriodFrom, vs...)) +} + +// FullServicePeriodFromGT applies the GT predicate on the "full_service_period_from" field. +func FullServicePeriodFromGT(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGT(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromGTE applies the GTE predicate on the "full_service_period_from" field. +func FullServicePeriodFromGTE(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGTE(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromLT applies the LT predicate on the "full_service_period_from" field. +func FullServicePeriodFromLT(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLT(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodFromLTE applies the LTE predicate on the "full_service_period_from" field. +func FullServicePeriodFromLTE(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLTE(FieldFullServicePeriodFrom, v)) +} + +// FullServicePeriodToEQ applies the EQ predicate on the "full_service_period_to" field. +func FullServicePeriodToEQ(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToNEQ applies the NEQ predicate on the "full_service_period_to" field. +func FullServicePeriodToNEQ(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNEQ(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToIn applies the In predicate on the "full_service_period_to" field. +func FullServicePeriodToIn(vs ...time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIn(FieldFullServicePeriodTo, vs...)) +} + +// FullServicePeriodToNotIn applies the NotIn predicate on the "full_service_period_to" field. +func FullServicePeriodToNotIn(vs ...time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotIn(FieldFullServicePeriodTo, vs...)) +} + +// FullServicePeriodToGT applies the GT predicate on the "full_service_period_to" field. +func FullServicePeriodToGT(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGT(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToGTE applies the GTE predicate on the "full_service_period_to" field. +func FullServicePeriodToGTE(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGTE(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToLT applies the LT predicate on the "full_service_period_to" field. +func FullServicePeriodToLT(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLT(FieldFullServicePeriodTo, v)) +} + +// FullServicePeriodToLTE applies the LTE predicate on the "full_service_period_to" field. +func FullServicePeriodToLTE(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLTE(FieldFullServicePeriodTo, v)) +} + +// BillingPeriodFromEQ applies the EQ predicate on the "billing_period_from" field. +func BillingPeriodFromEQ(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromNEQ applies the NEQ predicate on the "billing_period_from" field. +func BillingPeriodFromNEQ(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNEQ(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromIn applies the In predicate on the "billing_period_from" field. +func BillingPeriodFromIn(vs ...time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIn(FieldBillingPeriodFrom, vs...)) +} + +// BillingPeriodFromNotIn applies the NotIn predicate on the "billing_period_from" field. +func BillingPeriodFromNotIn(vs ...time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotIn(FieldBillingPeriodFrom, vs...)) +} + +// BillingPeriodFromGT applies the GT predicate on the "billing_period_from" field. +func BillingPeriodFromGT(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGT(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromGTE applies the GTE predicate on the "billing_period_from" field. +func BillingPeriodFromGTE(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGTE(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromLT applies the LT predicate on the "billing_period_from" field. +func BillingPeriodFromLT(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLT(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodFromLTE applies the LTE predicate on the "billing_period_from" field. +func BillingPeriodFromLTE(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLTE(FieldBillingPeriodFrom, v)) +} + +// BillingPeriodToEQ applies the EQ predicate on the "billing_period_to" field. +func BillingPeriodToEQ(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToNEQ applies the NEQ predicate on the "billing_period_to" field. +func BillingPeriodToNEQ(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNEQ(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToIn applies the In predicate on the "billing_period_to" field. +func BillingPeriodToIn(vs ...time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIn(FieldBillingPeriodTo, vs...)) +} + +// BillingPeriodToNotIn applies the NotIn predicate on the "billing_period_to" field. +func BillingPeriodToNotIn(vs ...time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotIn(FieldBillingPeriodTo, vs...)) +} + +// BillingPeriodToGT applies the GT predicate on the "billing_period_to" field. +func BillingPeriodToGT(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGT(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToGTE applies the GTE predicate on the "billing_period_to" field. +func BillingPeriodToGTE(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGTE(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToLT applies the LT predicate on the "billing_period_to" field. +func BillingPeriodToLT(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLT(FieldBillingPeriodTo, v)) +} + +// BillingPeriodToLTE applies the LTE predicate on the "billing_period_to" field. +func BillingPeriodToLTE(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLTE(FieldBillingPeriodTo, v)) +} + +// InvoiceAtEQ applies the EQ predicate on the "invoice_at" field. +func InvoiceAtEQ(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldInvoiceAt, v)) +} + +// InvoiceAtNEQ applies the NEQ predicate on the "invoice_at" field. +func InvoiceAtNEQ(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNEQ(FieldInvoiceAt, v)) +} + +// InvoiceAtIn applies the In predicate on the "invoice_at" field. +func InvoiceAtIn(vs ...time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIn(FieldInvoiceAt, vs...)) +} + +// InvoiceAtNotIn applies the NotIn predicate on the "invoice_at" field. +func InvoiceAtNotIn(vs ...time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotIn(FieldInvoiceAt, vs...)) +} + +// InvoiceAtGT applies the GT predicate on the "invoice_at" field. +func InvoiceAtGT(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGT(FieldInvoiceAt, v)) +} + +// InvoiceAtGTE applies the GTE predicate on the "invoice_at" field. +func InvoiceAtGTE(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGTE(FieldInvoiceAt, v)) +} + +// InvoiceAtLT applies the LT predicate on the "invoice_at" field. +func InvoiceAtLT(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLT(FieldInvoiceAt, v)) +} + +// InvoiceAtLTE applies the LTE predicate on the "invoice_at" field. +func InvoiceAtLTE(v time.Time) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLTE(FieldInvoiceAt, v)) +} + +// FeatureKeyEQ applies the EQ predicate on the "feature_key" field. +func FeatureKeyEQ(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEQ(FieldFeatureKey, v)) +} + +// FeatureKeyNEQ applies the NEQ predicate on the "feature_key" field. +func FeatureKeyNEQ(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNEQ(FieldFeatureKey, v)) +} + +// FeatureKeyIn applies the In predicate on the "feature_key" field. +func FeatureKeyIn(vs ...string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIn(FieldFeatureKey, vs...)) +} + +// FeatureKeyNotIn applies the NotIn predicate on the "feature_key" field. +func FeatureKeyNotIn(vs ...string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotIn(FieldFeatureKey, vs...)) +} + +// FeatureKeyGT applies the GT predicate on the "feature_key" field. +func FeatureKeyGT(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGT(FieldFeatureKey, v)) +} + +// FeatureKeyGTE applies the GTE predicate on the "feature_key" field. +func FeatureKeyGTE(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldGTE(FieldFeatureKey, v)) +} + +// FeatureKeyLT applies the LT predicate on the "feature_key" field. +func FeatureKeyLT(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLT(FieldFeatureKey, v)) +} + +// FeatureKeyLTE applies the LTE predicate on the "feature_key" field. +func FeatureKeyLTE(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldLTE(FieldFeatureKey, v)) +} + +// FeatureKeyContains applies the Contains predicate on the "feature_key" field. +func FeatureKeyContains(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldContains(FieldFeatureKey, v)) +} + +// FeatureKeyHasPrefix applies the HasPrefix predicate on the "feature_key" field. +func FeatureKeyHasPrefix(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldHasPrefix(FieldFeatureKey, v)) +} + +// FeatureKeyHasSuffix applies the HasSuffix predicate on the "feature_key" field. +func FeatureKeyHasSuffix(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldHasSuffix(FieldFeatureKey, v)) +} + +// FeatureKeyIsNil applies the IsNil predicate on the "feature_key" field. +func FeatureKeyIsNil() predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIsNull(FieldFeatureKey)) +} + +// FeatureKeyNotNil applies the NotNil predicate on the "feature_key" field. +func FeatureKeyNotNil() predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotNull(FieldFeatureKey)) +} + +// FeatureKeyEqualFold applies the EqualFold predicate on the "feature_key" field. +func FeatureKeyEqualFold(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldEqualFold(FieldFeatureKey, v)) +} + +// FeatureKeyContainsFold applies the ContainsFold predicate on the "feature_key" field. +func FeatureKeyContainsFold(v string) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldContainsFold(FieldFeatureKey, v)) +} + +// UnitConfigIsNil applies the IsNil predicate on the "unit_config" field. +func UnitConfigIsNil() predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldIsNull(FieldUnitConfig)) +} + +// UnitConfigNotNil applies the NotNil predicate on the "unit_config" field. +func UnitConfigNotNil() predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.FieldNotNull(FieldUnitConfig)) +} + +// HasUsageBased applies the HasEdge predicate on the "usage_based" edge. +func HasUsageBased() predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, 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.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(func(s *sql.Selector) { + step := newUsageBasedStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasTaxCode applies the HasEdge predicate on the "tax_code" edge. +func HasTaxCode() predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, TaxCodeTable, TaxCodeColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTaxCodeWith applies the HasEdge predicate on the "tax_code" edge with a given conditions (other predicates). +func HasTaxCodeWith(preds ...predicate.TaxCode) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(func(s *sql.Selector) { + step := newTaxCodeStep() + 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.ChargeUsageBasedOverride) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ChargeUsageBasedOverride) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ChargeUsageBasedOverride) predicate.ChargeUsageBasedOverride { + return predicate.ChargeUsageBasedOverride(sql.NotPredicates(p)) +} diff --git a/ent/db/chargeusagebasedoverride_create.go b/ent/db/chargeusagebasedoverride_create.go new file mode 100644 index 0000000000000000000000000000000000000000..87a06828ab4d94f568e4bc540c160959565d25b8 --- /dev/null +++ b/ent/db/chargeusagebasedoverride_create.go @@ -0,0 +1,1660 @@ +// 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/billing" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedoverride" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeUsageBasedOverrideCreate is the builder for creating a ChargeUsageBasedOverride entity. +type ChargeUsageBasedOverrideCreate struct { + config + mutation *ChargeUsageBasedOverrideMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *ChargeUsageBasedOverrideCreate) SetNamespace(v string) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetChargeID sets the "charge_id" field. +func (_c *ChargeUsageBasedOverrideCreate) SetChargeID(v string) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetChargeID(v) + return _c +} + +// SetName sets the "name" field. +func (_c *ChargeUsageBasedOverrideCreate) SetName(v string) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetName(v) + return _c +} + +// SetDescription sets the "description" field. +func (_c *ChargeUsageBasedOverrideCreate) SetDescription(v string) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetDescription(v) + return _c +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_c *ChargeUsageBasedOverrideCreate) SetNillableDescription(v *string) *ChargeUsageBasedOverrideCreate { + if v != nil { + _c.SetDescription(*v) + } + return _c +} + +// SetMetadata sets the "metadata" field. +func (_c *ChargeUsageBasedOverrideCreate) SetMetadata(v *models.Metadata) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetMetadata(v) + return _c +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (_c *ChargeUsageBasedOverrideCreate) SetTaxBehavior(v productcatalog.TaxBehavior) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetTaxBehavior(v) + return _c +} + +// SetNillableTaxBehavior sets the "tax_behavior" field if the given value is not nil. +func (_c *ChargeUsageBasedOverrideCreate) SetNillableTaxBehavior(v *productcatalog.TaxBehavior) *ChargeUsageBasedOverrideCreate { + if v != nil { + _c.SetTaxBehavior(*v) + } + return _c +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (_c *ChargeUsageBasedOverrideCreate) SetTaxCodeID(v string) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetTaxCodeID(v) + return _c +} + +// SetNillableTaxCodeID sets the "tax_code_id" field if the given value is not nil. +func (_c *ChargeUsageBasedOverrideCreate) SetNillableTaxCodeID(v *string) *ChargeUsageBasedOverrideCreate { + if v != nil { + _c.SetTaxCodeID(*v) + } + return _c +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (_c *ChargeUsageBasedOverrideCreate) SetIntentDeletedAt(v time.Time) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetIntentDeletedAt(v) + return _c +} + +// SetNillableIntentDeletedAt sets the "intent_deleted_at" field if the given value is not nil. +func (_c *ChargeUsageBasedOverrideCreate) SetNillableIntentDeletedAt(v *time.Time) *ChargeUsageBasedOverrideCreate { + if v != nil { + _c.SetIntentDeletedAt(*v) + } + return _c +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_c *ChargeUsageBasedOverrideCreate) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetServicePeriodFrom(v) + return _c +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_c *ChargeUsageBasedOverrideCreate) SetServicePeriodTo(v time.Time) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetServicePeriodTo(v) + return _c +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (_c *ChargeUsageBasedOverrideCreate) SetFullServicePeriodFrom(v time.Time) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetFullServicePeriodFrom(v) + return _c +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (_c *ChargeUsageBasedOverrideCreate) SetFullServicePeriodTo(v time.Time) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetFullServicePeriodTo(v) + return _c +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (_c *ChargeUsageBasedOverrideCreate) SetBillingPeriodFrom(v time.Time) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetBillingPeriodFrom(v) + return _c +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (_c *ChargeUsageBasedOverrideCreate) SetBillingPeriodTo(v time.Time) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetBillingPeriodTo(v) + return _c +} + +// SetInvoiceAt sets the "invoice_at" field. +func (_c *ChargeUsageBasedOverrideCreate) SetInvoiceAt(v time.Time) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetInvoiceAt(v) + return _c +} + +// SetFeatureKey sets the "feature_key" field. +func (_c *ChargeUsageBasedOverrideCreate) SetFeatureKey(v string) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetFeatureKey(v) + return _c +} + +// SetNillableFeatureKey sets the "feature_key" field if the given value is not nil. +func (_c *ChargeUsageBasedOverrideCreate) SetNillableFeatureKey(v *string) *ChargeUsageBasedOverrideCreate { + if v != nil { + _c.SetFeatureKey(*v) + } + return _c +} + +// SetPrice sets the "price" field. +func (_c *ChargeUsageBasedOverrideCreate) SetPrice(v *productcatalog.Price) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetPrice(v) + return _c +} + +// SetDiscounts sets the "discounts" field. +func (_c *ChargeUsageBasedOverrideCreate) SetDiscounts(v *billing.Discounts) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetDiscounts(v) + return _c +} + +// SetUnitConfig sets the "unit_config" field. +func (_c *ChargeUsageBasedOverrideCreate) SetUnitConfig(v *productcatalog.UnitConfig) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetUnitConfig(v) + return _c +} + +// SetID sets the "id" field. +func (_c *ChargeUsageBasedOverrideCreate) SetID(v string) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ChargeUsageBasedOverrideCreate) SetNillableID(v *string) *ChargeUsageBasedOverrideCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetUsageBasedID sets the "usage_based" edge to the ChargeUsageBased entity by ID. +func (_c *ChargeUsageBasedOverrideCreate) SetUsageBasedID(id string) *ChargeUsageBasedOverrideCreate { + _c.mutation.SetUsageBasedID(id) + return _c +} + +// SetUsageBased sets the "usage_based" edge to the ChargeUsageBased entity. +func (_c *ChargeUsageBasedOverrideCreate) SetUsageBased(v *ChargeUsageBased) *ChargeUsageBasedOverrideCreate { + return _c.SetUsageBasedID(v.ID) +} + +// SetTaxCode sets the "tax_code" edge to the TaxCode entity. +func (_c *ChargeUsageBasedOverrideCreate) SetTaxCode(v *TaxCode) *ChargeUsageBasedOverrideCreate { + return _c.SetTaxCodeID(v.ID) +} + +// Mutation returns the ChargeUsageBasedOverrideMutation object of the builder. +func (_c *ChargeUsageBasedOverrideCreate) Mutation() *ChargeUsageBasedOverrideMutation { + return _c.mutation +} + +// Save creates the ChargeUsageBasedOverride in the database. +func (_c *ChargeUsageBasedOverrideCreate) Save(ctx context.Context) (*ChargeUsageBasedOverride, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ChargeUsageBasedOverrideCreate) SaveX(ctx context.Context) *ChargeUsageBasedOverride { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeUsageBasedOverrideCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeUsageBasedOverrideCreate) 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 *ChargeUsageBasedOverrideCreate) defaults() { + if _, ok := _c.mutation.ID(); !ok { + v := chargeusagebasedoverride.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ChargeUsageBasedOverrideCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "ChargeUsageBasedOverride.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := chargeusagebasedoverride.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedOverride.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.ChargeID(); !ok { + return &ValidationError{Name: "charge_id", err: errors.New(`db: missing required field "ChargeUsageBasedOverride.charge_id"`)} + } + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "ChargeUsageBasedOverride.name"`)} + } + if v, ok := _c.mutation.Name(); ok { + if err := chargeusagebasedoverride.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedOverride.name": %w`, err)} + } + } + if v, ok := _c.mutation.TaxBehavior(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "tax_behavior", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedOverride.tax_behavior": %w`, err)} + } + } + if _, ok := _c.mutation.ServicePeriodFrom(); !ok { + return &ValidationError{Name: "service_period_from", err: errors.New(`db: missing required field "ChargeUsageBasedOverride.service_period_from"`)} + } + if _, ok := _c.mutation.ServicePeriodTo(); !ok { + return &ValidationError{Name: "service_period_to", err: errors.New(`db: missing required field "ChargeUsageBasedOverride.service_period_to"`)} + } + if _, ok := _c.mutation.FullServicePeriodFrom(); !ok { + return &ValidationError{Name: "full_service_period_from", err: errors.New(`db: missing required field "ChargeUsageBasedOverride.full_service_period_from"`)} + } + if _, ok := _c.mutation.FullServicePeriodTo(); !ok { + return &ValidationError{Name: "full_service_period_to", err: errors.New(`db: missing required field "ChargeUsageBasedOverride.full_service_period_to"`)} + } + if _, ok := _c.mutation.BillingPeriodFrom(); !ok { + return &ValidationError{Name: "billing_period_from", err: errors.New(`db: missing required field "ChargeUsageBasedOverride.billing_period_from"`)} + } + if _, ok := _c.mutation.BillingPeriodTo(); !ok { + return &ValidationError{Name: "billing_period_to", err: errors.New(`db: missing required field "ChargeUsageBasedOverride.billing_period_to"`)} + } + if _, ok := _c.mutation.InvoiceAt(); !ok { + return &ValidationError{Name: "invoice_at", err: errors.New(`db: missing required field "ChargeUsageBasedOverride.invoice_at"`)} + } + if v, ok := _c.mutation.FeatureKey(); ok { + if err := chargeusagebasedoverride.FeatureKeyValidator(v); err != nil { + return &ValidationError{Name: "feature_key", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedOverride.feature_key": %w`, err)} + } + } + if _, ok := _c.mutation.Price(); !ok { + return &ValidationError{Name: "price", err: errors.New(`db: missing required field "ChargeUsageBasedOverride.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 "ChargeUsageBasedOverride.price": %w`, err)} + } + } + if _, ok := _c.mutation.Discounts(); !ok { + return &ValidationError{Name: "discounts", err: errors.New(`db: missing required field "ChargeUsageBasedOverride.discounts"`)} + } + 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 "ChargeUsageBasedOverride.discounts": %w`, err)} + } + } + if v, ok := _c.mutation.UnitConfig(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "unit_config", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedOverride.unit_config": %w`, err)} + } + } + if len(_c.mutation.UsageBasedIDs()) == 0 { + return &ValidationError{Name: "usage_based", err: errors.New(`db: missing required edge "ChargeUsageBasedOverride.usage_based"`)} + } + return nil +} + +func (_c *ChargeUsageBasedOverrideCreate) sqlSave(ctx context.Context) (*ChargeUsageBasedOverride, 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 ChargeUsageBasedOverride.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ChargeUsageBasedOverrideCreate) createSpec() (*ChargeUsageBasedOverride, *sqlgraph.CreateSpec, error) { + var ( + _node = &ChargeUsageBasedOverride{config: _c.config} + _spec = sqlgraph.NewCreateSpec(chargeusagebasedoverride.Table, sqlgraph.NewFieldSpec(chargeusagebasedoverride.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(chargeusagebasedoverride.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(chargeusagebasedoverride.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Description(); ok { + _spec.SetField(chargeusagebasedoverride.FieldDescription, field.TypeString, value) + _node.Description = &value + } + if value, ok := _c.mutation.Metadata(); ok { + vv, err := chargeusagebasedoverride.ValueScanner.Metadata.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(chargeusagebasedoverride.FieldMetadata, field.TypeString, vv) + _node.Metadata = value + } + if value, ok := _c.mutation.TaxBehavior(); ok { + _spec.SetField(chargeusagebasedoverride.FieldTaxBehavior, field.TypeString, value) + _node.TaxBehavior = &value + } + if value, ok := _c.mutation.IntentDeletedAt(); ok { + _spec.SetField(chargeusagebasedoverride.FieldIntentDeletedAt, field.TypeTime, value) + _node.IntentDeletedAt = &value + } + if value, ok := _c.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeusagebasedoverride.FieldServicePeriodFrom, field.TypeTime, value) + _node.ServicePeriodFrom = value + } + if value, ok := _c.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeusagebasedoverride.FieldServicePeriodTo, field.TypeTime, value) + _node.ServicePeriodTo = value + } + if value, ok := _c.mutation.FullServicePeriodFrom(); ok { + _spec.SetField(chargeusagebasedoverride.FieldFullServicePeriodFrom, field.TypeTime, value) + _node.FullServicePeriodFrom = value + } + if value, ok := _c.mutation.FullServicePeriodTo(); ok { + _spec.SetField(chargeusagebasedoverride.FieldFullServicePeriodTo, field.TypeTime, value) + _node.FullServicePeriodTo = value + } + if value, ok := _c.mutation.BillingPeriodFrom(); ok { + _spec.SetField(chargeusagebasedoverride.FieldBillingPeriodFrom, field.TypeTime, value) + _node.BillingPeriodFrom = value + } + if value, ok := _c.mutation.BillingPeriodTo(); ok { + _spec.SetField(chargeusagebasedoverride.FieldBillingPeriodTo, field.TypeTime, value) + _node.BillingPeriodTo = value + } + if value, ok := _c.mutation.InvoiceAt(); ok { + _spec.SetField(chargeusagebasedoverride.FieldInvoiceAt, field.TypeTime, value) + _node.InvoiceAt = value + } + if value, ok := _c.mutation.FeatureKey(); ok { + _spec.SetField(chargeusagebasedoverride.FieldFeatureKey, field.TypeString, value) + _node.FeatureKey = &value + } + if value, ok := _c.mutation.Price(); ok { + vv, err := chargeusagebasedoverride.ValueScanner.Price.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(chargeusagebasedoverride.FieldPrice, field.TypeString, vv) + _node.Price = value + } + if value, ok := _c.mutation.Discounts(); ok { + vv, err := chargeusagebasedoverride.ValueScanner.Discounts.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(chargeusagebasedoverride.FieldDiscounts, field.TypeString, vv) + _node.Discounts = value + } + if value, ok := _c.mutation.UnitConfig(); ok { + vv, err := chargeusagebasedoverride.ValueScanner.UnitConfig.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(chargeusagebasedoverride.FieldUnitConfig, field.TypeString, vv) + _node.UnitConfig = value + } + if nodes := _c.mutation.UsageBasedIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeusagebasedoverride.UsageBasedTable, + Columns: []string{chargeusagebasedoverride.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.TaxCodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedoverride.TaxCodeTable, + Columns: []string{chargeusagebasedoverride.TaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.TaxCodeID = &nodes[0] + _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.ChargeUsageBasedOverride.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.ChargeUsageBasedOverrideUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *ChargeUsageBasedOverrideCreate) OnConflict(opts ...sql.ConflictOption) *ChargeUsageBasedOverrideUpsertOne { + _c.conflict = opts + return &ChargeUsageBasedOverrideUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeUsageBasedOverride.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeUsageBasedOverrideCreate) OnConflictColumns(columns ...string) *ChargeUsageBasedOverrideUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeUsageBasedOverrideUpsertOne{ + create: _c, + } +} + +type ( + // ChargeUsageBasedOverrideUpsertOne is the builder for "upsert"-ing + // one ChargeUsageBasedOverride node. + ChargeUsageBasedOverrideUpsertOne struct { + create *ChargeUsageBasedOverrideCreate + } + + // ChargeUsageBasedOverrideUpsert is the "OnConflict" setter. + ChargeUsageBasedOverrideUpsert struct { + *sql.UpdateSet + } +) + +// SetName sets the "name" field. +func (u *ChargeUsageBasedOverrideUpsert) SetName(v string) *ChargeUsageBasedOverrideUpsert { + u.Set(chargeusagebasedoverride.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsert) UpdateName() *ChargeUsageBasedOverrideUpsert { + u.SetExcluded(chargeusagebasedoverride.FieldName) + return u +} + +// SetDescription sets the "description" field. +func (u *ChargeUsageBasedOverrideUpsert) SetDescription(v string) *ChargeUsageBasedOverrideUpsert { + u.Set(chargeusagebasedoverride.FieldDescription, v) + return u +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsert) UpdateDescription() *ChargeUsageBasedOverrideUpsert { + u.SetExcluded(chargeusagebasedoverride.FieldDescription) + return u +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeUsageBasedOverrideUpsert) ClearDescription() *ChargeUsageBasedOverrideUpsert { + u.SetNull(chargeusagebasedoverride.FieldDescription) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeUsageBasedOverrideUpsert) SetMetadata(v *models.Metadata) *ChargeUsageBasedOverrideUpsert { + u.Set(chargeusagebasedoverride.FieldMetadata, v) + return u +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsert) UpdateMetadata() *ChargeUsageBasedOverrideUpsert { + u.SetExcluded(chargeusagebasedoverride.FieldMetadata) + return u +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeUsageBasedOverrideUpsert) ClearMetadata() *ChargeUsageBasedOverrideUpsert { + u.SetNull(chargeusagebasedoverride.FieldMetadata) + return u +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (u *ChargeUsageBasedOverrideUpsert) SetTaxBehavior(v productcatalog.TaxBehavior) *ChargeUsageBasedOverrideUpsert { + u.Set(chargeusagebasedoverride.FieldTaxBehavior, v) + return u +} + +// UpdateTaxBehavior sets the "tax_behavior" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsert) UpdateTaxBehavior() *ChargeUsageBasedOverrideUpsert { + u.SetExcluded(chargeusagebasedoverride.FieldTaxBehavior) + return u +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (u *ChargeUsageBasedOverrideUpsert) ClearTaxBehavior() *ChargeUsageBasedOverrideUpsert { + u.SetNull(chargeusagebasedoverride.FieldTaxBehavior) + return u +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (u *ChargeUsageBasedOverrideUpsert) SetTaxCodeID(v string) *ChargeUsageBasedOverrideUpsert { + u.Set(chargeusagebasedoverride.FieldTaxCodeID, v) + return u +} + +// UpdateTaxCodeID sets the "tax_code_id" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsert) UpdateTaxCodeID() *ChargeUsageBasedOverrideUpsert { + u.SetExcluded(chargeusagebasedoverride.FieldTaxCodeID) + return u +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (u *ChargeUsageBasedOverrideUpsert) ClearTaxCodeID() *ChargeUsageBasedOverrideUpsert { + u.SetNull(chargeusagebasedoverride.FieldTaxCodeID) + return u +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (u *ChargeUsageBasedOverrideUpsert) SetIntentDeletedAt(v time.Time) *ChargeUsageBasedOverrideUpsert { + u.Set(chargeusagebasedoverride.FieldIntentDeletedAt, v) + return u +} + +// UpdateIntentDeletedAt sets the "intent_deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsert) UpdateIntentDeletedAt() *ChargeUsageBasedOverrideUpsert { + u.SetExcluded(chargeusagebasedoverride.FieldIntentDeletedAt) + return u +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (u *ChargeUsageBasedOverrideUpsert) ClearIntentDeletedAt() *ChargeUsageBasedOverrideUpsert { + u.SetNull(chargeusagebasedoverride.FieldIntentDeletedAt) + return u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeUsageBasedOverrideUpsert) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedOverrideUpsert { + u.Set(chargeusagebasedoverride.FieldServicePeriodFrom, v) + return u +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsert) UpdateServicePeriodFrom() *ChargeUsageBasedOverrideUpsert { + u.SetExcluded(chargeusagebasedoverride.FieldServicePeriodFrom) + return u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeUsageBasedOverrideUpsert) SetServicePeriodTo(v time.Time) *ChargeUsageBasedOverrideUpsert { + u.Set(chargeusagebasedoverride.FieldServicePeriodTo, v) + return u +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsert) UpdateServicePeriodTo() *ChargeUsageBasedOverrideUpsert { + u.SetExcluded(chargeusagebasedoverride.FieldServicePeriodTo) + return u +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (u *ChargeUsageBasedOverrideUpsert) SetFullServicePeriodFrom(v time.Time) *ChargeUsageBasedOverrideUpsert { + u.Set(chargeusagebasedoverride.FieldFullServicePeriodFrom, v) + return u +} + +// UpdateFullServicePeriodFrom sets the "full_service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsert) UpdateFullServicePeriodFrom() *ChargeUsageBasedOverrideUpsert { + u.SetExcluded(chargeusagebasedoverride.FieldFullServicePeriodFrom) + return u +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (u *ChargeUsageBasedOverrideUpsert) SetFullServicePeriodTo(v time.Time) *ChargeUsageBasedOverrideUpsert { + u.Set(chargeusagebasedoverride.FieldFullServicePeriodTo, v) + return u +} + +// UpdateFullServicePeriodTo sets the "full_service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsert) UpdateFullServicePeriodTo() *ChargeUsageBasedOverrideUpsert { + u.SetExcluded(chargeusagebasedoverride.FieldFullServicePeriodTo) + return u +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (u *ChargeUsageBasedOverrideUpsert) SetBillingPeriodFrom(v time.Time) *ChargeUsageBasedOverrideUpsert { + u.Set(chargeusagebasedoverride.FieldBillingPeriodFrom, v) + return u +} + +// UpdateBillingPeriodFrom sets the "billing_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsert) UpdateBillingPeriodFrom() *ChargeUsageBasedOverrideUpsert { + u.SetExcluded(chargeusagebasedoverride.FieldBillingPeriodFrom) + return u +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (u *ChargeUsageBasedOverrideUpsert) SetBillingPeriodTo(v time.Time) *ChargeUsageBasedOverrideUpsert { + u.Set(chargeusagebasedoverride.FieldBillingPeriodTo, v) + return u +} + +// UpdateBillingPeriodTo sets the "billing_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsert) UpdateBillingPeriodTo() *ChargeUsageBasedOverrideUpsert { + u.SetExcluded(chargeusagebasedoverride.FieldBillingPeriodTo) + return u +} + +// SetInvoiceAt sets the "invoice_at" field. +func (u *ChargeUsageBasedOverrideUpsert) SetInvoiceAt(v time.Time) *ChargeUsageBasedOverrideUpsert { + u.Set(chargeusagebasedoverride.FieldInvoiceAt, v) + return u +} + +// UpdateInvoiceAt sets the "invoice_at" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsert) UpdateInvoiceAt() *ChargeUsageBasedOverrideUpsert { + u.SetExcluded(chargeusagebasedoverride.FieldInvoiceAt) + return u +} + +// SetFeatureKey sets the "feature_key" field. +func (u *ChargeUsageBasedOverrideUpsert) SetFeatureKey(v string) *ChargeUsageBasedOverrideUpsert { + u.Set(chargeusagebasedoverride.FieldFeatureKey, v) + return u +} + +// UpdateFeatureKey sets the "feature_key" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsert) UpdateFeatureKey() *ChargeUsageBasedOverrideUpsert { + u.SetExcluded(chargeusagebasedoverride.FieldFeatureKey) + return u +} + +// ClearFeatureKey clears the value of the "feature_key" field. +func (u *ChargeUsageBasedOverrideUpsert) ClearFeatureKey() *ChargeUsageBasedOverrideUpsert { + u.SetNull(chargeusagebasedoverride.FieldFeatureKey) + return u +} + +// SetPrice sets the "price" field. +func (u *ChargeUsageBasedOverrideUpsert) SetPrice(v *productcatalog.Price) *ChargeUsageBasedOverrideUpsert { + u.Set(chargeusagebasedoverride.FieldPrice, v) + return u +} + +// UpdatePrice sets the "price" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsert) UpdatePrice() *ChargeUsageBasedOverrideUpsert { + u.SetExcluded(chargeusagebasedoverride.FieldPrice) + return u +} + +// SetDiscounts sets the "discounts" field. +func (u *ChargeUsageBasedOverrideUpsert) SetDiscounts(v *billing.Discounts) *ChargeUsageBasedOverrideUpsert { + u.Set(chargeusagebasedoverride.FieldDiscounts, v) + return u +} + +// UpdateDiscounts sets the "discounts" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsert) UpdateDiscounts() *ChargeUsageBasedOverrideUpsert { + u.SetExcluded(chargeusagebasedoverride.FieldDiscounts) + return u +} + +// SetUnitConfig sets the "unit_config" field. +func (u *ChargeUsageBasedOverrideUpsert) SetUnitConfig(v *productcatalog.UnitConfig) *ChargeUsageBasedOverrideUpsert { + u.Set(chargeusagebasedoverride.FieldUnitConfig, v) + return u +} + +// UpdateUnitConfig sets the "unit_config" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsert) UpdateUnitConfig() *ChargeUsageBasedOverrideUpsert { + u.SetExcluded(chargeusagebasedoverride.FieldUnitConfig) + return u +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (u *ChargeUsageBasedOverrideUpsert) ClearUnitConfig() *ChargeUsageBasedOverrideUpsert { + u.SetNull(chargeusagebasedoverride.FieldUnitConfig) + 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.ChargeUsageBasedOverride.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeusagebasedoverride.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeUsageBasedOverrideUpsertOne) UpdateNewValues() *ChargeUsageBasedOverrideUpsertOne { + 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(chargeusagebasedoverride.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(chargeusagebasedoverride.FieldNamespace) + } + if _, exists := u.create.mutation.ChargeID(); exists { + s.SetIgnore(chargeusagebasedoverride.FieldChargeID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeUsageBasedOverride.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeUsageBasedOverrideUpsertOne) Ignore() *ChargeUsageBasedOverrideUpsertOne { + 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 *ChargeUsageBasedOverrideUpsertOne) DoNothing() *ChargeUsageBasedOverrideUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeUsageBasedOverrideCreate.OnConflict +// documentation for more info. +func (u *ChargeUsageBasedOverrideUpsertOne) Update(set func(*ChargeUsageBasedOverrideUpsert)) *ChargeUsageBasedOverrideUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeUsageBasedOverrideUpsert{UpdateSet: update}) + })) + return u +} + +// SetName sets the "name" field. +func (u *ChargeUsageBasedOverrideUpsertOne) SetName(v string) *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertOne) UpdateName() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *ChargeUsageBasedOverrideUpsertOne) SetDescription(v string) *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertOne) UpdateDescription() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeUsageBasedOverrideUpsertOne) ClearDescription() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.ClearDescription() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeUsageBasedOverrideUpsertOne) SetMetadata(v *models.Metadata) *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertOne) UpdateMetadata() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeUsageBasedOverrideUpsertOne) ClearMetadata() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.ClearMetadata() + }) +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (u *ChargeUsageBasedOverrideUpsertOne) SetTaxBehavior(v productcatalog.TaxBehavior) *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetTaxBehavior(v) + }) +} + +// UpdateTaxBehavior sets the "tax_behavior" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertOne) UpdateTaxBehavior() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateTaxBehavior() + }) +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (u *ChargeUsageBasedOverrideUpsertOne) ClearTaxBehavior() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.ClearTaxBehavior() + }) +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (u *ChargeUsageBasedOverrideUpsertOne) SetTaxCodeID(v string) *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetTaxCodeID(v) + }) +} + +// UpdateTaxCodeID sets the "tax_code_id" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertOne) UpdateTaxCodeID() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateTaxCodeID() + }) +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (u *ChargeUsageBasedOverrideUpsertOne) ClearTaxCodeID() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.ClearTaxCodeID() + }) +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (u *ChargeUsageBasedOverrideUpsertOne) SetIntentDeletedAt(v time.Time) *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetIntentDeletedAt(v) + }) +} + +// UpdateIntentDeletedAt sets the "intent_deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertOne) UpdateIntentDeletedAt() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateIntentDeletedAt() + }) +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (u *ChargeUsageBasedOverrideUpsertOne) ClearIntentDeletedAt() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.ClearIntentDeletedAt() + }) +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeUsageBasedOverrideUpsertOne) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertOne) UpdateServicePeriodFrom() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeUsageBasedOverrideUpsertOne) SetServicePeriodTo(v time.Time) *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertOne) UpdateServicePeriodTo() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (u *ChargeUsageBasedOverrideUpsertOne) SetFullServicePeriodFrom(v time.Time) *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetFullServicePeriodFrom(v) + }) +} + +// UpdateFullServicePeriodFrom sets the "full_service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertOne) UpdateFullServicePeriodFrom() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateFullServicePeriodFrom() + }) +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (u *ChargeUsageBasedOverrideUpsertOne) SetFullServicePeriodTo(v time.Time) *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetFullServicePeriodTo(v) + }) +} + +// UpdateFullServicePeriodTo sets the "full_service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertOne) UpdateFullServicePeriodTo() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateFullServicePeriodTo() + }) +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (u *ChargeUsageBasedOverrideUpsertOne) SetBillingPeriodFrom(v time.Time) *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetBillingPeriodFrom(v) + }) +} + +// UpdateBillingPeriodFrom sets the "billing_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertOne) UpdateBillingPeriodFrom() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateBillingPeriodFrom() + }) +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (u *ChargeUsageBasedOverrideUpsertOne) SetBillingPeriodTo(v time.Time) *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetBillingPeriodTo(v) + }) +} + +// UpdateBillingPeriodTo sets the "billing_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertOne) UpdateBillingPeriodTo() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateBillingPeriodTo() + }) +} + +// SetInvoiceAt sets the "invoice_at" field. +func (u *ChargeUsageBasedOverrideUpsertOne) SetInvoiceAt(v time.Time) *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetInvoiceAt(v) + }) +} + +// UpdateInvoiceAt sets the "invoice_at" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertOne) UpdateInvoiceAt() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateInvoiceAt() + }) +} + +// SetFeatureKey sets the "feature_key" field. +func (u *ChargeUsageBasedOverrideUpsertOne) SetFeatureKey(v string) *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetFeatureKey(v) + }) +} + +// UpdateFeatureKey sets the "feature_key" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertOne) UpdateFeatureKey() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateFeatureKey() + }) +} + +// ClearFeatureKey clears the value of the "feature_key" field. +func (u *ChargeUsageBasedOverrideUpsertOne) ClearFeatureKey() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.ClearFeatureKey() + }) +} + +// SetPrice sets the "price" field. +func (u *ChargeUsageBasedOverrideUpsertOne) SetPrice(v *productcatalog.Price) *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetPrice(v) + }) +} + +// UpdatePrice sets the "price" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertOne) UpdatePrice() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdatePrice() + }) +} + +// SetDiscounts sets the "discounts" field. +func (u *ChargeUsageBasedOverrideUpsertOne) SetDiscounts(v *billing.Discounts) *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetDiscounts(v) + }) +} + +// UpdateDiscounts sets the "discounts" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertOne) UpdateDiscounts() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateDiscounts() + }) +} + +// SetUnitConfig sets the "unit_config" field. +func (u *ChargeUsageBasedOverrideUpsertOne) SetUnitConfig(v *productcatalog.UnitConfig) *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetUnitConfig(v) + }) +} + +// UpdateUnitConfig sets the "unit_config" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertOne) UpdateUnitConfig() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateUnitConfig() + }) +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (u *ChargeUsageBasedOverrideUpsertOne) ClearUnitConfig() *ChargeUsageBasedOverrideUpsertOne { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.ClearUnitConfig() + }) +} + +// Exec executes the query. +func (u *ChargeUsageBasedOverrideUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeUsageBasedOverrideCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeUsageBasedOverrideUpsertOne) 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 *ChargeUsageBasedOverrideUpsertOne) 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: ChargeUsageBasedOverrideUpsertOne.ID is not supported by MySQL driver. Use ChargeUsageBasedOverrideUpsertOne.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 *ChargeUsageBasedOverrideUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ChargeUsageBasedOverrideCreateBulk is the builder for creating many ChargeUsageBasedOverride entities in bulk. +type ChargeUsageBasedOverrideCreateBulk struct { + config + err error + builders []*ChargeUsageBasedOverrideCreate + conflict []sql.ConflictOption +} + +// Save creates the ChargeUsageBasedOverride entities in the database. +func (_c *ChargeUsageBasedOverrideCreateBulk) Save(ctx context.Context) ([]*ChargeUsageBasedOverride, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ChargeUsageBasedOverride, 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.(*ChargeUsageBasedOverrideMutation) + 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 *ChargeUsageBasedOverrideCreateBulk) SaveX(ctx context.Context) []*ChargeUsageBasedOverride { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeUsageBasedOverrideCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeUsageBasedOverrideCreateBulk) 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.ChargeUsageBasedOverride.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.ChargeUsageBasedOverrideUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *ChargeUsageBasedOverrideCreateBulk) OnConflict(opts ...sql.ConflictOption) *ChargeUsageBasedOverrideUpsertBulk { + _c.conflict = opts + return &ChargeUsageBasedOverrideUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeUsageBasedOverride.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeUsageBasedOverrideCreateBulk) OnConflictColumns(columns ...string) *ChargeUsageBasedOverrideUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeUsageBasedOverrideUpsertBulk{ + create: _c, + } +} + +// ChargeUsageBasedOverrideUpsertBulk is the builder for "upsert"-ing +// a bulk of ChargeUsageBasedOverride nodes. +type ChargeUsageBasedOverrideUpsertBulk struct { + create *ChargeUsageBasedOverrideCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ChargeUsageBasedOverride.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeusagebasedoverride.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeUsageBasedOverrideUpsertBulk) UpdateNewValues() *ChargeUsageBasedOverrideUpsertBulk { + 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(chargeusagebasedoverride.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(chargeusagebasedoverride.FieldNamespace) + } + if _, exists := b.mutation.ChargeID(); exists { + s.SetIgnore(chargeusagebasedoverride.FieldChargeID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeUsageBasedOverride.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeUsageBasedOverrideUpsertBulk) Ignore() *ChargeUsageBasedOverrideUpsertBulk { + 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 *ChargeUsageBasedOverrideUpsertBulk) DoNothing() *ChargeUsageBasedOverrideUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeUsageBasedOverrideCreateBulk.OnConflict +// documentation for more info. +func (u *ChargeUsageBasedOverrideUpsertBulk) Update(set func(*ChargeUsageBasedOverrideUpsert)) *ChargeUsageBasedOverrideUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeUsageBasedOverrideUpsert{UpdateSet: update}) + })) + return u +} + +// SetName sets the "name" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) SetName(v string) *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertBulk) UpdateName() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) SetDescription(v string) *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertBulk) UpdateDescription() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) ClearDescription() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.ClearDescription() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) SetMetadata(v *models.Metadata) *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertBulk) UpdateMetadata() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) ClearMetadata() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.ClearMetadata() + }) +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) SetTaxBehavior(v productcatalog.TaxBehavior) *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetTaxBehavior(v) + }) +} + +// UpdateTaxBehavior sets the "tax_behavior" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertBulk) UpdateTaxBehavior() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateTaxBehavior() + }) +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) ClearTaxBehavior() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.ClearTaxBehavior() + }) +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) SetTaxCodeID(v string) *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetTaxCodeID(v) + }) +} + +// UpdateTaxCodeID sets the "tax_code_id" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertBulk) UpdateTaxCodeID() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateTaxCodeID() + }) +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) ClearTaxCodeID() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.ClearTaxCodeID() + }) +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) SetIntentDeletedAt(v time.Time) *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetIntentDeletedAt(v) + }) +} + +// UpdateIntentDeletedAt sets the "intent_deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertBulk) UpdateIntentDeletedAt() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateIntentDeletedAt() + }) +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) ClearIntentDeletedAt() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.ClearIntentDeletedAt() + }) +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertBulk) UpdateServicePeriodFrom() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) SetServicePeriodTo(v time.Time) *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertBulk) UpdateServicePeriodTo() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) SetFullServicePeriodFrom(v time.Time) *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetFullServicePeriodFrom(v) + }) +} + +// UpdateFullServicePeriodFrom sets the "full_service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertBulk) UpdateFullServicePeriodFrom() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateFullServicePeriodFrom() + }) +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) SetFullServicePeriodTo(v time.Time) *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetFullServicePeriodTo(v) + }) +} + +// UpdateFullServicePeriodTo sets the "full_service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertBulk) UpdateFullServicePeriodTo() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateFullServicePeriodTo() + }) +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) SetBillingPeriodFrom(v time.Time) *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetBillingPeriodFrom(v) + }) +} + +// UpdateBillingPeriodFrom sets the "billing_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertBulk) UpdateBillingPeriodFrom() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateBillingPeriodFrom() + }) +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) SetBillingPeriodTo(v time.Time) *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetBillingPeriodTo(v) + }) +} + +// UpdateBillingPeriodTo sets the "billing_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertBulk) UpdateBillingPeriodTo() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateBillingPeriodTo() + }) +} + +// SetInvoiceAt sets the "invoice_at" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) SetInvoiceAt(v time.Time) *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetInvoiceAt(v) + }) +} + +// UpdateInvoiceAt sets the "invoice_at" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertBulk) UpdateInvoiceAt() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateInvoiceAt() + }) +} + +// SetFeatureKey sets the "feature_key" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) SetFeatureKey(v string) *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetFeatureKey(v) + }) +} + +// UpdateFeatureKey sets the "feature_key" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertBulk) UpdateFeatureKey() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateFeatureKey() + }) +} + +// ClearFeatureKey clears the value of the "feature_key" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) ClearFeatureKey() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.ClearFeatureKey() + }) +} + +// SetPrice sets the "price" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) SetPrice(v *productcatalog.Price) *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetPrice(v) + }) +} + +// UpdatePrice sets the "price" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertBulk) UpdatePrice() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdatePrice() + }) +} + +// SetDiscounts sets the "discounts" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) SetDiscounts(v *billing.Discounts) *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetDiscounts(v) + }) +} + +// UpdateDiscounts sets the "discounts" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertBulk) UpdateDiscounts() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateDiscounts() + }) +} + +// SetUnitConfig sets the "unit_config" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) SetUnitConfig(v *productcatalog.UnitConfig) *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.SetUnitConfig(v) + }) +} + +// UpdateUnitConfig sets the "unit_config" field to the value that was provided on create. +func (u *ChargeUsageBasedOverrideUpsertBulk) UpdateUnitConfig() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.UpdateUnitConfig() + }) +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (u *ChargeUsageBasedOverrideUpsertBulk) ClearUnitConfig() *ChargeUsageBasedOverrideUpsertBulk { + return u.Update(func(s *ChargeUsageBasedOverrideUpsert) { + s.ClearUnitConfig() + }) +} + +// Exec executes the query. +func (u *ChargeUsageBasedOverrideUpsertBulk) 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 ChargeUsageBasedOverrideCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeUsageBasedOverrideCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeUsageBasedOverrideUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargeusagebasedoverride_delete.go b/ent/db/chargeusagebasedoverride_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..f8712da8280e3951b1b67cc7f5c0c4a3445a2cd5 --- /dev/null +++ b/ent/db/chargeusagebasedoverride_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/chargeusagebasedoverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeUsageBasedOverrideDelete is the builder for deleting a ChargeUsageBasedOverride entity. +type ChargeUsageBasedOverrideDelete struct { + config + hooks []Hook + mutation *ChargeUsageBasedOverrideMutation +} + +// Where appends a list predicates to the ChargeUsageBasedOverrideDelete builder. +func (_d *ChargeUsageBasedOverrideDelete) Where(ps ...predicate.ChargeUsageBasedOverride) *ChargeUsageBasedOverrideDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ChargeUsageBasedOverrideDelete) 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 *ChargeUsageBasedOverrideDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ChargeUsageBasedOverrideDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(chargeusagebasedoverride.Table, sqlgraph.NewFieldSpec(chargeusagebasedoverride.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 +} + +// ChargeUsageBasedOverrideDeleteOne is the builder for deleting a single ChargeUsageBasedOverride entity. +type ChargeUsageBasedOverrideDeleteOne struct { + _d *ChargeUsageBasedOverrideDelete +} + +// Where appends a list predicates to the ChargeUsageBasedOverrideDelete builder. +func (_d *ChargeUsageBasedOverrideDeleteOne) Where(ps ...predicate.ChargeUsageBasedOverride) *ChargeUsageBasedOverrideDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ChargeUsageBasedOverrideDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{chargeusagebasedoverride.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeUsageBasedOverrideDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargeusagebasedoverride_query.go b/ent/db/chargeusagebasedoverride_query.go new file mode 100644 index 0000000000000000000000000000000000000000..fb476fa4b84cda954a21d8656b9ce40222adfdd4 --- /dev/null +++ b/ent/db/chargeusagebasedoverride_query.go @@ -0,0 +1,721 @@ +// 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/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedoverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" +) + +// ChargeUsageBasedOverrideQuery is the builder for querying ChargeUsageBasedOverride entities. +type ChargeUsageBasedOverrideQuery struct { + config + ctx *QueryContext + order []chargeusagebasedoverride.OrderOption + inters []Interceptor + predicates []predicate.ChargeUsageBasedOverride + withUsageBased *ChargeUsageBasedQuery + withTaxCode *TaxCodeQuery + 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 ChargeUsageBasedOverrideQuery builder. +func (_q *ChargeUsageBasedOverrideQuery) Where(ps ...predicate.ChargeUsageBasedOverride) *ChargeUsageBasedOverrideQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ChargeUsageBasedOverrideQuery) Limit(limit int) *ChargeUsageBasedOverrideQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ChargeUsageBasedOverrideQuery) Offset(offset int) *ChargeUsageBasedOverrideQuery { + _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 *ChargeUsageBasedOverrideQuery) Unique(unique bool) *ChargeUsageBasedOverrideQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ChargeUsageBasedOverrideQuery) Order(o ...chargeusagebasedoverride.OrderOption) *ChargeUsageBasedOverrideQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryUsageBased chains the current query on the "usage_based" edge. +func (_q *ChargeUsageBasedOverrideQuery) 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(chargeusagebasedoverride.Table, chargeusagebasedoverride.FieldID, selector), + sqlgraph.To(chargeusagebased.Table, chargeusagebased.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargeusagebasedoverride.UsageBasedTable, chargeusagebasedoverride.UsageBasedColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryTaxCode chains the current query on the "tax_code" edge. +func (_q *ChargeUsageBasedOverrideQuery) QueryTaxCode() *TaxCodeQuery { + query := (&TaxCodeClient{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(chargeusagebasedoverride.Table, chargeusagebasedoverride.FieldID, selector), + sqlgraph.To(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebasedoverride.TaxCodeTable, chargeusagebasedoverride.TaxCodeColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ChargeUsageBasedOverride entity from the query. +// Returns a *NotFoundError when no ChargeUsageBasedOverride was found. +func (_q *ChargeUsageBasedOverrideQuery) First(ctx context.Context) (*ChargeUsageBasedOverride, 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{chargeusagebasedoverride.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ChargeUsageBasedOverrideQuery) FirstX(ctx context.Context) *ChargeUsageBasedOverride { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ChargeUsageBasedOverride ID from the query. +// Returns a *NotFoundError when no ChargeUsageBasedOverride ID was found. +func (_q *ChargeUsageBasedOverrideQuery) 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{chargeusagebasedoverride.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ChargeUsageBasedOverrideQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ChargeUsageBasedOverride entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ChargeUsageBasedOverride entity is found. +// Returns a *NotFoundError when no ChargeUsageBasedOverride entities are found. +func (_q *ChargeUsageBasedOverrideQuery) Only(ctx context.Context) (*ChargeUsageBasedOverride, 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{chargeusagebasedoverride.Label} + default: + return nil, &NotSingularError{chargeusagebasedoverride.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ChargeUsageBasedOverrideQuery) OnlyX(ctx context.Context) *ChargeUsageBasedOverride { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ChargeUsageBasedOverride ID in the query. +// Returns a *NotSingularError when more than one ChargeUsageBasedOverride ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ChargeUsageBasedOverrideQuery) 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{chargeusagebasedoverride.Label} + default: + err = &NotSingularError{chargeusagebasedoverride.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ChargeUsageBasedOverrideQuery) 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 ChargeUsageBasedOverrides. +func (_q *ChargeUsageBasedOverrideQuery) All(ctx context.Context) ([]*ChargeUsageBasedOverride, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ChargeUsageBasedOverride, *ChargeUsageBasedOverrideQuery]() + return withInterceptors[[]*ChargeUsageBasedOverride](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ChargeUsageBasedOverrideQuery) AllX(ctx context.Context) []*ChargeUsageBasedOverride { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ChargeUsageBasedOverride IDs. +func (_q *ChargeUsageBasedOverrideQuery) 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(chargeusagebasedoverride.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ChargeUsageBasedOverrideQuery) 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 *ChargeUsageBasedOverrideQuery) 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[*ChargeUsageBasedOverrideQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ChargeUsageBasedOverrideQuery) 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 *ChargeUsageBasedOverrideQuery) 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 *ChargeUsageBasedOverrideQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ChargeUsageBasedOverrideQuery 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 *ChargeUsageBasedOverrideQuery) Clone() *ChargeUsageBasedOverrideQuery { + if _q == nil { + return nil + } + return &ChargeUsageBasedOverrideQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]chargeusagebasedoverride.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ChargeUsageBasedOverride{}, _q.predicates...), + withUsageBased: _q.withUsageBased.Clone(), + withTaxCode: _q.withTaxCode.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 *ChargeUsageBasedOverrideQuery) WithUsageBased(opts ...func(*ChargeUsageBasedQuery)) *ChargeUsageBasedOverrideQuery { + query := (&ChargeUsageBasedClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withUsageBased = query + return _q +} + +// WithTaxCode tells the query-builder to eager-load the nodes that are connected to +// the "tax_code" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedOverrideQuery) WithTaxCode(opts ...func(*TaxCodeQuery)) *ChargeUsageBasedOverrideQuery { + query := (&TaxCodeClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withTaxCode = 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.ChargeUsageBasedOverride.Query(). +// GroupBy(chargeusagebasedoverride.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *ChargeUsageBasedOverrideQuery) GroupBy(field string, fields ...string) *ChargeUsageBasedOverrideGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ChargeUsageBasedOverrideGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = chargeusagebasedoverride.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.ChargeUsageBasedOverride.Query(). +// Select(chargeusagebasedoverride.FieldNamespace). +// Scan(ctx, &v) +func (_q *ChargeUsageBasedOverrideQuery) Select(fields ...string) *ChargeUsageBasedOverrideSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ChargeUsageBasedOverrideSelect{ChargeUsageBasedOverrideQuery: _q} + sbuild.label = chargeusagebasedoverride.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ChargeUsageBasedOverrideSelect configured with the given aggregations. +func (_q *ChargeUsageBasedOverrideQuery) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedOverrideSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ChargeUsageBasedOverrideQuery) 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 !chargeusagebasedoverride.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 *ChargeUsageBasedOverrideQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ChargeUsageBasedOverride, error) { + var ( + nodes = []*ChargeUsageBasedOverride{} + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withUsageBased != nil, + _q.withTaxCode != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ChargeUsageBasedOverride).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ChargeUsageBasedOverride{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 *ChargeUsageBasedOverride, e *ChargeUsageBased) { n.Edges.UsageBased = e }); err != nil { + return nil, err + } + } + if query := _q.withTaxCode; query != nil { + if err := _q.loadTaxCode(ctx, query, nodes, nil, + func(n *ChargeUsageBasedOverride, e *TaxCode) { n.Edges.TaxCode = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ChargeUsageBasedOverrideQuery) loadUsageBased(ctx context.Context, query *ChargeUsageBasedQuery, nodes []*ChargeUsageBasedOverride, init func(*ChargeUsageBasedOverride), assign func(*ChargeUsageBasedOverride, *ChargeUsageBased)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBasedOverride) + 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 *ChargeUsageBasedOverrideQuery) loadTaxCode(ctx context.Context, query *TaxCodeQuery, nodes []*ChargeUsageBasedOverride, init func(*ChargeUsageBasedOverride), assign func(*ChargeUsageBasedOverride, *TaxCode)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBasedOverride) + for i := range nodes { + if nodes[i].TaxCodeID == nil { + continue + } + fk := *nodes[i].TaxCodeID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(dbtaxcode.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 "tax_code_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *ChargeUsageBasedOverrideQuery) 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 *ChargeUsageBasedOverrideQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(chargeusagebasedoverride.Table, chargeusagebasedoverride.Columns, sqlgraph.NewFieldSpec(chargeusagebasedoverride.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, chargeusagebasedoverride.FieldID) + for i := range fields { + if fields[i] != chargeusagebasedoverride.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withUsageBased != nil { + _spec.Node.AddColumnOnce(chargeusagebasedoverride.FieldChargeID) + } + if _q.withTaxCode != nil { + _spec.Node.AddColumnOnce(chargeusagebasedoverride.FieldTaxCodeID) + } + } + 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 *ChargeUsageBasedOverrideQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(chargeusagebasedoverride.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = chargeusagebasedoverride.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 *ChargeUsageBasedOverrideQuery) ForUpdate(opts ...sql.LockOption) *ChargeUsageBasedOverrideQuery { + 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 *ChargeUsageBasedOverrideQuery) ForShare(opts ...sql.LockOption) *ChargeUsageBasedOverrideQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ChargeUsageBasedOverrideGroupBy is the group-by builder for ChargeUsageBasedOverride entities. +type ChargeUsageBasedOverrideGroupBy struct { + selector + build *ChargeUsageBasedOverrideQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ChargeUsageBasedOverrideGroupBy) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedOverrideGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ChargeUsageBasedOverrideGroupBy) 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[*ChargeUsageBasedOverrideQuery, *ChargeUsageBasedOverrideGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ChargeUsageBasedOverrideGroupBy) sqlScan(ctx context.Context, root *ChargeUsageBasedOverrideQuery, 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) +} + +// ChargeUsageBasedOverrideSelect is the builder for selecting fields of ChargeUsageBasedOverride entities. +type ChargeUsageBasedOverrideSelect struct { + *ChargeUsageBasedOverrideQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ChargeUsageBasedOverrideSelect) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedOverrideSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ChargeUsageBasedOverrideSelect) 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[*ChargeUsageBasedOverrideQuery, *ChargeUsageBasedOverrideSelect](ctx, _s.ChargeUsageBasedOverrideQuery, _s, _s.inters, v) +} + +func (_s *ChargeUsageBasedOverrideSelect) sqlScan(ctx context.Context, root *ChargeUsageBasedOverrideQuery, 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/ent/db/chargeusagebasedoverride_update.go b/ent/db/chargeusagebasedoverride_update.go new file mode 100644 index 0000000000000000000000000000000000000000..336fa11d1b5af606360d6606ea8f4ee37a5db2a0 --- /dev/null +++ b/ent/db/chargeusagebasedoverride_update.go @@ -0,0 +1,1002 @@ +// 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/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedoverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeUsageBasedOverrideUpdate is the builder for updating ChargeUsageBasedOverride entities. +type ChargeUsageBasedOverrideUpdate struct { + config + hooks []Hook + mutation *ChargeUsageBasedOverrideMutation +} + +// Where appends a list predicates to the ChargeUsageBasedOverrideUpdate builder. +func (_u *ChargeUsageBasedOverrideUpdate) Where(ps ...predicate.ChargeUsageBasedOverride) *ChargeUsageBasedOverrideUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetName sets the "name" field. +func (_u *ChargeUsageBasedOverrideUpdate) SetName(v string) *ChargeUsageBasedOverrideUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdate) SetNillableName(v *string) *ChargeUsageBasedOverrideUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *ChargeUsageBasedOverrideUpdate) SetDescription(v string) *ChargeUsageBasedOverrideUpdate { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdate) SetNillableDescription(v *string) *ChargeUsageBasedOverrideUpdate { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *ChargeUsageBasedOverrideUpdate) ClearDescription() *ChargeUsageBasedOverrideUpdate { + _u.mutation.ClearDescription() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *ChargeUsageBasedOverrideUpdate) SetMetadata(v *models.Metadata) *ChargeUsageBasedOverrideUpdate { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *ChargeUsageBasedOverrideUpdate) ClearMetadata() *ChargeUsageBasedOverrideUpdate { + _u.mutation.ClearMetadata() + return _u +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (_u *ChargeUsageBasedOverrideUpdate) SetTaxBehavior(v productcatalog.TaxBehavior) *ChargeUsageBasedOverrideUpdate { + _u.mutation.SetTaxBehavior(v) + return _u +} + +// SetNillableTaxBehavior sets the "tax_behavior" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdate) SetNillableTaxBehavior(v *productcatalog.TaxBehavior) *ChargeUsageBasedOverrideUpdate { + if v != nil { + _u.SetTaxBehavior(*v) + } + return _u +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (_u *ChargeUsageBasedOverrideUpdate) ClearTaxBehavior() *ChargeUsageBasedOverrideUpdate { + _u.mutation.ClearTaxBehavior() + return _u +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (_u *ChargeUsageBasedOverrideUpdate) SetTaxCodeID(v string) *ChargeUsageBasedOverrideUpdate { + _u.mutation.SetTaxCodeID(v) + return _u +} + +// SetNillableTaxCodeID sets the "tax_code_id" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdate) SetNillableTaxCodeID(v *string) *ChargeUsageBasedOverrideUpdate { + if v != nil { + _u.SetTaxCodeID(*v) + } + return _u +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (_u *ChargeUsageBasedOverrideUpdate) ClearTaxCodeID() *ChargeUsageBasedOverrideUpdate { + _u.mutation.ClearTaxCodeID() + return _u +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (_u *ChargeUsageBasedOverrideUpdate) SetIntentDeletedAt(v time.Time) *ChargeUsageBasedOverrideUpdate { + _u.mutation.SetIntentDeletedAt(v) + return _u +} + +// SetNillableIntentDeletedAt sets the "intent_deleted_at" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdate) SetNillableIntentDeletedAt(v *time.Time) *ChargeUsageBasedOverrideUpdate { + if v != nil { + _u.SetIntentDeletedAt(*v) + } + return _u +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (_u *ChargeUsageBasedOverrideUpdate) ClearIntentDeletedAt() *ChargeUsageBasedOverrideUpdate { + _u.mutation.ClearIntentDeletedAt() + return _u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeUsageBasedOverrideUpdate) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedOverrideUpdate { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdate) SetNillableServicePeriodFrom(v *time.Time) *ChargeUsageBasedOverrideUpdate { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeUsageBasedOverrideUpdate) SetServicePeriodTo(v time.Time) *ChargeUsageBasedOverrideUpdate { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdate) SetNillableServicePeriodTo(v *time.Time) *ChargeUsageBasedOverrideUpdate { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (_u *ChargeUsageBasedOverrideUpdate) SetFullServicePeriodFrom(v time.Time) *ChargeUsageBasedOverrideUpdate { + _u.mutation.SetFullServicePeriodFrom(v) + return _u +} + +// SetNillableFullServicePeriodFrom sets the "full_service_period_from" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdate) SetNillableFullServicePeriodFrom(v *time.Time) *ChargeUsageBasedOverrideUpdate { + if v != nil { + _u.SetFullServicePeriodFrom(*v) + } + return _u +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (_u *ChargeUsageBasedOverrideUpdate) SetFullServicePeriodTo(v time.Time) *ChargeUsageBasedOverrideUpdate { + _u.mutation.SetFullServicePeriodTo(v) + return _u +} + +// SetNillableFullServicePeriodTo sets the "full_service_period_to" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdate) SetNillableFullServicePeriodTo(v *time.Time) *ChargeUsageBasedOverrideUpdate { + if v != nil { + _u.SetFullServicePeriodTo(*v) + } + return _u +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (_u *ChargeUsageBasedOverrideUpdate) SetBillingPeriodFrom(v time.Time) *ChargeUsageBasedOverrideUpdate { + _u.mutation.SetBillingPeriodFrom(v) + return _u +} + +// SetNillableBillingPeriodFrom sets the "billing_period_from" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdate) SetNillableBillingPeriodFrom(v *time.Time) *ChargeUsageBasedOverrideUpdate { + if v != nil { + _u.SetBillingPeriodFrom(*v) + } + return _u +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (_u *ChargeUsageBasedOverrideUpdate) SetBillingPeriodTo(v time.Time) *ChargeUsageBasedOverrideUpdate { + _u.mutation.SetBillingPeriodTo(v) + return _u +} + +// SetNillableBillingPeriodTo sets the "billing_period_to" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdate) SetNillableBillingPeriodTo(v *time.Time) *ChargeUsageBasedOverrideUpdate { + if v != nil { + _u.SetBillingPeriodTo(*v) + } + return _u +} + +// SetInvoiceAt sets the "invoice_at" field. +func (_u *ChargeUsageBasedOverrideUpdate) SetInvoiceAt(v time.Time) *ChargeUsageBasedOverrideUpdate { + _u.mutation.SetInvoiceAt(v) + return _u +} + +// SetNillableInvoiceAt sets the "invoice_at" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdate) SetNillableInvoiceAt(v *time.Time) *ChargeUsageBasedOverrideUpdate { + if v != nil { + _u.SetInvoiceAt(*v) + } + return _u +} + +// SetFeatureKey sets the "feature_key" field. +func (_u *ChargeUsageBasedOverrideUpdate) SetFeatureKey(v string) *ChargeUsageBasedOverrideUpdate { + _u.mutation.SetFeatureKey(v) + return _u +} + +// SetNillableFeatureKey sets the "feature_key" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdate) SetNillableFeatureKey(v *string) *ChargeUsageBasedOverrideUpdate { + if v != nil { + _u.SetFeatureKey(*v) + } + return _u +} + +// ClearFeatureKey clears the value of the "feature_key" field. +func (_u *ChargeUsageBasedOverrideUpdate) ClearFeatureKey() *ChargeUsageBasedOverrideUpdate { + _u.mutation.ClearFeatureKey() + return _u +} + +// SetPrice sets the "price" field. +func (_u *ChargeUsageBasedOverrideUpdate) SetPrice(v *productcatalog.Price) *ChargeUsageBasedOverrideUpdate { + _u.mutation.SetPrice(v) + return _u +} + +// SetDiscounts sets the "discounts" field. +func (_u *ChargeUsageBasedOverrideUpdate) SetDiscounts(v *billing.Discounts) *ChargeUsageBasedOverrideUpdate { + _u.mutation.SetDiscounts(v) + return _u +} + +// SetUnitConfig sets the "unit_config" field. +func (_u *ChargeUsageBasedOverrideUpdate) SetUnitConfig(v *productcatalog.UnitConfig) *ChargeUsageBasedOverrideUpdate { + _u.mutation.SetUnitConfig(v) + return _u +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (_u *ChargeUsageBasedOverrideUpdate) ClearUnitConfig() *ChargeUsageBasedOverrideUpdate { + _u.mutation.ClearUnitConfig() + return _u +} + +// SetTaxCode sets the "tax_code" edge to the TaxCode entity. +func (_u *ChargeUsageBasedOverrideUpdate) SetTaxCode(v *TaxCode) *ChargeUsageBasedOverrideUpdate { + return _u.SetTaxCodeID(v.ID) +} + +// Mutation returns the ChargeUsageBasedOverrideMutation object of the builder. +func (_u *ChargeUsageBasedOverrideUpdate) Mutation() *ChargeUsageBasedOverrideMutation { + return _u.mutation +} + +// ClearTaxCode clears the "tax_code" edge to the TaxCode entity. +func (_u *ChargeUsageBasedOverrideUpdate) ClearTaxCode() *ChargeUsageBasedOverrideUpdate { + _u.mutation.ClearTaxCode() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ChargeUsageBasedOverrideUpdate) 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 *ChargeUsageBasedOverrideUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ChargeUsageBasedOverrideUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeUsageBasedOverrideUpdate) 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 *ChargeUsageBasedOverrideUpdate) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := chargeusagebasedoverride.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedOverride.name": %w`, err)} + } + } + if v, ok := _u.mutation.TaxBehavior(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "tax_behavior", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedOverride.tax_behavior": %w`, err)} + } + } + if v, ok := _u.mutation.FeatureKey(); ok { + if err := chargeusagebasedoverride.FeatureKeyValidator(v); err != nil { + return &ValidationError{Name: "feature_key", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedOverride.feature_key": %w`, err)} + } + } + if v, ok := _u.mutation.Price(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "price", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedOverride.price": %w`, err)} + } + } + 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 "ChargeUsageBasedOverride.discounts": %w`, err)} + } + } + if v, ok := _u.mutation.UnitConfig(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "unit_config", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedOverride.unit_config": %w`, err)} + } + } + if _u.mutation.UsageBasedCleared() && len(_u.mutation.UsageBasedIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBasedOverride.usage_based"`) + } + return nil +} + +func (_u *ChargeUsageBasedOverrideUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeusagebasedoverride.Table, chargeusagebasedoverride.Columns, sqlgraph.NewFieldSpec(chargeusagebasedoverride.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.Name(); ok { + _spec.SetField(chargeusagebasedoverride.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(chargeusagebasedoverride.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(chargeusagebasedoverride.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.Metadata(); ok { + vv, err := chargeusagebasedoverride.ValueScanner.Metadata.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(chargeusagebasedoverride.FieldMetadata, field.TypeString, vv) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(chargeusagebasedoverride.FieldMetadata, field.TypeString) + } + if value, ok := _u.mutation.TaxBehavior(); ok { + _spec.SetField(chargeusagebasedoverride.FieldTaxBehavior, field.TypeString, value) + } + if _u.mutation.TaxBehaviorCleared() { + _spec.ClearField(chargeusagebasedoverride.FieldTaxBehavior, field.TypeString) + } + if value, ok := _u.mutation.IntentDeletedAt(); ok { + _spec.SetField(chargeusagebasedoverride.FieldIntentDeletedAt, field.TypeTime, value) + } + if _u.mutation.IntentDeletedAtCleared() { + _spec.ClearField(chargeusagebasedoverride.FieldIntentDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeusagebasedoverride.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeusagebasedoverride.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.FullServicePeriodFrom(); ok { + _spec.SetField(chargeusagebasedoverride.FieldFullServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.FullServicePeriodTo(); ok { + _spec.SetField(chargeusagebasedoverride.FieldFullServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.BillingPeriodFrom(); ok { + _spec.SetField(chargeusagebasedoverride.FieldBillingPeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.BillingPeriodTo(); ok { + _spec.SetField(chargeusagebasedoverride.FieldBillingPeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.InvoiceAt(); ok { + _spec.SetField(chargeusagebasedoverride.FieldInvoiceAt, field.TypeTime, value) + } + if value, ok := _u.mutation.FeatureKey(); ok { + _spec.SetField(chargeusagebasedoverride.FieldFeatureKey, field.TypeString, value) + } + if _u.mutation.FeatureKeyCleared() { + _spec.ClearField(chargeusagebasedoverride.FieldFeatureKey, field.TypeString) + } + if value, ok := _u.mutation.Price(); ok { + vv, err := chargeusagebasedoverride.ValueScanner.Price.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(chargeusagebasedoverride.FieldPrice, field.TypeString, vv) + } + if value, ok := _u.mutation.Discounts(); ok { + vv, err := chargeusagebasedoverride.ValueScanner.Discounts.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(chargeusagebasedoverride.FieldDiscounts, field.TypeString, vv) + } + if value, ok := _u.mutation.UnitConfig(); ok { + vv, err := chargeusagebasedoverride.ValueScanner.UnitConfig.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(chargeusagebasedoverride.FieldUnitConfig, field.TypeString, vv) + } + if _u.mutation.UnitConfigCleared() { + _spec.ClearField(chargeusagebasedoverride.FieldUnitConfig, field.TypeString) + } + if _u.mutation.TaxCodeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedoverride.TaxCodeTable, + Columns: []string{chargeusagebasedoverride.TaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.TaxCodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedoverride.TaxCodeTable, + Columns: []string{chargeusagebasedoverride.TaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.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{chargeusagebasedoverride.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ChargeUsageBasedOverrideUpdateOne is the builder for updating a single ChargeUsageBasedOverride entity. +type ChargeUsageBasedOverrideUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ChargeUsageBasedOverrideMutation +} + +// SetName sets the "name" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetName(v string) *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetNillableName(v *string) *ChargeUsageBasedOverrideUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetDescription(v string) *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetNillableDescription(v *string) *ChargeUsageBasedOverrideUpdateOne { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) ClearDescription() *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.ClearDescription() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetMetadata(v *models.Metadata) *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) ClearMetadata() *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.ClearMetadata() + return _u +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetTaxBehavior(v productcatalog.TaxBehavior) *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.SetTaxBehavior(v) + return _u +} + +// SetNillableTaxBehavior sets the "tax_behavior" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetNillableTaxBehavior(v *productcatalog.TaxBehavior) *ChargeUsageBasedOverrideUpdateOne { + if v != nil { + _u.SetTaxBehavior(*v) + } + return _u +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) ClearTaxBehavior() *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.ClearTaxBehavior() + return _u +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetTaxCodeID(v string) *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.SetTaxCodeID(v) + return _u +} + +// SetNillableTaxCodeID sets the "tax_code_id" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetNillableTaxCodeID(v *string) *ChargeUsageBasedOverrideUpdateOne { + if v != nil { + _u.SetTaxCodeID(*v) + } + return _u +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) ClearTaxCodeID() *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.ClearTaxCodeID() + return _u +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetIntentDeletedAt(v time.Time) *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.SetIntentDeletedAt(v) + return _u +} + +// SetNillableIntentDeletedAt sets the "intent_deleted_at" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetNillableIntentDeletedAt(v *time.Time) *ChargeUsageBasedOverrideUpdateOne { + if v != nil { + _u.SetIntentDeletedAt(*v) + } + return _u +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) ClearIntentDeletedAt() *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.ClearIntentDeletedAt() + return _u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetNillableServicePeriodFrom(v *time.Time) *ChargeUsageBasedOverrideUpdateOne { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetServicePeriodTo(v time.Time) *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetNillableServicePeriodTo(v *time.Time) *ChargeUsageBasedOverrideUpdateOne { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetFullServicePeriodFrom(v time.Time) *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.SetFullServicePeriodFrom(v) + return _u +} + +// SetNillableFullServicePeriodFrom sets the "full_service_period_from" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetNillableFullServicePeriodFrom(v *time.Time) *ChargeUsageBasedOverrideUpdateOne { + if v != nil { + _u.SetFullServicePeriodFrom(*v) + } + return _u +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetFullServicePeriodTo(v time.Time) *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.SetFullServicePeriodTo(v) + return _u +} + +// SetNillableFullServicePeriodTo sets the "full_service_period_to" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetNillableFullServicePeriodTo(v *time.Time) *ChargeUsageBasedOverrideUpdateOne { + if v != nil { + _u.SetFullServicePeriodTo(*v) + } + return _u +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetBillingPeriodFrom(v time.Time) *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.SetBillingPeriodFrom(v) + return _u +} + +// SetNillableBillingPeriodFrom sets the "billing_period_from" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetNillableBillingPeriodFrom(v *time.Time) *ChargeUsageBasedOverrideUpdateOne { + if v != nil { + _u.SetBillingPeriodFrom(*v) + } + return _u +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetBillingPeriodTo(v time.Time) *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.SetBillingPeriodTo(v) + return _u +} + +// SetNillableBillingPeriodTo sets the "billing_period_to" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetNillableBillingPeriodTo(v *time.Time) *ChargeUsageBasedOverrideUpdateOne { + if v != nil { + _u.SetBillingPeriodTo(*v) + } + return _u +} + +// SetInvoiceAt sets the "invoice_at" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetInvoiceAt(v time.Time) *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.SetInvoiceAt(v) + return _u +} + +// SetNillableInvoiceAt sets the "invoice_at" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetNillableInvoiceAt(v *time.Time) *ChargeUsageBasedOverrideUpdateOne { + if v != nil { + _u.SetInvoiceAt(*v) + } + return _u +} + +// SetFeatureKey sets the "feature_key" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetFeatureKey(v string) *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.SetFeatureKey(v) + return _u +} + +// SetNillableFeatureKey sets the "feature_key" field if the given value is not nil. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetNillableFeatureKey(v *string) *ChargeUsageBasedOverrideUpdateOne { + if v != nil { + _u.SetFeatureKey(*v) + } + return _u +} + +// ClearFeatureKey clears the value of the "feature_key" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) ClearFeatureKey() *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.ClearFeatureKey() + return _u +} + +// SetPrice sets the "price" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetPrice(v *productcatalog.Price) *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.SetPrice(v) + return _u +} + +// SetDiscounts sets the "discounts" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetDiscounts(v *billing.Discounts) *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.SetDiscounts(v) + return _u +} + +// SetUnitConfig sets the "unit_config" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetUnitConfig(v *productcatalog.UnitConfig) *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.SetUnitConfig(v) + return _u +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (_u *ChargeUsageBasedOverrideUpdateOne) ClearUnitConfig() *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.ClearUnitConfig() + return _u +} + +// SetTaxCode sets the "tax_code" edge to the TaxCode entity. +func (_u *ChargeUsageBasedOverrideUpdateOne) SetTaxCode(v *TaxCode) *ChargeUsageBasedOverrideUpdateOne { + return _u.SetTaxCodeID(v.ID) +} + +// Mutation returns the ChargeUsageBasedOverrideMutation object of the builder. +func (_u *ChargeUsageBasedOverrideUpdateOne) Mutation() *ChargeUsageBasedOverrideMutation { + return _u.mutation +} + +// ClearTaxCode clears the "tax_code" edge to the TaxCode entity. +func (_u *ChargeUsageBasedOverrideUpdateOne) ClearTaxCode() *ChargeUsageBasedOverrideUpdateOne { + _u.mutation.ClearTaxCode() + return _u +} + +// Where appends a list predicates to the ChargeUsageBasedOverrideUpdate builder. +func (_u *ChargeUsageBasedOverrideUpdateOne) Where(ps ...predicate.ChargeUsageBasedOverride) *ChargeUsageBasedOverrideUpdateOne { + _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 *ChargeUsageBasedOverrideUpdateOne) Select(field string, fields ...string) *ChargeUsageBasedOverrideUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ChargeUsageBasedOverride entity. +func (_u *ChargeUsageBasedOverrideUpdateOne) Save(ctx context.Context) (*ChargeUsageBasedOverride, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeUsageBasedOverrideUpdateOne) SaveX(ctx context.Context) *ChargeUsageBasedOverride { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ChargeUsageBasedOverrideUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeUsageBasedOverrideUpdateOne) 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 *ChargeUsageBasedOverrideUpdateOne) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := chargeusagebasedoverride.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedOverride.name": %w`, err)} + } + } + if v, ok := _u.mutation.TaxBehavior(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "tax_behavior", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedOverride.tax_behavior": %w`, err)} + } + } + if v, ok := _u.mutation.FeatureKey(); ok { + if err := chargeusagebasedoverride.FeatureKeyValidator(v); err != nil { + return &ValidationError{Name: "feature_key", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedOverride.feature_key": %w`, err)} + } + } + if v, ok := _u.mutation.Price(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "price", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedOverride.price": %w`, err)} + } + } + 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 "ChargeUsageBasedOverride.discounts": %w`, err)} + } + } + if v, ok := _u.mutation.UnitConfig(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "unit_config", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedOverride.unit_config": %w`, err)} + } + } + if _u.mutation.UsageBasedCleared() && len(_u.mutation.UsageBasedIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBasedOverride.usage_based"`) + } + return nil +} + +func (_u *ChargeUsageBasedOverrideUpdateOne) sqlSave(ctx context.Context) (_node *ChargeUsageBasedOverride, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeusagebasedoverride.Table, chargeusagebasedoverride.Columns, sqlgraph.NewFieldSpec(chargeusagebasedoverride.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "ChargeUsageBasedOverride.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, chargeusagebasedoverride.FieldID) + for _, f := range fields { + if !chargeusagebasedoverride.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != chargeusagebasedoverride.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.Name(); ok { + _spec.SetField(chargeusagebasedoverride.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(chargeusagebasedoverride.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(chargeusagebasedoverride.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.Metadata(); ok { + vv, err := chargeusagebasedoverride.ValueScanner.Metadata.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(chargeusagebasedoverride.FieldMetadata, field.TypeString, vv) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(chargeusagebasedoverride.FieldMetadata, field.TypeString) + } + if value, ok := _u.mutation.TaxBehavior(); ok { + _spec.SetField(chargeusagebasedoverride.FieldTaxBehavior, field.TypeString, value) + } + if _u.mutation.TaxBehaviorCleared() { + _spec.ClearField(chargeusagebasedoverride.FieldTaxBehavior, field.TypeString) + } + if value, ok := _u.mutation.IntentDeletedAt(); ok { + _spec.SetField(chargeusagebasedoverride.FieldIntentDeletedAt, field.TypeTime, value) + } + if _u.mutation.IntentDeletedAtCleared() { + _spec.ClearField(chargeusagebasedoverride.FieldIntentDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeusagebasedoverride.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeusagebasedoverride.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.FullServicePeriodFrom(); ok { + _spec.SetField(chargeusagebasedoverride.FieldFullServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.FullServicePeriodTo(); ok { + _spec.SetField(chargeusagebasedoverride.FieldFullServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.BillingPeriodFrom(); ok { + _spec.SetField(chargeusagebasedoverride.FieldBillingPeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.BillingPeriodTo(); ok { + _spec.SetField(chargeusagebasedoverride.FieldBillingPeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.InvoiceAt(); ok { + _spec.SetField(chargeusagebasedoverride.FieldInvoiceAt, field.TypeTime, value) + } + if value, ok := _u.mutation.FeatureKey(); ok { + _spec.SetField(chargeusagebasedoverride.FieldFeatureKey, field.TypeString, value) + } + if _u.mutation.FeatureKeyCleared() { + _spec.ClearField(chargeusagebasedoverride.FieldFeatureKey, field.TypeString) + } + if value, ok := _u.mutation.Price(); ok { + vv, err := chargeusagebasedoverride.ValueScanner.Price.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(chargeusagebasedoverride.FieldPrice, field.TypeString, vv) + } + if value, ok := _u.mutation.Discounts(); ok { + vv, err := chargeusagebasedoverride.ValueScanner.Discounts.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(chargeusagebasedoverride.FieldDiscounts, field.TypeString, vv) + } + if value, ok := _u.mutation.UnitConfig(); ok { + vv, err := chargeusagebasedoverride.ValueScanner.UnitConfig.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(chargeusagebasedoverride.FieldUnitConfig, field.TypeString, vv) + } + if _u.mutation.UnitConfigCleared() { + _spec.ClearField(chargeusagebasedoverride.FieldUnitConfig, field.TypeString) + } + if _u.mutation.TaxCodeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedoverride.TaxCodeTable, + Columns: []string{chargeusagebasedoverride.TaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.TaxCodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedoverride.TaxCodeTable, + Columns: []string{chargeusagebasedoverride.TaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &ChargeUsageBasedOverride{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{chargeusagebasedoverride.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/ent/db/chargeusagebasedruncreditallocations.go b/ent/db/chargeusagebasedruncreditallocations.go new file mode 100644 index 0000000000000000000000000000000000000000..5477c125ec60294d155eca58d1a198c0c7b6c87c --- /dev/null +++ b/ent/db/chargeusagebasedruncreditallocations.go @@ -0,0 +1,331 @@ +// 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/creditrealization" + "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"` + // SortHint holds the value of the "sort_hint" field. + SortHint int `json:"sort_hint,omitempty"` + // Type holds the value of the "type" field. + Type creditrealization.Type `json:"type,omitempty"` + // CorrectsRealizationID holds the value of the "corrects_realization_id" field. + CorrectsRealizationID *string `json:"corrects_realization_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 { + // Corrections holds the value of the corrections edge. + Corrections []*ChargeUsageBasedRunCreditAllocations `json:"corrections,omitempty"` + // Allocation holds the value of the allocation edge. + Allocation *ChargeUsageBasedRunCreditAllocations `json:"allocation,omitempty"` + // 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 [3]bool +} + +// CorrectionsOrErr returns the Corrections value or an error if the edge +// was not loaded in eager-loading. +func (e ChargeUsageBasedRunCreditAllocationsEdges) CorrectionsOrErr() ([]*ChargeUsageBasedRunCreditAllocations, error) { + if e.loadedTypes[0] { + return e.Corrections, nil + } + return nil, &NotLoadedError{edge: "corrections"} +} + +// AllocationOrErr returns the Allocation value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedRunCreditAllocationsEdges) AllocationOrErr() (*ChargeUsageBasedRunCreditAllocations, error) { + if e.Allocation != nil { + return e.Allocation, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: chargeusagebasedruncreditallocations.Label} + } + return nil, &NotLoadedError{edge: "allocation"} +} + +// 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[2] { + 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.FieldSortHint: + values[i] = new(sql.NullInt64) + case chargeusagebasedruncreditallocations.FieldID, chargeusagebasedruncreditallocations.FieldLineID, chargeusagebasedruncreditallocations.FieldLedgerTransactionGroupID, chargeusagebasedruncreditallocations.FieldType, chargeusagebasedruncreditallocations.FieldCorrectsRealizationID, 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.FieldSortHint: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field sort_hint", values[i]) + } else if value.Valid { + _m.SortHint = int(value.Int64) + } + case chargeusagebasedruncreditallocations.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 = creditrealization.Type(value.String) + } + case chargeusagebasedruncreditallocations.FieldCorrectsRealizationID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field corrects_realization_id", values[i]) + } else if value.Valid { + _m.CorrectsRealizationID = new(string) + *_m.CorrectsRealizationID = 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) +} + +// QueryCorrections queries the "corrections" edge of the ChargeUsageBasedRunCreditAllocations entity. +func (_m *ChargeUsageBasedRunCreditAllocations) QueryCorrections() *ChargeUsageBasedRunCreditAllocationsQuery { + return NewChargeUsageBasedRunCreditAllocationsClient(_m.config).QueryCorrections(_m) +} + +// QueryAllocation queries the "allocation" edge of the ChargeUsageBasedRunCreditAllocations entity. +func (_m *ChargeUsageBasedRunCreditAllocations) QueryAllocation() *ChargeUsageBasedRunCreditAllocationsQuery { + return NewChargeUsageBasedRunCreditAllocationsClient(_m.config).QueryAllocation(_m) +} + +// 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("sort_hint=") + builder.WriteString(fmt.Sprintf("%v", _m.SortHint)) + builder.WriteString(", ") + builder.WriteString("type=") + builder.WriteString(fmt.Sprintf("%v", _m.Type)) + builder.WriteString(", ") + if v := _m.CorrectsRealizationID; v != nil { + builder.WriteString("corrects_realization_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("run_id=") + builder.WriteString(_m.RunID) + builder.WriteByte(')') + return builder.String() +} + +// ChargeUsageBasedRunCreditAllocationsSlice is a parsable slice of ChargeUsageBasedRunCreditAllocations. +type ChargeUsageBasedRunCreditAllocationsSlice []*ChargeUsageBasedRunCreditAllocations diff --git a/ent/db/chargeusagebasedruncreditallocations/chargeusagebasedruncreditallocations.go b/ent/db/chargeusagebasedruncreditallocations/chargeusagebasedruncreditallocations.go new file mode 100644 index 0000000000000000000000000000000000000000..ba2c3aa564b55daadf56193d1331f50a8414de27 --- /dev/null +++ b/ent/db/chargeusagebasedruncreditallocations/chargeusagebasedruncreditallocations.go @@ -0,0 +1,250 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeusagebasedruncreditallocations + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/creditrealization" +) + +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" + // FieldSortHint holds the string denoting the sort_hint field in the database. + FieldSortHint = "sort_hint" + // FieldType holds the string denoting the type field in the database. + FieldType = "type" + // FieldCorrectsRealizationID holds the string denoting the corrects_realization_id field in the database. + FieldCorrectsRealizationID = "corrects_realization_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" + // EdgeCorrections holds the string denoting the corrections edge name in mutations. + EdgeCorrections = "corrections" + // EdgeAllocation holds the string denoting the allocation edge name in mutations. + EdgeAllocation = "allocation" + // 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" + // CorrectionsTable is the table that holds the corrections relation/edge. + CorrectionsTable = "charge_usage_based_run_credit_allocations" + // CorrectionsColumn is the table column denoting the corrections relation/edge. + CorrectionsColumn = "corrects_realization_id" + // AllocationTable is the table that holds the allocation relation/edge. + AllocationTable = "charge_usage_based_run_credit_allocations" + // AllocationColumn is the table column denoting the allocation relation/edge. + AllocationColumn = "corrects_realization_id" + // 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, + FieldSortHint, + FieldType, + FieldCorrectsRealizationID, + 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 + // CorrectsRealizationIDValidator is a validator for the "corrects_realization_id" field. It is called by the builders before save. + CorrectsRealizationIDValidator 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 +) + +// TypeValidator is a validator for the "type" field enum values. It is called by the builders before save. +func TypeValidator(_type creditrealization.Type) error { + switch _type { + case "allocation", "correction": + return nil + default: + return fmt.Errorf("chargeusagebasedruncreditallocations: invalid enum value for type field: %q", _type) + } +} + +// 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() +} + +// BySortHint orders the results by the sort_hint field. +func BySortHint(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSortHint, opts...).ToFunc() +} + +// ByType orders the results by the type field. +func ByType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldType, opts...).ToFunc() +} + +// ByCorrectsRealizationID orders the results by the corrects_realization_id field. +func ByCorrectsRealizationID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCorrectsRealizationID, 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() +} + +// ByCorrectionsCount orders the results by corrections count. +func ByCorrectionsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newCorrectionsStep(), opts...) + } +} + +// ByCorrections orders the results by corrections terms. +func ByCorrections(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCorrectionsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByAllocationField orders the results by allocation field. +func ByAllocationField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newAllocationStep(), sql.OrderByField(field, opts...)) + } +} + +// 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 newCorrectionsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, CorrectionsTable, CorrectionsColumn), + ) +} +func newAllocationStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, AllocationTable, AllocationColumn), + ) +} +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/ent/db/chargeusagebasedruncreditallocations/where.go b/ent/db/chargeusagebasedruncreditallocations/where.go new file mode 100644 index 0000000000000000000000000000000000000000..fc0e24c7184006905e15cd51e5debae32a577fac --- /dev/null +++ b/ent/db/chargeusagebasedruncreditallocations/where.go @@ -0,0 +1,887 @@ +// 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/billing/charges/models/creditrealization" + "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)) +} + +// SortHint applies equality check predicate on the "sort_hint" field. It's identical to SortHintEQ. +func SortHint(v int) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldSortHint, v)) +} + +// CorrectsRealizationID applies equality check predicate on the "corrects_realization_id" field. It's identical to CorrectsRealizationIDEQ. +func CorrectsRealizationID(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldCorrectsRealizationID, 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)) +} + +// SortHintEQ applies the EQ predicate on the "sort_hint" field. +func SortHintEQ(v int) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldSortHint, v)) +} + +// SortHintNEQ applies the NEQ predicate on the "sort_hint" field. +func SortHintNEQ(v int) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNEQ(FieldSortHint, v)) +} + +// SortHintIn applies the In predicate on the "sort_hint" field. +func SortHintIn(vs ...int) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldIn(FieldSortHint, vs...)) +} + +// SortHintNotIn applies the NotIn predicate on the "sort_hint" field. +func SortHintNotIn(vs ...int) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNotIn(FieldSortHint, vs...)) +} + +// SortHintGT applies the GT predicate on the "sort_hint" field. +func SortHintGT(v int) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGT(FieldSortHint, v)) +} + +// SortHintGTE applies the GTE predicate on the "sort_hint" field. +func SortHintGTE(v int) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGTE(FieldSortHint, v)) +} + +// SortHintLT applies the LT predicate on the "sort_hint" field. +func SortHintLT(v int) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLT(FieldSortHint, v)) +} + +// SortHintLTE applies the LTE predicate on the "sort_hint" field. +func SortHintLTE(v int) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLTE(FieldSortHint, v)) +} + +// TypeEQ applies the EQ predicate on the "type" field. +func TypeEQ(v creditrealization.Type) predicate.ChargeUsageBasedRunCreditAllocations { + vc := v + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldType, vc)) +} + +// TypeNEQ applies the NEQ predicate on the "type" field. +func TypeNEQ(v creditrealization.Type) predicate.ChargeUsageBasedRunCreditAllocations { + vc := v + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNEQ(FieldType, vc)) +} + +// TypeIn applies the In predicate on the "type" field. +func TypeIn(vs ...creditrealization.Type) predicate.ChargeUsageBasedRunCreditAllocations { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldIn(FieldType, v...)) +} + +// TypeNotIn applies the NotIn predicate on the "type" field. +func TypeNotIn(vs ...creditrealization.Type) predicate.ChargeUsageBasedRunCreditAllocations { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNotIn(FieldType, v...)) +} + +// CorrectsRealizationIDEQ applies the EQ predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDEQ(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldCorrectsRealizationID, v)) +} + +// CorrectsRealizationIDNEQ applies the NEQ predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDNEQ(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNEQ(FieldCorrectsRealizationID, v)) +} + +// CorrectsRealizationIDIn applies the In predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDIn(vs ...string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldIn(FieldCorrectsRealizationID, vs...)) +} + +// CorrectsRealizationIDNotIn applies the NotIn predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDNotIn(vs ...string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNotIn(FieldCorrectsRealizationID, vs...)) +} + +// CorrectsRealizationIDGT applies the GT predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDGT(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGT(FieldCorrectsRealizationID, v)) +} + +// CorrectsRealizationIDGTE applies the GTE predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDGTE(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGTE(FieldCorrectsRealizationID, v)) +} + +// CorrectsRealizationIDLT applies the LT predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDLT(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLT(FieldCorrectsRealizationID, v)) +} + +// CorrectsRealizationIDLTE applies the LTE predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDLTE(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLTE(FieldCorrectsRealizationID, v)) +} + +// CorrectsRealizationIDContains applies the Contains predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDContains(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldContains(FieldCorrectsRealizationID, v)) +} + +// CorrectsRealizationIDHasPrefix applies the HasPrefix predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDHasPrefix(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldHasPrefix(FieldCorrectsRealizationID, v)) +} + +// CorrectsRealizationIDHasSuffix applies the HasSuffix predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDHasSuffix(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldHasSuffix(FieldCorrectsRealizationID, v)) +} + +// CorrectsRealizationIDIsNil applies the IsNil predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDIsNil() predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldIsNull(FieldCorrectsRealizationID)) +} + +// CorrectsRealizationIDNotNil applies the NotNil predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDNotNil() predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNotNull(FieldCorrectsRealizationID)) +} + +// CorrectsRealizationIDEqualFold applies the EqualFold predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDEqualFold(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEqualFold(FieldCorrectsRealizationID, v)) +} + +// CorrectsRealizationIDContainsFold applies the ContainsFold predicate on the "corrects_realization_id" field. +func CorrectsRealizationIDContainsFold(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldContainsFold(FieldCorrectsRealizationID, 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)) +} + +// HasCorrections applies the HasEdge predicate on the "corrections" edge. +func HasCorrections() predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, CorrectionsTable, CorrectionsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCorrectionsWith applies the HasEdge predicate on the "corrections" edge with a given conditions (other predicates). +func HasCorrectionsWith(preds ...predicate.ChargeUsageBasedRunCreditAllocations) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(func(s *sql.Selector) { + step := newCorrectionsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasAllocation applies the HasEdge predicate on the "allocation" edge. +func HasAllocation() predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, AllocationTable, AllocationColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasAllocationWith applies the HasEdge predicate on the "allocation" edge with a given conditions (other predicates). +func HasAllocationWith(preds ...predicate.ChargeUsageBasedRunCreditAllocations) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(func(s *sql.Selector) { + step := newAllocationStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// 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/ent/db/chargeusagebasedruncreditallocations_create.go b/ent/db/chargeusagebasedruncreditallocations_create.go new file mode 100644 index 0000000000000000000000000000000000000000..5bf73a2940a1cc85a5bf12b8526818946237ff23 --- /dev/null +++ b/ent/db/chargeusagebasedruncreditallocations_create.go @@ -0,0 +1,1276 @@ +// 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/creditrealization" + "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 +} + +// SetSortHint sets the "sort_hint" field. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetSortHint(v int) *ChargeUsageBasedRunCreditAllocationsCreate { + _c.mutation.SetSortHint(v) + return _c +} + +// SetType sets the "type" field. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetType(v creditrealization.Type) *ChargeUsageBasedRunCreditAllocationsCreate { + _c.mutation.SetType(v) + return _c +} + +// SetCorrectsRealizationID sets the "corrects_realization_id" field. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetCorrectsRealizationID(v string) *ChargeUsageBasedRunCreditAllocationsCreate { + _c.mutation.SetCorrectsRealizationID(v) + return _c +} + +// SetNillableCorrectsRealizationID sets the "corrects_realization_id" field if the given value is not nil. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetNillableCorrectsRealizationID(v *string) *ChargeUsageBasedRunCreditAllocationsCreate { + if v != nil { + _c.SetCorrectsRealizationID(*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 +} + +// AddCorrectionIDs adds the "corrections" edge to the ChargeUsageBasedRunCreditAllocations entity by IDs. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) AddCorrectionIDs(ids ...string) *ChargeUsageBasedRunCreditAllocationsCreate { + _c.mutation.AddCorrectionIDs(ids...) + return _c +} + +// AddCorrections adds the "corrections" edges to the ChargeUsageBasedRunCreditAllocations entity. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) AddCorrections(v ...*ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunCreditAllocationsCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddCorrectionIDs(ids...) +} + +// SetAllocationID sets the "allocation" edge to the ChargeUsageBasedRunCreditAllocations entity by ID. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetAllocationID(id string) *ChargeUsageBasedRunCreditAllocationsCreate { + _c.mutation.SetAllocationID(id) + return _c +} + +// SetNillableAllocationID sets the "allocation" edge to the ChargeUsageBasedRunCreditAllocations entity by ID if the given value is not nil. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetNillableAllocationID(id *string) *ChargeUsageBasedRunCreditAllocationsCreate { + if id != nil { + _c = _c.SetAllocationID(*id) + } + return _c +} + +// SetAllocation sets the "allocation" edge to the ChargeUsageBasedRunCreditAllocations entity. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetAllocation(v *ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunCreditAllocationsCreate { + return _c.SetAllocationID(v.ID) +} + +// 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.SortHint(); !ok { + return &ValidationError{Name: "sort_hint", err: errors.New(`db: missing required field "ChargeUsageBasedRunCreditAllocations.sort_hint"`)} + } + if _, ok := _c.mutation.GetType(); !ok { + return &ValidationError{Name: "type", err: errors.New(`db: missing required field "ChargeUsageBasedRunCreditAllocations.type"`)} + } + if v, ok := _c.mutation.GetType(); ok { + if err := chargeusagebasedruncreditallocations.TypeValidator(v); err != nil { + return &ValidationError{Name: "type", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunCreditAllocations.type": %w`, err)} + } + } + if v, ok := _c.mutation.CorrectsRealizationID(); ok { + if err := chargeusagebasedruncreditallocations.CorrectsRealizationIDValidator(v); err != nil { + return &ValidationError{Name: "corrects_realization_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunCreditAllocations.corrects_realization_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.SortHint(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldSortHint, field.TypeInt, value) + _node.SortHint = value + } + if value, ok := _c.mutation.GetType(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldType, field.TypeEnum, value) + _node.Type = 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.CorrectionsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: chargeusagebasedruncreditallocations.CorrectionsTable, + Columns: []string{chargeusagebasedruncreditallocations.CorrectionsColumn}, + 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.AllocationIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: chargeusagebasedruncreditallocations.AllocationTable, + Columns: []string{chargeusagebasedruncreditallocations.AllocationColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruncreditallocations.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.CorrectsRealizationID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + 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 +} + +// SetSortHint sets the "sort_hint" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) SetSortHint(v int) *ChargeUsageBasedRunCreditAllocationsUpsert { + u.Set(chargeusagebasedruncreditallocations.FieldSortHint, v) + return u +} + +// UpdateSortHint sets the "sort_hint" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) UpdateSortHint() *ChargeUsageBasedRunCreditAllocationsUpsert { + u.SetExcluded(chargeusagebasedruncreditallocations.FieldSortHint) + return u +} + +// AddSortHint adds v to the "sort_hint" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) AddSortHint(v int) *ChargeUsageBasedRunCreditAllocationsUpsert { + u.Add(chargeusagebasedruncreditallocations.FieldSortHint, v) + return u +} + +// SetCorrectsRealizationID sets the "corrects_realization_id" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) SetCorrectsRealizationID(v string) *ChargeUsageBasedRunCreditAllocationsUpsert { + u.Set(chargeusagebasedruncreditallocations.FieldCorrectsRealizationID, v) + return u +} + +// UpdateCorrectsRealizationID sets the "corrects_realization_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) UpdateCorrectsRealizationID() *ChargeUsageBasedRunCreditAllocationsUpsert { + u.SetExcluded(chargeusagebasedruncreditallocations.FieldCorrectsRealizationID) + return u +} + +// ClearCorrectsRealizationID clears the value of the "corrects_realization_id" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) ClearCorrectsRealizationID() *ChargeUsageBasedRunCreditAllocationsUpsert { + u.SetNull(chargeusagebasedruncreditallocations.FieldCorrectsRealizationID) + 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.GetType(); exists { + s.SetIgnore(chargeusagebasedruncreditallocations.FieldType) + } + 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() + }) +} + +// SetSortHint sets the "sort_hint" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) SetSortHint(v int) *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.SetSortHint(v) + }) +} + +// AddSortHint adds v to the "sort_hint" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) AddSortHint(v int) *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.AddSortHint(v) + }) +} + +// UpdateSortHint sets the "sort_hint" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) UpdateSortHint() *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.UpdateSortHint() + }) +} + +// SetCorrectsRealizationID sets the "corrects_realization_id" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) SetCorrectsRealizationID(v string) *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.SetCorrectsRealizationID(v) + }) +} + +// UpdateCorrectsRealizationID sets the "corrects_realization_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) UpdateCorrectsRealizationID() *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.UpdateCorrectsRealizationID() + }) +} + +// ClearCorrectsRealizationID clears the value of the "corrects_realization_id" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) ClearCorrectsRealizationID() *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.ClearCorrectsRealizationID() + }) +} + +// 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.GetType(); exists { + s.SetIgnore(chargeusagebasedruncreditallocations.FieldType) + } + 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() + }) +} + +// SetSortHint sets the "sort_hint" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) SetSortHint(v int) *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.SetSortHint(v) + }) +} + +// AddSortHint adds v to the "sort_hint" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) AddSortHint(v int) *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.AddSortHint(v) + }) +} + +// UpdateSortHint sets the "sort_hint" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) UpdateSortHint() *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.UpdateSortHint() + }) +} + +// SetCorrectsRealizationID sets the "corrects_realization_id" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) SetCorrectsRealizationID(v string) *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.SetCorrectsRealizationID(v) + }) +} + +// UpdateCorrectsRealizationID sets the "corrects_realization_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) UpdateCorrectsRealizationID() *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.UpdateCorrectsRealizationID() + }) +} + +// ClearCorrectsRealizationID clears the value of the "corrects_realization_id" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) ClearCorrectsRealizationID() *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.ClearCorrectsRealizationID() + }) +} + +// 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/ent/db/chargeusagebasedruncreditallocations_delete.go b/ent/db/chargeusagebasedruncreditallocations_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..fd9166d171f686daa68e1d5b13535f3a459f2b53 --- /dev/null +++ b/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/ent/db/chargeusagebasedruncreditallocations_query.go b/ent/db/chargeusagebasedruncreditallocations_query.go new file mode 100644 index 0000000000000000000000000000000000000000..d97fec2995f83450b45d143e59b20b0c4084ec91 --- /dev/null +++ b/ent/db/chargeusagebasedruncreditallocations_query.go @@ -0,0 +1,803 @@ +// 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/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 + withCorrections *ChargeUsageBasedRunCreditAllocationsQuery + withAllocation *ChargeUsageBasedRunCreditAllocationsQuery + 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 +} + +// QueryCorrections chains the current query on the "corrections" edge. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) QueryCorrections() *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(chargeusagebasedruncreditallocations.Table, chargeusagebasedruncreditallocations.FieldID, selector), + sqlgraph.To(chargeusagebasedruncreditallocations.Table, chargeusagebasedruncreditallocations.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, chargeusagebasedruncreditallocations.CorrectionsTable, chargeusagebasedruncreditallocations.CorrectionsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryAllocation chains the current query on the "allocation" edge. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) QueryAllocation() *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(chargeusagebasedruncreditallocations.Table, chargeusagebasedruncreditallocations.FieldID, selector), + sqlgraph.To(chargeusagebasedruncreditallocations.Table, chargeusagebasedruncreditallocations.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, chargeusagebasedruncreditallocations.AllocationTable, chargeusagebasedruncreditallocations.AllocationColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// 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...), + withCorrections: _q.withCorrections.Clone(), + withAllocation: _q.withAllocation.Clone(), + withRun: _q.withRun.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithCorrections tells the query-builder to eager-load the nodes that are connected to +// the "corrections" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) WithCorrections(opts ...func(*ChargeUsageBasedRunCreditAllocationsQuery)) *ChargeUsageBasedRunCreditAllocationsQuery { + query := (&ChargeUsageBasedRunCreditAllocationsClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCorrections = query + return _q +} + +// WithAllocation tells the query-builder to eager-load the nodes that are connected to +// the "allocation" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) WithAllocation(opts ...func(*ChargeUsageBasedRunCreditAllocationsQuery)) *ChargeUsageBasedRunCreditAllocationsQuery { + query := (&ChargeUsageBasedRunCreditAllocationsClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withAllocation = query + return _q +} + +// 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 = [3]bool{ + _q.withCorrections != nil, + _q.withAllocation != nil, + _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.withCorrections; query != nil { + if err := _q.loadCorrections(ctx, query, nodes, + func(n *ChargeUsageBasedRunCreditAllocations) { + n.Edges.Corrections = []*ChargeUsageBasedRunCreditAllocations{} + }, + func(n *ChargeUsageBasedRunCreditAllocations, e *ChargeUsageBasedRunCreditAllocations) { + n.Edges.Corrections = append(n.Edges.Corrections, e) + }); err != nil { + return nil, err + } + } + if query := _q.withAllocation; query != nil { + if err := _q.loadAllocation(ctx, query, nodes, nil, + func(n *ChargeUsageBasedRunCreditAllocations, e *ChargeUsageBasedRunCreditAllocations) { + n.Edges.Allocation = e + }); err != nil { + return nil, err + } + } + 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) loadCorrections(ctx context.Context, query *ChargeUsageBasedRunCreditAllocationsQuery, nodes []*ChargeUsageBasedRunCreditAllocations, init func(*ChargeUsageBasedRunCreditAllocations), assign func(*ChargeUsageBasedRunCreditAllocations, *ChargeUsageBasedRunCreditAllocations)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*ChargeUsageBasedRunCreditAllocations) + 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.FieldCorrectsRealizationID) + } + query.Where(predicate.ChargeUsageBasedRunCreditAllocations(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargeusagebasedruncreditallocations.CorrectionsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.CorrectsRealizationID + if fk == nil { + return fmt.Errorf(`foreign-key "corrects_realization_id" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "corrects_realization_id" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) loadAllocation(ctx context.Context, query *ChargeUsageBasedRunCreditAllocationsQuery, nodes []*ChargeUsageBasedRunCreditAllocations, init func(*ChargeUsageBasedRunCreditAllocations), assign func(*ChargeUsageBasedRunCreditAllocations, *ChargeUsageBasedRunCreditAllocations)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBasedRunCreditAllocations) + for i := range nodes { + if nodes[i].CorrectsRealizationID == nil { + continue + } + fk := *nodes[i].CorrectsRealizationID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(chargeusagebasedruncreditallocations.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 "corrects_realization_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return 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.withAllocation != nil { + _spec.Node.AddColumnOnce(chargeusagebasedruncreditallocations.FieldCorrectsRealizationID) + } + 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/ent/db/chargeusagebasedruncreditallocations_update.go b/ent/db/chargeusagebasedruncreditallocations_update.go new file mode 100644 index 0000000000000000000000000000000000000000..ea9bbc1fafab4885a3c0d521e3b5ec417c856ca3 --- /dev/null +++ b/ent/db/chargeusagebasedruncreditallocations_update.go @@ -0,0 +1,862 @@ +// 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 +} + +// SetSortHint sets the "sort_hint" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) SetSortHint(v int) *ChargeUsageBasedRunCreditAllocationsUpdate { + _u.mutation.ResetSortHint() + _u.mutation.SetSortHint(v) + return _u +} + +// SetNillableSortHint sets the "sort_hint" field if the given value is not nil. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) SetNillableSortHint(v *int) *ChargeUsageBasedRunCreditAllocationsUpdate { + if v != nil { + _u.SetSortHint(*v) + } + return _u +} + +// AddSortHint adds value to the "sort_hint" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) AddSortHint(v int) *ChargeUsageBasedRunCreditAllocationsUpdate { + _u.mutation.AddSortHint(v) + return _u +} + +// SetCorrectsRealizationID sets the "corrects_realization_id" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) SetCorrectsRealizationID(v string) *ChargeUsageBasedRunCreditAllocationsUpdate { + _u.mutation.SetCorrectsRealizationID(v) + return _u +} + +// SetNillableCorrectsRealizationID sets the "corrects_realization_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) SetNillableCorrectsRealizationID(v *string) *ChargeUsageBasedRunCreditAllocationsUpdate { + if v != nil { + _u.SetCorrectsRealizationID(*v) + } + return _u +} + +// ClearCorrectsRealizationID clears the value of the "corrects_realization_id" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) ClearCorrectsRealizationID() *ChargeUsageBasedRunCreditAllocationsUpdate { + _u.mutation.ClearCorrectsRealizationID() + 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 +} + +// AddCorrectionIDs adds the "corrections" edge to the ChargeUsageBasedRunCreditAllocations entity by IDs. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) AddCorrectionIDs(ids ...string) *ChargeUsageBasedRunCreditAllocationsUpdate { + _u.mutation.AddCorrectionIDs(ids...) + return _u +} + +// AddCorrections adds the "corrections" edges to the ChargeUsageBasedRunCreditAllocations entity. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) AddCorrections(v ...*ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunCreditAllocationsUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddCorrectionIDs(ids...) +} + +// SetAllocationID sets the "allocation" edge to the ChargeUsageBasedRunCreditAllocations entity by ID. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) SetAllocationID(id string) *ChargeUsageBasedRunCreditAllocationsUpdate { + _u.mutation.SetAllocationID(id) + return _u +} + +// SetNillableAllocationID sets the "allocation" edge to the ChargeUsageBasedRunCreditAllocations entity by ID if the given value is not nil. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) SetNillableAllocationID(id *string) *ChargeUsageBasedRunCreditAllocationsUpdate { + if id != nil { + _u = _u.SetAllocationID(*id) + } + return _u +} + +// SetAllocation sets the "allocation" edge to the ChargeUsageBasedRunCreditAllocations entity. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) SetAllocation(v *ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunCreditAllocationsUpdate { + return _u.SetAllocationID(v.ID) +} + +// Mutation returns the ChargeUsageBasedRunCreditAllocationsMutation object of the builder. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) Mutation() *ChargeUsageBasedRunCreditAllocationsMutation { + return _u.mutation +} + +// ClearCorrections clears all "corrections" edges to the ChargeUsageBasedRunCreditAllocations entity. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) ClearCorrections() *ChargeUsageBasedRunCreditAllocationsUpdate { + _u.mutation.ClearCorrections() + return _u +} + +// RemoveCorrectionIDs removes the "corrections" edge to ChargeUsageBasedRunCreditAllocations entities by IDs. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) RemoveCorrectionIDs(ids ...string) *ChargeUsageBasedRunCreditAllocationsUpdate { + _u.mutation.RemoveCorrectionIDs(ids...) + return _u +} + +// RemoveCorrections removes "corrections" edges to ChargeUsageBasedRunCreditAllocations entities. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) RemoveCorrections(v ...*ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunCreditAllocationsUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveCorrectionIDs(ids...) +} + +// ClearAllocation clears the "allocation" edge to the ChargeUsageBasedRunCreditAllocations entity. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) ClearAllocation() *ChargeUsageBasedRunCreditAllocationsUpdate { + _u.mutation.ClearAllocation() + return _u +} + +// 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 v, ok := _u.mutation.CorrectsRealizationID(); ok { + if err := chargeusagebasedruncreditallocations.CorrectsRealizationIDValidator(v); err != nil { + return &ValidationError{Name: "corrects_realization_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunCreditAllocations.corrects_realization_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.SortHint(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldSortHint, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedSortHint(); ok { + _spec.AddField(chargeusagebasedruncreditallocations.FieldSortHint, field.TypeInt, 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 _u.mutation.CorrectionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: chargeusagebasedruncreditallocations.CorrectionsTable, + Columns: []string{chargeusagebasedruncreditallocations.CorrectionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruncreditallocations.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedCorrectionsIDs(); len(nodes) > 0 && !_u.mutation.CorrectionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: chargeusagebasedruncreditallocations.CorrectionsTable, + Columns: []string{chargeusagebasedruncreditallocations.CorrectionsColumn}, + 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.CorrectionsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: chargeusagebasedruncreditallocations.CorrectionsTable, + Columns: []string{chargeusagebasedruncreditallocations.CorrectionsColumn}, + 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.AllocationCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: chargeusagebasedruncreditallocations.AllocationTable, + Columns: []string{chargeusagebasedruncreditallocations.AllocationColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruncreditallocations.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.AllocationIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: chargeusagebasedruncreditallocations.AllocationTable, + Columns: []string{chargeusagebasedruncreditallocations.AllocationColumn}, + 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 _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 +} + +// SetSortHint sets the "sort_hint" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetSortHint(v int) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.mutation.ResetSortHint() + _u.mutation.SetSortHint(v) + return _u +} + +// SetNillableSortHint sets the "sort_hint" field if the given value is not nil. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetNillableSortHint(v *int) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + if v != nil { + _u.SetSortHint(*v) + } + return _u +} + +// AddSortHint adds value to the "sort_hint" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) AddSortHint(v int) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.mutation.AddSortHint(v) + return _u +} + +// SetCorrectsRealizationID sets the "corrects_realization_id" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetCorrectsRealizationID(v string) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.mutation.SetCorrectsRealizationID(v) + return _u +} + +// SetNillableCorrectsRealizationID sets the "corrects_realization_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetNillableCorrectsRealizationID(v *string) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + if v != nil { + _u.SetCorrectsRealizationID(*v) + } + return _u +} + +// ClearCorrectsRealizationID clears the value of the "corrects_realization_id" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) ClearCorrectsRealizationID() *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.mutation.ClearCorrectsRealizationID() + 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 +} + +// AddCorrectionIDs adds the "corrections" edge to the ChargeUsageBasedRunCreditAllocations entity by IDs. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) AddCorrectionIDs(ids ...string) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.mutation.AddCorrectionIDs(ids...) + return _u +} + +// AddCorrections adds the "corrections" edges to the ChargeUsageBasedRunCreditAllocations entity. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) AddCorrections(v ...*ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddCorrectionIDs(ids...) +} + +// SetAllocationID sets the "allocation" edge to the ChargeUsageBasedRunCreditAllocations entity by ID. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetAllocationID(id string) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.mutation.SetAllocationID(id) + return _u +} + +// SetNillableAllocationID sets the "allocation" edge to the ChargeUsageBasedRunCreditAllocations entity by ID if the given value is not nil. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetNillableAllocationID(id *string) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + if id != nil { + _u = _u.SetAllocationID(*id) + } + return _u +} + +// SetAllocation sets the "allocation" edge to the ChargeUsageBasedRunCreditAllocations entity. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetAllocation(v *ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + return _u.SetAllocationID(v.ID) +} + +// Mutation returns the ChargeUsageBasedRunCreditAllocationsMutation object of the builder. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) Mutation() *ChargeUsageBasedRunCreditAllocationsMutation { + return _u.mutation +} + +// ClearCorrections clears all "corrections" edges to the ChargeUsageBasedRunCreditAllocations entity. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) ClearCorrections() *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.mutation.ClearCorrections() + return _u +} + +// RemoveCorrectionIDs removes the "corrections" edge to ChargeUsageBasedRunCreditAllocations entities by IDs. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) RemoveCorrectionIDs(ids ...string) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.mutation.RemoveCorrectionIDs(ids...) + return _u +} + +// RemoveCorrections removes "corrections" edges to ChargeUsageBasedRunCreditAllocations entities. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) RemoveCorrections(v ...*ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveCorrectionIDs(ids...) +} + +// ClearAllocation clears the "allocation" edge to the ChargeUsageBasedRunCreditAllocations entity. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) ClearAllocation() *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.mutation.ClearAllocation() + return _u +} + +// 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 v, ok := _u.mutation.CorrectsRealizationID(); ok { + if err := chargeusagebasedruncreditallocations.CorrectsRealizationIDValidator(v); err != nil { + return &ValidationError{Name: "corrects_realization_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunCreditAllocations.corrects_realization_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.SortHint(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldSortHint, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedSortHint(); ok { + _spec.AddField(chargeusagebasedruncreditallocations.FieldSortHint, field.TypeInt, 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 _u.mutation.CorrectionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: chargeusagebasedruncreditallocations.CorrectionsTable, + Columns: []string{chargeusagebasedruncreditallocations.CorrectionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruncreditallocations.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedCorrectionsIDs(); len(nodes) > 0 && !_u.mutation.CorrectionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: chargeusagebasedruncreditallocations.CorrectionsTable, + Columns: []string{chargeusagebasedruncreditallocations.CorrectionsColumn}, + 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.CorrectionsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: chargeusagebasedruncreditallocations.CorrectionsTable, + Columns: []string{chargeusagebasedruncreditallocations.CorrectionsColumn}, + 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.AllocationCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: chargeusagebasedruncreditallocations.AllocationTable, + Columns: []string{chargeusagebasedruncreditallocations.AllocationColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruncreditallocations.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.AllocationIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: chargeusagebasedruncreditallocations.AllocationTable, + Columns: []string{chargeusagebasedruncreditallocations.AllocationColumn}, + 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) + } + _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/ent/db/chargeusagebasedrundetailedline.go b/ent/db/chargeusagebasedrundetailedline.go new file mode 100644 index 0000000000000000000000000000000000000000..643c62d1b404c3923ff265f87af037dfc40a05a0 --- /dev/null +++ b/ent/db/chargeusagebasedrundetailedline.go @@ -0,0 +1,538 @@ +// 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/models/creditsapplied" + "github.com/openmeterio/openmeter/openmeter/billing/models/stddetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrundetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeUsageBasedRunDetailedLine is the model entity for the ChargeUsageBasedRunDetailedLine schema. +type ChargeUsageBasedRunDetailedLine struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // Currency holds the value of the "currency" field. + Currency currencyx.Code `json:"currency,omitempty"` + // ServicePeriodStart holds the value of the "service_period_start" field. + ServicePeriodStart time.Time `json:"service_period_start,omitempty"` + // ServicePeriodEnd holds the value of the "service_period_end" field. + ServicePeriodEnd time.Time `json:"service_period_end,omitempty"` + // Quantity holds the value of the "quantity" field. + Quantity alpacadecimal.Decimal `json:"quantity,omitempty"` + // InvoicingAppExternalID holds the value of the "invoicing_app_external_id" field. + InvoicingAppExternalID *string `json:"invoicing_app_external_id,omitempty"` + // ChildUniqueReferenceID holds the value of the "child_unique_reference_id" field. + ChildUniqueReferenceID string `json:"child_unique_reference_id,omitempty"` + // PerUnitAmount holds the value of the "per_unit_amount" field. + PerUnitAmount alpacadecimal.Decimal `json:"per_unit_amount,omitempty"` + // Category holds the value of the "category" field. + Category stddetailedline.Category `json:"category,omitempty"` + // PaymentTerm holds the value of the "payment_term" field. + PaymentTerm productcatalog.PaymentTermType `json:"payment_term,omitempty"` + // Index holds the value of the "index" field. + Index *int `json:"index,omitempty"` + // CreditsApplied holds the value of the "credits_applied" field. + CreditsApplied *creditsapplied.CreditsApplied `json:"credits_applied,omitempty"` + // Annotations holds the value of the "annotations" field. + // + // Deprecated: Field "annotations" was marked as deprecated in the schema. + Annotations models.Annotations `json:"annotations,omitempty"` + // Namespace holds the value of the "namespace" field. + Namespace string `json:"namespace,omitempty"` + // Metadata holds the value of the "metadata" field. + // + // Deprecated: Field "metadata" was marked as deprecated in the schema. + Metadata map[string]string `json:"metadata,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"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Description holds the value of the "description" field. + Description *string `json:"description,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"` + // ChargeID holds the value of the "charge_id" field. + ChargeID string `json:"charge_id,omitempty"` + // RunID holds the value of the "run_id" field. + RunID string `json:"run_id,omitempty"` + // PricerReferenceID holds the value of the "pricer_reference_id" field. + PricerReferenceID string `json:"pricer_reference_id,omitempty"` + // CorrectsRunID holds the value of the "corrects_run_id" field. + CorrectsRunID *string `json:"corrects_run_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ChargeUsageBasedRunDetailedLineQuery when eager-loading is set. + Edges ChargeUsageBasedRunDetailedLineEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ChargeUsageBasedRunDetailedLineEdges holds the relations/edges for other nodes in the graph. +type ChargeUsageBasedRunDetailedLineEdges struct { + // Charge holds the value of the charge edge. + Charge *ChargeUsageBased `json:"charge,omitempty"` + // Run holds the value of the run edge. + Run *ChargeUsageBasedRuns `json:"run,omitempty"` + // CorrectsRun holds the value of the corrects_run edge. + CorrectsRun *ChargeUsageBasedRuns `json:"corrects_run,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [3]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 ChargeUsageBasedRunDetailedLineEdges) ChargeOrErr() (*ChargeUsageBased, error) { + if e.Charge != nil { + return e.Charge, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: chargeusagebased.Label} + } + return nil, &NotLoadedError{edge: "charge"} +} + +// 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 ChargeUsageBasedRunDetailedLineEdges) RunOrErr() (*ChargeUsageBasedRuns, error) { + if e.Run != nil { + return e.Run, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: chargeusagebasedruns.Label} + } + return nil, &NotLoadedError{edge: "run"} +} + +// CorrectsRunOrErr returns the CorrectsRun value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedRunDetailedLineEdges) CorrectsRunOrErr() (*ChargeUsageBasedRuns, error) { + if e.CorrectsRun != nil { + return e.CorrectsRun, nil + } else if e.loadedTypes[2] { + return nil, &NotFoundError{label: chargeusagebasedruns.Label} + } + return nil, &NotLoadedError{edge: "corrects_run"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ChargeUsageBasedRunDetailedLine) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case chargeusagebasedrundetailedline.FieldCreditsApplied, chargeusagebasedrundetailedline.FieldAnnotations, chargeusagebasedrundetailedline.FieldMetadata: + values[i] = new([]byte) + case chargeusagebasedrundetailedline.FieldQuantity, chargeusagebasedrundetailedline.FieldPerUnitAmount, chargeusagebasedrundetailedline.FieldAmount, chargeusagebasedrundetailedline.FieldTaxesTotal, chargeusagebasedrundetailedline.FieldTaxesInclusiveTotal, chargeusagebasedrundetailedline.FieldTaxesExclusiveTotal, chargeusagebasedrundetailedline.FieldChargesTotal, chargeusagebasedrundetailedline.FieldDiscountsTotal, chargeusagebasedrundetailedline.FieldCreditsTotal, chargeusagebasedrundetailedline.FieldTotal: + values[i] = new(alpacadecimal.Decimal) + case chargeusagebasedrundetailedline.FieldIndex: + values[i] = new(sql.NullInt64) + case chargeusagebasedrundetailedline.FieldID, chargeusagebasedrundetailedline.FieldCurrency, chargeusagebasedrundetailedline.FieldInvoicingAppExternalID, chargeusagebasedrundetailedline.FieldChildUniqueReferenceID, chargeusagebasedrundetailedline.FieldCategory, chargeusagebasedrundetailedline.FieldPaymentTerm, chargeusagebasedrundetailedline.FieldNamespace, chargeusagebasedrundetailedline.FieldName, chargeusagebasedrundetailedline.FieldDescription, chargeusagebasedrundetailedline.FieldChargeID, chargeusagebasedrundetailedline.FieldRunID, chargeusagebasedrundetailedline.FieldPricerReferenceID, chargeusagebasedrundetailedline.FieldCorrectsRunID: + values[i] = new(sql.NullString) + case chargeusagebasedrundetailedline.FieldServicePeriodStart, chargeusagebasedrundetailedline.FieldServicePeriodEnd, chargeusagebasedrundetailedline.FieldCreatedAt, chargeusagebasedrundetailedline.FieldUpdatedAt, chargeusagebasedrundetailedline.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 ChargeUsageBasedRunDetailedLine fields. +func (_m *ChargeUsageBasedRunDetailedLine) 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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.FieldCurrency: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field currency", values[i]) + } else if value.Valid { + _m.Currency = currencyx.Code(value.String) + } + case chargeusagebasedrundetailedline.FieldServicePeriodStart: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field service_period_start", values[i]) + } else if value.Valid { + _m.ServicePeriodStart = value.Time + } + case chargeusagebasedrundetailedline.FieldServicePeriodEnd: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field service_period_end", values[i]) + } else if value.Valid { + _m.ServicePeriodEnd = value.Time + } + case chargeusagebasedrundetailedline.FieldQuantity: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field quantity", values[i]) + } else if value != nil { + _m.Quantity = *value + } + case chargeusagebasedrundetailedline.FieldInvoicingAppExternalID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field invoicing_app_external_id", values[i]) + } else if value.Valid { + _m.InvoicingAppExternalID = new(string) + *_m.InvoicingAppExternalID = value.String + } + case chargeusagebasedrundetailedline.FieldChildUniqueReferenceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field child_unique_reference_id", values[i]) + } else if value.Valid { + _m.ChildUniqueReferenceID = value.String + } + case chargeusagebasedrundetailedline.FieldPerUnitAmount: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field per_unit_amount", values[i]) + } else if value != nil { + _m.PerUnitAmount = *value + } + case chargeusagebasedrundetailedline.FieldCategory: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field category", values[i]) + } else if value.Valid { + _m.Category = stddetailedline.Category(value.String) + } + case chargeusagebasedrundetailedline.FieldPaymentTerm: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field payment_term", values[i]) + } else if value.Valid { + _m.PaymentTerm = productcatalog.PaymentTermType(value.String) + } + case chargeusagebasedrundetailedline.FieldIndex: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field index", values[i]) + } else if value.Valid { + _m.Index = new(int) + *_m.Index = int(value.Int64) + } + case chargeusagebasedrundetailedline.FieldCreditsApplied: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field credits_applied", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.CreditsApplied); err != nil { + return fmt.Errorf("unmarshal field credits_applied: %w", err) + } + } + case chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.FieldMetadata: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field metadata", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Metadata); err != nil { + return fmt.Errorf("unmarshal field metadata: %w", err) + } + } + case chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case chargeusagebasedrundetailedline.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + _m.Description = new(string) + *_m.Description = value.String + } + case chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 + } + case chargeusagebasedrundetailedline.FieldPricerReferenceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field pricer_reference_id", values[i]) + } else if value.Valid { + _m.PricerReferenceID = value.String + } + case chargeusagebasedrundetailedline.FieldCorrectsRunID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field corrects_run_id", values[i]) + } else if value.Valid { + _m.CorrectsRunID = new(string) + *_m.CorrectsRunID = 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 ChargeUsageBasedRunDetailedLine. +// This includes values selected through modifiers, order, etc. +func (_m *ChargeUsageBasedRunDetailedLine) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryCharge queries the "charge" edge of the ChargeUsageBasedRunDetailedLine entity. +func (_m *ChargeUsageBasedRunDetailedLine) QueryCharge() *ChargeUsageBasedQuery { + return NewChargeUsageBasedRunDetailedLineClient(_m.config).QueryCharge(_m) +} + +// QueryRun queries the "run" edge of the ChargeUsageBasedRunDetailedLine entity. +func (_m *ChargeUsageBasedRunDetailedLine) QueryRun() *ChargeUsageBasedRunsQuery { + return NewChargeUsageBasedRunDetailedLineClient(_m.config).QueryRun(_m) +} + +// QueryCorrectsRun queries the "corrects_run" edge of the ChargeUsageBasedRunDetailedLine entity. +func (_m *ChargeUsageBasedRunDetailedLine) QueryCorrectsRun() *ChargeUsageBasedRunsQuery { + return NewChargeUsageBasedRunDetailedLineClient(_m.config).QueryCorrectsRun(_m) +} + +// Update returns a builder for updating this ChargeUsageBasedRunDetailedLine. +// Note that you need to call ChargeUsageBasedRunDetailedLine.Unwrap() before calling this method if this ChargeUsageBasedRunDetailedLine +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ChargeUsageBasedRunDetailedLine) Update() *ChargeUsageBasedRunDetailedLineUpdateOne { + return NewChargeUsageBasedRunDetailedLineClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLine) Unwrap() *ChargeUsageBasedRunDetailedLine { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: ChargeUsageBasedRunDetailedLine is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ChargeUsageBasedRunDetailedLine) String() string { + var builder strings.Builder + builder.WriteString("ChargeUsageBasedRunDetailedLine(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("currency=") + builder.WriteString(fmt.Sprintf("%v", _m.Currency)) + builder.WriteString(", ") + builder.WriteString("service_period_start=") + builder.WriteString(_m.ServicePeriodStart.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("service_period_end=") + builder.WriteString(_m.ServicePeriodEnd.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("quantity=") + builder.WriteString(fmt.Sprintf("%v", _m.Quantity)) + builder.WriteString(", ") + if v := _m.InvoicingAppExternalID; v != nil { + builder.WriteString("invoicing_app_external_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("child_unique_reference_id=") + builder.WriteString(_m.ChildUniqueReferenceID) + builder.WriteString(", ") + builder.WriteString("per_unit_amount=") + builder.WriteString(fmt.Sprintf("%v", _m.PerUnitAmount)) + builder.WriteString(", ") + builder.WriteString("category=") + builder.WriteString(fmt.Sprintf("%v", _m.Category)) + builder.WriteString(", ") + builder.WriteString("payment_term=") + builder.WriteString(fmt.Sprintf("%v", _m.PaymentTerm)) + builder.WriteString(", ") + if v := _m.Index; v != nil { + builder.WriteString("index=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + builder.WriteString("credits_applied=") + builder.WriteString(fmt.Sprintf("%v", _m.CreditsApplied)) + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + builder.WriteString(", ") + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("metadata=") + builder.WriteString(fmt.Sprintf("%v", _m.Metadata)) + 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("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + if v := _m.Description; v != nil { + builder.WriteString("description=") + builder.WriteString(*v) + } + 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("charge_id=") + builder.WriteString(_m.ChargeID) + builder.WriteString(", ") + builder.WriteString("run_id=") + builder.WriteString(_m.RunID) + builder.WriteString(", ") + builder.WriteString("pricer_reference_id=") + builder.WriteString(_m.PricerReferenceID) + builder.WriteString(", ") + if v := _m.CorrectsRunID; v != nil { + builder.WriteString("corrects_run_id=") + builder.WriteString(*v) + } + builder.WriteByte(')') + return builder.String() +} + +// ChargeUsageBasedRunDetailedLines is a parsable slice of ChargeUsageBasedRunDetailedLine. +type ChargeUsageBasedRunDetailedLines []*ChargeUsageBasedRunDetailedLine diff --git a/ent/db/chargeusagebasedrundetailedline/chargeusagebasedrundetailedline.go b/ent/db/chargeusagebasedrundetailedline/chargeusagebasedrundetailedline.go new file mode 100644 index 0000000000000000000000000000000000000000..f30d5138078272136fbda2d4de5e1f76a7a4a947 --- /dev/null +++ b/ent/db/chargeusagebasedrundetailedline/chargeusagebasedrundetailedline.go @@ -0,0 +1,395 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeusagebasedrundetailedline + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/billing/models/stddetailedline" + "github.com/openmeterio/openmeter/openmeter/productcatalog" +) + +const ( + // Label holds the string label denoting the chargeusagebasedrundetailedline type in the database. + Label = "charge_usage_based_run_detailed_line" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldCurrency holds the string denoting the currency field in the database. + FieldCurrency = "currency" + // FieldServicePeriodStart holds the string denoting the service_period_start field in the database. + FieldServicePeriodStart = "service_period_start" + // FieldServicePeriodEnd holds the string denoting the service_period_end field in the database. + FieldServicePeriodEnd = "service_period_end" + // FieldQuantity holds the string denoting the quantity field in the database. + FieldQuantity = "quantity" + // FieldInvoicingAppExternalID holds the string denoting the invoicing_app_external_id field in the database. + FieldInvoicingAppExternalID = "invoicing_app_external_id" + // FieldChildUniqueReferenceID holds the string denoting the child_unique_reference_id field in the database. + FieldChildUniqueReferenceID = "child_unique_reference_id" + // FieldPerUnitAmount holds the string denoting the per_unit_amount field in the database. + FieldPerUnitAmount = "per_unit_amount" + // FieldCategory holds the string denoting the category field in the database. + FieldCategory = "category" + // FieldPaymentTerm holds the string denoting the payment_term field in the database. + FieldPaymentTerm = "payment_term" + // FieldIndex holds the string denoting the index field in the database. + FieldIndex = "index" + // FieldCreditsApplied holds the string denoting the credits_applied field in the database. + FieldCreditsApplied = "credits_applied" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // FieldNamespace holds the string denoting the namespace field in the database. + FieldNamespace = "namespace" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // 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" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // 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" + // FieldChargeID holds the string denoting the charge_id field in the database. + FieldChargeID = "charge_id" + // FieldRunID holds the string denoting the run_id field in the database. + FieldRunID = "run_id" + // FieldPricerReferenceID holds the string denoting the pricer_reference_id field in the database. + FieldPricerReferenceID = "pricer_reference_id" + // FieldCorrectsRunID holds the string denoting the corrects_run_id field in the database. + FieldCorrectsRunID = "corrects_run_id" + // EdgeCharge holds the string denoting the charge edge name in mutations. + EdgeCharge = "charge" + // EdgeRun holds the string denoting the run edge name in mutations. + EdgeRun = "run" + // EdgeCorrectsRun holds the string denoting the corrects_run edge name in mutations. + EdgeCorrectsRun = "corrects_run" + // Table holds the table name of the chargeusagebasedrundetailedline in the database. + Table = "charge_usage_based_run_detailed_line" + // ChargeTable is the table that holds the charge relation/edge. + ChargeTable = "charge_usage_based_run_detailed_line" + // ChargeInverseTable is the table name for the ChargeUsageBased entity. + // It exists in this package in order to avoid circular dependency with the "chargeusagebased" package. + ChargeInverseTable = "charge_usage_based" + // ChargeColumn is the table column denoting the charge relation/edge. + ChargeColumn = "charge_id" + // RunTable is the table that holds the run relation/edge. + RunTable = "charge_usage_based_run_detailed_line" + // 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" + // CorrectsRunTable is the table that holds the corrects_run relation/edge. + CorrectsRunTable = "charge_usage_based_run_detailed_line" + // CorrectsRunInverseTable is the table name for the ChargeUsageBasedRuns entity. + // It exists in this package in order to avoid circular dependency with the "chargeusagebasedruns" package. + CorrectsRunInverseTable = "charge_usage_based_runs" + // CorrectsRunColumn is the table column denoting the corrects_run relation/edge. + CorrectsRunColumn = "corrects_run_id" +) + +// Columns holds all SQL columns for chargeusagebasedrundetailedline fields. +var Columns = []string{ + FieldID, + FieldCurrency, + FieldServicePeriodStart, + FieldServicePeriodEnd, + FieldQuantity, + FieldInvoicingAppExternalID, + FieldChildUniqueReferenceID, + FieldPerUnitAmount, + FieldCategory, + FieldPaymentTerm, + FieldIndex, + FieldCreditsApplied, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldName, + FieldDescription, + FieldAmount, + FieldTaxesTotal, + FieldTaxesInclusiveTotal, + FieldTaxesExclusiveTotal, + FieldChargesTotal, + FieldDiscountsTotal, + FieldCreditsTotal, + FieldTotal, + FieldChargeID, + FieldRunID, + FieldPricerReferenceID, + FieldCorrectsRunID, +} + +// 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 + } + } + for _, f := range [...]string{FieldAnnotations, FieldMetadata} { + if column == f { + return true + } + } + return false +} + +var ( + // CurrencyValidator is a validator for the "currency" field. It is called by the builders before save. + CurrencyValidator func(string) error + // ChildUniqueReferenceIDValidator is a validator for the "child_unique_reference_id" field. It is called by the builders before save. + ChildUniqueReferenceIDValidator 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 + // PricerReferenceIDValidator is a validator for the "pricer_reference_id" field. It is called by the builders before save. + PricerReferenceIDValidator func(string) error + // CorrectsRunIDValidator is a validator for the "corrects_run_id" field. It is called by the builders before save. + CorrectsRunIDValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +const DefaultCategory stddetailedline.Category = "regular" + +// CategoryValidator is a validator for the "category" field enum values. It is called by the builders before save. +func CategoryValidator(c stddetailedline.Category) error { + switch c { + case "regular", "commitment": + return nil + default: + return fmt.Errorf("chargeusagebasedrundetailedline: invalid enum value for category field: %q", c) + } +} + +const DefaultPaymentTerm productcatalog.PaymentTermType = "in_advance" + +// PaymentTermValidator is a validator for the "payment_term" field enum values. It is called by the builders before save. +func PaymentTermValidator(pt productcatalog.PaymentTermType) error { + switch pt { + case "in_advance", "in_arrears": + return nil + default: + return fmt.Errorf("chargeusagebasedrundetailedline: invalid enum value for payment_term field: %q", pt) + } +} + +// OrderOption defines the ordering options for the ChargeUsageBasedRunDetailedLine 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() +} + +// ByCurrency orders the results by the currency field. +func ByCurrency(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCurrency, opts...).ToFunc() +} + +// ByServicePeriodStart orders the results by the service_period_start field. +func ByServicePeriodStart(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldServicePeriodStart, opts...).ToFunc() +} + +// ByServicePeriodEnd orders the results by the service_period_end field. +func ByServicePeriodEnd(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldServicePeriodEnd, opts...).ToFunc() +} + +// ByQuantity orders the results by the quantity field. +func ByQuantity(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldQuantity, opts...).ToFunc() +} + +// ByInvoicingAppExternalID orders the results by the invoicing_app_external_id field. +func ByInvoicingAppExternalID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoicingAppExternalID, opts...).ToFunc() +} + +// ByChildUniqueReferenceID orders the results by the child_unique_reference_id field. +func ByChildUniqueReferenceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChildUniqueReferenceID, opts...).ToFunc() +} + +// ByPerUnitAmount orders the results by the per_unit_amount field. +func ByPerUnitAmount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPerUnitAmount, opts...).ToFunc() +} + +// ByCategory orders the results by the category field. +func ByCategory(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCategory, opts...).ToFunc() +} + +// ByPaymentTerm orders the results by the payment_term field. +func ByPaymentTerm(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPaymentTerm, opts...).ToFunc() +} + +// ByIndex orders the results by the index field. +func ByIndex(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIndex, 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() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, 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() +} + +// ByChargeID orders the results by the charge_id field. +func ByChargeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChargeID, opts...).ToFunc() +} + +// ByRunID orders the results by the run_id field. +func ByRunID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRunID, opts...).ToFunc() +} + +// ByPricerReferenceID orders the results by the pricer_reference_id field. +func ByPricerReferenceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPricerReferenceID, opts...).ToFunc() +} + +// ByCorrectsRunID orders the results by the corrects_run_id field. +func ByCorrectsRunID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCorrectsRunID, 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...)) + } +} + +// 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...)) + } +} + +// ByCorrectsRunField orders the results by corrects_run field. +func ByCorrectsRunField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCorrectsRunStep(), sql.OrderByField(field, opts...)) + } +} +func newChargeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ChargeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ChargeTable, ChargeColumn), + ) +} +func newRunStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RunInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, RunTable, RunColumn), + ) +} +func newCorrectsRunStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CorrectsRunInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, CorrectsRunTable, CorrectsRunColumn), + ) +} diff --git a/ent/db/chargeusagebasedrundetailedline/where.go b/ent/db/chargeusagebasedrundetailedline/where.go new file mode 100644 index 0000000000000000000000000000000000000000..3b9b17aefbc6543809e8ab1f42da82aafbd5c82a --- /dev/null +++ b/ent/db/chargeusagebasedrundetailedline/where.go @@ -0,0 +1,1734 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeusagebasedrundetailedline + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/billing/models/stddetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContainsFold(FieldID, id)) +} + +// Currency applies equality check predicate on the "currency" field. It's identical to CurrencyEQ. +func Currency(v currencyx.Code) predicate.ChargeUsageBasedRunDetailedLine { + vc := string(v) + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldCurrency, vc)) +} + +// ServicePeriodStart applies equality check predicate on the "service_period_start" field. It's identical to ServicePeriodStartEQ. +func ServicePeriodStart(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldServicePeriodStart, v)) +} + +// ServicePeriodEnd applies equality check predicate on the "service_period_end" field. It's identical to ServicePeriodEndEQ. +func ServicePeriodEnd(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldServicePeriodEnd, v)) +} + +// Quantity applies equality check predicate on the "quantity" field. It's identical to QuantityEQ. +func Quantity(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldQuantity, v)) +} + +// InvoicingAppExternalID applies equality check predicate on the "invoicing_app_external_id" field. It's identical to InvoicingAppExternalIDEQ. +func InvoicingAppExternalID(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldInvoicingAppExternalID, v)) +} + +// ChildUniqueReferenceID applies equality check predicate on the "child_unique_reference_id" field. It's identical to ChildUniqueReferenceIDEQ. +func ChildUniqueReferenceID(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldChildUniqueReferenceID, v)) +} + +// PerUnitAmount applies equality check predicate on the "per_unit_amount" field. It's identical to PerUnitAmountEQ. +func PerUnitAmount(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldPerUnitAmount, v)) +} + +// Index applies equality check predicate on the "index" field. It's identical to IndexEQ. +func Index(v int) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldIndex, v)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(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.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(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.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(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.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldName, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldDescription, v)) +} + +// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ. +func Amount(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(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.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(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.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(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.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(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.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(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.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(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.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldCreditsTotal, v)) +} + +// Total applies equality check predicate on the "total" field. It's identical to TotalEQ. +func Total(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldTotal, v)) +} + +// ChargeID applies equality check predicate on the "charge_id" field. It's identical to ChargeIDEQ. +func ChargeID(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldChargeID, v)) +} + +// RunID applies equality check predicate on the "run_id" field. It's identical to RunIDEQ. +func RunID(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldRunID, v)) +} + +// PricerReferenceID applies equality check predicate on the "pricer_reference_id" field. It's identical to PricerReferenceIDEQ. +func PricerReferenceID(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldPricerReferenceID, v)) +} + +// CorrectsRunID applies equality check predicate on the "corrects_run_id" field. It's identical to CorrectsRunIDEQ. +func CorrectsRunID(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldCorrectsRunID, v)) +} + +// CurrencyEQ applies the EQ predicate on the "currency" field. +func CurrencyEQ(v currencyx.Code) predicate.ChargeUsageBasedRunDetailedLine { + vc := string(v) + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldCurrency, vc)) +} + +// CurrencyNEQ applies the NEQ predicate on the "currency" field. +func CurrencyNEQ(v currencyx.Code) predicate.ChargeUsageBasedRunDetailedLine { + vc := string(v) + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldCurrency, vc)) +} + +// CurrencyIn applies the In predicate on the "currency" field. +func CurrencyIn(vs ...currencyx.Code) predicate.ChargeUsageBasedRunDetailedLine { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldCurrency, v...)) +} + +// CurrencyNotIn applies the NotIn predicate on the "currency" field. +func CurrencyNotIn(vs ...currencyx.Code) predicate.ChargeUsageBasedRunDetailedLine { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldCurrency, v...)) +} + +// CurrencyGT applies the GT predicate on the "currency" field. +func CurrencyGT(v currencyx.Code) predicate.ChargeUsageBasedRunDetailedLine { + vc := string(v) + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldCurrency, vc)) +} + +// CurrencyGTE applies the GTE predicate on the "currency" field. +func CurrencyGTE(v currencyx.Code) predicate.ChargeUsageBasedRunDetailedLine { + vc := string(v) + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldCurrency, vc)) +} + +// CurrencyLT applies the LT predicate on the "currency" field. +func CurrencyLT(v currencyx.Code) predicate.ChargeUsageBasedRunDetailedLine { + vc := string(v) + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldCurrency, vc)) +} + +// CurrencyLTE applies the LTE predicate on the "currency" field. +func CurrencyLTE(v currencyx.Code) predicate.ChargeUsageBasedRunDetailedLine { + vc := string(v) + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldCurrency, vc)) +} + +// CurrencyContains applies the Contains predicate on the "currency" field. +func CurrencyContains(v currencyx.Code) predicate.ChargeUsageBasedRunDetailedLine { + vc := string(v) + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContains(FieldCurrency, vc)) +} + +// CurrencyHasPrefix applies the HasPrefix predicate on the "currency" field. +func CurrencyHasPrefix(v currencyx.Code) predicate.ChargeUsageBasedRunDetailedLine { + vc := string(v) + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldHasPrefix(FieldCurrency, vc)) +} + +// CurrencyHasSuffix applies the HasSuffix predicate on the "currency" field. +func CurrencyHasSuffix(v currencyx.Code) predicate.ChargeUsageBasedRunDetailedLine { + vc := string(v) + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldHasSuffix(FieldCurrency, vc)) +} + +// CurrencyEqualFold applies the EqualFold predicate on the "currency" field. +func CurrencyEqualFold(v currencyx.Code) predicate.ChargeUsageBasedRunDetailedLine { + vc := string(v) + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEqualFold(FieldCurrency, vc)) +} + +// CurrencyContainsFold applies the ContainsFold predicate on the "currency" field. +func CurrencyContainsFold(v currencyx.Code) predicate.ChargeUsageBasedRunDetailedLine { + vc := string(v) + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContainsFold(FieldCurrency, vc)) +} + +// ServicePeriodStartEQ applies the EQ predicate on the "service_period_start" field. +func ServicePeriodStartEQ(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldServicePeriodStart, v)) +} + +// ServicePeriodStartNEQ applies the NEQ predicate on the "service_period_start" field. +func ServicePeriodStartNEQ(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldServicePeriodStart, v)) +} + +// ServicePeriodStartIn applies the In predicate on the "service_period_start" field. +func ServicePeriodStartIn(vs ...time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldServicePeriodStart, vs...)) +} + +// ServicePeriodStartNotIn applies the NotIn predicate on the "service_period_start" field. +func ServicePeriodStartNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldServicePeriodStart, vs...)) +} + +// ServicePeriodStartGT applies the GT predicate on the "service_period_start" field. +func ServicePeriodStartGT(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldServicePeriodStart, v)) +} + +// ServicePeriodStartGTE applies the GTE predicate on the "service_period_start" field. +func ServicePeriodStartGTE(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldServicePeriodStart, v)) +} + +// ServicePeriodStartLT applies the LT predicate on the "service_period_start" field. +func ServicePeriodStartLT(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldServicePeriodStart, v)) +} + +// ServicePeriodStartLTE applies the LTE predicate on the "service_period_start" field. +func ServicePeriodStartLTE(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldServicePeriodStart, v)) +} + +// ServicePeriodEndEQ applies the EQ predicate on the "service_period_end" field. +func ServicePeriodEndEQ(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldServicePeriodEnd, v)) +} + +// ServicePeriodEndNEQ applies the NEQ predicate on the "service_period_end" field. +func ServicePeriodEndNEQ(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldServicePeriodEnd, v)) +} + +// ServicePeriodEndIn applies the In predicate on the "service_period_end" field. +func ServicePeriodEndIn(vs ...time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldServicePeriodEnd, vs...)) +} + +// ServicePeriodEndNotIn applies the NotIn predicate on the "service_period_end" field. +func ServicePeriodEndNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldServicePeriodEnd, vs...)) +} + +// ServicePeriodEndGT applies the GT predicate on the "service_period_end" field. +func ServicePeriodEndGT(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldServicePeriodEnd, v)) +} + +// ServicePeriodEndGTE applies the GTE predicate on the "service_period_end" field. +func ServicePeriodEndGTE(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldServicePeriodEnd, v)) +} + +// ServicePeriodEndLT applies the LT predicate on the "service_period_end" field. +func ServicePeriodEndLT(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldServicePeriodEnd, v)) +} + +// ServicePeriodEndLTE applies the LTE predicate on the "service_period_end" field. +func ServicePeriodEndLTE(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldServicePeriodEnd, v)) +} + +// QuantityEQ applies the EQ predicate on the "quantity" field. +func QuantityEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldQuantity, v)) +} + +// QuantityNEQ applies the NEQ predicate on the "quantity" field. +func QuantityNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldQuantity, v)) +} + +// QuantityIn applies the In predicate on the "quantity" field. +func QuantityIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldQuantity, vs...)) +} + +// QuantityNotIn applies the NotIn predicate on the "quantity" field. +func QuantityNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldQuantity, vs...)) +} + +// QuantityGT applies the GT predicate on the "quantity" field. +func QuantityGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldQuantity, v)) +} + +// QuantityGTE applies the GTE predicate on the "quantity" field. +func QuantityGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldQuantity, v)) +} + +// QuantityLT applies the LT predicate on the "quantity" field. +func QuantityLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldQuantity, v)) +} + +// QuantityLTE applies the LTE predicate on the "quantity" field. +func QuantityLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldQuantity, v)) +} + +// InvoicingAppExternalIDEQ applies the EQ predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDEQ(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDNEQ applies the NEQ predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDNEQ(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDIn applies the In predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDIn(vs ...string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldInvoicingAppExternalID, vs...)) +} + +// InvoicingAppExternalIDNotIn applies the NotIn predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDNotIn(vs ...string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldInvoicingAppExternalID, vs...)) +} + +// InvoicingAppExternalIDGT applies the GT predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDGT(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDGTE applies the GTE predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDGTE(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDLT applies the LT predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDLT(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDLTE applies the LTE predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDLTE(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDContains applies the Contains predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDContains(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContains(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDHasPrefix applies the HasPrefix predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDHasPrefix(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldHasPrefix(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDHasSuffix applies the HasSuffix predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDHasSuffix(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldHasSuffix(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDIsNil applies the IsNil predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDIsNil() predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIsNull(FieldInvoicingAppExternalID)) +} + +// InvoicingAppExternalIDNotNil applies the NotNil predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDNotNil() predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotNull(FieldInvoicingAppExternalID)) +} + +// InvoicingAppExternalIDEqualFold applies the EqualFold predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDEqualFold(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEqualFold(FieldInvoicingAppExternalID, v)) +} + +// InvoicingAppExternalIDContainsFold applies the ContainsFold predicate on the "invoicing_app_external_id" field. +func InvoicingAppExternalIDContainsFold(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContainsFold(FieldInvoicingAppExternalID, v)) +} + +// ChildUniqueReferenceIDEQ applies the EQ predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDEQ(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDNEQ applies the NEQ predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDNEQ(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDIn applies the In predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDIn(vs ...string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldChildUniqueReferenceID, vs...)) +} + +// ChildUniqueReferenceIDNotIn applies the NotIn predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDNotIn(vs ...string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldChildUniqueReferenceID, vs...)) +} + +// ChildUniqueReferenceIDGT applies the GT predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDGT(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDGTE applies the GTE predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDGTE(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDLT applies the LT predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDLT(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDLTE applies the LTE predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDLTE(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDContains applies the Contains predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDContains(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContains(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDHasPrefix applies the HasPrefix predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDHasPrefix(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldHasPrefix(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDHasSuffix applies the HasSuffix predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDHasSuffix(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldHasSuffix(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDEqualFold applies the EqualFold predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDEqualFold(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEqualFold(FieldChildUniqueReferenceID, v)) +} + +// ChildUniqueReferenceIDContainsFold applies the ContainsFold predicate on the "child_unique_reference_id" field. +func ChildUniqueReferenceIDContainsFold(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContainsFold(FieldChildUniqueReferenceID, v)) +} + +// PerUnitAmountEQ applies the EQ predicate on the "per_unit_amount" field. +func PerUnitAmountEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldPerUnitAmount, v)) +} + +// PerUnitAmountNEQ applies the NEQ predicate on the "per_unit_amount" field. +func PerUnitAmountNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldPerUnitAmount, v)) +} + +// PerUnitAmountIn applies the In predicate on the "per_unit_amount" field. +func PerUnitAmountIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldPerUnitAmount, vs...)) +} + +// PerUnitAmountNotIn applies the NotIn predicate on the "per_unit_amount" field. +func PerUnitAmountNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldPerUnitAmount, vs...)) +} + +// PerUnitAmountGT applies the GT predicate on the "per_unit_amount" field. +func PerUnitAmountGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldPerUnitAmount, v)) +} + +// PerUnitAmountGTE applies the GTE predicate on the "per_unit_amount" field. +func PerUnitAmountGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldPerUnitAmount, v)) +} + +// PerUnitAmountLT applies the LT predicate on the "per_unit_amount" field. +func PerUnitAmountLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldPerUnitAmount, v)) +} + +// PerUnitAmountLTE applies the LTE predicate on the "per_unit_amount" field. +func PerUnitAmountLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldPerUnitAmount, v)) +} + +// CategoryEQ applies the EQ predicate on the "category" field. +func CategoryEQ(v stddetailedline.Category) predicate.ChargeUsageBasedRunDetailedLine { + vc := v + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldCategory, vc)) +} + +// CategoryNEQ applies the NEQ predicate on the "category" field. +func CategoryNEQ(v stddetailedline.Category) predicate.ChargeUsageBasedRunDetailedLine { + vc := v + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldCategory, vc)) +} + +// CategoryIn applies the In predicate on the "category" field. +func CategoryIn(vs ...stddetailedline.Category) predicate.ChargeUsageBasedRunDetailedLine { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldCategory, v...)) +} + +// CategoryNotIn applies the NotIn predicate on the "category" field. +func CategoryNotIn(vs ...stddetailedline.Category) predicate.ChargeUsageBasedRunDetailedLine { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldCategory, v...)) +} + +// PaymentTermEQ applies the EQ predicate on the "payment_term" field. +func PaymentTermEQ(v productcatalog.PaymentTermType) predicate.ChargeUsageBasedRunDetailedLine { + vc := v + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldPaymentTerm, vc)) +} + +// PaymentTermNEQ applies the NEQ predicate on the "payment_term" field. +func PaymentTermNEQ(v productcatalog.PaymentTermType) predicate.ChargeUsageBasedRunDetailedLine { + vc := v + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldPaymentTerm, vc)) +} + +// PaymentTermIn applies the In predicate on the "payment_term" field. +func PaymentTermIn(vs ...productcatalog.PaymentTermType) predicate.ChargeUsageBasedRunDetailedLine { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldPaymentTerm, v...)) +} + +// PaymentTermNotIn applies the NotIn predicate on the "payment_term" field. +func PaymentTermNotIn(vs ...productcatalog.PaymentTermType) predicate.ChargeUsageBasedRunDetailedLine { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldPaymentTerm, v...)) +} + +// IndexEQ applies the EQ predicate on the "index" field. +func IndexEQ(v int) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldIndex, v)) +} + +// IndexNEQ applies the NEQ predicate on the "index" field. +func IndexNEQ(v int) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldIndex, v)) +} + +// IndexIn applies the In predicate on the "index" field. +func IndexIn(vs ...int) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldIndex, vs...)) +} + +// IndexNotIn applies the NotIn predicate on the "index" field. +func IndexNotIn(vs ...int) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldIndex, vs...)) +} + +// IndexGT applies the GT predicate on the "index" field. +func IndexGT(v int) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldIndex, v)) +} + +// IndexGTE applies the GTE predicate on the "index" field. +func IndexGTE(v int) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldIndex, v)) +} + +// IndexLT applies the LT predicate on the "index" field. +func IndexLT(v int) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldIndex, v)) +} + +// IndexLTE applies the LTE predicate on the "index" field. +func IndexLTE(v int) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldIndex, v)) +} + +// IndexIsNil applies the IsNil predicate on the "index" field. +func IndexIsNil() predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIsNull(FieldIndex)) +} + +// IndexNotNil applies the NotNil predicate on the "index" field. +func IndexNotNil() predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotNull(FieldIndex)) +} + +// CreditsAppliedIsNil applies the IsNil predicate on the "credits_applied" field. +func CreditsAppliedIsNil() predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIsNull(FieldCreditsApplied)) +} + +// CreditsAppliedNotNil applies the NotNil predicate on the "credits_applied" field. +func CreditsAppliedNotNil() predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotNull(FieldCreditsApplied)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotNull(FieldAnnotations)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContainsFold(FieldNamespace, v)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotNull(FieldMetadata)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotNull(FieldDeletedAt)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContainsFold(FieldName, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContainsFold(FieldDescription, v)) +} + +// AmountEQ applies the EQ predicate on the "amount" field. +func AmountEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldAmount, v)) +} + +// AmountNEQ applies the NEQ predicate on the "amount" field. +func AmountNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldAmount, v)) +} + +// AmountIn applies the In predicate on the "amount" field. +func AmountIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldAmount, vs...)) +} + +// AmountNotIn applies the NotIn predicate on the "amount" field. +func AmountNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldAmount, vs...)) +} + +// AmountGT applies the GT predicate on the "amount" field. +func AmountGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldAmount, v)) +} + +// AmountGTE applies the GTE predicate on the "amount" field. +func AmountGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldAmount, v)) +} + +// AmountLT applies the LT predicate on the "amount" field. +func AmountLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldAmount, v)) +} + +// AmountLTE applies the LTE predicate on the "amount" field. +func AmountLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldAmount, v)) +} + +// TaxesTotalEQ applies the EQ predicate on the "taxes_total" field. +func TaxesTotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldTaxesTotal, v)) +} + +// TaxesTotalNEQ applies the NEQ predicate on the "taxes_total" field. +func TaxesTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldTaxesTotal, v)) +} + +// TaxesTotalIn applies the In predicate on the "taxes_total" field. +func TaxesTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldTaxesTotal, vs...)) +} + +// TaxesTotalNotIn applies the NotIn predicate on the "taxes_total" field. +func TaxesTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldTaxesTotal, vs...)) +} + +// TaxesTotalGT applies the GT predicate on the "taxes_total" field. +func TaxesTotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldTaxesTotal, v)) +} + +// TaxesTotalGTE applies the GTE predicate on the "taxes_total" field. +func TaxesTotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldTaxesTotal, v)) +} + +// TaxesTotalLT applies the LT predicate on the "taxes_total" field. +func TaxesTotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldTaxesTotal, v)) +} + +// TaxesTotalLTE applies the LTE predicate on the "taxes_total" field. +func TaxesTotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldTaxesTotal, v)) +} + +// TaxesInclusiveTotalEQ applies the EQ predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalNEQ applies the NEQ predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalIn applies the In predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldTaxesInclusiveTotal, vs...)) +} + +// TaxesInclusiveTotalNotIn applies the NotIn predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldTaxesInclusiveTotal, vs...)) +} + +// TaxesInclusiveTotalGT applies the GT predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalGTE applies the GTE predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalLT applies the LT predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalLTE applies the LTE predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldTaxesInclusiveTotal, v)) +} + +// TaxesExclusiveTotalEQ applies the EQ predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalNEQ applies the NEQ predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalIn applies the In predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldTaxesExclusiveTotal, vs...)) +} + +// TaxesExclusiveTotalNotIn applies the NotIn predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldTaxesExclusiveTotal, vs...)) +} + +// TaxesExclusiveTotalGT applies the GT predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalGTE applies the GTE predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalLT applies the LT predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalLTE applies the LTE predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldTaxesExclusiveTotal, v)) +} + +// ChargesTotalEQ applies the EQ predicate on the "charges_total" field. +func ChargesTotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldChargesTotal, v)) +} + +// ChargesTotalNEQ applies the NEQ predicate on the "charges_total" field. +func ChargesTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldChargesTotal, v)) +} + +// ChargesTotalIn applies the In predicate on the "charges_total" field. +func ChargesTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldChargesTotal, vs...)) +} + +// ChargesTotalNotIn applies the NotIn predicate on the "charges_total" field. +func ChargesTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldChargesTotal, vs...)) +} + +// ChargesTotalGT applies the GT predicate on the "charges_total" field. +func ChargesTotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldChargesTotal, v)) +} + +// ChargesTotalGTE applies the GTE predicate on the "charges_total" field. +func ChargesTotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldChargesTotal, v)) +} + +// ChargesTotalLT applies the LT predicate on the "charges_total" field. +func ChargesTotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldChargesTotal, v)) +} + +// ChargesTotalLTE applies the LTE predicate on the "charges_total" field. +func ChargesTotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldChargesTotal, v)) +} + +// DiscountsTotalEQ applies the EQ predicate on the "discounts_total" field. +func DiscountsTotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldDiscountsTotal, v)) +} + +// DiscountsTotalNEQ applies the NEQ predicate on the "discounts_total" field. +func DiscountsTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldDiscountsTotal, v)) +} + +// DiscountsTotalIn applies the In predicate on the "discounts_total" field. +func DiscountsTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldDiscountsTotal, vs...)) +} + +// DiscountsTotalNotIn applies the NotIn predicate on the "discounts_total" field. +func DiscountsTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldDiscountsTotal, vs...)) +} + +// DiscountsTotalGT applies the GT predicate on the "discounts_total" field. +func DiscountsTotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldDiscountsTotal, v)) +} + +// DiscountsTotalGTE applies the GTE predicate on the "discounts_total" field. +func DiscountsTotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldDiscountsTotal, v)) +} + +// DiscountsTotalLT applies the LT predicate on the "discounts_total" field. +func DiscountsTotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldDiscountsTotal, v)) +} + +// DiscountsTotalLTE applies the LTE predicate on the "discounts_total" field. +func DiscountsTotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldDiscountsTotal, v)) +} + +// CreditsTotalEQ applies the EQ predicate on the "credits_total" field. +func CreditsTotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldCreditsTotal, v)) +} + +// CreditsTotalNEQ applies the NEQ predicate on the "credits_total" field. +func CreditsTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldCreditsTotal, v)) +} + +// CreditsTotalIn applies the In predicate on the "credits_total" field. +func CreditsTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldCreditsTotal, vs...)) +} + +// CreditsTotalNotIn applies the NotIn predicate on the "credits_total" field. +func CreditsTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldCreditsTotal, vs...)) +} + +// CreditsTotalGT applies the GT predicate on the "credits_total" field. +func CreditsTotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldCreditsTotal, v)) +} + +// CreditsTotalGTE applies the GTE predicate on the "credits_total" field. +func CreditsTotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldCreditsTotal, v)) +} + +// CreditsTotalLT applies the LT predicate on the "credits_total" field. +func CreditsTotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldCreditsTotal, v)) +} + +// CreditsTotalLTE applies the LTE predicate on the "credits_total" field. +func CreditsTotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldCreditsTotal, v)) +} + +// TotalEQ applies the EQ predicate on the "total" field. +func TotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldTotal, v)) +} + +// TotalNEQ applies the NEQ predicate on the "total" field. +func TotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldTotal, v)) +} + +// TotalIn applies the In predicate on the "total" field. +func TotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldTotal, vs...)) +} + +// TotalNotIn applies the NotIn predicate on the "total" field. +func TotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldTotal, vs...)) +} + +// TotalGT applies the GT predicate on the "total" field. +func TotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldTotal, v)) +} + +// TotalGTE applies the GTE predicate on the "total" field. +func TotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldTotal, v)) +} + +// TotalLT applies the LT predicate on the "total" field. +func TotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldTotal, v)) +} + +// TotalLTE applies the LTE predicate on the "total" field. +func TotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldTotal, v)) +} + +// ChargeIDEQ applies the EQ predicate on the "charge_id" field. +func ChargeIDEQ(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldChargeID, v)) +} + +// ChargeIDNEQ applies the NEQ predicate on the "charge_id" field. +func ChargeIDNEQ(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldChargeID, v)) +} + +// ChargeIDIn applies the In predicate on the "charge_id" field. +func ChargeIDIn(vs ...string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldChargeID, vs...)) +} + +// ChargeIDNotIn applies the NotIn predicate on the "charge_id" field. +func ChargeIDNotIn(vs ...string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldChargeID, vs...)) +} + +// ChargeIDGT applies the GT predicate on the "charge_id" field. +func ChargeIDGT(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldChargeID, v)) +} + +// ChargeIDGTE applies the GTE predicate on the "charge_id" field. +func ChargeIDGTE(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldChargeID, v)) +} + +// ChargeIDLT applies the LT predicate on the "charge_id" field. +func ChargeIDLT(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldChargeID, v)) +} + +// ChargeIDLTE applies the LTE predicate on the "charge_id" field. +func ChargeIDLTE(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldChargeID, v)) +} + +// ChargeIDContains applies the Contains predicate on the "charge_id" field. +func ChargeIDContains(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContains(FieldChargeID, v)) +} + +// ChargeIDHasPrefix applies the HasPrefix predicate on the "charge_id" field. +func ChargeIDHasPrefix(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldHasPrefix(FieldChargeID, v)) +} + +// ChargeIDHasSuffix applies the HasSuffix predicate on the "charge_id" field. +func ChargeIDHasSuffix(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldHasSuffix(FieldChargeID, v)) +} + +// ChargeIDEqualFold applies the EqualFold predicate on the "charge_id" field. +func ChargeIDEqualFold(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEqualFold(FieldChargeID, v)) +} + +// ChargeIDContainsFold applies the ContainsFold predicate on the "charge_id" field. +func ChargeIDContainsFold(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContainsFold(FieldChargeID, v)) +} + +// RunIDEQ applies the EQ predicate on the "run_id" field. +func RunIDEQ(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldRunID, v)) +} + +// RunIDNEQ applies the NEQ predicate on the "run_id" field. +func RunIDNEQ(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldRunID, v)) +} + +// RunIDIn applies the In predicate on the "run_id" field. +func RunIDIn(vs ...string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldRunID, vs...)) +} + +// RunIDNotIn applies the NotIn predicate on the "run_id" field. +func RunIDNotIn(vs ...string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldRunID, vs...)) +} + +// RunIDGT applies the GT predicate on the "run_id" field. +func RunIDGT(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldRunID, v)) +} + +// RunIDGTE applies the GTE predicate on the "run_id" field. +func RunIDGTE(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldRunID, v)) +} + +// RunIDLT applies the LT predicate on the "run_id" field. +func RunIDLT(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldRunID, v)) +} + +// RunIDLTE applies the LTE predicate on the "run_id" field. +func RunIDLTE(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldRunID, v)) +} + +// RunIDContains applies the Contains predicate on the "run_id" field. +func RunIDContains(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContains(FieldRunID, v)) +} + +// RunIDHasPrefix applies the HasPrefix predicate on the "run_id" field. +func RunIDHasPrefix(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldHasPrefix(FieldRunID, v)) +} + +// RunIDHasSuffix applies the HasSuffix predicate on the "run_id" field. +func RunIDHasSuffix(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldHasSuffix(FieldRunID, v)) +} + +// RunIDEqualFold applies the EqualFold predicate on the "run_id" field. +func RunIDEqualFold(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEqualFold(FieldRunID, v)) +} + +// RunIDContainsFold applies the ContainsFold predicate on the "run_id" field. +func RunIDContainsFold(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContainsFold(FieldRunID, v)) +} + +// PricerReferenceIDEQ applies the EQ predicate on the "pricer_reference_id" field. +func PricerReferenceIDEQ(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldPricerReferenceID, v)) +} + +// PricerReferenceIDNEQ applies the NEQ predicate on the "pricer_reference_id" field. +func PricerReferenceIDNEQ(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldPricerReferenceID, v)) +} + +// PricerReferenceIDIn applies the In predicate on the "pricer_reference_id" field. +func PricerReferenceIDIn(vs ...string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldPricerReferenceID, vs...)) +} + +// PricerReferenceIDNotIn applies the NotIn predicate on the "pricer_reference_id" field. +func PricerReferenceIDNotIn(vs ...string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldPricerReferenceID, vs...)) +} + +// PricerReferenceIDGT applies the GT predicate on the "pricer_reference_id" field. +func PricerReferenceIDGT(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldPricerReferenceID, v)) +} + +// PricerReferenceIDGTE applies the GTE predicate on the "pricer_reference_id" field. +func PricerReferenceIDGTE(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldPricerReferenceID, v)) +} + +// PricerReferenceIDLT applies the LT predicate on the "pricer_reference_id" field. +func PricerReferenceIDLT(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldPricerReferenceID, v)) +} + +// PricerReferenceIDLTE applies the LTE predicate on the "pricer_reference_id" field. +func PricerReferenceIDLTE(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldPricerReferenceID, v)) +} + +// PricerReferenceIDContains applies the Contains predicate on the "pricer_reference_id" field. +func PricerReferenceIDContains(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContains(FieldPricerReferenceID, v)) +} + +// PricerReferenceIDHasPrefix applies the HasPrefix predicate on the "pricer_reference_id" field. +func PricerReferenceIDHasPrefix(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldHasPrefix(FieldPricerReferenceID, v)) +} + +// PricerReferenceIDHasSuffix applies the HasSuffix predicate on the "pricer_reference_id" field. +func PricerReferenceIDHasSuffix(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldHasSuffix(FieldPricerReferenceID, v)) +} + +// PricerReferenceIDEqualFold applies the EqualFold predicate on the "pricer_reference_id" field. +func PricerReferenceIDEqualFold(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEqualFold(FieldPricerReferenceID, v)) +} + +// PricerReferenceIDContainsFold applies the ContainsFold predicate on the "pricer_reference_id" field. +func PricerReferenceIDContainsFold(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContainsFold(FieldPricerReferenceID, v)) +} + +// CorrectsRunIDEQ applies the EQ predicate on the "corrects_run_id" field. +func CorrectsRunIDEQ(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEQ(FieldCorrectsRunID, v)) +} + +// CorrectsRunIDNEQ applies the NEQ predicate on the "corrects_run_id" field. +func CorrectsRunIDNEQ(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNEQ(FieldCorrectsRunID, v)) +} + +// CorrectsRunIDIn applies the In predicate on the "corrects_run_id" field. +func CorrectsRunIDIn(vs ...string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIn(FieldCorrectsRunID, vs...)) +} + +// CorrectsRunIDNotIn applies the NotIn predicate on the "corrects_run_id" field. +func CorrectsRunIDNotIn(vs ...string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotIn(FieldCorrectsRunID, vs...)) +} + +// CorrectsRunIDGT applies the GT predicate on the "corrects_run_id" field. +func CorrectsRunIDGT(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGT(FieldCorrectsRunID, v)) +} + +// CorrectsRunIDGTE applies the GTE predicate on the "corrects_run_id" field. +func CorrectsRunIDGTE(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldGTE(FieldCorrectsRunID, v)) +} + +// CorrectsRunIDLT applies the LT predicate on the "corrects_run_id" field. +func CorrectsRunIDLT(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLT(FieldCorrectsRunID, v)) +} + +// CorrectsRunIDLTE applies the LTE predicate on the "corrects_run_id" field. +func CorrectsRunIDLTE(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldLTE(FieldCorrectsRunID, v)) +} + +// CorrectsRunIDContains applies the Contains predicate on the "corrects_run_id" field. +func CorrectsRunIDContains(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContains(FieldCorrectsRunID, v)) +} + +// CorrectsRunIDHasPrefix applies the HasPrefix predicate on the "corrects_run_id" field. +func CorrectsRunIDHasPrefix(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldHasPrefix(FieldCorrectsRunID, v)) +} + +// CorrectsRunIDHasSuffix applies the HasSuffix predicate on the "corrects_run_id" field. +func CorrectsRunIDHasSuffix(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldHasSuffix(FieldCorrectsRunID, v)) +} + +// CorrectsRunIDIsNil applies the IsNil predicate on the "corrects_run_id" field. +func CorrectsRunIDIsNil() predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldIsNull(FieldCorrectsRunID)) +} + +// CorrectsRunIDNotNil applies the NotNil predicate on the "corrects_run_id" field. +func CorrectsRunIDNotNil() predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldNotNull(FieldCorrectsRunID)) +} + +// CorrectsRunIDEqualFold applies the EqualFold predicate on the "corrects_run_id" field. +func CorrectsRunIDEqualFold(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldEqualFold(FieldCorrectsRunID, v)) +} + +// CorrectsRunIDContainsFold applies the ContainsFold predicate on the "corrects_run_id" field. +func CorrectsRunIDContainsFold(v string) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.FieldContainsFold(FieldCorrectsRunID, v)) +} + +// HasCharge applies the HasEdge predicate on the "charge" edge. +func HasCharge() predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, 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.ChargeUsageBased) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(func(s *sql.Selector) { + step := newChargeStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasRun applies the HasEdge predicate on the "run" edge. +func HasRun() predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(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.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(func(s *sql.Selector) { + step := newRunStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasCorrectsRun applies the HasEdge predicate on the "corrects_run" edge. +func HasCorrectsRun() predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, CorrectsRunTable, CorrectsRunColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCorrectsRunWith applies the HasEdge predicate on the "corrects_run" edge with a given conditions (other predicates). +func HasCorrectsRunWith(preds ...predicate.ChargeUsageBasedRuns) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(func(s *sql.Selector) { + step := newCorrectsRunStep() + 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.ChargeUsageBasedRunDetailedLine) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ChargeUsageBasedRunDetailedLine) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ChargeUsageBasedRunDetailedLine) predicate.ChargeUsageBasedRunDetailedLine { + return predicate.ChargeUsageBasedRunDetailedLine(sql.NotPredicates(p)) +} diff --git a/ent/db/chargeusagebasedrundetailedline_create.go b/ent/db/chargeusagebasedrundetailedline_create.go new file mode 100644 index 0000000000000000000000000000000000000000..da07ea00ac61b95e508a9f36cb8b03a390217f8d --- /dev/null +++ b/ent/db/chargeusagebasedrundetailedline_create.go @@ -0,0 +1,2348 @@ +// 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/models/creditsapplied" + "github.com/openmeterio/openmeter/openmeter/billing/models/stddetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrundetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeUsageBasedRunDetailedLineCreate is the builder for creating a ChargeUsageBasedRunDetailedLine entity. +type ChargeUsageBasedRunDetailedLineCreate struct { + config + mutation *ChargeUsageBasedRunDetailedLineMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetCurrency sets the "currency" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetCurrency(v currencyx.Code) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetCurrency(v) + return _c +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetServicePeriodStart(v time.Time) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetServicePeriodStart(v) + return _c +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetServicePeriodEnd(v time.Time) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetServicePeriodEnd(v) + return _c +} + +// SetQuantity sets the "quantity" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetQuantity(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetQuantity(v) + return _c +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetInvoicingAppExternalID(v string) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetInvoicingAppExternalID(v) + return _c +} + +// SetNillableInvoicingAppExternalID sets the "invoicing_app_external_id" field if the given value is not nil. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetNillableInvoicingAppExternalID(v *string) *ChargeUsageBasedRunDetailedLineCreate { + if v != nil { + _c.SetInvoicingAppExternalID(*v) + } + return _c +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetChildUniqueReferenceID(v string) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetChildUniqueReferenceID(v) + return _c +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetPerUnitAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetPerUnitAmount(v) + return _c +} + +// SetCategory sets the "category" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetCategory(v stddetailedline.Category) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetCategory(v) + return _c +} + +// SetNillableCategory sets the "category" field if the given value is not nil. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetNillableCategory(v *stddetailedline.Category) *ChargeUsageBasedRunDetailedLineCreate { + if v != nil { + _c.SetCategory(*v) + } + return _c +} + +// SetPaymentTerm sets the "payment_term" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetPaymentTerm(v) + return _c +} + +// SetNillablePaymentTerm sets the "payment_term" field if the given value is not nil. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetNillablePaymentTerm(v *productcatalog.PaymentTermType) *ChargeUsageBasedRunDetailedLineCreate { + if v != nil { + _c.SetPaymentTerm(*v) + } + return _c +} + +// SetIndex sets the "index" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetIndex(v int) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetIndex(v) + return _c +} + +// SetNillableIndex sets the "index" field if the given value is not nil. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetNillableIndex(v *int) *ChargeUsageBasedRunDetailedLineCreate { + if v != nil { + _c.SetIndex(*v) + } + return _c +} + +// SetCreditsApplied sets the "credits_applied" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetCreditsApplied(v *creditsapplied.CreditsApplied) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetCreditsApplied(v) + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetNamespace sets the "namespace" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetNamespace(v string) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetMetadata sets the "metadata" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetMetadata(v map[string]string) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetMetadata(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetCreatedAt(v time.Time) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetNillableCreatedAt(v *time.Time) *ChargeUsageBasedRunDetailedLineCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetNillableUpdatedAt(v *time.Time) *ChargeUsageBasedRunDetailedLineCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetDeletedAt(v time.Time) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetNillableDeletedAt(v *time.Time) *ChargeUsageBasedRunDetailedLineCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetName sets the "name" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetName(v string) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetName(v) + return _c +} + +// SetDescription sets the "description" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetDescription(v string) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetDescription(v) + return _c +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetNillableDescription(v *string) *ChargeUsageBasedRunDetailedLineCreate { + if v != nil { + _c.SetDescription(*v) + } + return _c +} + +// SetAmount sets the "amount" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetTaxesTotal(v) + return _c +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetTaxesInclusiveTotal(v) + return _c +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetTaxesExclusiveTotal(v) + return _c +} + +// SetChargesTotal sets the "charges_total" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetChargesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetChargesTotal(v) + return _c +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetDiscountsTotal(v) + return _c +} + +// SetCreditsTotal sets the "credits_total" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetCreditsTotal(v) + return _c +} + +// SetTotal sets the "total" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetTotal(v) + return _c +} + +// SetChargeID sets the "charge_id" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetChargeID(v string) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetChargeID(v) + return _c +} + +// SetRunID sets the "run_id" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetRunID(v string) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetRunID(v) + return _c +} + +// SetPricerReferenceID sets the "pricer_reference_id" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetPricerReferenceID(v string) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetPricerReferenceID(v) + return _c +} + +// SetCorrectsRunID sets the "corrects_run_id" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetCorrectsRunID(v string) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetCorrectsRunID(v) + return _c +} + +// SetNillableCorrectsRunID sets the "corrects_run_id" field if the given value is not nil. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetNillableCorrectsRunID(v *string) *ChargeUsageBasedRunDetailedLineCreate { + if v != nil { + _c.SetCorrectsRunID(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetID(v string) *ChargeUsageBasedRunDetailedLineCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetNillableID(v *string) *ChargeUsageBasedRunDetailedLineCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetCharge sets the "charge" edge to the ChargeUsageBased entity. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetCharge(v *ChargeUsageBased) *ChargeUsageBasedRunDetailedLineCreate { + return _c.SetChargeID(v.ID) +} + +// SetRun sets the "run" edge to the ChargeUsageBasedRuns entity. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetRun(v *ChargeUsageBasedRuns) *ChargeUsageBasedRunDetailedLineCreate { + return _c.SetRunID(v.ID) +} + +// SetCorrectsRun sets the "corrects_run" edge to the ChargeUsageBasedRuns entity. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SetCorrectsRun(v *ChargeUsageBasedRuns) *ChargeUsageBasedRunDetailedLineCreate { + return _c.SetCorrectsRunID(v.ID) +} + +// Mutation returns the ChargeUsageBasedRunDetailedLineMutation object of the builder. +func (_c *ChargeUsageBasedRunDetailedLineCreate) Mutation() *ChargeUsageBasedRunDetailedLineMutation { + return _c.mutation +} + +// Save creates the ChargeUsageBasedRunDetailedLine in the database. +func (_c *ChargeUsageBasedRunDetailedLineCreate) Save(ctx context.Context) (*ChargeUsageBasedRunDetailedLine, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ChargeUsageBasedRunDetailedLineCreate) SaveX(ctx context.Context) *ChargeUsageBasedRunDetailedLine { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeUsageBasedRunDetailedLineCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeUsageBasedRunDetailedLineCreate) 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 *ChargeUsageBasedRunDetailedLineCreate) defaults() { + if _, ok := _c.mutation.Category(); !ok { + v := chargeusagebasedrundetailedline.DefaultCategory + _c.mutation.SetCategory(v) + } + if _, ok := _c.mutation.PaymentTerm(); !ok { + v := chargeusagebasedrundetailedline.DefaultPaymentTerm + _c.mutation.SetPaymentTerm(v) + } + if _, ok := _c.mutation.CreatedAt(); !ok { + v := chargeusagebasedrundetailedline.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := chargeusagebasedrundetailedline.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := chargeusagebasedrundetailedline.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ChargeUsageBasedRunDetailedLineCreate) check() error { + if _, ok := _c.mutation.Currency(); !ok { + return &ValidationError{Name: "currency", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.currency"`)} + } + if v, ok := _c.mutation.Currency(); ok { + if err := chargeusagebasedrundetailedline.CurrencyValidator(string(v)); err != nil { + return &ValidationError{Name: "currency", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunDetailedLine.currency": %w`, err)} + } + } + if _, ok := _c.mutation.ServicePeriodStart(); !ok { + return &ValidationError{Name: "service_period_start", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.service_period_start"`)} + } + if _, ok := _c.mutation.ServicePeriodEnd(); !ok { + return &ValidationError{Name: "service_period_end", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.service_period_end"`)} + } + if _, ok := _c.mutation.Quantity(); !ok { + return &ValidationError{Name: "quantity", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.quantity"`)} + } + if _, ok := _c.mutation.ChildUniqueReferenceID(); !ok { + return &ValidationError{Name: "child_unique_reference_id", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.child_unique_reference_id"`)} + } + if v, ok := _c.mutation.ChildUniqueReferenceID(); ok { + if err := chargeusagebasedrundetailedline.ChildUniqueReferenceIDValidator(v); err != nil { + return &ValidationError{Name: "child_unique_reference_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunDetailedLine.child_unique_reference_id": %w`, err)} + } + } + if _, ok := _c.mutation.PerUnitAmount(); !ok { + return &ValidationError{Name: "per_unit_amount", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.per_unit_amount"`)} + } + if _, ok := _c.mutation.Category(); !ok { + return &ValidationError{Name: "category", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.category"`)} + } + if v, ok := _c.mutation.Category(); ok { + if err := chargeusagebasedrundetailedline.CategoryValidator(v); err != nil { + return &ValidationError{Name: "category", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunDetailedLine.category": %w`, err)} + } + } + if _, ok := _c.mutation.PaymentTerm(); !ok { + return &ValidationError{Name: "payment_term", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.payment_term"`)} + } + if v, ok := _c.mutation.PaymentTerm(); ok { + if err := chargeusagebasedrundetailedline.PaymentTermValidator(v); err != nil { + return &ValidationError{Name: "payment_term", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunDetailedLine.payment_term": %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 "ChargeUsageBasedRunDetailedLine.credits_applied": %w`, err)} + } + } + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := chargeusagebasedrundetailedline.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunDetailedLine.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.updated_at"`)} + } + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.name"`)} + } + if _, ok := _c.mutation.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.amount"`)} + } + if _, ok := _c.mutation.TaxesTotal(); !ok { + return &ValidationError{Name: "taxes_total", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.taxes_total"`)} + } + if _, ok := _c.mutation.TaxesInclusiveTotal(); !ok { + return &ValidationError{Name: "taxes_inclusive_total", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.taxes_inclusive_total"`)} + } + if _, ok := _c.mutation.TaxesExclusiveTotal(); !ok { + return &ValidationError{Name: "taxes_exclusive_total", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.taxes_exclusive_total"`)} + } + if _, ok := _c.mutation.ChargesTotal(); !ok { + return &ValidationError{Name: "charges_total", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.charges_total"`)} + } + if _, ok := _c.mutation.DiscountsTotal(); !ok { + return &ValidationError{Name: "discounts_total", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.discounts_total"`)} + } + if _, ok := _c.mutation.CreditsTotal(); !ok { + return &ValidationError{Name: "credits_total", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.credits_total"`)} + } + if _, ok := _c.mutation.Total(); !ok { + return &ValidationError{Name: "total", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.total"`)} + } + if _, ok := _c.mutation.ChargeID(); !ok { + return &ValidationError{Name: "charge_id", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.charge_id"`)} + } + if _, ok := _c.mutation.RunID(); !ok { + return &ValidationError{Name: "run_id", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.run_id"`)} + } + if _, ok := _c.mutation.PricerReferenceID(); !ok { + return &ValidationError{Name: "pricer_reference_id", err: errors.New(`db: missing required field "ChargeUsageBasedRunDetailedLine.pricer_reference_id"`)} + } + if v, ok := _c.mutation.PricerReferenceID(); ok { + if err := chargeusagebasedrundetailedline.PricerReferenceIDValidator(v); err != nil { + return &ValidationError{Name: "pricer_reference_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunDetailedLine.pricer_reference_id": %w`, err)} + } + } + if v, ok := _c.mutation.CorrectsRunID(); ok { + if err := chargeusagebasedrundetailedline.CorrectsRunIDValidator(v); err != nil { + return &ValidationError{Name: "corrects_run_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunDetailedLine.corrects_run_id": %w`, err)} + } + } + if len(_c.mutation.ChargeIDs()) == 0 { + return &ValidationError{Name: "charge", err: errors.New(`db: missing required edge "ChargeUsageBasedRunDetailedLine.charge"`)} + } + if len(_c.mutation.RunIDs()) == 0 { + return &ValidationError{Name: "run", err: errors.New(`db: missing required edge "ChargeUsageBasedRunDetailedLine.run"`)} + } + return nil +} + +func (_c *ChargeUsageBasedRunDetailedLineCreate) sqlSave(ctx context.Context) (*ChargeUsageBasedRunDetailedLine, 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 ChargeUsageBasedRunDetailedLine.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ChargeUsageBasedRunDetailedLineCreate) createSpec() (*ChargeUsageBasedRunDetailedLine, *sqlgraph.CreateSpec) { + var ( + _node = &ChargeUsageBasedRunDetailedLine{config: _c.config} + _spec = sqlgraph.NewCreateSpec(chargeusagebasedrundetailedline.Table, sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.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.Currency(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldCurrency, field.TypeString, value) + _node.Currency = value + } + if value, ok := _c.mutation.ServicePeriodStart(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldServicePeriodStart, field.TypeTime, value) + _node.ServicePeriodStart = value + } + if value, ok := _c.mutation.ServicePeriodEnd(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldServicePeriodEnd, field.TypeTime, value) + _node.ServicePeriodEnd = value + } + if value, ok := _c.mutation.Quantity(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldQuantity, field.TypeOther, value) + _node.Quantity = value + } + if value, ok := _c.mutation.InvoicingAppExternalID(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldInvoicingAppExternalID, field.TypeString, value) + _node.InvoicingAppExternalID = &value + } + if value, ok := _c.mutation.ChildUniqueReferenceID(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldChildUniqueReferenceID, field.TypeString, value) + _node.ChildUniqueReferenceID = value + } + if value, ok := _c.mutation.PerUnitAmount(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldPerUnitAmount, field.TypeOther, value) + _node.PerUnitAmount = value + } + if value, ok := _c.mutation.Category(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldCategory, field.TypeEnum, value) + _node.Category = value + } + if value, ok := _c.mutation.PaymentTerm(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldPaymentTerm, field.TypeEnum, value) + _node.PaymentTerm = value + } + if value, ok := _c.mutation.Index(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldIndex, field.TypeInt, value) + _node.Index = &value + } + if value, ok := _c.mutation.CreditsApplied(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldCreditsApplied, field.TypeJSON, value) + _node.CreditsApplied = value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Metadata(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldMetadata, field.TypeJSON, value) + _node.Metadata = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Description(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldDescription, field.TypeString, value) + _node.Description = &value + } + if value, ok := _c.mutation.Amount(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldAmount, field.TypeOther, value) + _node.Amount = value + } + if value, ok := _c.mutation.TaxesTotal(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldTaxesTotal, field.TypeOther, value) + _node.TaxesTotal = value + } + if value, ok := _c.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldTaxesInclusiveTotal, field.TypeOther, value) + _node.TaxesInclusiveTotal = value + } + if value, ok := _c.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldTaxesExclusiveTotal, field.TypeOther, value) + _node.TaxesExclusiveTotal = value + } + if value, ok := _c.mutation.ChargesTotal(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldChargesTotal, field.TypeOther, value) + _node.ChargesTotal = value + } + if value, ok := _c.mutation.DiscountsTotal(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldDiscountsTotal, field.TypeOther, value) + _node.DiscountsTotal = value + } + if value, ok := _c.mutation.CreditsTotal(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldCreditsTotal, field.TypeOther, value) + _node.CreditsTotal = value + } + if value, ok := _c.mutation.Total(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldTotal, field.TypeOther, value) + _node.Total = value + } + if value, ok := _c.mutation.PricerReferenceID(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldPricerReferenceID, field.TypeString, value) + _node.PricerReferenceID = value + } + if nodes := _c.mutation.ChargeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedrundetailedline.ChargeTable, + Columns: []string{chargeusagebasedrundetailedline.ChargeColumn}, + 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.RunIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedrundetailedline.RunTable, + Columns: []string{chargeusagebasedrundetailedline.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) + } + if nodes := _c.mutation.CorrectsRunIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedrundetailedline.CorrectsRunTable, + Columns: []string{chargeusagebasedrundetailedline.CorrectsRunColumn}, + 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.CorrectsRunID = &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.ChargeUsageBasedRunDetailedLine.Create(). +// SetCurrency(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.ChargeUsageBasedRunDetailedLineUpsert) { +// SetCurrency(v+v). +// }). +// Exec(ctx) +func (_c *ChargeUsageBasedRunDetailedLineCreate) OnConflict(opts ...sql.ConflictOption) *ChargeUsageBasedRunDetailedLineUpsertOne { + _c.conflict = opts + return &ChargeUsageBasedRunDetailedLineUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunDetailedLine.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeUsageBasedRunDetailedLineCreate) OnConflictColumns(columns ...string) *ChargeUsageBasedRunDetailedLineUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeUsageBasedRunDetailedLineUpsertOne{ + create: _c, + } +} + +type ( + // ChargeUsageBasedRunDetailedLineUpsertOne is the builder for "upsert"-ing + // one ChargeUsageBasedRunDetailedLine node. + ChargeUsageBasedRunDetailedLineUpsertOne struct { + create *ChargeUsageBasedRunDetailedLineCreate + } + + // ChargeUsageBasedRunDetailedLineUpsert is the "OnConflict" setter. + ChargeUsageBasedRunDetailedLineUpsert struct { + *sql.UpdateSet + } +) + +// SetServicePeriodStart sets the "service_period_start" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetServicePeriodStart(v time.Time) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldServicePeriodStart, v) + return u +} + +// UpdateServicePeriodStart sets the "service_period_start" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateServicePeriodStart() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldServicePeriodStart) + return u +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetServicePeriodEnd(v time.Time) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldServicePeriodEnd, v) + return u +} + +// UpdateServicePeriodEnd sets the "service_period_end" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateServicePeriodEnd() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldServicePeriodEnd) + return u +} + +// SetQuantity sets the "quantity" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetQuantity(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldQuantity, v) + return u +} + +// UpdateQuantity sets the "quantity" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateQuantity() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldQuantity) + return u +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetInvoicingAppExternalID(v string) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldInvoicingAppExternalID, v) + return u +} + +// UpdateInvoicingAppExternalID sets the "invoicing_app_external_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateInvoicingAppExternalID() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldInvoicingAppExternalID) + return u +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) ClearInvoicingAppExternalID() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetNull(chargeusagebasedrundetailedline.FieldInvoicingAppExternalID) + return u +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetChildUniqueReferenceID(v string) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldChildUniqueReferenceID, v) + return u +} + +// UpdateChildUniqueReferenceID sets the "child_unique_reference_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateChildUniqueReferenceID() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldChildUniqueReferenceID) + return u +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetPerUnitAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldPerUnitAmount, v) + return u +} + +// UpdatePerUnitAmount sets the "per_unit_amount" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdatePerUnitAmount() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldPerUnitAmount) + return u +} + +// SetCategory sets the "category" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetCategory(v stddetailedline.Category) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldCategory, v) + return u +} + +// UpdateCategory sets the "category" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateCategory() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldCategory) + return u +} + +// SetPaymentTerm sets the "payment_term" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldPaymentTerm, v) + return u +} + +// UpdatePaymentTerm sets the "payment_term" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdatePaymentTerm() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldPaymentTerm) + return u +} + +// SetIndex sets the "index" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetIndex(v int) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldIndex, v) + return u +} + +// UpdateIndex sets the "index" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateIndex() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldIndex) + return u +} + +// AddIndex adds v to the "index" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) AddIndex(v int) *ChargeUsageBasedRunDetailedLineUpsert { + u.Add(chargeusagebasedrundetailedline.FieldIndex, v) + return u +} + +// ClearIndex clears the value of the "index" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) ClearIndex() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetNull(chargeusagebasedrundetailedline.FieldIndex) + return u +} + +// SetCreditsApplied sets the "credits_applied" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetCreditsApplied(v *creditsapplied.CreditsApplied) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldCreditsApplied, v) + return u +} + +// UpdateCreditsApplied sets the "credits_applied" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateCreditsApplied() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldCreditsApplied) + return u +} + +// ClearCreditsApplied clears the value of the "credits_applied" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) ClearCreditsApplied() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetNull(chargeusagebasedrundetailedline.FieldCreditsApplied) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateAnnotations() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) ClearAnnotations() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetNull(chargeusagebasedrundetailedline.FieldAnnotations) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetMetadata(v map[string]string) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldMetadata, v) + return u +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateMetadata() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldMetadata) + return u +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) ClearMetadata() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetNull(chargeusagebasedrundetailedline.FieldMetadata) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateUpdatedAt() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetDeletedAt(v time.Time) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateDeletedAt() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) ClearDeletedAt() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetNull(chargeusagebasedrundetailedline.FieldDeletedAt) + return u +} + +// SetName sets the "name" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetName(v string) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateName() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldName) + return u +} + +// SetDescription sets the "description" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetDescription(v string) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldDescription, v) + return u +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateDescription() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldDescription) + return u +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) ClearDescription() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetNull(chargeusagebasedrundetailedline.FieldDescription) + return u +} + +// SetAmount sets the "amount" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldAmount, v) + return u +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateAmount() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldAmount) + return u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldTaxesTotal, v) + return u +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateTaxesTotal() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldTaxesTotal) + return u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldTaxesInclusiveTotal, v) + return u +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateTaxesInclusiveTotal() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldTaxesInclusiveTotal) + return u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldTaxesExclusiveTotal, v) + return u +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateTaxesExclusiveTotal() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldTaxesExclusiveTotal) + return u +} + +// SetChargesTotal sets the "charges_total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetChargesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldChargesTotal, v) + return u +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateChargesTotal() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldChargesTotal) + return u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldDiscountsTotal, v) + return u +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateDiscountsTotal() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldDiscountsTotal) + return u +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldCreditsTotal, v) + return u +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateCreditsTotal() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldCreditsTotal) + return u +} + +// SetTotal sets the "total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldTotal, v) + return u +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateTotal() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldTotal) + return u +} + +// SetChargeID sets the "charge_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetChargeID(v string) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldChargeID, v) + return u +} + +// UpdateChargeID sets the "charge_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateChargeID() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldChargeID) + return u +} + +// SetRunID sets the "run_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetRunID(v string) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldRunID, v) + return u +} + +// UpdateRunID sets the "run_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateRunID() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldRunID) + return u +} + +// SetPricerReferenceID sets the "pricer_reference_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetPricerReferenceID(v string) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldPricerReferenceID, v) + return u +} + +// UpdatePricerReferenceID sets the "pricer_reference_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdatePricerReferenceID() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldPricerReferenceID) + return u +} + +// SetCorrectsRunID sets the "corrects_run_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) SetCorrectsRunID(v string) *ChargeUsageBasedRunDetailedLineUpsert { + u.Set(chargeusagebasedrundetailedline.FieldCorrectsRunID, v) + return u +} + +// UpdateCorrectsRunID sets the "corrects_run_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsert) UpdateCorrectsRunID() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetExcluded(chargeusagebasedrundetailedline.FieldCorrectsRunID) + return u +} + +// ClearCorrectsRunID clears the value of the "corrects_run_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsert) ClearCorrectsRunID() *ChargeUsageBasedRunDetailedLineUpsert { + u.SetNull(chargeusagebasedrundetailedline.FieldCorrectsRunID) + 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.ChargeUsageBasedRunDetailedLine.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeusagebasedrundetailedline.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateNewValues() *ChargeUsageBasedRunDetailedLineUpsertOne { + 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(chargeusagebasedrundetailedline.FieldID) + } + if _, exists := u.create.mutation.Currency(); exists { + s.SetIgnore(chargeusagebasedrundetailedline.FieldCurrency) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(chargeusagebasedrundetailedline.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(chargeusagebasedrundetailedline.FieldCreatedAt) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunDetailedLine.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) Ignore() *ChargeUsageBasedRunDetailedLineUpsertOne { + 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 *ChargeUsageBasedRunDetailedLineUpsertOne) DoNothing() *ChargeUsageBasedRunDetailedLineUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeUsageBasedRunDetailedLineCreate.OnConflict +// documentation for more info. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) Update(set func(*ChargeUsageBasedRunDetailedLineUpsert)) *ChargeUsageBasedRunDetailedLineUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeUsageBasedRunDetailedLineUpsert{UpdateSet: update}) + })) + return u +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetServicePeriodStart(v time.Time) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetServicePeriodStart(v) + }) +} + +// UpdateServicePeriodStart sets the "service_period_start" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateServicePeriodStart() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateServicePeriodStart() + }) +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetServicePeriodEnd(v time.Time) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetServicePeriodEnd(v) + }) +} + +// UpdateServicePeriodEnd sets the "service_period_end" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateServicePeriodEnd() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateServicePeriodEnd() + }) +} + +// SetQuantity sets the "quantity" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetQuantity(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetQuantity(v) + }) +} + +// UpdateQuantity sets the "quantity" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateQuantity() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateQuantity() + }) +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetInvoicingAppExternalID(v string) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetInvoicingAppExternalID(v) + }) +} + +// UpdateInvoicingAppExternalID sets the "invoicing_app_external_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateInvoicingAppExternalID() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateInvoicingAppExternalID() + }) +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) ClearInvoicingAppExternalID() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.ClearInvoicingAppExternalID() + }) +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetChildUniqueReferenceID(v string) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetChildUniqueReferenceID(v) + }) +} + +// UpdateChildUniqueReferenceID sets the "child_unique_reference_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateChildUniqueReferenceID() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateChildUniqueReferenceID() + }) +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetPerUnitAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetPerUnitAmount(v) + }) +} + +// UpdatePerUnitAmount sets the "per_unit_amount" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdatePerUnitAmount() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdatePerUnitAmount() + }) +} + +// SetCategory sets the "category" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetCategory(v stddetailedline.Category) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetCategory(v) + }) +} + +// UpdateCategory sets the "category" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateCategory() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateCategory() + }) +} + +// SetPaymentTerm sets the "payment_term" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetPaymentTerm(v) + }) +} + +// UpdatePaymentTerm sets the "payment_term" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdatePaymentTerm() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdatePaymentTerm() + }) +} + +// SetIndex sets the "index" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetIndex(v int) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetIndex(v) + }) +} + +// AddIndex adds v to the "index" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) AddIndex(v int) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.AddIndex(v) + }) +} + +// UpdateIndex sets the "index" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateIndex() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateIndex() + }) +} + +// ClearIndex clears the value of the "index" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) ClearIndex() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.ClearIndex() + }) +} + +// SetCreditsApplied sets the "credits_applied" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetCreditsApplied(v *creditsapplied.CreditsApplied) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetCreditsApplied(v) + }) +} + +// UpdateCreditsApplied sets the "credits_applied" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateCreditsApplied() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateCreditsApplied() + }) +} + +// ClearCreditsApplied clears the value of the "credits_applied" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) ClearCreditsApplied() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.ClearCreditsApplied() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateAnnotations() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) ClearAnnotations() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.ClearAnnotations() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetMetadata(v map[string]string) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateMetadata() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) ClearMetadata() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateUpdatedAt() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetDeletedAt(v time.Time) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateDeletedAt() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) ClearDeletedAt() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetName(v string) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateName() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetDescription(v string) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateDescription() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) ClearDescription() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.ClearDescription() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateAmount() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateAmount() + }) +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetTaxesTotal(v) + }) +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateTaxesTotal() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateTaxesTotal() + }) +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetTaxesInclusiveTotal(v) + }) +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateTaxesInclusiveTotal() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateTaxesInclusiveTotal() + }) +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetTaxesExclusiveTotal(v) + }) +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateTaxesExclusiveTotal() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateTaxesExclusiveTotal() + }) +} + +// SetChargesTotal sets the "charges_total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetChargesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetChargesTotal(v) + }) +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateChargesTotal() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateChargesTotal() + }) +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetDiscountsTotal(v) + }) +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateDiscountsTotal() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateDiscountsTotal() + }) +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetCreditsTotal(v) + }) +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateCreditsTotal() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateCreditsTotal() + }) +} + +// SetTotal sets the "total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetTotal(v) + }) +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateTotal() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateTotal() + }) +} + +// SetChargeID sets the "charge_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetChargeID(v string) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetChargeID(v) + }) +} + +// UpdateChargeID sets the "charge_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateChargeID() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateChargeID() + }) +} + +// SetRunID sets the "run_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetRunID(v string) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetRunID(v) + }) +} + +// UpdateRunID sets the "run_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateRunID() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateRunID() + }) +} + +// SetPricerReferenceID sets the "pricer_reference_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetPricerReferenceID(v string) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetPricerReferenceID(v) + }) +} + +// UpdatePricerReferenceID sets the "pricer_reference_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdatePricerReferenceID() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdatePricerReferenceID() + }) +} + +// SetCorrectsRunID sets the "corrects_run_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) SetCorrectsRunID(v string) *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetCorrectsRunID(v) + }) +} + +// UpdateCorrectsRunID sets the "corrects_run_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) UpdateCorrectsRunID() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateCorrectsRunID() + }) +} + +// ClearCorrectsRunID clears the value of the "corrects_run_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) ClearCorrectsRunID() *ChargeUsageBasedRunDetailedLineUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.ClearCorrectsRunID() + }) +} + +// Exec executes the query. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeUsageBasedRunDetailedLineCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeUsageBasedRunDetailedLineUpsertOne) 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 *ChargeUsageBasedRunDetailedLineUpsertOne) 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: ChargeUsageBasedRunDetailedLineUpsertOne.ID is not supported by MySQL driver. Use ChargeUsageBasedRunDetailedLineUpsertOne.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 *ChargeUsageBasedRunDetailedLineUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ChargeUsageBasedRunDetailedLineCreateBulk is the builder for creating many ChargeUsageBasedRunDetailedLine entities in bulk. +type ChargeUsageBasedRunDetailedLineCreateBulk struct { + config + err error + builders []*ChargeUsageBasedRunDetailedLineCreate + conflict []sql.ConflictOption +} + +// Save creates the ChargeUsageBasedRunDetailedLine entities in the database. +func (_c *ChargeUsageBasedRunDetailedLineCreateBulk) Save(ctx context.Context) ([]*ChargeUsageBasedRunDetailedLine, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ChargeUsageBasedRunDetailedLine, 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.(*ChargeUsageBasedRunDetailedLineMutation) + 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 *ChargeUsageBasedRunDetailedLineCreateBulk) SaveX(ctx context.Context) []*ChargeUsageBasedRunDetailedLine { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeUsageBasedRunDetailedLineCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeUsageBasedRunDetailedLineCreateBulk) 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.ChargeUsageBasedRunDetailedLine.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.ChargeUsageBasedRunDetailedLineUpsert) { +// SetCurrency(v+v). +// }). +// Exec(ctx) +func (_c *ChargeUsageBasedRunDetailedLineCreateBulk) OnConflict(opts ...sql.ConflictOption) *ChargeUsageBasedRunDetailedLineUpsertBulk { + _c.conflict = opts + return &ChargeUsageBasedRunDetailedLineUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunDetailedLine.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeUsageBasedRunDetailedLineCreateBulk) OnConflictColumns(columns ...string) *ChargeUsageBasedRunDetailedLineUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeUsageBasedRunDetailedLineUpsertBulk{ + create: _c, + } +} + +// ChargeUsageBasedRunDetailedLineUpsertBulk is the builder for "upsert"-ing +// a bulk of ChargeUsageBasedRunDetailedLine nodes. +type ChargeUsageBasedRunDetailedLineUpsertBulk struct { + create *ChargeUsageBasedRunDetailedLineCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunDetailedLine.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeusagebasedrundetailedline.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateNewValues() *ChargeUsageBasedRunDetailedLineUpsertBulk { + 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(chargeusagebasedrundetailedline.FieldID) + } + if _, exists := b.mutation.Currency(); exists { + s.SetIgnore(chargeusagebasedrundetailedline.FieldCurrency) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(chargeusagebasedrundetailedline.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(chargeusagebasedrundetailedline.FieldCreatedAt) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunDetailedLine.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) Ignore() *ChargeUsageBasedRunDetailedLineUpsertBulk { + 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 *ChargeUsageBasedRunDetailedLineUpsertBulk) DoNothing() *ChargeUsageBasedRunDetailedLineUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeUsageBasedRunDetailedLineCreateBulk.OnConflict +// documentation for more info. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) Update(set func(*ChargeUsageBasedRunDetailedLineUpsert)) *ChargeUsageBasedRunDetailedLineUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeUsageBasedRunDetailedLineUpsert{UpdateSet: update}) + })) + return u +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetServicePeriodStart(v time.Time) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetServicePeriodStart(v) + }) +} + +// UpdateServicePeriodStart sets the "service_period_start" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateServicePeriodStart() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateServicePeriodStart() + }) +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetServicePeriodEnd(v time.Time) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetServicePeriodEnd(v) + }) +} + +// UpdateServicePeriodEnd sets the "service_period_end" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateServicePeriodEnd() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateServicePeriodEnd() + }) +} + +// SetQuantity sets the "quantity" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetQuantity(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetQuantity(v) + }) +} + +// UpdateQuantity sets the "quantity" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateQuantity() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateQuantity() + }) +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetInvoicingAppExternalID(v string) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetInvoicingAppExternalID(v) + }) +} + +// UpdateInvoicingAppExternalID sets the "invoicing_app_external_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateInvoicingAppExternalID() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateInvoicingAppExternalID() + }) +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) ClearInvoicingAppExternalID() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.ClearInvoicingAppExternalID() + }) +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetChildUniqueReferenceID(v string) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetChildUniqueReferenceID(v) + }) +} + +// UpdateChildUniqueReferenceID sets the "child_unique_reference_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateChildUniqueReferenceID() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateChildUniqueReferenceID() + }) +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetPerUnitAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetPerUnitAmount(v) + }) +} + +// UpdatePerUnitAmount sets the "per_unit_amount" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdatePerUnitAmount() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdatePerUnitAmount() + }) +} + +// SetCategory sets the "category" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetCategory(v stddetailedline.Category) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetCategory(v) + }) +} + +// UpdateCategory sets the "category" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateCategory() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateCategory() + }) +} + +// SetPaymentTerm sets the "payment_term" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetPaymentTerm(v) + }) +} + +// UpdatePaymentTerm sets the "payment_term" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdatePaymentTerm() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdatePaymentTerm() + }) +} + +// SetIndex sets the "index" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetIndex(v int) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetIndex(v) + }) +} + +// AddIndex adds v to the "index" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) AddIndex(v int) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.AddIndex(v) + }) +} + +// UpdateIndex sets the "index" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateIndex() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateIndex() + }) +} + +// ClearIndex clears the value of the "index" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) ClearIndex() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.ClearIndex() + }) +} + +// SetCreditsApplied sets the "credits_applied" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetCreditsApplied(v *creditsapplied.CreditsApplied) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetCreditsApplied(v) + }) +} + +// UpdateCreditsApplied sets the "credits_applied" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateCreditsApplied() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateCreditsApplied() + }) +} + +// ClearCreditsApplied clears the value of the "credits_applied" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) ClearCreditsApplied() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.ClearCreditsApplied() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateAnnotations() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) ClearAnnotations() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.ClearAnnotations() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetMetadata(v map[string]string) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateMetadata() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) ClearMetadata() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateUpdatedAt() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetDeletedAt(v time.Time) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateDeletedAt() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) ClearDeletedAt() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetName(v string) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateName() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetDescription(v string) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateDescription() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) ClearDescription() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.ClearDescription() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateAmount() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateAmount() + }) +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetTaxesTotal(v) + }) +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateTaxesTotal() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateTaxesTotal() + }) +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetTaxesInclusiveTotal(v) + }) +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateTaxesInclusiveTotal() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateTaxesInclusiveTotal() + }) +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetTaxesExclusiveTotal(v) + }) +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateTaxesExclusiveTotal() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateTaxesExclusiveTotal() + }) +} + +// SetChargesTotal sets the "charges_total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetChargesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetChargesTotal(v) + }) +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateChargesTotal() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateChargesTotal() + }) +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetDiscountsTotal(v) + }) +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateDiscountsTotal() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateDiscountsTotal() + }) +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetCreditsTotal(v) + }) +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateCreditsTotal() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateCreditsTotal() + }) +} + +// SetTotal sets the "total" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetTotal(v) + }) +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateTotal() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateTotal() + }) +} + +// SetChargeID sets the "charge_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetChargeID(v string) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetChargeID(v) + }) +} + +// UpdateChargeID sets the "charge_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateChargeID() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateChargeID() + }) +} + +// SetRunID sets the "run_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetRunID(v string) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetRunID(v) + }) +} + +// UpdateRunID sets the "run_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateRunID() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateRunID() + }) +} + +// SetPricerReferenceID sets the "pricer_reference_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetPricerReferenceID(v string) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetPricerReferenceID(v) + }) +} + +// UpdatePricerReferenceID sets the "pricer_reference_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdatePricerReferenceID() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdatePricerReferenceID() + }) +} + +// SetCorrectsRunID sets the "corrects_run_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) SetCorrectsRunID(v string) *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.SetCorrectsRunID(v) + }) +} + +// UpdateCorrectsRunID sets the "corrects_run_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) UpdateCorrectsRunID() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.UpdateCorrectsRunID() + }) +} + +// ClearCorrectsRunID clears the value of the "corrects_run_id" field. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) ClearCorrectsRunID() *ChargeUsageBasedRunDetailedLineUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunDetailedLineUpsert) { + s.ClearCorrectsRunID() + }) +} + +// Exec executes the query. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) 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 ChargeUsageBasedRunDetailedLineCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeUsageBasedRunDetailedLineCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeUsageBasedRunDetailedLineUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargeusagebasedrundetailedline_delete.go b/ent/db/chargeusagebasedrundetailedline_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..8299dd9f7661d2749e7681c8d3e5647ff45fcb35 --- /dev/null +++ b/ent/db/chargeusagebasedrundetailedline_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/chargeusagebasedrundetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeUsageBasedRunDetailedLineDelete is the builder for deleting a ChargeUsageBasedRunDetailedLine entity. +type ChargeUsageBasedRunDetailedLineDelete struct { + config + hooks []Hook + mutation *ChargeUsageBasedRunDetailedLineMutation +} + +// Where appends a list predicates to the ChargeUsageBasedRunDetailedLineDelete builder. +func (_d *ChargeUsageBasedRunDetailedLineDelete) Where(ps ...predicate.ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedRunDetailedLineDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ChargeUsageBasedRunDetailedLineDelete) 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 *ChargeUsageBasedRunDetailedLineDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ChargeUsageBasedRunDetailedLineDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(chargeusagebasedrundetailedline.Table, sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.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 +} + +// ChargeUsageBasedRunDetailedLineDeleteOne is the builder for deleting a single ChargeUsageBasedRunDetailedLine entity. +type ChargeUsageBasedRunDetailedLineDeleteOne struct { + _d *ChargeUsageBasedRunDetailedLineDelete +} + +// Where appends a list predicates to the ChargeUsageBasedRunDetailedLineDelete builder. +func (_d *ChargeUsageBasedRunDetailedLineDeleteOne) Where(ps ...predicate.ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedRunDetailedLineDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ChargeUsageBasedRunDetailedLineDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{chargeusagebasedrundetailedline.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeUsageBasedRunDetailedLineDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/chargeusagebasedrundetailedline_query.go b/ent/db/chargeusagebasedrundetailedline_query.go new file mode 100644 index 0000000000000000000000000000000000000000..a57a86610ddd1ebd4fea4bea21984d44f752767e --- /dev/null +++ b/ent/db/chargeusagebasedrundetailedline_query.go @@ -0,0 +1,795 @@ +// 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/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrundetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeUsageBasedRunDetailedLineQuery is the builder for querying ChargeUsageBasedRunDetailedLine entities. +type ChargeUsageBasedRunDetailedLineQuery struct { + config + ctx *QueryContext + order []chargeusagebasedrundetailedline.OrderOption + inters []Interceptor + predicates []predicate.ChargeUsageBasedRunDetailedLine + withCharge *ChargeUsageBasedQuery + withRun *ChargeUsageBasedRunsQuery + withCorrectsRun *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 ChargeUsageBasedRunDetailedLineQuery builder. +func (_q *ChargeUsageBasedRunDetailedLineQuery) Where(ps ...predicate.ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedRunDetailedLineQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ChargeUsageBasedRunDetailedLineQuery) Limit(limit int) *ChargeUsageBasedRunDetailedLineQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ChargeUsageBasedRunDetailedLineQuery) Offset(offset int) *ChargeUsageBasedRunDetailedLineQuery { + _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 *ChargeUsageBasedRunDetailedLineQuery) Unique(unique bool) *ChargeUsageBasedRunDetailedLineQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ChargeUsageBasedRunDetailedLineQuery) Order(o ...chargeusagebasedrundetailedline.OrderOption) *ChargeUsageBasedRunDetailedLineQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryCharge chains the current query on the "charge" edge. +func (_q *ChargeUsageBasedRunDetailedLineQuery) QueryCharge() *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(chargeusagebasedrundetailedline.Table, chargeusagebasedrundetailedline.FieldID, selector), + sqlgraph.To(chargeusagebased.Table, chargeusagebased.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebasedrundetailedline.ChargeTable, chargeusagebasedrundetailedline.ChargeColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryRun chains the current query on the "run" edge. +func (_q *ChargeUsageBasedRunDetailedLineQuery) 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(chargeusagebasedrundetailedline.Table, chargeusagebasedrundetailedline.FieldID, selector), + sqlgraph.To(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebasedrundetailedline.RunTable, chargeusagebasedrundetailedline.RunColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCorrectsRun chains the current query on the "corrects_run" edge. +func (_q *ChargeUsageBasedRunDetailedLineQuery) QueryCorrectsRun() *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(chargeusagebasedrundetailedline.Table, chargeusagebasedrundetailedline.FieldID, selector), + sqlgraph.To(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebasedrundetailedline.CorrectsRunTable, chargeusagebasedrundetailedline.CorrectsRunColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ChargeUsageBasedRunDetailedLine entity from the query. +// Returns a *NotFoundError when no ChargeUsageBasedRunDetailedLine was found. +func (_q *ChargeUsageBasedRunDetailedLineQuery) First(ctx context.Context) (*ChargeUsageBasedRunDetailedLine, 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{chargeusagebasedrundetailedline.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ChargeUsageBasedRunDetailedLineQuery) FirstX(ctx context.Context) *ChargeUsageBasedRunDetailedLine { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ChargeUsageBasedRunDetailedLine ID from the query. +// Returns a *NotFoundError when no ChargeUsageBasedRunDetailedLine ID was found. +func (_q *ChargeUsageBasedRunDetailedLineQuery) 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{chargeusagebasedrundetailedline.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ChargeUsageBasedRunDetailedLineQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ChargeUsageBasedRunDetailedLine entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ChargeUsageBasedRunDetailedLine entity is found. +// Returns a *NotFoundError when no ChargeUsageBasedRunDetailedLine entities are found. +func (_q *ChargeUsageBasedRunDetailedLineQuery) Only(ctx context.Context) (*ChargeUsageBasedRunDetailedLine, 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{chargeusagebasedrundetailedline.Label} + default: + return nil, &NotSingularError{chargeusagebasedrundetailedline.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ChargeUsageBasedRunDetailedLineQuery) OnlyX(ctx context.Context) *ChargeUsageBasedRunDetailedLine { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ChargeUsageBasedRunDetailedLine ID in the query. +// Returns a *NotSingularError when more than one ChargeUsageBasedRunDetailedLine ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ChargeUsageBasedRunDetailedLineQuery) 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{chargeusagebasedrundetailedline.Label} + default: + err = &NotSingularError{chargeusagebasedrundetailedline.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ChargeUsageBasedRunDetailedLineQuery) 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 ChargeUsageBasedRunDetailedLines. +func (_q *ChargeUsageBasedRunDetailedLineQuery) All(ctx context.Context) ([]*ChargeUsageBasedRunDetailedLine, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ChargeUsageBasedRunDetailedLine, *ChargeUsageBasedRunDetailedLineQuery]() + return withInterceptors[[]*ChargeUsageBasedRunDetailedLine](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ChargeUsageBasedRunDetailedLineQuery) AllX(ctx context.Context) []*ChargeUsageBasedRunDetailedLine { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ChargeUsageBasedRunDetailedLine IDs. +func (_q *ChargeUsageBasedRunDetailedLineQuery) 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(chargeusagebasedrundetailedline.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ChargeUsageBasedRunDetailedLineQuery) 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 *ChargeUsageBasedRunDetailedLineQuery) 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[*ChargeUsageBasedRunDetailedLineQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ChargeUsageBasedRunDetailedLineQuery) 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 *ChargeUsageBasedRunDetailedLineQuery) 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 *ChargeUsageBasedRunDetailedLineQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ChargeUsageBasedRunDetailedLineQuery 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 *ChargeUsageBasedRunDetailedLineQuery) Clone() *ChargeUsageBasedRunDetailedLineQuery { + if _q == nil { + return nil + } + return &ChargeUsageBasedRunDetailedLineQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]chargeusagebasedrundetailedline.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ChargeUsageBasedRunDetailedLine{}, _q.predicates...), + withCharge: _q.withCharge.Clone(), + withRun: _q.withRun.Clone(), + withCorrectsRun: _q.withCorrectsRun.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 *ChargeUsageBasedRunDetailedLineQuery) WithCharge(opts ...func(*ChargeUsageBasedQuery)) *ChargeUsageBasedRunDetailedLineQuery { + query := (&ChargeUsageBasedClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCharge = query + return _q +} + +// 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 *ChargeUsageBasedRunDetailedLineQuery) WithRun(opts ...func(*ChargeUsageBasedRunsQuery)) *ChargeUsageBasedRunDetailedLineQuery { + query := (&ChargeUsageBasedRunsClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withRun = query + return _q +} + +// WithCorrectsRun tells the query-builder to eager-load the nodes that are connected to +// the "corrects_run" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedRunDetailedLineQuery) WithCorrectsRun(opts ...func(*ChargeUsageBasedRunsQuery)) *ChargeUsageBasedRunDetailedLineQuery { + query := (&ChargeUsageBasedRunsClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCorrectsRun = 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 { +// Currency currencyx.Code `json:"currency,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.ChargeUsageBasedRunDetailedLine.Query(). +// GroupBy(chargeusagebasedrundetailedline.FieldCurrency). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *ChargeUsageBasedRunDetailedLineQuery) GroupBy(field string, fields ...string) *ChargeUsageBasedRunDetailedLineGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ChargeUsageBasedRunDetailedLineGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = chargeusagebasedrundetailedline.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 { +// Currency currencyx.Code `json:"currency,omitempty"` +// } +// +// client.ChargeUsageBasedRunDetailedLine.Query(). +// Select(chargeusagebasedrundetailedline.FieldCurrency). +// Scan(ctx, &v) +func (_q *ChargeUsageBasedRunDetailedLineQuery) Select(fields ...string) *ChargeUsageBasedRunDetailedLineSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ChargeUsageBasedRunDetailedLineSelect{ChargeUsageBasedRunDetailedLineQuery: _q} + sbuild.label = chargeusagebasedrundetailedline.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ChargeUsageBasedRunDetailedLineSelect configured with the given aggregations. +func (_q *ChargeUsageBasedRunDetailedLineQuery) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedRunDetailedLineSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ChargeUsageBasedRunDetailedLineQuery) 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 !chargeusagebasedrundetailedline.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 *ChargeUsageBasedRunDetailedLineQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ChargeUsageBasedRunDetailedLine, error) { + var ( + nodes = []*ChargeUsageBasedRunDetailedLine{} + _spec = _q.querySpec() + loadedTypes = [3]bool{ + _q.withCharge != nil, + _q.withRun != nil, + _q.withCorrectsRun != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ChargeUsageBasedRunDetailedLine).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ChargeUsageBasedRunDetailedLine{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 *ChargeUsageBasedRunDetailedLine, e *ChargeUsageBased) { n.Edges.Charge = e }); err != nil { + return nil, err + } + } + if query := _q.withRun; query != nil { + if err := _q.loadRun(ctx, query, nodes, nil, + func(n *ChargeUsageBasedRunDetailedLine, e *ChargeUsageBasedRuns) { n.Edges.Run = e }); err != nil { + return nil, err + } + } + if query := _q.withCorrectsRun; query != nil { + if err := _q.loadCorrectsRun(ctx, query, nodes, nil, + func(n *ChargeUsageBasedRunDetailedLine, e *ChargeUsageBasedRuns) { n.Edges.CorrectsRun = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ChargeUsageBasedRunDetailedLineQuery) loadCharge(ctx context.Context, query *ChargeUsageBasedQuery, nodes []*ChargeUsageBasedRunDetailedLine, init func(*ChargeUsageBasedRunDetailedLine), assign func(*ChargeUsageBasedRunDetailedLine, *ChargeUsageBased)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBasedRunDetailedLine) + 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 *ChargeUsageBasedRunDetailedLineQuery) loadRun(ctx context.Context, query *ChargeUsageBasedRunsQuery, nodes []*ChargeUsageBasedRunDetailedLine, init func(*ChargeUsageBasedRunDetailedLine), assign func(*ChargeUsageBasedRunDetailedLine, *ChargeUsageBasedRuns)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBasedRunDetailedLine) + 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 *ChargeUsageBasedRunDetailedLineQuery) loadCorrectsRun(ctx context.Context, query *ChargeUsageBasedRunsQuery, nodes []*ChargeUsageBasedRunDetailedLine, init func(*ChargeUsageBasedRunDetailedLine), assign func(*ChargeUsageBasedRunDetailedLine, *ChargeUsageBasedRuns)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBasedRunDetailedLine) + for i := range nodes { + if nodes[i].CorrectsRunID == nil { + continue + } + fk := *nodes[i].CorrectsRunID + 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 "corrects_run_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *ChargeUsageBasedRunDetailedLineQuery) 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 *ChargeUsageBasedRunDetailedLineQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(chargeusagebasedrundetailedline.Table, chargeusagebasedrundetailedline.Columns, sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.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, chargeusagebasedrundetailedline.FieldID) + for i := range fields { + if fields[i] != chargeusagebasedrundetailedline.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withCharge != nil { + _spec.Node.AddColumnOnce(chargeusagebasedrundetailedline.FieldChargeID) + } + if _q.withRun != nil { + _spec.Node.AddColumnOnce(chargeusagebasedrundetailedline.FieldRunID) + } + if _q.withCorrectsRun != nil { + _spec.Node.AddColumnOnce(chargeusagebasedrundetailedline.FieldCorrectsRunID) + } + } + 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 *ChargeUsageBasedRunDetailedLineQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(chargeusagebasedrundetailedline.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = chargeusagebasedrundetailedline.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 *ChargeUsageBasedRunDetailedLineQuery) ForUpdate(opts ...sql.LockOption) *ChargeUsageBasedRunDetailedLineQuery { + 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 *ChargeUsageBasedRunDetailedLineQuery) ForShare(opts ...sql.LockOption) *ChargeUsageBasedRunDetailedLineQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ChargeUsageBasedRunDetailedLineGroupBy is the group-by builder for ChargeUsageBasedRunDetailedLine entities. +type ChargeUsageBasedRunDetailedLineGroupBy struct { + selector + build *ChargeUsageBasedRunDetailedLineQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ChargeUsageBasedRunDetailedLineGroupBy) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedRunDetailedLineGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ChargeUsageBasedRunDetailedLineGroupBy) 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[*ChargeUsageBasedRunDetailedLineQuery, *ChargeUsageBasedRunDetailedLineGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ChargeUsageBasedRunDetailedLineGroupBy) sqlScan(ctx context.Context, root *ChargeUsageBasedRunDetailedLineQuery, 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) +} + +// ChargeUsageBasedRunDetailedLineSelect is the builder for selecting fields of ChargeUsageBasedRunDetailedLine entities. +type ChargeUsageBasedRunDetailedLineSelect struct { + *ChargeUsageBasedRunDetailedLineQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ChargeUsageBasedRunDetailedLineSelect) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedRunDetailedLineSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ChargeUsageBasedRunDetailedLineSelect) 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[*ChargeUsageBasedRunDetailedLineQuery, *ChargeUsageBasedRunDetailedLineSelect](ctx, _s.ChargeUsageBasedRunDetailedLineQuery, _s, _s.inters, v) +} + +func (_s *ChargeUsageBasedRunDetailedLineSelect) sqlScan(ctx context.Context, root *ChargeUsageBasedRunDetailedLineQuery, 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/ent/db/chargeusagebasedrundetailedline_update.go b/ent/db/chargeusagebasedrundetailedline_update.go new file mode 100644 index 0000000000000000000000000000000000000000..a1d1417a6a2e95c01956d0ddd50db490b37f833a --- /dev/null +++ b/ent/db/chargeusagebasedrundetailedline_update.go @@ -0,0 +1,1557 @@ +// 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/models/creditsapplied" + "github.com/openmeterio/openmeter/openmeter/billing/models/stddetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrundetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeUsageBasedRunDetailedLineUpdate is the builder for updating ChargeUsageBasedRunDetailedLine entities. +type ChargeUsageBasedRunDetailedLineUpdate struct { + config + hooks []Hook + mutation *ChargeUsageBasedRunDetailedLineMutation +} + +// Where appends a list predicates to the ChargeUsageBasedRunDetailedLineUpdate builder. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) Where(ps ...predicate.ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetServicePeriodStart(v time.Time) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetServicePeriodStart(v) + return _u +} + +// SetNillableServicePeriodStart sets the "service_period_start" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableServicePeriodStart(v *time.Time) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetServicePeriodStart(*v) + } + return _u +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetServicePeriodEnd(v time.Time) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetServicePeriodEnd(v) + return _u +} + +// SetNillableServicePeriodEnd sets the "service_period_end" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableServicePeriodEnd(v *time.Time) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetServicePeriodEnd(*v) + } + return _u +} + +// SetQuantity sets the "quantity" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetQuantity(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetQuantity(v) + return _u +} + +// SetNillableQuantity sets the "quantity" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableQuantity(v *alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetQuantity(*v) + } + return _u +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetInvoicingAppExternalID(v string) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetInvoicingAppExternalID(v) + return _u +} + +// SetNillableInvoicingAppExternalID sets the "invoicing_app_external_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableInvoicingAppExternalID(v *string) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetInvoicingAppExternalID(*v) + } + return _u +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) ClearInvoicingAppExternalID() *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.ClearInvoicingAppExternalID() + return _u +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetChildUniqueReferenceID(v string) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetChildUniqueReferenceID(v) + return _u +} + +// SetNillableChildUniqueReferenceID sets the "child_unique_reference_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableChildUniqueReferenceID(v *string) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetChildUniqueReferenceID(*v) + } + return _u +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetPerUnitAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetPerUnitAmount(v) + return _u +} + +// SetNillablePerUnitAmount sets the "per_unit_amount" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillablePerUnitAmount(v *alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetPerUnitAmount(*v) + } + return _u +} + +// SetCategory sets the "category" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetCategory(v stddetailedline.Category) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetCategory(v) + return _u +} + +// SetNillableCategory sets the "category" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableCategory(v *stddetailedline.Category) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetCategory(*v) + } + return _u +} + +// SetPaymentTerm sets the "payment_term" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetPaymentTerm(v) + return _u +} + +// SetNillablePaymentTerm sets the "payment_term" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillablePaymentTerm(v *productcatalog.PaymentTermType) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetPaymentTerm(*v) + } + return _u +} + +// SetIndex sets the "index" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetIndex(v int) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.ResetIndex() + _u.mutation.SetIndex(v) + return _u +} + +// SetNillableIndex sets the "index" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableIndex(v *int) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetIndex(*v) + } + return _u +} + +// AddIndex adds value to the "index" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) AddIndex(v int) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.AddIndex(v) + return _u +} + +// ClearIndex clears the value of the "index" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) ClearIndex() *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.ClearIndex() + return _u +} + +// SetCreditsApplied sets the "credits_applied" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetCreditsApplied(v *creditsapplied.CreditsApplied) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetCreditsApplied(v) + return _u +} + +// ClearCreditsApplied clears the value of the "credits_applied" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) ClearCreditsApplied() *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.ClearCreditsApplied() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) ClearAnnotations() *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetMetadata(v map[string]string) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) ClearMetadata() *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetDeletedAt(v time.Time) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableDeletedAt(v *time.Time) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) ClearDeletedAt() *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetName(v string) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableName(v *string) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetDescription(v string) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableDescription(v *string) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) ClearDescription() *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.ClearDescription() + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetTaxesTotal(v) + return _u +} + +// SetNillableTaxesTotal sets the "taxes_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableTaxesTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetTaxesTotal(*v) + } + return _u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetTaxesInclusiveTotal(v) + return _u +} + +// SetNillableTaxesInclusiveTotal sets the "taxes_inclusive_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableTaxesInclusiveTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetTaxesInclusiveTotal(*v) + } + return _u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetTaxesExclusiveTotal(v) + return _u +} + +// SetNillableTaxesExclusiveTotal sets the "taxes_exclusive_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableTaxesExclusiveTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetTaxesExclusiveTotal(*v) + } + return _u +} + +// SetChargesTotal sets the "charges_total" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetChargesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetChargesTotal(v) + return _u +} + +// SetNillableChargesTotal sets the "charges_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableChargesTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetChargesTotal(*v) + } + return _u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetDiscountsTotal(v) + return _u +} + +// SetNillableDiscountsTotal sets the "discounts_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableDiscountsTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetDiscountsTotal(*v) + } + return _u +} + +// SetCreditsTotal sets the "credits_total" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetCreditsTotal(v) + return _u +} + +// SetNillableCreditsTotal sets the "credits_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableCreditsTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetCreditsTotal(*v) + } + return _u +} + +// SetTotal sets the "total" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetTotal(v) + return _u +} + +// SetNillableTotal sets the "total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetTotal(*v) + } + return _u +} + +// SetChargeID sets the "charge_id" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetChargeID(v string) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetChargeID(v) + return _u +} + +// SetNillableChargeID sets the "charge_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableChargeID(v *string) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetChargeID(*v) + } + return _u +} + +// SetRunID sets the "run_id" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetRunID(v string) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetRunID(v) + return _u +} + +// SetNillableRunID sets the "run_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableRunID(v *string) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetRunID(*v) + } + return _u +} + +// SetPricerReferenceID sets the "pricer_reference_id" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetPricerReferenceID(v string) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetPricerReferenceID(v) + return _u +} + +// SetNillablePricerReferenceID sets the "pricer_reference_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillablePricerReferenceID(v *string) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetPricerReferenceID(*v) + } + return _u +} + +// SetCorrectsRunID sets the "corrects_run_id" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetCorrectsRunID(v string) *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.SetCorrectsRunID(v) + return _u +} + +// SetNillableCorrectsRunID sets the "corrects_run_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetNillableCorrectsRunID(v *string) *ChargeUsageBasedRunDetailedLineUpdate { + if v != nil { + _u.SetCorrectsRunID(*v) + } + return _u +} + +// ClearCorrectsRunID clears the value of the "corrects_run_id" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) ClearCorrectsRunID() *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.ClearCorrectsRunID() + return _u +} + +// SetCharge sets the "charge" edge to the ChargeUsageBased entity. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetCharge(v *ChargeUsageBased) *ChargeUsageBasedRunDetailedLineUpdate { + return _u.SetChargeID(v.ID) +} + +// SetRun sets the "run" edge to the ChargeUsageBasedRuns entity. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetRun(v *ChargeUsageBasedRuns) *ChargeUsageBasedRunDetailedLineUpdate { + return _u.SetRunID(v.ID) +} + +// SetCorrectsRun sets the "corrects_run" edge to the ChargeUsageBasedRuns entity. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) SetCorrectsRun(v *ChargeUsageBasedRuns) *ChargeUsageBasedRunDetailedLineUpdate { + return _u.SetCorrectsRunID(v.ID) +} + +// Mutation returns the ChargeUsageBasedRunDetailedLineMutation object of the builder. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) Mutation() *ChargeUsageBasedRunDetailedLineMutation { + return _u.mutation +} + +// ClearCharge clears the "charge" edge to the ChargeUsageBased entity. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) ClearCharge() *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.ClearCharge() + return _u +} + +// ClearRun clears the "run" edge to the ChargeUsageBasedRuns entity. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) ClearRun() *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.ClearRun() + return _u +} + +// ClearCorrectsRun clears the "corrects_run" edge to the ChargeUsageBasedRuns entity. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) ClearCorrectsRun() *ChargeUsageBasedRunDetailedLineUpdate { + _u.mutation.ClearCorrectsRun() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) 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 *ChargeUsageBasedRunDetailedLineUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) 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 *ChargeUsageBasedRunDetailedLineUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeusagebasedrundetailedline.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeUsageBasedRunDetailedLineUpdate) check() error { + if v, ok := _u.mutation.ChildUniqueReferenceID(); ok { + if err := chargeusagebasedrundetailedline.ChildUniqueReferenceIDValidator(v); err != nil { + return &ValidationError{Name: "child_unique_reference_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunDetailedLine.child_unique_reference_id": %w`, err)} + } + } + if v, ok := _u.mutation.Category(); ok { + if err := chargeusagebasedrundetailedline.CategoryValidator(v); err != nil { + return &ValidationError{Name: "category", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunDetailedLine.category": %w`, err)} + } + } + if v, ok := _u.mutation.PaymentTerm(); ok { + if err := chargeusagebasedrundetailedline.PaymentTermValidator(v); err != nil { + return &ValidationError{Name: "payment_term", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunDetailedLine.payment_term": %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 "ChargeUsageBasedRunDetailedLine.credits_applied": %w`, err)} + } + } + if v, ok := _u.mutation.PricerReferenceID(); ok { + if err := chargeusagebasedrundetailedline.PricerReferenceIDValidator(v); err != nil { + return &ValidationError{Name: "pricer_reference_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunDetailedLine.pricer_reference_id": %w`, err)} + } + } + if v, ok := _u.mutation.CorrectsRunID(); ok { + if err := chargeusagebasedrundetailedline.CorrectsRunIDValidator(v); err != nil { + return &ValidationError{Name: "corrects_run_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunDetailedLine.corrects_run_id": %w`, err)} + } + } + if _u.mutation.ChargeCleared() && len(_u.mutation.ChargeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBasedRunDetailedLine.charge"`) + } + if _u.mutation.RunCleared() && len(_u.mutation.RunIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBasedRunDetailedLine.run"`) + } + return nil +} + +func (_u *ChargeUsageBasedRunDetailedLineUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeusagebasedrundetailedline.Table, chargeusagebasedrundetailedline.Columns, sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.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.ServicePeriodStart(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldServicePeriodStart, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodEnd(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldServicePeriodEnd, field.TypeTime, value) + } + if value, ok := _u.mutation.Quantity(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldQuantity, field.TypeOther, value) + } + if value, ok := _u.mutation.InvoicingAppExternalID(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldInvoicingAppExternalID, field.TypeString, value) + } + if _u.mutation.InvoicingAppExternalIDCleared() { + _spec.ClearField(chargeusagebasedrundetailedline.FieldInvoicingAppExternalID, field.TypeString) + } + if value, ok := _u.mutation.ChildUniqueReferenceID(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldChildUniqueReferenceID, field.TypeString, value) + } + if value, ok := _u.mutation.PerUnitAmount(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldPerUnitAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.Category(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldCategory, field.TypeEnum, value) + } + if value, ok := _u.mutation.PaymentTerm(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldPaymentTerm, field.TypeEnum, value) + } + if value, ok := _u.mutation.Index(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldIndex, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedIndex(); ok { + _spec.AddField(chargeusagebasedrundetailedline.FieldIndex, field.TypeInt, value) + } + if _u.mutation.IndexCleared() { + _spec.ClearField(chargeusagebasedrundetailedline.FieldIndex, field.TypeInt) + } + if value, ok := _u.mutation.CreditsApplied(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldCreditsApplied, field.TypeJSON, value) + } + if _u.mutation.CreditsAppliedCleared() { + _spec.ClearField(chargeusagebasedrundetailedline.FieldCreditsApplied, field.TypeJSON) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargeusagebasedrundetailedline.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(chargeusagebasedrundetailedline.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeusagebasedrundetailedline.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(chargeusagebasedrundetailedline.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesTotal(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldTaxesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldTaxesInclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldTaxesExclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.ChargesTotal(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldChargesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.DiscountsTotal(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldDiscountsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.CreditsTotal(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldCreditsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.Total(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.PricerReferenceID(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldPricerReferenceID, field.TypeString, value) + } + if _u.mutation.ChargeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedrundetailedline.ChargeTable, + Columns: []string{chargeusagebasedrundetailedline.ChargeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebased.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ChargeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedrundetailedline.ChargeTable, + Columns: []string{chargeusagebasedrundetailedline.ChargeColumn}, + 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.RunCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedrundetailedline.RunTable, + Columns: []string{chargeusagebasedrundetailedline.RunColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RunIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedrundetailedline.RunTable, + Columns: []string{chargeusagebasedrundetailedline.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) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.CorrectsRunCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedrundetailedline.CorrectsRunTable, + Columns: []string{chargeusagebasedrundetailedline.CorrectsRunColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.CorrectsRunIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedrundetailedline.CorrectsRunTable, + Columns: []string{chargeusagebasedrundetailedline.CorrectsRunColumn}, + 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{chargeusagebasedrundetailedline.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ChargeUsageBasedRunDetailedLineUpdateOne is the builder for updating a single ChargeUsageBasedRunDetailedLine entity. +type ChargeUsageBasedRunDetailedLineUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ChargeUsageBasedRunDetailedLineMutation +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetServicePeriodStart(v time.Time) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetServicePeriodStart(v) + return _u +} + +// SetNillableServicePeriodStart sets the "service_period_start" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableServicePeriodStart(v *time.Time) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetServicePeriodStart(*v) + } + return _u +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetServicePeriodEnd(v time.Time) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetServicePeriodEnd(v) + return _u +} + +// SetNillableServicePeriodEnd sets the "service_period_end" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableServicePeriodEnd(v *time.Time) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetServicePeriodEnd(*v) + } + return _u +} + +// SetQuantity sets the "quantity" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetQuantity(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetQuantity(v) + return _u +} + +// SetNillableQuantity sets the "quantity" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableQuantity(v *alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetQuantity(*v) + } + return _u +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetInvoicingAppExternalID(v string) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetInvoicingAppExternalID(v) + return _u +} + +// SetNillableInvoicingAppExternalID sets the "invoicing_app_external_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableInvoicingAppExternalID(v *string) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetInvoicingAppExternalID(*v) + } + return _u +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) ClearInvoicingAppExternalID() *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.ClearInvoicingAppExternalID() + return _u +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetChildUniqueReferenceID(v string) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetChildUniqueReferenceID(v) + return _u +} + +// SetNillableChildUniqueReferenceID sets the "child_unique_reference_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableChildUniqueReferenceID(v *string) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetChildUniqueReferenceID(*v) + } + return _u +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetPerUnitAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetPerUnitAmount(v) + return _u +} + +// SetNillablePerUnitAmount sets the "per_unit_amount" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillablePerUnitAmount(v *alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetPerUnitAmount(*v) + } + return _u +} + +// SetCategory sets the "category" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetCategory(v stddetailedline.Category) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetCategory(v) + return _u +} + +// SetNillableCategory sets the "category" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableCategory(v *stddetailedline.Category) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetCategory(*v) + } + return _u +} + +// SetPaymentTerm sets the "payment_term" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetPaymentTerm(v productcatalog.PaymentTermType) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetPaymentTerm(v) + return _u +} + +// SetNillablePaymentTerm sets the "payment_term" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillablePaymentTerm(v *productcatalog.PaymentTermType) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetPaymentTerm(*v) + } + return _u +} + +// SetIndex sets the "index" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetIndex(v int) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.ResetIndex() + _u.mutation.SetIndex(v) + return _u +} + +// SetNillableIndex sets the "index" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableIndex(v *int) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetIndex(*v) + } + return _u +} + +// AddIndex adds value to the "index" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) AddIndex(v int) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.AddIndex(v) + return _u +} + +// ClearIndex clears the value of the "index" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) ClearIndex() *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.ClearIndex() + return _u +} + +// SetCreditsApplied sets the "credits_applied" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetCreditsApplied(v *creditsapplied.CreditsApplied) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetCreditsApplied(v) + return _u +} + +// ClearCreditsApplied clears the value of the "credits_applied" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) ClearCreditsApplied() *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.ClearCreditsApplied() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) ClearAnnotations() *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetMetadata(v map[string]string) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) ClearMetadata() *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetDeletedAt(v time.Time) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableDeletedAt(v *time.Time) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) ClearDeletedAt() *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetName(v string) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableName(v *string) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetDescription(v string) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableDescription(v *string) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) ClearDescription() *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.ClearDescription() + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetTaxesTotal(v) + return _u +} + +// SetNillableTaxesTotal sets the "taxes_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableTaxesTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetTaxesTotal(*v) + } + return _u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetTaxesInclusiveTotal(v) + return _u +} + +// SetNillableTaxesInclusiveTotal sets the "taxes_inclusive_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableTaxesInclusiveTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetTaxesInclusiveTotal(*v) + } + return _u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetTaxesExclusiveTotal(v) + return _u +} + +// SetNillableTaxesExclusiveTotal sets the "taxes_exclusive_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableTaxesExclusiveTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetTaxesExclusiveTotal(*v) + } + return _u +} + +// SetChargesTotal sets the "charges_total" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetChargesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetChargesTotal(v) + return _u +} + +// SetNillableChargesTotal sets the "charges_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableChargesTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetChargesTotal(*v) + } + return _u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetDiscountsTotal(v) + return _u +} + +// SetNillableDiscountsTotal sets the "discounts_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableDiscountsTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetDiscountsTotal(*v) + } + return _u +} + +// SetCreditsTotal sets the "credits_total" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetCreditsTotal(v) + return _u +} + +// SetNillableCreditsTotal sets the "credits_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableCreditsTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetCreditsTotal(*v) + } + return _u +} + +// SetTotal sets the "total" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetTotal(v) + return _u +} + +// SetNillableTotal sets the "total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetTotal(*v) + } + return _u +} + +// SetChargeID sets the "charge_id" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetChargeID(v string) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetChargeID(v) + return _u +} + +// SetNillableChargeID sets the "charge_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableChargeID(v *string) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetChargeID(*v) + } + return _u +} + +// SetRunID sets the "run_id" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetRunID(v string) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetRunID(v) + return _u +} + +// SetNillableRunID sets the "run_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableRunID(v *string) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetRunID(*v) + } + return _u +} + +// SetPricerReferenceID sets the "pricer_reference_id" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetPricerReferenceID(v string) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetPricerReferenceID(v) + return _u +} + +// SetNillablePricerReferenceID sets the "pricer_reference_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillablePricerReferenceID(v *string) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetPricerReferenceID(*v) + } + return _u +} + +// SetCorrectsRunID sets the "corrects_run_id" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetCorrectsRunID(v string) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.SetCorrectsRunID(v) + return _u +} + +// SetNillableCorrectsRunID sets the "corrects_run_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetNillableCorrectsRunID(v *string) *ChargeUsageBasedRunDetailedLineUpdateOne { + if v != nil { + _u.SetCorrectsRunID(*v) + } + return _u +} + +// ClearCorrectsRunID clears the value of the "corrects_run_id" field. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) ClearCorrectsRunID() *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.ClearCorrectsRunID() + return _u +} + +// SetCharge sets the "charge" edge to the ChargeUsageBased entity. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetCharge(v *ChargeUsageBased) *ChargeUsageBasedRunDetailedLineUpdateOne { + return _u.SetChargeID(v.ID) +} + +// SetRun sets the "run" edge to the ChargeUsageBasedRuns entity. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetRun(v *ChargeUsageBasedRuns) *ChargeUsageBasedRunDetailedLineUpdateOne { + return _u.SetRunID(v.ID) +} + +// SetCorrectsRun sets the "corrects_run" edge to the ChargeUsageBasedRuns entity. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SetCorrectsRun(v *ChargeUsageBasedRuns) *ChargeUsageBasedRunDetailedLineUpdateOne { + return _u.SetCorrectsRunID(v.ID) +} + +// Mutation returns the ChargeUsageBasedRunDetailedLineMutation object of the builder. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) Mutation() *ChargeUsageBasedRunDetailedLineMutation { + return _u.mutation +} + +// ClearCharge clears the "charge" edge to the ChargeUsageBased entity. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) ClearCharge() *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.ClearCharge() + return _u +} + +// ClearRun clears the "run" edge to the ChargeUsageBasedRuns entity. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) ClearRun() *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.ClearRun() + return _u +} + +// ClearCorrectsRun clears the "corrects_run" edge to the ChargeUsageBasedRuns entity. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) ClearCorrectsRun() *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.mutation.ClearCorrectsRun() + return _u +} + +// Where appends a list predicates to the ChargeUsageBasedRunDetailedLineUpdate builder. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) Where(ps ...predicate.ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedRunDetailedLineUpdateOne { + _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 *ChargeUsageBasedRunDetailedLineUpdateOne) Select(field string, fields ...string) *ChargeUsageBasedRunDetailedLineUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ChargeUsageBasedRunDetailedLine entity. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) Save(ctx context.Context) (*ChargeUsageBasedRunDetailedLine, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) SaveX(ctx context.Context) *ChargeUsageBasedRunDetailedLine { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) 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 *ChargeUsageBasedRunDetailedLineUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeusagebasedrundetailedline.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) check() error { + if v, ok := _u.mutation.ChildUniqueReferenceID(); ok { + if err := chargeusagebasedrundetailedline.ChildUniqueReferenceIDValidator(v); err != nil { + return &ValidationError{Name: "child_unique_reference_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunDetailedLine.child_unique_reference_id": %w`, err)} + } + } + if v, ok := _u.mutation.Category(); ok { + if err := chargeusagebasedrundetailedline.CategoryValidator(v); err != nil { + return &ValidationError{Name: "category", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunDetailedLine.category": %w`, err)} + } + } + if v, ok := _u.mutation.PaymentTerm(); ok { + if err := chargeusagebasedrundetailedline.PaymentTermValidator(v); err != nil { + return &ValidationError{Name: "payment_term", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunDetailedLine.payment_term": %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 "ChargeUsageBasedRunDetailedLine.credits_applied": %w`, err)} + } + } + if v, ok := _u.mutation.PricerReferenceID(); ok { + if err := chargeusagebasedrundetailedline.PricerReferenceIDValidator(v); err != nil { + return &ValidationError{Name: "pricer_reference_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunDetailedLine.pricer_reference_id": %w`, err)} + } + } + if v, ok := _u.mutation.CorrectsRunID(); ok { + if err := chargeusagebasedrundetailedline.CorrectsRunIDValidator(v); err != nil { + return &ValidationError{Name: "corrects_run_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunDetailedLine.corrects_run_id": %w`, err)} + } + } + if _u.mutation.ChargeCleared() && len(_u.mutation.ChargeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBasedRunDetailedLine.charge"`) + } + if _u.mutation.RunCleared() && len(_u.mutation.RunIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBasedRunDetailedLine.run"`) + } + return nil +} + +func (_u *ChargeUsageBasedRunDetailedLineUpdateOne) sqlSave(ctx context.Context) (_node *ChargeUsageBasedRunDetailedLine, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeusagebasedrundetailedline.Table, chargeusagebasedrundetailedline.Columns, sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "ChargeUsageBasedRunDetailedLine.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, chargeusagebasedrundetailedline.FieldID) + for _, f := range fields { + if !chargeusagebasedrundetailedline.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != chargeusagebasedrundetailedline.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.ServicePeriodStart(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldServicePeriodStart, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodEnd(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldServicePeriodEnd, field.TypeTime, value) + } + if value, ok := _u.mutation.Quantity(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldQuantity, field.TypeOther, value) + } + if value, ok := _u.mutation.InvoicingAppExternalID(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldInvoicingAppExternalID, field.TypeString, value) + } + if _u.mutation.InvoicingAppExternalIDCleared() { + _spec.ClearField(chargeusagebasedrundetailedline.FieldInvoicingAppExternalID, field.TypeString) + } + if value, ok := _u.mutation.ChildUniqueReferenceID(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldChildUniqueReferenceID, field.TypeString, value) + } + if value, ok := _u.mutation.PerUnitAmount(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldPerUnitAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.Category(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldCategory, field.TypeEnum, value) + } + if value, ok := _u.mutation.PaymentTerm(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldPaymentTerm, field.TypeEnum, value) + } + if value, ok := _u.mutation.Index(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldIndex, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedIndex(); ok { + _spec.AddField(chargeusagebasedrundetailedline.FieldIndex, field.TypeInt, value) + } + if _u.mutation.IndexCleared() { + _spec.ClearField(chargeusagebasedrundetailedline.FieldIndex, field.TypeInt) + } + if value, ok := _u.mutation.CreditsApplied(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldCreditsApplied, field.TypeJSON, value) + } + if _u.mutation.CreditsAppliedCleared() { + _spec.ClearField(chargeusagebasedrundetailedline.FieldCreditsApplied, field.TypeJSON) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargeusagebasedrundetailedline.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(chargeusagebasedrundetailedline.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeusagebasedrundetailedline.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(chargeusagebasedrundetailedline.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesTotal(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldTaxesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldTaxesInclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldTaxesExclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.ChargesTotal(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldChargesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.DiscountsTotal(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldDiscountsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.CreditsTotal(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldCreditsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.Total(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.PricerReferenceID(); ok { + _spec.SetField(chargeusagebasedrundetailedline.FieldPricerReferenceID, field.TypeString, value) + } + if _u.mutation.ChargeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedrundetailedline.ChargeTable, + Columns: []string{chargeusagebasedrundetailedline.ChargeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebased.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ChargeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedrundetailedline.ChargeTable, + Columns: []string{chargeusagebasedrundetailedline.ChargeColumn}, + 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.RunCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedrundetailedline.RunTable, + Columns: []string{chargeusagebasedrundetailedline.RunColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RunIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedrundetailedline.RunTable, + Columns: []string{chargeusagebasedrundetailedline.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) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.CorrectsRunCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedrundetailedline.CorrectsRunTable, + Columns: []string{chargeusagebasedrundetailedline.CorrectsRunColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.CorrectsRunIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedrundetailedline.CorrectsRunTable, + Columns: []string{chargeusagebasedrundetailedline.CorrectsRunColumn}, + 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 = &ChargeUsageBasedRunDetailedLine{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{chargeusagebasedrundetailedline.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/ent/db/chargeusagebasedruninvoicedusage.go b/ent/db/chargeusagebasedruninvoicedusage.go new file mode 100644 index 0000000000000000000000000000000000000000..77ab5ed54a8a8c12cb310a8fe28f4544c0871810 --- /dev/null +++ b/ent/db/chargeusagebasedruninvoicedusage.go @@ -0,0 +1,324 @@ +// 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"` + // 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"` + // 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.FieldID, 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.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.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)) + 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(", ") + 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/ent/db/chargeusagebasedruninvoicedusage/chargeusagebasedruninvoicedusage.go b/ent/db/chargeusagebasedruninvoicedusage/chargeusagebasedruninvoicedusage.go new file mode 100644 index 0000000000000000000000000000000000000000..e8915b563ba5f1fc46d4da72ef0802a6c950cd1a --- /dev/null +++ b/ent/db/chargeusagebasedruninvoicedusage/chargeusagebasedruninvoicedusage.go @@ -0,0 +1,211 @@ +// 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" + // 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" + // 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, + FieldServicePeriodFrom, + FieldServicePeriodTo, + 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 ( + // 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() +} + +// 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() +} + +// 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/ent/db/chargeusagebasedruninvoicedusage/where.go b/ent/db/chargeusagebasedruninvoicedusage/where.go new file mode 100644 index 0000000000000000000000000000000000000000..050f34a3b2b3ec95ed1a2c04435b1d3a46f12155 --- /dev/null +++ b/ent/db/chargeusagebasedruninvoicedusage/where.go @@ -0,0 +1,930 @@ +// 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)) +} + +// 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)) +} + +// 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)) +} + +// 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)) +} + +// 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/ent/db/chargeusagebasedruninvoicedusage_create.go b/ent/db/chargeusagebasedruninvoicedusage_create.go new file mode 100644 index 0000000000000000000000000000000000000000..fc35e4ea2dd97b2ea83d824df998c59bae8ff4d4 --- /dev/null +++ b/ent/db/chargeusagebasedruninvoicedusage_create.go @@ -0,0 +1,1379 @@ +// 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 +} + +// 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 +} + +// 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 _, 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 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.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.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(). +// SetServicePeriodFrom(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) { +// SetServicePeriodFrom(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 + } +) + +// 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 +} + +// 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 +} + +// 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() + }) +} + +// 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) { +// SetServicePeriodFrom(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 +} + +// 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() + }) +} + +// 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/ent/db/chargeusagebasedruninvoicedusage_delete.go b/ent/db/chargeusagebasedruninvoicedusage_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..e4c9b4beb0f3d5fcead72eb19f32a2d42e5cb11e --- /dev/null +++ b/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/ent/db/chargeusagebasedruninvoicedusage_query.go b/ent/db/chargeusagebasedruninvoicedusage_query.go new file mode 100644 index 0000000000000000000000000000000000000000..de7a6ffa5a66f76230d37a278acdbe9ea085ba50 --- /dev/null +++ b/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 { +// ServicePeriodFrom time.Time `json:"service_period_from,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.ChargeUsageBasedRunInvoicedUsage.Query(). +// GroupBy(chargeusagebasedruninvoicedusage.FieldServicePeriodFrom). +// 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 { +// ServicePeriodFrom time.Time `json:"service_period_from,omitempty"` +// } +// +// client.ChargeUsageBasedRunInvoicedUsage.Query(). +// Select(chargeusagebasedruninvoicedusage.FieldServicePeriodFrom). +// 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/ent/db/chargeusagebasedruninvoicedusage_update.go b/ent/db/chargeusagebasedruninvoicedusage_update.go new file mode 100644 index 0000000000000000000000000000000000000000..d09680722f192ba528f871c2bd0ef4c6f2e42855 --- /dev/null +++ b/ent/db/chargeusagebasedruninvoicedusage_update.go @@ -0,0 +1,726 @@ +// 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 +} + +// 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 +} + +// 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.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.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.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 +} + +// 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 +} + +// 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.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.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.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/ent/db/chargeusagebasedrunpayment.go b/ent/db/chargeusagebasedrunpayment.go new file mode 100644 index 0000000000000000000000000000000000000000..0b39eeaa001ea6a3aca6c3bd2928cb517437a90e --- /dev/null +++ b/ent/db/chargeusagebasedrunpayment.go @@ -0,0 +1,323 @@ +// 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"` + // InvoiceID holds the value of the "invoice_id" field. + InvoiceID string `json:"invoice_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.FieldInvoiceID, 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.FieldInvoiceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field invoice_id", values[i]) + } else if value.Valid { + _m.InvoiceID = 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("invoice_id=") + builder.WriteString(_m.InvoiceID) + 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/ent/db/chargeusagebasedrunpayment/chargeusagebasedrunpayment.go b/ent/db/chargeusagebasedrunpayment/chargeusagebasedrunpayment.go new file mode 100644 index 0000000000000000000000000000000000000000..63842b1704613d640f9641b8572edc22dd78c83c --- /dev/null +++ b/ent/db/chargeusagebasedrunpayment/chargeusagebasedrunpayment.go @@ -0,0 +1,217 @@ +// 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" + // FieldInvoiceID holds the string denoting the invoice_id field in the database. + FieldInvoiceID = "invoice_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, + FieldInvoiceID, + 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() +} + +// ByInvoiceID orders the results by the invoice_id field. +func ByInvoiceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoiceID, 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/ent/db/chargeusagebasedrunpayment/where.go b/ent/db/chargeusagebasedrunpayment/where.go new file mode 100644 index 0000000000000000000000000000000000000000..517a58193c94da637d2e133968245eac0cdb1b37 --- /dev/null +++ b/ent/db/chargeusagebasedrunpayment/where.go @@ -0,0 +1,976 @@ +// 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)) +} + +// InvoiceID applies equality check predicate on the "invoice_id" field. It's identical to InvoiceIDEQ. +func InvoiceID(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldInvoiceID, 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)) +} + +// InvoiceIDEQ applies the EQ predicate on the "invoice_id" field. +func InvoiceIDEQ(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldInvoiceID, v)) +} + +// InvoiceIDNEQ applies the NEQ predicate on the "invoice_id" field. +func InvoiceIDNEQ(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNEQ(FieldInvoiceID, v)) +} + +// InvoiceIDIn applies the In predicate on the "invoice_id" field. +func InvoiceIDIn(vs ...string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIn(FieldInvoiceID, vs...)) +} + +// InvoiceIDNotIn applies the NotIn predicate on the "invoice_id" field. +func InvoiceIDNotIn(vs ...string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotIn(FieldInvoiceID, vs...)) +} + +// InvoiceIDGT applies the GT predicate on the "invoice_id" field. +func InvoiceIDGT(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGT(FieldInvoiceID, v)) +} + +// InvoiceIDGTE applies the GTE predicate on the "invoice_id" field. +func InvoiceIDGTE(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGTE(FieldInvoiceID, v)) +} + +// InvoiceIDLT applies the LT predicate on the "invoice_id" field. +func InvoiceIDLT(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLT(FieldInvoiceID, v)) +} + +// InvoiceIDLTE applies the LTE predicate on the "invoice_id" field. +func InvoiceIDLTE(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLTE(FieldInvoiceID, v)) +} + +// InvoiceIDContains applies the Contains predicate on the "invoice_id" field. +func InvoiceIDContains(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldContains(FieldInvoiceID, v)) +} + +// InvoiceIDHasPrefix applies the HasPrefix predicate on the "invoice_id" field. +func InvoiceIDHasPrefix(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldHasPrefix(FieldInvoiceID, v)) +} + +// InvoiceIDHasSuffix applies the HasSuffix predicate on the "invoice_id" field. +func InvoiceIDHasSuffix(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldHasSuffix(FieldInvoiceID, v)) +} + +// InvoiceIDEqualFold applies the EqualFold predicate on the "invoice_id" field. +func InvoiceIDEqualFold(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEqualFold(FieldInvoiceID, v)) +} + +// InvoiceIDContainsFold applies the ContainsFold predicate on the "invoice_id" field. +func InvoiceIDContainsFold(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldContainsFold(FieldInvoiceID, 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/ent/db/chargeusagebasedrunpayment_create.go b/ent/db/chargeusagebasedrunpayment_create.go new file mode 100644 index 0000000000000000000000000000000000000000..f4c944c398cadc9d1aebc7dae362173e1567f175 --- /dev/null +++ b/ent/db/chargeusagebasedrunpayment_create.go @@ -0,0 +1,1344 @@ +// 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 +} + +// SetInvoiceID sets the "invoice_id" field. +func (_c *ChargeUsageBasedRunPaymentCreate) SetInvoiceID(v string) *ChargeUsageBasedRunPaymentCreate { + _c.mutation.SetInvoiceID(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.InvoiceID(); !ok { + return &ValidationError{Name: "invoice_id", err: errors.New(`db: missing required field "ChargeUsageBasedRunPayment.invoice_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.InvoiceID(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldInvoiceID, field.TypeString, value) + _node.InvoiceID = 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.InvoiceID(); exists { + s.SetIgnore(chargeusagebasedrunpayment.FieldInvoiceID) + } + 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.InvoiceID(); exists { + s.SetIgnore(chargeusagebasedrunpayment.FieldInvoiceID) + } + 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/ent/db/chargeusagebasedrunpayment_delete.go b/ent/db/chargeusagebasedrunpayment_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..4d3285ca8a6409c1b4b46f950f144bffb09709f8 --- /dev/null +++ b/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/ent/db/chargeusagebasedrunpayment_query.go b/ent/db/chargeusagebasedrunpayment_query.go new file mode 100644 index 0000000000000000000000000000000000000000..4f781fccf57a614a393d0948e4106e5992fe5203 --- /dev/null +++ b/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/ent/db/chargeusagebasedrunpayment_update.go b/ent/db/chargeusagebasedrunpayment_update.go new file mode 100644 index 0000000000000000000000000000000000000000..75b104c2e179081d532a2209122590389ef29670 --- /dev/null +++ b/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/ent/db/chargeusagebasedruns.go b/ent/db/chargeusagebasedruns.go new file mode 100644 index 0000000000000000000000000000000000000000..e05acb5040f71bbb95a29332510e1d61397e8574 --- /dev/null +++ b/ent/db/chargeusagebasedruns.go @@ -0,0 +1,533 @@ +// 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/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "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" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" +) + +// 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"` + // 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"` + // ChargeID holds the value of the "charge_id" field. + ChargeID string `json:"charge_id,omitempty"` + // For future-proofing runs may diverge from the charge feature later, but today this matches the parent charge feature_id. + FeatureID string `json:"feature_id,omitempty"` + // Type holds the value of the "type" field. + Type usagebased.RealizationRunType `json:"type,omitempty"` + // InitialType holds the value of the "initial_type" field. + InitialType usagebased.RealizationRunType `json:"initial_type,omitempty"` + // StoredAtLt holds the value of the "stored_at_lt" field. + StoredAtLt time.Time `json:"stored_at_lt,omitempty"` + // ServicePeriodTo holds the value of the "service_period_to" field. + ServicePeriodTo time.Time `json:"service_period_to,omitempty"` + // DetailedLinesPresent holds the value of the "detailed_lines_present" field. + DetailedLinesPresent bool `json:"detailed_lines_present,omitempty"` + // LineID holds the value of the "line_id" field. + LineID *string `json:"line_id,omitempty"` + // InvoiceID holds the value of the "invoice_id" field. + InvoiceID *string `json:"invoice_id,omitempty"` + // MeteredQuantity holds the value of the "metered_quantity" field. + MeteredQuantity alpacadecimal.Decimal `json:"metered_quantity,omitempty"` + // NoFiatTransactionRequired holds the value of the "no_fiat_transaction_required" field. + NoFiatTransactionRequired bool `json:"no_fiat_transaction_required,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"` + // Feature holds the value of the feature edge. + Feature *Feature `json:"feature,omitempty"` + // BillingInvoiceLine holds the value of the billing_invoice_line edge. + BillingInvoiceLine *BillingInvoiceLine `json:"billing_invoice_line,omitempty"` + // BillingInvoice holds the value of the billing_invoice edge. + BillingInvoice *BillingInvoice `json:"billing_invoice,omitempty"` + // CreditAllocations holds the value of the credit_allocations edge. + CreditAllocations []*ChargeUsageBasedRunCreditAllocations `json:"credit_allocations,omitempty"` + // DetailedLines holds the value of the detailed_lines edge. + DetailedLines []*ChargeUsageBasedRunDetailedLine `json:"detailed_lines,omitempty"` + // CorrectedDetailedLines holds the value of the corrected_detailed_lines edge. + CorrectedDetailedLines []*ChargeUsageBasedRunDetailedLine `json:"corrected_detailed_lines,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 [9]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"} +} + +// FeatureOrErr returns the Feature value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedRunsEdges) FeatureOrErr() (*Feature, error) { + if e.Feature != nil { + return e.Feature, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: dbfeature.Label} + } + return nil, &NotLoadedError{edge: "feature"} +} + +// BillingInvoiceLineOrErr returns the BillingInvoiceLine value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedRunsEdges) BillingInvoiceLineOrErr() (*BillingInvoiceLine, error) { + if e.BillingInvoiceLine != nil { + return e.BillingInvoiceLine, nil + } else if e.loadedTypes[2] { + return nil, &NotFoundError{label: billinginvoiceline.Label} + } + return nil, &NotLoadedError{edge: "billing_invoice_line"} +} + +// BillingInvoiceOrErr returns the BillingInvoice value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedRunsEdges) BillingInvoiceOrErr() (*BillingInvoice, error) { + if e.BillingInvoice != nil { + return e.BillingInvoice, nil + } else if e.loadedTypes[3] { + return nil, &NotFoundError{label: billinginvoice.Label} + } + return nil, &NotLoadedError{edge: "billing_invoice"} +} + +// 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[4] { + return e.CreditAllocations, nil + } + return nil, &NotLoadedError{edge: "credit_allocations"} +} + +// DetailedLinesOrErr returns the DetailedLines value or an error if the edge +// was not loaded in eager-loading. +func (e ChargeUsageBasedRunsEdges) DetailedLinesOrErr() ([]*ChargeUsageBasedRunDetailedLine, error) { + if e.loadedTypes[5] { + return e.DetailedLines, nil + } + return nil, &NotLoadedError{edge: "detailed_lines"} +} + +// CorrectedDetailedLinesOrErr returns the CorrectedDetailedLines value or an error if the edge +// was not loaded in eager-loading. +func (e ChargeUsageBasedRunsEdges) CorrectedDetailedLinesOrErr() ([]*ChargeUsageBasedRunDetailedLine, error) { + if e.loadedTypes[6] { + return e.CorrectedDetailedLines, nil + } + return nil, &NotLoadedError{edge: "corrected_detailed_lines"} +} + +// 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[7] { + 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[8] { + 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.FieldAmount, chargeusagebasedruns.FieldTaxesTotal, chargeusagebasedruns.FieldTaxesInclusiveTotal, chargeusagebasedruns.FieldTaxesExclusiveTotal, chargeusagebasedruns.FieldChargesTotal, chargeusagebasedruns.FieldDiscountsTotal, chargeusagebasedruns.FieldCreditsTotal, chargeusagebasedruns.FieldTotal, chargeusagebasedruns.FieldMeteredQuantity: + values[i] = new(alpacadecimal.Decimal) + case chargeusagebasedruns.FieldDetailedLinesPresent, chargeusagebasedruns.FieldNoFiatTransactionRequired: + values[i] = new(sql.NullBool) + case chargeusagebasedruns.FieldID, chargeusagebasedruns.FieldNamespace, chargeusagebasedruns.FieldChargeID, chargeusagebasedruns.FieldFeatureID, chargeusagebasedruns.FieldType, chargeusagebasedruns.FieldInitialType, chargeusagebasedruns.FieldLineID, chargeusagebasedruns.FieldInvoiceID: + values[i] = new(sql.NullString) + case chargeusagebasedruns.FieldCreatedAt, chargeusagebasedruns.FieldUpdatedAt, chargeusagebasedruns.FieldDeletedAt, chargeusagebasedruns.FieldStoredAtLt, chargeusagebasedruns.FieldServicePeriodTo: + 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.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 chargeusagebasedruns.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 chargeusagebasedruns.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 chargeusagebasedruns.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 chargeusagebasedruns.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 chargeusagebasedruns.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 chargeusagebasedruns.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 chargeusagebasedruns.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 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.FieldFeatureID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field feature_id", values[i]) + } else if value.Valid { + _m.FeatureID = 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.FieldInitialType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field initial_type", values[i]) + } else if value.Valid { + _m.InitialType = usagebased.RealizationRunType(value.String) + } + case chargeusagebasedruns.FieldStoredAtLt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field stored_at_lt", values[i]) + } else if value.Valid { + _m.StoredAtLt = value.Time + } + case chargeusagebasedruns.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 chargeusagebasedruns.FieldDetailedLinesPresent: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field detailed_lines_present", values[i]) + } else if value.Valid { + _m.DetailedLinesPresent = value.Bool + } + case chargeusagebasedruns.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 chargeusagebasedruns.FieldInvoiceID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field invoice_id", values[i]) + } else if value.Valid { + _m.InvoiceID = new(string) + *_m.InvoiceID = value.String + } + case chargeusagebasedruns.FieldMeteredQuantity: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field metered_quantity", values[i]) + } else if value != nil { + _m.MeteredQuantity = *value + } + case chargeusagebasedruns.FieldNoFiatTransactionRequired: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field no_fiat_transaction_required", values[i]) + } else if value.Valid { + _m.NoFiatTransactionRequired = value.Bool + } + 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) +} + +// QueryFeature queries the "feature" edge of the ChargeUsageBasedRuns entity. +func (_m *ChargeUsageBasedRuns) QueryFeature() *FeatureQuery { + return NewChargeUsageBasedRunsClient(_m.config).QueryFeature(_m) +} + +// QueryBillingInvoiceLine queries the "billing_invoice_line" edge of the ChargeUsageBasedRuns entity. +func (_m *ChargeUsageBasedRuns) QueryBillingInvoiceLine() *BillingInvoiceLineQuery { + return NewChargeUsageBasedRunsClient(_m.config).QueryBillingInvoiceLine(_m) +} + +// QueryBillingInvoice queries the "billing_invoice" edge of the ChargeUsageBasedRuns entity. +func (_m *ChargeUsageBasedRuns) QueryBillingInvoice() *BillingInvoiceQuery { + return NewChargeUsageBasedRunsClient(_m.config).QueryBillingInvoice(_m) +} + +// QueryCreditAllocations queries the "credit_allocations" edge of the ChargeUsageBasedRuns entity. +func (_m *ChargeUsageBasedRuns) QueryCreditAllocations() *ChargeUsageBasedRunCreditAllocationsQuery { + return NewChargeUsageBasedRunsClient(_m.config).QueryCreditAllocations(_m) +} + +// QueryDetailedLines queries the "detailed_lines" edge of the ChargeUsageBasedRuns entity. +func (_m *ChargeUsageBasedRuns) QueryDetailedLines() *ChargeUsageBasedRunDetailedLineQuery { + return NewChargeUsageBasedRunsClient(_m.config).QueryDetailedLines(_m) +} + +// QueryCorrectedDetailedLines queries the "corrected_detailed_lines" edge of the ChargeUsageBasedRuns entity. +func (_m *ChargeUsageBasedRuns) QueryCorrectedDetailedLines() *ChargeUsageBasedRunDetailedLineQuery { + return NewChargeUsageBasedRunsClient(_m.config).QueryCorrectedDetailedLines(_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("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("charge_id=") + builder.WriteString(_m.ChargeID) + builder.WriteString(", ") + builder.WriteString("feature_id=") + builder.WriteString(_m.FeatureID) + builder.WriteString(", ") + builder.WriteString("type=") + builder.WriteString(fmt.Sprintf("%v", _m.Type)) + builder.WriteString(", ") + builder.WriteString("initial_type=") + builder.WriteString(fmt.Sprintf("%v", _m.InitialType)) + builder.WriteString(", ") + builder.WriteString("stored_at_lt=") + builder.WriteString(_m.StoredAtLt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("service_period_to=") + builder.WriteString(_m.ServicePeriodTo.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("detailed_lines_present=") + builder.WriteString(fmt.Sprintf("%v", _m.DetailedLinesPresent)) + builder.WriteString(", ") + if v := _m.LineID; v != nil { + builder.WriteString("line_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.InvoiceID; v != nil { + builder.WriteString("invoice_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("metered_quantity=") + builder.WriteString(fmt.Sprintf("%v", _m.MeteredQuantity)) + builder.WriteString(", ") + builder.WriteString("no_fiat_transaction_required=") + builder.WriteString(fmt.Sprintf("%v", _m.NoFiatTransactionRequired)) + builder.WriteByte(')') + return builder.String() +} + +// ChargeUsageBasedRunsSlice is a parsable slice of ChargeUsageBasedRuns. +type ChargeUsageBasedRunsSlice []*ChargeUsageBasedRuns diff --git a/ent/db/chargeusagebasedruns/chargeusagebasedruns.go b/ent/db/chargeusagebasedruns/chargeusagebasedruns.go new file mode 100644 index 0000000000000000000000000000000000000000..9bb21a3692475232ad2d9723a391d72bb26b127b --- /dev/null +++ b/ent/db/chargeusagebasedruns/chargeusagebasedruns.go @@ -0,0 +1,495 @@ +// 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" + // 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" + // FieldChargeID holds the string denoting the charge_id field in the database. + FieldChargeID = "charge_id" + // FieldFeatureID holds the string denoting the feature_id field in the database. + FieldFeatureID = "feature_id" + // FieldType holds the string denoting the type field in the database. + FieldType = "type" + // FieldInitialType holds the string denoting the initial_type field in the database. + FieldInitialType = "initial_type" + // FieldStoredAtLt holds the string denoting the stored_at_lt field in the database. + FieldStoredAtLt = "stored_at_lt" + // FieldServicePeriodTo holds the string denoting the service_period_to field in the database. + FieldServicePeriodTo = "service_period_to" + // FieldDetailedLinesPresent holds the string denoting the detailed_lines_present field in the database. + FieldDetailedLinesPresent = "detailed_lines_present" + // FieldLineID holds the string denoting the line_id field in the database. + FieldLineID = "line_id" + // FieldInvoiceID holds the string denoting the invoice_id field in the database. + FieldInvoiceID = "invoice_id" + // FieldMeteredQuantity holds the string denoting the metered_quantity field in the database. + FieldMeteredQuantity = "metered_quantity" + // FieldNoFiatTransactionRequired holds the string denoting the no_fiat_transaction_required field in the database. + FieldNoFiatTransactionRequired = "no_fiat_transaction_required" + // EdgeUsageBased holds the string denoting the usage_based edge name in mutations. + EdgeUsageBased = "usage_based" + // EdgeFeature holds the string denoting the feature edge name in mutations. + EdgeFeature = "feature" + // EdgeBillingInvoiceLine holds the string denoting the billing_invoice_line edge name in mutations. + EdgeBillingInvoiceLine = "billing_invoice_line" + // EdgeBillingInvoice holds the string denoting the billing_invoice edge name in mutations. + EdgeBillingInvoice = "billing_invoice" + // EdgeCreditAllocations holds the string denoting the credit_allocations edge name in mutations. + EdgeCreditAllocations = "credit_allocations" + // EdgeDetailedLines holds the string denoting the detailed_lines edge name in mutations. + EdgeDetailedLines = "detailed_lines" + // EdgeCorrectedDetailedLines holds the string denoting the corrected_detailed_lines edge name in mutations. + EdgeCorrectedDetailedLines = "corrected_detailed_lines" + // 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" + // FeatureTable is the table that holds the feature relation/edge. + FeatureTable = "charge_usage_based_runs" + // FeatureInverseTable is the table name for the Feature entity. + // It exists in this package in order to avoid circular dependency with the "dbfeature" package. + FeatureInverseTable = "features" + // FeatureColumn is the table column denoting the feature relation/edge. + FeatureColumn = "feature_id" + // BillingInvoiceLineTable is the table that holds the billing_invoice_line relation/edge. + BillingInvoiceLineTable = "charge_usage_based_runs" + // BillingInvoiceLineInverseTable is the table name for the BillingInvoiceLine entity. + // It exists in this package in order to avoid circular dependency with the "billinginvoiceline" package. + BillingInvoiceLineInverseTable = "billing_invoice_lines" + // BillingInvoiceLineColumn is the table column denoting the billing_invoice_line relation/edge. + BillingInvoiceLineColumn = "line_id" + // BillingInvoiceTable is the table that holds the billing_invoice relation/edge. + BillingInvoiceTable = "charge_usage_based_runs" + // BillingInvoiceInverseTable is the table name for the BillingInvoice entity. + // It exists in this package in order to avoid circular dependency with the "billinginvoice" package. + BillingInvoiceInverseTable = "billing_invoices" + // BillingInvoiceColumn is the table column denoting the billing_invoice relation/edge. + BillingInvoiceColumn = "invoice_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" + // DetailedLinesTable is the table that holds the detailed_lines relation/edge. + DetailedLinesTable = "charge_usage_based_run_detailed_line" + // DetailedLinesInverseTable is the table name for the ChargeUsageBasedRunDetailedLine entity. + // It exists in this package in order to avoid circular dependency with the "chargeusagebasedrundetailedline" package. + DetailedLinesInverseTable = "charge_usage_based_run_detailed_line" + // DetailedLinesColumn is the table column denoting the detailed_lines relation/edge. + DetailedLinesColumn = "run_id" + // CorrectedDetailedLinesTable is the table that holds the corrected_detailed_lines relation/edge. + CorrectedDetailedLinesTable = "charge_usage_based_run_detailed_line" + // CorrectedDetailedLinesInverseTable is the table name for the ChargeUsageBasedRunDetailedLine entity. + // It exists in this package in order to avoid circular dependency with the "chargeusagebasedrundetailedline" package. + CorrectedDetailedLinesInverseTable = "charge_usage_based_run_detailed_line" + // CorrectedDetailedLinesColumn is the table column denoting the corrected_detailed_lines relation/edge. + CorrectedDetailedLinesColumn = "corrects_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, + FieldAmount, + FieldTaxesTotal, + FieldTaxesInclusiveTotal, + FieldTaxesExclusiveTotal, + FieldChargesTotal, + FieldDiscountsTotal, + FieldCreditsTotal, + FieldTotal, + FieldChargeID, + FieldFeatureID, + FieldType, + FieldInitialType, + FieldStoredAtLt, + FieldServicePeriodTo, + FieldDetailedLinesPresent, + FieldLineID, + FieldInvoiceID, + FieldMeteredQuantity, + FieldNoFiatTransactionRequired, +} + +// 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 + // FeatureIDValidator is a validator for the "feature_id" field. It is called by the builders before save. + FeatureIDValidator func(string) error + // LineIDValidator is a validator for the "line_id" field. It is called by the builders before save. + LineIDValidator func(string) error + // InvoiceIDValidator is a validator for the "invoice_id" field. It is called by the builders before save. + InvoiceIDValidator func(string) error + // 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 "final_realization", "partial_invoice", "invalid_due_to_unsupported_credit_note": + return nil + default: + return fmt.Errorf("chargeusagebasedruns: invalid enum value for type field: %q", _type) + } +} + +// InitialTypeValidator is a validator for the "initial_type" field enum values. It is called by the builders before save. +func InitialTypeValidator(it usagebased.RealizationRunType) error { + switch it { + case "final_realization", "partial_invoice", "invalid_due_to_unsupported_credit_note": + return nil + default: + return fmt.Errorf("chargeusagebasedruns: invalid enum value for initial_type field: %q", it) + } +} + +// 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() +} + +// 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() +} + +// ByChargeID orders the results by the charge_id field. +func ByChargeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChargeID, opts...).ToFunc() +} + +// ByFeatureID orders the results by the feature_id field. +func ByFeatureID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFeatureID, opts...).ToFunc() +} + +// ByType orders the results by the type field. +func ByType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldType, opts...).ToFunc() +} + +// ByInitialType orders the results by the initial_type field. +func ByInitialType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInitialType, opts...).ToFunc() +} + +// ByStoredAtLt orders the results by the stored_at_lt field. +func ByStoredAtLt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStoredAtLt, opts...).ToFunc() +} + +// ByServicePeriodTo orders the results by the service_period_to field. +func ByServicePeriodTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldServicePeriodTo, opts...).ToFunc() +} + +// ByDetailedLinesPresent orders the results by the detailed_lines_present field. +func ByDetailedLinesPresent(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDetailedLinesPresent, opts...).ToFunc() +} + +// ByLineID orders the results by the line_id field. +func ByLineID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLineID, opts...).ToFunc() +} + +// ByInvoiceID orders the results by the invoice_id field. +func ByInvoiceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoiceID, opts...).ToFunc() +} + +// ByMeteredQuantity orders the results by the metered_quantity field. +func ByMeteredQuantity(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMeteredQuantity, opts...).ToFunc() +} + +// ByNoFiatTransactionRequired orders the results by the no_fiat_transaction_required field. +func ByNoFiatTransactionRequired(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldNoFiatTransactionRequired, 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...)) + } +} + +// ByFeatureField orders the results by feature field. +func ByFeatureField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newFeatureStep(), sql.OrderByField(field, opts...)) + } +} + +// ByBillingInvoiceLineField orders the results by billing_invoice_line field. +func ByBillingInvoiceLineField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBillingInvoiceLineStep(), sql.OrderByField(field, opts...)) + } +} + +// ByBillingInvoiceField orders the results by billing_invoice field. +func ByBillingInvoiceField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBillingInvoiceStep(), 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...)...) + } +} + +// ByDetailedLinesCount orders the results by detailed_lines count. +func ByDetailedLinesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newDetailedLinesStep(), opts...) + } +} + +// ByDetailedLines orders the results by detailed_lines terms. +func ByDetailedLines(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newDetailedLinesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByCorrectedDetailedLinesCount orders the results by corrected_detailed_lines count. +func ByCorrectedDetailedLinesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newCorrectedDetailedLinesStep(), opts...) + } +} + +// ByCorrectedDetailedLines orders the results by corrected_detailed_lines terms. +func ByCorrectedDetailedLines(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCorrectedDetailedLinesStep(), 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 newFeatureStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(FeatureInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, FeatureTable, FeatureColumn), + ) +} +func newBillingInvoiceLineStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BillingInvoiceLineInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, BillingInvoiceLineTable, BillingInvoiceLineColumn), + ) +} +func newBillingInvoiceStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BillingInvoiceInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, BillingInvoiceTable, BillingInvoiceColumn), + ) +} +func newCreditAllocationsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CreditAllocationsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, CreditAllocationsTable, CreditAllocationsColumn), + ) +} +func newDetailedLinesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(DetailedLinesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, DetailedLinesTable, DetailedLinesColumn), + ) +} +func newCorrectedDetailedLinesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CorrectedDetailedLinesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, CorrectedDetailedLinesTable, CorrectedDetailedLinesColumn), + ) +} +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/ent/db/chargeusagebasedruns/where.go b/ent/db/chargeusagebasedruns/where.go new file mode 100644 index 0000000000000000000000000000000000000000..bea7c71fb7946fa079879c4dbbd3d3bb6ebefac5 --- /dev/null +++ b/ent/db/chargeusagebasedruns/where.go @@ -0,0 +1,1390 @@ +// 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)) +} + +// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ. +func Amount(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(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.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(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.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(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.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(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.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(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.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(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.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldCreditsTotal, v)) +} + +// Total applies equality check predicate on the "total" field. It's identical to TotalEQ. +func Total(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldTotal, 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)) +} + +// FeatureID applies equality check predicate on the "feature_id" field. It's identical to FeatureIDEQ. +func FeatureID(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldFeatureID, v)) +} + +// StoredAtLt applies equality check predicate on the "stored_at_lt" field. It's identical to StoredAtLtEQ. +func StoredAtLt(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldStoredAtLt, v)) +} + +// ServicePeriodTo applies equality check predicate on the "service_period_to" field. It's identical to ServicePeriodToEQ. +func ServicePeriodTo(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// DetailedLinesPresent applies equality check predicate on the "detailed_lines_present" field. It's identical to DetailedLinesPresentEQ. +func DetailedLinesPresent(v bool) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldDetailedLinesPresent, v)) +} + +// LineID applies equality check predicate on the "line_id" field. It's identical to LineIDEQ. +func LineID(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldLineID, v)) +} + +// InvoiceID applies equality check predicate on the "invoice_id" field. It's identical to InvoiceIDEQ. +func InvoiceID(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldInvoiceID, v)) +} + +// MeteredQuantity applies equality check predicate on the "metered_quantity" field. It's identical to MeteredQuantityEQ. +func MeteredQuantity(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldMeteredQuantity, v)) +} + +// NoFiatTransactionRequired applies equality check predicate on the "no_fiat_transaction_required" field. It's identical to NoFiatTransactionRequiredEQ. +func NoFiatTransactionRequired(v bool) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldNoFiatTransactionRequired, 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)) +} + +// AmountEQ applies the EQ predicate on the "amount" field. +func AmountEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldAmount, v)) +} + +// AmountNEQ applies the NEQ predicate on the "amount" field. +func AmountNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldAmount, v)) +} + +// AmountIn applies the In predicate on the "amount" field. +func AmountIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldAmount, vs...)) +} + +// AmountNotIn applies the NotIn predicate on the "amount" field. +func AmountNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldAmount, vs...)) +} + +// AmountGT applies the GT predicate on the "amount" field. +func AmountGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldAmount, v)) +} + +// AmountGTE applies the GTE predicate on the "amount" field. +func AmountGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldAmount, v)) +} + +// AmountLT applies the LT predicate on the "amount" field. +func AmountLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldAmount, v)) +} + +// AmountLTE applies the LTE predicate on the "amount" field. +func AmountLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldAmount, v)) +} + +// TaxesTotalEQ applies the EQ predicate on the "taxes_total" field. +func TaxesTotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldTaxesTotal, v)) +} + +// TaxesTotalNEQ applies the NEQ predicate on the "taxes_total" field. +func TaxesTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldTaxesTotal, v)) +} + +// TaxesTotalIn applies the In predicate on the "taxes_total" field. +func TaxesTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldTaxesTotal, vs...)) +} + +// TaxesTotalNotIn applies the NotIn predicate on the "taxes_total" field. +func TaxesTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldTaxesTotal, vs...)) +} + +// TaxesTotalGT applies the GT predicate on the "taxes_total" field. +func TaxesTotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldTaxesTotal, v)) +} + +// TaxesTotalGTE applies the GTE predicate on the "taxes_total" field. +func TaxesTotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldTaxesTotal, v)) +} + +// TaxesTotalLT applies the LT predicate on the "taxes_total" field. +func TaxesTotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldTaxesTotal, v)) +} + +// TaxesTotalLTE applies the LTE predicate on the "taxes_total" field. +func TaxesTotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldTaxesTotal, v)) +} + +// TaxesInclusiveTotalEQ applies the EQ predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalNEQ applies the NEQ predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalIn applies the In predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldTaxesInclusiveTotal, vs...)) +} + +// TaxesInclusiveTotalNotIn applies the NotIn predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldTaxesInclusiveTotal, vs...)) +} + +// TaxesInclusiveTotalGT applies the GT predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalGTE applies the GTE predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalLT applies the LT predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalLTE applies the LTE predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldTaxesInclusiveTotal, v)) +} + +// TaxesExclusiveTotalEQ applies the EQ predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalNEQ applies the NEQ predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalIn applies the In predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldTaxesExclusiveTotal, vs...)) +} + +// TaxesExclusiveTotalNotIn applies the NotIn predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldTaxesExclusiveTotal, vs...)) +} + +// TaxesExclusiveTotalGT applies the GT predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalGTE applies the GTE predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalLT applies the LT predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalLTE applies the LTE predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldTaxesExclusiveTotal, v)) +} + +// ChargesTotalEQ applies the EQ predicate on the "charges_total" field. +func ChargesTotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldChargesTotal, v)) +} + +// ChargesTotalNEQ applies the NEQ predicate on the "charges_total" field. +func ChargesTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldChargesTotal, v)) +} + +// ChargesTotalIn applies the In predicate on the "charges_total" field. +func ChargesTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldChargesTotal, vs...)) +} + +// ChargesTotalNotIn applies the NotIn predicate on the "charges_total" field. +func ChargesTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldChargesTotal, vs...)) +} + +// ChargesTotalGT applies the GT predicate on the "charges_total" field. +func ChargesTotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldChargesTotal, v)) +} + +// ChargesTotalGTE applies the GTE predicate on the "charges_total" field. +func ChargesTotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldChargesTotal, v)) +} + +// ChargesTotalLT applies the LT predicate on the "charges_total" field. +func ChargesTotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldChargesTotal, v)) +} + +// ChargesTotalLTE applies the LTE predicate on the "charges_total" field. +func ChargesTotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldChargesTotal, v)) +} + +// DiscountsTotalEQ applies the EQ predicate on the "discounts_total" field. +func DiscountsTotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldDiscountsTotal, v)) +} + +// DiscountsTotalNEQ applies the NEQ predicate on the "discounts_total" field. +func DiscountsTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldDiscountsTotal, v)) +} + +// DiscountsTotalIn applies the In predicate on the "discounts_total" field. +func DiscountsTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldDiscountsTotal, vs...)) +} + +// DiscountsTotalNotIn applies the NotIn predicate on the "discounts_total" field. +func DiscountsTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldDiscountsTotal, vs...)) +} + +// DiscountsTotalGT applies the GT predicate on the "discounts_total" field. +func DiscountsTotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldDiscountsTotal, v)) +} + +// DiscountsTotalGTE applies the GTE predicate on the "discounts_total" field. +func DiscountsTotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldDiscountsTotal, v)) +} + +// DiscountsTotalLT applies the LT predicate on the "discounts_total" field. +func DiscountsTotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldDiscountsTotal, v)) +} + +// DiscountsTotalLTE applies the LTE predicate on the "discounts_total" field. +func DiscountsTotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldDiscountsTotal, v)) +} + +// CreditsTotalEQ applies the EQ predicate on the "credits_total" field. +func CreditsTotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldCreditsTotal, v)) +} + +// CreditsTotalNEQ applies the NEQ predicate on the "credits_total" field. +func CreditsTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldCreditsTotal, v)) +} + +// CreditsTotalIn applies the In predicate on the "credits_total" field. +func CreditsTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldCreditsTotal, vs...)) +} + +// CreditsTotalNotIn applies the NotIn predicate on the "credits_total" field. +func CreditsTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldCreditsTotal, vs...)) +} + +// CreditsTotalGT applies the GT predicate on the "credits_total" field. +func CreditsTotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldCreditsTotal, v)) +} + +// CreditsTotalGTE applies the GTE predicate on the "credits_total" field. +func CreditsTotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldCreditsTotal, v)) +} + +// CreditsTotalLT applies the LT predicate on the "credits_total" field. +func CreditsTotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldCreditsTotal, v)) +} + +// CreditsTotalLTE applies the LTE predicate on the "credits_total" field. +func CreditsTotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldCreditsTotal, v)) +} + +// TotalEQ applies the EQ predicate on the "total" field. +func TotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldTotal, v)) +} + +// TotalNEQ applies the NEQ predicate on the "total" field. +func TotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldTotal, v)) +} + +// TotalIn applies the In predicate on the "total" field. +func TotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldTotal, vs...)) +} + +// TotalNotIn applies the NotIn predicate on the "total" field. +func TotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldTotal, vs...)) +} + +// TotalGT applies the GT predicate on the "total" field. +func TotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldTotal, v)) +} + +// TotalGTE applies the GTE predicate on the "total" field. +func TotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldTotal, v)) +} + +// TotalLT applies the LT predicate on the "total" field. +func TotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldTotal, v)) +} + +// TotalLTE applies the LTE predicate on the "total" field. +func TotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldTotal, v)) +} + +// 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)) +} + +// FeatureIDEQ applies the EQ predicate on the "feature_id" field. +func FeatureIDEQ(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldFeatureID, v)) +} + +// FeatureIDNEQ applies the NEQ predicate on the "feature_id" field. +func FeatureIDNEQ(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldFeatureID, v)) +} + +// FeatureIDIn applies the In predicate on the "feature_id" field. +func FeatureIDIn(vs ...string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldFeatureID, vs...)) +} + +// FeatureIDNotIn applies the NotIn predicate on the "feature_id" field. +func FeatureIDNotIn(vs ...string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldFeatureID, vs...)) +} + +// FeatureIDGT applies the GT predicate on the "feature_id" field. +func FeatureIDGT(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldFeatureID, v)) +} + +// FeatureIDGTE applies the GTE predicate on the "feature_id" field. +func FeatureIDGTE(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldFeatureID, v)) +} + +// FeatureIDLT applies the LT predicate on the "feature_id" field. +func FeatureIDLT(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldFeatureID, v)) +} + +// FeatureIDLTE applies the LTE predicate on the "feature_id" field. +func FeatureIDLTE(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldFeatureID, v)) +} + +// FeatureIDContains applies the Contains predicate on the "feature_id" field. +func FeatureIDContains(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldContains(FieldFeatureID, v)) +} + +// FeatureIDHasPrefix applies the HasPrefix predicate on the "feature_id" field. +func FeatureIDHasPrefix(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldHasPrefix(FieldFeatureID, v)) +} + +// FeatureIDHasSuffix applies the HasSuffix predicate on the "feature_id" field. +func FeatureIDHasSuffix(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldHasSuffix(FieldFeatureID, v)) +} + +// FeatureIDEqualFold applies the EqualFold predicate on the "feature_id" field. +func FeatureIDEqualFold(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEqualFold(FieldFeatureID, v)) +} + +// FeatureIDContainsFold applies the ContainsFold predicate on the "feature_id" field. +func FeatureIDContainsFold(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldContainsFold(FieldFeatureID, 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...)) +} + +// InitialTypeEQ applies the EQ predicate on the "initial_type" field. +func InitialTypeEQ(v usagebased.RealizationRunType) predicate.ChargeUsageBasedRuns { + vc := v + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldInitialType, vc)) +} + +// InitialTypeNEQ applies the NEQ predicate on the "initial_type" field. +func InitialTypeNEQ(v usagebased.RealizationRunType) predicate.ChargeUsageBasedRuns { + vc := v + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldInitialType, vc)) +} + +// InitialTypeIn applies the In predicate on the "initial_type" field. +func InitialTypeIn(vs ...usagebased.RealizationRunType) predicate.ChargeUsageBasedRuns { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldInitialType, v...)) +} + +// InitialTypeNotIn applies the NotIn predicate on the "initial_type" field. +func InitialTypeNotIn(vs ...usagebased.RealizationRunType) predicate.ChargeUsageBasedRuns { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldInitialType, v...)) +} + +// StoredAtLtEQ applies the EQ predicate on the "stored_at_lt" field. +func StoredAtLtEQ(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldStoredAtLt, v)) +} + +// StoredAtLtNEQ applies the NEQ predicate on the "stored_at_lt" field. +func StoredAtLtNEQ(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldStoredAtLt, v)) +} + +// StoredAtLtIn applies the In predicate on the "stored_at_lt" field. +func StoredAtLtIn(vs ...time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldStoredAtLt, vs...)) +} + +// StoredAtLtNotIn applies the NotIn predicate on the "stored_at_lt" field. +func StoredAtLtNotIn(vs ...time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldStoredAtLt, vs...)) +} + +// StoredAtLtGT applies the GT predicate on the "stored_at_lt" field. +func StoredAtLtGT(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldStoredAtLt, v)) +} + +// StoredAtLtGTE applies the GTE predicate on the "stored_at_lt" field. +func StoredAtLtGTE(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldStoredAtLt, v)) +} + +// StoredAtLtLT applies the LT predicate on the "stored_at_lt" field. +func StoredAtLtLT(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldStoredAtLt, v)) +} + +// StoredAtLtLTE applies the LTE predicate on the "stored_at_lt" field. +func StoredAtLtLTE(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldStoredAtLt, v)) +} + +// ServicePeriodToEQ applies the EQ predicate on the "service_period_to" field. +func ServicePeriodToEQ(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToNEQ applies the NEQ predicate on the "service_period_to" field. +func ServicePeriodToNEQ(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToIn applies the In predicate on the "service_period_to" field. +func ServicePeriodToIn(vs ...time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToNotIn applies the NotIn predicate on the "service_period_to" field. +func ServicePeriodToNotIn(vs ...time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToGT applies the GT predicate on the "service_period_to" field. +func ServicePeriodToGT(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToGTE applies the GTE predicate on the "service_period_to" field. +func ServicePeriodToGTE(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLT applies the LT predicate on the "service_period_to" field. +func ServicePeriodToLT(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLTE applies the LTE predicate on the "service_period_to" field. +func ServicePeriodToLTE(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldServicePeriodTo, v)) +} + +// DetailedLinesPresentEQ applies the EQ predicate on the "detailed_lines_present" field. +func DetailedLinesPresentEQ(v bool) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldDetailedLinesPresent, v)) +} + +// DetailedLinesPresentNEQ applies the NEQ predicate on the "detailed_lines_present" field. +func DetailedLinesPresentNEQ(v bool) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldDetailedLinesPresent, v)) +} + +// LineIDEQ applies the EQ predicate on the "line_id" field. +func LineIDEQ(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldLineID, v)) +} + +// LineIDNEQ applies the NEQ predicate on the "line_id" field. +func LineIDNEQ(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldLineID, v)) +} + +// LineIDIn applies the In predicate on the "line_id" field. +func LineIDIn(vs ...string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldLineID, vs...)) +} + +// LineIDNotIn applies the NotIn predicate on the "line_id" field. +func LineIDNotIn(vs ...string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldLineID, vs...)) +} + +// LineIDGT applies the GT predicate on the "line_id" field. +func LineIDGT(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldLineID, v)) +} + +// LineIDGTE applies the GTE predicate on the "line_id" field. +func LineIDGTE(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldLineID, v)) +} + +// LineIDLT applies the LT predicate on the "line_id" field. +func LineIDLT(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldLineID, v)) +} + +// LineIDLTE applies the LTE predicate on the "line_id" field. +func LineIDLTE(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldLineID, v)) +} + +// LineIDContains applies the Contains predicate on the "line_id" field. +func LineIDContains(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldContains(FieldLineID, v)) +} + +// LineIDHasPrefix applies the HasPrefix predicate on the "line_id" field. +func LineIDHasPrefix(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldHasPrefix(FieldLineID, v)) +} + +// LineIDHasSuffix applies the HasSuffix predicate on the "line_id" field. +func LineIDHasSuffix(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldHasSuffix(FieldLineID, v)) +} + +// LineIDIsNil applies the IsNil predicate on the "line_id" field. +func LineIDIsNil() predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIsNull(FieldLineID)) +} + +// LineIDNotNil applies the NotNil predicate on the "line_id" field. +func LineIDNotNil() predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotNull(FieldLineID)) +} + +// LineIDEqualFold applies the EqualFold predicate on the "line_id" field. +func LineIDEqualFold(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEqualFold(FieldLineID, v)) +} + +// LineIDContainsFold applies the ContainsFold predicate on the "line_id" field. +func LineIDContainsFold(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldContainsFold(FieldLineID, v)) +} + +// InvoiceIDEQ applies the EQ predicate on the "invoice_id" field. +func InvoiceIDEQ(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldInvoiceID, v)) +} + +// InvoiceIDNEQ applies the NEQ predicate on the "invoice_id" field. +func InvoiceIDNEQ(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldInvoiceID, v)) +} + +// InvoiceIDIn applies the In predicate on the "invoice_id" field. +func InvoiceIDIn(vs ...string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldInvoiceID, vs...)) +} + +// InvoiceIDNotIn applies the NotIn predicate on the "invoice_id" field. +func InvoiceIDNotIn(vs ...string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldInvoiceID, vs...)) +} + +// InvoiceIDGT applies the GT predicate on the "invoice_id" field. +func InvoiceIDGT(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldInvoiceID, v)) +} + +// InvoiceIDGTE applies the GTE predicate on the "invoice_id" field. +func InvoiceIDGTE(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldInvoiceID, v)) +} + +// InvoiceIDLT applies the LT predicate on the "invoice_id" field. +func InvoiceIDLT(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldInvoiceID, v)) +} + +// InvoiceIDLTE applies the LTE predicate on the "invoice_id" field. +func InvoiceIDLTE(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldInvoiceID, v)) +} + +// InvoiceIDContains applies the Contains predicate on the "invoice_id" field. +func InvoiceIDContains(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldContains(FieldInvoiceID, v)) +} + +// InvoiceIDHasPrefix applies the HasPrefix predicate on the "invoice_id" field. +func InvoiceIDHasPrefix(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldHasPrefix(FieldInvoiceID, v)) +} + +// InvoiceIDHasSuffix applies the HasSuffix predicate on the "invoice_id" field. +func InvoiceIDHasSuffix(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldHasSuffix(FieldInvoiceID, v)) +} + +// InvoiceIDIsNil applies the IsNil predicate on the "invoice_id" field. +func InvoiceIDIsNil() predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIsNull(FieldInvoiceID)) +} + +// InvoiceIDNotNil applies the NotNil predicate on the "invoice_id" field. +func InvoiceIDNotNil() predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotNull(FieldInvoiceID)) +} + +// InvoiceIDEqualFold applies the EqualFold predicate on the "invoice_id" field. +func InvoiceIDEqualFold(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEqualFold(FieldInvoiceID, v)) +} + +// InvoiceIDContainsFold applies the ContainsFold predicate on the "invoice_id" field. +func InvoiceIDContainsFold(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldContainsFold(FieldInvoiceID, v)) +} + +// MeteredQuantityEQ applies the EQ predicate on the "metered_quantity" field. +func MeteredQuantityEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldMeteredQuantity, v)) +} + +// MeteredQuantityNEQ applies the NEQ predicate on the "metered_quantity" field. +func MeteredQuantityNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldMeteredQuantity, v)) +} + +// MeteredQuantityIn applies the In predicate on the "metered_quantity" field. +func MeteredQuantityIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldMeteredQuantity, vs...)) +} + +// MeteredQuantityNotIn applies the NotIn predicate on the "metered_quantity" field. +func MeteredQuantityNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldMeteredQuantity, vs...)) +} + +// MeteredQuantityGT applies the GT predicate on the "metered_quantity" field. +func MeteredQuantityGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldMeteredQuantity, v)) +} + +// MeteredQuantityGTE applies the GTE predicate on the "metered_quantity" field. +func MeteredQuantityGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldMeteredQuantity, v)) +} + +// MeteredQuantityLT applies the LT predicate on the "metered_quantity" field. +func MeteredQuantityLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldMeteredQuantity, v)) +} + +// MeteredQuantityLTE applies the LTE predicate on the "metered_quantity" field. +func MeteredQuantityLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldMeteredQuantity, v)) +} + +// NoFiatTransactionRequiredEQ applies the EQ predicate on the "no_fiat_transaction_required" field. +func NoFiatTransactionRequiredEQ(v bool) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldNoFiatTransactionRequired, v)) +} + +// NoFiatTransactionRequiredNEQ applies the NEQ predicate on the "no_fiat_transaction_required" field. +func NoFiatTransactionRequiredNEQ(v bool) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldNoFiatTransactionRequired, 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) + } + }) + }) +} + +// HasFeature applies the HasEdge predicate on the "feature" edge. +func HasFeature() predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, FeatureTable, FeatureColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasFeatureWith applies the HasEdge predicate on the "feature" edge with a given conditions (other predicates). +func HasFeatureWith(preds ...predicate.Feature) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(func(s *sql.Selector) { + step := newFeatureStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasBillingInvoiceLine applies the HasEdge predicate on the "billing_invoice_line" edge. +func HasBillingInvoiceLine() predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, BillingInvoiceLineTable, BillingInvoiceLineColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBillingInvoiceLineWith applies the HasEdge predicate on the "billing_invoice_line" edge with a given conditions (other predicates). +func HasBillingInvoiceLineWith(preds ...predicate.BillingInvoiceLine) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(func(s *sql.Selector) { + step := newBillingInvoiceLineStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasBillingInvoice applies the HasEdge predicate on the "billing_invoice" edge. +func HasBillingInvoice() predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, BillingInvoiceTable, BillingInvoiceColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBillingInvoiceWith applies the HasEdge predicate on the "billing_invoice" edge with a given conditions (other predicates). +func HasBillingInvoiceWith(preds ...predicate.BillingInvoice) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(func(s *sql.Selector) { + step := newBillingInvoiceStep() + 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) + } + }) + }) +} + +// HasDetailedLines applies the HasEdge predicate on the "detailed_lines" edge. +func HasDetailedLines() predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, DetailedLinesTable, DetailedLinesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasDetailedLinesWith applies the HasEdge predicate on the "detailed_lines" edge with a given conditions (other predicates). +func HasDetailedLinesWith(preds ...predicate.ChargeUsageBasedRunDetailedLine) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(func(s *sql.Selector) { + step := newDetailedLinesStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasCorrectedDetailedLines applies the HasEdge predicate on the "corrected_detailed_lines" edge. +func HasCorrectedDetailedLines() predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, CorrectedDetailedLinesTable, CorrectedDetailedLinesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCorrectedDetailedLinesWith applies the HasEdge predicate on the "corrected_detailed_lines" edge with a given conditions (other predicates). +func HasCorrectedDetailedLinesWith(preds ...predicate.ChargeUsageBasedRunDetailedLine) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(func(s *sql.Selector) { + step := newCorrectedDetailedLinesStep() + 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/ent/db/chargeusagebasedruns_create.go b/ent/db/chargeusagebasedruns_create.go new file mode 100644 index 0000000000000000000000000000000000000000..7790365e170c27b1c2197c1715bab93219ef9dad --- /dev/null +++ b/ent/db/chargeusagebasedruns_create.go @@ -0,0 +1,1830 @@ +// 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/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrundetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" +) + +// 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 +} + +// SetAmount sets the "amount" field. +func (_c *ChargeUsageBasedRunsCreate) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunsCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_c *ChargeUsageBasedRunsCreate) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsCreate { + _c.mutation.SetTaxesTotal(v) + return _c +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_c *ChargeUsageBasedRunsCreate) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsCreate { + _c.mutation.SetTaxesInclusiveTotal(v) + return _c +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_c *ChargeUsageBasedRunsCreate) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsCreate { + _c.mutation.SetTaxesExclusiveTotal(v) + return _c +} + +// SetChargesTotal sets the "charges_total" field. +func (_c *ChargeUsageBasedRunsCreate) SetChargesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsCreate { + _c.mutation.SetChargesTotal(v) + return _c +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_c *ChargeUsageBasedRunsCreate) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsCreate { + _c.mutation.SetDiscountsTotal(v) + return _c +} + +// SetCreditsTotal sets the "credits_total" field. +func (_c *ChargeUsageBasedRunsCreate) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsCreate { + _c.mutation.SetCreditsTotal(v) + return _c +} + +// SetTotal sets the "total" field. +func (_c *ChargeUsageBasedRunsCreate) SetTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsCreate { + _c.mutation.SetTotal(v) + return _c +} + +// SetChargeID sets the "charge_id" field. +func (_c *ChargeUsageBasedRunsCreate) SetChargeID(v string) *ChargeUsageBasedRunsCreate { + _c.mutation.SetChargeID(v) + return _c +} + +// SetFeatureID sets the "feature_id" field. +func (_c *ChargeUsageBasedRunsCreate) SetFeatureID(v string) *ChargeUsageBasedRunsCreate { + _c.mutation.SetFeatureID(v) + return _c +} + +// SetType sets the "type" field. +func (_c *ChargeUsageBasedRunsCreate) SetType(v usagebased.RealizationRunType) *ChargeUsageBasedRunsCreate { + _c.mutation.SetType(v) + return _c +} + +// SetInitialType sets the "initial_type" field. +func (_c *ChargeUsageBasedRunsCreate) SetInitialType(v usagebased.RealizationRunType) *ChargeUsageBasedRunsCreate { + _c.mutation.SetInitialType(v) + return _c +} + +// SetStoredAtLt sets the "stored_at_lt" field. +func (_c *ChargeUsageBasedRunsCreate) SetStoredAtLt(v time.Time) *ChargeUsageBasedRunsCreate { + _c.mutation.SetStoredAtLt(v) + return _c +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_c *ChargeUsageBasedRunsCreate) SetServicePeriodTo(v time.Time) *ChargeUsageBasedRunsCreate { + _c.mutation.SetServicePeriodTo(v) + return _c +} + +// SetDetailedLinesPresent sets the "detailed_lines_present" field. +func (_c *ChargeUsageBasedRunsCreate) SetDetailedLinesPresent(v bool) *ChargeUsageBasedRunsCreate { + _c.mutation.SetDetailedLinesPresent(v) + return _c +} + +// SetLineID sets the "line_id" field. +func (_c *ChargeUsageBasedRunsCreate) SetLineID(v string) *ChargeUsageBasedRunsCreate { + _c.mutation.SetLineID(v) + return _c +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_c *ChargeUsageBasedRunsCreate) SetNillableLineID(v *string) *ChargeUsageBasedRunsCreate { + if v != nil { + _c.SetLineID(*v) + } + return _c +} + +// SetInvoiceID sets the "invoice_id" field. +func (_c *ChargeUsageBasedRunsCreate) SetInvoiceID(v string) *ChargeUsageBasedRunsCreate { + _c.mutation.SetInvoiceID(v) + return _c +} + +// SetNillableInvoiceID sets the "invoice_id" field if the given value is not nil. +func (_c *ChargeUsageBasedRunsCreate) SetNillableInvoiceID(v *string) *ChargeUsageBasedRunsCreate { + if v != nil { + _c.SetInvoiceID(*v) + } + return _c +} + +// SetMeteredQuantity sets the "metered_quantity" field. +func (_c *ChargeUsageBasedRunsCreate) SetMeteredQuantity(v alpacadecimal.Decimal) *ChargeUsageBasedRunsCreate { + _c.mutation.SetMeteredQuantity(v) + return _c +} + +// SetNoFiatTransactionRequired sets the "no_fiat_transaction_required" field. +func (_c *ChargeUsageBasedRunsCreate) SetNoFiatTransactionRequired(v bool) *ChargeUsageBasedRunsCreate { + _c.mutation.SetNoFiatTransactionRequired(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) +} + +// SetFeature sets the "feature" edge to the Feature entity. +func (_c *ChargeUsageBasedRunsCreate) SetFeature(v *Feature) *ChargeUsageBasedRunsCreate { + return _c.SetFeatureID(v.ID) +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID. +func (_c *ChargeUsageBasedRunsCreate) SetBillingInvoiceLineID(id string) *ChargeUsageBasedRunsCreate { + _c.mutation.SetBillingInvoiceLineID(id) + return _c +} + +// SetNillableBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID if the given value is not nil. +func (_c *ChargeUsageBasedRunsCreate) SetNillableBillingInvoiceLineID(id *string) *ChargeUsageBasedRunsCreate { + if id != nil { + _c = _c.SetBillingInvoiceLineID(*id) + } + return _c +} + +// SetBillingInvoiceLine sets the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_c *ChargeUsageBasedRunsCreate) SetBillingInvoiceLine(v *BillingInvoiceLine) *ChargeUsageBasedRunsCreate { + return _c.SetBillingInvoiceLineID(v.ID) +} + +// SetBillingInvoiceID sets the "billing_invoice" edge to the BillingInvoice entity by ID. +func (_c *ChargeUsageBasedRunsCreate) SetBillingInvoiceID(id string) *ChargeUsageBasedRunsCreate { + _c.mutation.SetBillingInvoiceID(id) + return _c +} + +// SetNillableBillingInvoiceID sets the "billing_invoice" edge to the BillingInvoice entity by ID if the given value is not nil. +func (_c *ChargeUsageBasedRunsCreate) SetNillableBillingInvoiceID(id *string) *ChargeUsageBasedRunsCreate { + if id != nil { + _c = _c.SetBillingInvoiceID(*id) + } + return _c +} + +// SetBillingInvoice sets the "billing_invoice" edge to the BillingInvoice entity. +func (_c *ChargeUsageBasedRunsCreate) SetBillingInvoice(v *BillingInvoice) *ChargeUsageBasedRunsCreate { + return _c.SetBillingInvoiceID(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...) +} + +// AddDetailedLineIDs adds the "detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity by IDs. +func (_c *ChargeUsageBasedRunsCreate) AddDetailedLineIDs(ids ...string) *ChargeUsageBasedRunsCreate { + _c.mutation.AddDetailedLineIDs(ids...) + return _c +} + +// AddDetailedLines adds the "detailed_lines" edges to the ChargeUsageBasedRunDetailedLine entity. +func (_c *ChargeUsageBasedRunsCreate) AddDetailedLines(v ...*ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedRunsCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddDetailedLineIDs(ids...) +} + +// AddCorrectedDetailedLineIDs adds the "corrected_detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity by IDs. +func (_c *ChargeUsageBasedRunsCreate) AddCorrectedDetailedLineIDs(ids ...string) *ChargeUsageBasedRunsCreate { + _c.mutation.AddCorrectedDetailedLineIDs(ids...) + return _c +} + +// AddCorrectedDetailedLines adds the "corrected_detailed_lines" edges to the ChargeUsageBasedRunDetailedLine entity. +func (_c *ChargeUsageBasedRunsCreate) AddCorrectedDetailedLines(v ...*ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedRunsCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddCorrectedDetailedLineIDs(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.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.amount"`)} + } + if _, ok := _c.mutation.TaxesTotal(); !ok { + return &ValidationError{Name: "taxes_total", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.taxes_total"`)} + } + if _, ok := _c.mutation.TaxesInclusiveTotal(); !ok { + return &ValidationError{Name: "taxes_inclusive_total", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.taxes_inclusive_total"`)} + } + if _, ok := _c.mutation.TaxesExclusiveTotal(); !ok { + return &ValidationError{Name: "taxes_exclusive_total", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.taxes_exclusive_total"`)} + } + if _, ok := _c.mutation.ChargesTotal(); !ok { + return &ValidationError{Name: "charges_total", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.charges_total"`)} + } + if _, ok := _c.mutation.DiscountsTotal(); !ok { + return &ValidationError{Name: "discounts_total", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.discounts_total"`)} + } + if _, ok := _c.mutation.CreditsTotal(); !ok { + return &ValidationError{Name: "credits_total", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.credits_total"`)} + } + if _, ok := _c.mutation.Total(); !ok { + return &ValidationError{Name: "total", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.total"`)} + } + 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.FeatureID(); !ok { + return &ValidationError{Name: "feature_id", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.feature_id"`)} + } + if v, ok := _c.mutation.FeatureID(); ok { + if err := chargeusagebasedruns.FeatureIDValidator(v); err != nil { + return &ValidationError{Name: "feature_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRuns.feature_id": %w`, err)} + } + } + 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.InitialType(); !ok { + return &ValidationError{Name: "initial_type", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.initial_type"`)} + } + if v, ok := _c.mutation.InitialType(); ok { + if err := chargeusagebasedruns.InitialTypeValidator(v); err != nil { + return &ValidationError{Name: "initial_type", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRuns.initial_type": %w`, err)} + } + } + if _, ok := _c.mutation.StoredAtLt(); !ok { + return &ValidationError{Name: "stored_at_lt", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.stored_at_lt"`)} + } + if _, ok := _c.mutation.ServicePeriodTo(); !ok { + return &ValidationError{Name: "service_period_to", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.service_period_to"`)} + } + if _, ok := _c.mutation.DetailedLinesPresent(); !ok { + return &ValidationError{Name: "detailed_lines_present", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.detailed_lines_present"`)} + } + if v, ok := _c.mutation.LineID(); ok { + if err := chargeusagebasedruns.LineIDValidator(v); err != nil { + return &ValidationError{Name: "line_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRuns.line_id": %w`, err)} + } + } + if v, ok := _c.mutation.InvoiceID(); ok { + if err := chargeusagebasedruns.InvoiceIDValidator(v); err != nil { + return &ValidationError{Name: "invoice_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRuns.invoice_id": %w`, err)} + } + } + if _, ok := _c.mutation.MeteredQuantity(); !ok { + return &ValidationError{Name: "metered_quantity", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.metered_quantity"`)} + } + if _, ok := _c.mutation.NoFiatTransactionRequired(); !ok { + return &ValidationError{Name: "no_fiat_transaction_required", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.no_fiat_transaction_required"`)} + } + if len(_c.mutation.UsageBasedIDs()) == 0 { + return &ValidationError{Name: "usage_based", err: errors.New(`db: missing required edge "ChargeUsageBasedRuns.usage_based"`)} + } + if len(_c.mutation.FeatureIDs()) == 0 { + return &ValidationError{Name: "feature", err: errors.New(`db: missing required edge "ChargeUsageBasedRuns.feature"`)} + } + 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.Amount(); ok { + _spec.SetField(chargeusagebasedruns.FieldAmount, field.TypeOther, value) + _node.Amount = value + } + if value, ok := _c.mutation.TaxesTotal(); ok { + _spec.SetField(chargeusagebasedruns.FieldTaxesTotal, field.TypeOther, value) + _node.TaxesTotal = value + } + if value, ok := _c.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(chargeusagebasedruns.FieldTaxesInclusiveTotal, field.TypeOther, value) + _node.TaxesInclusiveTotal = value + } + if value, ok := _c.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(chargeusagebasedruns.FieldTaxesExclusiveTotal, field.TypeOther, value) + _node.TaxesExclusiveTotal = value + } + if value, ok := _c.mutation.ChargesTotal(); ok { + _spec.SetField(chargeusagebasedruns.FieldChargesTotal, field.TypeOther, value) + _node.ChargesTotal = value + } + if value, ok := _c.mutation.DiscountsTotal(); ok { + _spec.SetField(chargeusagebasedruns.FieldDiscountsTotal, field.TypeOther, value) + _node.DiscountsTotal = value + } + if value, ok := _c.mutation.CreditsTotal(); ok { + _spec.SetField(chargeusagebasedruns.FieldCreditsTotal, field.TypeOther, value) + _node.CreditsTotal = value + } + if value, ok := _c.mutation.Total(); ok { + _spec.SetField(chargeusagebasedruns.FieldTotal, field.TypeOther, value) + _node.Total = value + } + if value, ok := _c.mutation.GetType(); ok { + _spec.SetField(chargeusagebasedruns.FieldType, field.TypeEnum, value) + _node.Type = value + } + if value, ok := _c.mutation.InitialType(); ok { + _spec.SetField(chargeusagebasedruns.FieldInitialType, field.TypeEnum, value) + _node.InitialType = value + } + if value, ok := _c.mutation.StoredAtLt(); ok { + _spec.SetField(chargeusagebasedruns.FieldStoredAtLt, field.TypeTime, value) + _node.StoredAtLt = value + } + if value, ok := _c.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeusagebasedruns.FieldServicePeriodTo, field.TypeTime, value) + _node.ServicePeriodTo = value + } + if value, ok := _c.mutation.DetailedLinesPresent(); ok { + _spec.SetField(chargeusagebasedruns.FieldDetailedLinesPresent, field.TypeBool, value) + _node.DetailedLinesPresent = value + } + if value, ok := _c.mutation.MeteredQuantity(); ok { + _spec.SetField(chargeusagebasedruns.FieldMeteredQuantity, field.TypeOther, value) + _node.MeteredQuantity = value + } + if value, ok := _c.mutation.NoFiatTransactionRequired(); ok { + _spec.SetField(chargeusagebasedruns.FieldNoFiatTransactionRequired, field.TypeBool, value) + _node.NoFiatTransactionRequired = 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.FeatureIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedruns.FeatureTable, + Columns: []string{chargeusagebasedruns.FeatureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbfeature.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.FeatureID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.BillingInvoiceLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeusagebasedruns.BillingInvoiceLineTable, + Columns: []string{chargeusagebasedruns.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.LineID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.BillingInvoiceIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedruns.BillingInvoiceTable, + Columns: []string{chargeusagebasedruns.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.InvoiceID = &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.DetailedLinesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.DetailedLinesTable, + Columns: []string{chargeusagebasedruns.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.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.CorrectedDetailedLinesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.CorrectedDetailedLinesTable, + Columns: []string{chargeusagebasedruns.CorrectedDetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.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 +} + +// SetAmount sets the "amount" field. +func (u *ChargeUsageBasedRunsUpsert) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsert { + u.Set(chargeusagebasedruns.FieldAmount, v) + return u +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsert) UpdateAmount() *ChargeUsageBasedRunsUpsert { + u.SetExcluded(chargeusagebasedruns.FieldAmount) + return u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *ChargeUsageBasedRunsUpsert) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsert { + u.Set(chargeusagebasedruns.FieldTaxesTotal, v) + return u +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsert) UpdateTaxesTotal() *ChargeUsageBasedRunsUpsert { + u.SetExcluded(chargeusagebasedruns.FieldTaxesTotal) + return u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *ChargeUsageBasedRunsUpsert) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsert { + u.Set(chargeusagebasedruns.FieldTaxesInclusiveTotal, v) + return u +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsert) UpdateTaxesInclusiveTotal() *ChargeUsageBasedRunsUpsert { + u.SetExcluded(chargeusagebasedruns.FieldTaxesInclusiveTotal) + return u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *ChargeUsageBasedRunsUpsert) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsert { + u.Set(chargeusagebasedruns.FieldTaxesExclusiveTotal, v) + return u +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsert) UpdateTaxesExclusiveTotal() *ChargeUsageBasedRunsUpsert { + u.SetExcluded(chargeusagebasedruns.FieldTaxesExclusiveTotal) + return u +} + +// SetChargesTotal sets the "charges_total" field. +func (u *ChargeUsageBasedRunsUpsert) SetChargesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsert { + u.Set(chargeusagebasedruns.FieldChargesTotal, v) + return u +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsert) UpdateChargesTotal() *ChargeUsageBasedRunsUpsert { + u.SetExcluded(chargeusagebasedruns.FieldChargesTotal) + return u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *ChargeUsageBasedRunsUpsert) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsert { + u.Set(chargeusagebasedruns.FieldDiscountsTotal, v) + return u +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsert) UpdateDiscountsTotal() *ChargeUsageBasedRunsUpsert { + u.SetExcluded(chargeusagebasedruns.FieldDiscountsTotal) + return u +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *ChargeUsageBasedRunsUpsert) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsert { + u.Set(chargeusagebasedruns.FieldCreditsTotal, v) + return u +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsert) UpdateCreditsTotal() *ChargeUsageBasedRunsUpsert { + u.SetExcluded(chargeusagebasedruns.FieldCreditsTotal) + return u +} + +// SetTotal sets the "total" field. +func (u *ChargeUsageBasedRunsUpsert) SetTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsert { + u.Set(chargeusagebasedruns.FieldTotal, v) + return u +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsert) UpdateTotal() *ChargeUsageBasedRunsUpsert { + u.SetExcluded(chargeusagebasedruns.FieldTotal) + return u +} + +// SetType sets the "type" field. +func (u *ChargeUsageBasedRunsUpsert) SetType(v usagebased.RealizationRunType) *ChargeUsageBasedRunsUpsert { + u.Set(chargeusagebasedruns.FieldType, v) + return u +} + +// UpdateType sets the "type" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsert) UpdateType() *ChargeUsageBasedRunsUpsert { + u.SetExcluded(chargeusagebasedruns.FieldType) + return u +} + +// SetStoredAtLt sets the "stored_at_lt" field. +func (u *ChargeUsageBasedRunsUpsert) SetStoredAtLt(v time.Time) *ChargeUsageBasedRunsUpsert { + u.Set(chargeusagebasedruns.FieldStoredAtLt, v) + return u +} + +// UpdateStoredAtLt sets the "stored_at_lt" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsert) UpdateStoredAtLt() *ChargeUsageBasedRunsUpsert { + u.SetExcluded(chargeusagebasedruns.FieldStoredAtLt) + return u +} + +// SetDetailedLinesPresent sets the "detailed_lines_present" field. +func (u *ChargeUsageBasedRunsUpsert) SetDetailedLinesPresent(v bool) *ChargeUsageBasedRunsUpsert { + u.Set(chargeusagebasedruns.FieldDetailedLinesPresent, v) + return u +} + +// UpdateDetailedLinesPresent sets the "detailed_lines_present" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsert) UpdateDetailedLinesPresent() *ChargeUsageBasedRunsUpsert { + u.SetExcluded(chargeusagebasedruns.FieldDetailedLinesPresent) + return u +} + +// SetLineID sets the "line_id" field. +func (u *ChargeUsageBasedRunsUpsert) SetLineID(v string) *ChargeUsageBasedRunsUpsert { + u.Set(chargeusagebasedruns.FieldLineID, v) + return u +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsert) UpdateLineID() *ChargeUsageBasedRunsUpsert { + u.SetExcluded(chargeusagebasedruns.FieldLineID) + return u +} + +// ClearLineID clears the value of the "line_id" field. +func (u *ChargeUsageBasedRunsUpsert) ClearLineID() *ChargeUsageBasedRunsUpsert { + u.SetNull(chargeusagebasedruns.FieldLineID) + return u +} + +// SetMeteredQuantity sets the "metered_quantity" field. +func (u *ChargeUsageBasedRunsUpsert) SetMeteredQuantity(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsert { + u.Set(chargeusagebasedruns.FieldMeteredQuantity, v) + return u +} + +// UpdateMeteredQuantity sets the "metered_quantity" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsert) UpdateMeteredQuantity() *ChargeUsageBasedRunsUpsert { + u.SetExcluded(chargeusagebasedruns.FieldMeteredQuantity) + return u +} + +// SetNoFiatTransactionRequired sets the "no_fiat_transaction_required" field. +func (u *ChargeUsageBasedRunsUpsert) SetNoFiatTransactionRequired(v bool) *ChargeUsageBasedRunsUpsert { + u.Set(chargeusagebasedruns.FieldNoFiatTransactionRequired, v) + return u +} + +// UpdateNoFiatTransactionRequired sets the "no_fiat_transaction_required" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsert) UpdateNoFiatTransactionRequired() *ChargeUsageBasedRunsUpsert { + u.SetExcluded(chargeusagebasedruns.FieldNoFiatTransactionRequired) + 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.FeatureID(); exists { + s.SetIgnore(chargeusagebasedruns.FieldFeatureID) + } + if _, exists := u.create.mutation.InitialType(); exists { + s.SetIgnore(chargeusagebasedruns.FieldInitialType) + } + if _, exists := u.create.mutation.ServicePeriodTo(); exists { + s.SetIgnore(chargeusagebasedruns.FieldServicePeriodTo) + } + if _, exists := u.create.mutation.InvoiceID(); exists { + s.SetIgnore(chargeusagebasedruns.FieldInvoiceID) + } + })) + 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() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeUsageBasedRunsUpsertOne) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertOne) UpdateAmount() *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateAmount() + }) +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *ChargeUsageBasedRunsUpsertOne) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetTaxesTotal(v) + }) +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertOne) UpdateTaxesTotal() *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateTaxesTotal() + }) +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *ChargeUsageBasedRunsUpsertOne) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetTaxesInclusiveTotal(v) + }) +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertOne) UpdateTaxesInclusiveTotal() *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateTaxesInclusiveTotal() + }) +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *ChargeUsageBasedRunsUpsertOne) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetTaxesExclusiveTotal(v) + }) +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertOne) UpdateTaxesExclusiveTotal() *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateTaxesExclusiveTotal() + }) +} + +// SetChargesTotal sets the "charges_total" field. +func (u *ChargeUsageBasedRunsUpsertOne) SetChargesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetChargesTotal(v) + }) +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertOne) UpdateChargesTotal() *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateChargesTotal() + }) +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *ChargeUsageBasedRunsUpsertOne) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetDiscountsTotal(v) + }) +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertOne) UpdateDiscountsTotal() *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateDiscountsTotal() + }) +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *ChargeUsageBasedRunsUpsertOne) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetCreditsTotal(v) + }) +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertOne) UpdateCreditsTotal() *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateCreditsTotal() + }) +} + +// SetTotal sets the "total" field. +func (u *ChargeUsageBasedRunsUpsertOne) SetTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetTotal(v) + }) +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertOne) UpdateTotal() *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateTotal() + }) +} + +// SetType sets the "type" field. +func (u *ChargeUsageBasedRunsUpsertOne) SetType(v usagebased.RealizationRunType) *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetType(v) + }) +} + +// UpdateType sets the "type" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertOne) UpdateType() *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateType() + }) +} + +// SetStoredAtLt sets the "stored_at_lt" field. +func (u *ChargeUsageBasedRunsUpsertOne) SetStoredAtLt(v time.Time) *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetStoredAtLt(v) + }) +} + +// UpdateStoredAtLt sets the "stored_at_lt" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertOne) UpdateStoredAtLt() *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateStoredAtLt() + }) +} + +// SetDetailedLinesPresent sets the "detailed_lines_present" field. +func (u *ChargeUsageBasedRunsUpsertOne) SetDetailedLinesPresent(v bool) *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetDetailedLinesPresent(v) + }) +} + +// UpdateDetailedLinesPresent sets the "detailed_lines_present" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertOne) UpdateDetailedLinesPresent() *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateDetailedLinesPresent() + }) +} + +// SetLineID sets the "line_id" field. +func (u *ChargeUsageBasedRunsUpsertOne) SetLineID(v string) *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetLineID(v) + }) +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertOne) UpdateLineID() *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateLineID() + }) +} + +// ClearLineID clears the value of the "line_id" field. +func (u *ChargeUsageBasedRunsUpsertOne) ClearLineID() *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.ClearLineID() + }) +} + +// SetMeteredQuantity sets the "metered_quantity" field. +func (u *ChargeUsageBasedRunsUpsertOne) SetMeteredQuantity(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetMeteredQuantity(v) + }) +} + +// UpdateMeteredQuantity sets the "metered_quantity" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertOne) UpdateMeteredQuantity() *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateMeteredQuantity() + }) +} + +// SetNoFiatTransactionRequired sets the "no_fiat_transaction_required" field. +func (u *ChargeUsageBasedRunsUpsertOne) SetNoFiatTransactionRequired(v bool) *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetNoFiatTransactionRequired(v) + }) +} + +// UpdateNoFiatTransactionRequired sets the "no_fiat_transaction_required" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertOne) UpdateNoFiatTransactionRequired() *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateNoFiatTransactionRequired() + }) +} + +// 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.FeatureID(); exists { + s.SetIgnore(chargeusagebasedruns.FieldFeatureID) + } + if _, exists := b.mutation.InitialType(); exists { + s.SetIgnore(chargeusagebasedruns.FieldInitialType) + } + if _, exists := b.mutation.ServicePeriodTo(); exists { + s.SetIgnore(chargeusagebasedruns.FieldServicePeriodTo) + } + if _, exists := b.mutation.InvoiceID(); exists { + s.SetIgnore(chargeusagebasedruns.FieldInvoiceID) + } + } + })) + 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() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeUsageBasedRunsUpsertBulk) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertBulk) UpdateAmount() *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateAmount() + }) +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *ChargeUsageBasedRunsUpsertBulk) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetTaxesTotal(v) + }) +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertBulk) UpdateTaxesTotal() *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateTaxesTotal() + }) +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *ChargeUsageBasedRunsUpsertBulk) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetTaxesInclusiveTotal(v) + }) +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertBulk) UpdateTaxesInclusiveTotal() *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateTaxesInclusiveTotal() + }) +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *ChargeUsageBasedRunsUpsertBulk) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetTaxesExclusiveTotal(v) + }) +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertBulk) UpdateTaxesExclusiveTotal() *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateTaxesExclusiveTotal() + }) +} + +// SetChargesTotal sets the "charges_total" field. +func (u *ChargeUsageBasedRunsUpsertBulk) SetChargesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetChargesTotal(v) + }) +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertBulk) UpdateChargesTotal() *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateChargesTotal() + }) +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *ChargeUsageBasedRunsUpsertBulk) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetDiscountsTotal(v) + }) +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertBulk) UpdateDiscountsTotal() *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateDiscountsTotal() + }) +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *ChargeUsageBasedRunsUpsertBulk) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetCreditsTotal(v) + }) +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertBulk) UpdateCreditsTotal() *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateCreditsTotal() + }) +} + +// SetTotal sets the "total" field. +func (u *ChargeUsageBasedRunsUpsertBulk) SetTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetTotal(v) + }) +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertBulk) UpdateTotal() *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateTotal() + }) +} + +// SetType sets the "type" field. +func (u *ChargeUsageBasedRunsUpsertBulk) SetType(v usagebased.RealizationRunType) *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetType(v) + }) +} + +// UpdateType sets the "type" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertBulk) UpdateType() *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateType() + }) +} + +// SetStoredAtLt sets the "stored_at_lt" field. +func (u *ChargeUsageBasedRunsUpsertBulk) SetStoredAtLt(v time.Time) *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetStoredAtLt(v) + }) +} + +// UpdateStoredAtLt sets the "stored_at_lt" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertBulk) UpdateStoredAtLt() *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateStoredAtLt() + }) +} + +// SetDetailedLinesPresent sets the "detailed_lines_present" field. +func (u *ChargeUsageBasedRunsUpsertBulk) SetDetailedLinesPresent(v bool) *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetDetailedLinesPresent(v) + }) +} + +// UpdateDetailedLinesPresent sets the "detailed_lines_present" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertBulk) UpdateDetailedLinesPresent() *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateDetailedLinesPresent() + }) +} + +// SetLineID sets the "line_id" field. +func (u *ChargeUsageBasedRunsUpsertBulk) SetLineID(v string) *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetLineID(v) + }) +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertBulk) UpdateLineID() *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateLineID() + }) +} + +// ClearLineID clears the value of the "line_id" field. +func (u *ChargeUsageBasedRunsUpsertBulk) ClearLineID() *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.ClearLineID() + }) +} + +// SetMeteredQuantity sets the "metered_quantity" field. +func (u *ChargeUsageBasedRunsUpsertBulk) SetMeteredQuantity(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetMeteredQuantity(v) + }) +} + +// UpdateMeteredQuantity sets the "metered_quantity" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertBulk) UpdateMeteredQuantity() *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateMeteredQuantity() + }) +} + +// SetNoFiatTransactionRequired sets the "no_fiat_transaction_required" field. +func (u *ChargeUsageBasedRunsUpsertBulk) SetNoFiatTransactionRequired(v bool) *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetNoFiatTransactionRequired(v) + }) +} + +// UpdateNoFiatTransactionRequired sets the "no_fiat_transaction_required" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertBulk) UpdateNoFiatTransactionRequired() *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateNoFiatTransactionRequired() + }) +} + +// 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/ent/db/chargeusagebasedruns_delete.go b/ent/db/chargeusagebasedruns_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..2e02a37f2ea052cf8ed80680acf5c8797beca6a4 --- /dev/null +++ b/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/ent/db/chargeusagebasedruns_query.go b/ent/db/chargeusagebasedruns_query.go new file mode 100644 index 0000000000000000000000000000000000000000..b19a0844112330ee167726af41eeb6ee7fbd3c24 --- /dev/null +++ b/ent/db/chargeusagebasedruns_query.go @@ -0,0 +1,1245 @@ +// 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/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrundetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + "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 + withFeature *FeatureQuery + withBillingInvoiceLine *BillingInvoiceLineQuery + withBillingInvoice *BillingInvoiceQuery + withCreditAllocations *ChargeUsageBasedRunCreditAllocationsQuery + withDetailedLines *ChargeUsageBasedRunDetailedLineQuery + withCorrectedDetailedLines *ChargeUsageBasedRunDetailedLineQuery + 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 +} + +// QueryFeature chains the current query on the "feature" edge. +func (_q *ChargeUsageBasedRunsQuery) QueryFeature() *FeatureQuery { + query := (&FeatureClient{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(dbfeature.Table, dbfeature.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebasedruns.FeatureTable, chargeusagebasedruns.FeatureColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryBillingInvoiceLine chains the current query on the "billing_invoice_line" edge. +func (_q *ChargeUsageBasedRunsQuery) QueryBillingInvoiceLine() *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{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(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargeusagebasedruns.BillingInvoiceLineTable, chargeusagebasedruns.BillingInvoiceLineColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryBillingInvoice chains the current query on the "billing_invoice" edge. +func (_q *ChargeUsageBasedRunsQuery) QueryBillingInvoice() *BillingInvoiceQuery { + query := (&BillingInvoiceClient{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(billinginvoice.Table, billinginvoice.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebasedruns.BillingInvoiceTable, chargeusagebasedruns.BillingInvoiceColumn), + ) + 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 +} + +// QueryDetailedLines chains the current query on the "detailed_lines" edge. +func (_q *ChargeUsageBasedRunsQuery) QueryDetailedLines() *ChargeUsageBasedRunDetailedLineQuery { + query := (&ChargeUsageBasedRunDetailedLineClient{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(chargeusagebasedrundetailedline.Table, chargeusagebasedrundetailedline.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, chargeusagebasedruns.DetailedLinesTable, chargeusagebasedruns.DetailedLinesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCorrectedDetailedLines chains the current query on the "corrected_detailed_lines" edge. +func (_q *ChargeUsageBasedRunsQuery) QueryCorrectedDetailedLines() *ChargeUsageBasedRunDetailedLineQuery { + query := (&ChargeUsageBasedRunDetailedLineClient{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(chargeusagebasedrundetailedline.Table, chargeusagebasedrundetailedline.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, chargeusagebasedruns.CorrectedDetailedLinesTable, chargeusagebasedruns.CorrectedDetailedLinesColumn), + ) + 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(), + withFeature: _q.withFeature.Clone(), + withBillingInvoiceLine: _q.withBillingInvoiceLine.Clone(), + withBillingInvoice: _q.withBillingInvoice.Clone(), + withCreditAllocations: _q.withCreditAllocations.Clone(), + withDetailedLines: _q.withDetailedLines.Clone(), + withCorrectedDetailedLines: _q.withCorrectedDetailedLines.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 +} + +// WithFeature tells the query-builder to eager-load the nodes that are connected to +// the "feature" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedRunsQuery) WithFeature(opts ...func(*FeatureQuery)) *ChargeUsageBasedRunsQuery { + query := (&FeatureClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withFeature = query + return _q +} + +// WithBillingInvoiceLine tells the query-builder to eager-load the nodes that are connected to +// the "billing_invoice_line" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedRunsQuery) WithBillingInvoiceLine(opts ...func(*BillingInvoiceLineQuery)) *ChargeUsageBasedRunsQuery { + query := (&BillingInvoiceLineClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingInvoiceLine = query + return _q +} + +// WithBillingInvoice tells the query-builder to eager-load the nodes that are connected to +// the "billing_invoice" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedRunsQuery) WithBillingInvoice(opts ...func(*BillingInvoiceQuery)) *ChargeUsageBasedRunsQuery { + query := (&BillingInvoiceClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingInvoice = 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 +} + +// WithDetailedLines tells the query-builder to eager-load the nodes that are connected to +// the "detailed_lines" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedRunsQuery) WithDetailedLines(opts ...func(*ChargeUsageBasedRunDetailedLineQuery)) *ChargeUsageBasedRunsQuery { + query := (&ChargeUsageBasedRunDetailedLineClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withDetailedLines = query + return _q +} + +// WithCorrectedDetailedLines tells the query-builder to eager-load the nodes that are connected to +// the "corrected_detailed_lines" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedRunsQuery) WithCorrectedDetailedLines(opts ...func(*ChargeUsageBasedRunDetailedLineQuery)) *ChargeUsageBasedRunsQuery { + query := (&ChargeUsageBasedRunDetailedLineClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCorrectedDetailedLines = 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 = [9]bool{ + _q.withUsageBased != nil, + _q.withFeature != nil, + _q.withBillingInvoiceLine != nil, + _q.withBillingInvoice != nil, + _q.withCreditAllocations != nil, + _q.withDetailedLines != nil, + _q.withCorrectedDetailedLines != 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.withFeature; query != nil { + if err := _q.loadFeature(ctx, query, nodes, nil, + func(n *ChargeUsageBasedRuns, e *Feature) { n.Edges.Feature = e }); err != nil { + return nil, err + } + } + if query := _q.withBillingInvoiceLine; query != nil { + if err := _q.loadBillingInvoiceLine(ctx, query, nodes, nil, + func(n *ChargeUsageBasedRuns, e *BillingInvoiceLine) { n.Edges.BillingInvoiceLine = e }); err != nil { + return nil, err + } + } + if query := _q.withBillingInvoice; query != nil { + if err := _q.loadBillingInvoice(ctx, query, nodes, nil, + func(n *ChargeUsageBasedRuns, e *BillingInvoice) { n.Edges.BillingInvoice = 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.withDetailedLines; query != nil { + if err := _q.loadDetailedLines(ctx, query, nodes, + func(n *ChargeUsageBasedRuns) { n.Edges.DetailedLines = []*ChargeUsageBasedRunDetailedLine{} }, + func(n *ChargeUsageBasedRuns, e *ChargeUsageBasedRunDetailedLine) { + n.Edges.DetailedLines = append(n.Edges.DetailedLines, e) + }); err != nil { + return nil, err + } + } + if query := _q.withCorrectedDetailedLines; query != nil { + if err := _q.loadCorrectedDetailedLines(ctx, query, nodes, + func(n *ChargeUsageBasedRuns) { n.Edges.CorrectedDetailedLines = []*ChargeUsageBasedRunDetailedLine{} }, + func(n *ChargeUsageBasedRuns, e *ChargeUsageBasedRunDetailedLine) { + n.Edges.CorrectedDetailedLines = append(n.Edges.CorrectedDetailedLines, 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) loadFeature(ctx context.Context, query *FeatureQuery, nodes []*ChargeUsageBasedRuns, init func(*ChargeUsageBasedRuns), assign func(*ChargeUsageBasedRuns, *Feature)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBasedRuns) + for i := range nodes { + fk := nodes[i].FeatureID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(dbfeature.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 "feature_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeUsageBasedRunsQuery) loadBillingInvoiceLine(ctx context.Context, query *BillingInvoiceLineQuery, nodes []*ChargeUsageBasedRuns, init func(*ChargeUsageBasedRuns), assign func(*ChargeUsageBasedRuns, *BillingInvoiceLine)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBasedRuns) + for i := range nodes { + if nodes[i].LineID == nil { + continue + } + fk := *nodes[i].LineID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(billinginvoiceline.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 "line_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeUsageBasedRunsQuery) loadBillingInvoice(ctx context.Context, query *BillingInvoiceQuery, nodes []*ChargeUsageBasedRuns, init func(*ChargeUsageBasedRuns), assign func(*ChargeUsageBasedRuns, *BillingInvoice)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBasedRuns) + for i := range nodes { + if nodes[i].InvoiceID == nil { + continue + } + fk := *nodes[i].InvoiceID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(billinginvoice.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 "invoice_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) loadDetailedLines(ctx context.Context, query *ChargeUsageBasedRunDetailedLineQuery, nodes []*ChargeUsageBasedRuns, init func(*ChargeUsageBasedRuns), assign func(*ChargeUsageBasedRuns, *ChargeUsageBasedRunDetailedLine)) 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(chargeusagebasedrundetailedline.FieldRunID) + } + query.Where(predicate.ChargeUsageBasedRunDetailedLine(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargeusagebasedruns.DetailedLinesColumn), 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) loadCorrectedDetailedLines(ctx context.Context, query *ChargeUsageBasedRunDetailedLineQuery, nodes []*ChargeUsageBasedRuns, init func(*ChargeUsageBasedRuns), assign func(*ChargeUsageBasedRuns, *ChargeUsageBasedRunDetailedLine)) 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(chargeusagebasedrundetailedline.FieldCorrectsRunID) + } + query.Where(predicate.ChargeUsageBasedRunDetailedLine(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargeusagebasedruns.CorrectedDetailedLinesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.CorrectsRunID + if fk == nil { + return fmt.Errorf(`foreign-key "corrects_run_id" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "corrects_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 _q.withFeature != nil { + _spec.Node.AddColumnOnce(chargeusagebasedruns.FieldFeatureID) + } + if _q.withBillingInvoiceLine != nil { + _spec.Node.AddColumnOnce(chargeusagebasedruns.FieldLineID) + } + if _q.withBillingInvoice != nil { + _spec.Node.AddColumnOnce(chargeusagebasedruns.FieldInvoiceID) + } + } + 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/ent/db/chargeusagebasedruns_update.go b/ent/db/chargeusagebasedruns_update.go new file mode 100644 index 0000000000000000000000000000000000000000..6b71320e62a2f230dd9b0a212ea1dfc470c00aaf --- /dev/null +++ b/ent/db/chargeusagebasedruns_update.go @@ -0,0 +1,1611 @@ +// 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/usagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrundetailedline" + "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 +} + +// SetAmount sets the "amount" field. +func (_u *ChargeUsageBasedRunsUpdate) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdate) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdate { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_u *ChargeUsageBasedRunsUpdate) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetTaxesTotal(v) + return _u +} + +// SetNillableTaxesTotal sets the "taxes_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdate) SetNillableTaxesTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdate { + if v != nil { + _u.SetTaxesTotal(*v) + } + return _u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_u *ChargeUsageBasedRunsUpdate) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetTaxesInclusiveTotal(v) + return _u +} + +// SetNillableTaxesInclusiveTotal sets the "taxes_inclusive_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdate) SetNillableTaxesInclusiveTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdate { + if v != nil { + _u.SetTaxesInclusiveTotal(*v) + } + return _u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_u *ChargeUsageBasedRunsUpdate) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetTaxesExclusiveTotal(v) + return _u +} + +// SetNillableTaxesExclusiveTotal sets the "taxes_exclusive_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdate) SetNillableTaxesExclusiveTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdate { + if v != nil { + _u.SetTaxesExclusiveTotal(*v) + } + return _u +} + +// SetChargesTotal sets the "charges_total" field. +func (_u *ChargeUsageBasedRunsUpdate) SetChargesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetChargesTotal(v) + return _u +} + +// SetNillableChargesTotal sets the "charges_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdate) SetNillableChargesTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdate { + if v != nil { + _u.SetChargesTotal(*v) + } + return _u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_u *ChargeUsageBasedRunsUpdate) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetDiscountsTotal(v) + return _u +} + +// SetNillableDiscountsTotal sets the "discounts_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdate) SetNillableDiscountsTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdate { + if v != nil { + _u.SetDiscountsTotal(*v) + } + return _u +} + +// SetCreditsTotal sets the "credits_total" field. +func (_u *ChargeUsageBasedRunsUpdate) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetCreditsTotal(v) + return _u +} + +// SetNillableCreditsTotal sets the "credits_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdate) SetNillableCreditsTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdate { + if v != nil { + _u.SetCreditsTotal(*v) + } + return _u +} + +// SetTotal sets the "total" field. +func (_u *ChargeUsageBasedRunsUpdate) SetTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetTotal(v) + return _u +} + +// SetNillableTotal sets the "total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdate) SetNillableTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdate { + if v != nil { + _u.SetTotal(*v) + } + return _u +} + +// SetType sets the "type" field. +func (_u *ChargeUsageBasedRunsUpdate) SetType(v usagebased.RealizationRunType) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetType(v) + return _u +} + +// SetNillableType sets the "type" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdate) SetNillableType(v *usagebased.RealizationRunType) *ChargeUsageBasedRunsUpdate { + if v != nil { + _u.SetType(*v) + } + return _u +} + +// SetStoredAtLt sets the "stored_at_lt" field. +func (_u *ChargeUsageBasedRunsUpdate) SetStoredAtLt(v time.Time) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetStoredAtLt(v) + return _u +} + +// SetNillableStoredAtLt sets the "stored_at_lt" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdate) SetNillableStoredAtLt(v *time.Time) *ChargeUsageBasedRunsUpdate { + if v != nil { + _u.SetStoredAtLt(*v) + } + return _u +} + +// SetDetailedLinesPresent sets the "detailed_lines_present" field. +func (_u *ChargeUsageBasedRunsUpdate) SetDetailedLinesPresent(v bool) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetDetailedLinesPresent(v) + return _u +} + +// SetNillableDetailedLinesPresent sets the "detailed_lines_present" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdate) SetNillableDetailedLinesPresent(v *bool) *ChargeUsageBasedRunsUpdate { + if v != nil { + _u.SetDetailedLinesPresent(*v) + } + return _u +} + +// SetLineID sets the "line_id" field. +func (_u *ChargeUsageBasedRunsUpdate) SetLineID(v string) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetLineID(v) + return _u +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdate) SetNillableLineID(v *string) *ChargeUsageBasedRunsUpdate { + if v != nil { + _u.SetLineID(*v) + } + return _u +} + +// ClearLineID clears the value of the "line_id" field. +func (_u *ChargeUsageBasedRunsUpdate) ClearLineID() *ChargeUsageBasedRunsUpdate { + _u.mutation.ClearLineID() + return _u +} + +// SetMeteredQuantity sets the "metered_quantity" field. +func (_u *ChargeUsageBasedRunsUpdate) SetMeteredQuantity(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetMeteredQuantity(v) + return _u +} + +// SetNillableMeteredQuantity sets the "metered_quantity" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdate) SetNillableMeteredQuantity(v *alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdate { + if v != nil { + _u.SetMeteredQuantity(*v) + } + return _u +} + +// SetNoFiatTransactionRequired sets the "no_fiat_transaction_required" field. +func (_u *ChargeUsageBasedRunsUpdate) SetNoFiatTransactionRequired(v bool) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetNoFiatTransactionRequired(v) + return _u +} + +// SetNillableNoFiatTransactionRequired sets the "no_fiat_transaction_required" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdate) SetNillableNoFiatTransactionRequired(v *bool) *ChargeUsageBasedRunsUpdate { + if v != nil { + _u.SetNoFiatTransactionRequired(*v) + } + return _u +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID. +func (_u *ChargeUsageBasedRunsUpdate) SetBillingInvoiceLineID(id string) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetBillingInvoiceLineID(id) + return _u +} + +// SetNillableBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdate) SetNillableBillingInvoiceLineID(id *string) *ChargeUsageBasedRunsUpdate { + if id != nil { + _u = _u.SetBillingInvoiceLineID(*id) + } + return _u +} + +// SetBillingInvoiceLine sets the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *ChargeUsageBasedRunsUpdate) SetBillingInvoiceLine(v *BillingInvoiceLine) *ChargeUsageBasedRunsUpdate { + return _u.SetBillingInvoiceLineID(v.ID) +} + +// 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...) +} + +// AddDetailedLineIDs adds the "detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity by IDs. +func (_u *ChargeUsageBasedRunsUpdate) AddDetailedLineIDs(ids ...string) *ChargeUsageBasedRunsUpdate { + _u.mutation.AddDetailedLineIDs(ids...) + return _u +} + +// AddDetailedLines adds the "detailed_lines" edges to the ChargeUsageBasedRunDetailedLine entity. +func (_u *ChargeUsageBasedRunsUpdate) AddDetailedLines(v ...*ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedRunsUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddDetailedLineIDs(ids...) +} + +// AddCorrectedDetailedLineIDs adds the "corrected_detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity by IDs. +func (_u *ChargeUsageBasedRunsUpdate) AddCorrectedDetailedLineIDs(ids ...string) *ChargeUsageBasedRunsUpdate { + _u.mutation.AddCorrectedDetailedLineIDs(ids...) + return _u +} + +// AddCorrectedDetailedLines adds the "corrected_detailed_lines" edges to the ChargeUsageBasedRunDetailedLine entity. +func (_u *ChargeUsageBasedRunsUpdate) AddCorrectedDetailedLines(v ...*ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedRunsUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddCorrectedDetailedLineIDs(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 +} + +// ClearBillingInvoiceLine clears the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *ChargeUsageBasedRunsUpdate) ClearBillingInvoiceLine() *ChargeUsageBasedRunsUpdate { + _u.mutation.ClearBillingInvoiceLine() + return _u +} + +// 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...) +} + +// ClearDetailedLines clears all "detailed_lines" edges to the ChargeUsageBasedRunDetailedLine entity. +func (_u *ChargeUsageBasedRunsUpdate) ClearDetailedLines() *ChargeUsageBasedRunsUpdate { + _u.mutation.ClearDetailedLines() + return _u +} + +// RemoveDetailedLineIDs removes the "detailed_lines" edge to ChargeUsageBasedRunDetailedLine entities by IDs. +func (_u *ChargeUsageBasedRunsUpdate) RemoveDetailedLineIDs(ids ...string) *ChargeUsageBasedRunsUpdate { + _u.mutation.RemoveDetailedLineIDs(ids...) + return _u +} + +// RemoveDetailedLines removes "detailed_lines" edges to ChargeUsageBasedRunDetailedLine entities. +func (_u *ChargeUsageBasedRunsUpdate) RemoveDetailedLines(v ...*ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedRunsUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveDetailedLineIDs(ids...) +} + +// ClearCorrectedDetailedLines clears all "corrected_detailed_lines" edges to the ChargeUsageBasedRunDetailedLine entity. +func (_u *ChargeUsageBasedRunsUpdate) ClearCorrectedDetailedLines() *ChargeUsageBasedRunsUpdate { + _u.mutation.ClearCorrectedDetailedLines() + return _u +} + +// RemoveCorrectedDetailedLineIDs removes the "corrected_detailed_lines" edge to ChargeUsageBasedRunDetailedLine entities by IDs. +func (_u *ChargeUsageBasedRunsUpdate) RemoveCorrectedDetailedLineIDs(ids ...string) *ChargeUsageBasedRunsUpdate { + _u.mutation.RemoveCorrectedDetailedLineIDs(ids...) + return _u +} + +// RemoveCorrectedDetailedLines removes "corrected_detailed_lines" edges to ChargeUsageBasedRunDetailedLine entities. +func (_u *ChargeUsageBasedRunsUpdate) RemoveCorrectedDetailedLines(v ...*ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedRunsUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveCorrectedDetailedLineIDs(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 v, ok := _u.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 v, ok := _u.mutation.LineID(); ok { + if err := chargeusagebasedruns.LineIDValidator(v); err != nil { + return &ValidationError{Name: "line_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRuns.line_id": %w`, err)} + } + } + if _u.mutation.UsageBasedCleared() && len(_u.mutation.UsageBasedIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBasedRuns.usage_based"`) + } + if _u.mutation.FeatureCleared() && len(_u.mutation.FeatureIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBasedRuns.feature"`) + } + 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.Amount(); ok { + _spec.SetField(chargeusagebasedruns.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesTotal(); ok { + _spec.SetField(chargeusagebasedruns.FieldTaxesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(chargeusagebasedruns.FieldTaxesInclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(chargeusagebasedruns.FieldTaxesExclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.ChargesTotal(); ok { + _spec.SetField(chargeusagebasedruns.FieldChargesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.DiscountsTotal(); ok { + _spec.SetField(chargeusagebasedruns.FieldDiscountsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.CreditsTotal(); ok { + _spec.SetField(chargeusagebasedruns.FieldCreditsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.Total(); ok { + _spec.SetField(chargeusagebasedruns.FieldTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.GetType(); ok { + _spec.SetField(chargeusagebasedruns.FieldType, field.TypeEnum, value) + } + if value, ok := _u.mutation.StoredAtLt(); ok { + _spec.SetField(chargeusagebasedruns.FieldStoredAtLt, field.TypeTime, value) + } + if value, ok := _u.mutation.DetailedLinesPresent(); ok { + _spec.SetField(chargeusagebasedruns.FieldDetailedLinesPresent, field.TypeBool, value) + } + if value, ok := _u.mutation.MeteredQuantity(); ok { + _spec.SetField(chargeusagebasedruns.FieldMeteredQuantity, field.TypeOther, value) + } + if value, ok := _u.mutation.NoFiatTransactionRequired(); ok { + _spec.SetField(chargeusagebasedruns.FieldNoFiatTransactionRequired, field.TypeBool, value) + } + if _u.mutation.BillingInvoiceLineCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeusagebasedruns.BillingInvoiceLineTable, + Columns: []string{chargeusagebasedruns.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingInvoiceLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeusagebasedruns.BillingInvoiceLineTable, + Columns: []string{chargeusagebasedruns.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.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.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.DetailedLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.DetailedLinesTable, + Columns: []string{chargeusagebasedruns.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedDetailedLinesIDs(); len(nodes) > 0 && !_u.mutation.DetailedLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.DetailedLinesTable, + Columns: []string{chargeusagebasedruns.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.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.DetailedLinesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.DetailedLinesTable, + Columns: []string{chargeusagebasedruns.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.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.CorrectedDetailedLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.CorrectedDetailedLinesTable, + Columns: []string{chargeusagebasedruns.CorrectedDetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedCorrectedDetailedLinesIDs(); len(nodes) > 0 && !_u.mutation.CorrectedDetailedLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.CorrectedDetailedLinesTable, + Columns: []string{chargeusagebasedruns.CorrectedDetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.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.CorrectedDetailedLinesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.CorrectedDetailedLinesTable, + Columns: []string{chargeusagebasedruns.CorrectedDetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.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 +} + +// SetAmount sets the "amount" field. +func (_u *ChargeUsageBasedRunsUpdateOne) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdateOne { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_u *ChargeUsageBasedRunsUpdateOne) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetTaxesTotal(v) + return _u +} + +// SetNillableTaxesTotal sets the "taxes_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNillableTaxesTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdateOne { + if v != nil { + _u.SetTaxesTotal(*v) + } + return _u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_u *ChargeUsageBasedRunsUpdateOne) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetTaxesInclusiveTotal(v) + return _u +} + +// SetNillableTaxesInclusiveTotal sets the "taxes_inclusive_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNillableTaxesInclusiveTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdateOne { + if v != nil { + _u.SetTaxesInclusiveTotal(*v) + } + return _u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_u *ChargeUsageBasedRunsUpdateOne) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetTaxesExclusiveTotal(v) + return _u +} + +// SetNillableTaxesExclusiveTotal sets the "taxes_exclusive_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNillableTaxesExclusiveTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdateOne { + if v != nil { + _u.SetTaxesExclusiveTotal(*v) + } + return _u +} + +// SetChargesTotal sets the "charges_total" field. +func (_u *ChargeUsageBasedRunsUpdateOne) SetChargesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetChargesTotal(v) + return _u +} + +// SetNillableChargesTotal sets the "charges_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNillableChargesTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdateOne { + if v != nil { + _u.SetChargesTotal(*v) + } + return _u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_u *ChargeUsageBasedRunsUpdateOne) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetDiscountsTotal(v) + return _u +} + +// SetNillableDiscountsTotal sets the "discounts_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNillableDiscountsTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdateOne { + if v != nil { + _u.SetDiscountsTotal(*v) + } + return _u +} + +// SetCreditsTotal sets the "credits_total" field. +func (_u *ChargeUsageBasedRunsUpdateOne) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetCreditsTotal(v) + return _u +} + +// SetNillableCreditsTotal sets the "credits_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNillableCreditsTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdateOne { + if v != nil { + _u.SetCreditsTotal(*v) + } + return _u +} + +// SetTotal sets the "total" field. +func (_u *ChargeUsageBasedRunsUpdateOne) SetTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetTotal(v) + return _u +} + +// SetNillableTotal sets the "total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNillableTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdateOne { + if v != nil { + _u.SetTotal(*v) + } + return _u +} + +// SetType sets the "type" field. +func (_u *ChargeUsageBasedRunsUpdateOne) SetType(v usagebased.RealizationRunType) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetType(v) + return _u +} + +// SetNillableType sets the "type" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNillableType(v *usagebased.RealizationRunType) *ChargeUsageBasedRunsUpdateOne { + if v != nil { + _u.SetType(*v) + } + return _u +} + +// SetStoredAtLt sets the "stored_at_lt" field. +func (_u *ChargeUsageBasedRunsUpdateOne) SetStoredAtLt(v time.Time) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetStoredAtLt(v) + return _u +} + +// SetNillableStoredAtLt sets the "stored_at_lt" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNillableStoredAtLt(v *time.Time) *ChargeUsageBasedRunsUpdateOne { + if v != nil { + _u.SetStoredAtLt(*v) + } + return _u +} + +// SetDetailedLinesPresent sets the "detailed_lines_present" field. +func (_u *ChargeUsageBasedRunsUpdateOne) SetDetailedLinesPresent(v bool) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetDetailedLinesPresent(v) + return _u +} + +// SetNillableDetailedLinesPresent sets the "detailed_lines_present" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNillableDetailedLinesPresent(v *bool) *ChargeUsageBasedRunsUpdateOne { + if v != nil { + _u.SetDetailedLinesPresent(*v) + } + return _u +} + +// SetLineID sets the "line_id" field. +func (_u *ChargeUsageBasedRunsUpdateOne) SetLineID(v string) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetLineID(v) + return _u +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNillableLineID(v *string) *ChargeUsageBasedRunsUpdateOne { + if v != nil { + _u.SetLineID(*v) + } + return _u +} + +// ClearLineID clears the value of the "line_id" field. +func (_u *ChargeUsageBasedRunsUpdateOne) ClearLineID() *ChargeUsageBasedRunsUpdateOne { + _u.mutation.ClearLineID() + return _u +} + +// SetMeteredQuantity sets the "metered_quantity" field. +func (_u *ChargeUsageBasedRunsUpdateOne) SetMeteredQuantity(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetMeteredQuantity(v) + return _u +} + +// SetNillableMeteredQuantity sets the "metered_quantity" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNillableMeteredQuantity(v *alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdateOne { + if v != nil { + _u.SetMeteredQuantity(*v) + } + return _u +} + +// SetNoFiatTransactionRequired sets the "no_fiat_transaction_required" field. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNoFiatTransactionRequired(v bool) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetNoFiatTransactionRequired(v) + return _u +} + +// SetNillableNoFiatTransactionRequired sets the "no_fiat_transaction_required" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNillableNoFiatTransactionRequired(v *bool) *ChargeUsageBasedRunsUpdateOne { + if v != nil { + _u.SetNoFiatTransactionRequired(*v) + } + return _u +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID. +func (_u *ChargeUsageBasedRunsUpdateOne) SetBillingInvoiceLineID(id string) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetBillingInvoiceLineID(id) + return _u +} + +// SetNillableBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by ID if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNillableBillingInvoiceLineID(id *string) *ChargeUsageBasedRunsUpdateOne { + if id != nil { + _u = _u.SetBillingInvoiceLineID(*id) + } + return _u +} + +// SetBillingInvoiceLine sets the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *ChargeUsageBasedRunsUpdateOne) SetBillingInvoiceLine(v *BillingInvoiceLine) *ChargeUsageBasedRunsUpdateOne { + return _u.SetBillingInvoiceLineID(v.ID) +} + +// 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...) +} + +// AddDetailedLineIDs adds the "detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity by IDs. +func (_u *ChargeUsageBasedRunsUpdateOne) AddDetailedLineIDs(ids ...string) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.AddDetailedLineIDs(ids...) + return _u +} + +// AddDetailedLines adds the "detailed_lines" edges to the ChargeUsageBasedRunDetailedLine entity. +func (_u *ChargeUsageBasedRunsUpdateOne) AddDetailedLines(v ...*ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedRunsUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddDetailedLineIDs(ids...) +} + +// AddCorrectedDetailedLineIDs adds the "corrected_detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity by IDs. +func (_u *ChargeUsageBasedRunsUpdateOne) AddCorrectedDetailedLineIDs(ids ...string) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.AddCorrectedDetailedLineIDs(ids...) + return _u +} + +// AddCorrectedDetailedLines adds the "corrected_detailed_lines" edges to the ChargeUsageBasedRunDetailedLine entity. +func (_u *ChargeUsageBasedRunsUpdateOne) AddCorrectedDetailedLines(v ...*ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedRunsUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddCorrectedDetailedLineIDs(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 +} + +// ClearBillingInvoiceLine clears the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (_u *ChargeUsageBasedRunsUpdateOne) ClearBillingInvoiceLine() *ChargeUsageBasedRunsUpdateOne { + _u.mutation.ClearBillingInvoiceLine() + return _u +} + +// 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...) +} + +// ClearDetailedLines clears all "detailed_lines" edges to the ChargeUsageBasedRunDetailedLine entity. +func (_u *ChargeUsageBasedRunsUpdateOne) ClearDetailedLines() *ChargeUsageBasedRunsUpdateOne { + _u.mutation.ClearDetailedLines() + return _u +} + +// RemoveDetailedLineIDs removes the "detailed_lines" edge to ChargeUsageBasedRunDetailedLine entities by IDs. +func (_u *ChargeUsageBasedRunsUpdateOne) RemoveDetailedLineIDs(ids ...string) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.RemoveDetailedLineIDs(ids...) + return _u +} + +// RemoveDetailedLines removes "detailed_lines" edges to ChargeUsageBasedRunDetailedLine entities. +func (_u *ChargeUsageBasedRunsUpdateOne) RemoveDetailedLines(v ...*ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedRunsUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveDetailedLineIDs(ids...) +} + +// ClearCorrectedDetailedLines clears all "corrected_detailed_lines" edges to the ChargeUsageBasedRunDetailedLine entity. +func (_u *ChargeUsageBasedRunsUpdateOne) ClearCorrectedDetailedLines() *ChargeUsageBasedRunsUpdateOne { + _u.mutation.ClearCorrectedDetailedLines() + return _u +} + +// RemoveCorrectedDetailedLineIDs removes the "corrected_detailed_lines" edge to ChargeUsageBasedRunDetailedLine entities by IDs. +func (_u *ChargeUsageBasedRunsUpdateOne) RemoveCorrectedDetailedLineIDs(ids ...string) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.RemoveCorrectedDetailedLineIDs(ids...) + return _u +} + +// RemoveCorrectedDetailedLines removes "corrected_detailed_lines" edges to ChargeUsageBasedRunDetailedLine entities. +func (_u *ChargeUsageBasedRunsUpdateOne) RemoveCorrectedDetailedLines(v ...*ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedRunsUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveCorrectedDetailedLineIDs(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 v, ok := _u.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 v, ok := _u.mutation.LineID(); ok { + if err := chargeusagebasedruns.LineIDValidator(v); err != nil { + return &ValidationError{Name: "line_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRuns.line_id": %w`, err)} + } + } + if _u.mutation.UsageBasedCleared() && len(_u.mutation.UsageBasedIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBasedRuns.usage_based"`) + } + if _u.mutation.FeatureCleared() && len(_u.mutation.FeatureIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBasedRuns.feature"`) + } + 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.Amount(); ok { + _spec.SetField(chargeusagebasedruns.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesTotal(); ok { + _spec.SetField(chargeusagebasedruns.FieldTaxesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(chargeusagebasedruns.FieldTaxesInclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(chargeusagebasedruns.FieldTaxesExclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.ChargesTotal(); ok { + _spec.SetField(chargeusagebasedruns.FieldChargesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.DiscountsTotal(); ok { + _spec.SetField(chargeusagebasedruns.FieldDiscountsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.CreditsTotal(); ok { + _spec.SetField(chargeusagebasedruns.FieldCreditsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.Total(); ok { + _spec.SetField(chargeusagebasedruns.FieldTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.GetType(); ok { + _spec.SetField(chargeusagebasedruns.FieldType, field.TypeEnum, value) + } + if value, ok := _u.mutation.StoredAtLt(); ok { + _spec.SetField(chargeusagebasedruns.FieldStoredAtLt, field.TypeTime, value) + } + if value, ok := _u.mutation.DetailedLinesPresent(); ok { + _spec.SetField(chargeusagebasedruns.FieldDetailedLinesPresent, field.TypeBool, value) + } + if value, ok := _u.mutation.MeteredQuantity(); ok { + _spec.SetField(chargeusagebasedruns.FieldMeteredQuantity, field.TypeOther, value) + } + if value, ok := _u.mutation.NoFiatTransactionRequired(); ok { + _spec.SetField(chargeusagebasedruns.FieldNoFiatTransactionRequired, field.TypeBool, value) + } + if _u.mutation.BillingInvoiceLineCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeusagebasedruns.BillingInvoiceLineTable, + Columns: []string{chargeusagebasedruns.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingInvoiceLineIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeusagebasedruns.BillingInvoiceLineTable, + Columns: []string{chargeusagebasedruns.BillingInvoiceLineColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoiceline.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.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.DetailedLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.DetailedLinesTable, + Columns: []string{chargeusagebasedruns.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedDetailedLinesIDs(); len(nodes) > 0 && !_u.mutation.DetailedLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.DetailedLinesTable, + Columns: []string{chargeusagebasedruns.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.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.DetailedLinesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.DetailedLinesTable, + Columns: []string{chargeusagebasedruns.DetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.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.CorrectedDetailedLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.CorrectedDetailedLinesTable, + Columns: []string{chargeusagebasedruns.CorrectedDetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedCorrectedDetailedLinesIDs(); len(nodes) > 0 && !_u.mutation.CorrectedDetailedLinesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.CorrectedDetailedLinesTable, + Columns: []string{chargeusagebasedruns.CorrectedDetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.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.CorrectedDetailedLinesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.CorrectedDetailedLinesTable, + Columns: []string{chargeusagebasedruns.CorrectedDetailedLinesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrundetailedline.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/ent/db/client.go b/ent/db/client.go new file mode 100644 index 0000000000000000000000000000000000000000..439611c943f5bc960c8df48127b12b8f1bd9d781 --- /dev/null +++ b/ent/db/client.go @@ -0,0 +1,16386 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "log" + "reflect" + + "github.com/openmeterio/openmeter/openmeter/ent/db/migrate" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/ent/db/addon" + "github.com/openmeterio/openmeter/openmeter/ent/db/addonratecard" + dbapp "github.com/openmeterio/openmeter/openmeter/ent/db/app" + "github.com/openmeterio/openmeter/openmeter/ent/db/appcustomer" + "github.com/openmeterio/openmeter/openmeter/ent/db/appcustominvoicing" + "github.com/openmeterio/openmeter/openmeter/ent/db/appcustominvoicingcustomer" + "github.com/openmeterio/openmeter/openmeter/ent/db/appstripe" + "github.com/openmeterio/openmeter/openmeter/ent/db/appstripecustomer" + "github.com/openmeterio/openmeter/openmeter/ent/db/balancesnapshot" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingcustomerlock" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingcustomeroverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceflatfeelineconfig" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicelinediscount" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicelineusagediscount" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicesplitlinegroup" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceusagebasedlineconfig" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicevalidationissue" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicewriteschemalevel" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingprofile" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingsequencenumbers" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingstandardinvoicedetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingstandardinvoicedetailedlineamountdiscount" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingworkflowconfig" + "github.com/openmeterio/openmeter/openmeter/ent/db/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchase" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchasecreditgrant" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchaseexternalpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchaseinvoicedpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeoverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerundetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedoverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrundetailedline" + "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/creditrealizationlineage" + "github.com/openmeterio/openmeter/openmeter/ent/db/creditrealizationlineagesegment" + "github.com/openmeterio/openmeter/openmeter/ent/db/currencycostbasis" + "github.com/openmeterio/openmeter/openmeter/ent/db/customcurrency" + "github.com/openmeterio/openmeter/openmeter/ent/db/customer" + "github.com/openmeterio/openmeter/openmeter/ent/db/customersubjects" + "github.com/openmeterio/openmeter/openmeter/ent/db/entitlement" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + dbgrant "github.com/openmeterio/openmeter/openmeter/ent/db/grant" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgerbreakagerecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgercreditvoidrecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgercustomeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgerentry" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccountroute" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransaction" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransactiongroup" + "github.com/openmeterio/openmeter/openmeter/ent/db/llmcostprice" + dbmeter "github.com/openmeterio/openmeter/openmeter/ent/db/meter" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationchannel" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationevent" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationeventdeliverystatus" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationrule" + "github.com/openmeterio/openmeter/openmeter/ent/db/organizationdefaulttaxcodes" + "github.com/openmeterio/openmeter/openmeter/ent/db/plan" + "github.com/openmeterio/openmeter/openmeter/ent/db/planaddon" + "github.com/openmeterio/openmeter/openmeter/ent/db/planphase" + "github.com/openmeterio/openmeter/openmeter/ent/db/planratecard" + "github.com/openmeterio/openmeter/openmeter/ent/db/subject" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionaddon" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionaddonquantity" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionbillingsyncstate" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionphase" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" + "github.com/openmeterio/openmeter/openmeter/ent/db/usagereset" + + stdsql "database/sql" +) + +// Client is the client that holds all ent builders. +type Client struct { + config + // Schema is the client for creating, migrating and dropping schema. + Schema *migrate.Schema + // Addon is the client for interacting with the Addon builders. + Addon *AddonClient + // AddonRateCard is the client for interacting with the AddonRateCard builders. + AddonRateCard *AddonRateCardClient + // App is the client for interacting with the App builders. + App *AppClient + // AppCustomInvoicing is the client for interacting with the AppCustomInvoicing builders. + AppCustomInvoicing *AppCustomInvoicingClient + // AppCustomInvoicingCustomer is the client for interacting with the AppCustomInvoicingCustomer builders. + AppCustomInvoicingCustomer *AppCustomInvoicingCustomerClient + // AppCustomer is the client for interacting with the AppCustomer builders. + AppCustomer *AppCustomerClient + // AppStripe is the client for interacting with the AppStripe builders. + AppStripe *AppStripeClient + // AppStripeCustomer is the client for interacting with the AppStripeCustomer builders. + AppStripeCustomer *AppStripeCustomerClient + // BalanceSnapshot is the client for interacting with the BalanceSnapshot builders. + BalanceSnapshot *BalanceSnapshotClient + // BillingCustomerLock is the client for interacting with the BillingCustomerLock builders. + BillingCustomerLock *BillingCustomerLockClient + // BillingCustomerOverride is the client for interacting with the BillingCustomerOverride builders. + BillingCustomerOverride *BillingCustomerOverrideClient + // BillingInvoice is the client for interacting with the BillingInvoice builders. + BillingInvoice *BillingInvoiceClient + // BillingInvoiceFlatFeeLineConfig is the client for interacting with the BillingInvoiceFlatFeeLineConfig builders. + BillingInvoiceFlatFeeLineConfig *BillingInvoiceFlatFeeLineConfigClient + // BillingInvoiceLine is the client for interacting with the BillingInvoiceLine builders. + BillingInvoiceLine *BillingInvoiceLineClient + // BillingInvoiceLineDiscount is the client for interacting with the BillingInvoiceLineDiscount builders. + BillingInvoiceLineDiscount *BillingInvoiceLineDiscountClient + // BillingInvoiceLineUsageDiscount is the client for interacting with the BillingInvoiceLineUsageDiscount builders. + BillingInvoiceLineUsageDiscount *BillingInvoiceLineUsageDiscountClient + // BillingInvoiceSplitLineGroup is the client for interacting with the BillingInvoiceSplitLineGroup builders. + BillingInvoiceSplitLineGroup *BillingInvoiceSplitLineGroupClient + // BillingInvoiceUsageBasedLineConfig is the client for interacting with the BillingInvoiceUsageBasedLineConfig builders. + BillingInvoiceUsageBasedLineConfig *BillingInvoiceUsageBasedLineConfigClient + // BillingInvoiceValidationIssue is the client for interacting with the BillingInvoiceValidationIssue builders. + BillingInvoiceValidationIssue *BillingInvoiceValidationIssueClient + // BillingInvoiceWriteSchemaLevel is the client for interacting with the BillingInvoiceWriteSchemaLevel builders. + BillingInvoiceWriteSchemaLevel *BillingInvoiceWriteSchemaLevelClient + // BillingProfile is the client for interacting with the BillingProfile builders. + BillingProfile *BillingProfileClient + // BillingSequenceNumbers is the client for interacting with the BillingSequenceNumbers builders. + BillingSequenceNumbers *BillingSequenceNumbersClient + // BillingStandardInvoiceDetailedLine is the client for interacting with the BillingStandardInvoiceDetailedLine builders. + BillingStandardInvoiceDetailedLine *BillingStandardInvoiceDetailedLineClient + // BillingStandardInvoiceDetailedLineAmountDiscount is the client for interacting with the BillingStandardInvoiceDetailedLineAmountDiscount builders. + BillingStandardInvoiceDetailedLineAmountDiscount *BillingStandardInvoiceDetailedLineAmountDiscountClient + // BillingWorkflowConfig is the client for interacting with the BillingWorkflowConfig builders. + BillingWorkflowConfig *BillingWorkflowConfigClient + // Charge is the client for interacting with the Charge builders. + Charge *ChargeClient + // ChargeCreditPurchase is the client for interacting with the ChargeCreditPurchase builders. + ChargeCreditPurchase *ChargeCreditPurchaseClient + // ChargeCreditPurchaseCreditGrant is the client for interacting with the ChargeCreditPurchaseCreditGrant builders. + ChargeCreditPurchaseCreditGrant *ChargeCreditPurchaseCreditGrantClient + // ChargeCreditPurchaseExternalPayment is the client for interacting with the ChargeCreditPurchaseExternalPayment builders. + ChargeCreditPurchaseExternalPayment *ChargeCreditPurchaseExternalPaymentClient + // ChargeCreditPurchaseInvoicedPayment is the client for interacting with the ChargeCreditPurchaseInvoicedPayment builders. + ChargeCreditPurchaseInvoicedPayment *ChargeCreditPurchaseInvoicedPaymentClient + // ChargeFlatFee is the client for interacting with the ChargeFlatFee builders. + ChargeFlatFee *ChargeFlatFeeClient + // ChargeFlatFeeOverride is the client for interacting with the ChargeFlatFeeOverride builders. + ChargeFlatFeeOverride *ChargeFlatFeeOverrideClient + // ChargeFlatFeeRun is the client for interacting with the ChargeFlatFeeRun builders. + ChargeFlatFeeRun *ChargeFlatFeeRunClient + // ChargeFlatFeeRunCreditAllocations is the client for interacting with the ChargeFlatFeeRunCreditAllocations builders. + ChargeFlatFeeRunCreditAllocations *ChargeFlatFeeRunCreditAllocationsClient + // ChargeFlatFeeRunDetailedLine is the client for interacting with the ChargeFlatFeeRunDetailedLine builders. + ChargeFlatFeeRunDetailedLine *ChargeFlatFeeRunDetailedLineClient + // ChargeFlatFeeRunInvoicedUsage is the client for interacting with the ChargeFlatFeeRunInvoicedUsage builders. + ChargeFlatFeeRunInvoicedUsage *ChargeFlatFeeRunInvoicedUsageClient + // ChargeFlatFeeRunPayment is the client for interacting with the ChargeFlatFeeRunPayment builders. + ChargeFlatFeeRunPayment *ChargeFlatFeeRunPaymentClient + // ChargeUsageBased is the client for interacting with the ChargeUsageBased builders. + ChargeUsageBased *ChargeUsageBasedClient + // ChargeUsageBasedOverride is the client for interacting with the ChargeUsageBasedOverride builders. + ChargeUsageBasedOverride *ChargeUsageBasedOverrideClient + // ChargeUsageBasedRunCreditAllocations is the client for interacting with the ChargeUsageBasedRunCreditAllocations builders. + ChargeUsageBasedRunCreditAllocations *ChargeUsageBasedRunCreditAllocationsClient + // ChargeUsageBasedRunDetailedLine is the client for interacting with the ChargeUsageBasedRunDetailedLine builders. + ChargeUsageBasedRunDetailedLine *ChargeUsageBasedRunDetailedLineClient + // 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 + // ChargesSearchV1 is the client for interacting with the ChargesSearchV1 builders. + ChargesSearchV1 *ChargesSearchV1Client + // CreditRealizationLineage is the client for interacting with the CreditRealizationLineage builders. + CreditRealizationLineage *CreditRealizationLineageClient + // CreditRealizationLineageSegment is the client for interacting with the CreditRealizationLineageSegment builders. + CreditRealizationLineageSegment *CreditRealizationLineageSegmentClient + // CurrencyCostBasis is the client for interacting with the CurrencyCostBasis builders. + CurrencyCostBasis *CurrencyCostBasisClient + // CustomCurrency is the client for interacting with the CustomCurrency builders. + CustomCurrency *CustomCurrencyClient + // Customer is the client for interacting with the Customer builders. + Customer *CustomerClient + // CustomerSubjects is the client for interacting with the CustomerSubjects builders. + CustomerSubjects *CustomerSubjectsClient + // Entitlement is the client for interacting with the Entitlement builders. + Entitlement *EntitlementClient + // Feature is the client for interacting with the Feature builders. + Feature *FeatureClient + // Grant is the client for interacting with the Grant builders. + Grant *GrantClient + // LLMCostPrice is the client for interacting with the LLMCostPrice builders. + LLMCostPrice *LLMCostPriceClient + // LedgerAccount is the client for interacting with the LedgerAccount builders. + LedgerAccount *LedgerAccountClient + // LedgerBreakageRecord is the client for interacting with the LedgerBreakageRecord builders. + LedgerBreakageRecord *LedgerBreakageRecordClient + // LedgerCreditVoidRecord is the client for interacting with the LedgerCreditVoidRecord builders. + LedgerCreditVoidRecord *LedgerCreditVoidRecordClient + // LedgerCustomerAccount is the client for interacting with the LedgerCustomerAccount builders. + LedgerCustomerAccount *LedgerCustomerAccountClient + // LedgerEntry is the client for interacting with the LedgerEntry builders. + LedgerEntry *LedgerEntryClient + // LedgerSubAccount is the client for interacting with the LedgerSubAccount builders. + LedgerSubAccount *LedgerSubAccountClient + // LedgerSubAccountRoute is the client for interacting with the LedgerSubAccountRoute builders. + LedgerSubAccountRoute *LedgerSubAccountRouteClient + // LedgerTransaction is the client for interacting with the LedgerTransaction builders. + LedgerTransaction *LedgerTransactionClient + // LedgerTransactionGroup is the client for interacting with the LedgerTransactionGroup builders. + LedgerTransactionGroup *LedgerTransactionGroupClient + // Meter is the client for interacting with the Meter builders. + Meter *MeterClient + // NotificationChannel is the client for interacting with the NotificationChannel builders. + NotificationChannel *NotificationChannelClient + // NotificationEvent is the client for interacting with the NotificationEvent builders. + NotificationEvent *NotificationEventClient + // NotificationEventDeliveryStatus is the client for interacting with the NotificationEventDeliveryStatus builders. + NotificationEventDeliveryStatus *NotificationEventDeliveryStatusClient + // NotificationRule is the client for interacting with the NotificationRule builders. + NotificationRule *NotificationRuleClient + // OrganizationDefaultTaxCodes is the client for interacting with the OrganizationDefaultTaxCodes builders. + OrganizationDefaultTaxCodes *OrganizationDefaultTaxCodesClient + // Plan is the client for interacting with the Plan builders. + Plan *PlanClient + // PlanAddon is the client for interacting with the PlanAddon builders. + PlanAddon *PlanAddonClient + // PlanPhase is the client for interacting with the PlanPhase builders. + PlanPhase *PlanPhaseClient + // PlanRateCard is the client for interacting with the PlanRateCard builders. + PlanRateCard *PlanRateCardClient + // Subject is the client for interacting with the Subject builders. + Subject *SubjectClient + // Subscription is the client for interacting with the Subscription builders. + Subscription *SubscriptionClient + // SubscriptionAddon is the client for interacting with the SubscriptionAddon builders. + SubscriptionAddon *SubscriptionAddonClient + // SubscriptionAddonQuantity is the client for interacting with the SubscriptionAddonQuantity builders. + SubscriptionAddonQuantity *SubscriptionAddonQuantityClient + // SubscriptionBillingSyncState is the client for interacting with the SubscriptionBillingSyncState builders. + SubscriptionBillingSyncState *SubscriptionBillingSyncStateClient + // SubscriptionItem is the client for interacting with the SubscriptionItem builders. + SubscriptionItem *SubscriptionItemClient + // SubscriptionPhase is the client for interacting with the SubscriptionPhase builders. + SubscriptionPhase *SubscriptionPhaseClient + // TaxCode is the client for interacting with the TaxCode builders. + TaxCode *TaxCodeClient + // UsageReset is the client for interacting with the UsageReset builders. + UsageReset *UsageResetClient +} + +// NewClient creates a new client configured with the given options. +func NewClient(opts ...Option) *Client { + client := &Client{config: newConfig(opts...)} + client.init() + return client +} + +func (c *Client) init() { + c.Schema = migrate.NewSchema(c.driver) + c.Addon = NewAddonClient(c.config) + c.AddonRateCard = NewAddonRateCardClient(c.config) + c.App = NewAppClient(c.config) + c.AppCustomInvoicing = NewAppCustomInvoicingClient(c.config) + c.AppCustomInvoicingCustomer = NewAppCustomInvoicingCustomerClient(c.config) + c.AppCustomer = NewAppCustomerClient(c.config) + c.AppStripe = NewAppStripeClient(c.config) + c.AppStripeCustomer = NewAppStripeCustomerClient(c.config) + c.BalanceSnapshot = NewBalanceSnapshotClient(c.config) + c.BillingCustomerLock = NewBillingCustomerLockClient(c.config) + c.BillingCustomerOverride = NewBillingCustomerOverrideClient(c.config) + c.BillingInvoice = NewBillingInvoiceClient(c.config) + c.BillingInvoiceFlatFeeLineConfig = NewBillingInvoiceFlatFeeLineConfigClient(c.config) + c.BillingInvoiceLine = NewBillingInvoiceLineClient(c.config) + c.BillingInvoiceLineDiscount = NewBillingInvoiceLineDiscountClient(c.config) + c.BillingInvoiceLineUsageDiscount = NewBillingInvoiceLineUsageDiscountClient(c.config) + c.BillingInvoiceSplitLineGroup = NewBillingInvoiceSplitLineGroupClient(c.config) + c.BillingInvoiceUsageBasedLineConfig = NewBillingInvoiceUsageBasedLineConfigClient(c.config) + c.BillingInvoiceValidationIssue = NewBillingInvoiceValidationIssueClient(c.config) + c.BillingInvoiceWriteSchemaLevel = NewBillingInvoiceWriteSchemaLevelClient(c.config) + c.BillingProfile = NewBillingProfileClient(c.config) + c.BillingSequenceNumbers = NewBillingSequenceNumbersClient(c.config) + c.BillingStandardInvoiceDetailedLine = NewBillingStandardInvoiceDetailedLineClient(c.config) + c.BillingStandardInvoiceDetailedLineAmountDiscount = NewBillingStandardInvoiceDetailedLineAmountDiscountClient(c.config) + c.BillingWorkflowConfig = NewBillingWorkflowConfigClient(c.config) + c.Charge = NewChargeClient(c.config) + c.ChargeCreditPurchase = NewChargeCreditPurchaseClient(c.config) + c.ChargeCreditPurchaseCreditGrant = NewChargeCreditPurchaseCreditGrantClient(c.config) + c.ChargeCreditPurchaseExternalPayment = NewChargeCreditPurchaseExternalPaymentClient(c.config) + c.ChargeCreditPurchaseInvoicedPayment = NewChargeCreditPurchaseInvoicedPaymentClient(c.config) + c.ChargeFlatFee = NewChargeFlatFeeClient(c.config) + c.ChargeFlatFeeOverride = NewChargeFlatFeeOverrideClient(c.config) + c.ChargeFlatFeeRun = NewChargeFlatFeeRunClient(c.config) + c.ChargeFlatFeeRunCreditAllocations = NewChargeFlatFeeRunCreditAllocationsClient(c.config) + c.ChargeFlatFeeRunDetailedLine = NewChargeFlatFeeRunDetailedLineClient(c.config) + c.ChargeFlatFeeRunInvoicedUsage = NewChargeFlatFeeRunInvoicedUsageClient(c.config) + c.ChargeFlatFeeRunPayment = NewChargeFlatFeeRunPaymentClient(c.config) + c.ChargeUsageBased = NewChargeUsageBasedClient(c.config) + c.ChargeUsageBasedOverride = NewChargeUsageBasedOverrideClient(c.config) + c.ChargeUsageBasedRunCreditAllocations = NewChargeUsageBasedRunCreditAllocationsClient(c.config) + c.ChargeUsageBasedRunDetailedLine = NewChargeUsageBasedRunDetailedLineClient(c.config) + c.ChargeUsageBasedRunInvoicedUsage = NewChargeUsageBasedRunInvoicedUsageClient(c.config) + c.ChargeUsageBasedRunPayment = NewChargeUsageBasedRunPaymentClient(c.config) + c.ChargeUsageBasedRuns = NewChargeUsageBasedRunsClient(c.config) + c.ChargesSearchV1 = NewChargesSearchV1Client(c.config) + c.CreditRealizationLineage = NewCreditRealizationLineageClient(c.config) + c.CreditRealizationLineageSegment = NewCreditRealizationLineageSegmentClient(c.config) + c.CurrencyCostBasis = NewCurrencyCostBasisClient(c.config) + c.CustomCurrency = NewCustomCurrencyClient(c.config) + c.Customer = NewCustomerClient(c.config) + c.CustomerSubjects = NewCustomerSubjectsClient(c.config) + c.Entitlement = NewEntitlementClient(c.config) + c.Feature = NewFeatureClient(c.config) + c.Grant = NewGrantClient(c.config) + c.LLMCostPrice = NewLLMCostPriceClient(c.config) + c.LedgerAccount = NewLedgerAccountClient(c.config) + c.LedgerBreakageRecord = NewLedgerBreakageRecordClient(c.config) + c.LedgerCreditVoidRecord = NewLedgerCreditVoidRecordClient(c.config) + c.LedgerCustomerAccount = NewLedgerCustomerAccountClient(c.config) + c.LedgerEntry = NewLedgerEntryClient(c.config) + c.LedgerSubAccount = NewLedgerSubAccountClient(c.config) + c.LedgerSubAccountRoute = NewLedgerSubAccountRouteClient(c.config) + c.LedgerTransaction = NewLedgerTransactionClient(c.config) + c.LedgerTransactionGroup = NewLedgerTransactionGroupClient(c.config) + c.Meter = NewMeterClient(c.config) + c.NotificationChannel = NewNotificationChannelClient(c.config) + c.NotificationEvent = NewNotificationEventClient(c.config) + c.NotificationEventDeliveryStatus = NewNotificationEventDeliveryStatusClient(c.config) + c.NotificationRule = NewNotificationRuleClient(c.config) + c.OrganizationDefaultTaxCodes = NewOrganizationDefaultTaxCodesClient(c.config) + c.Plan = NewPlanClient(c.config) + c.PlanAddon = NewPlanAddonClient(c.config) + c.PlanPhase = NewPlanPhaseClient(c.config) + c.PlanRateCard = NewPlanRateCardClient(c.config) + c.Subject = NewSubjectClient(c.config) + c.Subscription = NewSubscriptionClient(c.config) + c.SubscriptionAddon = NewSubscriptionAddonClient(c.config) + c.SubscriptionAddonQuantity = NewSubscriptionAddonQuantityClient(c.config) + c.SubscriptionBillingSyncState = NewSubscriptionBillingSyncStateClient(c.config) + c.SubscriptionItem = NewSubscriptionItemClient(c.config) + c.SubscriptionPhase = NewSubscriptionPhaseClient(c.config) + c.TaxCode = NewTaxCodeClient(c.config) + c.UsageReset = NewUsageResetClient(c.config) +} + +type ( + // config is the configuration for the client and its builder. + config struct { + // driver used for executing database requests. + driver dialect.Driver + // debug enable a debug logging. + debug bool + // log used for logging on debug mode. + log func(...any) + // hooks to execute on mutations. + hooks *hooks + // interceptors to execute on queries. + inters *inters + } + // Option function to configure the client. + Option func(*config) +) + +// newConfig creates a new config for the client. +func newConfig(opts ...Option) config { + cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}} + cfg.options(opts...) + return cfg +} + +// options applies the options on the config object. +func (c *config) options(opts ...Option) { + for _, opt := range opts { + opt(c) + } + if c.debug { + c.driver = dialect.Debug(c.driver, c.log) + } +} + +// Debug enables debug logging on the ent.Driver. +func Debug() Option { + return func(c *config) { + c.debug = true + } +} + +// Log sets the logging function for debug mode. +func Log(fn func(...any)) Option { + return func(c *config) { + c.log = fn + } +} + +// Driver configures the client driver. +func Driver(driver dialect.Driver) Option { + return func(c *config) { + c.driver = driver + } +} + +// Open opens a database/sql.DB specified by the driver name and +// the data source name, and returns a new client attached to it. +// Optional parameters can be added for configuring the client. +func Open(driverName, dataSourceName string, options ...Option) (*Client, error) { + switch driverName { + case dialect.MySQL, dialect.Postgres, dialect.SQLite: + drv, err := sql.Open(driverName, dataSourceName) + if err != nil { + return nil, err + } + return NewClient(append(options, Driver(drv))...), nil + default: + return nil, fmt.Errorf("unsupported driver: %q", driverName) + } +} + +// ErrTxStarted is returned when trying to start a new transaction from a transactional client. +var ErrTxStarted = errors.New("db: cannot start a transaction within a transaction") + +// Tx returns a new transactional client. The provided context +// is used until the transaction is committed or rolled back. +func (c *Client) Tx(ctx context.Context) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, ErrTxStarted + } + tx, err := newTx(ctx, c.driver) + if err != nil { + return nil, fmt.Errorf("db: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = tx + return &Tx{ + ctx: ctx, + config: cfg, + Addon: NewAddonClient(cfg), + AddonRateCard: NewAddonRateCardClient(cfg), + App: NewAppClient(cfg), + AppCustomInvoicing: NewAppCustomInvoicingClient(cfg), + AppCustomInvoicingCustomer: NewAppCustomInvoicingCustomerClient(cfg), + AppCustomer: NewAppCustomerClient(cfg), + AppStripe: NewAppStripeClient(cfg), + AppStripeCustomer: NewAppStripeCustomerClient(cfg), + BalanceSnapshot: NewBalanceSnapshotClient(cfg), + BillingCustomerLock: NewBillingCustomerLockClient(cfg), + BillingCustomerOverride: NewBillingCustomerOverrideClient(cfg), + BillingInvoice: NewBillingInvoiceClient(cfg), + BillingInvoiceFlatFeeLineConfig: NewBillingInvoiceFlatFeeLineConfigClient(cfg), + BillingInvoiceLine: NewBillingInvoiceLineClient(cfg), + BillingInvoiceLineDiscount: NewBillingInvoiceLineDiscountClient(cfg), + BillingInvoiceLineUsageDiscount: NewBillingInvoiceLineUsageDiscountClient(cfg), + BillingInvoiceSplitLineGroup: NewBillingInvoiceSplitLineGroupClient(cfg), + BillingInvoiceUsageBasedLineConfig: NewBillingInvoiceUsageBasedLineConfigClient(cfg), + BillingInvoiceValidationIssue: NewBillingInvoiceValidationIssueClient(cfg), + BillingInvoiceWriteSchemaLevel: NewBillingInvoiceWriteSchemaLevelClient(cfg), + BillingProfile: NewBillingProfileClient(cfg), + BillingSequenceNumbers: NewBillingSequenceNumbersClient(cfg), + BillingStandardInvoiceDetailedLine: NewBillingStandardInvoiceDetailedLineClient(cfg), + BillingStandardInvoiceDetailedLineAmountDiscount: NewBillingStandardInvoiceDetailedLineAmountDiscountClient(cfg), + BillingWorkflowConfig: NewBillingWorkflowConfigClient(cfg), + Charge: NewChargeClient(cfg), + ChargeCreditPurchase: NewChargeCreditPurchaseClient(cfg), + ChargeCreditPurchaseCreditGrant: NewChargeCreditPurchaseCreditGrantClient(cfg), + ChargeCreditPurchaseExternalPayment: NewChargeCreditPurchaseExternalPaymentClient(cfg), + ChargeCreditPurchaseInvoicedPayment: NewChargeCreditPurchaseInvoicedPaymentClient(cfg), + ChargeFlatFee: NewChargeFlatFeeClient(cfg), + ChargeFlatFeeOverride: NewChargeFlatFeeOverrideClient(cfg), + ChargeFlatFeeRun: NewChargeFlatFeeRunClient(cfg), + ChargeFlatFeeRunCreditAllocations: NewChargeFlatFeeRunCreditAllocationsClient(cfg), + ChargeFlatFeeRunDetailedLine: NewChargeFlatFeeRunDetailedLineClient(cfg), + ChargeFlatFeeRunInvoicedUsage: NewChargeFlatFeeRunInvoicedUsageClient(cfg), + ChargeFlatFeeRunPayment: NewChargeFlatFeeRunPaymentClient(cfg), + ChargeUsageBased: NewChargeUsageBasedClient(cfg), + ChargeUsageBasedOverride: NewChargeUsageBasedOverrideClient(cfg), + ChargeUsageBasedRunCreditAllocations: NewChargeUsageBasedRunCreditAllocationsClient(cfg), + ChargeUsageBasedRunDetailedLine: NewChargeUsageBasedRunDetailedLineClient(cfg), + ChargeUsageBasedRunInvoicedUsage: NewChargeUsageBasedRunInvoicedUsageClient(cfg), + ChargeUsageBasedRunPayment: NewChargeUsageBasedRunPaymentClient(cfg), + ChargeUsageBasedRuns: NewChargeUsageBasedRunsClient(cfg), + ChargesSearchV1: NewChargesSearchV1Client(cfg), + CreditRealizationLineage: NewCreditRealizationLineageClient(cfg), + CreditRealizationLineageSegment: NewCreditRealizationLineageSegmentClient(cfg), + CurrencyCostBasis: NewCurrencyCostBasisClient(cfg), + CustomCurrency: NewCustomCurrencyClient(cfg), + Customer: NewCustomerClient(cfg), + CustomerSubjects: NewCustomerSubjectsClient(cfg), + Entitlement: NewEntitlementClient(cfg), + Feature: NewFeatureClient(cfg), + Grant: NewGrantClient(cfg), + LLMCostPrice: NewLLMCostPriceClient(cfg), + LedgerAccount: NewLedgerAccountClient(cfg), + LedgerBreakageRecord: NewLedgerBreakageRecordClient(cfg), + LedgerCreditVoidRecord: NewLedgerCreditVoidRecordClient(cfg), + LedgerCustomerAccount: NewLedgerCustomerAccountClient(cfg), + LedgerEntry: NewLedgerEntryClient(cfg), + LedgerSubAccount: NewLedgerSubAccountClient(cfg), + LedgerSubAccountRoute: NewLedgerSubAccountRouteClient(cfg), + LedgerTransaction: NewLedgerTransactionClient(cfg), + LedgerTransactionGroup: NewLedgerTransactionGroupClient(cfg), + Meter: NewMeterClient(cfg), + NotificationChannel: NewNotificationChannelClient(cfg), + NotificationEvent: NewNotificationEventClient(cfg), + NotificationEventDeliveryStatus: NewNotificationEventDeliveryStatusClient(cfg), + NotificationRule: NewNotificationRuleClient(cfg), + OrganizationDefaultTaxCodes: NewOrganizationDefaultTaxCodesClient(cfg), + Plan: NewPlanClient(cfg), + PlanAddon: NewPlanAddonClient(cfg), + PlanPhase: NewPlanPhaseClient(cfg), + PlanRateCard: NewPlanRateCardClient(cfg), + Subject: NewSubjectClient(cfg), + Subscription: NewSubscriptionClient(cfg), + SubscriptionAddon: NewSubscriptionAddonClient(cfg), + SubscriptionAddonQuantity: NewSubscriptionAddonQuantityClient(cfg), + SubscriptionBillingSyncState: NewSubscriptionBillingSyncStateClient(cfg), + SubscriptionItem: NewSubscriptionItemClient(cfg), + SubscriptionPhase: NewSubscriptionPhaseClient(cfg), + TaxCode: NewTaxCodeClient(cfg), + UsageReset: NewUsageResetClient(cfg), + }, nil +} + +// BeginTx returns a transactional client with specified options. +func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, errors.New("ent: cannot start a transaction within a transaction") + } + tx, err := c.driver.(interface { + BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) + }).BeginTx(ctx, opts) + if err != nil { + return nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = &txDriver{tx: tx, drv: c.driver} + return &Tx{ + ctx: ctx, + config: cfg, + Addon: NewAddonClient(cfg), + AddonRateCard: NewAddonRateCardClient(cfg), + App: NewAppClient(cfg), + AppCustomInvoicing: NewAppCustomInvoicingClient(cfg), + AppCustomInvoicingCustomer: NewAppCustomInvoicingCustomerClient(cfg), + AppCustomer: NewAppCustomerClient(cfg), + AppStripe: NewAppStripeClient(cfg), + AppStripeCustomer: NewAppStripeCustomerClient(cfg), + BalanceSnapshot: NewBalanceSnapshotClient(cfg), + BillingCustomerLock: NewBillingCustomerLockClient(cfg), + BillingCustomerOverride: NewBillingCustomerOverrideClient(cfg), + BillingInvoice: NewBillingInvoiceClient(cfg), + BillingInvoiceFlatFeeLineConfig: NewBillingInvoiceFlatFeeLineConfigClient(cfg), + BillingInvoiceLine: NewBillingInvoiceLineClient(cfg), + BillingInvoiceLineDiscount: NewBillingInvoiceLineDiscountClient(cfg), + BillingInvoiceLineUsageDiscount: NewBillingInvoiceLineUsageDiscountClient(cfg), + BillingInvoiceSplitLineGroup: NewBillingInvoiceSplitLineGroupClient(cfg), + BillingInvoiceUsageBasedLineConfig: NewBillingInvoiceUsageBasedLineConfigClient(cfg), + BillingInvoiceValidationIssue: NewBillingInvoiceValidationIssueClient(cfg), + BillingInvoiceWriteSchemaLevel: NewBillingInvoiceWriteSchemaLevelClient(cfg), + BillingProfile: NewBillingProfileClient(cfg), + BillingSequenceNumbers: NewBillingSequenceNumbersClient(cfg), + BillingStandardInvoiceDetailedLine: NewBillingStandardInvoiceDetailedLineClient(cfg), + BillingStandardInvoiceDetailedLineAmountDiscount: NewBillingStandardInvoiceDetailedLineAmountDiscountClient(cfg), + BillingWorkflowConfig: NewBillingWorkflowConfigClient(cfg), + Charge: NewChargeClient(cfg), + ChargeCreditPurchase: NewChargeCreditPurchaseClient(cfg), + ChargeCreditPurchaseCreditGrant: NewChargeCreditPurchaseCreditGrantClient(cfg), + ChargeCreditPurchaseExternalPayment: NewChargeCreditPurchaseExternalPaymentClient(cfg), + ChargeCreditPurchaseInvoicedPayment: NewChargeCreditPurchaseInvoicedPaymentClient(cfg), + ChargeFlatFee: NewChargeFlatFeeClient(cfg), + ChargeFlatFeeOverride: NewChargeFlatFeeOverrideClient(cfg), + ChargeFlatFeeRun: NewChargeFlatFeeRunClient(cfg), + ChargeFlatFeeRunCreditAllocations: NewChargeFlatFeeRunCreditAllocationsClient(cfg), + ChargeFlatFeeRunDetailedLine: NewChargeFlatFeeRunDetailedLineClient(cfg), + ChargeFlatFeeRunInvoicedUsage: NewChargeFlatFeeRunInvoicedUsageClient(cfg), + ChargeFlatFeeRunPayment: NewChargeFlatFeeRunPaymentClient(cfg), + ChargeUsageBased: NewChargeUsageBasedClient(cfg), + ChargeUsageBasedOverride: NewChargeUsageBasedOverrideClient(cfg), + ChargeUsageBasedRunCreditAllocations: NewChargeUsageBasedRunCreditAllocationsClient(cfg), + ChargeUsageBasedRunDetailedLine: NewChargeUsageBasedRunDetailedLineClient(cfg), + ChargeUsageBasedRunInvoicedUsage: NewChargeUsageBasedRunInvoicedUsageClient(cfg), + ChargeUsageBasedRunPayment: NewChargeUsageBasedRunPaymentClient(cfg), + ChargeUsageBasedRuns: NewChargeUsageBasedRunsClient(cfg), + ChargesSearchV1: NewChargesSearchV1Client(cfg), + CreditRealizationLineage: NewCreditRealizationLineageClient(cfg), + CreditRealizationLineageSegment: NewCreditRealizationLineageSegmentClient(cfg), + CurrencyCostBasis: NewCurrencyCostBasisClient(cfg), + CustomCurrency: NewCustomCurrencyClient(cfg), + Customer: NewCustomerClient(cfg), + CustomerSubjects: NewCustomerSubjectsClient(cfg), + Entitlement: NewEntitlementClient(cfg), + Feature: NewFeatureClient(cfg), + Grant: NewGrantClient(cfg), + LLMCostPrice: NewLLMCostPriceClient(cfg), + LedgerAccount: NewLedgerAccountClient(cfg), + LedgerBreakageRecord: NewLedgerBreakageRecordClient(cfg), + LedgerCreditVoidRecord: NewLedgerCreditVoidRecordClient(cfg), + LedgerCustomerAccount: NewLedgerCustomerAccountClient(cfg), + LedgerEntry: NewLedgerEntryClient(cfg), + LedgerSubAccount: NewLedgerSubAccountClient(cfg), + LedgerSubAccountRoute: NewLedgerSubAccountRouteClient(cfg), + LedgerTransaction: NewLedgerTransactionClient(cfg), + LedgerTransactionGroup: NewLedgerTransactionGroupClient(cfg), + Meter: NewMeterClient(cfg), + NotificationChannel: NewNotificationChannelClient(cfg), + NotificationEvent: NewNotificationEventClient(cfg), + NotificationEventDeliveryStatus: NewNotificationEventDeliveryStatusClient(cfg), + NotificationRule: NewNotificationRuleClient(cfg), + OrganizationDefaultTaxCodes: NewOrganizationDefaultTaxCodesClient(cfg), + Plan: NewPlanClient(cfg), + PlanAddon: NewPlanAddonClient(cfg), + PlanPhase: NewPlanPhaseClient(cfg), + PlanRateCard: NewPlanRateCardClient(cfg), + Subject: NewSubjectClient(cfg), + Subscription: NewSubscriptionClient(cfg), + SubscriptionAddon: NewSubscriptionAddonClient(cfg), + SubscriptionAddonQuantity: NewSubscriptionAddonQuantityClient(cfg), + SubscriptionBillingSyncState: NewSubscriptionBillingSyncStateClient(cfg), + SubscriptionItem: NewSubscriptionItemClient(cfg), + SubscriptionPhase: NewSubscriptionPhaseClient(cfg), + TaxCode: NewTaxCodeClient(cfg), + UsageReset: NewUsageResetClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// Addon. +// Query(). +// Count(ctx) +func (c *Client) Debug() *Client { + if c.debug { + return c + } + cfg := c.config + cfg.driver = dialect.Debug(c.driver, c.log) + client := &Client{config: cfg} + client.init() + return client +} + +// Close closes the database connection and prevents new queries from starting. +func (c *Client) Close() error { + return c.driver.Close() +} + +// Use adds the mutation hooks to all the entity clients. +// In order to add hooks to a specific client, call: `client.Node.Use(...)`. +func (c *Client) Use(hooks ...Hook) { + for _, n := range []interface{ Use(...Hook) }{ + c.Addon, c.AddonRateCard, c.App, c.AppCustomInvoicing, + c.AppCustomInvoicingCustomer, c.AppCustomer, c.AppStripe, c.AppStripeCustomer, + c.BalanceSnapshot, c.BillingCustomerLock, c.BillingCustomerOverride, + c.BillingInvoice, c.BillingInvoiceFlatFeeLineConfig, c.BillingInvoiceLine, + c.BillingInvoiceLineDiscount, c.BillingInvoiceLineUsageDiscount, + c.BillingInvoiceSplitLineGroup, c.BillingInvoiceUsageBasedLineConfig, + c.BillingInvoiceValidationIssue, c.BillingInvoiceWriteSchemaLevel, + c.BillingProfile, c.BillingSequenceNumbers, + c.BillingStandardInvoiceDetailedLine, + c.BillingStandardInvoiceDetailedLineAmountDiscount, c.BillingWorkflowConfig, + c.Charge, c.ChargeCreditPurchase, c.ChargeCreditPurchaseCreditGrant, + c.ChargeCreditPurchaseExternalPayment, c.ChargeCreditPurchaseInvoicedPayment, + c.ChargeFlatFee, c.ChargeFlatFeeOverride, c.ChargeFlatFeeRun, + c.ChargeFlatFeeRunCreditAllocations, c.ChargeFlatFeeRunDetailedLine, + c.ChargeFlatFeeRunInvoicedUsage, c.ChargeFlatFeeRunPayment, c.ChargeUsageBased, + c.ChargeUsageBasedOverride, c.ChargeUsageBasedRunCreditAllocations, + c.ChargeUsageBasedRunDetailedLine, c.ChargeUsageBasedRunInvoicedUsage, + c.ChargeUsageBasedRunPayment, c.ChargeUsageBasedRuns, + c.CreditRealizationLineage, c.CreditRealizationLineageSegment, + c.CurrencyCostBasis, c.CustomCurrency, c.Customer, c.CustomerSubjects, + c.Entitlement, c.Feature, c.Grant, c.LLMCostPrice, c.LedgerAccount, + c.LedgerBreakageRecord, c.LedgerCreditVoidRecord, c.LedgerCustomerAccount, + c.LedgerEntry, c.LedgerSubAccount, c.LedgerSubAccountRoute, + c.LedgerTransaction, c.LedgerTransactionGroup, c.Meter, c.NotificationChannel, + c.NotificationEvent, c.NotificationEventDeliveryStatus, c.NotificationRule, + c.OrganizationDefaultTaxCodes, c.Plan, c.PlanAddon, c.PlanPhase, + c.PlanRateCard, c.Subject, c.Subscription, c.SubscriptionAddon, + c.SubscriptionAddonQuantity, c.SubscriptionBillingSyncState, + c.SubscriptionItem, c.SubscriptionPhase, c.TaxCode, c.UsageReset, + } { + n.Use(hooks...) + } +} + +// Intercept adds the query interceptors to all the entity clients. +// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. +func (c *Client) Intercept(interceptors ...Interceptor) { + for _, n := range []interface{ Intercept(...Interceptor) }{ + c.Addon, c.AddonRateCard, c.App, c.AppCustomInvoicing, + c.AppCustomInvoicingCustomer, c.AppCustomer, c.AppStripe, c.AppStripeCustomer, + c.BalanceSnapshot, c.BillingCustomerLock, c.BillingCustomerOverride, + c.BillingInvoice, c.BillingInvoiceFlatFeeLineConfig, c.BillingInvoiceLine, + c.BillingInvoiceLineDiscount, c.BillingInvoiceLineUsageDiscount, + c.BillingInvoiceSplitLineGroup, c.BillingInvoiceUsageBasedLineConfig, + c.BillingInvoiceValidationIssue, c.BillingInvoiceWriteSchemaLevel, + c.BillingProfile, c.BillingSequenceNumbers, + c.BillingStandardInvoiceDetailedLine, + c.BillingStandardInvoiceDetailedLineAmountDiscount, c.BillingWorkflowConfig, + c.Charge, c.ChargeCreditPurchase, c.ChargeCreditPurchaseCreditGrant, + c.ChargeCreditPurchaseExternalPayment, c.ChargeCreditPurchaseInvoicedPayment, + c.ChargeFlatFee, c.ChargeFlatFeeOverride, c.ChargeFlatFeeRun, + c.ChargeFlatFeeRunCreditAllocations, c.ChargeFlatFeeRunDetailedLine, + c.ChargeFlatFeeRunInvoicedUsage, c.ChargeFlatFeeRunPayment, c.ChargeUsageBased, + c.ChargeUsageBasedOverride, c.ChargeUsageBasedRunCreditAllocations, + c.ChargeUsageBasedRunDetailedLine, c.ChargeUsageBasedRunInvoicedUsage, + c.ChargeUsageBasedRunPayment, c.ChargeUsageBasedRuns, c.ChargesSearchV1, + c.CreditRealizationLineage, c.CreditRealizationLineageSegment, + c.CurrencyCostBasis, c.CustomCurrency, c.Customer, c.CustomerSubjects, + c.Entitlement, c.Feature, c.Grant, c.LLMCostPrice, c.LedgerAccount, + c.LedgerBreakageRecord, c.LedgerCreditVoidRecord, c.LedgerCustomerAccount, + c.LedgerEntry, c.LedgerSubAccount, c.LedgerSubAccountRoute, + c.LedgerTransaction, c.LedgerTransactionGroup, c.Meter, c.NotificationChannel, + c.NotificationEvent, c.NotificationEventDeliveryStatus, c.NotificationRule, + c.OrganizationDefaultTaxCodes, c.Plan, c.PlanAddon, c.PlanPhase, + c.PlanRateCard, c.Subject, c.Subscription, c.SubscriptionAddon, + c.SubscriptionAddonQuantity, c.SubscriptionBillingSyncState, + c.SubscriptionItem, c.SubscriptionPhase, c.TaxCode, c.UsageReset, + } { + n.Intercept(interceptors...) + } +} + +// Mutate implements the ent.Mutator interface. +func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { + switch m := m.(type) { + case *AddonMutation: + return c.Addon.mutate(ctx, m) + case *AddonRateCardMutation: + return c.AddonRateCard.mutate(ctx, m) + case *AppMutation: + return c.App.mutate(ctx, m) + case *AppCustomInvoicingMutation: + return c.AppCustomInvoicing.mutate(ctx, m) + case *AppCustomInvoicingCustomerMutation: + return c.AppCustomInvoicingCustomer.mutate(ctx, m) + case *AppCustomerMutation: + return c.AppCustomer.mutate(ctx, m) + case *AppStripeMutation: + return c.AppStripe.mutate(ctx, m) + case *AppStripeCustomerMutation: + return c.AppStripeCustomer.mutate(ctx, m) + case *BalanceSnapshotMutation: + return c.BalanceSnapshot.mutate(ctx, m) + case *BillingCustomerLockMutation: + return c.BillingCustomerLock.mutate(ctx, m) + case *BillingCustomerOverrideMutation: + return c.BillingCustomerOverride.mutate(ctx, m) + case *BillingInvoiceMutation: + return c.BillingInvoice.mutate(ctx, m) + case *BillingInvoiceFlatFeeLineConfigMutation: + return c.BillingInvoiceFlatFeeLineConfig.mutate(ctx, m) + case *BillingInvoiceLineMutation: + return c.BillingInvoiceLine.mutate(ctx, m) + case *BillingInvoiceLineDiscountMutation: + return c.BillingInvoiceLineDiscount.mutate(ctx, m) + case *BillingInvoiceLineUsageDiscountMutation: + return c.BillingInvoiceLineUsageDiscount.mutate(ctx, m) + case *BillingInvoiceSplitLineGroupMutation: + return c.BillingInvoiceSplitLineGroup.mutate(ctx, m) + case *BillingInvoiceUsageBasedLineConfigMutation: + return c.BillingInvoiceUsageBasedLineConfig.mutate(ctx, m) + case *BillingInvoiceValidationIssueMutation: + return c.BillingInvoiceValidationIssue.mutate(ctx, m) + case *BillingInvoiceWriteSchemaLevelMutation: + return c.BillingInvoiceWriteSchemaLevel.mutate(ctx, m) + case *BillingProfileMutation: + return c.BillingProfile.mutate(ctx, m) + case *BillingSequenceNumbersMutation: + return c.BillingSequenceNumbers.mutate(ctx, m) + case *BillingStandardInvoiceDetailedLineMutation: + return c.BillingStandardInvoiceDetailedLine.mutate(ctx, m) + case *BillingStandardInvoiceDetailedLineAmountDiscountMutation: + return c.BillingStandardInvoiceDetailedLineAmountDiscount.mutate(ctx, m) + case *BillingWorkflowConfigMutation: + return c.BillingWorkflowConfig.mutate(ctx, m) + case *ChargeMutation: + return c.Charge.mutate(ctx, m) + case *ChargeCreditPurchaseMutation: + return c.ChargeCreditPurchase.mutate(ctx, m) + case *ChargeCreditPurchaseCreditGrantMutation: + return c.ChargeCreditPurchaseCreditGrant.mutate(ctx, m) + case *ChargeCreditPurchaseExternalPaymentMutation: + return c.ChargeCreditPurchaseExternalPayment.mutate(ctx, m) + case *ChargeCreditPurchaseInvoicedPaymentMutation: + return c.ChargeCreditPurchaseInvoicedPayment.mutate(ctx, m) + case *ChargeFlatFeeMutation: + return c.ChargeFlatFee.mutate(ctx, m) + case *ChargeFlatFeeOverrideMutation: + return c.ChargeFlatFeeOverride.mutate(ctx, m) + case *ChargeFlatFeeRunMutation: + return c.ChargeFlatFeeRun.mutate(ctx, m) + case *ChargeFlatFeeRunCreditAllocationsMutation: + return c.ChargeFlatFeeRunCreditAllocations.mutate(ctx, m) + case *ChargeFlatFeeRunDetailedLineMutation: + return c.ChargeFlatFeeRunDetailedLine.mutate(ctx, m) + case *ChargeFlatFeeRunInvoicedUsageMutation: + return c.ChargeFlatFeeRunInvoicedUsage.mutate(ctx, m) + case *ChargeFlatFeeRunPaymentMutation: + return c.ChargeFlatFeeRunPayment.mutate(ctx, m) + case *ChargeUsageBasedMutation: + return c.ChargeUsageBased.mutate(ctx, m) + case *ChargeUsageBasedOverrideMutation: + return c.ChargeUsageBasedOverride.mutate(ctx, m) + case *ChargeUsageBasedRunCreditAllocationsMutation: + return c.ChargeUsageBasedRunCreditAllocations.mutate(ctx, m) + case *ChargeUsageBasedRunDetailedLineMutation: + return c.ChargeUsageBasedRunDetailedLine.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 *CreditRealizationLineageMutation: + return c.CreditRealizationLineage.mutate(ctx, m) + case *CreditRealizationLineageSegmentMutation: + return c.CreditRealizationLineageSegment.mutate(ctx, m) + case *CurrencyCostBasisMutation: + return c.CurrencyCostBasis.mutate(ctx, m) + case *CustomCurrencyMutation: + return c.CustomCurrency.mutate(ctx, m) + case *CustomerMutation: + return c.Customer.mutate(ctx, m) + case *CustomerSubjectsMutation: + return c.CustomerSubjects.mutate(ctx, m) + case *EntitlementMutation: + return c.Entitlement.mutate(ctx, m) + case *FeatureMutation: + return c.Feature.mutate(ctx, m) + case *GrantMutation: + return c.Grant.mutate(ctx, m) + case *LLMCostPriceMutation: + return c.LLMCostPrice.mutate(ctx, m) + case *LedgerAccountMutation: + return c.LedgerAccount.mutate(ctx, m) + case *LedgerBreakageRecordMutation: + return c.LedgerBreakageRecord.mutate(ctx, m) + case *LedgerCreditVoidRecordMutation: + return c.LedgerCreditVoidRecord.mutate(ctx, m) + case *LedgerCustomerAccountMutation: + return c.LedgerCustomerAccount.mutate(ctx, m) + case *LedgerEntryMutation: + return c.LedgerEntry.mutate(ctx, m) + case *LedgerSubAccountMutation: + return c.LedgerSubAccount.mutate(ctx, m) + case *LedgerSubAccountRouteMutation: + return c.LedgerSubAccountRoute.mutate(ctx, m) + case *LedgerTransactionMutation: + return c.LedgerTransaction.mutate(ctx, m) + case *LedgerTransactionGroupMutation: + return c.LedgerTransactionGroup.mutate(ctx, m) + case *MeterMutation: + return c.Meter.mutate(ctx, m) + case *NotificationChannelMutation: + return c.NotificationChannel.mutate(ctx, m) + case *NotificationEventMutation: + return c.NotificationEvent.mutate(ctx, m) + case *NotificationEventDeliveryStatusMutation: + return c.NotificationEventDeliveryStatus.mutate(ctx, m) + case *NotificationRuleMutation: + return c.NotificationRule.mutate(ctx, m) + case *OrganizationDefaultTaxCodesMutation: + return c.OrganizationDefaultTaxCodes.mutate(ctx, m) + case *PlanMutation: + return c.Plan.mutate(ctx, m) + case *PlanAddonMutation: + return c.PlanAddon.mutate(ctx, m) + case *PlanPhaseMutation: + return c.PlanPhase.mutate(ctx, m) + case *PlanRateCardMutation: + return c.PlanRateCard.mutate(ctx, m) + case *SubjectMutation: + return c.Subject.mutate(ctx, m) + case *SubscriptionMutation: + return c.Subscription.mutate(ctx, m) + case *SubscriptionAddonMutation: + return c.SubscriptionAddon.mutate(ctx, m) + case *SubscriptionAddonQuantityMutation: + return c.SubscriptionAddonQuantity.mutate(ctx, m) + case *SubscriptionBillingSyncStateMutation: + return c.SubscriptionBillingSyncState.mutate(ctx, m) + case *SubscriptionItemMutation: + return c.SubscriptionItem.mutate(ctx, m) + case *SubscriptionPhaseMutation: + return c.SubscriptionPhase.mutate(ctx, m) + case *TaxCodeMutation: + return c.TaxCode.mutate(ctx, m) + case *UsageResetMutation: + return c.UsageReset.mutate(ctx, m) + default: + return nil, fmt.Errorf("db: unknown mutation type %T", m) + } +} + +// AddonClient is a client for the Addon schema. +type AddonClient struct { + config +} + +// NewAddonClient returns a client for the Addon from the given config. +func NewAddonClient(c config) *AddonClient { + return &AddonClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `addon.Hooks(f(g(h())))`. +func (c *AddonClient) Use(hooks ...Hook) { + c.hooks.Addon = append(c.hooks.Addon, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `addon.Intercept(f(g(h())))`. +func (c *AddonClient) Intercept(interceptors ...Interceptor) { + c.inters.Addon = append(c.inters.Addon, interceptors...) +} + +// Create returns a builder for creating a Addon entity. +func (c *AddonClient) Create() *AddonCreate { + mutation := newAddonMutation(c.config, OpCreate) + return &AddonCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Addon entities. +func (c *AddonClient) CreateBulk(builders ...*AddonCreate) *AddonCreateBulk { + return &AddonCreateBulk{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 *AddonClient) MapCreateBulk(slice any, setFunc func(*AddonCreate, int)) *AddonCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AddonCreateBulk{err: fmt.Errorf("calling to AddonClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AddonCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AddonCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Addon. +func (c *AddonClient) Update() *AddonUpdate { + mutation := newAddonMutation(c.config, OpUpdate) + return &AddonUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AddonClient) UpdateOne(_m *Addon) *AddonUpdateOne { + mutation := newAddonMutation(c.config, OpUpdateOne, withAddon(_m)) + return &AddonUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AddonClient) UpdateOneID(id string) *AddonUpdateOne { + mutation := newAddonMutation(c.config, OpUpdateOne, withAddonID(id)) + return &AddonUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Addon. +func (c *AddonClient) Delete() *AddonDelete { + mutation := newAddonMutation(c.config, OpDelete) + return &AddonDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AddonClient) DeleteOne(_m *Addon) *AddonDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AddonClient) DeleteOneID(id string) *AddonDeleteOne { + builder := c.Delete().Where(addon.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AddonDeleteOne{builder} +} + +// Query returns a query builder for Addon. +func (c *AddonClient) Query() *AddonQuery { + return &AddonQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAddon}, + inters: c.Interceptors(), + } +} + +// Get returns a Addon entity by its id. +func (c *AddonClient) Get(ctx context.Context, id string) (*Addon, error) { + return c.Query().Where(addon.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AddonClient) GetX(ctx context.Context, id string) *Addon { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryRatecards queries the ratecards edge of a Addon. +func (c *AddonClient) QueryRatecards(_m *Addon) *AddonRateCardQuery { + query := (&AddonRateCardClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(addon.Table, addon.FieldID, id), + sqlgraph.To(addonratecard.Table, addonratecard.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, addon.RatecardsTable, addon.RatecardsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryPlans queries the plans edge of a Addon. +func (c *AddonClient) QueryPlans(_m *Addon) *PlanAddonQuery { + query := (&PlanAddonClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(addon.Table, addon.FieldID, id), + sqlgraph.To(planaddon.Table, planaddon.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, addon.PlansTable, addon.PlansColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubscriptionAddons queries the subscription_addons edge of a Addon. +func (c *AddonClient) QuerySubscriptionAddons(_m *Addon) *SubscriptionAddonQuery { + query := (&SubscriptionAddonClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(addon.Table, addon.FieldID, id), + sqlgraph.To(subscriptionaddon.Table, subscriptionaddon.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, addon.SubscriptionAddonsTable, addon.SubscriptionAddonsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AddonClient) Hooks() []Hook { + return c.hooks.Addon +} + +// Interceptors returns the client interceptors. +func (c *AddonClient) Interceptors() []Interceptor { + return c.inters.Addon +} + +func (c *AddonClient) mutate(ctx context.Context, m *AddonMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AddonCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AddonUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AddonUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AddonDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown Addon mutation op: %q", m.Op()) + } +} + +// AddonRateCardClient is a client for the AddonRateCard schema. +type AddonRateCardClient struct { + config +} + +// NewAddonRateCardClient returns a client for the AddonRateCard from the given config. +func NewAddonRateCardClient(c config) *AddonRateCardClient { + return &AddonRateCardClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `addonratecard.Hooks(f(g(h())))`. +func (c *AddonRateCardClient) Use(hooks ...Hook) { + c.hooks.AddonRateCard = append(c.hooks.AddonRateCard, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `addonratecard.Intercept(f(g(h())))`. +func (c *AddonRateCardClient) Intercept(interceptors ...Interceptor) { + c.inters.AddonRateCard = append(c.inters.AddonRateCard, interceptors...) +} + +// Create returns a builder for creating a AddonRateCard entity. +func (c *AddonRateCardClient) Create() *AddonRateCardCreate { + mutation := newAddonRateCardMutation(c.config, OpCreate) + return &AddonRateCardCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of AddonRateCard entities. +func (c *AddonRateCardClient) CreateBulk(builders ...*AddonRateCardCreate) *AddonRateCardCreateBulk { + return &AddonRateCardCreateBulk{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 *AddonRateCardClient) MapCreateBulk(slice any, setFunc func(*AddonRateCardCreate, int)) *AddonRateCardCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AddonRateCardCreateBulk{err: fmt.Errorf("calling to AddonRateCardClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AddonRateCardCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AddonRateCardCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for AddonRateCard. +func (c *AddonRateCardClient) Update() *AddonRateCardUpdate { + mutation := newAddonRateCardMutation(c.config, OpUpdate) + return &AddonRateCardUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AddonRateCardClient) UpdateOne(_m *AddonRateCard) *AddonRateCardUpdateOne { + mutation := newAddonRateCardMutation(c.config, OpUpdateOne, withAddonRateCard(_m)) + return &AddonRateCardUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AddonRateCardClient) UpdateOneID(id string) *AddonRateCardUpdateOne { + mutation := newAddonRateCardMutation(c.config, OpUpdateOne, withAddonRateCardID(id)) + return &AddonRateCardUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for AddonRateCard. +func (c *AddonRateCardClient) Delete() *AddonRateCardDelete { + mutation := newAddonRateCardMutation(c.config, OpDelete) + return &AddonRateCardDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AddonRateCardClient) DeleteOne(_m *AddonRateCard) *AddonRateCardDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AddonRateCardClient) DeleteOneID(id string) *AddonRateCardDeleteOne { + builder := c.Delete().Where(addonratecard.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AddonRateCardDeleteOne{builder} +} + +// Query returns a query builder for AddonRateCard. +func (c *AddonRateCardClient) Query() *AddonRateCardQuery { + return &AddonRateCardQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAddonRateCard}, + inters: c.Interceptors(), + } +} + +// Get returns a AddonRateCard entity by its id. +func (c *AddonRateCardClient) Get(ctx context.Context, id string) (*AddonRateCard, error) { + return c.Query().Where(addonratecard.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AddonRateCardClient) GetX(ctx context.Context, id string) *AddonRateCard { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryAddon queries the addon edge of a AddonRateCard. +func (c *AddonRateCardClient) QueryAddon(_m *AddonRateCard) *AddonQuery { + query := (&AddonClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(addonratecard.Table, addonratecard.FieldID, id), + sqlgraph.To(addon.Table, addon.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, addonratecard.AddonTable, addonratecard.AddonColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryFeatures queries the features edge of a AddonRateCard. +func (c *AddonRateCardClient) QueryFeatures(_m *AddonRateCard) *FeatureQuery { + query := (&FeatureClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(addonratecard.Table, addonratecard.FieldID, id), + sqlgraph.To(dbfeature.Table, dbfeature.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, addonratecard.FeaturesTable, addonratecard.FeaturesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryTaxCode queries the tax_code edge of a AddonRateCard. +func (c *AddonRateCardClient) QueryTaxCode(_m *AddonRateCard) *TaxCodeQuery { + query := (&TaxCodeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(addonratecard.Table, addonratecard.FieldID, id), + sqlgraph.To(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, addonratecard.TaxCodeTable, addonratecard.TaxCodeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AddonRateCardClient) Hooks() []Hook { + return c.hooks.AddonRateCard +} + +// Interceptors returns the client interceptors. +func (c *AddonRateCardClient) Interceptors() []Interceptor { + return c.inters.AddonRateCard +} + +func (c *AddonRateCardClient) mutate(ctx context.Context, m *AddonRateCardMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AddonRateCardCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AddonRateCardUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AddonRateCardUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AddonRateCardDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown AddonRateCard mutation op: %q", m.Op()) + } +} + +// AppClient is a client for the App schema. +type AppClient struct { + config +} + +// NewAppClient returns a client for the App from the given config. +func NewAppClient(c config) *AppClient { + return &AppClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `dbapp.Hooks(f(g(h())))`. +func (c *AppClient) Use(hooks ...Hook) { + c.hooks.App = append(c.hooks.App, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `dbapp.Intercept(f(g(h())))`. +func (c *AppClient) Intercept(interceptors ...Interceptor) { + c.inters.App = append(c.inters.App, interceptors...) +} + +// Create returns a builder for creating a App entity. +func (c *AppClient) Create() *AppCreate { + mutation := newAppMutation(c.config, OpCreate) + return &AppCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of App entities. +func (c *AppClient) CreateBulk(builders ...*AppCreate) *AppCreateBulk { + return &AppCreateBulk{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 *AppClient) MapCreateBulk(slice any, setFunc func(*AppCreate, int)) *AppCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AppCreateBulk{err: fmt.Errorf("calling to AppClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AppCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AppCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for App. +func (c *AppClient) Update() *AppUpdate { + mutation := newAppMutation(c.config, OpUpdate) + return &AppUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AppClient) UpdateOne(_m *App) *AppUpdateOne { + mutation := newAppMutation(c.config, OpUpdateOne, withApp(_m)) + return &AppUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AppClient) UpdateOneID(id string) *AppUpdateOne { + mutation := newAppMutation(c.config, OpUpdateOne, withAppID(id)) + return &AppUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for App. +func (c *AppClient) Delete() *AppDelete { + mutation := newAppMutation(c.config, OpDelete) + return &AppDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AppClient) DeleteOne(_m *App) *AppDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AppClient) DeleteOneID(id string) *AppDeleteOne { + builder := c.Delete().Where(dbapp.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AppDeleteOne{builder} +} + +// Query returns a query builder for App. +func (c *AppClient) Query() *AppQuery { + return &AppQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeApp}, + inters: c.Interceptors(), + } +} + +// Get returns a App entity by its id. +func (c *AppClient) Get(ctx context.Context, id string) (*App, error) { + return c.Query().Where(dbapp.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AppClient) GetX(ctx context.Context, id string) *App { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryCustomerApps queries the customer_apps edge of a App. +func (c *AppClient) QueryCustomerApps(_m *App) *AppCustomerQuery { + query := (&AppCustomerClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbapp.Table, dbapp.FieldID, id), + sqlgraph.To(appcustomer.Table, appcustomer.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbapp.CustomerAppsTable, dbapp.CustomerAppsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingProfileTaxApp queries the billing_profile_tax_app edge of a App. +func (c *AppClient) QueryBillingProfileTaxApp(_m *App) *BillingProfileQuery { + query := (&BillingProfileClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbapp.Table, dbapp.FieldID, id), + sqlgraph.To(billingprofile.Table, billingprofile.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbapp.BillingProfileTaxAppTable, dbapp.BillingProfileTaxAppColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingProfileInvoicingApp queries the billing_profile_invoicing_app edge of a App. +func (c *AppClient) QueryBillingProfileInvoicingApp(_m *App) *BillingProfileQuery { + query := (&BillingProfileClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbapp.Table, dbapp.FieldID, id), + sqlgraph.To(billingprofile.Table, billingprofile.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbapp.BillingProfileInvoicingAppTable, dbapp.BillingProfileInvoicingAppColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingProfilePaymentApp queries the billing_profile_payment_app edge of a App. +func (c *AppClient) QueryBillingProfilePaymentApp(_m *App) *BillingProfileQuery { + query := (&BillingProfileClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbapp.Table, dbapp.FieldID, id), + sqlgraph.To(billingprofile.Table, billingprofile.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbapp.BillingProfilePaymentAppTable, dbapp.BillingProfilePaymentAppColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingInvoiceTaxApp queries the billing_invoice_tax_app edge of a App. +func (c *AppClient) QueryBillingInvoiceTaxApp(_m *App) *BillingInvoiceQuery { + query := (&BillingInvoiceClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbapp.Table, dbapp.FieldID, id), + sqlgraph.To(billinginvoice.Table, billinginvoice.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbapp.BillingInvoiceTaxAppTable, dbapp.BillingInvoiceTaxAppColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingInvoiceInvoicingApp queries the billing_invoice_invoicing_app edge of a App. +func (c *AppClient) QueryBillingInvoiceInvoicingApp(_m *App) *BillingInvoiceQuery { + query := (&BillingInvoiceClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbapp.Table, dbapp.FieldID, id), + sqlgraph.To(billinginvoice.Table, billinginvoice.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbapp.BillingInvoiceInvoicingAppTable, dbapp.BillingInvoiceInvoicingAppColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingInvoicePaymentApp queries the billing_invoice_payment_app edge of a App. +func (c *AppClient) QueryBillingInvoicePaymentApp(_m *App) *BillingInvoiceQuery { + query := (&BillingInvoiceClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbapp.Table, dbapp.FieldID, id), + sqlgraph.To(billinginvoice.Table, billinginvoice.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbapp.BillingInvoicePaymentAppTable, dbapp.BillingInvoicePaymentAppColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AppClient) Hooks() []Hook { + return c.hooks.App +} + +// Interceptors returns the client interceptors. +func (c *AppClient) Interceptors() []Interceptor { + return c.inters.App +} + +func (c *AppClient) mutate(ctx context.Context, m *AppMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AppCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AppUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AppUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AppDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown App mutation op: %q", m.Op()) + } +} + +// AppCustomInvoicingClient is a client for the AppCustomInvoicing schema. +type AppCustomInvoicingClient struct { + config +} + +// NewAppCustomInvoicingClient returns a client for the AppCustomInvoicing from the given config. +func NewAppCustomInvoicingClient(c config) *AppCustomInvoicingClient { + return &AppCustomInvoicingClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `appcustominvoicing.Hooks(f(g(h())))`. +func (c *AppCustomInvoicingClient) Use(hooks ...Hook) { + c.hooks.AppCustomInvoicing = append(c.hooks.AppCustomInvoicing, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `appcustominvoicing.Intercept(f(g(h())))`. +func (c *AppCustomInvoicingClient) Intercept(interceptors ...Interceptor) { + c.inters.AppCustomInvoicing = append(c.inters.AppCustomInvoicing, interceptors...) +} + +// Create returns a builder for creating a AppCustomInvoicing entity. +func (c *AppCustomInvoicingClient) Create() *AppCustomInvoicingCreate { + mutation := newAppCustomInvoicingMutation(c.config, OpCreate) + return &AppCustomInvoicingCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of AppCustomInvoicing entities. +func (c *AppCustomInvoicingClient) CreateBulk(builders ...*AppCustomInvoicingCreate) *AppCustomInvoicingCreateBulk { + return &AppCustomInvoicingCreateBulk{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 *AppCustomInvoicingClient) MapCreateBulk(slice any, setFunc func(*AppCustomInvoicingCreate, int)) *AppCustomInvoicingCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AppCustomInvoicingCreateBulk{err: fmt.Errorf("calling to AppCustomInvoicingClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AppCustomInvoicingCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AppCustomInvoicingCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for AppCustomInvoicing. +func (c *AppCustomInvoicingClient) Update() *AppCustomInvoicingUpdate { + mutation := newAppCustomInvoicingMutation(c.config, OpUpdate) + return &AppCustomInvoicingUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AppCustomInvoicingClient) UpdateOne(_m *AppCustomInvoicing) *AppCustomInvoicingUpdateOne { + mutation := newAppCustomInvoicingMutation(c.config, OpUpdateOne, withAppCustomInvoicing(_m)) + return &AppCustomInvoicingUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AppCustomInvoicingClient) UpdateOneID(id string) *AppCustomInvoicingUpdateOne { + mutation := newAppCustomInvoicingMutation(c.config, OpUpdateOne, withAppCustomInvoicingID(id)) + return &AppCustomInvoicingUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for AppCustomInvoicing. +func (c *AppCustomInvoicingClient) Delete() *AppCustomInvoicingDelete { + mutation := newAppCustomInvoicingMutation(c.config, OpDelete) + return &AppCustomInvoicingDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AppCustomInvoicingClient) DeleteOne(_m *AppCustomInvoicing) *AppCustomInvoicingDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AppCustomInvoicingClient) DeleteOneID(id string) *AppCustomInvoicingDeleteOne { + builder := c.Delete().Where(appcustominvoicing.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AppCustomInvoicingDeleteOne{builder} +} + +// Query returns a query builder for AppCustomInvoicing. +func (c *AppCustomInvoicingClient) Query() *AppCustomInvoicingQuery { + return &AppCustomInvoicingQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAppCustomInvoicing}, + inters: c.Interceptors(), + } +} + +// Get returns a AppCustomInvoicing entity by its id. +func (c *AppCustomInvoicingClient) Get(ctx context.Context, id string) (*AppCustomInvoicing, error) { + return c.Query().Where(appcustominvoicing.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AppCustomInvoicingClient) GetX(ctx context.Context, id string) *AppCustomInvoicing { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryCustomerApps queries the customer_apps edge of a AppCustomInvoicing. +func (c *AppCustomInvoicingClient) QueryCustomerApps(_m *AppCustomInvoicing) *AppCustomInvoicingCustomerQuery { + query := (&AppCustomInvoicingCustomerClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(appcustominvoicing.Table, appcustominvoicing.FieldID, id), + sqlgraph.To(appcustominvoicingcustomer.Table, appcustominvoicingcustomer.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, appcustominvoicing.CustomerAppsTable, appcustominvoicing.CustomerAppsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryApp queries the app edge of a AppCustomInvoicing. +func (c *AppCustomInvoicingClient) QueryApp(_m *AppCustomInvoicing) *AppQuery { + query := (&AppClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(appcustominvoicing.Table, appcustominvoicing.FieldID, id), + sqlgraph.To(dbapp.Table, dbapp.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, appcustominvoicing.AppTable, appcustominvoicing.AppColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AppCustomInvoicingClient) Hooks() []Hook { + return c.hooks.AppCustomInvoicing +} + +// Interceptors returns the client interceptors. +func (c *AppCustomInvoicingClient) Interceptors() []Interceptor { + return c.inters.AppCustomInvoicing +} + +func (c *AppCustomInvoicingClient) mutate(ctx context.Context, m *AppCustomInvoicingMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AppCustomInvoicingCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AppCustomInvoicingUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AppCustomInvoicingUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AppCustomInvoicingDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown AppCustomInvoicing mutation op: %q", m.Op()) + } +} + +// AppCustomInvoicingCustomerClient is a client for the AppCustomInvoicingCustomer schema. +type AppCustomInvoicingCustomerClient struct { + config +} + +// NewAppCustomInvoicingCustomerClient returns a client for the AppCustomInvoicingCustomer from the given config. +func NewAppCustomInvoicingCustomerClient(c config) *AppCustomInvoicingCustomerClient { + return &AppCustomInvoicingCustomerClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `appcustominvoicingcustomer.Hooks(f(g(h())))`. +func (c *AppCustomInvoicingCustomerClient) Use(hooks ...Hook) { + c.hooks.AppCustomInvoicingCustomer = append(c.hooks.AppCustomInvoicingCustomer, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `appcustominvoicingcustomer.Intercept(f(g(h())))`. +func (c *AppCustomInvoicingCustomerClient) Intercept(interceptors ...Interceptor) { + c.inters.AppCustomInvoicingCustomer = append(c.inters.AppCustomInvoicingCustomer, interceptors...) +} + +// Create returns a builder for creating a AppCustomInvoicingCustomer entity. +func (c *AppCustomInvoicingCustomerClient) Create() *AppCustomInvoicingCustomerCreate { + mutation := newAppCustomInvoicingCustomerMutation(c.config, OpCreate) + return &AppCustomInvoicingCustomerCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of AppCustomInvoicingCustomer entities. +func (c *AppCustomInvoicingCustomerClient) CreateBulk(builders ...*AppCustomInvoicingCustomerCreate) *AppCustomInvoicingCustomerCreateBulk { + return &AppCustomInvoicingCustomerCreateBulk{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 *AppCustomInvoicingCustomerClient) MapCreateBulk(slice any, setFunc func(*AppCustomInvoicingCustomerCreate, int)) *AppCustomInvoicingCustomerCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AppCustomInvoicingCustomerCreateBulk{err: fmt.Errorf("calling to AppCustomInvoicingCustomerClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AppCustomInvoicingCustomerCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AppCustomInvoicingCustomerCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for AppCustomInvoicingCustomer. +func (c *AppCustomInvoicingCustomerClient) Update() *AppCustomInvoicingCustomerUpdate { + mutation := newAppCustomInvoicingCustomerMutation(c.config, OpUpdate) + return &AppCustomInvoicingCustomerUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AppCustomInvoicingCustomerClient) UpdateOne(_m *AppCustomInvoicingCustomer) *AppCustomInvoicingCustomerUpdateOne { + mutation := newAppCustomInvoicingCustomerMutation(c.config, OpUpdateOne, withAppCustomInvoicingCustomer(_m)) + return &AppCustomInvoicingCustomerUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AppCustomInvoicingCustomerClient) UpdateOneID(id int) *AppCustomInvoicingCustomerUpdateOne { + mutation := newAppCustomInvoicingCustomerMutation(c.config, OpUpdateOne, withAppCustomInvoicingCustomerID(id)) + return &AppCustomInvoicingCustomerUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for AppCustomInvoicingCustomer. +func (c *AppCustomInvoicingCustomerClient) Delete() *AppCustomInvoicingCustomerDelete { + mutation := newAppCustomInvoicingCustomerMutation(c.config, OpDelete) + return &AppCustomInvoicingCustomerDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AppCustomInvoicingCustomerClient) DeleteOne(_m *AppCustomInvoicingCustomer) *AppCustomInvoicingCustomerDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AppCustomInvoicingCustomerClient) DeleteOneID(id int) *AppCustomInvoicingCustomerDeleteOne { + builder := c.Delete().Where(appcustominvoicingcustomer.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AppCustomInvoicingCustomerDeleteOne{builder} +} + +// Query returns a query builder for AppCustomInvoicingCustomer. +func (c *AppCustomInvoicingCustomerClient) Query() *AppCustomInvoicingCustomerQuery { + return &AppCustomInvoicingCustomerQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAppCustomInvoicingCustomer}, + inters: c.Interceptors(), + } +} + +// Get returns a AppCustomInvoicingCustomer entity by its id. +func (c *AppCustomInvoicingCustomerClient) Get(ctx context.Context, id int) (*AppCustomInvoicingCustomer, error) { + return c.Query().Where(appcustominvoicingcustomer.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AppCustomInvoicingCustomerClient) GetX(ctx context.Context, id int) *AppCustomInvoicingCustomer { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryCustomInvoicingApp queries the custom_invoicing_app edge of a AppCustomInvoicingCustomer. +func (c *AppCustomInvoicingCustomerClient) QueryCustomInvoicingApp(_m *AppCustomInvoicingCustomer) *AppCustomInvoicingQuery { + query := (&AppCustomInvoicingClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(appcustominvoicingcustomer.Table, appcustominvoicingcustomer.FieldID, id), + sqlgraph.To(appcustominvoicing.Table, appcustominvoicing.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, appcustominvoicingcustomer.CustomInvoicingAppTable, appcustominvoicingcustomer.CustomInvoicingAppColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCustomer queries the customer edge of a AppCustomInvoicingCustomer. +func (c *AppCustomInvoicingCustomerClient) QueryCustomer(_m *AppCustomInvoicingCustomer) *CustomerQuery { + query := (&CustomerClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(appcustominvoicingcustomer.Table, appcustominvoicingcustomer.FieldID, id), + sqlgraph.To(customer.Table, customer.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, appcustominvoicingcustomer.CustomerTable, appcustominvoicingcustomer.CustomerColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AppCustomInvoicingCustomerClient) Hooks() []Hook { + return c.hooks.AppCustomInvoicingCustomer +} + +// Interceptors returns the client interceptors. +func (c *AppCustomInvoicingCustomerClient) Interceptors() []Interceptor { + return c.inters.AppCustomInvoicingCustomer +} + +func (c *AppCustomInvoicingCustomerClient) mutate(ctx context.Context, m *AppCustomInvoicingCustomerMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AppCustomInvoicingCustomerCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AppCustomInvoicingCustomerUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AppCustomInvoicingCustomerUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AppCustomInvoicingCustomerDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown AppCustomInvoicingCustomer mutation op: %q", m.Op()) + } +} + +// AppCustomerClient is a client for the AppCustomer schema. +type AppCustomerClient struct { + config +} + +// NewAppCustomerClient returns a client for the AppCustomer from the given config. +func NewAppCustomerClient(c config) *AppCustomerClient { + return &AppCustomerClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `appcustomer.Hooks(f(g(h())))`. +func (c *AppCustomerClient) Use(hooks ...Hook) { + c.hooks.AppCustomer = append(c.hooks.AppCustomer, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `appcustomer.Intercept(f(g(h())))`. +func (c *AppCustomerClient) Intercept(interceptors ...Interceptor) { + c.inters.AppCustomer = append(c.inters.AppCustomer, interceptors...) +} + +// Create returns a builder for creating a AppCustomer entity. +func (c *AppCustomerClient) Create() *AppCustomerCreate { + mutation := newAppCustomerMutation(c.config, OpCreate) + return &AppCustomerCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of AppCustomer entities. +func (c *AppCustomerClient) CreateBulk(builders ...*AppCustomerCreate) *AppCustomerCreateBulk { + return &AppCustomerCreateBulk{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 *AppCustomerClient) MapCreateBulk(slice any, setFunc func(*AppCustomerCreate, int)) *AppCustomerCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AppCustomerCreateBulk{err: fmt.Errorf("calling to AppCustomerClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AppCustomerCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AppCustomerCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for AppCustomer. +func (c *AppCustomerClient) Update() *AppCustomerUpdate { + mutation := newAppCustomerMutation(c.config, OpUpdate) + return &AppCustomerUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AppCustomerClient) UpdateOne(_m *AppCustomer) *AppCustomerUpdateOne { + mutation := newAppCustomerMutation(c.config, OpUpdateOne, withAppCustomer(_m)) + return &AppCustomerUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AppCustomerClient) UpdateOneID(id int) *AppCustomerUpdateOne { + mutation := newAppCustomerMutation(c.config, OpUpdateOne, withAppCustomerID(id)) + return &AppCustomerUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for AppCustomer. +func (c *AppCustomerClient) Delete() *AppCustomerDelete { + mutation := newAppCustomerMutation(c.config, OpDelete) + return &AppCustomerDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AppCustomerClient) DeleteOne(_m *AppCustomer) *AppCustomerDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AppCustomerClient) DeleteOneID(id int) *AppCustomerDeleteOne { + builder := c.Delete().Where(appcustomer.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AppCustomerDeleteOne{builder} +} + +// Query returns a query builder for AppCustomer. +func (c *AppCustomerClient) Query() *AppCustomerQuery { + return &AppCustomerQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAppCustomer}, + inters: c.Interceptors(), + } +} + +// Get returns a AppCustomer entity by its id. +func (c *AppCustomerClient) Get(ctx context.Context, id int) (*AppCustomer, error) { + return c.Query().Where(appcustomer.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AppCustomerClient) GetX(ctx context.Context, id int) *AppCustomer { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryApp queries the app edge of a AppCustomer. +func (c *AppCustomerClient) QueryApp(_m *AppCustomer) *AppQuery { + query := (&AppClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(appcustomer.Table, appcustomer.FieldID, id), + sqlgraph.To(dbapp.Table, dbapp.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, appcustomer.AppTable, appcustomer.AppColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCustomer queries the customer edge of a AppCustomer. +func (c *AppCustomerClient) QueryCustomer(_m *AppCustomer) *CustomerQuery { + query := (&CustomerClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(appcustomer.Table, appcustomer.FieldID, id), + sqlgraph.To(customer.Table, customer.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, appcustomer.CustomerTable, appcustomer.CustomerColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AppCustomerClient) Hooks() []Hook { + return c.hooks.AppCustomer +} + +// Interceptors returns the client interceptors. +func (c *AppCustomerClient) Interceptors() []Interceptor { + return c.inters.AppCustomer +} + +func (c *AppCustomerClient) mutate(ctx context.Context, m *AppCustomerMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AppCustomerCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AppCustomerUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AppCustomerUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AppCustomerDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown AppCustomer mutation op: %q", m.Op()) + } +} + +// AppStripeClient is a client for the AppStripe schema. +type AppStripeClient struct { + config +} + +// NewAppStripeClient returns a client for the AppStripe from the given config. +func NewAppStripeClient(c config) *AppStripeClient { + return &AppStripeClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `appstripe.Hooks(f(g(h())))`. +func (c *AppStripeClient) Use(hooks ...Hook) { + c.hooks.AppStripe = append(c.hooks.AppStripe, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `appstripe.Intercept(f(g(h())))`. +func (c *AppStripeClient) Intercept(interceptors ...Interceptor) { + c.inters.AppStripe = append(c.inters.AppStripe, interceptors...) +} + +// Create returns a builder for creating a AppStripe entity. +func (c *AppStripeClient) Create() *AppStripeCreate { + mutation := newAppStripeMutation(c.config, OpCreate) + return &AppStripeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of AppStripe entities. +func (c *AppStripeClient) CreateBulk(builders ...*AppStripeCreate) *AppStripeCreateBulk { + return &AppStripeCreateBulk{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 *AppStripeClient) MapCreateBulk(slice any, setFunc func(*AppStripeCreate, int)) *AppStripeCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AppStripeCreateBulk{err: fmt.Errorf("calling to AppStripeClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AppStripeCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AppStripeCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for AppStripe. +func (c *AppStripeClient) Update() *AppStripeUpdate { + mutation := newAppStripeMutation(c.config, OpUpdate) + return &AppStripeUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AppStripeClient) UpdateOne(_m *AppStripe) *AppStripeUpdateOne { + mutation := newAppStripeMutation(c.config, OpUpdateOne, withAppStripe(_m)) + return &AppStripeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AppStripeClient) UpdateOneID(id string) *AppStripeUpdateOne { + mutation := newAppStripeMutation(c.config, OpUpdateOne, withAppStripeID(id)) + return &AppStripeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for AppStripe. +func (c *AppStripeClient) Delete() *AppStripeDelete { + mutation := newAppStripeMutation(c.config, OpDelete) + return &AppStripeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AppStripeClient) DeleteOne(_m *AppStripe) *AppStripeDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AppStripeClient) DeleteOneID(id string) *AppStripeDeleteOne { + builder := c.Delete().Where(appstripe.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AppStripeDeleteOne{builder} +} + +// Query returns a query builder for AppStripe. +func (c *AppStripeClient) Query() *AppStripeQuery { + return &AppStripeQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAppStripe}, + inters: c.Interceptors(), + } +} + +// Get returns a AppStripe entity by its id. +func (c *AppStripeClient) Get(ctx context.Context, id string) (*AppStripe, error) { + return c.Query().Where(appstripe.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AppStripeClient) GetX(ctx context.Context, id string) *AppStripe { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryCustomerApps queries the customer_apps edge of a AppStripe. +func (c *AppStripeClient) QueryCustomerApps(_m *AppStripe) *AppStripeCustomerQuery { + query := (&AppStripeCustomerClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(appstripe.Table, appstripe.FieldID, id), + sqlgraph.To(appstripecustomer.Table, appstripecustomer.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, appstripe.CustomerAppsTable, appstripe.CustomerAppsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryApp queries the app edge of a AppStripe. +func (c *AppStripeClient) QueryApp(_m *AppStripe) *AppQuery { + query := (&AppClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(appstripe.Table, appstripe.FieldID, id), + sqlgraph.To(dbapp.Table, dbapp.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, appstripe.AppTable, appstripe.AppColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AppStripeClient) Hooks() []Hook { + return c.hooks.AppStripe +} + +// Interceptors returns the client interceptors. +func (c *AppStripeClient) Interceptors() []Interceptor { + return c.inters.AppStripe +} + +func (c *AppStripeClient) mutate(ctx context.Context, m *AppStripeMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AppStripeCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AppStripeUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AppStripeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AppStripeDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown AppStripe mutation op: %q", m.Op()) + } +} + +// AppStripeCustomerClient is a client for the AppStripeCustomer schema. +type AppStripeCustomerClient struct { + config +} + +// NewAppStripeCustomerClient returns a client for the AppStripeCustomer from the given config. +func NewAppStripeCustomerClient(c config) *AppStripeCustomerClient { + return &AppStripeCustomerClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `appstripecustomer.Hooks(f(g(h())))`. +func (c *AppStripeCustomerClient) Use(hooks ...Hook) { + c.hooks.AppStripeCustomer = append(c.hooks.AppStripeCustomer, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `appstripecustomer.Intercept(f(g(h())))`. +func (c *AppStripeCustomerClient) Intercept(interceptors ...Interceptor) { + c.inters.AppStripeCustomer = append(c.inters.AppStripeCustomer, interceptors...) +} + +// Create returns a builder for creating a AppStripeCustomer entity. +func (c *AppStripeCustomerClient) Create() *AppStripeCustomerCreate { + mutation := newAppStripeCustomerMutation(c.config, OpCreate) + return &AppStripeCustomerCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of AppStripeCustomer entities. +func (c *AppStripeCustomerClient) CreateBulk(builders ...*AppStripeCustomerCreate) *AppStripeCustomerCreateBulk { + return &AppStripeCustomerCreateBulk{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 *AppStripeCustomerClient) MapCreateBulk(slice any, setFunc func(*AppStripeCustomerCreate, int)) *AppStripeCustomerCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AppStripeCustomerCreateBulk{err: fmt.Errorf("calling to AppStripeCustomerClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AppStripeCustomerCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AppStripeCustomerCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for AppStripeCustomer. +func (c *AppStripeCustomerClient) Update() *AppStripeCustomerUpdate { + mutation := newAppStripeCustomerMutation(c.config, OpUpdate) + return &AppStripeCustomerUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AppStripeCustomerClient) UpdateOne(_m *AppStripeCustomer) *AppStripeCustomerUpdateOne { + mutation := newAppStripeCustomerMutation(c.config, OpUpdateOne, withAppStripeCustomer(_m)) + return &AppStripeCustomerUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AppStripeCustomerClient) UpdateOneID(id int) *AppStripeCustomerUpdateOne { + mutation := newAppStripeCustomerMutation(c.config, OpUpdateOne, withAppStripeCustomerID(id)) + return &AppStripeCustomerUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for AppStripeCustomer. +func (c *AppStripeCustomerClient) Delete() *AppStripeCustomerDelete { + mutation := newAppStripeCustomerMutation(c.config, OpDelete) + return &AppStripeCustomerDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AppStripeCustomerClient) DeleteOne(_m *AppStripeCustomer) *AppStripeCustomerDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AppStripeCustomerClient) DeleteOneID(id int) *AppStripeCustomerDeleteOne { + builder := c.Delete().Where(appstripecustomer.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AppStripeCustomerDeleteOne{builder} +} + +// Query returns a query builder for AppStripeCustomer. +func (c *AppStripeCustomerClient) Query() *AppStripeCustomerQuery { + return &AppStripeCustomerQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAppStripeCustomer}, + inters: c.Interceptors(), + } +} + +// Get returns a AppStripeCustomer entity by its id. +func (c *AppStripeCustomerClient) Get(ctx context.Context, id int) (*AppStripeCustomer, error) { + return c.Query().Where(appstripecustomer.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AppStripeCustomerClient) GetX(ctx context.Context, id int) *AppStripeCustomer { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryStripeApp queries the stripe_app edge of a AppStripeCustomer. +func (c *AppStripeCustomerClient) QueryStripeApp(_m *AppStripeCustomer) *AppStripeQuery { + query := (&AppStripeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(appstripecustomer.Table, appstripecustomer.FieldID, id), + sqlgraph.To(appstripe.Table, appstripe.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, appstripecustomer.StripeAppTable, appstripecustomer.StripeAppColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCustomer queries the customer edge of a AppStripeCustomer. +func (c *AppStripeCustomerClient) QueryCustomer(_m *AppStripeCustomer) *CustomerQuery { + query := (&CustomerClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(appstripecustomer.Table, appstripecustomer.FieldID, id), + sqlgraph.To(customer.Table, customer.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, appstripecustomer.CustomerTable, appstripecustomer.CustomerColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AppStripeCustomerClient) Hooks() []Hook { + return c.hooks.AppStripeCustomer +} + +// Interceptors returns the client interceptors. +func (c *AppStripeCustomerClient) Interceptors() []Interceptor { + return c.inters.AppStripeCustomer +} + +func (c *AppStripeCustomerClient) mutate(ctx context.Context, m *AppStripeCustomerMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AppStripeCustomerCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AppStripeCustomerUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AppStripeCustomerUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AppStripeCustomerDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown AppStripeCustomer mutation op: %q", m.Op()) + } +} + +// BalanceSnapshotClient is a client for the BalanceSnapshot schema. +type BalanceSnapshotClient struct { + config +} + +// NewBalanceSnapshotClient returns a client for the BalanceSnapshot from the given config. +func NewBalanceSnapshotClient(c config) *BalanceSnapshotClient { + return &BalanceSnapshotClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `balancesnapshot.Hooks(f(g(h())))`. +func (c *BalanceSnapshotClient) Use(hooks ...Hook) { + c.hooks.BalanceSnapshot = append(c.hooks.BalanceSnapshot, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `balancesnapshot.Intercept(f(g(h())))`. +func (c *BalanceSnapshotClient) Intercept(interceptors ...Interceptor) { + c.inters.BalanceSnapshot = append(c.inters.BalanceSnapshot, interceptors...) +} + +// Create returns a builder for creating a BalanceSnapshot entity. +func (c *BalanceSnapshotClient) Create() *BalanceSnapshotCreate { + mutation := newBalanceSnapshotMutation(c.config, OpCreate) + return &BalanceSnapshotCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of BalanceSnapshot entities. +func (c *BalanceSnapshotClient) CreateBulk(builders ...*BalanceSnapshotCreate) *BalanceSnapshotCreateBulk { + return &BalanceSnapshotCreateBulk{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 *BalanceSnapshotClient) MapCreateBulk(slice any, setFunc func(*BalanceSnapshotCreate, int)) *BalanceSnapshotCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &BalanceSnapshotCreateBulk{err: fmt.Errorf("calling to BalanceSnapshotClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*BalanceSnapshotCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &BalanceSnapshotCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for BalanceSnapshot. +func (c *BalanceSnapshotClient) Update() *BalanceSnapshotUpdate { + mutation := newBalanceSnapshotMutation(c.config, OpUpdate) + return &BalanceSnapshotUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BalanceSnapshotClient) UpdateOne(_m *BalanceSnapshot) *BalanceSnapshotUpdateOne { + mutation := newBalanceSnapshotMutation(c.config, OpUpdateOne, withBalanceSnapshot(_m)) + return &BalanceSnapshotUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BalanceSnapshotClient) UpdateOneID(id int) *BalanceSnapshotUpdateOne { + mutation := newBalanceSnapshotMutation(c.config, OpUpdateOne, withBalanceSnapshotID(id)) + return &BalanceSnapshotUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for BalanceSnapshot. +func (c *BalanceSnapshotClient) Delete() *BalanceSnapshotDelete { + mutation := newBalanceSnapshotMutation(c.config, OpDelete) + return &BalanceSnapshotDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BalanceSnapshotClient) DeleteOne(_m *BalanceSnapshot) *BalanceSnapshotDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *BalanceSnapshotClient) DeleteOneID(id int) *BalanceSnapshotDeleteOne { + builder := c.Delete().Where(balancesnapshot.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BalanceSnapshotDeleteOne{builder} +} + +// Query returns a query builder for BalanceSnapshot. +func (c *BalanceSnapshotClient) Query() *BalanceSnapshotQuery { + return &BalanceSnapshotQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeBalanceSnapshot}, + inters: c.Interceptors(), + } +} + +// Get returns a BalanceSnapshot entity by its id. +func (c *BalanceSnapshotClient) Get(ctx context.Context, id int) (*BalanceSnapshot, error) { + return c.Query().Where(balancesnapshot.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BalanceSnapshotClient) GetX(ctx context.Context, id int) *BalanceSnapshot { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryEntitlement queries the entitlement edge of a BalanceSnapshot. +func (c *BalanceSnapshotClient) QueryEntitlement(_m *BalanceSnapshot) *EntitlementQuery { + query := (&EntitlementClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(balancesnapshot.Table, balancesnapshot.FieldID, id), + sqlgraph.To(entitlement.Table, entitlement.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, balancesnapshot.EntitlementTable, balancesnapshot.EntitlementColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *BalanceSnapshotClient) Hooks() []Hook { + return c.hooks.BalanceSnapshot +} + +// Interceptors returns the client interceptors. +func (c *BalanceSnapshotClient) Interceptors() []Interceptor { + return c.inters.BalanceSnapshot +} + +func (c *BalanceSnapshotClient) mutate(ctx context.Context, m *BalanceSnapshotMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&BalanceSnapshotCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&BalanceSnapshotUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&BalanceSnapshotUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&BalanceSnapshotDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown BalanceSnapshot mutation op: %q", m.Op()) + } +} + +// BillingCustomerLockClient is a client for the BillingCustomerLock schema. +type BillingCustomerLockClient struct { + config +} + +// NewBillingCustomerLockClient returns a client for the BillingCustomerLock from the given config. +func NewBillingCustomerLockClient(c config) *BillingCustomerLockClient { + return &BillingCustomerLockClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `billingcustomerlock.Hooks(f(g(h())))`. +func (c *BillingCustomerLockClient) Use(hooks ...Hook) { + c.hooks.BillingCustomerLock = append(c.hooks.BillingCustomerLock, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `billingcustomerlock.Intercept(f(g(h())))`. +func (c *BillingCustomerLockClient) Intercept(interceptors ...Interceptor) { + c.inters.BillingCustomerLock = append(c.inters.BillingCustomerLock, interceptors...) +} + +// Create returns a builder for creating a BillingCustomerLock entity. +func (c *BillingCustomerLockClient) Create() *BillingCustomerLockCreate { + mutation := newBillingCustomerLockMutation(c.config, OpCreate) + return &BillingCustomerLockCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of BillingCustomerLock entities. +func (c *BillingCustomerLockClient) CreateBulk(builders ...*BillingCustomerLockCreate) *BillingCustomerLockCreateBulk { + return &BillingCustomerLockCreateBulk{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 *BillingCustomerLockClient) MapCreateBulk(slice any, setFunc func(*BillingCustomerLockCreate, int)) *BillingCustomerLockCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &BillingCustomerLockCreateBulk{err: fmt.Errorf("calling to BillingCustomerLockClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*BillingCustomerLockCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &BillingCustomerLockCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for BillingCustomerLock. +func (c *BillingCustomerLockClient) Update() *BillingCustomerLockUpdate { + mutation := newBillingCustomerLockMutation(c.config, OpUpdate) + return &BillingCustomerLockUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BillingCustomerLockClient) UpdateOne(_m *BillingCustomerLock) *BillingCustomerLockUpdateOne { + mutation := newBillingCustomerLockMutation(c.config, OpUpdateOne, withBillingCustomerLock(_m)) + return &BillingCustomerLockUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BillingCustomerLockClient) UpdateOneID(id string) *BillingCustomerLockUpdateOne { + mutation := newBillingCustomerLockMutation(c.config, OpUpdateOne, withBillingCustomerLockID(id)) + return &BillingCustomerLockUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for BillingCustomerLock. +func (c *BillingCustomerLockClient) Delete() *BillingCustomerLockDelete { + mutation := newBillingCustomerLockMutation(c.config, OpDelete) + return &BillingCustomerLockDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BillingCustomerLockClient) DeleteOne(_m *BillingCustomerLock) *BillingCustomerLockDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *BillingCustomerLockClient) DeleteOneID(id string) *BillingCustomerLockDeleteOne { + builder := c.Delete().Where(billingcustomerlock.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BillingCustomerLockDeleteOne{builder} +} + +// Query returns a query builder for BillingCustomerLock. +func (c *BillingCustomerLockClient) Query() *BillingCustomerLockQuery { + return &BillingCustomerLockQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeBillingCustomerLock}, + inters: c.Interceptors(), + } +} + +// Get returns a BillingCustomerLock entity by its id. +func (c *BillingCustomerLockClient) Get(ctx context.Context, id string) (*BillingCustomerLock, error) { + return c.Query().Where(billingcustomerlock.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BillingCustomerLockClient) GetX(ctx context.Context, id string) *BillingCustomerLock { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *BillingCustomerLockClient) Hooks() []Hook { + return c.hooks.BillingCustomerLock +} + +// Interceptors returns the client interceptors. +func (c *BillingCustomerLockClient) Interceptors() []Interceptor { + return c.inters.BillingCustomerLock +} + +func (c *BillingCustomerLockClient) mutate(ctx context.Context, m *BillingCustomerLockMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&BillingCustomerLockCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&BillingCustomerLockUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&BillingCustomerLockUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&BillingCustomerLockDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown BillingCustomerLock mutation op: %q", m.Op()) + } +} + +// BillingCustomerOverrideClient is a client for the BillingCustomerOverride schema. +type BillingCustomerOverrideClient struct { + config +} + +// NewBillingCustomerOverrideClient returns a client for the BillingCustomerOverride from the given config. +func NewBillingCustomerOverrideClient(c config) *BillingCustomerOverrideClient { + return &BillingCustomerOverrideClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `billingcustomeroverride.Hooks(f(g(h())))`. +func (c *BillingCustomerOverrideClient) Use(hooks ...Hook) { + c.hooks.BillingCustomerOverride = append(c.hooks.BillingCustomerOverride, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `billingcustomeroverride.Intercept(f(g(h())))`. +func (c *BillingCustomerOverrideClient) Intercept(interceptors ...Interceptor) { + c.inters.BillingCustomerOverride = append(c.inters.BillingCustomerOverride, interceptors...) +} + +// Create returns a builder for creating a BillingCustomerOverride entity. +func (c *BillingCustomerOverrideClient) Create() *BillingCustomerOverrideCreate { + mutation := newBillingCustomerOverrideMutation(c.config, OpCreate) + return &BillingCustomerOverrideCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of BillingCustomerOverride entities. +func (c *BillingCustomerOverrideClient) CreateBulk(builders ...*BillingCustomerOverrideCreate) *BillingCustomerOverrideCreateBulk { + return &BillingCustomerOverrideCreateBulk{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 *BillingCustomerOverrideClient) MapCreateBulk(slice any, setFunc func(*BillingCustomerOverrideCreate, int)) *BillingCustomerOverrideCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &BillingCustomerOverrideCreateBulk{err: fmt.Errorf("calling to BillingCustomerOverrideClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*BillingCustomerOverrideCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &BillingCustomerOverrideCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for BillingCustomerOverride. +func (c *BillingCustomerOverrideClient) Update() *BillingCustomerOverrideUpdate { + mutation := newBillingCustomerOverrideMutation(c.config, OpUpdate) + return &BillingCustomerOverrideUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BillingCustomerOverrideClient) UpdateOne(_m *BillingCustomerOverride) *BillingCustomerOverrideUpdateOne { + mutation := newBillingCustomerOverrideMutation(c.config, OpUpdateOne, withBillingCustomerOverride(_m)) + return &BillingCustomerOverrideUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BillingCustomerOverrideClient) UpdateOneID(id string) *BillingCustomerOverrideUpdateOne { + mutation := newBillingCustomerOverrideMutation(c.config, OpUpdateOne, withBillingCustomerOverrideID(id)) + return &BillingCustomerOverrideUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for BillingCustomerOverride. +func (c *BillingCustomerOverrideClient) Delete() *BillingCustomerOverrideDelete { + mutation := newBillingCustomerOverrideMutation(c.config, OpDelete) + return &BillingCustomerOverrideDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BillingCustomerOverrideClient) DeleteOne(_m *BillingCustomerOverride) *BillingCustomerOverrideDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *BillingCustomerOverrideClient) DeleteOneID(id string) *BillingCustomerOverrideDeleteOne { + builder := c.Delete().Where(billingcustomeroverride.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BillingCustomerOverrideDeleteOne{builder} +} + +// Query returns a query builder for BillingCustomerOverride. +func (c *BillingCustomerOverrideClient) Query() *BillingCustomerOverrideQuery { + return &BillingCustomerOverrideQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeBillingCustomerOverride}, + inters: c.Interceptors(), + } +} + +// Get returns a BillingCustomerOverride entity by its id. +func (c *BillingCustomerOverrideClient) Get(ctx context.Context, id string) (*BillingCustomerOverride, error) { + return c.Query().Where(billingcustomeroverride.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BillingCustomerOverrideClient) GetX(ctx context.Context, id string) *BillingCustomerOverride { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryCustomer queries the customer edge of a BillingCustomerOverride. +func (c *BillingCustomerOverrideClient) QueryCustomer(_m *BillingCustomerOverride) *CustomerQuery { + query := (&CustomerClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billingcustomeroverride.Table, billingcustomeroverride.FieldID, id), + sqlgraph.To(customer.Table, customer.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, billingcustomeroverride.CustomerTable, billingcustomeroverride.CustomerColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingProfile queries the billing_profile edge of a BillingCustomerOverride. +func (c *BillingCustomerOverrideClient) QueryBillingProfile(_m *BillingCustomerOverride) *BillingProfileQuery { + query := (&BillingProfileClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billingcustomeroverride.Table, billingcustomeroverride.FieldID, id), + sqlgraph.To(billingprofile.Table, billingprofile.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billingcustomeroverride.BillingProfileTable, billingcustomeroverride.BillingProfileColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryTaxCode queries the tax_code edge of a BillingCustomerOverride. +func (c *BillingCustomerOverrideClient) QueryTaxCode(_m *BillingCustomerOverride) *TaxCodeQuery { + query := (&TaxCodeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billingcustomeroverride.Table, billingcustomeroverride.FieldID, id), + sqlgraph.To(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billingcustomeroverride.TaxCodeTable, billingcustomeroverride.TaxCodeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *BillingCustomerOverrideClient) Hooks() []Hook { + return c.hooks.BillingCustomerOverride +} + +// Interceptors returns the client interceptors. +func (c *BillingCustomerOverrideClient) Interceptors() []Interceptor { + return c.inters.BillingCustomerOverride +} + +func (c *BillingCustomerOverrideClient) mutate(ctx context.Context, m *BillingCustomerOverrideMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&BillingCustomerOverrideCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&BillingCustomerOverrideUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&BillingCustomerOverrideUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&BillingCustomerOverrideDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown BillingCustomerOverride mutation op: %q", m.Op()) + } +} + +// BillingInvoiceClient is a client for the BillingInvoice schema. +type BillingInvoiceClient struct { + config +} + +// NewBillingInvoiceClient returns a client for the BillingInvoice from the given config. +func NewBillingInvoiceClient(c config) *BillingInvoiceClient { + return &BillingInvoiceClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `billinginvoice.Hooks(f(g(h())))`. +func (c *BillingInvoiceClient) Use(hooks ...Hook) { + c.hooks.BillingInvoice = append(c.hooks.BillingInvoice, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `billinginvoice.Intercept(f(g(h())))`. +func (c *BillingInvoiceClient) Intercept(interceptors ...Interceptor) { + c.inters.BillingInvoice = append(c.inters.BillingInvoice, interceptors...) +} + +// Create returns a builder for creating a BillingInvoice entity. +func (c *BillingInvoiceClient) Create() *BillingInvoiceCreate { + mutation := newBillingInvoiceMutation(c.config, OpCreate) + return &BillingInvoiceCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of BillingInvoice entities. +func (c *BillingInvoiceClient) CreateBulk(builders ...*BillingInvoiceCreate) *BillingInvoiceCreateBulk { + return &BillingInvoiceCreateBulk{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 *BillingInvoiceClient) MapCreateBulk(slice any, setFunc func(*BillingInvoiceCreate, int)) *BillingInvoiceCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &BillingInvoiceCreateBulk{err: fmt.Errorf("calling to BillingInvoiceClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*BillingInvoiceCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &BillingInvoiceCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for BillingInvoice. +func (c *BillingInvoiceClient) Update() *BillingInvoiceUpdate { + mutation := newBillingInvoiceMutation(c.config, OpUpdate) + return &BillingInvoiceUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BillingInvoiceClient) UpdateOne(_m *BillingInvoice) *BillingInvoiceUpdateOne { + mutation := newBillingInvoiceMutation(c.config, OpUpdateOne, withBillingInvoice(_m)) + return &BillingInvoiceUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BillingInvoiceClient) UpdateOneID(id string) *BillingInvoiceUpdateOne { + mutation := newBillingInvoiceMutation(c.config, OpUpdateOne, withBillingInvoiceID(id)) + return &BillingInvoiceUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for BillingInvoice. +func (c *BillingInvoiceClient) Delete() *BillingInvoiceDelete { + mutation := newBillingInvoiceMutation(c.config, OpDelete) + return &BillingInvoiceDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BillingInvoiceClient) DeleteOne(_m *BillingInvoice) *BillingInvoiceDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *BillingInvoiceClient) DeleteOneID(id string) *BillingInvoiceDeleteOne { + builder := c.Delete().Where(billinginvoice.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BillingInvoiceDeleteOne{builder} +} + +// Query returns a query builder for BillingInvoice. +func (c *BillingInvoiceClient) Query() *BillingInvoiceQuery { + return &BillingInvoiceQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeBillingInvoice}, + inters: c.Interceptors(), + } +} + +// Get returns a BillingInvoice entity by its id. +func (c *BillingInvoiceClient) Get(ctx context.Context, id string) (*BillingInvoice, error) { + return c.Query().Where(billinginvoice.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BillingInvoiceClient) GetX(ctx context.Context, id string) *BillingInvoice { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QuerySourceBillingProfile queries the source_billing_profile edge of a BillingInvoice. +func (c *BillingInvoiceClient) QuerySourceBillingProfile(_m *BillingInvoice) *BillingProfileQuery { + query := (&BillingProfileClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoice.Table, billinginvoice.FieldID, id), + sqlgraph.To(billingprofile.Table, billingprofile.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoice.SourceBillingProfileTable, billinginvoice.SourceBillingProfileColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingWorkflowConfig queries the billing_workflow_config edge of a BillingInvoice. +func (c *BillingInvoiceClient) QueryBillingWorkflowConfig(_m *BillingInvoice) *BillingWorkflowConfigQuery { + query := (&BillingWorkflowConfigClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoice.Table, billinginvoice.FieldID, id), + sqlgraph.To(billingworkflowconfig.Table, billingworkflowconfig.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, billinginvoice.BillingWorkflowConfigTable, billinginvoice.BillingWorkflowConfigColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingInvoiceLines queries the billing_invoice_lines edge of a BillingInvoice. +func (c *BillingInvoiceClient) QueryBillingInvoiceLines(_m *BillingInvoice) *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoice.Table, billinginvoice.FieldID, id), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, billinginvoice.BillingInvoiceLinesTable, billinginvoice.BillingInvoiceLinesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingInvoiceDetailedLines queries the billing_invoice_detailed_lines edge of a BillingInvoice. +func (c *BillingInvoiceClient) QueryBillingInvoiceDetailedLines(_m *BillingInvoice) *BillingStandardInvoiceDetailedLineQuery { + query := (&BillingStandardInvoiceDetailedLineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoice.Table, billinginvoice.FieldID, id), + sqlgraph.To(billingstandardinvoicedetailedline.Table, billingstandardinvoicedetailedline.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, billinginvoice.BillingInvoiceDetailedLinesTable, billinginvoice.BillingInvoiceDetailedLinesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingInvoiceValidationIssues queries the billing_invoice_validation_issues edge of a BillingInvoice. +func (c *BillingInvoiceClient) QueryBillingInvoiceValidationIssues(_m *BillingInvoice) *BillingInvoiceValidationIssueQuery { + query := (&BillingInvoiceValidationIssueClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoice.Table, billinginvoice.FieldID, id), + sqlgraph.To(billinginvoicevalidationissue.Table, billinginvoicevalidationissue.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, billinginvoice.BillingInvoiceValidationIssuesTable, billinginvoice.BillingInvoiceValidationIssuesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargeFlatFeeRuns queries the charge_flat_fee_runs edge of a BillingInvoice. +func (c *BillingInvoiceClient) QueryChargeFlatFeeRuns(_m *BillingInvoice) *ChargeFlatFeeRunQuery { + query := (&ChargeFlatFeeRunClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoice.Table, billinginvoice.FieldID, id), + sqlgraph.To(chargeflatfeerun.Table, chargeflatfeerun.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, billinginvoice.ChargeFlatFeeRunsTable, billinginvoice.ChargeFlatFeeRunsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargeUsageBasedRuns queries the charge_usage_based_runs edge of a BillingInvoice. +func (c *BillingInvoiceClient) QueryChargeUsageBasedRuns(_m *BillingInvoice) *ChargeUsageBasedRunsQuery { + query := (&ChargeUsageBasedRunsClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoice.Table, billinginvoice.FieldID, id), + sqlgraph.To(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, billinginvoice.ChargeUsageBasedRunsTable, billinginvoice.ChargeUsageBasedRunsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingInvoiceCustomer queries the billing_invoice_customer edge of a BillingInvoice. +func (c *BillingInvoiceClient) QueryBillingInvoiceCustomer(_m *BillingInvoice) *CustomerQuery { + query := (&CustomerClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoice.Table, billinginvoice.FieldID, id), + sqlgraph.To(customer.Table, customer.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoice.BillingInvoiceCustomerTable, billinginvoice.BillingInvoiceCustomerColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryTaxApp queries the tax_app edge of a BillingInvoice. +func (c *BillingInvoiceClient) QueryTaxApp(_m *BillingInvoice) *AppQuery { + query := (&AppClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoice.Table, billinginvoice.FieldID, id), + sqlgraph.To(dbapp.Table, dbapp.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoice.TaxAppTable, billinginvoice.TaxAppColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryInvoicingApp queries the invoicing_app edge of a BillingInvoice. +func (c *BillingInvoiceClient) QueryInvoicingApp(_m *BillingInvoice) *AppQuery { + query := (&AppClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoice.Table, billinginvoice.FieldID, id), + sqlgraph.To(dbapp.Table, dbapp.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoice.InvoicingAppTable, billinginvoice.InvoicingAppColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryPaymentApp queries the payment_app edge of a BillingInvoice. +func (c *BillingInvoiceClient) QueryPaymentApp(_m *BillingInvoice) *AppQuery { + query := (&AppClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoice.Table, billinginvoice.FieldID, id), + sqlgraph.To(dbapp.Table, dbapp.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoice.PaymentAppTable, billinginvoice.PaymentAppColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *BillingInvoiceClient) Hooks() []Hook { + return c.hooks.BillingInvoice +} + +// Interceptors returns the client interceptors. +func (c *BillingInvoiceClient) Interceptors() []Interceptor { + return c.inters.BillingInvoice +} + +func (c *BillingInvoiceClient) mutate(ctx context.Context, m *BillingInvoiceMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&BillingInvoiceCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&BillingInvoiceUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&BillingInvoiceUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&BillingInvoiceDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown BillingInvoice mutation op: %q", m.Op()) + } +} + +// BillingInvoiceFlatFeeLineConfigClient is a client for the BillingInvoiceFlatFeeLineConfig schema. +type BillingInvoiceFlatFeeLineConfigClient struct { + config +} + +// NewBillingInvoiceFlatFeeLineConfigClient returns a client for the BillingInvoiceFlatFeeLineConfig from the given config. +func NewBillingInvoiceFlatFeeLineConfigClient(c config) *BillingInvoiceFlatFeeLineConfigClient { + return &BillingInvoiceFlatFeeLineConfigClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `billinginvoiceflatfeelineconfig.Hooks(f(g(h())))`. +func (c *BillingInvoiceFlatFeeLineConfigClient) Use(hooks ...Hook) { + c.hooks.BillingInvoiceFlatFeeLineConfig = append(c.hooks.BillingInvoiceFlatFeeLineConfig, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `billinginvoiceflatfeelineconfig.Intercept(f(g(h())))`. +func (c *BillingInvoiceFlatFeeLineConfigClient) Intercept(interceptors ...Interceptor) { + c.inters.BillingInvoiceFlatFeeLineConfig = append(c.inters.BillingInvoiceFlatFeeLineConfig, interceptors...) +} + +// Create returns a builder for creating a BillingInvoiceFlatFeeLineConfig entity. +func (c *BillingInvoiceFlatFeeLineConfigClient) Create() *BillingInvoiceFlatFeeLineConfigCreate { + mutation := newBillingInvoiceFlatFeeLineConfigMutation(c.config, OpCreate) + return &BillingInvoiceFlatFeeLineConfigCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of BillingInvoiceFlatFeeLineConfig entities. +func (c *BillingInvoiceFlatFeeLineConfigClient) CreateBulk(builders ...*BillingInvoiceFlatFeeLineConfigCreate) *BillingInvoiceFlatFeeLineConfigCreateBulk { + return &BillingInvoiceFlatFeeLineConfigCreateBulk{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 *BillingInvoiceFlatFeeLineConfigClient) MapCreateBulk(slice any, setFunc func(*BillingInvoiceFlatFeeLineConfigCreate, int)) *BillingInvoiceFlatFeeLineConfigCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &BillingInvoiceFlatFeeLineConfigCreateBulk{err: fmt.Errorf("calling to BillingInvoiceFlatFeeLineConfigClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*BillingInvoiceFlatFeeLineConfigCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &BillingInvoiceFlatFeeLineConfigCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for BillingInvoiceFlatFeeLineConfig. +func (c *BillingInvoiceFlatFeeLineConfigClient) Update() *BillingInvoiceFlatFeeLineConfigUpdate { + mutation := newBillingInvoiceFlatFeeLineConfigMutation(c.config, OpUpdate) + return &BillingInvoiceFlatFeeLineConfigUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BillingInvoiceFlatFeeLineConfigClient) UpdateOne(_m *BillingInvoiceFlatFeeLineConfig) *BillingInvoiceFlatFeeLineConfigUpdateOne { + mutation := newBillingInvoiceFlatFeeLineConfigMutation(c.config, OpUpdateOne, withBillingInvoiceFlatFeeLineConfig(_m)) + return &BillingInvoiceFlatFeeLineConfigUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BillingInvoiceFlatFeeLineConfigClient) UpdateOneID(id string) *BillingInvoiceFlatFeeLineConfigUpdateOne { + mutation := newBillingInvoiceFlatFeeLineConfigMutation(c.config, OpUpdateOne, withBillingInvoiceFlatFeeLineConfigID(id)) + return &BillingInvoiceFlatFeeLineConfigUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for BillingInvoiceFlatFeeLineConfig. +func (c *BillingInvoiceFlatFeeLineConfigClient) Delete() *BillingInvoiceFlatFeeLineConfigDelete { + mutation := newBillingInvoiceFlatFeeLineConfigMutation(c.config, OpDelete) + return &BillingInvoiceFlatFeeLineConfigDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BillingInvoiceFlatFeeLineConfigClient) DeleteOne(_m *BillingInvoiceFlatFeeLineConfig) *BillingInvoiceFlatFeeLineConfigDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *BillingInvoiceFlatFeeLineConfigClient) DeleteOneID(id string) *BillingInvoiceFlatFeeLineConfigDeleteOne { + builder := c.Delete().Where(billinginvoiceflatfeelineconfig.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BillingInvoiceFlatFeeLineConfigDeleteOne{builder} +} + +// Query returns a query builder for BillingInvoiceFlatFeeLineConfig. +func (c *BillingInvoiceFlatFeeLineConfigClient) Query() *BillingInvoiceFlatFeeLineConfigQuery { + return &BillingInvoiceFlatFeeLineConfigQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeBillingInvoiceFlatFeeLineConfig}, + inters: c.Interceptors(), + } +} + +// Get returns a BillingInvoiceFlatFeeLineConfig entity by its id. +func (c *BillingInvoiceFlatFeeLineConfigClient) Get(ctx context.Context, id string) (*BillingInvoiceFlatFeeLineConfig, error) { + return c.Query().Where(billinginvoiceflatfeelineconfig.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BillingInvoiceFlatFeeLineConfigClient) GetX(ctx context.Context, id string) *BillingInvoiceFlatFeeLineConfig { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *BillingInvoiceFlatFeeLineConfigClient) Hooks() []Hook { + return c.hooks.BillingInvoiceFlatFeeLineConfig +} + +// Interceptors returns the client interceptors. +func (c *BillingInvoiceFlatFeeLineConfigClient) Interceptors() []Interceptor { + return c.inters.BillingInvoiceFlatFeeLineConfig +} + +func (c *BillingInvoiceFlatFeeLineConfigClient) mutate(ctx context.Context, m *BillingInvoiceFlatFeeLineConfigMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&BillingInvoiceFlatFeeLineConfigCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&BillingInvoiceFlatFeeLineConfigUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&BillingInvoiceFlatFeeLineConfigUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&BillingInvoiceFlatFeeLineConfigDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown BillingInvoiceFlatFeeLineConfig mutation op: %q", m.Op()) + } +} + +// BillingInvoiceLineClient is a client for the BillingInvoiceLine schema. +type BillingInvoiceLineClient struct { + config +} + +// NewBillingInvoiceLineClient returns a client for the BillingInvoiceLine from the given config. +func NewBillingInvoiceLineClient(c config) *BillingInvoiceLineClient { + return &BillingInvoiceLineClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `billinginvoiceline.Hooks(f(g(h())))`. +func (c *BillingInvoiceLineClient) Use(hooks ...Hook) { + c.hooks.BillingInvoiceLine = append(c.hooks.BillingInvoiceLine, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `billinginvoiceline.Intercept(f(g(h())))`. +func (c *BillingInvoiceLineClient) Intercept(interceptors ...Interceptor) { + c.inters.BillingInvoiceLine = append(c.inters.BillingInvoiceLine, interceptors...) +} + +// Create returns a builder for creating a BillingInvoiceLine entity. +func (c *BillingInvoiceLineClient) Create() *BillingInvoiceLineCreate { + mutation := newBillingInvoiceLineMutation(c.config, OpCreate) + return &BillingInvoiceLineCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of BillingInvoiceLine entities. +func (c *BillingInvoiceLineClient) CreateBulk(builders ...*BillingInvoiceLineCreate) *BillingInvoiceLineCreateBulk { + return &BillingInvoiceLineCreateBulk{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 *BillingInvoiceLineClient) MapCreateBulk(slice any, setFunc func(*BillingInvoiceLineCreate, int)) *BillingInvoiceLineCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &BillingInvoiceLineCreateBulk{err: fmt.Errorf("calling to BillingInvoiceLineClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*BillingInvoiceLineCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &BillingInvoiceLineCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for BillingInvoiceLine. +func (c *BillingInvoiceLineClient) Update() *BillingInvoiceLineUpdate { + mutation := newBillingInvoiceLineMutation(c.config, OpUpdate) + return &BillingInvoiceLineUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BillingInvoiceLineClient) UpdateOne(_m *BillingInvoiceLine) *BillingInvoiceLineUpdateOne { + mutation := newBillingInvoiceLineMutation(c.config, OpUpdateOne, withBillingInvoiceLine(_m)) + return &BillingInvoiceLineUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BillingInvoiceLineClient) UpdateOneID(id string) *BillingInvoiceLineUpdateOne { + mutation := newBillingInvoiceLineMutation(c.config, OpUpdateOne, withBillingInvoiceLineID(id)) + return &BillingInvoiceLineUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for BillingInvoiceLine. +func (c *BillingInvoiceLineClient) Delete() *BillingInvoiceLineDelete { + mutation := newBillingInvoiceLineMutation(c.config, OpDelete) + return &BillingInvoiceLineDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BillingInvoiceLineClient) DeleteOne(_m *BillingInvoiceLine) *BillingInvoiceLineDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *BillingInvoiceLineClient) DeleteOneID(id string) *BillingInvoiceLineDeleteOne { + builder := c.Delete().Where(billinginvoiceline.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BillingInvoiceLineDeleteOne{builder} +} + +// Query returns a query builder for BillingInvoiceLine. +func (c *BillingInvoiceLineClient) Query() *BillingInvoiceLineQuery { + return &BillingInvoiceLineQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeBillingInvoiceLine}, + inters: c.Interceptors(), + } +} + +// Get returns a BillingInvoiceLine entity by its id. +func (c *BillingInvoiceLineClient) Get(ctx context.Context, id string) (*BillingInvoiceLine, error) { + return c.Query().Where(billinginvoiceline.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BillingInvoiceLineClient) GetX(ctx context.Context, id string) *BillingInvoiceLine { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryBillingInvoice queries the billing_invoice edge of a BillingInvoiceLine. +func (c *BillingInvoiceLineClient) QueryBillingInvoice(_m *BillingInvoiceLine) *BillingInvoiceQuery { + query := (&BillingInvoiceClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoiceline.Table, billinginvoiceline.FieldID, id), + sqlgraph.To(billinginvoice.Table, billinginvoice.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoiceline.BillingInvoiceTable, billinginvoiceline.BillingInvoiceColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySplitLineGroup queries the split_line_group edge of a BillingInvoiceLine. +func (c *BillingInvoiceLineClient) QuerySplitLineGroup(_m *BillingInvoiceLine) *BillingInvoiceSplitLineGroupQuery { + query := (&BillingInvoiceSplitLineGroupClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoiceline.Table, billinginvoiceline.FieldID, id), + sqlgraph.To(billinginvoicesplitlinegroup.Table, billinginvoicesplitlinegroup.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoiceline.SplitLineGroupTable, billinginvoiceline.SplitLineGroupColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryFlatFeeLine queries the flat_fee_line edge of a BillingInvoiceLine. +func (c *BillingInvoiceLineClient) QueryFlatFeeLine(_m *BillingInvoiceLine) *BillingInvoiceFlatFeeLineConfigQuery { + query := (&BillingInvoiceFlatFeeLineConfigClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoiceline.Table, billinginvoiceline.FieldID, id), + sqlgraph.To(billinginvoiceflatfeelineconfig.Table, billinginvoiceflatfeelineconfig.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, billinginvoiceline.FlatFeeLineTable, billinginvoiceline.FlatFeeLineColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryUsageBasedLine queries the usage_based_line edge of a BillingInvoiceLine. +func (c *BillingInvoiceLineClient) QueryUsageBasedLine(_m *BillingInvoiceLine) *BillingInvoiceUsageBasedLineConfigQuery { + query := (&BillingInvoiceUsageBasedLineConfigClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoiceline.Table, billinginvoiceline.FieldID, id), + sqlgraph.To(billinginvoiceusagebasedlineconfig.Table, billinginvoiceusagebasedlineconfig.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, billinginvoiceline.UsageBasedLineTable, billinginvoiceline.UsageBasedLineColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryParentLine queries the parent_line edge of a BillingInvoiceLine. +func (c *BillingInvoiceLineClient) QueryParentLine(_m *BillingInvoiceLine) *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoiceline.Table, billinginvoiceline.FieldID, id), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoiceline.ParentLineTable, billinginvoiceline.ParentLineColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryDetailedLines queries the detailed_lines edge of a BillingInvoiceLine. +func (c *BillingInvoiceLineClient) QueryDetailedLines(_m *BillingInvoiceLine) *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoiceline.Table, billinginvoiceline.FieldID, id), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, billinginvoiceline.DetailedLinesTable, billinginvoiceline.DetailedLinesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryDetailedLinesV2 queries the detailed_lines_v2 edge of a BillingInvoiceLine. +func (c *BillingInvoiceLineClient) QueryDetailedLinesV2(_m *BillingInvoiceLine) *BillingStandardInvoiceDetailedLineQuery { + query := (&BillingStandardInvoiceDetailedLineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoiceline.Table, billinginvoiceline.FieldID, id), + sqlgraph.To(billingstandardinvoicedetailedline.Table, billingstandardinvoicedetailedline.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, billinginvoiceline.DetailedLinesV2Table, billinginvoiceline.DetailedLinesV2Column), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryLineUsageDiscounts queries the line_usage_discounts edge of a BillingInvoiceLine. +func (c *BillingInvoiceLineClient) QueryLineUsageDiscounts(_m *BillingInvoiceLine) *BillingInvoiceLineUsageDiscountQuery { + query := (&BillingInvoiceLineUsageDiscountClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoiceline.Table, billinginvoiceline.FieldID, id), + sqlgraph.To(billinginvoicelineusagediscount.Table, billinginvoicelineusagediscount.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, billinginvoiceline.LineUsageDiscountsTable, billinginvoiceline.LineUsageDiscountsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryLineAmountDiscounts queries the line_amount_discounts edge of a BillingInvoiceLine. +func (c *BillingInvoiceLineClient) QueryLineAmountDiscounts(_m *BillingInvoiceLine) *BillingInvoiceLineDiscountQuery { + query := (&BillingInvoiceLineDiscountClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoiceline.Table, billinginvoiceline.FieldID, id), + sqlgraph.To(billinginvoicelinediscount.Table, billinginvoicelinediscount.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, billinginvoiceline.LineAmountDiscountsTable, billinginvoiceline.LineAmountDiscountsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubscription queries the subscription edge of a BillingInvoiceLine. +func (c *BillingInvoiceLineClient) QuerySubscription(_m *BillingInvoiceLine) *SubscriptionQuery { + query := (&SubscriptionClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoiceline.Table, billinginvoiceline.FieldID, id), + sqlgraph.To(subscription.Table, subscription.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoiceline.SubscriptionTable, billinginvoiceline.SubscriptionColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubscriptionPhase queries the subscription_phase edge of a BillingInvoiceLine. +func (c *BillingInvoiceLineClient) QuerySubscriptionPhase(_m *BillingInvoiceLine) *SubscriptionPhaseQuery { + query := (&SubscriptionPhaseClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoiceline.Table, billinginvoiceline.FieldID, id), + sqlgraph.To(subscriptionphase.Table, subscriptionphase.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoiceline.SubscriptionPhaseTable, billinginvoiceline.SubscriptionPhaseColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubscriptionItem queries the subscription_item edge of a BillingInvoiceLine. +func (c *BillingInvoiceLineClient) QuerySubscriptionItem(_m *BillingInvoiceLine) *SubscriptionItemQuery { + query := (&SubscriptionItemClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoiceline.Table, billinginvoiceline.FieldID, id), + sqlgraph.To(subscriptionitem.Table, subscriptionitem.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoiceline.SubscriptionItemTable, billinginvoiceline.SubscriptionItemColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCharge queries the charge edge of a BillingInvoiceLine. +func (c *BillingInvoiceLineClient) QueryCharge(_m *BillingInvoiceLine) *ChargeQuery { + query := (&ChargeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoiceline.Table, billinginvoiceline.FieldID, id), + sqlgraph.To(charge.Table, charge.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoiceline.ChargeTable, billinginvoiceline.ChargeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargeFlatFeeRunPayment queries the charge_flat_fee_run_payment edge of a BillingInvoiceLine. +func (c *BillingInvoiceLineClient) QueryChargeFlatFeeRunPayment(_m *BillingInvoiceLine) *ChargeFlatFeeRunPaymentQuery { + query := (&ChargeFlatFeeRunPaymentClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoiceline.Table, billinginvoiceline.FieldID, id), + sqlgraph.To(chargeflatfeerunpayment.Table, chargeflatfeerunpayment.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, billinginvoiceline.ChargeFlatFeeRunPaymentTable, billinginvoiceline.ChargeFlatFeeRunPaymentColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargeFlatFeeRunCreditAllocations queries the charge_flat_fee_run_credit_allocations edge of a BillingInvoiceLine. +func (c *BillingInvoiceLineClient) QueryChargeFlatFeeRunCreditAllocations(_m *BillingInvoiceLine) *ChargeFlatFeeRunCreditAllocationsQuery { + query := (&ChargeFlatFeeRunCreditAllocationsClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoiceline.Table, billinginvoiceline.FieldID, id), + sqlgraph.To(chargeflatfeeruncreditallocations.Table, chargeflatfeeruncreditallocations.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, billinginvoiceline.ChargeFlatFeeRunCreditAllocationsTable, billinginvoiceline.ChargeFlatFeeRunCreditAllocationsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargeFlatFeeRuns queries the charge_flat_fee_runs edge of a BillingInvoiceLine. +func (c *BillingInvoiceLineClient) QueryChargeFlatFeeRuns(_m *BillingInvoiceLine) *ChargeFlatFeeRunQuery { + query := (&ChargeFlatFeeRunClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoiceline.Table, billinginvoiceline.FieldID, id), + sqlgraph.To(chargeflatfeerun.Table, chargeflatfeerun.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, billinginvoiceline.ChargeFlatFeeRunsTable, billinginvoiceline.ChargeFlatFeeRunsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargeUsageBasedRun queries the charge_usage_based_run edge of a BillingInvoiceLine. +func (c *BillingInvoiceLineClient) QueryChargeUsageBasedRun(_m *BillingInvoiceLine) *ChargeUsageBasedRunsQuery { + query := (&ChargeUsageBasedRunsClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoiceline.Table, billinginvoiceline.FieldID, id), + sqlgraph.To(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, billinginvoiceline.ChargeUsageBasedRunTable, billinginvoiceline.ChargeUsageBasedRunColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargeCreditPurchaseInvoicedPayment queries the charge_credit_purchase_invoiced_payment edge of a BillingInvoiceLine. +func (c *BillingInvoiceLineClient) QueryChargeCreditPurchaseInvoicedPayment(_m *BillingInvoiceLine) *ChargeCreditPurchaseInvoicedPaymentQuery { + query := (&ChargeCreditPurchaseInvoicedPaymentClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoiceline.Table, billinginvoiceline.FieldID, id), + sqlgraph.To(chargecreditpurchaseinvoicedpayment.Table, chargecreditpurchaseinvoicedpayment.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, billinginvoiceline.ChargeCreditPurchaseInvoicedPaymentTable, billinginvoiceline.ChargeCreditPurchaseInvoicedPaymentColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryTaxCode queries the tax_code edge of a BillingInvoiceLine. +func (c *BillingInvoiceLineClient) QueryTaxCode(_m *BillingInvoiceLine) *TaxCodeQuery { + query := (&TaxCodeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoiceline.Table, billinginvoiceline.FieldID, id), + sqlgraph.To(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoiceline.TaxCodeTable, billinginvoiceline.TaxCodeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *BillingInvoiceLineClient) Hooks() []Hook { + return c.hooks.BillingInvoiceLine +} + +// Interceptors returns the client interceptors. +func (c *BillingInvoiceLineClient) Interceptors() []Interceptor { + return c.inters.BillingInvoiceLine +} + +func (c *BillingInvoiceLineClient) mutate(ctx context.Context, m *BillingInvoiceLineMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&BillingInvoiceLineCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&BillingInvoiceLineUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&BillingInvoiceLineUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&BillingInvoiceLineDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown BillingInvoiceLine mutation op: %q", m.Op()) + } +} + +// BillingInvoiceLineDiscountClient is a client for the BillingInvoiceLineDiscount schema. +type BillingInvoiceLineDiscountClient struct { + config +} + +// NewBillingInvoiceLineDiscountClient returns a client for the BillingInvoiceLineDiscount from the given config. +func NewBillingInvoiceLineDiscountClient(c config) *BillingInvoiceLineDiscountClient { + return &BillingInvoiceLineDiscountClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `billinginvoicelinediscount.Hooks(f(g(h())))`. +func (c *BillingInvoiceLineDiscountClient) Use(hooks ...Hook) { + c.hooks.BillingInvoiceLineDiscount = append(c.hooks.BillingInvoiceLineDiscount, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `billinginvoicelinediscount.Intercept(f(g(h())))`. +func (c *BillingInvoiceLineDiscountClient) Intercept(interceptors ...Interceptor) { + c.inters.BillingInvoiceLineDiscount = append(c.inters.BillingInvoiceLineDiscount, interceptors...) +} + +// Create returns a builder for creating a BillingInvoiceLineDiscount entity. +func (c *BillingInvoiceLineDiscountClient) Create() *BillingInvoiceLineDiscountCreate { + mutation := newBillingInvoiceLineDiscountMutation(c.config, OpCreate) + return &BillingInvoiceLineDiscountCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of BillingInvoiceLineDiscount entities. +func (c *BillingInvoiceLineDiscountClient) CreateBulk(builders ...*BillingInvoiceLineDiscountCreate) *BillingInvoiceLineDiscountCreateBulk { + return &BillingInvoiceLineDiscountCreateBulk{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 *BillingInvoiceLineDiscountClient) MapCreateBulk(slice any, setFunc func(*BillingInvoiceLineDiscountCreate, int)) *BillingInvoiceLineDiscountCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &BillingInvoiceLineDiscountCreateBulk{err: fmt.Errorf("calling to BillingInvoiceLineDiscountClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*BillingInvoiceLineDiscountCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &BillingInvoiceLineDiscountCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for BillingInvoiceLineDiscount. +func (c *BillingInvoiceLineDiscountClient) Update() *BillingInvoiceLineDiscountUpdate { + mutation := newBillingInvoiceLineDiscountMutation(c.config, OpUpdate) + return &BillingInvoiceLineDiscountUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BillingInvoiceLineDiscountClient) UpdateOne(_m *BillingInvoiceLineDiscount) *BillingInvoiceLineDiscountUpdateOne { + mutation := newBillingInvoiceLineDiscountMutation(c.config, OpUpdateOne, withBillingInvoiceLineDiscount(_m)) + return &BillingInvoiceLineDiscountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BillingInvoiceLineDiscountClient) UpdateOneID(id string) *BillingInvoiceLineDiscountUpdateOne { + mutation := newBillingInvoiceLineDiscountMutation(c.config, OpUpdateOne, withBillingInvoiceLineDiscountID(id)) + return &BillingInvoiceLineDiscountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for BillingInvoiceLineDiscount. +func (c *BillingInvoiceLineDiscountClient) Delete() *BillingInvoiceLineDiscountDelete { + mutation := newBillingInvoiceLineDiscountMutation(c.config, OpDelete) + return &BillingInvoiceLineDiscountDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BillingInvoiceLineDiscountClient) DeleteOne(_m *BillingInvoiceLineDiscount) *BillingInvoiceLineDiscountDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *BillingInvoiceLineDiscountClient) DeleteOneID(id string) *BillingInvoiceLineDiscountDeleteOne { + builder := c.Delete().Where(billinginvoicelinediscount.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BillingInvoiceLineDiscountDeleteOne{builder} +} + +// Query returns a query builder for BillingInvoiceLineDiscount. +func (c *BillingInvoiceLineDiscountClient) Query() *BillingInvoiceLineDiscountQuery { + return &BillingInvoiceLineDiscountQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeBillingInvoiceLineDiscount}, + inters: c.Interceptors(), + } +} + +// Get returns a BillingInvoiceLineDiscount entity by its id. +func (c *BillingInvoiceLineDiscountClient) Get(ctx context.Context, id string) (*BillingInvoiceLineDiscount, error) { + return c.Query().Where(billinginvoicelinediscount.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BillingInvoiceLineDiscountClient) GetX(ctx context.Context, id string) *BillingInvoiceLineDiscount { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryBillingInvoiceLine queries the billing_invoice_line edge of a BillingInvoiceLineDiscount. +func (c *BillingInvoiceLineDiscountClient) QueryBillingInvoiceLine(_m *BillingInvoiceLineDiscount) *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoicelinediscount.Table, billinginvoicelinediscount.FieldID, id), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoicelinediscount.BillingInvoiceLineTable, billinginvoicelinediscount.BillingInvoiceLineColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *BillingInvoiceLineDiscountClient) Hooks() []Hook { + return c.hooks.BillingInvoiceLineDiscount +} + +// Interceptors returns the client interceptors. +func (c *BillingInvoiceLineDiscountClient) Interceptors() []Interceptor { + return c.inters.BillingInvoiceLineDiscount +} + +func (c *BillingInvoiceLineDiscountClient) mutate(ctx context.Context, m *BillingInvoiceLineDiscountMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&BillingInvoiceLineDiscountCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&BillingInvoiceLineDiscountUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&BillingInvoiceLineDiscountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&BillingInvoiceLineDiscountDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown BillingInvoiceLineDiscount mutation op: %q", m.Op()) + } +} + +// BillingInvoiceLineUsageDiscountClient is a client for the BillingInvoiceLineUsageDiscount schema. +type BillingInvoiceLineUsageDiscountClient struct { + config +} + +// NewBillingInvoiceLineUsageDiscountClient returns a client for the BillingInvoiceLineUsageDiscount from the given config. +func NewBillingInvoiceLineUsageDiscountClient(c config) *BillingInvoiceLineUsageDiscountClient { + return &BillingInvoiceLineUsageDiscountClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `billinginvoicelineusagediscount.Hooks(f(g(h())))`. +func (c *BillingInvoiceLineUsageDiscountClient) Use(hooks ...Hook) { + c.hooks.BillingInvoiceLineUsageDiscount = append(c.hooks.BillingInvoiceLineUsageDiscount, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `billinginvoicelineusagediscount.Intercept(f(g(h())))`. +func (c *BillingInvoiceLineUsageDiscountClient) Intercept(interceptors ...Interceptor) { + c.inters.BillingInvoiceLineUsageDiscount = append(c.inters.BillingInvoiceLineUsageDiscount, interceptors...) +} + +// Create returns a builder for creating a BillingInvoiceLineUsageDiscount entity. +func (c *BillingInvoiceLineUsageDiscountClient) Create() *BillingInvoiceLineUsageDiscountCreate { + mutation := newBillingInvoiceLineUsageDiscountMutation(c.config, OpCreate) + return &BillingInvoiceLineUsageDiscountCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of BillingInvoiceLineUsageDiscount entities. +func (c *BillingInvoiceLineUsageDiscountClient) CreateBulk(builders ...*BillingInvoiceLineUsageDiscountCreate) *BillingInvoiceLineUsageDiscountCreateBulk { + return &BillingInvoiceLineUsageDiscountCreateBulk{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 *BillingInvoiceLineUsageDiscountClient) MapCreateBulk(slice any, setFunc func(*BillingInvoiceLineUsageDiscountCreate, int)) *BillingInvoiceLineUsageDiscountCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &BillingInvoiceLineUsageDiscountCreateBulk{err: fmt.Errorf("calling to BillingInvoiceLineUsageDiscountClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*BillingInvoiceLineUsageDiscountCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &BillingInvoiceLineUsageDiscountCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for BillingInvoiceLineUsageDiscount. +func (c *BillingInvoiceLineUsageDiscountClient) Update() *BillingInvoiceLineUsageDiscountUpdate { + mutation := newBillingInvoiceLineUsageDiscountMutation(c.config, OpUpdate) + return &BillingInvoiceLineUsageDiscountUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BillingInvoiceLineUsageDiscountClient) UpdateOne(_m *BillingInvoiceLineUsageDiscount) *BillingInvoiceLineUsageDiscountUpdateOne { + mutation := newBillingInvoiceLineUsageDiscountMutation(c.config, OpUpdateOne, withBillingInvoiceLineUsageDiscount(_m)) + return &BillingInvoiceLineUsageDiscountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BillingInvoiceLineUsageDiscountClient) UpdateOneID(id string) *BillingInvoiceLineUsageDiscountUpdateOne { + mutation := newBillingInvoiceLineUsageDiscountMutation(c.config, OpUpdateOne, withBillingInvoiceLineUsageDiscountID(id)) + return &BillingInvoiceLineUsageDiscountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for BillingInvoiceLineUsageDiscount. +func (c *BillingInvoiceLineUsageDiscountClient) Delete() *BillingInvoiceLineUsageDiscountDelete { + mutation := newBillingInvoiceLineUsageDiscountMutation(c.config, OpDelete) + return &BillingInvoiceLineUsageDiscountDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BillingInvoiceLineUsageDiscountClient) DeleteOne(_m *BillingInvoiceLineUsageDiscount) *BillingInvoiceLineUsageDiscountDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *BillingInvoiceLineUsageDiscountClient) DeleteOneID(id string) *BillingInvoiceLineUsageDiscountDeleteOne { + builder := c.Delete().Where(billinginvoicelineusagediscount.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BillingInvoiceLineUsageDiscountDeleteOne{builder} +} + +// Query returns a query builder for BillingInvoiceLineUsageDiscount. +func (c *BillingInvoiceLineUsageDiscountClient) Query() *BillingInvoiceLineUsageDiscountQuery { + return &BillingInvoiceLineUsageDiscountQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeBillingInvoiceLineUsageDiscount}, + inters: c.Interceptors(), + } +} + +// Get returns a BillingInvoiceLineUsageDiscount entity by its id. +func (c *BillingInvoiceLineUsageDiscountClient) Get(ctx context.Context, id string) (*BillingInvoiceLineUsageDiscount, error) { + return c.Query().Where(billinginvoicelineusagediscount.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BillingInvoiceLineUsageDiscountClient) GetX(ctx context.Context, id string) *BillingInvoiceLineUsageDiscount { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryBillingInvoiceLine queries the billing_invoice_line edge of a BillingInvoiceLineUsageDiscount. +func (c *BillingInvoiceLineUsageDiscountClient) QueryBillingInvoiceLine(_m *BillingInvoiceLineUsageDiscount) *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoicelineusagediscount.Table, billinginvoicelineusagediscount.FieldID, id), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoicelineusagediscount.BillingInvoiceLineTable, billinginvoicelineusagediscount.BillingInvoiceLineColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *BillingInvoiceLineUsageDiscountClient) Hooks() []Hook { + return c.hooks.BillingInvoiceLineUsageDiscount +} + +// Interceptors returns the client interceptors. +func (c *BillingInvoiceLineUsageDiscountClient) Interceptors() []Interceptor { + return c.inters.BillingInvoiceLineUsageDiscount +} + +func (c *BillingInvoiceLineUsageDiscountClient) mutate(ctx context.Context, m *BillingInvoiceLineUsageDiscountMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&BillingInvoiceLineUsageDiscountCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&BillingInvoiceLineUsageDiscountUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&BillingInvoiceLineUsageDiscountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&BillingInvoiceLineUsageDiscountDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown BillingInvoiceLineUsageDiscount mutation op: %q", m.Op()) + } +} + +// BillingInvoiceSplitLineGroupClient is a client for the BillingInvoiceSplitLineGroup schema. +type BillingInvoiceSplitLineGroupClient struct { + config +} + +// NewBillingInvoiceSplitLineGroupClient returns a client for the BillingInvoiceSplitLineGroup from the given config. +func NewBillingInvoiceSplitLineGroupClient(c config) *BillingInvoiceSplitLineGroupClient { + return &BillingInvoiceSplitLineGroupClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `billinginvoicesplitlinegroup.Hooks(f(g(h())))`. +func (c *BillingInvoiceSplitLineGroupClient) Use(hooks ...Hook) { + c.hooks.BillingInvoiceSplitLineGroup = append(c.hooks.BillingInvoiceSplitLineGroup, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `billinginvoicesplitlinegroup.Intercept(f(g(h())))`. +func (c *BillingInvoiceSplitLineGroupClient) Intercept(interceptors ...Interceptor) { + c.inters.BillingInvoiceSplitLineGroup = append(c.inters.BillingInvoiceSplitLineGroup, interceptors...) +} + +// Create returns a builder for creating a BillingInvoiceSplitLineGroup entity. +func (c *BillingInvoiceSplitLineGroupClient) Create() *BillingInvoiceSplitLineGroupCreate { + mutation := newBillingInvoiceSplitLineGroupMutation(c.config, OpCreate) + return &BillingInvoiceSplitLineGroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of BillingInvoiceSplitLineGroup entities. +func (c *BillingInvoiceSplitLineGroupClient) CreateBulk(builders ...*BillingInvoiceSplitLineGroupCreate) *BillingInvoiceSplitLineGroupCreateBulk { + return &BillingInvoiceSplitLineGroupCreateBulk{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 *BillingInvoiceSplitLineGroupClient) MapCreateBulk(slice any, setFunc func(*BillingInvoiceSplitLineGroupCreate, int)) *BillingInvoiceSplitLineGroupCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &BillingInvoiceSplitLineGroupCreateBulk{err: fmt.Errorf("calling to BillingInvoiceSplitLineGroupClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*BillingInvoiceSplitLineGroupCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &BillingInvoiceSplitLineGroupCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for BillingInvoiceSplitLineGroup. +func (c *BillingInvoiceSplitLineGroupClient) Update() *BillingInvoiceSplitLineGroupUpdate { + mutation := newBillingInvoiceSplitLineGroupMutation(c.config, OpUpdate) + return &BillingInvoiceSplitLineGroupUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BillingInvoiceSplitLineGroupClient) UpdateOne(_m *BillingInvoiceSplitLineGroup) *BillingInvoiceSplitLineGroupUpdateOne { + mutation := newBillingInvoiceSplitLineGroupMutation(c.config, OpUpdateOne, withBillingInvoiceSplitLineGroup(_m)) + return &BillingInvoiceSplitLineGroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BillingInvoiceSplitLineGroupClient) UpdateOneID(id string) *BillingInvoiceSplitLineGroupUpdateOne { + mutation := newBillingInvoiceSplitLineGroupMutation(c.config, OpUpdateOne, withBillingInvoiceSplitLineGroupID(id)) + return &BillingInvoiceSplitLineGroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for BillingInvoiceSplitLineGroup. +func (c *BillingInvoiceSplitLineGroupClient) Delete() *BillingInvoiceSplitLineGroupDelete { + mutation := newBillingInvoiceSplitLineGroupMutation(c.config, OpDelete) + return &BillingInvoiceSplitLineGroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BillingInvoiceSplitLineGroupClient) DeleteOne(_m *BillingInvoiceSplitLineGroup) *BillingInvoiceSplitLineGroupDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *BillingInvoiceSplitLineGroupClient) DeleteOneID(id string) *BillingInvoiceSplitLineGroupDeleteOne { + builder := c.Delete().Where(billinginvoicesplitlinegroup.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BillingInvoiceSplitLineGroupDeleteOne{builder} +} + +// Query returns a query builder for BillingInvoiceSplitLineGroup. +func (c *BillingInvoiceSplitLineGroupClient) Query() *BillingInvoiceSplitLineGroupQuery { + return &BillingInvoiceSplitLineGroupQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeBillingInvoiceSplitLineGroup}, + inters: c.Interceptors(), + } +} + +// Get returns a BillingInvoiceSplitLineGroup entity by its id. +func (c *BillingInvoiceSplitLineGroupClient) Get(ctx context.Context, id string) (*BillingInvoiceSplitLineGroup, error) { + return c.Query().Where(billinginvoicesplitlinegroup.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BillingInvoiceSplitLineGroupClient) GetX(ctx context.Context, id string) *BillingInvoiceSplitLineGroup { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryBillingInvoiceLines queries the billing_invoice_lines edge of a BillingInvoiceSplitLineGroup. +func (c *BillingInvoiceSplitLineGroupClient) QueryBillingInvoiceLines(_m *BillingInvoiceSplitLineGroup) *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoicesplitlinegroup.Table, billinginvoicesplitlinegroup.FieldID, id), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, billinginvoicesplitlinegroup.BillingInvoiceLinesTable, billinginvoicesplitlinegroup.BillingInvoiceLinesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubscription queries the subscription edge of a BillingInvoiceSplitLineGroup. +func (c *BillingInvoiceSplitLineGroupClient) QuerySubscription(_m *BillingInvoiceSplitLineGroup) *SubscriptionQuery { + query := (&SubscriptionClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoicesplitlinegroup.Table, billinginvoicesplitlinegroup.FieldID, id), + sqlgraph.To(subscription.Table, subscription.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoicesplitlinegroup.SubscriptionTable, billinginvoicesplitlinegroup.SubscriptionColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubscriptionPhase queries the subscription_phase edge of a BillingInvoiceSplitLineGroup. +func (c *BillingInvoiceSplitLineGroupClient) QuerySubscriptionPhase(_m *BillingInvoiceSplitLineGroup) *SubscriptionPhaseQuery { + query := (&SubscriptionPhaseClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoicesplitlinegroup.Table, billinginvoicesplitlinegroup.FieldID, id), + sqlgraph.To(subscriptionphase.Table, subscriptionphase.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoicesplitlinegroup.SubscriptionPhaseTable, billinginvoicesplitlinegroup.SubscriptionPhaseColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubscriptionItem queries the subscription_item edge of a BillingInvoiceSplitLineGroup. +func (c *BillingInvoiceSplitLineGroupClient) QuerySubscriptionItem(_m *BillingInvoiceSplitLineGroup) *SubscriptionItemQuery { + query := (&SubscriptionItemClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoicesplitlinegroup.Table, billinginvoicesplitlinegroup.FieldID, id), + sqlgraph.To(subscriptionitem.Table, subscriptionitem.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoicesplitlinegroup.SubscriptionItemTable, billinginvoicesplitlinegroup.SubscriptionItemColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCharge queries the charge edge of a BillingInvoiceSplitLineGroup. +func (c *BillingInvoiceSplitLineGroupClient) QueryCharge(_m *BillingInvoiceSplitLineGroup) *ChargeQuery { + query := (&ChargeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoicesplitlinegroup.Table, billinginvoicesplitlinegroup.FieldID, id), + sqlgraph.To(charge.Table, charge.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoicesplitlinegroup.ChargeTable, billinginvoicesplitlinegroup.ChargeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *BillingInvoiceSplitLineGroupClient) Hooks() []Hook { + return c.hooks.BillingInvoiceSplitLineGroup +} + +// Interceptors returns the client interceptors. +func (c *BillingInvoiceSplitLineGroupClient) Interceptors() []Interceptor { + return c.inters.BillingInvoiceSplitLineGroup +} + +func (c *BillingInvoiceSplitLineGroupClient) mutate(ctx context.Context, m *BillingInvoiceSplitLineGroupMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&BillingInvoiceSplitLineGroupCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&BillingInvoiceSplitLineGroupUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&BillingInvoiceSplitLineGroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&BillingInvoiceSplitLineGroupDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown BillingInvoiceSplitLineGroup mutation op: %q", m.Op()) + } +} + +// BillingInvoiceUsageBasedLineConfigClient is a client for the BillingInvoiceUsageBasedLineConfig schema. +type BillingInvoiceUsageBasedLineConfigClient struct { + config +} + +// NewBillingInvoiceUsageBasedLineConfigClient returns a client for the BillingInvoiceUsageBasedLineConfig from the given config. +func NewBillingInvoiceUsageBasedLineConfigClient(c config) *BillingInvoiceUsageBasedLineConfigClient { + return &BillingInvoiceUsageBasedLineConfigClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `billinginvoiceusagebasedlineconfig.Hooks(f(g(h())))`. +func (c *BillingInvoiceUsageBasedLineConfigClient) Use(hooks ...Hook) { + c.hooks.BillingInvoiceUsageBasedLineConfig = append(c.hooks.BillingInvoiceUsageBasedLineConfig, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `billinginvoiceusagebasedlineconfig.Intercept(f(g(h())))`. +func (c *BillingInvoiceUsageBasedLineConfigClient) Intercept(interceptors ...Interceptor) { + c.inters.BillingInvoiceUsageBasedLineConfig = append(c.inters.BillingInvoiceUsageBasedLineConfig, interceptors...) +} + +// Create returns a builder for creating a BillingInvoiceUsageBasedLineConfig entity. +func (c *BillingInvoiceUsageBasedLineConfigClient) Create() *BillingInvoiceUsageBasedLineConfigCreate { + mutation := newBillingInvoiceUsageBasedLineConfigMutation(c.config, OpCreate) + return &BillingInvoiceUsageBasedLineConfigCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of BillingInvoiceUsageBasedLineConfig entities. +func (c *BillingInvoiceUsageBasedLineConfigClient) CreateBulk(builders ...*BillingInvoiceUsageBasedLineConfigCreate) *BillingInvoiceUsageBasedLineConfigCreateBulk { + return &BillingInvoiceUsageBasedLineConfigCreateBulk{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 *BillingInvoiceUsageBasedLineConfigClient) MapCreateBulk(slice any, setFunc func(*BillingInvoiceUsageBasedLineConfigCreate, int)) *BillingInvoiceUsageBasedLineConfigCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &BillingInvoiceUsageBasedLineConfigCreateBulk{err: fmt.Errorf("calling to BillingInvoiceUsageBasedLineConfigClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*BillingInvoiceUsageBasedLineConfigCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &BillingInvoiceUsageBasedLineConfigCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for BillingInvoiceUsageBasedLineConfig. +func (c *BillingInvoiceUsageBasedLineConfigClient) Update() *BillingInvoiceUsageBasedLineConfigUpdate { + mutation := newBillingInvoiceUsageBasedLineConfigMutation(c.config, OpUpdate) + return &BillingInvoiceUsageBasedLineConfigUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BillingInvoiceUsageBasedLineConfigClient) UpdateOne(_m *BillingInvoiceUsageBasedLineConfig) *BillingInvoiceUsageBasedLineConfigUpdateOne { + mutation := newBillingInvoiceUsageBasedLineConfigMutation(c.config, OpUpdateOne, withBillingInvoiceUsageBasedLineConfig(_m)) + return &BillingInvoiceUsageBasedLineConfigUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BillingInvoiceUsageBasedLineConfigClient) UpdateOneID(id string) *BillingInvoiceUsageBasedLineConfigUpdateOne { + mutation := newBillingInvoiceUsageBasedLineConfigMutation(c.config, OpUpdateOne, withBillingInvoiceUsageBasedLineConfigID(id)) + return &BillingInvoiceUsageBasedLineConfigUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for BillingInvoiceUsageBasedLineConfig. +func (c *BillingInvoiceUsageBasedLineConfigClient) Delete() *BillingInvoiceUsageBasedLineConfigDelete { + mutation := newBillingInvoiceUsageBasedLineConfigMutation(c.config, OpDelete) + return &BillingInvoiceUsageBasedLineConfigDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BillingInvoiceUsageBasedLineConfigClient) DeleteOne(_m *BillingInvoiceUsageBasedLineConfig) *BillingInvoiceUsageBasedLineConfigDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *BillingInvoiceUsageBasedLineConfigClient) DeleteOneID(id string) *BillingInvoiceUsageBasedLineConfigDeleteOne { + builder := c.Delete().Where(billinginvoiceusagebasedlineconfig.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BillingInvoiceUsageBasedLineConfigDeleteOne{builder} +} + +// Query returns a query builder for BillingInvoiceUsageBasedLineConfig. +func (c *BillingInvoiceUsageBasedLineConfigClient) Query() *BillingInvoiceUsageBasedLineConfigQuery { + return &BillingInvoiceUsageBasedLineConfigQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeBillingInvoiceUsageBasedLineConfig}, + inters: c.Interceptors(), + } +} + +// Get returns a BillingInvoiceUsageBasedLineConfig entity by its id. +func (c *BillingInvoiceUsageBasedLineConfigClient) Get(ctx context.Context, id string) (*BillingInvoiceUsageBasedLineConfig, error) { + return c.Query().Where(billinginvoiceusagebasedlineconfig.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BillingInvoiceUsageBasedLineConfigClient) GetX(ctx context.Context, id string) *BillingInvoiceUsageBasedLineConfig { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *BillingInvoiceUsageBasedLineConfigClient) Hooks() []Hook { + return c.hooks.BillingInvoiceUsageBasedLineConfig +} + +// Interceptors returns the client interceptors. +func (c *BillingInvoiceUsageBasedLineConfigClient) Interceptors() []Interceptor { + return c.inters.BillingInvoiceUsageBasedLineConfig +} + +func (c *BillingInvoiceUsageBasedLineConfigClient) mutate(ctx context.Context, m *BillingInvoiceUsageBasedLineConfigMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&BillingInvoiceUsageBasedLineConfigCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&BillingInvoiceUsageBasedLineConfigUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&BillingInvoiceUsageBasedLineConfigUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&BillingInvoiceUsageBasedLineConfigDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown BillingInvoiceUsageBasedLineConfig mutation op: %q", m.Op()) + } +} + +// BillingInvoiceValidationIssueClient is a client for the BillingInvoiceValidationIssue schema. +type BillingInvoiceValidationIssueClient struct { + config +} + +// NewBillingInvoiceValidationIssueClient returns a client for the BillingInvoiceValidationIssue from the given config. +func NewBillingInvoiceValidationIssueClient(c config) *BillingInvoiceValidationIssueClient { + return &BillingInvoiceValidationIssueClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `billinginvoicevalidationissue.Hooks(f(g(h())))`. +func (c *BillingInvoiceValidationIssueClient) Use(hooks ...Hook) { + c.hooks.BillingInvoiceValidationIssue = append(c.hooks.BillingInvoiceValidationIssue, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `billinginvoicevalidationissue.Intercept(f(g(h())))`. +func (c *BillingInvoiceValidationIssueClient) Intercept(interceptors ...Interceptor) { + c.inters.BillingInvoiceValidationIssue = append(c.inters.BillingInvoiceValidationIssue, interceptors...) +} + +// Create returns a builder for creating a BillingInvoiceValidationIssue entity. +func (c *BillingInvoiceValidationIssueClient) Create() *BillingInvoiceValidationIssueCreate { + mutation := newBillingInvoiceValidationIssueMutation(c.config, OpCreate) + return &BillingInvoiceValidationIssueCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of BillingInvoiceValidationIssue entities. +func (c *BillingInvoiceValidationIssueClient) CreateBulk(builders ...*BillingInvoiceValidationIssueCreate) *BillingInvoiceValidationIssueCreateBulk { + return &BillingInvoiceValidationIssueCreateBulk{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 *BillingInvoiceValidationIssueClient) MapCreateBulk(slice any, setFunc func(*BillingInvoiceValidationIssueCreate, int)) *BillingInvoiceValidationIssueCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &BillingInvoiceValidationIssueCreateBulk{err: fmt.Errorf("calling to BillingInvoiceValidationIssueClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*BillingInvoiceValidationIssueCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &BillingInvoiceValidationIssueCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for BillingInvoiceValidationIssue. +func (c *BillingInvoiceValidationIssueClient) Update() *BillingInvoiceValidationIssueUpdate { + mutation := newBillingInvoiceValidationIssueMutation(c.config, OpUpdate) + return &BillingInvoiceValidationIssueUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BillingInvoiceValidationIssueClient) UpdateOne(_m *BillingInvoiceValidationIssue) *BillingInvoiceValidationIssueUpdateOne { + mutation := newBillingInvoiceValidationIssueMutation(c.config, OpUpdateOne, withBillingInvoiceValidationIssue(_m)) + return &BillingInvoiceValidationIssueUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BillingInvoiceValidationIssueClient) UpdateOneID(id string) *BillingInvoiceValidationIssueUpdateOne { + mutation := newBillingInvoiceValidationIssueMutation(c.config, OpUpdateOne, withBillingInvoiceValidationIssueID(id)) + return &BillingInvoiceValidationIssueUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for BillingInvoiceValidationIssue. +func (c *BillingInvoiceValidationIssueClient) Delete() *BillingInvoiceValidationIssueDelete { + mutation := newBillingInvoiceValidationIssueMutation(c.config, OpDelete) + return &BillingInvoiceValidationIssueDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BillingInvoiceValidationIssueClient) DeleteOne(_m *BillingInvoiceValidationIssue) *BillingInvoiceValidationIssueDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *BillingInvoiceValidationIssueClient) DeleteOneID(id string) *BillingInvoiceValidationIssueDeleteOne { + builder := c.Delete().Where(billinginvoicevalidationissue.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BillingInvoiceValidationIssueDeleteOne{builder} +} + +// Query returns a query builder for BillingInvoiceValidationIssue. +func (c *BillingInvoiceValidationIssueClient) Query() *BillingInvoiceValidationIssueQuery { + return &BillingInvoiceValidationIssueQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeBillingInvoiceValidationIssue}, + inters: c.Interceptors(), + } +} + +// Get returns a BillingInvoiceValidationIssue entity by its id. +func (c *BillingInvoiceValidationIssueClient) Get(ctx context.Context, id string) (*BillingInvoiceValidationIssue, error) { + return c.Query().Where(billinginvoicevalidationissue.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BillingInvoiceValidationIssueClient) GetX(ctx context.Context, id string) *BillingInvoiceValidationIssue { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryBillingInvoice queries the billing_invoice edge of a BillingInvoiceValidationIssue. +func (c *BillingInvoiceValidationIssueClient) QueryBillingInvoice(_m *BillingInvoiceValidationIssue) *BillingInvoiceQuery { + query := (&BillingInvoiceClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billinginvoicevalidationissue.Table, billinginvoicevalidationissue.FieldID, id), + sqlgraph.To(billinginvoice.Table, billinginvoice.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billinginvoicevalidationissue.BillingInvoiceTable, billinginvoicevalidationissue.BillingInvoiceColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *BillingInvoiceValidationIssueClient) Hooks() []Hook { + return c.hooks.BillingInvoiceValidationIssue +} + +// Interceptors returns the client interceptors. +func (c *BillingInvoiceValidationIssueClient) Interceptors() []Interceptor { + return c.inters.BillingInvoiceValidationIssue +} + +func (c *BillingInvoiceValidationIssueClient) mutate(ctx context.Context, m *BillingInvoiceValidationIssueMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&BillingInvoiceValidationIssueCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&BillingInvoiceValidationIssueUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&BillingInvoiceValidationIssueUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&BillingInvoiceValidationIssueDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown BillingInvoiceValidationIssue mutation op: %q", m.Op()) + } +} + +// BillingInvoiceWriteSchemaLevelClient is a client for the BillingInvoiceWriteSchemaLevel schema. +type BillingInvoiceWriteSchemaLevelClient struct { + config +} + +// NewBillingInvoiceWriteSchemaLevelClient returns a client for the BillingInvoiceWriteSchemaLevel from the given config. +func NewBillingInvoiceWriteSchemaLevelClient(c config) *BillingInvoiceWriteSchemaLevelClient { + return &BillingInvoiceWriteSchemaLevelClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `billinginvoicewriteschemalevel.Hooks(f(g(h())))`. +func (c *BillingInvoiceWriteSchemaLevelClient) Use(hooks ...Hook) { + c.hooks.BillingInvoiceWriteSchemaLevel = append(c.hooks.BillingInvoiceWriteSchemaLevel, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `billinginvoicewriteschemalevel.Intercept(f(g(h())))`. +func (c *BillingInvoiceWriteSchemaLevelClient) Intercept(interceptors ...Interceptor) { + c.inters.BillingInvoiceWriteSchemaLevel = append(c.inters.BillingInvoiceWriteSchemaLevel, interceptors...) +} + +// Create returns a builder for creating a BillingInvoiceWriteSchemaLevel entity. +func (c *BillingInvoiceWriteSchemaLevelClient) Create() *BillingInvoiceWriteSchemaLevelCreate { + mutation := newBillingInvoiceWriteSchemaLevelMutation(c.config, OpCreate) + return &BillingInvoiceWriteSchemaLevelCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of BillingInvoiceWriteSchemaLevel entities. +func (c *BillingInvoiceWriteSchemaLevelClient) CreateBulk(builders ...*BillingInvoiceWriteSchemaLevelCreate) *BillingInvoiceWriteSchemaLevelCreateBulk { + return &BillingInvoiceWriteSchemaLevelCreateBulk{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 *BillingInvoiceWriteSchemaLevelClient) MapCreateBulk(slice any, setFunc func(*BillingInvoiceWriteSchemaLevelCreate, int)) *BillingInvoiceWriteSchemaLevelCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &BillingInvoiceWriteSchemaLevelCreateBulk{err: fmt.Errorf("calling to BillingInvoiceWriteSchemaLevelClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*BillingInvoiceWriteSchemaLevelCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &BillingInvoiceWriteSchemaLevelCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for BillingInvoiceWriteSchemaLevel. +func (c *BillingInvoiceWriteSchemaLevelClient) Update() *BillingInvoiceWriteSchemaLevelUpdate { + mutation := newBillingInvoiceWriteSchemaLevelMutation(c.config, OpUpdate) + return &BillingInvoiceWriteSchemaLevelUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BillingInvoiceWriteSchemaLevelClient) UpdateOne(_m *BillingInvoiceWriteSchemaLevel) *BillingInvoiceWriteSchemaLevelUpdateOne { + mutation := newBillingInvoiceWriteSchemaLevelMutation(c.config, OpUpdateOne, withBillingInvoiceWriteSchemaLevel(_m)) + return &BillingInvoiceWriteSchemaLevelUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BillingInvoiceWriteSchemaLevelClient) UpdateOneID(id string) *BillingInvoiceWriteSchemaLevelUpdateOne { + mutation := newBillingInvoiceWriteSchemaLevelMutation(c.config, OpUpdateOne, withBillingInvoiceWriteSchemaLevelID(id)) + return &BillingInvoiceWriteSchemaLevelUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for BillingInvoiceWriteSchemaLevel. +func (c *BillingInvoiceWriteSchemaLevelClient) Delete() *BillingInvoiceWriteSchemaLevelDelete { + mutation := newBillingInvoiceWriteSchemaLevelMutation(c.config, OpDelete) + return &BillingInvoiceWriteSchemaLevelDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BillingInvoiceWriteSchemaLevelClient) DeleteOne(_m *BillingInvoiceWriteSchemaLevel) *BillingInvoiceWriteSchemaLevelDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *BillingInvoiceWriteSchemaLevelClient) DeleteOneID(id string) *BillingInvoiceWriteSchemaLevelDeleteOne { + builder := c.Delete().Where(billinginvoicewriteschemalevel.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BillingInvoiceWriteSchemaLevelDeleteOne{builder} +} + +// Query returns a query builder for BillingInvoiceWriteSchemaLevel. +func (c *BillingInvoiceWriteSchemaLevelClient) Query() *BillingInvoiceWriteSchemaLevelQuery { + return &BillingInvoiceWriteSchemaLevelQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeBillingInvoiceWriteSchemaLevel}, + inters: c.Interceptors(), + } +} + +// Get returns a BillingInvoiceWriteSchemaLevel entity by its id. +func (c *BillingInvoiceWriteSchemaLevelClient) Get(ctx context.Context, id string) (*BillingInvoiceWriteSchemaLevel, error) { + return c.Query().Where(billinginvoicewriteschemalevel.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BillingInvoiceWriteSchemaLevelClient) GetX(ctx context.Context, id string) *BillingInvoiceWriteSchemaLevel { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *BillingInvoiceWriteSchemaLevelClient) Hooks() []Hook { + return c.hooks.BillingInvoiceWriteSchemaLevel +} + +// Interceptors returns the client interceptors. +func (c *BillingInvoiceWriteSchemaLevelClient) Interceptors() []Interceptor { + return c.inters.BillingInvoiceWriteSchemaLevel +} + +func (c *BillingInvoiceWriteSchemaLevelClient) mutate(ctx context.Context, m *BillingInvoiceWriteSchemaLevelMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&BillingInvoiceWriteSchemaLevelCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&BillingInvoiceWriteSchemaLevelUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&BillingInvoiceWriteSchemaLevelUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&BillingInvoiceWriteSchemaLevelDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown BillingInvoiceWriteSchemaLevel mutation op: %q", m.Op()) + } +} + +// BillingProfileClient is a client for the BillingProfile schema. +type BillingProfileClient struct { + config +} + +// NewBillingProfileClient returns a client for the BillingProfile from the given config. +func NewBillingProfileClient(c config) *BillingProfileClient { + return &BillingProfileClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `billingprofile.Hooks(f(g(h())))`. +func (c *BillingProfileClient) Use(hooks ...Hook) { + c.hooks.BillingProfile = append(c.hooks.BillingProfile, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `billingprofile.Intercept(f(g(h())))`. +func (c *BillingProfileClient) Intercept(interceptors ...Interceptor) { + c.inters.BillingProfile = append(c.inters.BillingProfile, interceptors...) +} + +// Create returns a builder for creating a BillingProfile entity. +func (c *BillingProfileClient) Create() *BillingProfileCreate { + mutation := newBillingProfileMutation(c.config, OpCreate) + return &BillingProfileCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of BillingProfile entities. +func (c *BillingProfileClient) CreateBulk(builders ...*BillingProfileCreate) *BillingProfileCreateBulk { + return &BillingProfileCreateBulk{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 *BillingProfileClient) MapCreateBulk(slice any, setFunc func(*BillingProfileCreate, int)) *BillingProfileCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &BillingProfileCreateBulk{err: fmt.Errorf("calling to BillingProfileClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*BillingProfileCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &BillingProfileCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for BillingProfile. +func (c *BillingProfileClient) Update() *BillingProfileUpdate { + mutation := newBillingProfileMutation(c.config, OpUpdate) + return &BillingProfileUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BillingProfileClient) UpdateOne(_m *BillingProfile) *BillingProfileUpdateOne { + mutation := newBillingProfileMutation(c.config, OpUpdateOne, withBillingProfile(_m)) + return &BillingProfileUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BillingProfileClient) UpdateOneID(id string) *BillingProfileUpdateOne { + mutation := newBillingProfileMutation(c.config, OpUpdateOne, withBillingProfileID(id)) + return &BillingProfileUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for BillingProfile. +func (c *BillingProfileClient) Delete() *BillingProfileDelete { + mutation := newBillingProfileMutation(c.config, OpDelete) + return &BillingProfileDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BillingProfileClient) DeleteOne(_m *BillingProfile) *BillingProfileDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *BillingProfileClient) DeleteOneID(id string) *BillingProfileDeleteOne { + builder := c.Delete().Where(billingprofile.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BillingProfileDeleteOne{builder} +} + +// Query returns a query builder for BillingProfile. +func (c *BillingProfileClient) Query() *BillingProfileQuery { + return &BillingProfileQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeBillingProfile}, + inters: c.Interceptors(), + } +} + +// Get returns a BillingProfile entity by its id. +func (c *BillingProfileClient) Get(ctx context.Context, id string) (*BillingProfile, error) { + return c.Query().Where(billingprofile.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BillingProfileClient) GetX(ctx context.Context, id string) *BillingProfile { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryBillingInvoices queries the billing_invoices edge of a BillingProfile. +func (c *BillingProfileClient) QueryBillingInvoices(_m *BillingProfile) *BillingInvoiceQuery { + query := (&BillingInvoiceClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billingprofile.Table, billingprofile.FieldID, id), + sqlgraph.To(billinginvoice.Table, billinginvoice.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, billingprofile.BillingInvoicesTable, billingprofile.BillingInvoicesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingCustomerOverride queries the billing_customer_override edge of a BillingProfile. +func (c *BillingProfileClient) QueryBillingCustomerOverride(_m *BillingProfile) *BillingCustomerOverrideQuery { + query := (&BillingCustomerOverrideClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billingprofile.Table, billingprofile.FieldID, id), + sqlgraph.To(billingcustomeroverride.Table, billingcustomeroverride.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, billingprofile.BillingCustomerOverrideTable, billingprofile.BillingCustomerOverrideColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryWorkflowConfig queries the workflow_config edge of a BillingProfile. +func (c *BillingProfileClient) QueryWorkflowConfig(_m *BillingProfile) *BillingWorkflowConfigQuery { + query := (&BillingWorkflowConfigClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billingprofile.Table, billingprofile.FieldID, id), + sqlgraph.To(billingworkflowconfig.Table, billingworkflowconfig.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, billingprofile.WorkflowConfigTable, billingprofile.WorkflowConfigColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryTaxApp queries the tax_app edge of a BillingProfile. +func (c *BillingProfileClient) QueryTaxApp(_m *BillingProfile) *AppQuery { + query := (&AppClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billingprofile.Table, billingprofile.FieldID, id), + sqlgraph.To(dbapp.Table, dbapp.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billingprofile.TaxAppTable, billingprofile.TaxAppColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryInvoicingApp queries the invoicing_app edge of a BillingProfile. +func (c *BillingProfileClient) QueryInvoicingApp(_m *BillingProfile) *AppQuery { + query := (&AppClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billingprofile.Table, billingprofile.FieldID, id), + sqlgraph.To(dbapp.Table, dbapp.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billingprofile.InvoicingAppTable, billingprofile.InvoicingAppColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryPaymentApp queries the payment_app edge of a BillingProfile. +func (c *BillingProfileClient) QueryPaymentApp(_m *BillingProfile) *AppQuery { + query := (&AppClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billingprofile.Table, billingprofile.FieldID, id), + sqlgraph.To(dbapp.Table, dbapp.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billingprofile.PaymentAppTable, billingprofile.PaymentAppColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *BillingProfileClient) Hooks() []Hook { + return c.hooks.BillingProfile +} + +// Interceptors returns the client interceptors. +func (c *BillingProfileClient) Interceptors() []Interceptor { + return c.inters.BillingProfile +} + +func (c *BillingProfileClient) mutate(ctx context.Context, m *BillingProfileMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&BillingProfileCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&BillingProfileUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&BillingProfileUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&BillingProfileDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown BillingProfile mutation op: %q", m.Op()) + } +} + +// BillingSequenceNumbersClient is a client for the BillingSequenceNumbers schema. +type BillingSequenceNumbersClient struct { + config +} + +// NewBillingSequenceNumbersClient returns a client for the BillingSequenceNumbers from the given config. +func NewBillingSequenceNumbersClient(c config) *BillingSequenceNumbersClient { + return &BillingSequenceNumbersClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `billingsequencenumbers.Hooks(f(g(h())))`. +func (c *BillingSequenceNumbersClient) Use(hooks ...Hook) { + c.hooks.BillingSequenceNumbers = append(c.hooks.BillingSequenceNumbers, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `billingsequencenumbers.Intercept(f(g(h())))`. +func (c *BillingSequenceNumbersClient) Intercept(interceptors ...Interceptor) { + c.inters.BillingSequenceNumbers = append(c.inters.BillingSequenceNumbers, interceptors...) +} + +// Create returns a builder for creating a BillingSequenceNumbers entity. +func (c *BillingSequenceNumbersClient) Create() *BillingSequenceNumbersCreate { + mutation := newBillingSequenceNumbersMutation(c.config, OpCreate) + return &BillingSequenceNumbersCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of BillingSequenceNumbers entities. +func (c *BillingSequenceNumbersClient) CreateBulk(builders ...*BillingSequenceNumbersCreate) *BillingSequenceNumbersCreateBulk { + return &BillingSequenceNumbersCreateBulk{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 *BillingSequenceNumbersClient) MapCreateBulk(slice any, setFunc func(*BillingSequenceNumbersCreate, int)) *BillingSequenceNumbersCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &BillingSequenceNumbersCreateBulk{err: fmt.Errorf("calling to BillingSequenceNumbersClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*BillingSequenceNumbersCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &BillingSequenceNumbersCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for BillingSequenceNumbers. +func (c *BillingSequenceNumbersClient) Update() *BillingSequenceNumbersUpdate { + mutation := newBillingSequenceNumbersMutation(c.config, OpUpdate) + return &BillingSequenceNumbersUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BillingSequenceNumbersClient) UpdateOne(_m *BillingSequenceNumbers) *BillingSequenceNumbersUpdateOne { + mutation := newBillingSequenceNumbersMutation(c.config, OpUpdateOne, withBillingSequenceNumbers(_m)) + return &BillingSequenceNumbersUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BillingSequenceNumbersClient) UpdateOneID(id int) *BillingSequenceNumbersUpdateOne { + mutation := newBillingSequenceNumbersMutation(c.config, OpUpdateOne, withBillingSequenceNumbersID(id)) + return &BillingSequenceNumbersUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for BillingSequenceNumbers. +func (c *BillingSequenceNumbersClient) Delete() *BillingSequenceNumbersDelete { + mutation := newBillingSequenceNumbersMutation(c.config, OpDelete) + return &BillingSequenceNumbersDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BillingSequenceNumbersClient) DeleteOne(_m *BillingSequenceNumbers) *BillingSequenceNumbersDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *BillingSequenceNumbersClient) DeleteOneID(id int) *BillingSequenceNumbersDeleteOne { + builder := c.Delete().Where(billingsequencenumbers.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BillingSequenceNumbersDeleteOne{builder} +} + +// Query returns a query builder for BillingSequenceNumbers. +func (c *BillingSequenceNumbersClient) Query() *BillingSequenceNumbersQuery { + return &BillingSequenceNumbersQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeBillingSequenceNumbers}, + inters: c.Interceptors(), + } +} + +// Get returns a BillingSequenceNumbers entity by its id. +func (c *BillingSequenceNumbersClient) Get(ctx context.Context, id int) (*BillingSequenceNumbers, error) { + return c.Query().Where(billingsequencenumbers.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BillingSequenceNumbersClient) GetX(ctx context.Context, id int) *BillingSequenceNumbers { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *BillingSequenceNumbersClient) Hooks() []Hook { + return c.hooks.BillingSequenceNumbers +} + +// Interceptors returns the client interceptors. +func (c *BillingSequenceNumbersClient) Interceptors() []Interceptor { + return c.inters.BillingSequenceNumbers +} + +func (c *BillingSequenceNumbersClient) mutate(ctx context.Context, m *BillingSequenceNumbersMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&BillingSequenceNumbersCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&BillingSequenceNumbersUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&BillingSequenceNumbersUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&BillingSequenceNumbersDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown BillingSequenceNumbers mutation op: %q", m.Op()) + } +} + +// BillingStandardInvoiceDetailedLineClient is a client for the BillingStandardInvoiceDetailedLine schema. +type BillingStandardInvoiceDetailedLineClient struct { + config +} + +// NewBillingStandardInvoiceDetailedLineClient returns a client for the BillingStandardInvoiceDetailedLine from the given config. +func NewBillingStandardInvoiceDetailedLineClient(c config) *BillingStandardInvoiceDetailedLineClient { + return &BillingStandardInvoiceDetailedLineClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `billingstandardinvoicedetailedline.Hooks(f(g(h())))`. +func (c *BillingStandardInvoiceDetailedLineClient) Use(hooks ...Hook) { + c.hooks.BillingStandardInvoiceDetailedLine = append(c.hooks.BillingStandardInvoiceDetailedLine, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `billingstandardinvoicedetailedline.Intercept(f(g(h())))`. +func (c *BillingStandardInvoiceDetailedLineClient) Intercept(interceptors ...Interceptor) { + c.inters.BillingStandardInvoiceDetailedLine = append(c.inters.BillingStandardInvoiceDetailedLine, interceptors...) +} + +// Create returns a builder for creating a BillingStandardInvoiceDetailedLine entity. +func (c *BillingStandardInvoiceDetailedLineClient) Create() *BillingStandardInvoiceDetailedLineCreate { + mutation := newBillingStandardInvoiceDetailedLineMutation(c.config, OpCreate) + return &BillingStandardInvoiceDetailedLineCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of BillingStandardInvoiceDetailedLine entities. +func (c *BillingStandardInvoiceDetailedLineClient) CreateBulk(builders ...*BillingStandardInvoiceDetailedLineCreate) *BillingStandardInvoiceDetailedLineCreateBulk { + return &BillingStandardInvoiceDetailedLineCreateBulk{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 *BillingStandardInvoiceDetailedLineClient) MapCreateBulk(slice any, setFunc func(*BillingStandardInvoiceDetailedLineCreate, int)) *BillingStandardInvoiceDetailedLineCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &BillingStandardInvoiceDetailedLineCreateBulk{err: fmt.Errorf("calling to BillingStandardInvoiceDetailedLineClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*BillingStandardInvoiceDetailedLineCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &BillingStandardInvoiceDetailedLineCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for BillingStandardInvoiceDetailedLine. +func (c *BillingStandardInvoiceDetailedLineClient) Update() *BillingStandardInvoiceDetailedLineUpdate { + mutation := newBillingStandardInvoiceDetailedLineMutation(c.config, OpUpdate) + return &BillingStandardInvoiceDetailedLineUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BillingStandardInvoiceDetailedLineClient) UpdateOne(_m *BillingStandardInvoiceDetailedLine) *BillingStandardInvoiceDetailedLineUpdateOne { + mutation := newBillingStandardInvoiceDetailedLineMutation(c.config, OpUpdateOne, withBillingStandardInvoiceDetailedLine(_m)) + return &BillingStandardInvoiceDetailedLineUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BillingStandardInvoiceDetailedLineClient) UpdateOneID(id string) *BillingStandardInvoiceDetailedLineUpdateOne { + mutation := newBillingStandardInvoiceDetailedLineMutation(c.config, OpUpdateOne, withBillingStandardInvoiceDetailedLineID(id)) + return &BillingStandardInvoiceDetailedLineUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for BillingStandardInvoiceDetailedLine. +func (c *BillingStandardInvoiceDetailedLineClient) Delete() *BillingStandardInvoiceDetailedLineDelete { + mutation := newBillingStandardInvoiceDetailedLineMutation(c.config, OpDelete) + return &BillingStandardInvoiceDetailedLineDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BillingStandardInvoiceDetailedLineClient) DeleteOne(_m *BillingStandardInvoiceDetailedLine) *BillingStandardInvoiceDetailedLineDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *BillingStandardInvoiceDetailedLineClient) DeleteOneID(id string) *BillingStandardInvoiceDetailedLineDeleteOne { + builder := c.Delete().Where(billingstandardinvoicedetailedline.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BillingStandardInvoiceDetailedLineDeleteOne{builder} +} + +// Query returns a query builder for BillingStandardInvoiceDetailedLine. +func (c *BillingStandardInvoiceDetailedLineClient) Query() *BillingStandardInvoiceDetailedLineQuery { + return &BillingStandardInvoiceDetailedLineQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeBillingStandardInvoiceDetailedLine}, + inters: c.Interceptors(), + } +} + +// Get returns a BillingStandardInvoiceDetailedLine entity by its id. +func (c *BillingStandardInvoiceDetailedLineClient) Get(ctx context.Context, id string) (*BillingStandardInvoiceDetailedLine, error) { + return c.Query().Where(billingstandardinvoicedetailedline.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BillingStandardInvoiceDetailedLineClient) GetX(ctx context.Context, id string) *BillingStandardInvoiceDetailedLine { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryBillingInvoice queries the billing_invoice edge of a BillingStandardInvoiceDetailedLine. +func (c *BillingStandardInvoiceDetailedLineClient) QueryBillingInvoice(_m *BillingStandardInvoiceDetailedLine) *BillingInvoiceQuery { + query := (&BillingInvoiceClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billingstandardinvoicedetailedline.Table, billingstandardinvoicedetailedline.FieldID, id), + sqlgraph.To(billinginvoice.Table, billinginvoice.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billingstandardinvoicedetailedline.BillingInvoiceTable, billingstandardinvoicedetailedline.BillingInvoiceColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingInvoiceLine queries the billing_invoice_line edge of a BillingStandardInvoiceDetailedLine. +func (c *BillingStandardInvoiceDetailedLineClient) QueryBillingInvoiceLine(_m *BillingStandardInvoiceDetailedLine) *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billingstandardinvoicedetailedline.Table, billingstandardinvoicedetailedline.FieldID, id), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billingstandardinvoicedetailedline.BillingInvoiceLineTable, billingstandardinvoicedetailedline.BillingInvoiceLineColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryAmountDiscounts queries the amount_discounts edge of a BillingStandardInvoiceDetailedLine. +func (c *BillingStandardInvoiceDetailedLineClient) QueryAmountDiscounts(_m *BillingStandardInvoiceDetailedLine) *BillingStandardInvoiceDetailedLineAmountDiscountQuery { + query := (&BillingStandardInvoiceDetailedLineAmountDiscountClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billingstandardinvoicedetailedline.Table, billingstandardinvoicedetailedline.FieldID, id), + sqlgraph.To(billingstandardinvoicedetailedlineamountdiscount.Table, billingstandardinvoicedetailedlineamountdiscount.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, billingstandardinvoicedetailedline.AmountDiscountsTable, billingstandardinvoicedetailedline.AmountDiscountsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *BillingStandardInvoiceDetailedLineClient) Hooks() []Hook { + return c.hooks.BillingStandardInvoiceDetailedLine +} + +// Interceptors returns the client interceptors. +func (c *BillingStandardInvoiceDetailedLineClient) Interceptors() []Interceptor { + return c.inters.BillingStandardInvoiceDetailedLine +} + +func (c *BillingStandardInvoiceDetailedLineClient) mutate(ctx context.Context, m *BillingStandardInvoiceDetailedLineMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&BillingStandardInvoiceDetailedLineCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&BillingStandardInvoiceDetailedLineUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&BillingStandardInvoiceDetailedLineUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&BillingStandardInvoiceDetailedLineDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown BillingStandardInvoiceDetailedLine mutation op: %q", m.Op()) + } +} + +// BillingStandardInvoiceDetailedLineAmountDiscountClient is a client for the BillingStandardInvoiceDetailedLineAmountDiscount schema. +type BillingStandardInvoiceDetailedLineAmountDiscountClient struct { + config +} + +// NewBillingStandardInvoiceDetailedLineAmountDiscountClient returns a client for the BillingStandardInvoiceDetailedLineAmountDiscount from the given config. +func NewBillingStandardInvoiceDetailedLineAmountDiscountClient(c config) *BillingStandardInvoiceDetailedLineAmountDiscountClient { + return &BillingStandardInvoiceDetailedLineAmountDiscountClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `billingstandardinvoicedetailedlineamountdiscount.Hooks(f(g(h())))`. +func (c *BillingStandardInvoiceDetailedLineAmountDiscountClient) Use(hooks ...Hook) { + c.hooks.BillingStandardInvoiceDetailedLineAmountDiscount = append(c.hooks.BillingStandardInvoiceDetailedLineAmountDiscount, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `billingstandardinvoicedetailedlineamountdiscount.Intercept(f(g(h())))`. +func (c *BillingStandardInvoiceDetailedLineAmountDiscountClient) Intercept(interceptors ...Interceptor) { + c.inters.BillingStandardInvoiceDetailedLineAmountDiscount = append(c.inters.BillingStandardInvoiceDetailedLineAmountDiscount, interceptors...) +} + +// Create returns a builder for creating a BillingStandardInvoiceDetailedLineAmountDiscount entity. +func (c *BillingStandardInvoiceDetailedLineAmountDiscountClient) Create() *BillingStandardInvoiceDetailedLineAmountDiscountCreate { + mutation := newBillingStandardInvoiceDetailedLineAmountDiscountMutation(c.config, OpCreate) + return &BillingStandardInvoiceDetailedLineAmountDiscountCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of BillingStandardInvoiceDetailedLineAmountDiscount entities. +func (c *BillingStandardInvoiceDetailedLineAmountDiscountClient) CreateBulk(builders ...*BillingStandardInvoiceDetailedLineAmountDiscountCreate) *BillingStandardInvoiceDetailedLineAmountDiscountCreateBulk { + return &BillingStandardInvoiceDetailedLineAmountDiscountCreateBulk{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 *BillingStandardInvoiceDetailedLineAmountDiscountClient) MapCreateBulk(slice any, setFunc func(*BillingStandardInvoiceDetailedLineAmountDiscountCreate, int)) *BillingStandardInvoiceDetailedLineAmountDiscountCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &BillingStandardInvoiceDetailedLineAmountDiscountCreateBulk{err: fmt.Errorf("calling to BillingStandardInvoiceDetailedLineAmountDiscountClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*BillingStandardInvoiceDetailedLineAmountDiscountCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &BillingStandardInvoiceDetailedLineAmountDiscountCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for BillingStandardInvoiceDetailedLineAmountDiscount. +func (c *BillingStandardInvoiceDetailedLineAmountDiscountClient) Update() *BillingStandardInvoiceDetailedLineAmountDiscountUpdate { + mutation := newBillingStandardInvoiceDetailedLineAmountDiscountMutation(c.config, OpUpdate) + return &BillingStandardInvoiceDetailedLineAmountDiscountUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BillingStandardInvoiceDetailedLineAmountDiscountClient) UpdateOne(_m *BillingStandardInvoiceDetailedLineAmountDiscount) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + mutation := newBillingStandardInvoiceDetailedLineAmountDiscountMutation(c.config, OpUpdateOne, withBillingStandardInvoiceDetailedLineAmountDiscount(_m)) + return &BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BillingStandardInvoiceDetailedLineAmountDiscountClient) UpdateOneID(id string) *BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne { + mutation := newBillingStandardInvoiceDetailedLineAmountDiscountMutation(c.config, OpUpdateOne, withBillingStandardInvoiceDetailedLineAmountDiscountID(id)) + return &BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for BillingStandardInvoiceDetailedLineAmountDiscount. +func (c *BillingStandardInvoiceDetailedLineAmountDiscountClient) Delete() *BillingStandardInvoiceDetailedLineAmountDiscountDelete { + mutation := newBillingStandardInvoiceDetailedLineAmountDiscountMutation(c.config, OpDelete) + return &BillingStandardInvoiceDetailedLineAmountDiscountDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BillingStandardInvoiceDetailedLineAmountDiscountClient) DeleteOne(_m *BillingStandardInvoiceDetailedLineAmountDiscount) *BillingStandardInvoiceDetailedLineAmountDiscountDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *BillingStandardInvoiceDetailedLineAmountDiscountClient) DeleteOneID(id string) *BillingStandardInvoiceDetailedLineAmountDiscountDeleteOne { + builder := c.Delete().Where(billingstandardinvoicedetailedlineamountdiscount.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BillingStandardInvoiceDetailedLineAmountDiscountDeleteOne{builder} +} + +// Query returns a query builder for BillingStandardInvoiceDetailedLineAmountDiscount. +func (c *BillingStandardInvoiceDetailedLineAmountDiscountClient) Query() *BillingStandardInvoiceDetailedLineAmountDiscountQuery { + return &BillingStandardInvoiceDetailedLineAmountDiscountQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeBillingStandardInvoiceDetailedLineAmountDiscount}, + inters: c.Interceptors(), + } +} + +// Get returns a BillingStandardInvoiceDetailedLineAmountDiscount entity by its id. +func (c *BillingStandardInvoiceDetailedLineAmountDiscountClient) Get(ctx context.Context, id string) (*BillingStandardInvoiceDetailedLineAmountDiscount, error) { + return c.Query().Where(billingstandardinvoicedetailedlineamountdiscount.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BillingStandardInvoiceDetailedLineAmountDiscountClient) GetX(ctx context.Context, id string) *BillingStandardInvoiceDetailedLineAmountDiscount { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryDetailedLine queries the detailed_line edge of a BillingStandardInvoiceDetailedLineAmountDiscount. +func (c *BillingStandardInvoiceDetailedLineAmountDiscountClient) QueryDetailedLine(_m *BillingStandardInvoiceDetailedLineAmountDiscount) *BillingStandardInvoiceDetailedLineQuery { + query := (&BillingStandardInvoiceDetailedLineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billingstandardinvoicedetailedlineamountdiscount.Table, billingstandardinvoicedetailedlineamountdiscount.FieldID, id), + sqlgraph.To(billingstandardinvoicedetailedline.Table, billingstandardinvoicedetailedline.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billingstandardinvoicedetailedlineamountdiscount.DetailedLineTable, billingstandardinvoicedetailedlineamountdiscount.DetailedLineColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *BillingStandardInvoiceDetailedLineAmountDiscountClient) Hooks() []Hook { + return c.hooks.BillingStandardInvoiceDetailedLineAmountDiscount +} + +// Interceptors returns the client interceptors. +func (c *BillingStandardInvoiceDetailedLineAmountDiscountClient) Interceptors() []Interceptor { + return c.inters.BillingStandardInvoiceDetailedLineAmountDiscount +} + +func (c *BillingStandardInvoiceDetailedLineAmountDiscountClient) mutate(ctx context.Context, m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&BillingStandardInvoiceDetailedLineAmountDiscountCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&BillingStandardInvoiceDetailedLineAmountDiscountUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&BillingStandardInvoiceDetailedLineAmountDiscountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&BillingStandardInvoiceDetailedLineAmountDiscountDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown BillingStandardInvoiceDetailedLineAmountDiscount mutation op: %q", m.Op()) + } +} + +// BillingWorkflowConfigClient is a client for the BillingWorkflowConfig schema. +type BillingWorkflowConfigClient struct { + config +} + +// NewBillingWorkflowConfigClient returns a client for the BillingWorkflowConfig from the given config. +func NewBillingWorkflowConfigClient(c config) *BillingWorkflowConfigClient { + return &BillingWorkflowConfigClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `billingworkflowconfig.Hooks(f(g(h())))`. +func (c *BillingWorkflowConfigClient) Use(hooks ...Hook) { + c.hooks.BillingWorkflowConfig = append(c.hooks.BillingWorkflowConfig, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `billingworkflowconfig.Intercept(f(g(h())))`. +func (c *BillingWorkflowConfigClient) Intercept(interceptors ...Interceptor) { + c.inters.BillingWorkflowConfig = append(c.inters.BillingWorkflowConfig, interceptors...) +} + +// Create returns a builder for creating a BillingWorkflowConfig entity. +func (c *BillingWorkflowConfigClient) Create() *BillingWorkflowConfigCreate { + mutation := newBillingWorkflowConfigMutation(c.config, OpCreate) + return &BillingWorkflowConfigCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of BillingWorkflowConfig entities. +func (c *BillingWorkflowConfigClient) CreateBulk(builders ...*BillingWorkflowConfigCreate) *BillingWorkflowConfigCreateBulk { + return &BillingWorkflowConfigCreateBulk{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 *BillingWorkflowConfigClient) MapCreateBulk(slice any, setFunc func(*BillingWorkflowConfigCreate, int)) *BillingWorkflowConfigCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &BillingWorkflowConfigCreateBulk{err: fmt.Errorf("calling to BillingWorkflowConfigClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*BillingWorkflowConfigCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &BillingWorkflowConfigCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for BillingWorkflowConfig. +func (c *BillingWorkflowConfigClient) Update() *BillingWorkflowConfigUpdate { + mutation := newBillingWorkflowConfigMutation(c.config, OpUpdate) + return &BillingWorkflowConfigUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BillingWorkflowConfigClient) UpdateOne(_m *BillingWorkflowConfig) *BillingWorkflowConfigUpdateOne { + mutation := newBillingWorkflowConfigMutation(c.config, OpUpdateOne, withBillingWorkflowConfig(_m)) + return &BillingWorkflowConfigUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BillingWorkflowConfigClient) UpdateOneID(id string) *BillingWorkflowConfigUpdateOne { + mutation := newBillingWorkflowConfigMutation(c.config, OpUpdateOne, withBillingWorkflowConfigID(id)) + return &BillingWorkflowConfigUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for BillingWorkflowConfig. +func (c *BillingWorkflowConfigClient) Delete() *BillingWorkflowConfigDelete { + mutation := newBillingWorkflowConfigMutation(c.config, OpDelete) + return &BillingWorkflowConfigDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BillingWorkflowConfigClient) DeleteOne(_m *BillingWorkflowConfig) *BillingWorkflowConfigDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *BillingWorkflowConfigClient) DeleteOneID(id string) *BillingWorkflowConfigDeleteOne { + builder := c.Delete().Where(billingworkflowconfig.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BillingWorkflowConfigDeleteOne{builder} +} + +// Query returns a query builder for BillingWorkflowConfig. +func (c *BillingWorkflowConfigClient) Query() *BillingWorkflowConfigQuery { + return &BillingWorkflowConfigQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeBillingWorkflowConfig}, + inters: c.Interceptors(), + } +} + +// Get returns a BillingWorkflowConfig entity by its id. +func (c *BillingWorkflowConfigClient) Get(ctx context.Context, id string) (*BillingWorkflowConfig, error) { + return c.Query().Where(billingworkflowconfig.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BillingWorkflowConfigClient) GetX(ctx context.Context, id string) *BillingWorkflowConfig { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryBillingInvoices queries the billing_invoices edge of a BillingWorkflowConfig. +func (c *BillingWorkflowConfigClient) QueryBillingInvoices(_m *BillingWorkflowConfig) *BillingInvoiceQuery { + query := (&BillingInvoiceClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billingworkflowconfig.Table, billingworkflowconfig.FieldID, id), + sqlgraph.To(billinginvoice.Table, billinginvoice.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, billingworkflowconfig.BillingInvoicesTable, billingworkflowconfig.BillingInvoicesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingProfile queries the billing_profile edge of a BillingWorkflowConfig. +func (c *BillingWorkflowConfigClient) QueryBillingProfile(_m *BillingWorkflowConfig) *BillingProfileQuery { + query := (&BillingProfileClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billingworkflowconfig.Table, billingworkflowconfig.FieldID, id), + sqlgraph.To(billingprofile.Table, billingprofile.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, billingworkflowconfig.BillingProfileTable, billingworkflowconfig.BillingProfileColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryTaxCode queries the tax_code edge of a BillingWorkflowConfig. +func (c *BillingWorkflowConfigClient) QueryTaxCode(_m *BillingWorkflowConfig) *TaxCodeQuery { + query := (&TaxCodeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(billingworkflowconfig.Table, billingworkflowconfig.FieldID, id), + sqlgraph.To(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, billingworkflowconfig.TaxCodeTable, billingworkflowconfig.TaxCodeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *BillingWorkflowConfigClient) Hooks() []Hook { + return c.hooks.BillingWorkflowConfig +} + +// Interceptors returns the client interceptors. +func (c *BillingWorkflowConfigClient) Interceptors() []Interceptor { + return c.inters.BillingWorkflowConfig +} + +func (c *BillingWorkflowConfigClient) mutate(ctx context.Context, m *BillingWorkflowConfigMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&BillingWorkflowConfigCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&BillingWorkflowConfigUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&BillingWorkflowConfigUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&BillingWorkflowConfigDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown BillingWorkflowConfig mutation op: %q", m.Op()) + } +} + +// ChargeClient is a client for the Charge schema. +type ChargeClient struct { + config +} + +// NewChargeClient returns a client for the Charge from the given config. +func NewChargeClient(c config) *ChargeClient { + return &ChargeClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `charge.Hooks(f(g(h())))`. +func (c *ChargeClient) Use(hooks ...Hook) { + c.hooks.Charge = append(c.hooks.Charge, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `charge.Intercept(f(g(h())))`. +func (c *ChargeClient) Intercept(interceptors ...Interceptor) { + c.inters.Charge = append(c.inters.Charge, interceptors...) +} + +// Create returns a builder for creating a Charge entity. +func (c *ChargeClient) Create() *ChargeCreate { + mutation := newChargeMutation(c.config, OpCreate) + return &ChargeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Charge entities. +func (c *ChargeClient) CreateBulk(builders ...*ChargeCreate) *ChargeCreateBulk { + return &ChargeCreateBulk{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 *ChargeClient) MapCreateBulk(slice any, setFunc func(*ChargeCreate, int)) *ChargeCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ChargeCreateBulk{err: fmt.Errorf("calling to ChargeClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ChargeCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ChargeCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Charge. +func (c *ChargeClient) Update() *ChargeUpdate { + mutation := newChargeMutation(c.config, OpUpdate) + return &ChargeUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ChargeClient) UpdateOne(_m *Charge) *ChargeUpdateOne { + mutation := newChargeMutation(c.config, OpUpdateOne, withCharge(_m)) + return &ChargeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ChargeClient) UpdateOneID(id string) *ChargeUpdateOne { + mutation := newChargeMutation(c.config, OpUpdateOne, withChargeID(id)) + return &ChargeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Charge. +func (c *ChargeClient) Delete() *ChargeDelete { + mutation := newChargeMutation(c.config, OpDelete) + return &ChargeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ChargeClient) DeleteOne(_m *Charge) *ChargeDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ChargeClient) DeleteOneID(id string) *ChargeDeleteOne { + builder := c.Delete().Where(charge.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ChargeDeleteOne{builder} +} + +// Query returns a query builder for Charge. +func (c *ChargeClient) Query() *ChargeQuery { + return &ChargeQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeCharge}, + inters: c.Interceptors(), + } +} + +// Get returns a Charge entity by its id. +func (c *ChargeClient) Get(ctx context.Context, id string) (*Charge, error) { + return c.Query().Where(charge.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ChargeClient) GetX(ctx context.Context, id string) *Charge { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryFlatFee queries the flat_fee edge of a Charge. +func (c *ChargeClient) QueryFlatFee(_m *Charge) *ChargeFlatFeeQuery { + query := (&ChargeFlatFeeClient{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(chargeflatfee.Table, chargeflatfee.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, charge.FlatFeeTable, charge.FlatFeeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCreditPurchase queries the credit_purchase edge of a Charge. +func (c *ChargeClient) QueryCreditPurchase(_m *Charge) *ChargeCreditPurchaseQuery { + query := (&ChargeCreditPurchaseClient{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(chargecreditpurchase.Table, chargecreditpurchase.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, charge.CreditPurchaseTable, charge.CreditPurchaseColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + 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, true, 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() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(charge.Table, charge.FieldID, id), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, charge.BillingInvoiceLinesTable, charge.BillingInvoiceLinesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingSplitLineGroups queries the billing_split_line_groups edge of a Charge. +func (c *ChargeClient) QueryBillingSplitLineGroups(_m *Charge) *BillingInvoiceSplitLineGroupQuery { + query := (&BillingInvoiceSplitLineGroupClient{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(billinginvoicesplitlinegroup.Table, billinginvoicesplitlinegroup.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, charge.BillingSplitLineGroupsTable, charge.BillingSplitLineGroupsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCreditRealizationLineages queries the credit_realization_lineages edge of a Charge. +func (c *ChargeClient) QueryCreditRealizationLineages(_m *Charge) *CreditRealizationLineageQuery { + query := (&CreditRealizationLineageClient{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(creditrealizationlineage.Table, creditrealizationlineage.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, charge.CreditRealizationLineagesTable, charge.CreditRealizationLineagesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ChargeClient) Hooks() []Hook { + return c.hooks.Charge +} + +// Interceptors returns the client interceptors. +func (c *ChargeClient) Interceptors() []Interceptor { + return c.inters.Charge +} + +func (c *ChargeClient) mutate(ctx context.Context, m *ChargeMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ChargeCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ChargeUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ChargeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ChargeDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown Charge mutation op: %q", m.Op()) + } +} + +// ChargeCreditPurchaseClient is a client for the ChargeCreditPurchase schema. +type ChargeCreditPurchaseClient struct { + config +} + +// NewChargeCreditPurchaseClient returns a client for the ChargeCreditPurchase from the given config. +func NewChargeCreditPurchaseClient(c config) *ChargeCreditPurchaseClient { + return &ChargeCreditPurchaseClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `chargecreditpurchase.Hooks(f(g(h())))`. +func (c *ChargeCreditPurchaseClient) Use(hooks ...Hook) { + c.hooks.ChargeCreditPurchase = append(c.hooks.ChargeCreditPurchase, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `chargecreditpurchase.Intercept(f(g(h())))`. +func (c *ChargeCreditPurchaseClient) Intercept(interceptors ...Interceptor) { + c.inters.ChargeCreditPurchase = append(c.inters.ChargeCreditPurchase, interceptors...) +} + +// Create returns a builder for creating a ChargeCreditPurchase entity. +func (c *ChargeCreditPurchaseClient) Create() *ChargeCreditPurchaseCreate { + mutation := newChargeCreditPurchaseMutation(c.config, OpCreate) + return &ChargeCreditPurchaseCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ChargeCreditPurchase entities. +func (c *ChargeCreditPurchaseClient) CreateBulk(builders ...*ChargeCreditPurchaseCreate) *ChargeCreditPurchaseCreateBulk { + return &ChargeCreditPurchaseCreateBulk{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 *ChargeCreditPurchaseClient) MapCreateBulk(slice any, setFunc func(*ChargeCreditPurchaseCreate, int)) *ChargeCreditPurchaseCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ChargeCreditPurchaseCreateBulk{err: fmt.Errorf("calling to ChargeCreditPurchaseClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ChargeCreditPurchaseCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ChargeCreditPurchaseCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ChargeCreditPurchase. +func (c *ChargeCreditPurchaseClient) Update() *ChargeCreditPurchaseUpdate { + mutation := newChargeCreditPurchaseMutation(c.config, OpUpdate) + return &ChargeCreditPurchaseUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ChargeCreditPurchaseClient) UpdateOne(_m *ChargeCreditPurchase) *ChargeCreditPurchaseUpdateOne { + mutation := newChargeCreditPurchaseMutation(c.config, OpUpdateOne, withChargeCreditPurchase(_m)) + return &ChargeCreditPurchaseUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ChargeCreditPurchaseClient) UpdateOneID(id string) *ChargeCreditPurchaseUpdateOne { + mutation := newChargeCreditPurchaseMutation(c.config, OpUpdateOne, withChargeCreditPurchaseID(id)) + return &ChargeCreditPurchaseUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ChargeCreditPurchase. +func (c *ChargeCreditPurchaseClient) Delete() *ChargeCreditPurchaseDelete { + mutation := newChargeCreditPurchaseMutation(c.config, OpDelete) + return &ChargeCreditPurchaseDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ChargeCreditPurchaseClient) DeleteOne(_m *ChargeCreditPurchase) *ChargeCreditPurchaseDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ChargeCreditPurchaseClient) DeleteOneID(id string) *ChargeCreditPurchaseDeleteOne { + builder := c.Delete().Where(chargecreditpurchase.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ChargeCreditPurchaseDeleteOne{builder} +} + +// Query returns a query builder for ChargeCreditPurchase. +func (c *ChargeCreditPurchaseClient) Query() *ChargeCreditPurchaseQuery { + return &ChargeCreditPurchaseQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeChargeCreditPurchase}, + inters: c.Interceptors(), + } +} + +// Get returns a ChargeCreditPurchase entity by its id. +func (c *ChargeCreditPurchaseClient) Get(ctx context.Context, id string) (*ChargeCreditPurchase, error) { + return c.Query().Where(chargecreditpurchase.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ChargeCreditPurchaseClient) GetX(ctx context.Context, id string) *ChargeCreditPurchase { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryExternalPayment queries the external_payment edge of a ChargeCreditPurchase. +func (c *ChargeCreditPurchaseClient) QueryExternalPayment(_m *ChargeCreditPurchase) *ChargeCreditPurchaseExternalPaymentQuery { + query := (&ChargeCreditPurchaseExternalPaymentClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargecreditpurchase.Table, chargecreditpurchase.FieldID, id), + sqlgraph.To(chargecreditpurchaseexternalpayment.Table, chargecreditpurchaseexternalpayment.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargecreditpurchase.ExternalPaymentTable, chargecreditpurchase.ExternalPaymentColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryInvoicedPayment queries the invoiced_payment edge of a ChargeCreditPurchase. +func (c *ChargeCreditPurchaseClient) QueryInvoicedPayment(_m *ChargeCreditPurchase) *ChargeCreditPurchaseInvoicedPaymentQuery { + query := (&ChargeCreditPurchaseInvoicedPaymentClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargecreditpurchase.Table, chargecreditpurchase.FieldID, id), + sqlgraph.To(chargecreditpurchaseinvoicedpayment.Table, chargecreditpurchaseinvoicedpayment.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargecreditpurchase.InvoicedPaymentTable, chargecreditpurchase.InvoicedPaymentColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCreditGrant queries the credit_grant edge of a ChargeCreditPurchase. +func (c *ChargeCreditPurchaseClient) QueryCreditGrant(_m *ChargeCreditPurchase) *ChargeCreditPurchaseCreditGrantQuery { + query := (&ChargeCreditPurchaseCreditGrantClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargecreditpurchase.Table, chargecreditpurchase.FieldID, id), + sqlgraph.To(chargecreditpurchasecreditgrant.Table, chargecreditpurchasecreditgrant.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargecreditpurchase.CreditGrantTable, chargecreditpurchase.CreditGrantColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCharge queries the charge edge of a ChargeCreditPurchase. +func (c *ChargeCreditPurchaseClient) QueryCharge(_m *ChargeCreditPurchase) *ChargeQuery { + query := (&ChargeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargecreditpurchase.Table, chargecreditpurchase.FieldID, id), + sqlgraph.To(charge.Table, charge.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargecreditpurchase.ChargeTable, chargecreditpurchase.ChargeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubscription queries the subscription edge of a ChargeCreditPurchase. +func (c *ChargeCreditPurchaseClient) QuerySubscription(_m *ChargeCreditPurchase) *SubscriptionQuery { + query := (&SubscriptionClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargecreditpurchase.Table, chargecreditpurchase.FieldID, id), + sqlgraph.To(subscription.Table, subscription.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargecreditpurchase.SubscriptionTable, chargecreditpurchase.SubscriptionColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubscriptionPhase queries the subscription_phase edge of a ChargeCreditPurchase. +func (c *ChargeCreditPurchaseClient) QuerySubscriptionPhase(_m *ChargeCreditPurchase) *SubscriptionPhaseQuery { + query := (&SubscriptionPhaseClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargecreditpurchase.Table, chargecreditpurchase.FieldID, id), + sqlgraph.To(subscriptionphase.Table, subscriptionphase.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargecreditpurchase.SubscriptionPhaseTable, chargecreditpurchase.SubscriptionPhaseColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubscriptionItem queries the subscription_item edge of a ChargeCreditPurchase. +func (c *ChargeCreditPurchaseClient) QuerySubscriptionItem(_m *ChargeCreditPurchase) *SubscriptionItemQuery { + query := (&SubscriptionItemClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargecreditpurchase.Table, chargecreditpurchase.FieldID, id), + sqlgraph.To(subscriptionitem.Table, subscriptionitem.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargecreditpurchase.SubscriptionItemTable, chargecreditpurchase.SubscriptionItemColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCustomer queries the customer edge of a ChargeCreditPurchase. +func (c *ChargeCreditPurchaseClient) QueryCustomer(_m *ChargeCreditPurchase) *CustomerQuery { + query := (&CustomerClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargecreditpurchase.Table, chargecreditpurchase.FieldID, id), + sqlgraph.To(customer.Table, customer.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargecreditpurchase.CustomerTable, chargecreditpurchase.CustomerColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryTaxCode queries the tax_code edge of a ChargeCreditPurchase. +func (c *ChargeCreditPurchaseClient) QueryTaxCode(_m *ChargeCreditPurchase) *TaxCodeQuery { + query := (&TaxCodeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargecreditpurchase.Table, chargecreditpurchase.FieldID, id), + sqlgraph.To(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargecreditpurchase.TaxCodeTable, chargecreditpurchase.TaxCodeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ChargeCreditPurchaseClient) Hooks() []Hook { + return c.hooks.ChargeCreditPurchase +} + +// Interceptors returns the client interceptors. +func (c *ChargeCreditPurchaseClient) Interceptors() []Interceptor { + return c.inters.ChargeCreditPurchase +} + +func (c *ChargeCreditPurchaseClient) mutate(ctx context.Context, m *ChargeCreditPurchaseMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ChargeCreditPurchaseCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ChargeCreditPurchaseUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ChargeCreditPurchaseUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ChargeCreditPurchaseDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown ChargeCreditPurchase mutation op: %q", m.Op()) + } +} + +// ChargeCreditPurchaseCreditGrantClient is a client for the ChargeCreditPurchaseCreditGrant schema. +type ChargeCreditPurchaseCreditGrantClient struct { + config +} + +// NewChargeCreditPurchaseCreditGrantClient returns a client for the ChargeCreditPurchaseCreditGrant from the given config. +func NewChargeCreditPurchaseCreditGrantClient(c config) *ChargeCreditPurchaseCreditGrantClient { + return &ChargeCreditPurchaseCreditGrantClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `chargecreditpurchasecreditgrant.Hooks(f(g(h())))`. +func (c *ChargeCreditPurchaseCreditGrantClient) Use(hooks ...Hook) { + c.hooks.ChargeCreditPurchaseCreditGrant = append(c.hooks.ChargeCreditPurchaseCreditGrant, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `chargecreditpurchasecreditgrant.Intercept(f(g(h())))`. +func (c *ChargeCreditPurchaseCreditGrantClient) Intercept(interceptors ...Interceptor) { + c.inters.ChargeCreditPurchaseCreditGrant = append(c.inters.ChargeCreditPurchaseCreditGrant, interceptors...) +} + +// Create returns a builder for creating a ChargeCreditPurchaseCreditGrant entity. +func (c *ChargeCreditPurchaseCreditGrantClient) Create() *ChargeCreditPurchaseCreditGrantCreate { + mutation := newChargeCreditPurchaseCreditGrantMutation(c.config, OpCreate) + return &ChargeCreditPurchaseCreditGrantCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ChargeCreditPurchaseCreditGrant entities. +func (c *ChargeCreditPurchaseCreditGrantClient) CreateBulk(builders ...*ChargeCreditPurchaseCreditGrantCreate) *ChargeCreditPurchaseCreditGrantCreateBulk { + return &ChargeCreditPurchaseCreditGrantCreateBulk{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 *ChargeCreditPurchaseCreditGrantClient) MapCreateBulk(slice any, setFunc func(*ChargeCreditPurchaseCreditGrantCreate, int)) *ChargeCreditPurchaseCreditGrantCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ChargeCreditPurchaseCreditGrantCreateBulk{err: fmt.Errorf("calling to ChargeCreditPurchaseCreditGrantClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ChargeCreditPurchaseCreditGrantCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ChargeCreditPurchaseCreditGrantCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ChargeCreditPurchaseCreditGrant. +func (c *ChargeCreditPurchaseCreditGrantClient) Update() *ChargeCreditPurchaseCreditGrantUpdate { + mutation := newChargeCreditPurchaseCreditGrantMutation(c.config, OpUpdate) + return &ChargeCreditPurchaseCreditGrantUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ChargeCreditPurchaseCreditGrantClient) UpdateOne(_m *ChargeCreditPurchaseCreditGrant) *ChargeCreditPurchaseCreditGrantUpdateOne { + mutation := newChargeCreditPurchaseCreditGrantMutation(c.config, OpUpdateOne, withChargeCreditPurchaseCreditGrant(_m)) + return &ChargeCreditPurchaseCreditGrantUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ChargeCreditPurchaseCreditGrantClient) UpdateOneID(id string) *ChargeCreditPurchaseCreditGrantUpdateOne { + mutation := newChargeCreditPurchaseCreditGrantMutation(c.config, OpUpdateOne, withChargeCreditPurchaseCreditGrantID(id)) + return &ChargeCreditPurchaseCreditGrantUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ChargeCreditPurchaseCreditGrant. +func (c *ChargeCreditPurchaseCreditGrantClient) Delete() *ChargeCreditPurchaseCreditGrantDelete { + mutation := newChargeCreditPurchaseCreditGrantMutation(c.config, OpDelete) + return &ChargeCreditPurchaseCreditGrantDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ChargeCreditPurchaseCreditGrantClient) DeleteOne(_m *ChargeCreditPurchaseCreditGrant) *ChargeCreditPurchaseCreditGrantDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ChargeCreditPurchaseCreditGrantClient) DeleteOneID(id string) *ChargeCreditPurchaseCreditGrantDeleteOne { + builder := c.Delete().Where(chargecreditpurchasecreditgrant.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ChargeCreditPurchaseCreditGrantDeleteOne{builder} +} + +// Query returns a query builder for ChargeCreditPurchaseCreditGrant. +func (c *ChargeCreditPurchaseCreditGrantClient) Query() *ChargeCreditPurchaseCreditGrantQuery { + return &ChargeCreditPurchaseCreditGrantQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeChargeCreditPurchaseCreditGrant}, + inters: c.Interceptors(), + } +} + +// Get returns a ChargeCreditPurchaseCreditGrant entity by its id. +func (c *ChargeCreditPurchaseCreditGrantClient) Get(ctx context.Context, id string) (*ChargeCreditPurchaseCreditGrant, error) { + return c.Query().Where(chargecreditpurchasecreditgrant.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ChargeCreditPurchaseCreditGrantClient) GetX(ctx context.Context, id string) *ChargeCreditPurchaseCreditGrant { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryCreditPurchase queries the credit_purchase edge of a ChargeCreditPurchaseCreditGrant. +func (c *ChargeCreditPurchaseCreditGrantClient) QueryCreditPurchase(_m *ChargeCreditPurchaseCreditGrant) *ChargeCreditPurchaseQuery { + query := (&ChargeCreditPurchaseClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargecreditpurchasecreditgrant.Table, chargecreditpurchasecreditgrant.FieldID, id), + sqlgraph.To(chargecreditpurchase.Table, chargecreditpurchase.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargecreditpurchasecreditgrant.CreditPurchaseTable, chargecreditpurchasecreditgrant.CreditPurchaseColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ChargeCreditPurchaseCreditGrantClient) Hooks() []Hook { + return c.hooks.ChargeCreditPurchaseCreditGrant +} + +// Interceptors returns the client interceptors. +func (c *ChargeCreditPurchaseCreditGrantClient) Interceptors() []Interceptor { + return c.inters.ChargeCreditPurchaseCreditGrant +} + +func (c *ChargeCreditPurchaseCreditGrantClient) mutate(ctx context.Context, m *ChargeCreditPurchaseCreditGrantMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ChargeCreditPurchaseCreditGrantCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ChargeCreditPurchaseCreditGrantUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ChargeCreditPurchaseCreditGrantUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ChargeCreditPurchaseCreditGrantDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown ChargeCreditPurchaseCreditGrant mutation op: %q", m.Op()) + } +} + +// ChargeCreditPurchaseExternalPaymentClient is a client for the ChargeCreditPurchaseExternalPayment schema. +type ChargeCreditPurchaseExternalPaymentClient struct { + config +} + +// NewChargeCreditPurchaseExternalPaymentClient returns a client for the ChargeCreditPurchaseExternalPayment from the given config. +func NewChargeCreditPurchaseExternalPaymentClient(c config) *ChargeCreditPurchaseExternalPaymentClient { + return &ChargeCreditPurchaseExternalPaymentClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `chargecreditpurchaseexternalpayment.Hooks(f(g(h())))`. +func (c *ChargeCreditPurchaseExternalPaymentClient) Use(hooks ...Hook) { + c.hooks.ChargeCreditPurchaseExternalPayment = append(c.hooks.ChargeCreditPurchaseExternalPayment, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `chargecreditpurchaseexternalpayment.Intercept(f(g(h())))`. +func (c *ChargeCreditPurchaseExternalPaymentClient) Intercept(interceptors ...Interceptor) { + c.inters.ChargeCreditPurchaseExternalPayment = append(c.inters.ChargeCreditPurchaseExternalPayment, interceptors...) +} + +// Create returns a builder for creating a ChargeCreditPurchaseExternalPayment entity. +func (c *ChargeCreditPurchaseExternalPaymentClient) Create() *ChargeCreditPurchaseExternalPaymentCreate { + mutation := newChargeCreditPurchaseExternalPaymentMutation(c.config, OpCreate) + return &ChargeCreditPurchaseExternalPaymentCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ChargeCreditPurchaseExternalPayment entities. +func (c *ChargeCreditPurchaseExternalPaymentClient) CreateBulk(builders ...*ChargeCreditPurchaseExternalPaymentCreate) *ChargeCreditPurchaseExternalPaymentCreateBulk { + return &ChargeCreditPurchaseExternalPaymentCreateBulk{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 *ChargeCreditPurchaseExternalPaymentClient) MapCreateBulk(slice any, setFunc func(*ChargeCreditPurchaseExternalPaymentCreate, int)) *ChargeCreditPurchaseExternalPaymentCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ChargeCreditPurchaseExternalPaymentCreateBulk{err: fmt.Errorf("calling to ChargeCreditPurchaseExternalPaymentClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ChargeCreditPurchaseExternalPaymentCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ChargeCreditPurchaseExternalPaymentCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ChargeCreditPurchaseExternalPayment. +func (c *ChargeCreditPurchaseExternalPaymentClient) Update() *ChargeCreditPurchaseExternalPaymentUpdate { + mutation := newChargeCreditPurchaseExternalPaymentMutation(c.config, OpUpdate) + return &ChargeCreditPurchaseExternalPaymentUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ChargeCreditPurchaseExternalPaymentClient) UpdateOne(_m *ChargeCreditPurchaseExternalPayment) *ChargeCreditPurchaseExternalPaymentUpdateOne { + mutation := newChargeCreditPurchaseExternalPaymentMutation(c.config, OpUpdateOne, withChargeCreditPurchaseExternalPayment(_m)) + return &ChargeCreditPurchaseExternalPaymentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ChargeCreditPurchaseExternalPaymentClient) UpdateOneID(id string) *ChargeCreditPurchaseExternalPaymentUpdateOne { + mutation := newChargeCreditPurchaseExternalPaymentMutation(c.config, OpUpdateOne, withChargeCreditPurchaseExternalPaymentID(id)) + return &ChargeCreditPurchaseExternalPaymentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ChargeCreditPurchaseExternalPayment. +func (c *ChargeCreditPurchaseExternalPaymentClient) Delete() *ChargeCreditPurchaseExternalPaymentDelete { + mutation := newChargeCreditPurchaseExternalPaymentMutation(c.config, OpDelete) + return &ChargeCreditPurchaseExternalPaymentDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ChargeCreditPurchaseExternalPaymentClient) DeleteOne(_m *ChargeCreditPurchaseExternalPayment) *ChargeCreditPurchaseExternalPaymentDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ChargeCreditPurchaseExternalPaymentClient) DeleteOneID(id string) *ChargeCreditPurchaseExternalPaymentDeleteOne { + builder := c.Delete().Where(chargecreditpurchaseexternalpayment.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ChargeCreditPurchaseExternalPaymentDeleteOne{builder} +} + +// Query returns a query builder for ChargeCreditPurchaseExternalPayment. +func (c *ChargeCreditPurchaseExternalPaymentClient) Query() *ChargeCreditPurchaseExternalPaymentQuery { + return &ChargeCreditPurchaseExternalPaymentQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeChargeCreditPurchaseExternalPayment}, + inters: c.Interceptors(), + } +} + +// Get returns a ChargeCreditPurchaseExternalPayment entity by its id. +func (c *ChargeCreditPurchaseExternalPaymentClient) Get(ctx context.Context, id string) (*ChargeCreditPurchaseExternalPayment, error) { + return c.Query().Where(chargecreditpurchaseexternalpayment.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ChargeCreditPurchaseExternalPaymentClient) GetX(ctx context.Context, id string) *ChargeCreditPurchaseExternalPayment { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryCreditPurchase queries the credit_purchase edge of a ChargeCreditPurchaseExternalPayment. +func (c *ChargeCreditPurchaseExternalPaymentClient) QueryCreditPurchase(_m *ChargeCreditPurchaseExternalPayment) *ChargeCreditPurchaseQuery { + query := (&ChargeCreditPurchaseClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargecreditpurchaseexternalpayment.Table, chargecreditpurchaseexternalpayment.FieldID, id), + sqlgraph.To(chargecreditpurchase.Table, chargecreditpurchase.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargecreditpurchaseexternalpayment.CreditPurchaseTable, chargecreditpurchaseexternalpayment.CreditPurchaseColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ChargeCreditPurchaseExternalPaymentClient) Hooks() []Hook { + return c.hooks.ChargeCreditPurchaseExternalPayment +} + +// Interceptors returns the client interceptors. +func (c *ChargeCreditPurchaseExternalPaymentClient) Interceptors() []Interceptor { + return c.inters.ChargeCreditPurchaseExternalPayment +} + +func (c *ChargeCreditPurchaseExternalPaymentClient) mutate(ctx context.Context, m *ChargeCreditPurchaseExternalPaymentMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ChargeCreditPurchaseExternalPaymentCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ChargeCreditPurchaseExternalPaymentUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ChargeCreditPurchaseExternalPaymentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ChargeCreditPurchaseExternalPaymentDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown ChargeCreditPurchaseExternalPayment mutation op: %q", m.Op()) + } +} + +// ChargeCreditPurchaseInvoicedPaymentClient is a client for the ChargeCreditPurchaseInvoicedPayment schema. +type ChargeCreditPurchaseInvoicedPaymentClient struct { + config +} + +// NewChargeCreditPurchaseInvoicedPaymentClient returns a client for the ChargeCreditPurchaseInvoicedPayment from the given config. +func NewChargeCreditPurchaseInvoicedPaymentClient(c config) *ChargeCreditPurchaseInvoicedPaymentClient { + return &ChargeCreditPurchaseInvoicedPaymentClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `chargecreditpurchaseinvoicedpayment.Hooks(f(g(h())))`. +func (c *ChargeCreditPurchaseInvoicedPaymentClient) Use(hooks ...Hook) { + c.hooks.ChargeCreditPurchaseInvoicedPayment = append(c.hooks.ChargeCreditPurchaseInvoicedPayment, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `chargecreditpurchaseinvoicedpayment.Intercept(f(g(h())))`. +func (c *ChargeCreditPurchaseInvoicedPaymentClient) Intercept(interceptors ...Interceptor) { + c.inters.ChargeCreditPurchaseInvoicedPayment = append(c.inters.ChargeCreditPurchaseInvoicedPayment, interceptors...) +} + +// Create returns a builder for creating a ChargeCreditPurchaseInvoicedPayment entity. +func (c *ChargeCreditPurchaseInvoicedPaymentClient) Create() *ChargeCreditPurchaseInvoicedPaymentCreate { + mutation := newChargeCreditPurchaseInvoicedPaymentMutation(c.config, OpCreate) + return &ChargeCreditPurchaseInvoicedPaymentCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ChargeCreditPurchaseInvoicedPayment entities. +func (c *ChargeCreditPurchaseInvoicedPaymentClient) CreateBulk(builders ...*ChargeCreditPurchaseInvoicedPaymentCreate) *ChargeCreditPurchaseInvoicedPaymentCreateBulk { + return &ChargeCreditPurchaseInvoicedPaymentCreateBulk{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 *ChargeCreditPurchaseInvoicedPaymentClient) MapCreateBulk(slice any, setFunc func(*ChargeCreditPurchaseInvoicedPaymentCreate, int)) *ChargeCreditPurchaseInvoicedPaymentCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ChargeCreditPurchaseInvoicedPaymentCreateBulk{err: fmt.Errorf("calling to ChargeCreditPurchaseInvoicedPaymentClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ChargeCreditPurchaseInvoicedPaymentCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ChargeCreditPurchaseInvoicedPaymentCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ChargeCreditPurchaseInvoicedPayment. +func (c *ChargeCreditPurchaseInvoicedPaymentClient) Update() *ChargeCreditPurchaseInvoicedPaymentUpdate { + mutation := newChargeCreditPurchaseInvoicedPaymentMutation(c.config, OpUpdate) + return &ChargeCreditPurchaseInvoicedPaymentUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ChargeCreditPurchaseInvoicedPaymentClient) UpdateOne(_m *ChargeCreditPurchaseInvoicedPayment) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + mutation := newChargeCreditPurchaseInvoicedPaymentMutation(c.config, OpUpdateOne, withChargeCreditPurchaseInvoicedPayment(_m)) + return &ChargeCreditPurchaseInvoicedPaymentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ChargeCreditPurchaseInvoicedPaymentClient) UpdateOneID(id string) *ChargeCreditPurchaseInvoicedPaymentUpdateOne { + mutation := newChargeCreditPurchaseInvoicedPaymentMutation(c.config, OpUpdateOne, withChargeCreditPurchaseInvoicedPaymentID(id)) + return &ChargeCreditPurchaseInvoicedPaymentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ChargeCreditPurchaseInvoicedPayment. +func (c *ChargeCreditPurchaseInvoicedPaymentClient) Delete() *ChargeCreditPurchaseInvoicedPaymentDelete { + mutation := newChargeCreditPurchaseInvoicedPaymentMutation(c.config, OpDelete) + return &ChargeCreditPurchaseInvoicedPaymentDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ChargeCreditPurchaseInvoicedPaymentClient) DeleteOne(_m *ChargeCreditPurchaseInvoicedPayment) *ChargeCreditPurchaseInvoicedPaymentDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ChargeCreditPurchaseInvoicedPaymentClient) DeleteOneID(id string) *ChargeCreditPurchaseInvoicedPaymentDeleteOne { + builder := c.Delete().Where(chargecreditpurchaseinvoicedpayment.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ChargeCreditPurchaseInvoicedPaymentDeleteOne{builder} +} + +// Query returns a query builder for ChargeCreditPurchaseInvoicedPayment. +func (c *ChargeCreditPurchaseInvoicedPaymentClient) Query() *ChargeCreditPurchaseInvoicedPaymentQuery { + return &ChargeCreditPurchaseInvoicedPaymentQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeChargeCreditPurchaseInvoicedPayment}, + inters: c.Interceptors(), + } +} + +// Get returns a ChargeCreditPurchaseInvoicedPayment entity by its id. +func (c *ChargeCreditPurchaseInvoicedPaymentClient) Get(ctx context.Context, id string) (*ChargeCreditPurchaseInvoicedPayment, error) { + return c.Query().Where(chargecreditpurchaseinvoicedpayment.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ChargeCreditPurchaseInvoicedPaymentClient) GetX(ctx context.Context, id string) *ChargeCreditPurchaseInvoicedPayment { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryBillingInvoiceLine queries the billing_invoice_line edge of a ChargeCreditPurchaseInvoicedPayment. +func (c *ChargeCreditPurchaseInvoicedPaymentClient) QueryBillingInvoiceLine(_m *ChargeCreditPurchaseInvoicedPayment) *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargecreditpurchaseinvoicedpayment.Table, chargecreditpurchaseinvoicedpayment.FieldID, id), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargecreditpurchaseinvoicedpayment.BillingInvoiceLineTable, chargecreditpurchaseinvoicedpayment.BillingInvoiceLineColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCreditPurchase queries the credit_purchase edge of a ChargeCreditPurchaseInvoicedPayment. +func (c *ChargeCreditPurchaseInvoicedPaymentClient) QueryCreditPurchase(_m *ChargeCreditPurchaseInvoicedPayment) *ChargeCreditPurchaseQuery { + query := (&ChargeCreditPurchaseClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargecreditpurchaseinvoicedpayment.Table, chargecreditpurchaseinvoicedpayment.FieldID, id), + sqlgraph.To(chargecreditpurchase.Table, chargecreditpurchase.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargecreditpurchaseinvoicedpayment.CreditPurchaseTable, chargecreditpurchaseinvoicedpayment.CreditPurchaseColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ChargeCreditPurchaseInvoicedPaymentClient) Hooks() []Hook { + return c.hooks.ChargeCreditPurchaseInvoicedPayment +} + +// Interceptors returns the client interceptors. +func (c *ChargeCreditPurchaseInvoicedPaymentClient) Interceptors() []Interceptor { + return c.inters.ChargeCreditPurchaseInvoicedPayment +} + +func (c *ChargeCreditPurchaseInvoicedPaymentClient) mutate(ctx context.Context, m *ChargeCreditPurchaseInvoicedPaymentMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ChargeCreditPurchaseInvoicedPaymentCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ChargeCreditPurchaseInvoicedPaymentUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ChargeCreditPurchaseInvoicedPaymentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ChargeCreditPurchaseInvoicedPaymentDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown ChargeCreditPurchaseInvoicedPayment mutation op: %q", m.Op()) + } +} + +// ChargeFlatFeeClient is a client for the ChargeFlatFee schema. +type ChargeFlatFeeClient struct { + config +} + +// NewChargeFlatFeeClient returns a client for the ChargeFlatFee from the given config. +func NewChargeFlatFeeClient(c config) *ChargeFlatFeeClient { + return &ChargeFlatFeeClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `chargeflatfee.Hooks(f(g(h())))`. +func (c *ChargeFlatFeeClient) Use(hooks ...Hook) { + c.hooks.ChargeFlatFee = append(c.hooks.ChargeFlatFee, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `chargeflatfee.Intercept(f(g(h())))`. +func (c *ChargeFlatFeeClient) Intercept(interceptors ...Interceptor) { + c.inters.ChargeFlatFee = append(c.inters.ChargeFlatFee, interceptors...) +} + +// Create returns a builder for creating a ChargeFlatFee entity. +func (c *ChargeFlatFeeClient) Create() *ChargeFlatFeeCreate { + mutation := newChargeFlatFeeMutation(c.config, OpCreate) + return &ChargeFlatFeeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ChargeFlatFee entities. +func (c *ChargeFlatFeeClient) CreateBulk(builders ...*ChargeFlatFeeCreate) *ChargeFlatFeeCreateBulk { + return &ChargeFlatFeeCreateBulk{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 *ChargeFlatFeeClient) MapCreateBulk(slice any, setFunc func(*ChargeFlatFeeCreate, int)) *ChargeFlatFeeCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ChargeFlatFeeCreateBulk{err: fmt.Errorf("calling to ChargeFlatFeeClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ChargeFlatFeeCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ChargeFlatFeeCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ChargeFlatFee. +func (c *ChargeFlatFeeClient) Update() *ChargeFlatFeeUpdate { + mutation := newChargeFlatFeeMutation(c.config, OpUpdate) + return &ChargeFlatFeeUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ChargeFlatFeeClient) UpdateOne(_m *ChargeFlatFee) *ChargeFlatFeeUpdateOne { + mutation := newChargeFlatFeeMutation(c.config, OpUpdateOne, withChargeFlatFee(_m)) + return &ChargeFlatFeeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ChargeFlatFeeClient) UpdateOneID(id string) *ChargeFlatFeeUpdateOne { + mutation := newChargeFlatFeeMutation(c.config, OpUpdateOne, withChargeFlatFeeID(id)) + return &ChargeFlatFeeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ChargeFlatFee. +func (c *ChargeFlatFeeClient) Delete() *ChargeFlatFeeDelete { + mutation := newChargeFlatFeeMutation(c.config, OpDelete) + return &ChargeFlatFeeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ChargeFlatFeeClient) DeleteOne(_m *ChargeFlatFee) *ChargeFlatFeeDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ChargeFlatFeeClient) DeleteOneID(id string) *ChargeFlatFeeDeleteOne { + builder := c.Delete().Where(chargeflatfee.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ChargeFlatFeeDeleteOne{builder} +} + +// Query returns a query builder for ChargeFlatFee. +func (c *ChargeFlatFeeClient) Query() *ChargeFlatFeeQuery { + return &ChargeFlatFeeQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeChargeFlatFee}, + inters: c.Interceptors(), + } +} + +// Get returns a ChargeFlatFee entity by its id. +func (c *ChargeFlatFeeClient) Get(ctx context.Context, id string) (*ChargeFlatFee, error) { + return c.Query().Where(chargeflatfee.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ChargeFlatFeeClient) GetX(ctx context.Context, id string) *ChargeFlatFee { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryRuns queries the runs edge of a ChargeFlatFee. +func (c *ChargeFlatFeeClient) QueryRuns(_m *ChargeFlatFee) *ChargeFlatFeeRunQuery { + query := (&ChargeFlatFeeRunClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfee.Table, chargeflatfee.FieldID, id), + sqlgraph.To(chargeflatfeerun.Table, chargeflatfeerun.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, chargeflatfee.RunsTable, chargeflatfee.RunsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCurrentRun queries the current_run edge of a ChargeFlatFee. +func (c *ChargeFlatFeeClient) QueryCurrentRun(_m *ChargeFlatFee) *ChargeFlatFeeRunQuery { + query := (&ChargeFlatFeeRunClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfee.Table, chargeflatfee.FieldID, id), + sqlgraph.To(chargeflatfeerun.Table, chargeflatfeerun.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, chargeflatfee.CurrentRunTable, chargeflatfee.CurrentRunColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCharge queries the charge edge of a ChargeFlatFee. +func (c *ChargeFlatFeeClient) QueryCharge(_m *ChargeFlatFee) *ChargeQuery { + query := (&ChargeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfee.Table, chargeflatfee.FieldID, id), + sqlgraph.To(charge.Table, charge.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargeflatfee.ChargeTable, chargeflatfee.ChargeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryIntentOverride queries the intent_override edge of a ChargeFlatFee. +func (c *ChargeFlatFeeClient) QueryIntentOverride(_m *ChargeFlatFee) *ChargeFlatFeeOverrideQuery { + query := (&ChargeFlatFeeOverrideClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfee.Table, chargeflatfee.FieldID, id), + sqlgraph.To(chargeflatfeeoverride.Table, chargeflatfeeoverride.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargeflatfee.IntentOverrideTable, chargeflatfee.IntentOverrideColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubscription queries the subscription edge of a ChargeFlatFee. +func (c *ChargeFlatFeeClient) QuerySubscription(_m *ChargeFlatFee) *SubscriptionQuery { + query := (&SubscriptionClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfee.Table, chargeflatfee.FieldID, id), + sqlgraph.To(subscription.Table, subscription.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfee.SubscriptionTable, chargeflatfee.SubscriptionColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubscriptionPhase queries the subscription_phase edge of a ChargeFlatFee. +func (c *ChargeFlatFeeClient) QuerySubscriptionPhase(_m *ChargeFlatFee) *SubscriptionPhaseQuery { + query := (&SubscriptionPhaseClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfee.Table, chargeflatfee.FieldID, id), + sqlgraph.To(subscriptionphase.Table, subscriptionphase.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfee.SubscriptionPhaseTable, chargeflatfee.SubscriptionPhaseColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubscriptionItem queries the subscription_item edge of a ChargeFlatFee. +func (c *ChargeFlatFeeClient) QuerySubscriptionItem(_m *ChargeFlatFee) *SubscriptionItemQuery { + query := (&SubscriptionItemClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfee.Table, chargeflatfee.FieldID, id), + sqlgraph.To(subscriptionitem.Table, subscriptionitem.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfee.SubscriptionItemTable, chargeflatfee.SubscriptionItemColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCustomer queries the customer edge of a ChargeFlatFee. +func (c *ChargeFlatFeeClient) QueryCustomer(_m *ChargeFlatFee) *CustomerQuery { + query := (&CustomerClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfee.Table, chargeflatfee.FieldID, id), + sqlgraph.To(customer.Table, customer.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfee.CustomerTable, chargeflatfee.CustomerColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryFeature queries the feature edge of a ChargeFlatFee. +func (c *ChargeFlatFeeClient) QueryFeature(_m *ChargeFlatFee) *FeatureQuery { + query := (&FeatureClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfee.Table, chargeflatfee.FieldID, id), + sqlgraph.To(dbfeature.Table, dbfeature.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfee.FeatureTable, chargeflatfee.FeatureColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryTaxCode queries the tax_code edge of a ChargeFlatFee. +func (c *ChargeFlatFeeClient) QueryTaxCode(_m *ChargeFlatFee) *TaxCodeQuery { + query := (&TaxCodeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfee.Table, chargeflatfee.FieldID, id), + sqlgraph.To(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfee.TaxCodeTable, chargeflatfee.TaxCodeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ChargeFlatFeeClient) Hooks() []Hook { + return c.hooks.ChargeFlatFee +} + +// Interceptors returns the client interceptors. +func (c *ChargeFlatFeeClient) Interceptors() []Interceptor { + return c.inters.ChargeFlatFee +} + +func (c *ChargeFlatFeeClient) mutate(ctx context.Context, m *ChargeFlatFeeMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ChargeFlatFeeCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ChargeFlatFeeUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ChargeFlatFeeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ChargeFlatFeeDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown ChargeFlatFee mutation op: %q", m.Op()) + } +} + +// ChargeFlatFeeOverrideClient is a client for the ChargeFlatFeeOverride schema. +type ChargeFlatFeeOverrideClient struct { + config +} + +// NewChargeFlatFeeOverrideClient returns a client for the ChargeFlatFeeOverride from the given config. +func NewChargeFlatFeeOverrideClient(c config) *ChargeFlatFeeOverrideClient { + return &ChargeFlatFeeOverrideClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `chargeflatfeeoverride.Hooks(f(g(h())))`. +func (c *ChargeFlatFeeOverrideClient) Use(hooks ...Hook) { + c.hooks.ChargeFlatFeeOverride = append(c.hooks.ChargeFlatFeeOverride, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `chargeflatfeeoverride.Intercept(f(g(h())))`. +func (c *ChargeFlatFeeOverrideClient) Intercept(interceptors ...Interceptor) { + c.inters.ChargeFlatFeeOverride = append(c.inters.ChargeFlatFeeOverride, interceptors...) +} + +// Create returns a builder for creating a ChargeFlatFeeOverride entity. +func (c *ChargeFlatFeeOverrideClient) Create() *ChargeFlatFeeOverrideCreate { + mutation := newChargeFlatFeeOverrideMutation(c.config, OpCreate) + return &ChargeFlatFeeOverrideCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ChargeFlatFeeOverride entities. +func (c *ChargeFlatFeeOverrideClient) CreateBulk(builders ...*ChargeFlatFeeOverrideCreate) *ChargeFlatFeeOverrideCreateBulk { + return &ChargeFlatFeeOverrideCreateBulk{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 *ChargeFlatFeeOverrideClient) MapCreateBulk(slice any, setFunc func(*ChargeFlatFeeOverrideCreate, int)) *ChargeFlatFeeOverrideCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ChargeFlatFeeOverrideCreateBulk{err: fmt.Errorf("calling to ChargeFlatFeeOverrideClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ChargeFlatFeeOverrideCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ChargeFlatFeeOverrideCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ChargeFlatFeeOverride. +func (c *ChargeFlatFeeOverrideClient) Update() *ChargeFlatFeeOverrideUpdate { + mutation := newChargeFlatFeeOverrideMutation(c.config, OpUpdate) + return &ChargeFlatFeeOverrideUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ChargeFlatFeeOverrideClient) UpdateOne(_m *ChargeFlatFeeOverride) *ChargeFlatFeeOverrideUpdateOne { + mutation := newChargeFlatFeeOverrideMutation(c.config, OpUpdateOne, withChargeFlatFeeOverride(_m)) + return &ChargeFlatFeeOverrideUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ChargeFlatFeeOverrideClient) UpdateOneID(id string) *ChargeFlatFeeOverrideUpdateOne { + mutation := newChargeFlatFeeOverrideMutation(c.config, OpUpdateOne, withChargeFlatFeeOverrideID(id)) + return &ChargeFlatFeeOverrideUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ChargeFlatFeeOverride. +func (c *ChargeFlatFeeOverrideClient) Delete() *ChargeFlatFeeOverrideDelete { + mutation := newChargeFlatFeeOverrideMutation(c.config, OpDelete) + return &ChargeFlatFeeOverrideDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ChargeFlatFeeOverrideClient) DeleteOne(_m *ChargeFlatFeeOverride) *ChargeFlatFeeOverrideDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ChargeFlatFeeOverrideClient) DeleteOneID(id string) *ChargeFlatFeeOverrideDeleteOne { + builder := c.Delete().Where(chargeflatfeeoverride.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ChargeFlatFeeOverrideDeleteOne{builder} +} + +// Query returns a query builder for ChargeFlatFeeOverride. +func (c *ChargeFlatFeeOverrideClient) Query() *ChargeFlatFeeOverrideQuery { + return &ChargeFlatFeeOverrideQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeChargeFlatFeeOverride}, + inters: c.Interceptors(), + } +} + +// Get returns a ChargeFlatFeeOverride entity by its id. +func (c *ChargeFlatFeeOverrideClient) Get(ctx context.Context, id string) (*ChargeFlatFeeOverride, error) { + return c.Query().Where(chargeflatfeeoverride.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ChargeFlatFeeOverrideClient) GetX(ctx context.Context, id string) *ChargeFlatFeeOverride { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryFlatFee queries the flat_fee edge of a ChargeFlatFeeOverride. +func (c *ChargeFlatFeeOverrideClient) QueryFlatFee(_m *ChargeFlatFeeOverride) *ChargeFlatFeeQuery { + query := (&ChargeFlatFeeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfeeoverride.Table, chargeflatfeeoverride.FieldID, id), + sqlgraph.To(chargeflatfee.Table, chargeflatfee.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargeflatfeeoverride.FlatFeeTable, chargeflatfeeoverride.FlatFeeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryTaxCode queries the tax_code edge of a ChargeFlatFeeOverride. +func (c *ChargeFlatFeeOverrideClient) QueryTaxCode(_m *ChargeFlatFeeOverride) *TaxCodeQuery { + query := (&TaxCodeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfeeoverride.Table, chargeflatfeeoverride.FieldID, id), + sqlgraph.To(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfeeoverride.TaxCodeTable, chargeflatfeeoverride.TaxCodeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ChargeFlatFeeOverrideClient) Hooks() []Hook { + return c.hooks.ChargeFlatFeeOverride +} + +// Interceptors returns the client interceptors. +func (c *ChargeFlatFeeOverrideClient) Interceptors() []Interceptor { + return c.inters.ChargeFlatFeeOverride +} + +func (c *ChargeFlatFeeOverrideClient) mutate(ctx context.Context, m *ChargeFlatFeeOverrideMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ChargeFlatFeeOverrideCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ChargeFlatFeeOverrideUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ChargeFlatFeeOverrideUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ChargeFlatFeeOverrideDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown ChargeFlatFeeOverride mutation op: %q", m.Op()) + } +} + +// ChargeFlatFeeRunClient is a client for the ChargeFlatFeeRun schema. +type ChargeFlatFeeRunClient struct { + config +} + +// NewChargeFlatFeeRunClient returns a client for the ChargeFlatFeeRun from the given config. +func NewChargeFlatFeeRunClient(c config) *ChargeFlatFeeRunClient { + return &ChargeFlatFeeRunClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `chargeflatfeerun.Hooks(f(g(h())))`. +func (c *ChargeFlatFeeRunClient) Use(hooks ...Hook) { + c.hooks.ChargeFlatFeeRun = append(c.hooks.ChargeFlatFeeRun, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `chargeflatfeerun.Intercept(f(g(h())))`. +func (c *ChargeFlatFeeRunClient) Intercept(interceptors ...Interceptor) { + c.inters.ChargeFlatFeeRun = append(c.inters.ChargeFlatFeeRun, interceptors...) +} + +// Create returns a builder for creating a ChargeFlatFeeRun entity. +func (c *ChargeFlatFeeRunClient) Create() *ChargeFlatFeeRunCreate { + mutation := newChargeFlatFeeRunMutation(c.config, OpCreate) + return &ChargeFlatFeeRunCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ChargeFlatFeeRun entities. +func (c *ChargeFlatFeeRunClient) CreateBulk(builders ...*ChargeFlatFeeRunCreate) *ChargeFlatFeeRunCreateBulk { + return &ChargeFlatFeeRunCreateBulk{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 *ChargeFlatFeeRunClient) MapCreateBulk(slice any, setFunc func(*ChargeFlatFeeRunCreate, int)) *ChargeFlatFeeRunCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ChargeFlatFeeRunCreateBulk{err: fmt.Errorf("calling to ChargeFlatFeeRunClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ChargeFlatFeeRunCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ChargeFlatFeeRunCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ChargeFlatFeeRun. +func (c *ChargeFlatFeeRunClient) Update() *ChargeFlatFeeRunUpdate { + mutation := newChargeFlatFeeRunMutation(c.config, OpUpdate) + return &ChargeFlatFeeRunUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ChargeFlatFeeRunClient) UpdateOne(_m *ChargeFlatFeeRun) *ChargeFlatFeeRunUpdateOne { + mutation := newChargeFlatFeeRunMutation(c.config, OpUpdateOne, withChargeFlatFeeRun(_m)) + return &ChargeFlatFeeRunUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ChargeFlatFeeRunClient) UpdateOneID(id string) *ChargeFlatFeeRunUpdateOne { + mutation := newChargeFlatFeeRunMutation(c.config, OpUpdateOne, withChargeFlatFeeRunID(id)) + return &ChargeFlatFeeRunUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ChargeFlatFeeRun. +func (c *ChargeFlatFeeRunClient) Delete() *ChargeFlatFeeRunDelete { + mutation := newChargeFlatFeeRunMutation(c.config, OpDelete) + return &ChargeFlatFeeRunDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ChargeFlatFeeRunClient) DeleteOne(_m *ChargeFlatFeeRun) *ChargeFlatFeeRunDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ChargeFlatFeeRunClient) DeleteOneID(id string) *ChargeFlatFeeRunDeleteOne { + builder := c.Delete().Where(chargeflatfeerun.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ChargeFlatFeeRunDeleteOne{builder} +} + +// Query returns a query builder for ChargeFlatFeeRun. +func (c *ChargeFlatFeeRunClient) Query() *ChargeFlatFeeRunQuery { + return &ChargeFlatFeeRunQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeChargeFlatFeeRun}, + inters: c.Interceptors(), + } +} + +// Get returns a ChargeFlatFeeRun entity by its id. +func (c *ChargeFlatFeeRunClient) Get(ctx context.Context, id string) (*ChargeFlatFeeRun, error) { + return c.Query().Where(chargeflatfeerun.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ChargeFlatFeeRunClient) GetX(ctx context.Context, id string) *ChargeFlatFeeRun { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryFlatFee queries the flat_fee edge of a ChargeFlatFeeRun. +func (c *ChargeFlatFeeRunClient) QueryFlatFee(_m *ChargeFlatFeeRun) *ChargeFlatFeeQuery { + query := (&ChargeFlatFeeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfeerun.Table, chargeflatfeerun.FieldID, id), + sqlgraph.To(chargeflatfee.Table, chargeflatfee.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfeerun.FlatFeeTable, chargeflatfeerun.FlatFeeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingInvoiceLine queries the billing_invoice_line edge of a ChargeFlatFeeRun. +func (c *ChargeFlatFeeRunClient) QueryBillingInvoiceLine(_m *ChargeFlatFeeRun) *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfeerun.Table, chargeflatfeerun.FieldID, id), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargeflatfeerun.BillingInvoiceLineTable, chargeflatfeerun.BillingInvoiceLineColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingInvoice queries the billing_invoice edge of a ChargeFlatFeeRun. +func (c *ChargeFlatFeeRunClient) QueryBillingInvoice(_m *ChargeFlatFeeRun) *BillingInvoiceQuery { + query := (&BillingInvoiceClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfeerun.Table, chargeflatfeerun.FieldID, id), + sqlgraph.To(billinginvoice.Table, billinginvoice.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfeerun.BillingInvoiceTable, chargeflatfeerun.BillingInvoiceColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCreditAllocations queries the credit_allocations edge of a ChargeFlatFeeRun. +func (c *ChargeFlatFeeRunClient) QueryCreditAllocations(_m *ChargeFlatFeeRun) *ChargeFlatFeeRunCreditAllocationsQuery { + query := (&ChargeFlatFeeRunCreditAllocationsClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfeerun.Table, chargeflatfeerun.FieldID, id), + sqlgraph.To(chargeflatfeeruncreditallocations.Table, chargeflatfeeruncreditallocations.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, chargeflatfeerun.CreditAllocationsTable, chargeflatfeerun.CreditAllocationsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryDetailedLines queries the detailed_lines edge of a ChargeFlatFeeRun. +func (c *ChargeFlatFeeRunClient) QueryDetailedLines(_m *ChargeFlatFeeRun) *ChargeFlatFeeRunDetailedLineQuery { + query := (&ChargeFlatFeeRunDetailedLineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfeerun.Table, chargeflatfeerun.FieldID, id), + sqlgraph.To(chargeflatfeerundetailedline.Table, chargeflatfeerundetailedline.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, chargeflatfeerun.DetailedLinesTable, chargeflatfeerun.DetailedLinesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryInvoicedUsage queries the invoiced_usage edge of a ChargeFlatFeeRun. +func (c *ChargeFlatFeeRunClient) QueryInvoicedUsage(_m *ChargeFlatFeeRun) *ChargeFlatFeeRunInvoicedUsageQuery { + query := (&ChargeFlatFeeRunInvoicedUsageClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfeerun.Table, chargeflatfeerun.FieldID, id), + sqlgraph.To(chargeflatfeeruninvoicedusage.Table, chargeflatfeeruninvoicedusage.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargeflatfeerun.InvoicedUsageTable, chargeflatfeerun.InvoicedUsageColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryPayment queries the payment edge of a ChargeFlatFeeRun. +func (c *ChargeFlatFeeRunClient) QueryPayment(_m *ChargeFlatFeeRun) *ChargeFlatFeeRunPaymentQuery { + query := (&ChargeFlatFeeRunPaymentClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfeerun.Table, chargeflatfeerun.FieldID, id), + sqlgraph.To(chargeflatfeerunpayment.Table, chargeflatfeerunpayment.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargeflatfeerun.PaymentTable, chargeflatfeerun.PaymentColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ChargeFlatFeeRunClient) Hooks() []Hook { + return c.hooks.ChargeFlatFeeRun +} + +// Interceptors returns the client interceptors. +func (c *ChargeFlatFeeRunClient) Interceptors() []Interceptor { + return c.inters.ChargeFlatFeeRun +} + +func (c *ChargeFlatFeeRunClient) mutate(ctx context.Context, m *ChargeFlatFeeRunMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ChargeFlatFeeRunCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ChargeFlatFeeRunUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ChargeFlatFeeRunUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ChargeFlatFeeRunDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown ChargeFlatFeeRun mutation op: %q", m.Op()) + } +} + +// ChargeFlatFeeRunCreditAllocationsClient is a client for the ChargeFlatFeeRunCreditAllocations schema. +type ChargeFlatFeeRunCreditAllocationsClient struct { + config +} + +// NewChargeFlatFeeRunCreditAllocationsClient returns a client for the ChargeFlatFeeRunCreditAllocations from the given config. +func NewChargeFlatFeeRunCreditAllocationsClient(c config) *ChargeFlatFeeRunCreditAllocationsClient { + return &ChargeFlatFeeRunCreditAllocationsClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `chargeflatfeeruncreditallocations.Hooks(f(g(h())))`. +func (c *ChargeFlatFeeRunCreditAllocationsClient) Use(hooks ...Hook) { + c.hooks.ChargeFlatFeeRunCreditAllocations = append(c.hooks.ChargeFlatFeeRunCreditAllocations, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `chargeflatfeeruncreditallocations.Intercept(f(g(h())))`. +func (c *ChargeFlatFeeRunCreditAllocationsClient) Intercept(interceptors ...Interceptor) { + c.inters.ChargeFlatFeeRunCreditAllocations = append(c.inters.ChargeFlatFeeRunCreditAllocations, interceptors...) +} + +// Create returns a builder for creating a ChargeFlatFeeRunCreditAllocations entity. +func (c *ChargeFlatFeeRunCreditAllocationsClient) Create() *ChargeFlatFeeRunCreditAllocationsCreate { + mutation := newChargeFlatFeeRunCreditAllocationsMutation(c.config, OpCreate) + return &ChargeFlatFeeRunCreditAllocationsCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ChargeFlatFeeRunCreditAllocations entities. +func (c *ChargeFlatFeeRunCreditAllocationsClient) CreateBulk(builders ...*ChargeFlatFeeRunCreditAllocationsCreate) *ChargeFlatFeeRunCreditAllocationsCreateBulk { + return &ChargeFlatFeeRunCreditAllocationsCreateBulk{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 *ChargeFlatFeeRunCreditAllocationsClient) MapCreateBulk(slice any, setFunc func(*ChargeFlatFeeRunCreditAllocationsCreate, int)) *ChargeFlatFeeRunCreditAllocationsCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ChargeFlatFeeRunCreditAllocationsCreateBulk{err: fmt.Errorf("calling to ChargeFlatFeeRunCreditAllocationsClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ChargeFlatFeeRunCreditAllocationsCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ChargeFlatFeeRunCreditAllocationsCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ChargeFlatFeeRunCreditAllocations. +func (c *ChargeFlatFeeRunCreditAllocationsClient) Update() *ChargeFlatFeeRunCreditAllocationsUpdate { + mutation := newChargeFlatFeeRunCreditAllocationsMutation(c.config, OpUpdate) + return &ChargeFlatFeeRunCreditAllocationsUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ChargeFlatFeeRunCreditAllocationsClient) UpdateOne(_m *ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + mutation := newChargeFlatFeeRunCreditAllocationsMutation(c.config, OpUpdateOne, withChargeFlatFeeRunCreditAllocations(_m)) + return &ChargeFlatFeeRunCreditAllocationsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ChargeFlatFeeRunCreditAllocationsClient) UpdateOneID(id string) *ChargeFlatFeeRunCreditAllocationsUpdateOne { + mutation := newChargeFlatFeeRunCreditAllocationsMutation(c.config, OpUpdateOne, withChargeFlatFeeRunCreditAllocationsID(id)) + return &ChargeFlatFeeRunCreditAllocationsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ChargeFlatFeeRunCreditAllocations. +func (c *ChargeFlatFeeRunCreditAllocationsClient) Delete() *ChargeFlatFeeRunCreditAllocationsDelete { + mutation := newChargeFlatFeeRunCreditAllocationsMutation(c.config, OpDelete) + return &ChargeFlatFeeRunCreditAllocationsDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ChargeFlatFeeRunCreditAllocationsClient) DeleteOne(_m *ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunCreditAllocationsDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ChargeFlatFeeRunCreditAllocationsClient) DeleteOneID(id string) *ChargeFlatFeeRunCreditAllocationsDeleteOne { + builder := c.Delete().Where(chargeflatfeeruncreditallocations.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ChargeFlatFeeRunCreditAllocationsDeleteOne{builder} +} + +// Query returns a query builder for ChargeFlatFeeRunCreditAllocations. +func (c *ChargeFlatFeeRunCreditAllocationsClient) Query() *ChargeFlatFeeRunCreditAllocationsQuery { + return &ChargeFlatFeeRunCreditAllocationsQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeChargeFlatFeeRunCreditAllocations}, + inters: c.Interceptors(), + } +} + +// Get returns a ChargeFlatFeeRunCreditAllocations entity by its id. +func (c *ChargeFlatFeeRunCreditAllocationsClient) Get(ctx context.Context, id string) (*ChargeFlatFeeRunCreditAllocations, error) { + return c.Query().Where(chargeflatfeeruncreditallocations.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ChargeFlatFeeRunCreditAllocationsClient) GetX(ctx context.Context, id string) *ChargeFlatFeeRunCreditAllocations { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryCorrections queries the corrections edge of a ChargeFlatFeeRunCreditAllocations. +func (c *ChargeFlatFeeRunCreditAllocationsClient) QueryCorrections(_m *ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunCreditAllocationsQuery { + query := (&ChargeFlatFeeRunCreditAllocationsClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfeeruncreditallocations.Table, chargeflatfeeruncreditallocations.FieldID, id), + sqlgraph.To(chargeflatfeeruncreditallocations.Table, chargeflatfeeruncreditallocations.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, chargeflatfeeruncreditallocations.CorrectionsTable, chargeflatfeeruncreditallocations.CorrectionsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryAllocation queries the allocation edge of a ChargeFlatFeeRunCreditAllocations. +func (c *ChargeFlatFeeRunCreditAllocationsClient) QueryAllocation(_m *ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunCreditAllocationsQuery { + query := (&ChargeFlatFeeRunCreditAllocationsClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfeeruncreditallocations.Table, chargeflatfeeruncreditallocations.FieldID, id), + sqlgraph.To(chargeflatfeeruncreditallocations.Table, chargeflatfeeruncreditallocations.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, chargeflatfeeruncreditallocations.AllocationTable, chargeflatfeeruncreditallocations.AllocationColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryRun queries the run edge of a ChargeFlatFeeRunCreditAllocations. +func (c *ChargeFlatFeeRunCreditAllocationsClient) QueryRun(_m *ChargeFlatFeeRunCreditAllocations) *ChargeFlatFeeRunQuery { + query := (&ChargeFlatFeeRunClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfeeruncreditallocations.Table, chargeflatfeeruncreditallocations.FieldID, id), + sqlgraph.To(chargeflatfeerun.Table, chargeflatfeerun.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfeeruncreditallocations.RunTable, chargeflatfeeruncreditallocations.RunColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingInvoiceLine queries the billing_invoice_line edge of a ChargeFlatFeeRunCreditAllocations. +func (c *ChargeFlatFeeRunCreditAllocationsClient) QueryBillingInvoiceLine(_m *ChargeFlatFeeRunCreditAllocations) *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfeeruncreditallocations.Table, chargeflatfeeruncreditallocations.FieldID, id), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfeeruncreditallocations.BillingInvoiceLineTable, chargeflatfeeruncreditallocations.BillingInvoiceLineColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ChargeFlatFeeRunCreditAllocationsClient) Hooks() []Hook { + return c.hooks.ChargeFlatFeeRunCreditAllocations +} + +// Interceptors returns the client interceptors. +func (c *ChargeFlatFeeRunCreditAllocationsClient) Interceptors() []Interceptor { + return c.inters.ChargeFlatFeeRunCreditAllocations +} + +func (c *ChargeFlatFeeRunCreditAllocationsClient) mutate(ctx context.Context, m *ChargeFlatFeeRunCreditAllocationsMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ChargeFlatFeeRunCreditAllocationsCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ChargeFlatFeeRunCreditAllocationsUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ChargeFlatFeeRunCreditAllocationsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ChargeFlatFeeRunCreditAllocationsDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown ChargeFlatFeeRunCreditAllocations mutation op: %q", m.Op()) + } +} + +// ChargeFlatFeeRunDetailedLineClient is a client for the ChargeFlatFeeRunDetailedLine schema. +type ChargeFlatFeeRunDetailedLineClient struct { + config +} + +// NewChargeFlatFeeRunDetailedLineClient returns a client for the ChargeFlatFeeRunDetailedLine from the given config. +func NewChargeFlatFeeRunDetailedLineClient(c config) *ChargeFlatFeeRunDetailedLineClient { + return &ChargeFlatFeeRunDetailedLineClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `chargeflatfeerundetailedline.Hooks(f(g(h())))`. +func (c *ChargeFlatFeeRunDetailedLineClient) Use(hooks ...Hook) { + c.hooks.ChargeFlatFeeRunDetailedLine = append(c.hooks.ChargeFlatFeeRunDetailedLine, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `chargeflatfeerundetailedline.Intercept(f(g(h())))`. +func (c *ChargeFlatFeeRunDetailedLineClient) Intercept(interceptors ...Interceptor) { + c.inters.ChargeFlatFeeRunDetailedLine = append(c.inters.ChargeFlatFeeRunDetailedLine, interceptors...) +} + +// Create returns a builder for creating a ChargeFlatFeeRunDetailedLine entity. +func (c *ChargeFlatFeeRunDetailedLineClient) Create() *ChargeFlatFeeRunDetailedLineCreate { + mutation := newChargeFlatFeeRunDetailedLineMutation(c.config, OpCreate) + return &ChargeFlatFeeRunDetailedLineCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ChargeFlatFeeRunDetailedLine entities. +func (c *ChargeFlatFeeRunDetailedLineClient) CreateBulk(builders ...*ChargeFlatFeeRunDetailedLineCreate) *ChargeFlatFeeRunDetailedLineCreateBulk { + return &ChargeFlatFeeRunDetailedLineCreateBulk{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 *ChargeFlatFeeRunDetailedLineClient) MapCreateBulk(slice any, setFunc func(*ChargeFlatFeeRunDetailedLineCreate, int)) *ChargeFlatFeeRunDetailedLineCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ChargeFlatFeeRunDetailedLineCreateBulk{err: fmt.Errorf("calling to ChargeFlatFeeRunDetailedLineClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ChargeFlatFeeRunDetailedLineCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ChargeFlatFeeRunDetailedLineCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ChargeFlatFeeRunDetailedLine. +func (c *ChargeFlatFeeRunDetailedLineClient) Update() *ChargeFlatFeeRunDetailedLineUpdate { + mutation := newChargeFlatFeeRunDetailedLineMutation(c.config, OpUpdate) + return &ChargeFlatFeeRunDetailedLineUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ChargeFlatFeeRunDetailedLineClient) UpdateOne(_m *ChargeFlatFeeRunDetailedLine) *ChargeFlatFeeRunDetailedLineUpdateOne { + mutation := newChargeFlatFeeRunDetailedLineMutation(c.config, OpUpdateOne, withChargeFlatFeeRunDetailedLine(_m)) + return &ChargeFlatFeeRunDetailedLineUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ChargeFlatFeeRunDetailedLineClient) UpdateOneID(id string) *ChargeFlatFeeRunDetailedLineUpdateOne { + mutation := newChargeFlatFeeRunDetailedLineMutation(c.config, OpUpdateOne, withChargeFlatFeeRunDetailedLineID(id)) + return &ChargeFlatFeeRunDetailedLineUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ChargeFlatFeeRunDetailedLine. +func (c *ChargeFlatFeeRunDetailedLineClient) Delete() *ChargeFlatFeeRunDetailedLineDelete { + mutation := newChargeFlatFeeRunDetailedLineMutation(c.config, OpDelete) + return &ChargeFlatFeeRunDetailedLineDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ChargeFlatFeeRunDetailedLineClient) DeleteOne(_m *ChargeFlatFeeRunDetailedLine) *ChargeFlatFeeRunDetailedLineDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ChargeFlatFeeRunDetailedLineClient) DeleteOneID(id string) *ChargeFlatFeeRunDetailedLineDeleteOne { + builder := c.Delete().Where(chargeflatfeerundetailedline.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ChargeFlatFeeRunDetailedLineDeleteOne{builder} +} + +// Query returns a query builder for ChargeFlatFeeRunDetailedLine. +func (c *ChargeFlatFeeRunDetailedLineClient) Query() *ChargeFlatFeeRunDetailedLineQuery { + return &ChargeFlatFeeRunDetailedLineQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeChargeFlatFeeRunDetailedLine}, + inters: c.Interceptors(), + } +} + +// Get returns a ChargeFlatFeeRunDetailedLine entity by its id. +func (c *ChargeFlatFeeRunDetailedLineClient) Get(ctx context.Context, id string) (*ChargeFlatFeeRunDetailedLine, error) { + return c.Query().Where(chargeflatfeerundetailedline.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ChargeFlatFeeRunDetailedLineClient) GetX(ctx context.Context, id string) *ChargeFlatFeeRunDetailedLine { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryRun queries the run edge of a ChargeFlatFeeRunDetailedLine. +func (c *ChargeFlatFeeRunDetailedLineClient) QueryRun(_m *ChargeFlatFeeRunDetailedLine) *ChargeFlatFeeRunQuery { + query := (&ChargeFlatFeeRunClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfeerundetailedline.Table, chargeflatfeerundetailedline.FieldID, id), + sqlgraph.To(chargeflatfeerun.Table, chargeflatfeerun.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeflatfeerundetailedline.RunTable, chargeflatfeerundetailedline.RunColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ChargeFlatFeeRunDetailedLineClient) Hooks() []Hook { + return c.hooks.ChargeFlatFeeRunDetailedLine +} + +// Interceptors returns the client interceptors. +func (c *ChargeFlatFeeRunDetailedLineClient) Interceptors() []Interceptor { + return c.inters.ChargeFlatFeeRunDetailedLine +} + +func (c *ChargeFlatFeeRunDetailedLineClient) mutate(ctx context.Context, m *ChargeFlatFeeRunDetailedLineMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ChargeFlatFeeRunDetailedLineCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ChargeFlatFeeRunDetailedLineUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ChargeFlatFeeRunDetailedLineUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ChargeFlatFeeRunDetailedLineDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown ChargeFlatFeeRunDetailedLine mutation op: %q", m.Op()) + } +} + +// ChargeFlatFeeRunInvoicedUsageClient is a client for the ChargeFlatFeeRunInvoicedUsage schema. +type ChargeFlatFeeRunInvoicedUsageClient struct { + config +} + +// NewChargeFlatFeeRunInvoicedUsageClient returns a client for the ChargeFlatFeeRunInvoicedUsage from the given config. +func NewChargeFlatFeeRunInvoicedUsageClient(c config) *ChargeFlatFeeRunInvoicedUsageClient { + return &ChargeFlatFeeRunInvoicedUsageClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `chargeflatfeeruninvoicedusage.Hooks(f(g(h())))`. +func (c *ChargeFlatFeeRunInvoicedUsageClient) Use(hooks ...Hook) { + c.hooks.ChargeFlatFeeRunInvoicedUsage = append(c.hooks.ChargeFlatFeeRunInvoicedUsage, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `chargeflatfeeruninvoicedusage.Intercept(f(g(h())))`. +func (c *ChargeFlatFeeRunInvoicedUsageClient) Intercept(interceptors ...Interceptor) { + c.inters.ChargeFlatFeeRunInvoicedUsage = append(c.inters.ChargeFlatFeeRunInvoicedUsage, interceptors...) +} + +// Create returns a builder for creating a ChargeFlatFeeRunInvoicedUsage entity. +func (c *ChargeFlatFeeRunInvoicedUsageClient) Create() *ChargeFlatFeeRunInvoicedUsageCreate { + mutation := newChargeFlatFeeRunInvoicedUsageMutation(c.config, OpCreate) + return &ChargeFlatFeeRunInvoicedUsageCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ChargeFlatFeeRunInvoicedUsage entities. +func (c *ChargeFlatFeeRunInvoicedUsageClient) CreateBulk(builders ...*ChargeFlatFeeRunInvoicedUsageCreate) *ChargeFlatFeeRunInvoicedUsageCreateBulk { + return &ChargeFlatFeeRunInvoicedUsageCreateBulk{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 *ChargeFlatFeeRunInvoicedUsageClient) MapCreateBulk(slice any, setFunc func(*ChargeFlatFeeRunInvoicedUsageCreate, int)) *ChargeFlatFeeRunInvoicedUsageCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ChargeFlatFeeRunInvoicedUsageCreateBulk{err: fmt.Errorf("calling to ChargeFlatFeeRunInvoicedUsageClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ChargeFlatFeeRunInvoicedUsageCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ChargeFlatFeeRunInvoicedUsageCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ChargeFlatFeeRunInvoicedUsage. +func (c *ChargeFlatFeeRunInvoicedUsageClient) Update() *ChargeFlatFeeRunInvoicedUsageUpdate { + mutation := newChargeFlatFeeRunInvoicedUsageMutation(c.config, OpUpdate) + return &ChargeFlatFeeRunInvoicedUsageUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ChargeFlatFeeRunInvoicedUsageClient) UpdateOne(_m *ChargeFlatFeeRunInvoicedUsage) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + mutation := newChargeFlatFeeRunInvoicedUsageMutation(c.config, OpUpdateOne, withChargeFlatFeeRunInvoicedUsage(_m)) + return &ChargeFlatFeeRunInvoicedUsageUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ChargeFlatFeeRunInvoicedUsageClient) UpdateOneID(id string) *ChargeFlatFeeRunInvoicedUsageUpdateOne { + mutation := newChargeFlatFeeRunInvoicedUsageMutation(c.config, OpUpdateOne, withChargeFlatFeeRunInvoicedUsageID(id)) + return &ChargeFlatFeeRunInvoicedUsageUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ChargeFlatFeeRunInvoicedUsage. +func (c *ChargeFlatFeeRunInvoicedUsageClient) Delete() *ChargeFlatFeeRunInvoicedUsageDelete { + mutation := newChargeFlatFeeRunInvoicedUsageMutation(c.config, OpDelete) + return &ChargeFlatFeeRunInvoicedUsageDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ChargeFlatFeeRunInvoicedUsageClient) DeleteOne(_m *ChargeFlatFeeRunInvoicedUsage) *ChargeFlatFeeRunInvoicedUsageDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ChargeFlatFeeRunInvoicedUsageClient) DeleteOneID(id string) *ChargeFlatFeeRunInvoicedUsageDeleteOne { + builder := c.Delete().Where(chargeflatfeeruninvoicedusage.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ChargeFlatFeeRunInvoicedUsageDeleteOne{builder} +} + +// Query returns a query builder for ChargeFlatFeeRunInvoicedUsage. +func (c *ChargeFlatFeeRunInvoicedUsageClient) Query() *ChargeFlatFeeRunInvoicedUsageQuery { + return &ChargeFlatFeeRunInvoicedUsageQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeChargeFlatFeeRunInvoicedUsage}, + inters: c.Interceptors(), + } +} + +// Get returns a ChargeFlatFeeRunInvoicedUsage entity by its id. +func (c *ChargeFlatFeeRunInvoicedUsageClient) Get(ctx context.Context, id string) (*ChargeFlatFeeRunInvoicedUsage, error) { + return c.Query().Where(chargeflatfeeruninvoicedusage.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ChargeFlatFeeRunInvoicedUsageClient) GetX(ctx context.Context, id string) *ChargeFlatFeeRunInvoicedUsage { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryRun queries the run edge of a ChargeFlatFeeRunInvoicedUsage. +func (c *ChargeFlatFeeRunInvoicedUsageClient) QueryRun(_m *ChargeFlatFeeRunInvoicedUsage) *ChargeFlatFeeRunQuery { + query := (&ChargeFlatFeeRunClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfeeruninvoicedusage.Table, chargeflatfeeruninvoicedusage.FieldID, id), + sqlgraph.To(chargeflatfeerun.Table, chargeflatfeerun.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargeflatfeeruninvoicedusage.RunTable, chargeflatfeeruninvoicedusage.RunColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ChargeFlatFeeRunInvoicedUsageClient) Hooks() []Hook { + return c.hooks.ChargeFlatFeeRunInvoicedUsage +} + +// Interceptors returns the client interceptors. +func (c *ChargeFlatFeeRunInvoicedUsageClient) Interceptors() []Interceptor { + return c.inters.ChargeFlatFeeRunInvoicedUsage +} + +func (c *ChargeFlatFeeRunInvoicedUsageClient) mutate(ctx context.Context, m *ChargeFlatFeeRunInvoicedUsageMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ChargeFlatFeeRunInvoicedUsageCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ChargeFlatFeeRunInvoicedUsageUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ChargeFlatFeeRunInvoicedUsageUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ChargeFlatFeeRunInvoicedUsageDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown ChargeFlatFeeRunInvoicedUsage mutation op: %q", m.Op()) + } +} + +// ChargeFlatFeeRunPaymentClient is a client for the ChargeFlatFeeRunPayment schema. +type ChargeFlatFeeRunPaymentClient struct { + config +} + +// NewChargeFlatFeeRunPaymentClient returns a client for the ChargeFlatFeeRunPayment from the given config. +func NewChargeFlatFeeRunPaymentClient(c config) *ChargeFlatFeeRunPaymentClient { + return &ChargeFlatFeeRunPaymentClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `chargeflatfeerunpayment.Hooks(f(g(h())))`. +func (c *ChargeFlatFeeRunPaymentClient) Use(hooks ...Hook) { + c.hooks.ChargeFlatFeeRunPayment = append(c.hooks.ChargeFlatFeeRunPayment, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `chargeflatfeerunpayment.Intercept(f(g(h())))`. +func (c *ChargeFlatFeeRunPaymentClient) Intercept(interceptors ...Interceptor) { + c.inters.ChargeFlatFeeRunPayment = append(c.inters.ChargeFlatFeeRunPayment, interceptors...) +} + +// Create returns a builder for creating a ChargeFlatFeeRunPayment entity. +func (c *ChargeFlatFeeRunPaymentClient) Create() *ChargeFlatFeeRunPaymentCreate { + mutation := newChargeFlatFeeRunPaymentMutation(c.config, OpCreate) + return &ChargeFlatFeeRunPaymentCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ChargeFlatFeeRunPayment entities. +func (c *ChargeFlatFeeRunPaymentClient) CreateBulk(builders ...*ChargeFlatFeeRunPaymentCreate) *ChargeFlatFeeRunPaymentCreateBulk { + return &ChargeFlatFeeRunPaymentCreateBulk{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 *ChargeFlatFeeRunPaymentClient) MapCreateBulk(slice any, setFunc func(*ChargeFlatFeeRunPaymentCreate, int)) *ChargeFlatFeeRunPaymentCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ChargeFlatFeeRunPaymentCreateBulk{err: fmt.Errorf("calling to ChargeFlatFeeRunPaymentClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ChargeFlatFeeRunPaymentCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ChargeFlatFeeRunPaymentCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ChargeFlatFeeRunPayment. +func (c *ChargeFlatFeeRunPaymentClient) Update() *ChargeFlatFeeRunPaymentUpdate { + mutation := newChargeFlatFeeRunPaymentMutation(c.config, OpUpdate) + return &ChargeFlatFeeRunPaymentUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ChargeFlatFeeRunPaymentClient) UpdateOne(_m *ChargeFlatFeeRunPayment) *ChargeFlatFeeRunPaymentUpdateOne { + mutation := newChargeFlatFeeRunPaymentMutation(c.config, OpUpdateOne, withChargeFlatFeeRunPayment(_m)) + return &ChargeFlatFeeRunPaymentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ChargeFlatFeeRunPaymentClient) UpdateOneID(id string) *ChargeFlatFeeRunPaymentUpdateOne { + mutation := newChargeFlatFeeRunPaymentMutation(c.config, OpUpdateOne, withChargeFlatFeeRunPaymentID(id)) + return &ChargeFlatFeeRunPaymentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ChargeFlatFeeRunPayment. +func (c *ChargeFlatFeeRunPaymentClient) Delete() *ChargeFlatFeeRunPaymentDelete { + mutation := newChargeFlatFeeRunPaymentMutation(c.config, OpDelete) + return &ChargeFlatFeeRunPaymentDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ChargeFlatFeeRunPaymentClient) DeleteOne(_m *ChargeFlatFeeRunPayment) *ChargeFlatFeeRunPaymentDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ChargeFlatFeeRunPaymentClient) DeleteOneID(id string) *ChargeFlatFeeRunPaymentDeleteOne { + builder := c.Delete().Where(chargeflatfeerunpayment.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ChargeFlatFeeRunPaymentDeleteOne{builder} +} + +// Query returns a query builder for ChargeFlatFeeRunPayment. +func (c *ChargeFlatFeeRunPaymentClient) Query() *ChargeFlatFeeRunPaymentQuery { + return &ChargeFlatFeeRunPaymentQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeChargeFlatFeeRunPayment}, + inters: c.Interceptors(), + } +} + +// Get returns a ChargeFlatFeeRunPayment entity by its id. +func (c *ChargeFlatFeeRunPaymentClient) Get(ctx context.Context, id string) (*ChargeFlatFeeRunPayment, error) { + return c.Query().Where(chargeflatfeerunpayment.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ChargeFlatFeeRunPaymentClient) GetX(ctx context.Context, id string) *ChargeFlatFeeRunPayment { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryBillingInvoiceLine queries the billing_invoice_line edge of a ChargeFlatFeeRunPayment. +func (c *ChargeFlatFeeRunPaymentClient) QueryBillingInvoiceLine(_m *ChargeFlatFeeRunPayment) *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfeerunpayment.Table, chargeflatfeerunpayment.FieldID, id), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargeflatfeerunpayment.BillingInvoiceLineTable, chargeflatfeerunpayment.BillingInvoiceLineColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryRun queries the run edge of a ChargeFlatFeeRunPayment. +func (c *ChargeFlatFeeRunPaymentClient) QueryRun(_m *ChargeFlatFeeRunPayment) *ChargeFlatFeeRunQuery { + query := (&ChargeFlatFeeRunClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeflatfeerunpayment.Table, chargeflatfeerunpayment.FieldID, id), + sqlgraph.To(chargeflatfeerun.Table, chargeflatfeerun.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargeflatfeerunpayment.RunTable, chargeflatfeerunpayment.RunColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ChargeFlatFeeRunPaymentClient) Hooks() []Hook { + return c.hooks.ChargeFlatFeeRunPayment +} + +// Interceptors returns the client interceptors. +func (c *ChargeFlatFeeRunPaymentClient) Interceptors() []Interceptor { + return c.inters.ChargeFlatFeeRunPayment +} + +func (c *ChargeFlatFeeRunPaymentClient) mutate(ctx context.Context, m *ChargeFlatFeeRunPaymentMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ChargeFlatFeeRunPaymentCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ChargeFlatFeeRunPaymentUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ChargeFlatFeeRunPaymentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ChargeFlatFeeRunPaymentDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown ChargeFlatFeeRunPayment mutation op: %q", m.Op()) + } +} + +// 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 +} + +// 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 +} + +// QueryDetailedLines queries the detailed_lines edge of a ChargeUsageBased. +func (c *ChargeUsageBasedClient) QueryDetailedLines(_m *ChargeUsageBased) *ChargeUsageBasedRunDetailedLineQuery { + query := (&ChargeUsageBasedRunDetailedLineClient{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(chargeusagebasedrundetailedline.Table, chargeusagebasedrundetailedline.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, chargeusagebased.DetailedLinesTable, chargeusagebased.DetailedLinesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCurrentRun queries the current_run edge of a ChargeUsageBased. +func (c *ChargeUsageBasedClient) QueryCurrentRun(_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.M2O, false, chargeusagebased.CurrentRunTable, chargeusagebased.CurrentRunColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// 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, false, chargeusagebased.ChargeTable, chargeusagebased.ChargeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryIntentOverride queries the intent_override edge of a ChargeUsageBased. +func (c *ChargeUsageBasedClient) QueryIntentOverride(_m *ChargeUsageBased) *ChargeUsageBasedOverrideQuery { + query := (&ChargeUsageBasedOverrideClient{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(chargeusagebasedoverride.Table, chargeusagebasedoverride.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargeusagebased.IntentOverrideTable, chargeusagebased.IntentOverrideColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubscription queries the subscription edge of a ChargeUsageBased. +func (c *ChargeUsageBasedClient) QuerySubscription(_m *ChargeUsageBased) *SubscriptionQuery { + query := (&SubscriptionClient{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(subscription.Table, subscription.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebased.SubscriptionTable, chargeusagebased.SubscriptionColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubscriptionPhase queries the subscription_phase edge of a ChargeUsageBased. +func (c *ChargeUsageBasedClient) QuerySubscriptionPhase(_m *ChargeUsageBased) *SubscriptionPhaseQuery { + query := (&SubscriptionPhaseClient{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(subscriptionphase.Table, subscriptionphase.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebased.SubscriptionPhaseTable, chargeusagebased.SubscriptionPhaseColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubscriptionItem queries the subscription_item edge of a ChargeUsageBased. +func (c *ChargeUsageBasedClient) QuerySubscriptionItem(_m *ChargeUsageBased) *SubscriptionItemQuery { + query := (&SubscriptionItemClient{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(subscriptionitem.Table, subscriptionitem.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebased.SubscriptionItemTable, chargeusagebased.SubscriptionItemColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCustomer queries the customer edge of a ChargeUsageBased. +func (c *ChargeUsageBasedClient) QueryCustomer(_m *ChargeUsageBased) *CustomerQuery { + query := (&CustomerClient{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(customer.Table, customer.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebased.CustomerTable, chargeusagebased.CustomerColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryFeature queries the feature edge of a ChargeUsageBased. +func (c *ChargeUsageBasedClient) QueryFeature(_m *ChargeUsageBased) *FeatureQuery { + query := (&FeatureClient{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(dbfeature.Table, dbfeature.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebased.FeatureTable, chargeusagebased.FeatureColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryTaxCode queries the tax_code edge of a ChargeUsageBased. +func (c *ChargeUsageBasedClient) QueryTaxCode(_m *ChargeUsageBased) *TaxCodeQuery { + query := (&TaxCodeClient{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(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebased.TaxCodeTable, chargeusagebased.TaxCodeColumn), + ) + 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()) + } +} + +// ChargeUsageBasedOverrideClient is a client for the ChargeUsageBasedOverride schema. +type ChargeUsageBasedOverrideClient struct { + config +} + +// NewChargeUsageBasedOverrideClient returns a client for the ChargeUsageBasedOverride from the given config. +func NewChargeUsageBasedOverrideClient(c config) *ChargeUsageBasedOverrideClient { + return &ChargeUsageBasedOverrideClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `chargeusagebasedoverride.Hooks(f(g(h())))`. +func (c *ChargeUsageBasedOverrideClient) Use(hooks ...Hook) { + c.hooks.ChargeUsageBasedOverride = append(c.hooks.ChargeUsageBasedOverride, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `chargeusagebasedoverride.Intercept(f(g(h())))`. +func (c *ChargeUsageBasedOverrideClient) Intercept(interceptors ...Interceptor) { + c.inters.ChargeUsageBasedOverride = append(c.inters.ChargeUsageBasedOverride, interceptors...) +} + +// Create returns a builder for creating a ChargeUsageBasedOverride entity. +func (c *ChargeUsageBasedOverrideClient) Create() *ChargeUsageBasedOverrideCreate { + mutation := newChargeUsageBasedOverrideMutation(c.config, OpCreate) + return &ChargeUsageBasedOverrideCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ChargeUsageBasedOverride entities. +func (c *ChargeUsageBasedOverrideClient) CreateBulk(builders ...*ChargeUsageBasedOverrideCreate) *ChargeUsageBasedOverrideCreateBulk { + return &ChargeUsageBasedOverrideCreateBulk{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 *ChargeUsageBasedOverrideClient) MapCreateBulk(slice any, setFunc func(*ChargeUsageBasedOverrideCreate, int)) *ChargeUsageBasedOverrideCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ChargeUsageBasedOverrideCreateBulk{err: fmt.Errorf("calling to ChargeUsageBasedOverrideClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ChargeUsageBasedOverrideCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ChargeUsageBasedOverrideCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ChargeUsageBasedOverride. +func (c *ChargeUsageBasedOverrideClient) Update() *ChargeUsageBasedOverrideUpdate { + mutation := newChargeUsageBasedOverrideMutation(c.config, OpUpdate) + return &ChargeUsageBasedOverrideUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ChargeUsageBasedOverrideClient) UpdateOne(_m *ChargeUsageBasedOverride) *ChargeUsageBasedOverrideUpdateOne { + mutation := newChargeUsageBasedOverrideMutation(c.config, OpUpdateOne, withChargeUsageBasedOverride(_m)) + return &ChargeUsageBasedOverrideUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ChargeUsageBasedOverrideClient) UpdateOneID(id string) *ChargeUsageBasedOverrideUpdateOne { + mutation := newChargeUsageBasedOverrideMutation(c.config, OpUpdateOne, withChargeUsageBasedOverrideID(id)) + return &ChargeUsageBasedOverrideUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ChargeUsageBasedOverride. +func (c *ChargeUsageBasedOverrideClient) Delete() *ChargeUsageBasedOverrideDelete { + mutation := newChargeUsageBasedOverrideMutation(c.config, OpDelete) + return &ChargeUsageBasedOverrideDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ChargeUsageBasedOverrideClient) DeleteOne(_m *ChargeUsageBasedOverride) *ChargeUsageBasedOverrideDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ChargeUsageBasedOverrideClient) DeleteOneID(id string) *ChargeUsageBasedOverrideDeleteOne { + builder := c.Delete().Where(chargeusagebasedoverride.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ChargeUsageBasedOverrideDeleteOne{builder} +} + +// Query returns a query builder for ChargeUsageBasedOverride. +func (c *ChargeUsageBasedOverrideClient) Query() *ChargeUsageBasedOverrideQuery { + return &ChargeUsageBasedOverrideQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeChargeUsageBasedOverride}, + inters: c.Interceptors(), + } +} + +// Get returns a ChargeUsageBasedOverride entity by its id. +func (c *ChargeUsageBasedOverrideClient) Get(ctx context.Context, id string) (*ChargeUsageBasedOverride, error) { + return c.Query().Where(chargeusagebasedoverride.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ChargeUsageBasedOverrideClient) GetX(ctx context.Context, id string) *ChargeUsageBasedOverride { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryUsageBased queries the usage_based edge of a ChargeUsageBasedOverride. +func (c *ChargeUsageBasedOverrideClient) QueryUsageBased(_m *ChargeUsageBasedOverride) *ChargeUsageBasedQuery { + query := (&ChargeUsageBasedClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebasedoverride.Table, chargeusagebasedoverride.FieldID, id), + sqlgraph.To(chargeusagebased.Table, chargeusagebased.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargeusagebasedoverride.UsageBasedTable, chargeusagebasedoverride.UsageBasedColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryTaxCode queries the tax_code edge of a ChargeUsageBasedOverride. +func (c *ChargeUsageBasedOverrideClient) QueryTaxCode(_m *ChargeUsageBasedOverride) *TaxCodeQuery { + query := (&TaxCodeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebasedoverride.Table, chargeusagebasedoverride.FieldID, id), + sqlgraph.To(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebasedoverride.TaxCodeTable, chargeusagebasedoverride.TaxCodeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ChargeUsageBasedOverrideClient) Hooks() []Hook { + return c.hooks.ChargeUsageBasedOverride +} + +// Interceptors returns the client interceptors. +func (c *ChargeUsageBasedOverrideClient) Interceptors() []Interceptor { + return c.inters.ChargeUsageBasedOverride +} + +func (c *ChargeUsageBasedOverrideClient) mutate(ctx context.Context, m *ChargeUsageBasedOverrideMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ChargeUsageBasedOverrideCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ChargeUsageBasedOverrideUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ChargeUsageBasedOverrideUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ChargeUsageBasedOverrideDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown ChargeUsageBasedOverride 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 +} + +// QueryCorrections queries the corrections edge of a ChargeUsageBasedRunCreditAllocations. +func (c *ChargeUsageBasedRunCreditAllocationsClient) QueryCorrections(_m *ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunCreditAllocationsQuery { + query := (&ChargeUsageBasedRunCreditAllocationsClient{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(chargeusagebasedruncreditallocations.Table, chargeusagebasedruncreditallocations.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, chargeusagebasedruncreditallocations.CorrectionsTable, chargeusagebasedruncreditallocations.CorrectionsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryAllocation queries the allocation edge of a ChargeUsageBasedRunCreditAllocations. +func (c *ChargeUsageBasedRunCreditAllocationsClient) QueryAllocation(_m *ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunCreditAllocationsQuery { + query := (&ChargeUsageBasedRunCreditAllocationsClient{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(chargeusagebasedruncreditallocations.Table, chargeusagebasedruncreditallocations.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, chargeusagebasedruncreditallocations.AllocationTable, chargeusagebasedruncreditallocations.AllocationColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// 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()) + } +} + +// ChargeUsageBasedRunDetailedLineClient is a client for the ChargeUsageBasedRunDetailedLine schema. +type ChargeUsageBasedRunDetailedLineClient struct { + config +} + +// NewChargeUsageBasedRunDetailedLineClient returns a client for the ChargeUsageBasedRunDetailedLine from the given config. +func NewChargeUsageBasedRunDetailedLineClient(c config) *ChargeUsageBasedRunDetailedLineClient { + return &ChargeUsageBasedRunDetailedLineClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `chargeusagebasedrundetailedline.Hooks(f(g(h())))`. +func (c *ChargeUsageBasedRunDetailedLineClient) Use(hooks ...Hook) { + c.hooks.ChargeUsageBasedRunDetailedLine = append(c.hooks.ChargeUsageBasedRunDetailedLine, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `chargeusagebasedrundetailedline.Intercept(f(g(h())))`. +func (c *ChargeUsageBasedRunDetailedLineClient) Intercept(interceptors ...Interceptor) { + c.inters.ChargeUsageBasedRunDetailedLine = append(c.inters.ChargeUsageBasedRunDetailedLine, interceptors...) +} + +// Create returns a builder for creating a ChargeUsageBasedRunDetailedLine entity. +func (c *ChargeUsageBasedRunDetailedLineClient) Create() *ChargeUsageBasedRunDetailedLineCreate { + mutation := newChargeUsageBasedRunDetailedLineMutation(c.config, OpCreate) + return &ChargeUsageBasedRunDetailedLineCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ChargeUsageBasedRunDetailedLine entities. +func (c *ChargeUsageBasedRunDetailedLineClient) CreateBulk(builders ...*ChargeUsageBasedRunDetailedLineCreate) *ChargeUsageBasedRunDetailedLineCreateBulk { + return &ChargeUsageBasedRunDetailedLineCreateBulk{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 *ChargeUsageBasedRunDetailedLineClient) MapCreateBulk(slice any, setFunc func(*ChargeUsageBasedRunDetailedLineCreate, int)) *ChargeUsageBasedRunDetailedLineCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ChargeUsageBasedRunDetailedLineCreateBulk{err: fmt.Errorf("calling to ChargeUsageBasedRunDetailedLineClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ChargeUsageBasedRunDetailedLineCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ChargeUsageBasedRunDetailedLineCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ChargeUsageBasedRunDetailedLine. +func (c *ChargeUsageBasedRunDetailedLineClient) Update() *ChargeUsageBasedRunDetailedLineUpdate { + mutation := newChargeUsageBasedRunDetailedLineMutation(c.config, OpUpdate) + return &ChargeUsageBasedRunDetailedLineUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ChargeUsageBasedRunDetailedLineClient) UpdateOne(_m *ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedRunDetailedLineUpdateOne { + mutation := newChargeUsageBasedRunDetailedLineMutation(c.config, OpUpdateOne, withChargeUsageBasedRunDetailedLine(_m)) + return &ChargeUsageBasedRunDetailedLineUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ChargeUsageBasedRunDetailedLineClient) UpdateOneID(id string) *ChargeUsageBasedRunDetailedLineUpdateOne { + mutation := newChargeUsageBasedRunDetailedLineMutation(c.config, OpUpdateOne, withChargeUsageBasedRunDetailedLineID(id)) + return &ChargeUsageBasedRunDetailedLineUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ChargeUsageBasedRunDetailedLine. +func (c *ChargeUsageBasedRunDetailedLineClient) Delete() *ChargeUsageBasedRunDetailedLineDelete { + mutation := newChargeUsageBasedRunDetailedLineMutation(c.config, OpDelete) + return &ChargeUsageBasedRunDetailedLineDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ChargeUsageBasedRunDetailedLineClient) DeleteOne(_m *ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedRunDetailedLineDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ChargeUsageBasedRunDetailedLineClient) DeleteOneID(id string) *ChargeUsageBasedRunDetailedLineDeleteOne { + builder := c.Delete().Where(chargeusagebasedrundetailedline.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ChargeUsageBasedRunDetailedLineDeleteOne{builder} +} + +// Query returns a query builder for ChargeUsageBasedRunDetailedLine. +func (c *ChargeUsageBasedRunDetailedLineClient) Query() *ChargeUsageBasedRunDetailedLineQuery { + return &ChargeUsageBasedRunDetailedLineQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeChargeUsageBasedRunDetailedLine}, + inters: c.Interceptors(), + } +} + +// Get returns a ChargeUsageBasedRunDetailedLine entity by its id. +func (c *ChargeUsageBasedRunDetailedLineClient) Get(ctx context.Context, id string) (*ChargeUsageBasedRunDetailedLine, error) { + return c.Query().Where(chargeusagebasedrundetailedline.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ChargeUsageBasedRunDetailedLineClient) GetX(ctx context.Context, id string) *ChargeUsageBasedRunDetailedLine { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryCharge queries the charge edge of a ChargeUsageBasedRunDetailedLine. +func (c *ChargeUsageBasedRunDetailedLineClient) QueryCharge(_m *ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedQuery { + query := (&ChargeUsageBasedClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebasedrundetailedline.Table, chargeusagebasedrundetailedline.FieldID, id), + sqlgraph.To(chargeusagebased.Table, chargeusagebased.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebasedrundetailedline.ChargeTable, chargeusagebasedrundetailedline.ChargeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryRun queries the run edge of a ChargeUsageBasedRunDetailedLine. +func (c *ChargeUsageBasedRunDetailedLineClient) QueryRun(_m *ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedRunsQuery { + query := (&ChargeUsageBasedRunsClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebasedrundetailedline.Table, chargeusagebasedrundetailedline.FieldID, id), + sqlgraph.To(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebasedrundetailedline.RunTable, chargeusagebasedrundetailedline.RunColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCorrectsRun queries the corrects_run edge of a ChargeUsageBasedRunDetailedLine. +func (c *ChargeUsageBasedRunDetailedLineClient) QueryCorrectsRun(_m *ChargeUsageBasedRunDetailedLine) *ChargeUsageBasedRunsQuery { + query := (&ChargeUsageBasedRunsClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebasedrundetailedline.Table, chargeusagebasedrundetailedline.FieldID, id), + sqlgraph.To(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebasedrundetailedline.CorrectsRunTable, chargeusagebasedrundetailedline.CorrectsRunColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ChargeUsageBasedRunDetailedLineClient) Hooks() []Hook { + return c.hooks.ChargeUsageBasedRunDetailedLine +} + +// Interceptors returns the client interceptors. +func (c *ChargeUsageBasedRunDetailedLineClient) Interceptors() []Interceptor { + return c.inters.ChargeUsageBasedRunDetailedLine +} + +func (c *ChargeUsageBasedRunDetailedLineClient) mutate(ctx context.Context, m *ChargeUsageBasedRunDetailedLineMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ChargeUsageBasedRunDetailedLineCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ChargeUsageBasedRunDetailedLineUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ChargeUsageBasedRunDetailedLineUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ChargeUsageBasedRunDetailedLineDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown ChargeUsageBasedRunDetailedLine 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 +} + +// QueryFeature queries the feature edge of a ChargeUsageBasedRuns. +func (c *ChargeUsageBasedRunsClient) QueryFeature(_m *ChargeUsageBasedRuns) *FeatureQuery { + query := (&FeatureClient{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(dbfeature.Table, dbfeature.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebasedruns.FeatureTable, chargeusagebasedruns.FeatureColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingInvoiceLine queries the billing_invoice_line edge of a ChargeUsageBasedRuns. +func (c *ChargeUsageBasedRunsClient) QueryBillingInvoiceLine(_m *ChargeUsageBasedRuns) *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{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(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargeusagebasedruns.BillingInvoiceLineTable, chargeusagebasedruns.BillingInvoiceLineColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingInvoice queries the billing_invoice edge of a ChargeUsageBasedRuns. +func (c *ChargeUsageBasedRunsClient) QueryBillingInvoice(_m *ChargeUsageBasedRuns) *BillingInvoiceQuery { + query := (&BillingInvoiceClient{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(billinginvoice.Table, billinginvoice.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebasedruns.BillingInvoiceTable, chargeusagebasedruns.BillingInvoiceColumn), + ) + 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 +} + +// QueryDetailedLines queries the detailed_lines edge of a ChargeUsageBasedRuns. +func (c *ChargeUsageBasedRunsClient) QueryDetailedLines(_m *ChargeUsageBasedRuns) *ChargeUsageBasedRunDetailedLineQuery { + query := (&ChargeUsageBasedRunDetailedLineClient{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(chargeusagebasedrundetailedline.Table, chargeusagebasedrundetailedline.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, chargeusagebasedruns.DetailedLinesTable, chargeusagebasedruns.DetailedLinesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCorrectedDetailedLines queries the corrected_detailed_lines edge of a ChargeUsageBasedRuns. +func (c *ChargeUsageBasedRunsClient) QueryCorrectedDetailedLines(_m *ChargeUsageBasedRuns) *ChargeUsageBasedRunDetailedLineQuery { + query := (&ChargeUsageBasedRunDetailedLineClient{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(chargeusagebasedrundetailedline.Table, chargeusagebasedrundetailedline.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, chargeusagebasedruns.CorrectedDetailedLinesTable, chargeusagebasedruns.CorrectedDetailedLinesColumn), + ) + 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()) + } +} + +// ChargesSearchV1Client is a client for the ChargesSearchV1 schema. +type ChargesSearchV1Client struct { + config +} + +// NewChargesSearchV1Client returns a client for the ChargesSearchV1 from the given config. +func NewChargesSearchV1Client(c config) *ChargesSearchV1Client { + return &ChargesSearchV1Client{config: c} +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `chargessearchv1.Intercept(f(g(h())))`. +func (c *ChargesSearchV1Client) Intercept(interceptors ...Interceptor) { + c.inters.ChargesSearchV1 = append(c.inters.ChargesSearchV1, interceptors...) +} + +// Query returns a query builder for ChargesSearchV1. +func (c *ChargesSearchV1Client) Query() *ChargesSearchV1Query { + return &ChargesSearchV1Query{ + config: c.config, + ctx: &QueryContext{Type: TypeChargesSearchV1}, + inters: c.Interceptors(), + } +} + +// Interceptors returns the client interceptors. +func (c *ChargesSearchV1Client) Interceptors() []Interceptor { + return c.inters.ChargesSearchV1 +} + +// CreditRealizationLineageClient is a client for the CreditRealizationLineage schema. +type CreditRealizationLineageClient struct { + config +} + +// NewCreditRealizationLineageClient returns a client for the CreditRealizationLineage from the given config. +func NewCreditRealizationLineageClient(c config) *CreditRealizationLineageClient { + return &CreditRealizationLineageClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `creditrealizationlineage.Hooks(f(g(h())))`. +func (c *CreditRealizationLineageClient) Use(hooks ...Hook) { + c.hooks.CreditRealizationLineage = append(c.hooks.CreditRealizationLineage, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `creditrealizationlineage.Intercept(f(g(h())))`. +func (c *CreditRealizationLineageClient) Intercept(interceptors ...Interceptor) { + c.inters.CreditRealizationLineage = append(c.inters.CreditRealizationLineage, interceptors...) +} + +// Create returns a builder for creating a CreditRealizationLineage entity. +func (c *CreditRealizationLineageClient) Create() *CreditRealizationLineageCreate { + mutation := newCreditRealizationLineageMutation(c.config, OpCreate) + return &CreditRealizationLineageCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of CreditRealizationLineage entities. +func (c *CreditRealizationLineageClient) CreateBulk(builders ...*CreditRealizationLineageCreate) *CreditRealizationLineageCreateBulk { + return &CreditRealizationLineageCreateBulk{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 *CreditRealizationLineageClient) MapCreateBulk(slice any, setFunc func(*CreditRealizationLineageCreate, int)) *CreditRealizationLineageCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &CreditRealizationLineageCreateBulk{err: fmt.Errorf("calling to CreditRealizationLineageClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*CreditRealizationLineageCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &CreditRealizationLineageCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for CreditRealizationLineage. +func (c *CreditRealizationLineageClient) Update() *CreditRealizationLineageUpdate { + mutation := newCreditRealizationLineageMutation(c.config, OpUpdate) + return &CreditRealizationLineageUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *CreditRealizationLineageClient) UpdateOne(_m *CreditRealizationLineage) *CreditRealizationLineageUpdateOne { + mutation := newCreditRealizationLineageMutation(c.config, OpUpdateOne, withCreditRealizationLineage(_m)) + return &CreditRealizationLineageUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *CreditRealizationLineageClient) UpdateOneID(id string) *CreditRealizationLineageUpdateOne { + mutation := newCreditRealizationLineageMutation(c.config, OpUpdateOne, withCreditRealizationLineageID(id)) + return &CreditRealizationLineageUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for CreditRealizationLineage. +func (c *CreditRealizationLineageClient) Delete() *CreditRealizationLineageDelete { + mutation := newCreditRealizationLineageMutation(c.config, OpDelete) + return &CreditRealizationLineageDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *CreditRealizationLineageClient) DeleteOne(_m *CreditRealizationLineage) *CreditRealizationLineageDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *CreditRealizationLineageClient) DeleteOneID(id string) *CreditRealizationLineageDeleteOne { + builder := c.Delete().Where(creditrealizationlineage.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &CreditRealizationLineageDeleteOne{builder} +} + +// Query returns a query builder for CreditRealizationLineage. +func (c *CreditRealizationLineageClient) Query() *CreditRealizationLineageQuery { + return &CreditRealizationLineageQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeCreditRealizationLineage}, + inters: c.Interceptors(), + } +} + +// Get returns a CreditRealizationLineage entity by its id. +func (c *CreditRealizationLineageClient) Get(ctx context.Context, id string) (*CreditRealizationLineage, error) { + return c.Query().Where(creditrealizationlineage.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *CreditRealizationLineageClient) GetX(ctx context.Context, id string) *CreditRealizationLineage { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryCharge queries the charge edge of a CreditRealizationLineage. +func (c *CreditRealizationLineageClient) QueryCharge(_m *CreditRealizationLineage) *ChargeQuery { + query := (&ChargeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(creditrealizationlineage.Table, creditrealizationlineage.FieldID, id), + sqlgraph.To(charge.Table, charge.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, creditrealizationlineage.ChargeTable, creditrealizationlineage.ChargeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySegments queries the segments edge of a CreditRealizationLineage. +func (c *CreditRealizationLineageClient) QuerySegments(_m *CreditRealizationLineage) *CreditRealizationLineageSegmentQuery { + query := (&CreditRealizationLineageSegmentClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(creditrealizationlineage.Table, creditrealizationlineage.FieldID, id), + sqlgraph.To(creditrealizationlineagesegment.Table, creditrealizationlineagesegment.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, creditrealizationlineage.SegmentsTable, creditrealizationlineage.SegmentsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *CreditRealizationLineageClient) Hooks() []Hook { + return c.hooks.CreditRealizationLineage +} + +// Interceptors returns the client interceptors. +func (c *CreditRealizationLineageClient) Interceptors() []Interceptor { + return c.inters.CreditRealizationLineage +} + +func (c *CreditRealizationLineageClient) mutate(ctx context.Context, m *CreditRealizationLineageMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&CreditRealizationLineageCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&CreditRealizationLineageUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&CreditRealizationLineageUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&CreditRealizationLineageDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown CreditRealizationLineage mutation op: %q", m.Op()) + } +} + +// CreditRealizationLineageSegmentClient is a client for the CreditRealizationLineageSegment schema. +type CreditRealizationLineageSegmentClient struct { + config +} + +// NewCreditRealizationLineageSegmentClient returns a client for the CreditRealizationLineageSegment from the given config. +func NewCreditRealizationLineageSegmentClient(c config) *CreditRealizationLineageSegmentClient { + return &CreditRealizationLineageSegmentClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `creditrealizationlineagesegment.Hooks(f(g(h())))`. +func (c *CreditRealizationLineageSegmentClient) Use(hooks ...Hook) { + c.hooks.CreditRealizationLineageSegment = append(c.hooks.CreditRealizationLineageSegment, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `creditrealizationlineagesegment.Intercept(f(g(h())))`. +func (c *CreditRealizationLineageSegmentClient) Intercept(interceptors ...Interceptor) { + c.inters.CreditRealizationLineageSegment = append(c.inters.CreditRealizationLineageSegment, interceptors...) +} + +// Create returns a builder for creating a CreditRealizationLineageSegment entity. +func (c *CreditRealizationLineageSegmentClient) Create() *CreditRealizationLineageSegmentCreate { + mutation := newCreditRealizationLineageSegmentMutation(c.config, OpCreate) + return &CreditRealizationLineageSegmentCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of CreditRealizationLineageSegment entities. +func (c *CreditRealizationLineageSegmentClient) CreateBulk(builders ...*CreditRealizationLineageSegmentCreate) *CreditRealizationLineageSegmentCreateBulk { + return &CreditRealizationLineageSegmentCreateBulk{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 *CreditRealizationLineageSegmentClient) MapCreateBulk(slice any, setFunc func(*CreditRealizationLineageSegmentCreate, int)) *CreditRealizationLineageSegmentCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &CreditRealizationLineageSegmentCreateBulk{err: fmt.Errorf("calling to CreditRealizationLineageSegmentClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*CreditRealizationLineageSegmentCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &CreditRealizationLineageSegmentCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for CreditRealizationLineageSegment. +func (c *CreditRealizationLineageSegmentClient) Update() *CreditRealizationLineageSegmentUpdate { + mutation := newCreditRealizationLineageSegmentMutation(c.config, OpUpdate) + return &CreditRealizationLineageSegmentUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *CreditRealizationLineageSegmentClient) UpdateOne(_m *CreditRealizationLineageSegment) *CreditRealizationLineageSegmentUpdateOne { + mutation := newCreditRealizationLineageSegmentMutation(c.config, OpUpdateOne, withCreditRealizationLineageSegment(_m)) + return &CreditRealizationLineageSegmentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *CreditRealizationLineageSegmentClient) UpdateOneID(id string) *CreditRealizationLineageSegmentUpdateOne { + mutation := newCreditRealizationLineageSegmentMutation(c.config, OpUpdateOne, withCreditRealizationLineageSegmentID(id)) + return &CreditRealizationLineageSegmentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for CreditRealizationLineageSegment. +func (c *CreditRealizationLineageSegmentClient) Delete() *CreditRealizationLineageSegmentDelete { + mutation := newCreditRealizationLineageSegmentMutation(c.config, OpDelete) + return &CreditRealizationLineageSegmentDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *CreditRealizationLineageSegmentClient) DeleteOne(_m *CreditRealizationLineageSegment) *CreditRealizationLineageSegmentDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *CreditRealizationLineageSegmentClient) DeleteOneID(id string) *CreditRealizationLineageSegmentDeleteOne { + builder := c.Delete().Where(creditrealizationlineagesegment.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &CreditRealizationLineageSegmentDeleteOne{builder} +} + +// Query returns a query builder for CreditRealizationLineageSegment. +func (c *CreditRealizationLineageSegmentClient) Query() *CreditRealizationLineageSegmentQuery { + return &CreditRealizationLineageSegmentQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeCreditRealizationLineageSegment}, + inters: c.Interceptors(), + } +} + +// Get returns a CreditRealizationLineageSegment entity by its id. +func (c *CreditRealizationLineageSegmentClient) Get(ctx context.Context, id string) (*CreditRealizationLineageSegment, error) { + return c.Query().Where(creditrealizationlineagesegment.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *CreditRealizationLineageSegmentClient) GetX(ctx context.Context, id string) *CreditRealizationLineageSegment { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryLineage queries the lineage edge of a CreditRealizationLineageSegment. +func (c *CreditRealizationLineageSegmentClient) QueryLineage(_m *CreditRealizationLineageSegment) *CreditRealizationLineageQuery { + query := (&CreditRealizationLineageClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(creditrealizationlineagesegment.Table, creditrealizationlineagesegment.FieldID, id), + sqlgraph.To(creditrealizationlineage.Table, creditrealizationlineage.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, creditrealizationlineagesegment.LineageTable, creditrealizationlineagesegment.LineageColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *CreditRealizationLineageSegmentClient) Hooks() []Hook { + return c.hooks.CreditRealizationLineageSegment +} + +// Interceptors returns the client interceptors. +func (c *CreditRealizationLineageSegmentClient) Interceptors() []Interceptor { + return c.inters.CreditRealizationLineageSegment +} + +func (c *CreditRealizationLineageSegmentClient) mutate(ctx context.Context, m *CreditRealizationLineageSegmentMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&CreditRealizationLineageSegmentCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&CreditRealizationLineageSegmentUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&CreditRealizationLineageSegmentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&CreditRealizationLineageSegmentDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown CreditRealizationLineageSegment mutation op: %q", m.Op()) + } +} + +// CurrencyCostBasisClient is a client for the CurrencyCostBasis schema. +type CurrencyCostBasisClient struct { + config +} + +// NewCurrencyCostBasisClient returns a client for the CurrencyCostBasis from the given config. +func NewCurrencyCostBasisClient(c config) *CurrencyCostBasisClient { + return &CurrencyCostBasisClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `currencycostbasis.Hooks(f(g(h())))`. +func (c *CurrencyCostBasisClient) Use(hooks ...Hook) { + c.hooks.CurrencyCostBasis = append(c.hooks.CurrencyCostBasis, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `currencycostbasis.Intercept(f(g(h())))`. +func (c *CurrencyCostBasisClient) Intercept(interceptors ...Interceptor) { + c.inters.CurrencyCostBasis = append(c.inters.CurrencyCostBasis, interceptors...) +} + +// Create returns a builder for creating a CurrencyCostBasis entity. +func (c *CurrencyCostBasisClient) Create() *CurrencyCostBasisCreate { + mutation := newCurrencyCostBasisMutation(c.config, OpCreate) + return &CurrencyCostBasisCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of CurrencyCostBasis entities. +func (c *CurrencyCostBasisClient) CreateBulk(builders ...*CurrencyCostBasisCreate) *CurrencyCostBasisCreateBulk { + return &CurrencyCostBasisCreateBulk{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 *CurrencyCostBasisClient) MapCreateBulk(slice any, setFunc func(*CurrencyCostBasisCreate, int)) *CurrencyCostBasisCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &CurrencyCostBasisCreateBulk{err: fmt.Errorf("calling to CurrencyCostBasisClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*CurrencyCostBasisCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &CurrencyCostBasisCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for CurrencyCostBasis. +func (c *CurrencyCostBasisClient) Update() *CurrencyCostBasisUpdate { + mutation := newCurrencyCostBasisMutation(c.config, OpUpdate) + return &CurrencyCostBasisUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *CurrencyCostBasisClient) UpdateOne(_m *CurrencyCostBasis) *CurrencyCostBasisUpdateOne { + mutation := newCurrencyCostBasisMutation(c.config, OpUpdateOne, withCurrencyCostBasis(_m)) + return &CurrencyCostBasisUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *CurrencyCostBasisClient) UpdateOneID(id string) *CurrencyCostBasisUpdateOne { + mutation := newCurrencyCostBasisMutation(c.config, OpUpdateOne, withCurrencyCostBasisID(id)) + return &CurrencyCostBasisUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for CurrencyCostBasis. +func (c *CurrencyCostBasisClient) Delete() *CurrencyCostBasisDelete { + mutation := newCurrencyCostBasisMutation(c.config, OpDelete) + return &CurrencyCostBasisDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *CurrencyCostBasisClient) DeleteOne(_m *CurrencyCostBasis) *CurrencyCostBasisDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *CurrencyCostBasisClient) DeleteOneID(id string) *CurrencyCostBasisDeleteOne { + builder := c.Delete().Where(currencycostbasis.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &CurrencyCostBasisDeleteOne{builder} +} + +// Query returns a query builder for CurrencyCostBasis. +func (c *CurrencyCostBasisClient) Query() *CurrencyCostBasisQuery { + return &CurrencyCostBasisQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeCurrencyCostBasis}, + inters: c.Interceptors(), + } +} + +// Get returns a CurrencyCostBasis entity by its id. +func (c *CurrencyCostBasisClient) Get(ctx context.Context, id string) (*CurrencyCostBasis, error) { + return c.Query().Where(currencycostbasis.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *CurrencyCostBasisClient) GetX(ctx context.Context, id string) *CurrencyCostBasis { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryCurrency queries the currency edge of a CurrencyCostBasis. +func (c *CurrencyCostBasisClient) QueryCurrency(_m *CurrencyCostBasis) *CustomCurrencyQuery { + query := (&CustomCurrencyClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(currencycostbasis.Table, currencycostbasis.FieldID, id), + sqlgraph.To(customcurrency.Table, customcurrency.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, currencycostbasis.CurrencyTable, currencycostbasis.CurrencyColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *CurrencyCostBasisClient) Hooks() []Hook { + return c.hooks.CurrencyCostBasis +} + +// Interceptors returns the client interceptors. +func (c *CurrencyCostBasisClient) Interceptors() []Interceptor { + return c.inters.CurrencyCostBasis +} + +func (c *CurrencyCostBasisClient) mutate(ctx context.Context, m *CurrencyCostBasisMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&CurrencyCostBasisCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&CurrencyCostBasisUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&CurrencyCostBasisUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&CurrencyCostBasisDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown CurrencyCostBasis mutation op: %q", m.Op()) + } +} + +// CustomCurrencyClient is a client for the CustomCurrency schema. +type CustomCurrencyClient struct { + config +} + +// NewCustomCurrencyClient returns a client for the CustomCurrency from the given config. +func NewCustomCurrencyClient(c config) *CustomCurrencyClient { + return &CustomCurrencyClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `customcurrency.Hooks(f(g(h())))`. +func (c *CustomCurrencyClient) Use(hooks ...Hook) { + c.hooks.CustomCurrency = append(c.hooks.CustomCurrency, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `customcurrency.Intercept(f(g(h())))`. +func (c *CustomCurrencyClient) Intercept(interceptors ...Interceptor) { + c.inters.CustomCurrency = append(c.inters.CustomCurrency, interceptors...) +} + +// Create returns a builder for creating a CustomCurrency entity. +func (c *CustomCurrencyClient) Create() *CustomCurrencyCreate { + mutation := newCustomCurrencyMutation(c.config, OpCreate) + return &CustomCurrencyCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of CustomCurrency entities. +func (c *CustomCurrencyClient) CreateBulk(builders ...*CustomCurrencyCreate) *CustomCurrencyCreateBulk { + return &CustomCurrencyCreateBulk{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 *CustomCurrencyClient) MapCreateBulk(slice any, setFunc func(*CustomCurrencyCreate, int)) *CustomCurrencyCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &CustomCurrencyCreateBulk{err: fmt.Errorf("calling to CustomCurrencyClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*CustomCurrencyCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &CustomCurrencyCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for CustomCurrency. +func (c *CustomCurrencyClient) Update() *CustomCurrencyUpdate { + mutation := newCustomCurrencyMutation(c.config, OpUpdate) + return &CustomCurrencyUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *CustomCurrencyClient) UpdateOne(_m *CustomCurrency) *CustomCurrencyUpdateOne { + mutation := newCustomCurrencyMutation(c.config, OpUpdateOne, withCustomCurrency(_m)) + return &CustomCurrencyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *CustomCurrencyClient) UpdateOneID(id string) *CustomCurrencyUpdateOne { + mutation := newCustomCurrencyMutation(c.config, OpUpdateOne, withCustomCurrencyID(id)) + return &CustomCurrencyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for CustomCurrency. +func (c *CustomCurrencyClient) Delete() *CustomCurrencyDelete { + mutation := newCustomCurrencyMutation(c.config, OpDelete) + return &CustomCurrencyDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *CustomCurrencyClient) DeleteOne(_m *CustomCurrency) *CustomCurrencyDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *CustomCurrencyClient) DeleteOneID(id string) *CustomCurrencyDeleteOne { + builder := c.Delete().Where(customcurrency.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &CustomCurrencyDeleteOne{builder} +} + +// Query returns a query builder for CustomCurrency. +func (c *CustomCurrencyClient) Query() *CustomCurrencyQuery { + return &CustomCurrencyQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeCustomCurrency}, + inters: c.Interceptors(), + } +} + +// Get returns a CustomCurrency entity by its id. +func (c *CustomCurrencyClient) Get(ctx context.Context, id string) (*CustomCurrency, error) { + return c.Query().Where(customcurrency.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *CustomCurrencyClient) GetX(ctx context.Context, id string) *CustomCurrency { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryCostBasisHistory queries the cost_basis_history edge of a CustomCurrency. +func (c *CustomCurrencyClient) QueryCostBasisHistory(_m *CustomCurrency) *CurrencyCostBasisQuery { + query := (&CurrencyCostBasisClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(customcurrency.Table, customcurrency.FieldID, id), + sqlgraph.To(currencycostbasis.Table, currencycostbasis.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, customcurrency.CostBasisHistoryTable, customcurrency.CostBasisHistoryColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *CustomCurrencyClient) Hooks() []Hook { + return c.hooks.CustomCurrency +} + +// Interceptors returns the client interceptors. +func (c *CustomCurrencyClient) Interceptors() []Interceptor { + return c.inters.CustomCurrency +} + +func (c *CustomCurrencyClient) mutate(ctx context.Context, m *CustomCurrencyMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&CustomCurrencyCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&CustomCurrencyUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&CustomCurrencyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&CustomCurrencyDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown CustomCurrency mutation op: %q", m.Op()) + } +} + +// CustomerClient is a client for the Customer schema. +type CustomerClient struct { + config +} + +// NewCustomerClient returns a client for the Customer from the given config. +func NewCustomerClient(c config) *CustomerClient { + return &CustomerClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `customer.Hooks(f(g(h())))`. +func (c *CustomerClient) Use(hooks ...Hook) { + c.hooks.Customer = append(c.hooks.Customer, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `customer.Intercept(f(g(h())))`. +func (c *CustomerClient) Intercept(interceptors ...Interceptor) { + c.inters.Customer = append(c.inters.Customer, interceptors...) +} + +// Create returns a builder for creating a Customer entity. +func (c *CustomerClient) Create() *CustomerCreate { + mutation := newCustomerMutation(c.config, OpCreate) + return &CustomerCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Customer entities. +func (c *CustomerClient) CreateBulk(builders ...*CustomerCreate) *CustomerCreateBulk { + return &CustomerCreateBulk{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 *CustomerClient) MapCreateBulk(slice any, setFunc func(*CustomerCreate, int)) *CustomerCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &CustomerCreateBulk{err: fmt.Errorf("calling to CustomerClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*CustomerCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &CustomerCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Customer. +func (c *CustomerClient) Update() *CustomerUpdate { + mutation := newCustomerMutation(c.config, OpUpdate) + return &CustomerUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *CustomerClient) UpdateOne(_m *Customer) *CustomerUpdateOne { + mutation := newCustomerMutation(c.config, OpUpdateOne, withCustomer(_m)) + return &CustomerUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *CustomerClient) UpdateOneID(id string) *CustomerUpdateOne { + mutation := newCustomerMutation(c.config, OpUpdateOne, withCustomerID(id)) + return &CustomerUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Customer. +func (c *CustomerClient) Delete() *CustomerDelete { + mutation := newCustomerMutation(c.config, OpDelete) + return &CustomerDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *CustomerClient) DeleteOne(_m *Customer) *CustomerDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *CustomerClient) DeleteOneID(id string) *CustomerDeleteOne { + builder := c.Delete().Where(customer.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &CustomerDeleteOne{builder} +} + +// Query returns a query builder for Customer. +func (c *CustomerClient) Query() *CustomerQuery { + return &CustomerQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeCustomer}, + inters: c.Interceptors(), + } +} + +// Get returns a Customer entity by its id. +func (c *CustomerClient) Get(ctx context.Context, id string) (*Customer, error) { + return c.Query().Where(customer.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *CustomerClient) GetX(ctx context.Context, id string) *Customer { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryApps queries the apps edge of a Customer. +func (c *CustomerClient) QueryApps(_m *Customer) *AppCustomerQuery { + query := (&AppCustomerClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(customer.Table, customer.FieldID, id), + sqlgraph.To(appcustomer.Table, appcustomer.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, customer.AppsTable, customer.AppsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubjects queries the subjects edge of a Customer. +func (c *CustomerClient) QuerySubjects(_m *Customer) *CustomerSubjectsQuery { + query := (&CustomerSubjectsClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(customer.Table, customer.FieldID, id), + sqlgraph.To(customersubjects.Table, customersubjects.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, customer.SubjectsTable, customer.SubjectsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingCustomerOverride queries the billing_customer_override edge of a Customer. +func (c *CustomerClient) QueryBillingCustomerOverride(_m *Customer) *BillingCustomerOverrideQuery { + query := (&BillingCustomerOverrideClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(customer.Table, customer.FieldID, id), + sqlgraph.To(billingcustomeroverride.Table, billingcustomeroverride.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, customer.BillingCustomerOverrideTable, customer.BillingCustomerOverrideColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingInvoice queries the billing_invoice edge of a Customer. +func (c *CustomerClient) QueryBillingInvoice(_m *Customer) *BillingInvoiceQuery { + query := (&BillingInvoiceClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(customer.Table, customer.FieldID, id), + sqlgraph.To(billinginvoice.Table, billinginvoice.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, customer.BillingInvoiceTable, customer.BillingInvoiceColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubscription queries the subscription edge of a Customer. +func (c *CustomerClient) QuerySubscription(_m *Customer) *SubscriptionQuery { + query := (&SubscriptionClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(customer.Table, customer.FieldID, id), + sqlgraph.To(subscription.Table, subscription.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, customer.SubscriptionTable, customer.SubscriptionColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryEntitlements queries the entitlements edge of a Customer. +func (c *CustomerClient) QueryEntitlements(_m *Customer) *EntitlementQuery { + query := (&EntitlementClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(customer.Table, customer.FieldID, id), + sqlgraph.To(entitlement.Table, entitlement.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, customer.EntitlementsTable, customer.EntitlementsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargesCreditPurchase queries the charges_credit_purchase edge of a Customer. +func (c *CustomerClient) QueryChargesCreditPurchase(_m *Customer) *ChargeCreditPurchaseQuery { + query := (&ChargeCreditPurchaseClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(customer.Table, customer.FieldID, id), + sqlgraph.To(chargecreditpurchase.Table, chargecreditpurchase.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, customer.ChargesCreditPurchaseTable, customer.ChargesCreditPurchaseColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargesFlatFee queries the charges_flat_fee edge of a Customer. +func (c *CustomerClient) QueryChargesFlatFee(_m *Customer) *ChargeFlatFeeQuery { + query := (&ChargeFlatFeeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(customer.Table, customer.FieldID, id), + sqlgraph.To(chargeflatfee.Table, chargeflatfee.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, customer.ChargesFlatFeeTable, customer.ChargesFlatFeeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargesUsageBased queries the charges_usage_based edge of a Customer. +func (c *CustomerClient) QueryChargesUsageBased(_m *Customer) *ChargeUsageBasedQuery { + query := (&ChargeUsageBasedClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(customer.Table, customer.FieldID, id), + sqlgraph.To(chargeusagebased.Table, chargeusagebased.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, customer.ChargesUsageBasedTable, customer.ChargesUsageBasedColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *CustomerClient) Hooks() []Hook { + return c.hooks.Customer +} + +// Interceptors returns the client interceptors. +func (c *CustomerClient) Interceptors() []Interceptor { + return c.inters.Customer +} + +func (c *CustomerClient) mutate(ctx context.Context, m *CustomerMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&CustomerCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&CustomerUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&CustomerUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&CustomerDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown Customer mutation op: %q", m.Op()) + } +} + +// CustomerSubjectsClient is a client for the CustomerSubjects schema. +type CustomerSubjectsClient struct { + config +} + +// NewCustomerSubjectsClient returns a client for the CustomerSubjects from the given config. +func NewCustomerSubjectsClient(c config) *CustomerSubjectsClient { + return &CustomerSubjectsClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `customersubjects.Hooks(f(g(h())))`. +func (c *CustomerSubjectsClient) Use(hooks ...Hook) { + c.hooks.CustomerSubjects = append(c.hooks.CustomerSubjects, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `customersubjects.Intercept(f(g(h())))`. +func (c *CustomerSubjectsClient) Intercept(interceptors ...Interceptor) { + c.inters.CustomerSubjects = append(c.inters.CustomerSubjects, interceptors...) +} + +// Create returns a builder for creating a CustomerSubjects entity. +func (c *CustomerSubjectsClient) Create() *CustomerSubjectsCreate { + mutation := newCustomerSubjectsMutation(c.config, OpCreate) + return &CustomerSubjectsCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of CustomerSubjects entities. +func (c *CustomerSubjectsClient) CreateBulk(builders ...*CustomerSubjectsCreate) *CustomerSubjectsCreateBulk { + return &CustomerSubjectsCreateBulk{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 *CustomerSubjectsClient) MapCreateBulk(slice any, setFunc func(*CustomerSubjectsCreate, int)) *CustomerSubjectsCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &CustomerSubjectsCreateBulk{err: fmt.Errorf("calling to CustomerSubjectsClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*CustomerSubjectsCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &CustomerSubjectsCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for CustomerSubjects. +func (c *CustomerSubjectsClient) Update() *CustomerSubjectsUpdate { + mutation := newCustomerSubjectsMutation(c.config, OpUpdate) + return &CustomerSubjectsUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *CustomerSubjectsClient) UpdateOne(_m *CustomerSubjects) *CustomerSubjectsUpdateOne { + mutation := newCustomerSubjectsMutation(c.config, OpUpdateOne, withCustomerSubjects(_m)) + return &CustomerSubjectsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *CustomerSubjectsClient) UpdateOneID(id int) *CustomerSubjectsUpdateOne { + mutation := newCustomerSubjectsMutation(c.config, OpUpdateOne, withCustomerSubjectsID(id)) + return &CustomerSubjectsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for CustomerSubjects. +func (c *CustomerSubjectsClient) Delete() *CustomerSubjectsDelete { + mutation := newCustomerSubjectsMutation(c.config, OpDelete) + return &CustomerSubjectsDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *CustomerSubjectsClient) DeleteOne(_m *CustomerSubjects) *CustomerSubjectsDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *CustomerSubjectsClient) DeleteOneID(id int) *CustomerSubjectsDeleteOne { + builder := c.Delete().Where(customersubjects.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &CustomerSubjectsDeleteOne{builder} +} + +// Query returns a query builder for CustomerSubjects. +func (c *CustomerSubjectsClient) Query() *CustomerSubjectsQuery { + return &CustomerSubjectsQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeCustomerSubjects}, + inters: c.Interceptors(), + } +} + +// Get returns a CustomerSubjects entity by its id. +func (c *CustomerSubjectsClient) Get(ctx context.Context, id int) (*CustomerSubjects, error) { + return c.Query().Where(customersubjects.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *CustomerSubjectsClient) GetX(ctx context.Context, id int) *CustomerSubjects { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryCustomer queries the customer edge of a CustomerSubjects. +func (c *CustomerSubjectsClient) QueryCustomer(_m *CustomerSubjects) *CustomerQuery { + query := (&CustomerClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(customersubjects.Table, customersubjects.FieldID, id), + sqlgraph.To(customer.Table, customer.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, customersubjects.CustomerTable, customersubjects.CustomerColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *CustomerSubjectsClient) Hooks() []Hook { + return c.hooks.CustomerSubjects +} + +// Interceptors returns the client interceptors. +func (c *CustomerSubjectsClient) Interceptors() []Interceptor { + return c.inters.CustomerSubjects +} + +func (c *CustomerSubjectsClient) mutate(ctx context.Context, m *CustomerSubjectsMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&CustomerSubjectsCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&CustomerSubjectsUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&CustomerSubjectsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&CustomerSubjectsDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown CustomerSubjects mutation op: %q", m.Op()) + } +} + +// EntitlementClient is a client for the Entitlement schema. +type EntitlementClient struct { + config +} + +// NewEntitlementClient returns a client for the Entitlement from the given config. +func NewEntitlementClient(c config) *EntitlementClient { + return &EntitlementClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `entitlement.Hooks(f(g(h())))`. +func (c *EntitlementClient) Use(hooks ...Hook) { + c.hooks.Entitlement = append(c.hooks.Entitlement, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `entitlement.Intercept(f(g(h())))`. +func (c *EntitlementClient) Intercept(interceptors ...Interceptor) { + c.inters.Entitlement = append(c.inters.Entitlement, interceptors...) +} + +// Create returns a builder for creating a Entitlement entity. +func (c *EntitlementClient) Create() *EntitlementCreate { + mutation := newEntitlementMutation(c.config, OpCreate) + return &EntitlementCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Entitlement entities. +func (c *EntitlementClient) CreateBulk(builders ...*EntitlementCreate) *EntitlementCreateBulk { + return &EntitlementCreateBulk{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 *EntitlementClient) MapCreateBulk(slice any, setFunc func(*EntitlementCreate, int)) *EntitlementCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &EntitlementCreateBulk{err: fmt.Errorf("calling to EntitlementClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*EntitlementCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &EntitlementCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Entitlement. +func (c *EntitlementClient) Update() *EntitlementUpdate { + mutation := newEntitlementMutation(c.config, OpUpdate) + return &EntitlementUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *EntitlementClient) UpdateOne(_m *Entitlement) *EntitlementUpdateOne { + mutation := newEntitlementMutation(c.config, OpUpdateOne, withEntitlement(_m)) + return &EntitlementUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *EntitlementClient) UpdateOneID(id string) *EntitlementUpdateOne { + mutation := newEntitlementMutation(c.config, OpUpdateOne, withEntitlementID(id)) + return &EntitlementUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Entitlement. +func (c *EntitlementClient) Delete() *EntitlementDelete { + mutation := newEntitlementMutation(c.config, OpDelete) + return &EntitlementDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *EntitlementClient) DeleteOne(_m *Entitlement) *EntitlementDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *EntitlementClient) DeleteOneID(id string) *EntitlementDeleteOne { + builder := c.Delete().Where(entitlement.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &EntitlementDeleteOne{builder} +} + +// Query returns a query builder for Entitlement. +func (c *EntitlementClient) Query() *EntitlementQuery { + return &EntitlementQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeEntitlement}, + inters: c.Interceptors(), + } +} + +// Get returns a Entitlement entity by its id. +func (c *EntitlementClient) Get(ctx context.Context, id string) (*Entitlement, error) { + return c.Query().Where(entitlement.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *EntitlementClient) GetX(ctx context.Context, id string) *Entitlement { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryUsageReset queries the usage_reset edge of a Entitlement. +func (c *EntitlementClient) QueryUsageReset(_m *Entitlement) *UsageResetQuery { + query := (&UsageResetClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(entitlement.Table, entitlement.FieldID, id), + sqlgraph.To(usagereset.Table, usagereset.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, entitlement.UsageResetTable, entitlement.UsageResetColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryGrant queries the grant edge of a Entitlement. +func (c *EntitlementClient) QueryGrant(_m *Entitlement) *GrantQuery { + query := (&GrantClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(entitlement.Table, entitlement.FieldID, id), + sqlgraph.To(dbgrant.Table, dbgrant.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, entitlement.GrantTable, entitlement.GrantColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBalanceSnapshot queries the balance_snapshot edge of a Entitlement. +func (c *EntitlementClient) QueryBalanceSnapshot(_m *Entitlement) *BalanceSnapshotQuery { + query := (&BalanceSnapshotClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(entitlement.Table, entitlement.FieldID, id), + sqlgraph.To(balancesnapshot.Table, balancesnapshot.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, entitlement.BalanceSnapshotTable, entitlement.BalanceSnapshotColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubscriptionItem queries the subscription_item edge of a Entitlement. +func (c *EntitlementClient) QuerySubscriptionItem(_m *Entitlement) *SubscriptionItemQuery { + query := (&SubscriptionItemClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(entitlement.Table, entitlement.FieldID, id), + sqlgraph.To(subscriptionitem.Table, subscriptionitem.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, entitlement.SubscriptionItemTable, entitlement.SubscriptionItemColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryFeature queries the feature edge of a Entitlement. +func (c *EntitlementClient) QueryFeature(_m *Entitlement) *FeatureQuery { + query := (&FeatureClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(entitlement.Table, entitlement.FieldID, id), + sqlgraph.To(dbfeature.Table, dbfeature.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, entitlement.FeatureTable, entitlement.FeatureColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCustomer queries the customer edge of a Entitlement. +func (c *EntitlementClient) QueryCustomer(_m *Entitlement) *CustomerQuery { + query := (&CustomerClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(entitlement.Table, entitlement.FieldID, id), + sqlgraph.To(customer.Table, customer.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, entitlement.CustomerTable, entitlement.CustomerColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *EntitlementClient) Hooks() []Hook { + return c.hooks.Entitlement +} + +// Interceptors returns the client interceptors. +func (c *EntitlementClient) Interceptors() []Interceptor { + return c.inters.Entitlement +} + +func (c *EntitlementClient) mutate(ctx context.Context, m *EntitlementMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&EntitlementCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&EntitlementUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&EntitlementUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&EntitlementDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown Entitlement mutation op: %q", m.Op()) + } +} + +// FeatureClient is a client for the Feature schema. +type FeatureClient struct { + config +} + +// NewFeatureClient returns a client for the Feature from the given config. +func NewFeatureClient(c config) *FeatureClient { + return &FeatureClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `dbfeature.Hooks(f(g(h())))`. +func (c *FeatureClient) Use(hooks ...Hook) { + c.hooks.Feature = append(c.hooks.Feature, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `dbfeature.Intercept(f(g(h())))`. +func (c *FeatureClient) Intercept(interceptors ...Interceptor) { + c.inters.Feature = append(c.inters.Feature, interceptors...) +} + +// Create returns a builder for creating a Feature entity. +func (c *FeatureClient) Create() *FeatureCreate { + mutation := newFeatureMutation(c.config, OpCreate) + return &FeatureCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Feature entities. +func (c *FeatureClient) CreateBulk(builders ...*FeatureCreate) *FeatureCreateBulk { + return &FeatureCreateBulk{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 *FeatureClient) MapCreateBulk(slice any, setFunc func(*FeatureCreate, int)) *FeatureCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &FeatureCreateBulk{err: fmt.Errorf("calling to FeatureClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*FeatureCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &FeatureCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Feature. +func (c *FeatureClient) Update() *FeatureUpdate { + mutation := newFeatureMutation(c.config, OpUpdate) + return &FeatureUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *FeatureClient) UpdateOne(_m *Feature) *FeatureUpdateOne { + mutation := newFeatureMutation(c.config, OpUpdateOne, withFeature(_m)) + return &FeatureUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *FeatureClient) UpdateOneID(id string) *FeatureUpdateOne { + mutation := newFeatureMutation(c.config, OpUpdateOne, withFeatureID(id)) + return &FeatureUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Feature. +func (c *FeatureClient) Delete() *FeatureDelete { + mutation := newFeatureMutation(c.config, OpDelete) + return &FeatureDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *FeatureClient) DeleteOne(_m *Feature) *FeatureDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *FeatureClient) DeleteOneID(id string) *FeatureDeleteOne { + builder := c.Delete().Where(dbfeature.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &FeatureDeleteOne{builder} +} + +// Query returns a query builder for Feature. +func (c *FeatureClient) Query() *FeatureQuery { + return &FeatureQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeFeature}, + inters: c.Interceptors(), + } +} + +// Get returns a Feature entity by its id. +func (c *FeatureClient) Get(ctx context.Context, id string) (*Feature, error) { + return c.Query().Where(dbfeature.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *FeatureClient) GetX(ctx context.Context, id string) *Feature { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryEntitlement queries the entitlement edge of a Feature. +func (c *FeatureClient) QueryEntitlement(_m *Feature) *EntitlementQuery { + query := (&EntitlementClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbfeature.Table, dbfeature.FieldID, id), + sqlgraph.To(entitlement.Table, entitlement.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbfeature.EntitlementTable, dbfeature.EntitlementColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryRatecard queries the ratecard edge of a Feature. +func (c *FeatureClient) QueryRatecard(_m *Feature) *PlanRateCardQuery { + query := (&PlanRateCardClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbfeature.Table, dbfeature.FieldID, id), + sqlgraph.To(planratecard.Table, planratecard.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbfeature.RatecardTable, dbfeature.RatecardColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryAddonRatecard queries the addon_ratecard edge of a Feature. +func (c *FeatureClient) QueryAddonRatecard(_m *Feature) *AddonRateCardQuery { + query := (&AddonRateCardClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbfeature.Table, dbfeature.FieldID, id), + sqlgraph.To(addonratecard.Table, addonratecard.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbfeature.AddonRatecardTable, dbfeature.AddonRatecardColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryUsageBasedCharges queries the usage_based_charges edge of a Feature. +func (c *FeatureClient) QueryUsageBasedCharges(_m *Feature) *ChargeUsageBasedQuery { + query := (&ChargeUsageBasedClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbfeature.Table, dbfeature.FieldID, id), + sqlgraph.To(chargeusagebased.Table, chargeusagebased.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbfeature.UsageBasedChargesTable, dbfeature.UsageBasedChargesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryUsageBasedRuns queries the usage_based_runs edge of a Feature. +func (c *FeatureClient) QueryUsageBasedRuns(_m *Feature) *ChargeUsageBasedRunsQuery { + query := (&ChargeUsageBasedRunsClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbfeature.Table, dbfeature.FieldID, id), + sqlgraph.To(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbfeature.UsageBasedRunsTable, dbfeature.UsageBasedRunsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryFlatFeeCharges queries the flat_fee_charges edge of a Feature. +func (c *FeatureClient) QueryFlatFeeCharges(_m *Feature) *ChargeFlatFeeQuery { + query := (&ChargeFlatFeeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbfeature.Table, dbfeature.FieldID, id), + sqlgraph.To(chargeflatfee.Table, chargeflatfee.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbfeature.FlatFeeChargesTable, dbfeature.FlatFeeChargesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryMeter queries the meter edge of a Feature. +func (c *FeatureClient) QueryMeter(_m *Feature) *MeterQuery { + query := (&MeterClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbfeature.Table, dbfeature.FieldID, id), + sqlgraph.To(dbmeter.Table, dbmeter.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, dbfeature.MeterTable, dbfeature.MeterColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *FeatureClient) Hooks() []Hook { + return c.hooks.Feature +} + +// Interceptors returns the client interceptors. +func (c *FeatureClient) Interceptors() []Interceptor { + return c.inters.Feature +} + +func (c *FeatureClient) mutate(ctx context.Context, m *FeatureMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&FeatureCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&FeatureUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&FeatureUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&FeatureDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown Feature mutation op: %q", m.Op()) + } +} + +// GrantClient is a client for the Grant schema. +type GrantClient struct { + config +} + +// NewGrantClient returns a client for the Grant from the given config. +func NewGrantClient(c config) *GrantClient { + return &GrantClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `dbgrant.Hooks(f(g(h())))`. +func (c *GrantClient) Use(hooks ...Hook) { + c.hooks.Grant = append(c.hooks.Grant, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `dbgrant.Intercept(f(g(h())))`. +func (c *GrantClient) Intercept(interceptors ...Interceptor) { + c.inters.Grant = append(c.inters.Grant, interceptors...) +} + +// Create returns a builder for creating a Grant entity. +func (c *GrantClient) Create() *GrantCreate { + mutation := newGrantMutation(c.config, OpCreate) + return &GrantCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Grant entities. +func (c *GrantClient) CreateBulk(builders ...*GrantCreate) *GrantCreateBulk { + return &GrantCreateBulk{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 *GrantClient) MapCreateBulk(slice any, setFunc func(*GrantCreate, int)) *GrantCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &GrantCreateBulk{err: fmt.Errorf("calling to GrantClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*GrantCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &GrantCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Grant. +func (c *GrantClient) Update() *GrantUpdate { + mutation := newGrantMutation(c.config, OpUpdate) + return &GrantUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *GrantClient) UpdateOne(_m *Grant) *GrantUpdateOne { + mutation := newGrantMutation(c.config, OpUpdateOne, withGrant(_m)) + return &GrantUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *GrantClient) UpdateOneID(id string) *GrantUpdateOne { + mutation := newGrantMutation(c.config, OpUpdateOne, withGrantID(id)) + return &GrantUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Grant. +func (c *GrantClient) Delete() *GrantDelete { + mutation := newGrantMutation(c.config, OpDelete) + return &GrantDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *GrantClient) DeleteOne(_m *Grant) *GrantDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *GrantClient) DeleteOneID(id string) *GrantDeleteOne { + builder := c.Delete().Where(dbgrant.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &GrantDeleteOne{builder} +} + +// Query returns a query builder for Grant. +func (c *GrantClient) Query() *GrantQuery { + return &GrantQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeGrant}, + inters: c.Interceptors(), + } +} + +// Get returns a Grant entity by its id. +func (c *GrantClient) Get(ctx context.Context, id string) (*Grant, error) { + return c.Query().Where(dbgrant.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *GrantClient) GetX(ctx context.Context, id string) *Grant { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryEntitlement queries the entitlement edge of a Grant. +func (c *GrantClient) QueryEntitlement(_m *Grant) *EntitlementQuery { + query := (&EntitlementClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbgrant.Table, dbgrant.FieldID, id), + sqlgraph.To(entitlement.Table, entitlement.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, dbgrant.EntitlementTable, dbgrant.EntitlementColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *GrantClient) Hooks() []Hook { + return c.hooks.Grant +} + +// Interceptors returns the client interceptors. +func (c *GrantClient) Interceptors() []Interceptor { + return c.inters.Grant +} + +func (c *GrantClient) mutate(ctx context.Context, m *GrantMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&GrantCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&GrantUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&GrantUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&GrantDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown Grant mutation op: %q", m.Op()) + } +} + +// LLMCostPriceClient is a client for the LLMCostPrice schema. +type LLMCostPriceClient struct { + config +} + +// NewLLMCostPriceClient returns a client for the LLMCostPrice from the given config. +func NewLLMCostPriceClient(c config) *LLMCostPriceClient { + return &LLMCostPriceClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `llmcostprice.Hooks(f(g(h())))`. +func (c *LLMCostPriceClient) Use(hooks ...Hook) { + c.hooks.LLMCostPrice = append(c.hooks.LLMCostPrice, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `llmcostprice.Intercept(f(g(h())))`. +func (c *LLMCostPriceClient) Intercept(interceptors ...Interceptor) { + c.inters.LLMCostPrice = append(c.inters.LLMCostPrice, interceptors...) +} + +// Create returns a builder for creating a LLMCostPrice entity. +func (c *LLMCostPriceClient) Create() *LLMCostPriceCreate { + mutation := newLLMCostPriceMutation(c.config, OpCreate) + return &LLMCostPriceCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LLMCostPrice entities. +func (c *LLMCostPriceClient) CreateBulk(builders ...*LLMCostPriceCreate) *LLMCostPriceCreateBulk { + return &LLMCostPriceCreateBulk{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 *LLMCostPriceClient) MapCreateBulk(slice any, setFunc func(*LLMCostPriceCreate, int)) *LLMCostPriceCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &LLMCostPriceCreateBulk{err: fmt.Errorf("calling to LLMCostPriceClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*LLMCostPriceCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &LLMCostPriceCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LLMCostPrice. +func (c *LLMCostPriceClient) Update() *LLMCostPriceUpdate { + mutation := newLLMCostPriceMutation(c.config, OpUpdate) + return &LLMCostPriceUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LLMCostPriceClient) UpdateOne(_m *LLMCostPrice) *LLMCostPriceUpdateOne { + mutation := newLLMCostPriceMutation(c.config, OpUpdateOne, withLLMCostPrice(_m)) + return &LLMCostPriceUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LLMCostPriceClient) UpdateOneID(id string) *LLMCostPriceUpdateOne { + mutation := newLLMCostPriceMutation(c.config, OpUpdateOne, withLLMCostPriceID(id)) + return &LLMCostPriceUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LLMCostPrice. +func (c *LLMCostPriceClient) Delete() *LLMCostPriceDelete { + mutation := newLLMCostPriceMutation(c.config, OpDelete) + return &LLMCostPriceDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *LLMCostPriceClient) DeleteOne(_m *LLMCostPrice) *LLMCostPriceDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *LLMCostPriceClient) DeleteOneID(id string) *LLMCostPriceDeleteOne { + builder := c.Delete().Where(llmcostprice.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LLMCostPriceDeleteOne{builder} +} + +// Query returns a query builder for LLMCostPrice. +func (c *LLMCostPriceClient) Query() *LLMCostPriceQuery { + return &LLMCostPriceQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeLLMCostPrice}, + inters: c.Interceptors(), + } +} + +// Get returns a LLMCostPrice entity by its id. +func (c *LLMCostPriceClient) Get(ctx context.Context, id string) (*LLMCostPrice, error) { + return c.Query().Where(llmcostprice.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LLMCostPriceClient) GetX(ctx context.Context, id string) *LLMCostPrice { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *LLMCostPriceClient) Hooks() []Hook { + return c.hooks.LLMCostPrice +} + +// Interceptors returns the client interceptors. +func (c *LLMCostPriceClient) Interceptors() []Interceptor { + return c.inters.LLMCostPrice +} + +func (c *LLMCostPriceClient) mutate(ctx context.Context, m *LLMCostPriceMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&LLMCostPriceCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&LLMCostPriceUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&LLMCostPriceUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&LLMCostPriceDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown LLMCostPrice mutation op: %q", m.Op()) + } +} + +// LedgerAccountClient is a client for the LedgerAccount schema. +type LedgerAccountClient struct { + config +} + +// NewLedgerAccountClient returns a client for the LedgerAccount from the given config. +func NewLedgerAccountClient(c config) *LedgerAccountClient { + return &LedgerAccountClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `ledgeraccount.Hooks(f(g(h())))`. +func (c *LedgerAccountClient) Use(hooks ...Hook) { + c.hooks.LedgerAccount = append(c.hooks.LedgerAccount, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `ledgeraccount.Intercept(f(g(h())))`. +func (c *LedgerAccountClient) Intercept(interceptors ...Interceptor) { + c.inters.LedgerAccount = append(c.inters.LedgerAccount, interceptors...) +} + +// Create returns a builder for creating a LedgerAccount entity. +func (c *LedgerAccountClient) Create() *LedgerAccountCreate { + mutation := newLedgerAccountMutation(c.config, OpCreate) + return &LedgerAccountCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LedgerAccount entities. +func (c *LedgerAccountClient) CreateBulk(builders ...*LedgerAccountCreate) *LedgerAccountCreateBulk { + return &LedgerAccountCreateBulk{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 *LedgerAccountClient) MapCreateBulk(slice any, setFunc func(*LedgerAccountCreate, int)) *LedgerAccountCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &LedgerAccountCreateBulk{err: fmt.Errorf("calling to LedgerAccountClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*LedgerAccountCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &LedgerAccountCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LedgerAccount. +func (c *LedgerAccountClient) Update() *LedgerAccountUpdate { + mutation := newLedgerAccountMutation(c.config, OpUpdate) + return &LedgerAccountUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LedgerAccountClient) UpdateOne(_m *LedgerAccount) *LedgerAccountUpdateOne { + mutation := newLedgerAccountMutation(c.config, OpUpdateOne, withLedgerAccount(_m)) + return &LedgerAccountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LedgerAccountClient) UpdateOneID(id string) *LedgerAccountUpdateOne { + mutation := newLedgerAccountMutation(c.config, OpUpdateOne, withLedgerAccountID(id)) + return &LedgerAccountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LedgerAccount. +func (c *LedgerAccountClient) Delete() *LedgerAccountDelete { + mutation := newLedgerAccountMutation(c.config, OpDelete) + return &LedgerAccountDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *LedgerAccountClient) DeleteOne(_m *LedgerAccount) *LedgerAccountDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *LedgerAccountClient) DeleteOneID(id string) *LedgerAccountDeleteOne { + builder := c.Delete().Where(ledgeraccount.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LedgerAccountDeleteOne{builder} +} + +// Query returns a query builder for LedgerAccount. +func (c *LedgerAccountClient) Query() *LedgerAccountQuery { + return &LedgerAccountQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeLedgerAccount}, + inters: c.Interceptors(), + } +} + +// Get returns a LedgerAccount entity by its id. +func (c *LedgerAccountClient) Get(ctx context.Context, id string) (*LedgerAccount, error) { + return c.Query().Where(ledgeraccount.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LedgerAccountClient) GetX(ctx context.Context, id string) *LedgerAccount { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QuerySubAccounts queries the sub_accounts edge of a LedgerAccount. +func (c *LedgerAccountClient) QuerySubAccounts(_m *LedgerAccount) *LedgerSubAccountQuery { + query := (&LedgerSubAccountClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgeraccount.Table, ledgeraccount.FieldID, id), + sqlgraph.To(ledgersubaccount.Table, ledgersubaccount.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgeraccount.SubAccountsTable, ledgeraccount.SubAccountsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubAccountRoutes queries the sub_account_routes edge of a LedgerAccount. +func (c *LedgerAccountClient) QuerySubAccountRoutes(_m *LedgerAccount) *LedgerSubAccountRouteQuery { + query := (&LedgerSubAccountRouteClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgeraccount.Table, ledgeraccount.FieldID, id), + sqlgraph.To(ledgersubaccountroute.Table, ledgersubaccountroute.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgeraccount.SubAccountRoutesTable, ledgeraccount.SubAccountRoutesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCustomerAccounts queries the customer_accounts edge of a LedgerAccount. +func (c *LedgerAccountClient) QueryCustomerAccounts(_m *LedgerAccount) *LedgerCustomerAccountQuery { + query := (&LedgerCustomerAccountClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgeraccount.Table, ledgeraccount.FieldID, id), + sqlgraph.To(ledgercustomeraccount.Table, ledgercustomeraccount.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgeraccount.CustomerAccountsTable, ledgeraccount.CustomerAccountsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *LedgerAccountClient) Hooks() []Hook { + return c.hooks.LedgerAccount +} + +// Interceptors returns the client interceptors. +func (c *LedgerAccountClient) Interceptors() []Interceptor { + return c.inters.LedgerAccount +} + +func (c *LedgerAccountClient) mutate(ctx context.Context, m *LedgerAccountMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&LedgerAccountCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&LedgerAccountUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&LedgerAccountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&LedgerAccountDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown LedgerAccount mutation op: %q", m.Op()) + } +} + +// LedgerBreakageRecordClient is a client for the LedgerBreakageRecord schema. +type LedgerBreakageRecordClient struct { + config +} + +// NewLedgerBreakageRecordClient returns a client for the LedgerBreakageRecord from the given config. +func NewLedgerBreakageRecordClient(c config) *LedgerBreakageRecordClient { + return &LedgerBreakageRecordClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `ledgerbreakagerecord.Hooks(f(g(h())))`. +func (c *LedgerBreakageRecordClient) Use(hooks ...Hook) { + c.hooks.LedgerBreakageRecord = append(c.hooks.LedgerBreakageRecord, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `ledgerbreakagerecord.Intercept(f(g(h())))`. +func (c *LedgerBreakageRecordClient) Intercept(interceptors ...Interceptor) { + c.inters.LedgerBreakageRecord = append(c.inters.LedgerBreakageRecord, interceptors...) +} + +// Create returns a builder for creating a LedgerBreakageRecord entity. +func (c *LedgerBreakageRecordClient) Create() *LedgerBreakageRecordCreate { + mutation := newLedgerBreakageRecordMutation(c.config, OpCreate) + return &LedgerBreakageRecordCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LedgerBreakageRecord entities. +func (c *LedgerBreakageRecordClient) CreateBulk(builders ...*LedgerBreakageRecordCreate) *LedgerBreakageRecordCreateBulk { + return &LedgerBreakageRecordCreateBulk{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 *LedgerBreakageRecordClient) MapCreateBulk(slice any, setFunc func(*LedgerBreakageRecordCreate, int)) *LedgerBreakageRecordCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &LedgerBreakageRecordCreateBulk{err: fmt.Errorf("calling to LedgerBreakageRecordClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*LedgerBreakageRecordCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &LedgerBreakageRecordCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LedgerBreakageRecord. +func (c *LedgerBreakageRecordClient) Update() *LedgerBreakageRecordUpdate { + mutation := newLedgerBreakageRecordMutation(c.config, OpUpdate) + return &LedgerBreakageRecordUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LedgerBreakageRecordClient) UpdateOne(_m *LedgerBreakageRecord) *LedgerBreakageRecordUpdateOne { + mutation := newLedgerBreakageRecordMutation(c.config, OpUpdateOne, withLedgerBreakageRecord(_m)) + return &LedgerBreakageRecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LedgerBreakageRecordClient) UpdateOneID(id string) *LedgerBreakageRecordUpdateOne { + mutation := newLedgerBreakageRecordMutation(c.config, OpUpdateOne, withLedgerBreakageRecordID(id)) + return &LedgerBreakageRecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LedgerBreakageRecord. +func (c *LedgerBreakageRecordClient) Delete() *LedgerBreakageRecordDelete { + mutation := newLedgerBreakageRecordMutation(c.config, OpDelete) + return &LedgerBreakageRecordDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *LedgerBreakageRecordClient) DeleteOne(_m *LedgerBreakageRecord) *LedgerBreakageRecordDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *LedgerBreakageRecordClient) DeleteOneID(id string) *LedgerBreakageRecordDeleteOne { + builder := c.Delete().Where(ledgerbreakagerecord.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LedgerBreakageRecordDeleteOne{builder} +} + +// Query returns a query builder for LedgerBreakageRecord. +func (c *LedgerBreakageRecordClient) Query() *LedgerBreakageRecordQuery { + return &LedgerBreakageRecordQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeLedgerBreakageRecord}, + inters: c.Interceptors(), + } +} + +// Get returns a LedgerBreakageRecord entity by its id. +func (c *LedgerBreakageRecordClient) Get(ctx context.Context, id string) (*LedgerBreakageRecord, error) { + return c.Query().Where(ledgerbreakagerecord.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LedgerBreakageRecordClient) GetX(ctx context.Context, id string) *LedgerBreakageRecord { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QuerySourceTransactionGroup queries the source_transaction_group edge of a LedgerBreakageRecord. +func (c *LedgerBreakageRecordClient) QuerySourceTransactionGroup(_m *LedgerBreakageRecord) *LedgerTransactionGroupQuery { + query := (&LedgerTransactionGroupClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, id), + sqlgraph.To(ledgertransactiongroup.Table, ledgertransactiongroup.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerbreakagerecord.SourceTransactionGroupTable, ledgerbreakagerecord.SourceTransactionGroupColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySourceTransaction queries the source_transaction edge of a LedgerBreakageRecord. +func (c *LedgerBreakageRecordClient) QuerySourceTransaction(_m *LedgerBreakageRecord) *LedgerTransactionQuery { + query := (&LedgerTransactionClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, id), + sqlgraph.To(ledgertransaction.Table, ledgertransaction.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerbreakagerecord.SourceTransactionTable, ledgerbreakagerecord.SourceTransactionColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySourceEntry queries the source_entry edge of a LedgerBreakageRecord. +func (c *LedgerBreakageRecordClient) QuerySourceEntry(_m *LedgerBreakageRecord) *LedgerEntryQuery { + query := (&LedgerEntryClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, id), + sqlgraph.To(ledgerentry.Table, ledgerentry.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerbreakagerecord.SourceEntryTable, ledgerbreakagerecord.SourceEntryColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBreakageTransactionGroup queries the breakage_transaction_group edge of a LedgerBreakageRecord. +func (c *LedgerBreakageRecordClient) QueryBreakageTransactionGroup(_m *LedgerBreakageRecord) *LedgerTransactionGroupQuery { + query := (&LedgerTransactionGroupClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, id), + sqlgraph.To(ledgertransactiongroup.Table, ledgertransactiongroup.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerbreakagerecord.BreakageTransactionGroupTable, ledgerbreakagerecord.BreakageTransactionGroupColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBreakageTransaction queries the breakage_transaction edge of a LedgerBreakageRecord. +func (c *LedgerBreakageRecordClient) QueryBreakageTransaction(_m *LedgerBreakageRecord) *LedgerTransactionQuery { + query := (&LedgerTransactionClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, id), + sqlgraph.To(ledgertransaction.Table, ledgertransaction.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerbreakagerecord.BreakageTransactionTable, ledgerbreakagerecord.BreakageTransactionColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryFboSubAccount queries the fbo_sub_account edge of a LedgerBreakageRecord. +func (c *LedgerBreakageRecordClient) QueryFboSubAccount(_m *LedgerBreakageRecord) *LedgerSubAccountQuery { + query := (&LedgerSubAccountClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, id), + sqlgraph.To(ledgersubaccount.Table, ledgersubaccount.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerbreakagerecord.FboSubAccountTable, ledgerbreakagerecord.FboSubAccountColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBreakageSubAccount queries the breakage_sub_account edge of a LedgerBreakageRecord. +func (c *LedgerBreakageRecordClient) QueryBreakageSubAccount(_m *LedgerBreakageRecord) *LedgerSubAccountQuery { + query := (&LedgerSubAccountClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, id), + sqlgraph.To(ledgersubaccount.Table, ledgersubaccount.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerbreakagerecord.BreakageSubAccountTable, ledgerbreakagerecord.BreakageSubAccountColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryPlannedReleases queries the planned_releases edge of a LedgerBreakageRecord. +func (c *LedgerBreakageRecordClient) QueryPlannedReleases(_m *LedgerBreakageRecord) *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, id), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgerbreakagerecord.PlannedReleasesTable, ledgerbreakagerecord.PlannedReleasesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryReleaseReopens queries the release_reopens edge of a LedgerBreakageRecord. +func (c *LedgerBreakageRecordClient) QueryReleaseReopens(_m *LedgerBreakageRecord) *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, id), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgerbreakagerecord.ReleaseReopensTable, ledgerbreakagerecord.ReleaseReopensColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryPlan queries the plan edge of a LedgerBreakageRecord. +func (c *LedgerBreakageRecordClient) QueryPlan(_m *LedgerBreakageRecord) *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, id), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerbreakagerecord.PlanTable, ledgerbreakagerecord.PlanColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryRelease queries the release edge of a LedgerBreakageRecord. +func (c *LedgerBreakageRecordClient) QueryRelease(_m *LedgerBreakageRecord) *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, id), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerbreakagerecord.ReleaseTable, ledgerbreakagerecord.ReleaseColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *LedgerBreakageRecordClient) Hooks() []Hook { + return c.hooks.LedgerBreakageRecord +} + +// Interceptors returns the client interceptors. +func (c *LedgerBreakageRecordClient) Interceptors() []Interceptor { + return c.inters.LedgerBreakageRecord +} + +func (c *LedgerBreakageRecordClient) mutate(ctx context.Context, m *LedgerBreakageRecordMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&LedgerBreakageRecordCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&LedgerBreakageRecordUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&LedgerBreakageRecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&LedgerBreakageRecordDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown LedgerBreakageRecord mutation op: %q", m.Op()) + } +} + +// LedgerCreditVoidRecordClient is a client for the LedgerCreditVoidRecord schema. +type LedgerCreditVoidRecordClient struct { + config +} + +// NewLedgerCreditVoidRecordClient returns a client for the LedgerCreditVoidRecord from the given config. +func NewLedgerCreditVoidRecordClient(c config) *LedgerCreditVoidRecordClient { + return &LedgerCreditVoidRecordClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `ledgercreditvoidrecord.Hooks(f(g(h())))`. +func (c *LedgerCreditVoidRecordClient) Use(hooks ...Hook) { + c.hooks.LedgerCreditVoidRecord = append(c.hooks.LedgerCreditVoidRecord, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `ledgercreditvoidrecord.Intercept(f(g(h())))`. +func (c *LedgerCreditVoidRecordClient) Intercept(interceptors ...Interceptor) { + c.inters.LedgerCreditVoidRecord = append(c.inters.LedgerCreditVoidRecord, interceptors...) +} + +// Create returns a builder for creating a LedgerCreditVoidRecord entity. +func (c *LedgerCreditVoidRecordClient) Create() *LedgerCreditVoidRecordCreate { + mutation := newLedgerCreditVoidRecordMutation(c.config, OpCreate) + return &LedgerCreditVoidRecordCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LedgerCreditVoidRecord entities. +func (c *LedgerCreditVoidRecordClient) CreateBulk(builders ...*LedgerCreditVoidRecordCreate) *LedgerCreditVoidRecordCreateBulk { + return &LedgerCreditVoidRecordCreateBulk{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 *LedgerCreditVoidRecordClient) MapCreateBulk(slice any, setFunc func(*LedgerCreditVoidRecordCreate, int)) *LedgerCreditVoidRecordCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &LedgerCreditVoidRecordCreateBulk{err: fmt.Errorf("calling to LedgerCreditVoidRecordClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*LedgerCreditVoidRecordCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &LedgerCreditVoidRecordCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LedgerCreditVoidRecord. +func (c *LedgerCreditVoidRecordClient) Update() *LedgerCreditVoidRecordUpdate { + mutation := newLedgerCreditVoidRecordMutation(c.config, OpUpdate) + return &LedgerCreditVoidRecordUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LedgerCreditVoidRecordClient) UpdateOne(_m *LedgerCreditVoidRecord) *LedgerCreditVoidRecordUpdateOne { + mutation := newLedgerCreditVoidRecordMutation(c.config, OpUpdateOne, withLedgerCreditVoidRecord(_m)) + return &LedgerCreditVoidRecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LedgerCreditVoidRecordClient) UpdateOneID(id string) *LedgerCreditVoidRecordUpdateOne { + mutation := newLedgerCreditVoidRecordMutation(c.config, OpUpdateOne, withLedgerCreditVoidRecordID(id)) + return &LedgerCreditVoidRecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LedgerCreditVoidRecord. +func (c *LedgerCreditVoidRecordClient) Delete() *LedgerCreditVoidRecordDelete { + mutation := newLedgerCreditVoidRecordMutation(c.config, OpDelete) + return &LedgerCreditVoidRecordDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *LedgerCreditVoidRecordClient) DeleteOne(_m *LedgerCreditVoidRecord) *LedgerCreditVoidRecordDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *LedgerCreditVoidRecordClient) DeleteOneID(id string) *LedgerCreditVoidRecordDeleteOne { + builder := c.Delete().Where(ledgercreditvoidrecord.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LedgerCreditVoidRecordDeleteOne{builder} +} + +// Query returns a query builder for LedgerCreditVoidRecord. +func (c *LedgerCreditVoidRecordClient) Query() *LedgerCreditVoidRecordQuery { + return &LedgerCreditVoidRecordQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeLedgerCreditVoidRecord}, + inters: c.Interceptors(), + } +} + +// Get returns a LedgerCreditVoidRecord entity by its id. +func (c *LedgerCreditVoidRecordClient) Get(ctx context.Context, id string) (*LedgerCreditVoidRecord, error) { + return c.Query().Where(ledgercreditvoidrecord.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LedgerCreditVoidRecordClient) GetX(ctx context.Context, id string) *LedgerCreditVoidRecord { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *LedgerCreditVoidRecordClient) Hooks() []Hook { + return c.hooks.LedgerCreditVoidRecord +} + +// Interceptors returns the client interceptors. +func (c *LedgerCreditVoidRecordClient) Interceptors() []Interceptor { + return c.inters.LedgerCreditVoidRecord +} + +func (c *LedgerCreditVoidRecordClient) mutate(ctx context.Context, m *LedgerCreditVoidRecordMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&LedgerCreditVoidRecordCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&LedgerCreditVoidRecordUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&LedgerCreditVoidRecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&LedgerCreditVoidRecordDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown LedgerCreditVoidRecord mutation op: %q", m.Op()) + } +} + +// LedgerCustomerAccountClient is a client for the LedgerCustomerAccount schema. +type LedgerCustomerAccountClient struct { + config +} + +// NewLedgerCustomerAccountClient returns a client for the LedgerCustomerAccount from the given config. +func NewLedgerCustomerAccountClient(c config) *LedgerCustomerAccountClient { + return &LedgerCustomerAccountClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `ledgercustomeraccount.Hooks(f(g(h())))`. +func (c *LedgerCustomerAccountClient) Use(hooks ...Hook) { + c.hooks.LedgerCustomerAccount = append(c.hooks.LedgerCustomerAccount, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `ledgercustomeraccount.Intercept(f(g(h())))`. +func (c *LedgerCustomerAccountClient) Intercept(interceptors ...Interceptor) { + c.inters.LedgerCustomerAccount = append(c.inters.LedgerCustomerAccount, interceptors...) +} + +// Create returns a builder for creating a LedgerCustomerAccount entity. +func (c *LedgerCustomerAccountClient) Create() *LedgerCustomerAccountCreate { + mutation := newLedgerCustomerAccountMutation(c.config, OpCreate) + return &LedgerCustomerAccountCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LedgerCustomerAccount entities. +func (c *LedgerCustomerAccountClient) CreateBulk(builders ...*LedgerCustomerAccountCreate) *LedgerCustomerAccountCreateBulk { + return &LedgerCustomerAccountCreateBulk{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 *LedgerCustomerAccountClient) MapCreateBulk(slice any, setFunc func(*LedgerCustomerAccountCreate, int)) *LedgerCustomerAccountCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &LedgerCustomerAccountCreateBulk{err: fmt.Errorf("calling to LedgerCustomerAccountClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*LedgerCustomerAccountCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &LedgerCustomerAccountCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LedgerCustomerAccount. +func (c *LedgerCustomerAccountClient) Update() *LedgerCustomerAccountUpdate { + mutation := newLedgerCustomerAccountMutation(c.config, OpUpdate) + return &LedgerCustomerAccountUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LedgerCustomerAccountClient) UpdateOne(_m *LedgerCustomerAccount) *LedgerCustomerAccountUpdateOne { + mutation := newLedgerCustomerAccountMutation(c.config, OpUpdateOne, withLedgerCustomerAccount(_m)) + return &LedgerCustomerAccountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LedgerCustomerAccountClient) UpdateOneID(id string) *LedgerCustomerAccountUpdateOne { + mutation := newLedgerCustomerAccountMutation(c.config, OpUpdateOne, withLedgerCustomerAccountID(id)) + return &LedgerCustomerAccountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LedgerCustomerAccount. +func (c *LedgerCustomerAccountClient) Delete() *LedgerCustomerAccountDelete { + mutation := newLedgerCustomerAccountMutation(c.config, OpDelete) + return &LedgerCustomerAccountDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *LedgerCustomerAccountClient) DeleteOne(_m *LedgerCustomerAccount) *LedgerCustomerAccountDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *LedgerCustomerAccountClient) DeleteOneID(id string) *LedgerCustomerAccountDeleteOne { + builder := c.Delete().Where(ledgercustomeraccount.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LedgerCustomerAccountDeleteOne{builder} +} + +// Query returns a query builder for LedgerCustomerAccount. +func (c *LedgerCustomerAccountClient) Query() *LedgerCustomerAccountQuery { + return &LedgerCustomerAccountQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeLedgerCustomerAccount}, + inters: c.Interceptors(), + } +} + +// Get returns a LedgerCustomerAccount entity by its id. +func (c *LedgerCustomerAccountClient) Get(ctx context.Context, id string) (*LedgerCustomerAccount, error) { + return c.Query().Where(ledgercustomeraccount.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LedgerCustomerAccountClient) GetX(ctx context.Context, id string) *LedgerCustomerAccount { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryAccount queries the account edge of a LedgerCustomerAccount. +func (c *LedgerCustomerAccountClient) QueryAccount(_m *LedgerCustomerAccount) *LedgerAccountQuery { + query := (&LedgerAccountClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgercustomeraccount.Table, ledgercustomeraccount.FieldID, id), + sqlgraph.To(ledgeraccount.Table, ledgeraccount.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgercustomeraccount.AccountTable, ledgercustomeraccount.AccountColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *LedgerCustomerAccountClient) Hooks() []Hook { + return c.hooks.LedgerCustomerAccount +} + +// Interceptors returns the client interceptors. +func (c *LedgerCustomerAccountClient) Interceptors() []Interceptor { + return c.inters.LedgerCustomerAccount +} + +func (c *LedgerCustomerAccountClient) mutate(ctx context.Context, m *LedgerCustomerAccountMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&LedgerCustomerAccountCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&LedgerCustomerAccountUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&LedgerCustomerAccountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&LedgerCustomerAccountDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown LedgerCustomerAccount mutation op: %q", m.Op()) + } +} + +// LedgerEntryClient is a client for the LedgerEntry schema. +type LedgerEntryClient struct { + config +} + +// NewLedgerEntryClient returns a client for the LedgerEntry from the given config. +func NewLedgerEntryClient(c config) *LedgerEntryClient { + return &LedgerEntryClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `ledgerentry.Hooks(f(g(h())))`. +func (c *LedgerEntryClient) Use(hooks ...Hook) { + c.hooks.LedgerEntry = append(c.hooks.LedgerEntry, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `ledgerentry.Intercept(f(g(h())))`. +func (c *LedgerEntryClient) Intercept(interceptors ...Interceptor) { + c.inters.LedgerEntry = append(c.inters.LedgerEntry, interceptors...) +} + +// Create returns a builder for creating a LedgerEntry entity. +func (c *LedgerEntryClient) Create() *LedgerEntryCreate { + mutation := newLedgerEntryMutation(c.config, OpCreate) + return &LedgerEntryCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LedgerEntry entities. +func (c *LedgerEntryClient) CreateBulk(builders ...*LedgerEntryCreate) *LedgerEntryCreateBulk { + return &LedgerEntryCreateBulk{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 *LedgerEntryClient) MapCreateBulk(slice any, setFunc func(*LedgerEntryCreate, int)) *LedgerEntryCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &LedgerEntryCreateBulk{err: fmt.Errorf("calling to LedgerEntryClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*LedgerEntryCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &LedgerEntryCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LedgerEntry. +func (c *LedgerEntryClient) Update() *LedgerEntryUpdate { + mutation := newLedgerEntryMutation(c.config, OpUpdate) + return &LedgerEntryUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LedgerEntryClient) UpdateOne(_m *LedgerEntry) *LedgerEntryUpdateOne { + mutation := newLedgerEntryMutation(c.config, OpUpdateOne, withLedgerEntry(_m)) + return &LedgerEntryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LedgerEntryClient) UpdateOneID(id string) *LedgerEntryUpdateOne { + mutation := newLedgerEntryMutation(c.config, OpUpdateOne, withLedgerEntryID(id)) + return &LedgerEntryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LedgerEntry. +func (c *LedgerEntryClient) Delete() *LedgerEntryDelete { + mutation := newLedgerEntryMutation(c.config, OpDelete) + return &LedgerEntryDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *LedgerEntryClient) DeleteOne(_m *LedgerEntry) *LedgerEntryDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *LedgerEntryClient) DeleteOneID(id string) *LedgerEntryDeleteOne { + builder := c.Delete().Where(ledgerentry.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LedgerEntryDeleteOne{builder} +} + +// Query returns a query builder for LedgerEntry. +func (c *LedgerEntryClient) Query() *LedgerEntryQuery { + return &LedgerEntryQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeLedgerEntry}, + inters: c.Interceptors(), + } +} + +// Get returns a LedgerEntry entity by its id. +func (c *LedgerEntryClient) Get(ctx context.Context, id string) (*LedgerEntry, error) { + return c.Query().Where(ledgerentry.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LedgerEntryClient) GetX(ctx context.Context, id string) *LedgerEntry { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryTransaction queries the transaction edge of a LedgerEntry. +func (c *LedgerEntryClient) QueryTransaction(_m *LedgerEntry) *LedgerTransactionQuery { + query := (&LedgerTransactionClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgerentry.Table, ledgerentry.FieldID, id), + sqlgraph.To(ledgertransaction.Table, ledgertransaction.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerentry.TransactionTable, ledgerentry.TransactionColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubAccount queries the sub_account edge of a LedgerEntry. +func (c *LedgerEntryClient) QuerySubAccount(_m *LedgerEntry) *LedgerSubAccountQuery { + query := (&LedgerSubAccountClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgerentry.Table, ledgerentry.FieldID, id), + sqlgraph.To(ledgersubaccount.Table, ledgersubaccount.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerentry.SubAccountTable, ledgerentry.SubAccountColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySourceBreakageRecords queries the source_breakage_records edge of a LedgerEntry. +func (c *LedgerEntryClient) QuerySourceBreakageRecords(_m *LedgerEntry) *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgerentry.Table, ledgerentry.FieldID, id), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgerentry.SourceBreakageRecordsTable, ledgerentry.SourceBreakageRecordsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *LedgerEntryClient) Hooks() []Hook { + return c.hooks.LedgerEntry +} + +// Interceptors returns the client interceptors. +func (c *LedgerEntryClient) Interceptors() []Interceptor { + return c.inters.LedgerEntry +} + +func (c *LedgerEntryClient) mutate(ctx context.Context, m *LedgerEntryMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&LedgerEntryCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&LedgerEntryUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&LedgerEntryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&LedgerEntryDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown LedgerEntry mutation op: %q", m.Op()) + } +} + +// LedgerSubAccountClient is a client for the LedgerSubAccount schema. +type LedgerSubAccountClient struct { + config +} + +// NewLedgerSubAccountClient returns a client for the LedgerSubAccount from the given config. +func NewLedgerSubAccountClient(c config) *LedgerSubAccountClient { + return &LedgerSubAccountClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `ledgersubaccount.Hooks(f(g(h())))`. +func (c *LedgerSubAccountClient) Use(hooks ...Hook) { + c.hooks.LedgerSubAccount = append(c.hooks.LedgerSubAccount, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `ledgersubaccount.Intercept(f(g(h())))`. +func (c *LedgerSubAccountClient) Intercept(interceptors ...Interceptor) { + c.inters.LedgerSubAccount = append(c.inters.LedgerSubAccount, interceptors...) +} + +// Create returns a builder for creating a LedgerSubAccount entity. +func (c *LedgerSubAccountClient) Create() *LedgerSubAccountCreate { + mutation := newLedgerSubAccountMutation(c.config, OpCreate) + return &LedgerSubAccountCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LedgerSubAccount entities. +func (c *LedgerSubAccountClient) CreateBulk(builders ...*LedgerSubAccountCreate) *LedgerSubAccountCreateBulk { + return &LedgerSubAccountCreateBulk{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 *LedgerSubAccountClient) MapCreateBulk(slice any, setFunc func(*LedgerSubAccountCreate, int)) *LedgerSubAccountCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &LedgerSubAccountCreateBulk{err: fmt.Errorf("calling to LedgerSubAccountClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*LedgerSubAccountCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &LedgerSubAccountCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LedgerSubAccount. +func (c *LedgerSubAccountClient) Update() *LedgerSubAccountUpdate { + mutation := newLedgerSubAccountMutation(c.config, OpUpdate) + return &LedgerSubAccountUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LedgerSubAccountClient) UpdateOne(_m *LedgerSubAccount) *LedgerSubAccountUpdateOne { + mutation := newLedgerSubAccountMutation(c.config, OpUpdateOne, withLedgerSubAccount(_m)) + return &LedgerSubAccountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LedgerSubAccountClient) UpdateOneID(id string) *LedgerSubAccountUpdateOne { + mutation := newLedgerSubAccountMutation(c.config, OpUpdateOne, withLedgerSubAccountID(id)) + return &LedgerSubAccountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LedgerSubAccount. +func (c *LedgerSubAccountClient) Delete() *LedgerSubAccountDelete { + mutation := newLedgerSubAccountMutation(c.config, OpDelete) + return &LedgerSubAccountDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *LedgerSubAccountClient) DeleteOne(_m *LedgerSubAccount) *LedgerSubAccountDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *LedgerSubAccountClient) DeleteOneID(id string) *LedgerSubAccountDeleteOne { + builder := c.Delete().Where(ledgersubaccount.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LedgerSubAccountDeleteOne{builder} +} + +// Query returns a query builder for LedgerSubAccount. +func (c *LedgerSubAccountClient) Query() *LedgerSubAccountQuery { + return &LedgerSubAccountQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeLedgerSubAccount}, + inters: c.Interceptors(), + } +} + +// Get returns a LedgerSubAccount entity by its id. +func (c *LedgerSubAccountClient) Get(ctx context.Context, id string) (*LedgerSubAccount, error) { + return c.Query().Where(ledgersubaccount.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LedgerSubAccountClient) GetX(ctx context.Context, id string) *LedgerSubAccount { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryAccount queries the account edge of a LedgerSubAccount. +func (c *LedgerSubAccountClient) QueryAccount(_m *LedgerSubAccount) *LedgerAccountQuery { + query := (&LedgerAccountClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgersubaccount.Table, ledgersubaccount.FieldID, id), + sqlgraph.To(ledgeraccount.Table, ledgeraccount.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgersubaccount.AccountTable, ledgersubaccount.AccountColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryRoute queries the route edge of a LedgerSubAccount. +func (c *LedgerSubAccountClient) QueryRoute(_m *LedgerSubAccount) *LedgerSubAccountRouteQuery { + query := (&LedgerSubAccountRouteClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgersubaccount.Table, ledgersubaccount.FieldID, id), + sqlgraph.To(ledgersubaccountroute.Table, ledgersubaccountroute.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgersubaccount.RouteTable, ledgersubaccount.RouteColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryEntries queries the entries edge of a LedgerSubAccount. +func (c *LedgerSubAccountClient) QueryEntries(_m *LedgerSubAccount) *LedgerEntryQuery { + query := (&LedgerEntryClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgersubaccount.Table, ledgersubaccount.FieldID, id), + sqlgraph.To(ledgerentry.Table, ledgerentry.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgersubaccount.EntriesTable, ledgersubaccount.EntriesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryFboBreakageRecords queries the fbo_breakage_records edge of a LedgerSubAccount. +func (c *LedgerSubAccountClient) QueryFboBreakageRecords(_m *LedgerSubAccount) *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgersubaccount.Table, ledgersubaccount.FieldID, id), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgersubaccount.FboBreakageRecordsTable, ledgersubaccount.FboBreakageRecordsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBreakageRecords queries the breakage_records edge of a LedgerSubAccount. +func (c *LedgerSubAccountClient) QueryBreakageRecords(_m *LedgerSubAccount) *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgersubaccount.Table, ledgersubaccount.FieldID, id), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgersubaccount.BreakageRecordsTable, ledgersubaccount.BreakageRecordsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *LedgerSubAccountClient) Hooks() []Hook { + return c.hooks.LedgerSubAccount +} + +// Interceptors returns the client interceptors. +func (c *LedgerSubAccountClient) Interceptors() []Interceptor { + return c.inters.LedgerSubAccount +} + +func (c *LedgerSubAccountClient) mutate(ctx context.Context, m *LedgerSubAccountMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&LedgerSubAccountCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&LedgerSubAccountUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&LedgerSubAccountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&LedgerSubAccountDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown LedgerSubAccount mutation op: %q", m.Op()) + } +} + +// LedgerSubAccountRouteClient is a client for the LedgerSubAccountRoute schema. +type LedgerSubAccountRouteClient struct { + config +} + +// NewLedgerSubAccountRouteClient returns a client for the LedgerSubAccountRoute from the given config. +func NewLedgerSubAccountRouteClient(c config) *LedgerSubAccountRouteClient { + return &LedgerSubAccountRouteClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `ledgersubaccountroute.Hooks(f(g(h())))`. +func (c *LedgerSubAccountRouteClient) Use(hooks ...Hook) { + c.hooks.LedgerSubAccountRoute = append(c.hooks.LedgerSubAccountRoute, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `ledgersubaccountroute.Intercept(f(g(h())))`. +func (c *LedgerSubAccountRouteClient) Intercept(interceptors ...Interceptor) { + c.inters.LedgerSubAccountRoute = append(c.inters.LedgerSubAccountRoute, interceptors...) +} + +// Create returns a builder for creating a LedgerSubAccountRoute entity. +func (c *LedgerSubAccountRouteClient) Create() *LedgerSubAccountRouteCreate { + mutation := newLedgerSubAccountRouteMutation(c.config, OpCreate) + return &LedgerSubAccountRouteCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LedgerSubAccountRoute entities. +func (c *LedgerSubAccountRouteClient) CreateBulk(builders ...*LedgerSubAccountRouteCreate) *LedgerSubAccountRouteCreateBulk { + return &LedgerSubAccountRouteCreateBulk{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 *LedgerSubAccountRouteClient) MapCreateBulk(slice any, setFunc func(*LedgerSubAccountRouteCreate, int)) *LedgerSubAccountRouteCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &LedgerSubAccountRouteCreateBulk{err: fmt.Errorf("calling to LedgerSubAccountRouteClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*LedgerSubAccountRouteCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &LedgerSubAccountRouteCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LedgerSubAccountRoute. +func (c *LedgerSubAccountRouteClient) Update() *LedgerSubAccountRouteUpdate { + mutation := newLedgerSubAccountRouteMutation(c.config, OpUpdate) + return &LedgerSubAccountRouteUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LedgerSubAccountRouteClient) UpdateOne(_m *LedgerSubAccountRoute) *LedgerSubAccountRouteUpdateOne { + mutation := newLedgerSubAccountRouteMutation(c.config, OpUpdateOne, withLedgerSubAccountRoute(_m)) + return &LedgerSubAccountRouteUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LedgerSubAccountRouteClient) UpdateOneID(id string) *LedgerSubAccountRouteUpdateOne { + mutation := newLedgerSubAccountRouteMutation(c.config, OpUpdateOne, withLedgerSubAccountRouteID(id)) + return &LedgerSubAccountRouteUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LedgerSubAccountRoute. +func (c *LedgerSubAccountRouteClient) Delete() *LedgerSubAccountRouteDelete { + mutation := newLedgerSubAccountRouteMutation(c.config, OpDelete) + return &LedgerSubAccountRouteDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *LedgerSubAccountRouteClient) DeleteOne(_m *LedgerSubAccountRoute) *LedgerSubAccountRouteDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *LedgerSubAccountRouteClient) DeleteOneID(id string) *LedgerSubAccountRouteDeleteOne { + builder := c.Delete().Where(ledgersubaccountroute.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LedgerSubAccountRouteDeleteOne{builder} +} + +// Query returns a query builder for LedgerSubAccountRoute. +func (c *LedgerSubAccountRouteClient) Query() *LedgerSubAccountRouteQuery { + return &LedgerSubAccountRouteQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeLedgerSubAccountRoute}, + inters: c.Interceptors(), + } +} + +// Get returns a LedgerSubAccountRoute entity by its id. +func (c *LedgerSubAccountRouteClient) Get(ctx context.Context, id string) (*LedgerSubAccountRoute, error) { + return c.Query().Where(ledgersubaccountroute.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LedgerSubAccountRouteClient) GetX(ctx context.Context, id string) *LedgerSubAccountRoute { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryAccount queries the account edge of a LedgerSubAccountRoute. +func (c *LedgerSubAccountRouteClient) QueryAccount(_m *LedgerSubAccountRoute) *LedgerAccountQuery { + query := (&LedgerAccountClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgersubaccountroute.Table, ledgersubaccountroute.FieldID, id), + sqlgraph.To(ledgeraccount.Table, ledgeraccount.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgersubaccountroute.AccountTable, ledgersubaccountroute.AccountColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubAccounts queries the sub_accounts edge of a LedgerSubAccountRoute. +func (c *LedgerSubAccountRouteClient) QuerySubAccounts(_m *LedgerSubAccountRoute) *LedgerSubAccountQuery { + query := (&LedgerSubAccountClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgersubaccountroute.Table, ledgersubaccountroute.FieldID, id), + sqlgraph.To(ledgersubaccount.Table, ledgersubaccount.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgersubaccountroute.SubAccountsTable, ledgersubaccountroute.SubAccountsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *LedgerSubAccountRouteClient) Hooks() []Hook { + return c.hooks.LedgerSubAccountRoute +} + +// Interceptors returns the client interceptors. +func (c *LedgerSubAccountRouteClient) Interceptors() []Interceptor { + return c.inters.LedgerSubAccountRoute +} + +func (c *LedgerSubAccountRouteClient) mutate(ctx context.Context, m *LedgerSubAccountRouteMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&LedgerSubAccountRouteCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&LedgerSubAccountRouteUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&LedgerSubAccountRouteUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&LedgerSubAccountRouteDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown LedgerSubAccountRoute mutation op: %q", m.Op()) + } +} + +// LedgerTransactionClient is a client for the LedgerTransaction schema. +type LedgerTransactionClient struct { + config +} + +// NewLedgerTransactionClient returns a client for the LedgerTransaction from the given config. +func NewLedgerTransactionClient(c config) *LedgerTransactionClient { + return &LedgerTransactionClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `ledgertransaction.Hooks(f(g(h())))`. +func (c *LedgerTransactionClient) Use(hooks ...Hook) { + c.hooks.LedgerTransaction = append(c.hooks.LedgerTransaction, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `ledgertransaction.Intercept(f(g(h())))`. +func (c *LedgerTransactionClient) Intercept(interceptors ...Interceptor) { + c.inters.LedgerTransaction = append(c.inters.LedgerTransaction, interceptors...) +} + +// Create returns a builder for creating a LedgerTransaction entity. +func (c *LedgerTransactionClient) Create() *LedgerTransactionCreate { + mutation := newLedgerTransactionMutation(c.config, OpCreate) + return &LedgerTransactionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LedgerTransaction entities. +func (c *LedgerTransactionClient) CreateBulk(builders ...*LedgerTransactionCreate) *LedgerTransactionCreateBulk { + return &LedgerTransactionCreateBulk{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 *LedgerTransactionClient) MapCreateBulk(slice any, setFunc func(*LedgerTransactionCreate, int)) *LedgerTransactionCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &LedgerTransactionCreateBulk{err: fmt.Errorf("calling to LedgerTransactionClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*LedgerTransactionCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &LedgerTransactionCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LedgerTransaction. +func (c *LedgerTransactionClient) Update() *LedgerTransactionUpdate { + mutation := newLedgerTransactionMutation(c.config, OpUpdate) + return &LedgerTransactionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LedgerTransactionClient) UpdateOne(_m *LedgerTransaction) *LedgerTransactionUpdateOne { + mutation := newLedgerTransactionMutation(c.config, OpUpdateOne, withLedgerTransaction(_m)) + return &LedgerTransactionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LedgerTransactionClient) UpdateOneID(id string) *LedgerTransactionUpdateOne { + mutation := newLedgerTransactionMutation(c.config, OpUpdateOne, withLedgerTransactionID(id)) + return &LedgerTransactionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LedgerTransaction. +func (c *LedgerTransactionClient) Delete() *LedgerTransactionDelete { + mutation := newLedgerTransactionMutation(c.config, OpDelete) + return &LedgerTransactionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *LedgerTransactionClient) DeleteOne(_m *LedgerTransaction) *LedgerTransactionDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *LedgerTransactionClient) DeleteOneID(id string) *LedgerTransactionDeleteOne { + builder := c.Delete().Where(ledgertransaction.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LedgerTransactionDeleteOne{builder} +} + +// Query returns a query builder for LedgerTransaction. +func (c *LedgerTransactionClient) Query() *LedgerTransactionQuery { + return &LedgerTransactionQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeLedgerTransaction}, + inters: c.Interceptors(), + } +} + +// Get returns a LedgerTransaction entity by its id. +func (c *LedgerTransactionClient) Get(ctx context.Context, id string) (*LedgerTransaction, error) { + return c.Query().Where(ledgertransaction.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LedgerTransactionClient) GetX(ctx context.Context, id string) *LedgerTransaction { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryGroup queries the group edge of a LedgerTransaction. +func (c *LedgerTransactionClient) QueryGroup(_m *LedgerTransaction) *LedgerTransactionGroupQuery { + query := (&LedgerTransactionGroupClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgertransaction.Table, ledgertransaction.FieldID, id), + sqlgraph.To(ledgertransactiongroup.Table, ledgertransactiongroup.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgertransaction.GroupTable, ledgertransaction.GroupColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryEntries queries the entries edge of a LedgerTransaction. +func (c *LedgerTransactionClient) QueryEntries(_m *LedgerTransaction) *LedgerEntryQuery { + query := (&LedgerEntryClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgertransaction.Table, ledgertransaction.FieldID, id), + sqlgraph.To(ledgerentry.Table, ledgerentry.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgertransaction.EntriesTable, ledgertransaction.EntriesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySourceBreakageRecords queries the source_breakage_records edge of a LedgerTransaction. +func (c *LedgerTransactionClient) QuerySourceBreakageRecords(_m *LedgerTransaction) *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgertransaction.Table, ledgertransaction.FieldID, id), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgertransaction.SourceBreakageRecordsTable, ledgertransaction.SourceBreakageRecordsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBreakageRecords queries the breakage_records edge of a LedgerTransaction. +func (c *LedgerTransactionClient) QueryBreakageRecords(_m *LedgerTransaction) *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgertransaction.Table, ledgertransaction.FieldID, id), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgertransaction.BreakageRecordsTable, ledgertransaction.BreakageRecordsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *LedgerTransactionClient) Hooks() []Hook { + return c.hooks.LedgerTransaction +} + +// Interceptors returns the client interceptors. +func (c *LedgerTransactionClient) Interceptors() []Interceptor { + return c.inters.LedgerTransaction +} + +func (c *LedgerTransactionClient) mutate(ctx context.Context, m *LedgerTransactionMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&LedgerTransactionCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&LedgerTransactionUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&LedgerTransactionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&LedgerTransactionDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown LedgerTransaction mutation op: %q", m.Op()) + } +} + +// LedgerTransactionGroupClient is a client for the LedgerTransactionGroup schema. +type LedgerTransactionGroupClient struct { + config +} + +// NewLedgerTransactionGroupClient returns a client for the LedgerTransactionGroup from the given config. +func NewLedgerTransactionGroupClient(c config) *LedgerTransactionGroupClient { + return &LedgerTransactionGroupClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `ledgertransactiongroup.Hooks(f(g(h())))`. +func (c *LedgerTransactionGroupClient) Use(hooks ...Hook) { + c.hooks.LedgerTransactionGroup = append(c.hooks.LedgerTransactionGroup, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `ledgertransactiongroup.Intercept(f(g(h())))`. +func (c *LedgerTransactionGroupClient) Intercept(interceptors ...Interceptor) { + c.inters.LedgerTransactionGroup = append(c.inters.LedgerTransactionGroup, interceptors...) +} + +// Create returns a builder for creating a LedgerTransactionGroup entity. +func (c *LedgerTransactionGroupClient) Create() *LedgerTransactionGroupCreate { + mutation := newLedgerTransactionGroupMutation(c.config, OpCreate) + return &LedgerTransactionGroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LedgerTransactionGroup entities. +func (c *LedgerTransactionGroupClient) CreateBulk(builders ...*LedgerTransactionGroupCreate) *LedgerTransactionGroupCreateBulk { + return &LedgerTransactionGroupCreateBulk{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 *LedgerTransactionGroupClient) MapCreateBulk(slice any, setFunc func(*LedgerTransactionGroupCreate, int)) *LedgerTransactionGroupCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &LedgerTransactionGroupCreateBulk{err: fmt.Errorf("calling to LedgerTransactionGroupClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*LedgerTransactionGroupCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &LedgerTransactionGroupCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LedgerTransactionGroup. +func (c *LedgerTransactionGroupClient) Update() *LedgerTransactionGroupUpdate { + mutation := newLedgerTransactionGroupMutation(c.config, OpUpdate) + return &LedgerTransactionGroupUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LedgerTransactionGroupClient) UpdateOne(_m *LedgerTransactionGroup) *LedgerTransactionGroupUpdateOne { + mutation := newLedgerTransactionGroupMutation(c.config, OpUpdateOne, withLedgerTransactionGroup(_m)) + return &LedgerTransactionGroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LedgerTransactionGroupClient) UpdateOneID(id string) *LedgerTransactionGroupUpdateOne { + mutation := newLedgerTransactionGroupMutation(c.config, OpUpdateOne, withLedgerTransactionGroupID(id)) + return &LedgerTransactionGroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LedgerTransactionGroup. +func (c *LedgerTransactionGroupClient) Delete() *LedgerTransactionGroupDelete { + mutation := newLedgerTransactionGroupMutation(c.config, OpDelete) + return &LedgerTransactionGroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *LedgerTransactionGroupClient) DeleteOne(_m *LedgerTransactionGroup) *LedgerTransactionGroupDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *LedgerTransactionGroupClient) DeleteOneID(id string) *LedgerTransactionGroupDeleteOne { + builder := c.Delete().Where(ledgertransactiongroup.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LedgerTransactionGroupDeleteOne{builder} +} + +// Query returns a query builder for LedgerTransactionGroup. +func (c *LedgerTransactionGroupClient) Query() *LedgerTransactionGroupQuery { + return &LedgerTransactionGroupQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeLedgerTransactionGroup}, + inters: c.Interceptors(), + } +} + +// Get returns a LedgerTransactionGroup entity by its id. +func (c *LedgerTransactionGroupClient) Get(ctx context.Context, id string) (*LedgerTransactionGroup, error) { + return c.Query().Where(ledgertransactiongroup.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LedgerTransactionGroupClient) GetX(ctx context.Context, id string) *LedgerTransactionGroup { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryTransactions queries the transactions edge of a LedgerTransactionGroup. +func (c *LedgerTransactionGroupClient) QueryTransactions(_m *LedgerTransactionGroup) *LedgerTransactionQuery { + query := (&LedgerTransactionClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgertransactiongroup.Table, ledgertransactiongroup.FieldID, id), + sqlgraph.To(ledgertransaction.Table, ledgertransaction.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgertransactiongroup.TransactionsTable, ledgertransactiongroup.TransactionsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySourceBreakageRecords queries the source_breakage_records edge of a LedgerTransactionGroup. +func (c *LedgerTransactionGroupClient) QuerySourceBreakageRecords(_m *LedgerTransactionGroup) *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgertransactiongroup.Table, ledgertransactiongroup.FieldID, id), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgertransactiongroup.SourceBreakageRecordsTable, ledgertransactiongroup.SourceBreakageRecordsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBreakageRecords queries the breakage_records edge of a LedgerTransactionGroup. +func (c *LedgerTransactionGroupClient) QueryBreakageRecords(_m *LedgerTransactionGroup) *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(ledgertransactiongroup.Table, ledgertransactiongroup.FieldID, id), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgertransactiongroup.BreakageRecordsTable, ledgertransactiongroup.BreakageRecordsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *LedgerTransactionGroupClient) Hooks() []Hook { + return c.hooks.LedgerTransactionGroup +} + +// Interceptors returns the client interceptors. +func (c *LedgerTransactionGroupClient) Interceptors() []Interceptor { + return c.inters.LedgerTransactionGroup +} + +func (c *LedgerTransactionGroupClient) mutate(ctx context.Context, m *LedgerTransactionGroupMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&LedgerTransactionGroupCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&LedgerTransactionGroupUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&LedgerTransactionGroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&LedgerTransactionGroupDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown LedgerTransactionGroup mutation op: %q", m.Op()) + } +} + +// MeterClient is a client for the Meter schema. +type MeterClient struct { + config +} + +// NewMeterClient returns a client for the Meter from the given config. +func NewMeterClient(c config) *MeterClient { + return &MeterClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `dbmeter.Hooks(f(g(h())))`. +func (c *MeterClient) Use(hooks ...Hook) { + c.hooks.Meter = append(c.hooks.Meter, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `dbmeter.Intercept(f(g(h())))`. +func (c *MeterClient) Intercept(interceptors ...Interceptor) { + c.inters.Meter = append(c.inters.Meter, interceptors...) +} + +// Create returns a builder for creating a Meter entity. +func (c *MeterClient) Create() *MeterCreate { + mutation := newMeterMutation(c.config, OpCreate) + return &MeterCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Meter entities. +func (c *MeterClient) CreateBulk(builders ...*MeterCreate) *MeterCreateBulk { + return &MeterCreateBulk{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 *MeterClient) MapCreateBulk(slice any, setFunc func(*MeterCreate, int)) *MeterCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &MeterCreateBulk{err: fmt.Errorf("calling to MeterClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*MeterCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &MeterCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Meter. +func (c *MeterClient) Update() *MeterUpdate { + mutation := newMeterMutation(c.config, OpUpdate) + return &MeterUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *MeterClient) UpdateOne(_m *Meter) *MeterUpdateOne { + mutation := newMeterMutation(c.config, OpUpdateOne, withMeter(_m)) + return &MeterUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *MeterClient) UpdateOneID(id string) *MeterUpdateOne { + mutation := newMeterMutation(c.config, OpUpdateOne, withMeterID(id)) + return &MeterUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Meter. +func (c *MeterClient) Delete() *MeterDelete { + mutation := newMeterMutation(c.config, OpDelete) + return &MeterDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *MeterClient) DeleteOne(_m *Meter) *MeterDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *MeterClient) DeleteOneID(id string) *MeterDeleteOne { + builder := c.Delete().Where(dbmeter.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &MeterDeleteOne{builder} +} + +// Query returns a query builder for Meter. +func (c *MeterClient) Query() *MeterQuery { + return &MeterQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeMeter}, + inters: c.Interceptors(), + } +} + +// Get returns a Meter entity by its id. +func (c *MeterClient) Get(ctx context.Context, id string) (*Meter, error) { + return c.Query().Where(dbmeter.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *MeterClient) GetX(ctx context.Context, id string) *Meter { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryFeature queries the feature edge of a Meter. +func (c *MeterClient) QueryFeature(_m *Meter) *FeatureQuery { + query := (&FeatureClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbmeter.Table, dbmeter.FieldID, id), + sqlgraph.To(dbfeature.Table, dbfeature.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbmeter.FeatureTable, dbmeter.FeatureColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *MeterClient) Hooks() []Hook { + return c.hooks.Meter +} + +// Interceptors returns the client interceptors. +func (c *MeterClient) Interceptors() []Interceptor { + return c.inters.Meter +} + +func (c *MeterClient) mutate(ctx context.Context, m *MeterMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&MeterCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&MeterUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&MeterUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&MeterDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown Meter mutation op: %q", m.Op()) + } +} + +// NotificationChannelClient is a client for the NotificationChannel schema. +type NotificationChannelClient struct { + config +} + +// NewNotificationChannelClient returns a client for the NotificationChannel from the given config. +func NewNotificationChannelClient(c config) *NotificationChannelClient { + return &NotificationChannelClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `notificationchannel.Hooks(f(g(h())))`. +func (c *NotificationChannelClient) Use(hooks ...Hook) { + c.hooks.NotificationChannel = append(c.hooks.NotificationChannel, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `notificationchannel.Intercept(f(g(h())))`. +func (c *NotificationChannelClient) Intercept(interceptors ...Interceptor) { + c.inters.NotificationChannel = append(c.inters.NotificationChannel, interceptors...) +} + +// Create returns a builder for creating a NotificationChannel entity. +func (c *NotificationChannelClient) Create() *NotificationChannelCreate { + mutation := newNotificationChannelMutation(c.config, OpCreate) + return &NotificationChannelCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of NotificationChannel entities. +func (c *NotificationChannelClient) CreateBulk(builders ...*NotificationChannelCreate) *NotificationChannelCreateBulk { + return &NotificationChannelCreateBulk{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 *NotificationChannelClient) MapCreateBulk(slice any, setFunc func(*NotificationChannelCreate, int)) *NotificationChannelCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &NotificationChannelCreateBulk{err: fmt.Errorf("calling to NotificationChannelClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*NotificationChannelCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &NotificationChannelCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for NotificationChannel. +func (c *NotificationChannelClient) Update() *NotificationChannelUpdate { + mutation := newNotificationChannelMutation(c.config, OpUpdate) + return &NotificationChannelUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *NotificationChannelClient) UpdateOne(_m *NotificationChannel) *NotificationChannelUpdateOne { + mutation := newNotificationChannelMutation(c.config, OpUpdateOne, withNotificationChannel(_m)) + return &NotificationChannelUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *NotificationChannelClient) UpdateOneID(id string) *NotificationChannelUpdateOne { + mutation := newNotificationChannelMutation(c.config, OpUpdateOne, withNotificationChannelID(id)) + return &NotificationChannelUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for NotificationChannel. +func (c *NotificationChannelClient) Delete() *NotificationChannelDelete { + mutation := newNotificationChannelMutation(c.config, OpDelete) + return &NotificationChannelDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *NotificationChannelClient) DeleteOne(_m *NotificationChannel) *NotificationChannelDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *NotificationChannelClient) DeleteOneID(id string) *NotificationChannelDeleteOne { + builder := c.Delete().Where(notificationchannel.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &NotificationChannelDeleteOne{builder} +} + +// Query returns a query builder for NotificationChannel. +func (c *NotificationChannelClient) Query() *NotificationChannelQuery { + return &NotificationChannelQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeNotificationChannel}, + inters: c.Interceptors(), + } +} + +// Get returns a NotificationChannel entity by its id. +func (c *NotificationChannelClient) Get(ctx context.Context, id string) (*NotificationChannel, error) { + return c.Query().Where(notificationchannel.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *NotificationChannelClient) GetX(ctx context.Context, id string) *NotificationChannel { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryRules queries the rules edge of a NotificationChannel. +func (c *NotificationChannelClient) QueryRules(_m *NotificationChannel) *NotificationRuleQuery { + query := (&NotificationRuleClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(notificationchannel.Table, notificationchannel.FieldID, id), + sqlgraph.To(notificationrule.Table, notificationrule.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, notificationchannel.RulesTable, notificationchannel.RulesPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *NotificationChannelClient) Hooks() []Hook { + return c.hooks.NotificationChannel +} + +// Interceptors returns the client interceptors. +func (c *NotificationChannelClient) Interceptors() []Interceptor { + return c.inters.NotificationChannel +} + +func (c *NotificationChannelClient) mutate(ctx context.Context, m *NotificationChannelMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&NotificationChannelCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&NotificationChannelUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&NotificationChannelUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&NotificationChannelDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown NotificationChannel mutation op: %q", m.Op()) + } +} + +// NotificationEventClient is a client for the NotificationEvent schema. +type NotificationEventClient struct { + config +} + +// NewNotificationEventClient returns a client for the NotificationEvent from the given config. +func NewNotificationEventClient(c config) *NotificationEventClient { + return &NotificationEventClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `notificationevent.Hooks(f(g(h())))`. +func (c *NotificationEventClient) Use(hooks ...Hook) { + c.hooks.NotificationEvent = append(c.hooks.NotificationEvent, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `notificationevent.Intercept(f(g(h())))`. +func (c *NotificationEventClient) Intercept(interceptors ...Interceptor) { + c.inters.NotificationEvent = append(c.inters.NotificationEvent, interceptors...) +} + +// Create returns a builder for creating a NotificationEvent entity. +func (c *NotificationEventClient) Create() *NotificationEventCreate { + mutation := newNotificationEventMutation(c.config, OpCreate) + return &NotificationEventCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of NotificationEvent entities. +func (c *NotificationEventClient) CreateBulk(builders ...*NotificationEventCreate) *NotificationEventCreateBulk { + return &NotificationEventCreateBulk{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 *NotificationEventClient) MapCreateBulk(slice any, setFunc func(*NotificationEventCreate, int)) *NotificationEventCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &NotificationEventCreateBulk{err: fmt.Errorf("calling to NotificationEventClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*NotificationEventCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &NotificationEventCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for NotificationEvent. +func (c *NotificationEventClient) Update() *NotificationEventUpdate { + mutation := newNotificationEventMutation(c.config, OpUpdate) + return &NotificationEventUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *NotificationEventClient) UpdateOne(_m *NotificationEvent) *NotificationEventUpdateOne { + mutation := newNotificationEventMutation(c.config, OpUpdateOne, withNotificationEvent(_m)) + return &NotificationEventUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *NotificationEventClient) UpdateOneID(id string) *NotificationEventUpdateOne { + mutation := newNotificationEventMutation(c.config, OpUpdateOne, withNotificationEventID(id)) + return &NotificationEventUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for NotificationEvent. +func (c *NotificationEventClient) Delete() *NotificationEventDelete { + mutation := newNotificationEventMutation(c.config, OpDelete) + return &NotificationEventDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *NotificationEventClient) DeleteOne(_m *NotificationEvent) *NotificationEventDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *NotificationEventClient) DeleteOneID(id string) *NotificationEventDeleteOne { + builder := c.Delete().Where(notificationevent.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &NotificationEventDeleteOne{builder} +} + +// Query returns a query builder for NotificationEvent. +func (c *NotificationEventClient) Query() *NotificationEventQuery { + return &NotificationEventQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeNotificationEvent}, + inters: c.Interceptors(), + } +} + +// Get returns a NotificationEvent entity by its id. +func (c *NotificationEventClient) Get(ctx context.Context, id string) (*NotificationEvent, error) { + return c.Query().Where(notificationevent.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *NotificationEventClient) GetX(ctx context.Context, id string) *NotificationEvent { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryDeliveryStatuses queries the delivery_statuses edge of a NotificationEvent. +func (c *NotificationEventClient) QueryDeliveryStatuses(_m *NotificationEvent) *NotificationEventDeliveryStatusQuery { + query := (&NotificationEventDeliveryStatusClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(notificationevent.Table, notificationevent.FieldID, id), + sqlgraph.To(notificationeventdeliverystatus.Table, notificationeventdeliverystatus.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, notificationevent.DeliveryStatusesTable, notificationevent.DeliveryStatusesPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryRules queries the rules edge of a NotificationEvent. +func (c *NotificationEventClient) QueryRules(_m *NotificationEvent) *NotificationRuleQuery { + query := (&NotificationRuleClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(notificationevent.Table, notificationevent.FieldID, id), + sqlgraph.To(notificationrule.Table, notificationrule.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, notificationevent.RulesTable, notificationevent.RulesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *NotificationEventClient) Hooks() []Hook { + return c.hooks.NotificationEvent +} + +// Interceptors returns the client interceptors. +func (c *NotificationEventClient) Interceptors() []Interceptor { + return c.inters.NotificationEvent +} + +func (c *NotificationEventClient) mutate(ctx context.Context, m *NotificationEventMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&NotificationEventCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&NotificationEventUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&NotificationEventUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&NotificationEventDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown NotificationEvent mutation op: %q", m.Op()) + } +} + +// NotificationEventDeliveryStatusClient is a client for the NotificationEventDeliveryStatus schema. +type NotificationEventDeliveryStatusClient struct { + config +} + +// NewNotificationEventDeliveryStatusClient returns a client for the NotificationEventDeliveryStatus from the given config. +func NewNotificationEventDeliveryStatusClient(c config) *NotificationEventDeliveryStatusClient { + return &NotificationEventDeliveryStatusClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `notificationeventdeliverystatus.Hooks(f(g(h())))`. +func (c *NotificationEventDeliveryStatusClient) Use(hooks ...Hook) { + c.hooks.NotificationEventDeliveryStatus = append(c.hooks.NotificationEventDeliveryStatus, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `notificationeventdeliverystatus.Intercept(f(g(h())))`. +func (c *NotificationEventDeliveryStatusClient) Intercept(interceptors ...Interceptor) { + c.inters.NotificationEventDeliveryStatus = append(c.inters.NotificationEventDeliveryStatus, interceptors...) +} + +// Create returns a builder for creating a NotificationEventDeliveryStatus entity. +func (c *NotificationEventDeliveryStatusClient) Create() *NotificationEventDeliveryStatusCreate { + mutation := newNotificationEventDeliveryStatusMutation(c.config, OpCreate) + return &NotificationEventDeliveryStatusCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of NotificationEventDeliveryStatus entities. +func (c *NotificationEventDeliveryStatusClient) CreateBulk(builders ...*NotificationEventDeliveryStatusCreate) *NotificationEventDeliveryStatusCreateBulk { + return &NotificationEventDeliveryStatusCreateBulk{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 *NotificationEventDeliveryStatusClient) MapCreateBulk(slice any, setFunc func(*NotificationEventDeliveryStatusCreate, int)) *NotificationEventDeliveryStatusCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &NotificationEventDeliveryStatusCreateBulk{err: fmt.Errorf("calling to NotificationEventDeliveryStatusClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*NotificationEventDeliveryStatusCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &NotificationEventDeliveryStatusCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for NotificationEventDeliveryStatus. +func (c *NotificationEventDeliveryStatusClient) Update() *NotificationEventDeliveryStatusUpdate { + mutation := newNotificationEventDeliveryStatusMutation(c.config, OpUpdate) + return &NotificationEventDeliveryStatusUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *NotificationEventDeliveryStatusClient) UpdateOne(_m *NotificationEventDeliveryStatus) *NotificationEventDeliveryStatusUpdateOne { + mutation := newNotificationEventDeliveryStatusMutation(c.config, OpUpdateOne, withNotificationEventDeliveryStatus(_m)) + return &NotificationEventDeliveryStatusUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *NotificationEventDeliveryStatusClient) UpdateOneID(id string) *NotificationEventDeliveryStatusUpdateOne { + mutation := newNotificationEventDeliveryStatusMutation(c.config, OpUpdateOne, withNotificationEventDeliveryStatusID(id)) + return &NotificationEventDeliveryStatusUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for NotificationEventDeliveryStatus. +func (c *NotificationEventDeliveryStatusClient) Delete() *NotificationEventDeliveryStatusDelete { + mutation := newNotificationEventDeliveryStatusMutation(c.config, OpDelete) + return &NotificationEventDeliveryStatusDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *NotificationEventDeliveryStatusClient) DeleteOne(_m *NotificationEventDeliveryStatus) *NotificationEventDeliveryStatusDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *NotificationEventDeliveryStatusClient) DeleteOneID(id string) *NotificationEventDeliveryStatusDeleteOne { + builder := c.Delete().Where(notificationeventdeliverystatus.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &NotificationEventDeliveryStatusDeleteOne{builder} +} + +// Query returns a query builder for NotificationEventDeliveryStatus. +func (c *NotificationEventDeliveryStatusClient) Query() *NotificationEventDeliveryStatusQuery { + return &NotificationEventDeliveryStatusQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeNotificationEventDeliveryStatus}, + inters: c.Interceptors(), + } +} + +// Get returns a NotificationEventDeliveryStatus entity by its id. +func (c *NotificationEventDeliveryStatusClient) Get(ctx context.Context, id string) (*NotificationEventDeliveryStatus, error) { + return c.Query().Where(notificationeventdeliverystatus.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *NotificationEventDeliveryStatusClient) GetX(ctx context.Context, id string) *NotificationEventDeliveryStatus { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryEvents queries the events edge of a NotificationEventDeliveryStatus. +func (c *NotificationEventDeliveryStatusClient) QueryEvents(_m *NotificationEventDeliveryStatus) *NotificationEventQuery { + query := (&NotificationEventClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(notificationeventdeliverystatus.Table, notificationeventdeliverystatus.FieldID, id), + sqlgraph.To(notificationevent.Table, notificationevent.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, notificationeventdeliverystatus.EventsTable, notificationeventdeliverystatus.EventsPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *NotificationEventDeliveryStatusClient) Hooks() []Hook { + return c.hooks.NotificationEventDeliveryStatus +} + +// Interceptors returns the client interceptors. +func (c *NotificationEventDeliveryStatusClient) Interceptors() []Interceptor { + return c.inters.NotificationEventDeliveryStatus +} + +func (c *NotificationEventDeliveryStatusClient) mutate(ctx context.Context, m *NotificationEventDeliveryStatusMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&NotificationEventDeliveryStatusCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&NotificationEventDeliveryStatusUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&NotificationEventDeliveryStatusUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&NotificationEventDeliveryStatusDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown NotificationEventDeliveryStatus mutation op: %q", m.Op()) + } +} + +// NotificationRuleClient is a client for the NotificationRule schema. +type NotificationRuleClient struct { + config +} + +// NewNotificationRuleClient returns a client for the NotificationRule from the given config. +func NewNotificationRuleClient(c config) *NotificationRuleClient { + return &NotificationRuleClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `notificationrule.Hooks(f(g(h())))`. +func (c *NotificationRuleClient) Use(hooks ...Hook) { + c.hooks.NotificationRule = append(c.hooks.NotificationRule, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `notificationrule.Intercept(f(g(h())))`. +func (c *NotificationRuleClient) Intercept(interceptors ...Interceptor) { + c.inters.NotificationRule = append(c.inters.NotificationRule, interceptors...) +} + +// Create returns a builder for creating a NotificationRule entity. +func (c *NotificationRuleClient) Create() *NotificationRuleCreate { + mutation := newNotificationRuleMutation(c.config, OpCreate) + return &NotificationRuleCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of NotificationRule entities. +func (c *NotificationRuleClient) CreateBulk(builders ...*NotificationRuleCreate) *NotificationRuleCreateBulk { + return &NotificationRuleCreateBulk{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 *NotificationRuleClient) MapCreateBulk(slice any, setFunc func(*NotificationRuleCreate, int)) *NotificationRuleCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &NotificationRuleCreateBulk{err: fmt.Errorf("calling to NotificationRuleClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*NotificationRuleCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &NotificationRuleCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for NotificationRule. +func (c *NotificationRuleClient) Update() *NotificationRuleUpdate { + mutation := newNotificationRuleMutation(c.config, OpUpdate) + return &NotificationRuleUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *NotificationRuleClient) UpdateOne(_m *NotificationRule) *NotificationRuleUpdateOne { + mutation := newNotificationRuleMutation(c.config, OpUpdateOne, withNotificationRule(_m)) + return &NotificationRuleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *NotificationRuleClient) UpdateOneID(id string) *NotificationRuleUpdateOne { + mutation := newNotificationRuleMutation(c.config, OpUpdateOne, withNotificationRuleID(id)) + return &NotificationRuleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for NotificationRule. +func (c *NotificationRuleClient) Delete() *NotificationRuleDelete { + mutation := newNotificationRuleMutation(c.config, OpDelete) + return &NotificationRuleDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *NotificationRuleClient) DeleteOne(_m *NotificationRule) *NotificationRuleDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *NotificationRuleClient) DeleteOneID(id string) *NotificationRuleDeleteOne { + builder := c.Delete().Where(notificationrule.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &NotificationRuleDeleteOne{builder} +} + +// Query returns a query builder for NotificationRule. +func (c *NotificationRuleClient) Query() *NotificationRuleQuery { + return &NotificationRuleQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeNotificationRule}, + inters: c.Interceptors(), + } +} + +// Get returns a NotificationRule entity by its id. +func (c *NotificationRuleClient) Get(ctx context.Context, id string) (*NotificationRule, error) { + return c.Query().Where(notificationrule.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *NotificationRuleClient) GetX(ctx context.Context, id string) *NotificationRule { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryChannels queries the channels edge of a NotificationRule. +func (c *NotificationRuleClient) QueryChannels(_m *NotificationRule) *NotificationChannelQuery { + query := (&NotificationChannelClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(notificationrule.Table, notificationrule.FieldID, id), + sqlgraph.To(notificationchannel.Table, notificationchannel.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, notificationrule.ChannelsTable, notificationrule.ChannelsPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryEvents queries the events edge of a NotificationRule. +func (c *NotificationRuleClient) QueryEvents(_m *NotificationRule) *NotificationEventQuery { + query := (&NotificationEventClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(notificationrule.Table, notificationrule.FieldID, id), + sqlgraph.To(notificationevent.Table, notificationevent.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, notificationrule.EventsTable, notificationrule.EventsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *NotificationRuleClient) Hooks() []Hook { + return c.hooks.NotificationRule +} + +// Interceptors returns the client interceptors. +func (c *NotificationRuleClient) Interceptors() []Interceptor { + return c.inters.NotificationRule +} + +func (c *NotificationRuleClient) mutate(ctx context.Context, m *NotificationRuleMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&NotificationRuleCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&NotificationRuleUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&NotificationRuleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&NotificationRuleDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown NotificationRule mutation op: %q", m.Op()) + } +} + +// OrganizationDefaultTaxCodesClient is a client for the OrganizationDefaultTaxCodes schema. +type OrganizationDefaultTaxCodesClient struct { + config +} + +// NewOrganizationDefaultTaxCodesClient returns a client for the OrganizationDefaultTaxCodes from the given config. +func NewOrganizationDefaultTaxCodesClient(c config) *OrganizationDefaultTaxCodesClient { + return &OrganizationDefaultTaxCodesClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `organizationdefaulttaxcodes.Hooks(f(g(h())))`. +func (c *OrganizationDefaultTaxCodesClient) Use(hooks ...Hook) { + c.hooks.OrganizationDefaultTaxCodes = append(c.hooks.OrganizationDefaultTaxCodes, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `organizationdefaulttaxcodes.Intercept(f(g(h())))`. +func (c *OrganizationDefaultTaxCodesClient) Intercept(interceptors ...Interceptor) { + c.inters.OrganizationDefaultTaxCodes = append(c.inters.OrganizationDefaultTaxCodes, interceptors...) +} + +// Create returns a builder for creating a OrganizationDefaultTaxCodes entity. +func (c *OrganizationDefaultTaxCodesClient) Create() *OrganizationDefaultTaxCodesCreate { + mutation := newOrganizationDefaultTaxCodesMutation(c.config, OpCreate) + return &OrganizationDefaultTaxCodesCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of OrganizationDefaultTaxCodes entities. +func (c *OrganizationDefaultTaxCodesClient) CreateBulk(builders ...*OrganizationDefaultTaxCodesCreate) *OrganizationDefaultTaxCodesCreateBulk { + return &OrganizationDefaultTaxCodesCreateBulk{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 *OrganizationDefaultTaxCodesClient) MapCreateBulk(slice any, setFunc func(*OrganizationDefaultTaxCodesCreate, int)) *OrganizationDefaultTaxCodesCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &OrganizationDefaultTaxCodesCreateBulk{err: fmt.Errorf("calling to OrganizationDefaultTaxCodesClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*OrganizationDefaultTaxCodesCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &OrganizationDefaultTaxCodesCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for OrganizationDefaultTaxCodes. +func (c *OrganizationDefaultTaxCodesClient) Update() *OrganizationDefaultTaxCodesUpdate { + mutation := newOrganizationDefaultTaxCodesMutation(c.config, OpUpdate) + return &OrganizationDefaultTaxCodesUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *OrganizationDefaultTaxCodesClient) UpdateOne(_m *OrganizationDefaultTaxCodes) *OrganizationDefaultTaxCodesUpdateOne { + mutation := newOrganizationDefaultTaxCodesMutation(c.config, OpUpdateOne, withOrganizationDefaultTaxCodes(_m)) + return &OrganizationDefaultTaxCodesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *OrganizationDefaultTaxCodesClient) UpdateOneID(id string) *OrganizationDefaultTaxCodesUpdateOne { + mutation := newOrganizationDefaultTaxCodesMutation(c.config, OpUpdateOne, withOrganizationDefaultTaxCodesID(id)) + return &OrganizationDefaultTaxCodesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for OrganizationDefaultTaxCodes. +func (c *OrganizationDefaultTaxCodesClient) Delete() *OrganizationDefaultTaxCodesDelete { + mutation := newOrganizationDefaultTaxCodesMutation(c.config, OpDelete) + return &OrganizationDefaultTaxCodesDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *OrganizationDefaultTaxCodesClient) DeleteOne(_m *OrganizationDefaultTaxCodes) *OrganizationDefaultTaxCodesDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *OrganizationDefaultTaxCodesClient) DeleteOneID(id string) *OrganizationDefaultTaxCodesDeleteOne { + builder := c.Delete().Where(organizationdefaulttaxcodes.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &OrganizationDefaultTaxCodesDeleteOne{builder} +} + +// Query returns a query builder for OrganizationDefaultTaxCodes. +func (c *OrganizationDefaultTaxCodesClient) Query() *OrganizationDefaultTaxCodesQuery { + return &OrganizationDefaultTaxCodesQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeOrganizationDefaultTaxCodes}, + inters: c.Interceptors(), + } +} + +// Get returns a OrganizationDefaultTaxCodes entity by its id. +func (c *OrganizationDefaultTaxCodesClient) Get(ctx context.Context, id string) (*OrganizationDefaultTaxCodes, error) { + return c.Query().Where(organizationdefaulttaxcodes.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *OrganizationDefaultTaxCodesClient) GetX(ctx context.Context, id string) *OrganizationDefaultTaxCodes { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryInvoicingTaxCode queries the invoicing_tax_code edge of a OrganizationDefaultTaxCodes. +func (c *OrganizationDefaultTaxCodesClient) QueryInvoicingTaxCode(_m *OrganizationDefaultTaxCodes) *TaxCodeQuery { + query := (&TaxCodeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(organizationdefaulttaxcodes.Table, organizationdefaulttaxcodes.FieldID, id), + sqlgraph.To(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, organizationdefaulttaxcodes.InvoicingTaxCodeTable, organizationdefaulttaxcodes.InvoicingTaxCodeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCreditGrantTaxCode queries the credit_grant_tax_code edge of a OrganizationDefaultTaxCodes. +func (c *OrganizationDefaultTaxCodesClient) QueryCreditGrantTaxCode(_m *OrganizationDefaultTaxCodes) *TaxCodeQuery { + query := (&TaxCodeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(organizationdefaulttaxcodes.Table, organizationdefaulttaxcodes.FieldID, id), + sqlgraph.To(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, organizationdefaulttaxcodes.CreditGrantTaxCodeTable, organizationdefaulttaxcodes.CreditGrantTaxCodeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *OrganizationDefaultTaxCodesClient) Hooks() []Hook { + return c.hooks.OrganizationDefaultTaxCodes +} + +// Interceptors returns the client interceptors. +func (c *OrganizationDefaultTaxCodesClient) Interceptors() []Interceptor { + return c.inters.OrganizationDefaultTaxCodes +} + +func (c *OrganizationDefaultTaxCodesClient) mutate(ctx context.Context, m *OrganizationDefaultTaxCodesMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&OrganizationDefaultTaxCodesCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&OrganizationDefaultTaxCodesUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&OrganizationDefaultTaxCodesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&OrganizationDefaultTaxCodesDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown OrganizationDefaultTaxCodes mutation op: %q", m.Op()) + } +} + +// PlanClient is a client for the Plan schema. +type PlanClient struct { + config +} + +// NewPlanClient returns a client for the Plan from the given config. +func NewPlanClient(c config) *PlanClient { + return &PlanClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `plan.Hooks(f(g(h())))`. +func (c *PlanClient) Use(hooks ...Hook) { + c.hooks.Plan = append(c.hooks.Plan, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `plan.Intercept(f(g(h())))`. +func (c *PlanClient) Intercept(interceptors ...Interceptor) { + c.inters.Plan = append(c.inters.Plan, interceptors...) +} + +// Create returns a builder for creating a Plan entity. +func (c *PlanClient) Create() *PlanCreate { + mutation := newPlanMutation(c.config, OpCreate) + return &PlanCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Plan entities. +func (c *PlanClient) CreateBulk(builders ...*PlanCreate) *PlanCreateBulk { + return &PlanCreateBulk{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 *PlanClient) MapCreateBulk(slice any, setFunc func(*PlanCreate, int)) *PlanCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &PlanCreateBulk{err: fmt.Errorf("calling to PlanClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*PlanCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &PlanCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Plan. +func (c *PlanClient) Update() *PlanUpdate { + mutation := newPlanMutation(c.config, OpUpdate) + return &PlanUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *PlanClient) UpdateOne(_m *Plan) *PlanUpdateOne { + mutation := newPlanMutation(c.config, OpUpdateOne, withPlan(_m)) + return &PlanUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *PlanClient) UpdateOneID(id string) *PlanUpdateOne { + mutation := newPlanMutation(c.config, OpUpdateOne, withPlanID(id)) + return &PlanUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Plan. +func (c *PlanClient) Delete() *PlanDelete { + mutation := newPlanMutation(c.config, OpDelete) + return &PlanDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *PlanClient) DeleteOne(_m *Plan) *PlanDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *PlanClient) DeleteOneID(id string) *PlanDeleteOne { + builder := c.Delete().Where(plan.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &PlanDeleteOne{builder} +} + +// Query returns a query builder for Plan. +func (c *PlanClient) Query() *PlanQuery { + return &PlanQuery{ + config: c.config, + ctx: &QueryContext{Type: TypePlan}, + inters: c.Interceptors(), + } +} + +// Get returns a Plan entity by its id. +func (c *PlanClient) Get(ctx context.Context, id string) (*Plan, error) { + return c.Query().Where(plan.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *PlanClient) GetX(ctx context.Context, id string) *Plan { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryPhases queries the phases edge of a Plan. +func (c *PlanClient) QueryPhases(_m *Plan) *PlanPhaseQuery { + query := (&PlanPhaseClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(plan.Table, plan.FieldID, id), + sqlgraph.To(planphase.Table, planphase.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, plan.PhasesTable, plan.PhasesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryAddons queries the addons edge of a Plan. +func (c *PlanClient) QueryAddons(_m *Plan) *PlanAddonQuery { + query := (&PlanAddonClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(plan.Table, plan.FieldID, id), + sqlgraph.To(planaddon.Table, planaddon.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, plan.AddonsTable, plan.AddonsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubscriptions queries the subscriptions edge of a Plan. +func (c *PlanClient) QuerySubscriptions(_m *Plan) *SubscriptionQuery { + query := (&SubscriptionClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(plan.Table, plan.FieldID, id), + sqlgraph.To(subscription.Table, subscription.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, plan.SubscriptionsTable, plan.SubscriptionsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *PlanClient) Hooks() []Hook { + return c.hooks.Plan +} + +// Interceptors returns the client interceptors. +func (c *PlanClient) Interceptors() []Interceptor { + return c.inters.Plan +} + +func (c *PlanClient) mutate(ctx context.Context, m *PlanMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&PlanCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&PlanUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&PlanUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&PlanDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown Plan mutation op: %q", m.Op()) + } +} + +// PlanAddonClient is a client for the PlanAddon schema. +type PlanAddonClient struct { + config +} + +// NewPlanAddonClient returns a client for the PlanAddon from the given config. +func NewPlanAddonClient(c config) *PlanAddonClient { + return &PlanAddonClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `planaddon.Hooks(f(g(h())))`. +func (c *PlanAddonClient) Use(hooks ...Hook) { + c.hooks.PlanAddon = append(c.hooks.PlanAddon, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `planaddon.Intercept(f(g(h())))`. +func (c *PlanAddonClient) Intercept(interceptors ...Interceptor) { + c.inters.PlanAddon = append(c.inters.PlanAddon, interceptors...) +} + +// Create returns a builder for creating a PlanAddon entity. +func (c *PlanAddonClient) Create() *PlanAddonCreate { + mutation := newPlanAddonMutation(c.config, OpCreate) + return &PlanAddonCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of PlanAddon entities. +func (c *PlanAddonClient) CreateBulk(builders ...*PlanAddonCreate) *PlanAddonCreateBulk { + return &PlanAddonCreateBulk{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 *PlanAddonClient) MapCreateBulk(slice any, setFunc func(*PlanAddonCreate, int)) *PlanAddonCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &PlanAddonCreateBulk{err: fmt.Errorf("calling to PlanAddonClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*PlanAddonCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &PlanAddonCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for PlanAddon. +func (c *PlanAddonClient) Update() *PlanAddonUpdate { + mutation := newPlanAddonMutation(c.config, OpUpdate) + return &PlanAddonUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *PlanAddonClient) UpdateOne(_m *PlanAddon) *PlanAddonUpdateOne { + mutation := newPlanAddonMutation(c.config, OpUpdateOne, withPlanAddon(_m)) + return &PlanAddonUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *PlanAddonClient) UpdateOneID(id string) *PlanAddonUpdateOne { + mutation := newPlanAddonMutation(c.config, OpUpdateOne, withPlanAddonID(id)) + return &PlanAddonUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for PlanAddon. +func (c *PlanAddonClient) Delete() *PlanAddonDelete { + mutation := newPlanAddonMutation(c.config, OpDelete) + return &PlanAddonDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *PlanAddonClient) DeleteOne(_m *PlanAddon) *PlanAddonDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *PlanAddonClient) DeleteOneID(id string) *PlanAddonDeleteOne { + builder := c.Delete().Where(planaddon.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &PlanAddonDeleteOne{builder} +} + +// Query returns a query builder for PlanAddon. +func (c *PlanAddonClient) Query() *PlanAddonQuery { + return &PlanAddonQuery{ + config: c.config, + ctx: &QueryContext{Type: TypePlanAddon}, + inters: c.Interceptors(), + } +} + +// Get returns a PlanAddon entity by its id. +func (c *PlanAddonClient) Get(ctx context.Context, id string) (*PlanAddon, error) { + return c.Query().Where(planaddon.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *PlanAddonClient) GetX(ctx context.Context, id string) *PlanAddon { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryPlan queries the plan edge of a PlanAddon. +func (c *PlanAddonClient) QueryPlan(_m *PlanAddon) *PlanQuery { + query := (&PlanClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(planaddon.Table, planaddon.FieldID, id), + sqlgraph.To(plan.Table, plan.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, planaddon.PlanTable, planaddon.PlanColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryAddon queries the addon edge of a PlanAddon. +func (c *PlanAddonClient) QueryAddon(_m *PlanAddon) *AddonQuery { + query := (&AddonClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(planaddon.Table, planaddon.FieldID, id), + sqlgraph.To(addon.Table, addon.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, planaddon.AddonTable, planaddon.AddonColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *PlanAddonClient) Hooks() []Hook { + return c.hooks.PlanAddon +} + +// Interceptors returns the client interceptors. +func (c *PlanAddonClient) Interceptors() []Interceptor { + return c.inters.PlanAddon +} + +func (c *PlanAddonClient) mutate(ctx context.Context, m *PlanAddonMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&PlanAddonCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&PlanAddonUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&PlanAddonUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&PlanAddonDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown PlanAddon mutation op: %q", m.Op()) + } +} + +// PlanPhaseClient is a client for the PlanPhase schema. +type PlanPhaseClient struct { + config +} + +// NewPlanPhaseClient returns a client for the PlanPhase from the given config. +func NewPlanPhaseClient(c config) *PlanPhaseClient { + return &PlanPhaseClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `planphase.Hooks(f(g(h())))`. +func (c *PlanPhaseClient) Use(hooks ...Hook) { + c.hooks.PlanPhase = append(c.hooks.PlanPhase, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `planphase.Intercept(f(g(h())))`. +func (c *PlanPhaseClient) Intercept(interceptors ...Interceptor) { + c.inters.PlanPhase = append(c.inters.PlanPhase, interceptors...) +} + +// Create returns a builder for creating a PlanPhase entity. +func (c *PlanPhaseClient) Create() *PlanPhaseCreate { + mutation := newPlanPhaseMutation(c.config, OpCreate) + return &PlanPhaseCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of PlanPhase entities. +func (c *PlanPhaseClient) CreateBulk(builders ...*PlanPhaseCreate) *PlanPhaseCreateBulk { + return &PlanPhaseCreateBulk{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 *PlanPhaseClient) MapCreateBulk(slice any, setFunc func(*PlanPhaseCreate, int)) *PlanPhaseCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &PlanPhaseCreateBulk{err: fmt.Errorf("calling to PlanPhaseClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*PlanPhaseCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &PlanPhaseCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for PlanPhase. +func (c *PlanPhaseClient) Update() *PlanPhaseUpdate { + mutation := newPlanPhaseMutation(c.config, OpUpdate) + return &PlanPhaseUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *PlanPhaseClient) UpdateOne(_m *PlanPhase) *PlanPhaseUpdateOne { + mutation := newPlanPhaseMutation(c.config, OpUpdateOne, withPlanPhase(_m)) + return &PlanPhaseUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *PlanPhaseClient) UpdateOneID(id string) *PlanPhaseUpdateOne { + mutation := newPlanPhaseMutation(c.config, OpUpdateOne, withPlanPhaseID(id)) + return &PlanPhaseUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for PlanPhase. +func (c *PlanPhaseClient) Delete() *PlanPhaseDelete { + mutation := newPlanPhaseMutation(c.config, OpDelete) + return &PlanPhaseDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *PlanPhaseClient) DeleteOne(_m *PlanPhase) *PlanPhaseDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *PlanPhaseClient) DeleteOneID(id string) *PlanPhaseDeleteOne { + builder := c.Delete().Where(planphase.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &PlanPhaseDeleteOne{builder} +} + +// Query returns a query builder for PlanPhase. +func (c *PlanPhaseClient) Query() *PlanPhaseQuery { + return &PlanPhaseQuery{ + config: c.config, + ctx: &QueryContext{Type: TypePlanPhase}, + inters: c.Interceptors(), + } +} + +// Get returns a PlanPhase entity by its id. +func (c *PlanPhaseClient) Get(ctx context.Context, id string) (*PlanPhase, error) { + return c.Query().Where(planphase.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *PlanPhaseClient) GetX(ctx context.Context, id string) *PlanPhase { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryPlan queries the plan edge of a PlanPhase. +func (c *PlanPhaseClient) QueryPlan(_m *PlanPhase) *PlanQuery { + query := (&PlanClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(planphase.Table, planphase.FieldID, id), + sqlgraph.To(plan.Table, plan.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, planphase.PlanTable, planphase.PlanColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryRatecards queries the ratecards edge of a PlanPhase. +func (c *PlanPhaseClient) QueryRatecards(_m *PlanPhase) *PlanRateCardQuery { + query := (&PlanRateCardClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(planphase.Table, planphase.FieldID, id), + sqlgraph.To(planratecard.Table, planratecard.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, planphase.RatecardsTable, planphase.RatecardsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *PlanPhaseClient) Hooks() []Hook { + return c.hooks.PlanPhase +} + +// Interceptors returns the client interceptors. +func (c *PlanPhaseClient) Interceptors() []Interceptor { + return c.inters.PlanPhase +} + +func (c *PlanPhaseClient) mutate(ctx context.Context, m *PlanPhaseMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&PlanPhaseCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&PlanPhaseUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&PlanPhaseUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&PlanPhaseDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown PlanPhase mutation op: %q", m.Op()) + } +} + +// PlanRateCardClient is a client for the PlanRateCard schema. +type PlanRateCardClient struct { + config +} + +// NewPlanRateCardClient returns a client for the PlanRateCard from the given config. +func NewPlanRateCardClient(c config) *PlanRateCardClient { + return &PlanRateCardClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `planratecard.Hooks(f(g(h())))`. +func (c *PlanRateCardClient) Use(hooks ...Hook) { + c.hooks.PlanRateCard = append(c.hooks.PlanRateCard, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `planratecard.Intercept(f(g(h())))`. +func (c *PlanRateCardClient) Intercept(interceptors ...Interceptor) { + c.inters.PlanRateCard = append(c.inters.PlanRateCard, interceptors...) +} + +// Create returns a builder for creating a PlanRateCard entity. +func (c *PlanRateCardClient) Create() *PlanRateCardCreate { + mutation := newPlanRateCardMutation(c.config, OpCreate) + return &PlanRateCardCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of PlanRateCard entities. +func (c *PlanRateCardClient) CreateBulk(builders ...*PlanRateCardCreate) *PlanRateCardCreateBulk { + return &PlanRateCardCreateBulk{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 *PlanRateCardClient) MapCreateBulk(slice any, setFunc func(*PlanRateCardCreate, int)) *PlanRateCardCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &PlanRateCardCreateBulk{err: fmt.Errorf("calling to PlanRateCardClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*PlanRateCardCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &PlanRateCardCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for PlanRateCard. +func (c *PlanRateCardClient) Update() *PlanRateCardUpdate { + mutation := newPlanRateCardMutation(c.config, OpUpdate) + return &PlanRateCardUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *PlanRateCardClient) UpdateOne(_m *PlanRateCard) *PlanRateCardUpdateOne { + mutation := newPlanRateCardMutation(c.config, OpUpdateOne, withPlanRateCard(_m)) + return &PlanRateCardUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *PlanRateCardClient) UpdateOneID(id string) *PlanRateCardUpdateOne { + mutation := newPlanRateCardMutation(c.config, OpUpdateOne, withPlanRateCardID(id)) + return &PlanRateCardUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for PlanRateCard. +func (c *PlanRateCardClient) Delete() *PlanRateCardDelete { + mutation := newPlanRateCardMutation(c.config, OpDelete) + return &PlanRateCardDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *PlanRateCardClient) DeleteOne(_m *PlanRateCard) *PlanRateCardDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *PlanRateCardClient) DeleteOneID(id string) *PlanRateCardDeleteOne { + builder := c.Delete().Where(planratecard.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &PlanRateCardDeleteOne{builder} +} + +// Query returns a query builder for PlanRateCard. +func (c *PlanRateCardClient) Query() *PlanRateCardQuery { + return &PlanRateCardQuery{ + config: c.config, + ctx: &QueryContext{Type: TypePlanRateCard}, + inters: c.Interceptors(), + } +} + +// Get returns a PlanRateCard entity by its id. +func (c *PlanRateCardClient) Get(ctx context.Context, id string) (*PlanRateCard, error) { + return c.Query().Where(planratecard.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *PlanRateCardClient) GetX(ctx context.Context, id string) *PlanRateCard { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryPhase queries the phase edge of a PlanRateCard. +func (c *PlanRateCardClient) QueryPhase(_m *PlanRateCard) *PlanPhaseQuery { + query := (&PlanPhaseClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(planratecard.Table, planratecard.FieldID, id), + sqlgraph.To(planphase.Table, planphase.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, planratecard.PhaseTable, planratecard.PhaseColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryFeatures queries the features edge of a PlanRateCard. +func (c *PlanRateCardClient) QueryFeatures(_m *PlanRateCard) *FeatureQuery { + query := (&FeatureClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(planratecard.Table, planratecard.FieldID, id), + sqlgraph.To(dbfeature.Table, dbfeature.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, planratecard.FeaturesTable, planratecard.FeaturesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryTaxCode queries the tax_code edge of a PlanRateCard. +func (c *PlanRateCardClient) QueryTaxCode(_m *PlanRateCard) *TaxCodeQuery { + query := (&TaxCodeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(planratecard.Table, planratecard.FieldID, id), + sqlgraph.To(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, planratecard.TaxCodeTable, planratecard.TaxCodeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *PlanRateCardClient) Hooks() []Hook { + return c.hooks.PlanRateCard +} + +// Interceptors returns the client interceptors. +func (c *PlanRateCardClient) Interceptors() []Interceptor { + return c.inters.PlanRateCard +} + +func (c *PlanRateCardClient) mutate(ctx context.Context, m *PlanRateCardMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&PlanRateCardCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&PlanRateCardUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&PlanRateCardUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&PlanRateCardDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown PlanRateCard mutation op: %q", m.Op()) + } +} + +// SubjectClient is a client for the Subject schema. +type SubjectClient struct { + config +} + +// NewSubjectClient returns a client for the Subject from the given config. +func NewSubjectClient(c config) *SubjectClient { + return &SubjectClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `subject.Hooks(f(g(h())))`. +func (c *SubjectClient) Use(hooks ...Hook) { + c.hooks.Subject = append(c.hooks.Subject, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `subject.Intercept(f(g(h())))`. +func (c *SubjectClient) Intercept(interceptors ...Interceptor) { + c.inters.Subject = append(c.inters.Subject, interceptors...) +} + +// Create returns a builder for creating a Subject entity. +func (c *SubjectClient) Create() *SubjectCreate { + mutation := newSubjectMutation(c.config, OpCreate) + return &SubjectCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Subject entities. +func (c *SubjectClient) CreateBulk(builders ...*SubjectCreate) *SubjectCreateBulk { + return &SubjectCreateBulk{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 *SubjectClient) MapCreateBulk(slice any, setFunc func(*SubjectCreate, int)) *SubjectCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &SubjectCreateBulk{err: fmt.Errorf("calling to SubjectClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*SubjectCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &SubjectCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Subject. +func (c *SubjectClient) Update() *SubjectUpdate { + mutation := newSubjectMutation(c.config, OpUpdate) + return &SubjectUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *SubjectClient) UpdateOne(_m *Subject) *SubjectUpdateOne { + mutation := newSubjectMutation(c.config, OpUpdateOne, withSubject(_m)) + return &SubjectUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *SubjectClient) UpdateOneID(id string) *SubjectUpdateOne { + mutation := newSubjectMutation(c.config, OpUpdateOne, withSubjectID(id)) + return &SubjectUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Subject. +func (c *SubjectClient) Delete() *SubjectDelete { + mutation := newSubjectMutation(c.config, OpDelete) + return &SubjectDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *SubjectClient) DeleteOne(_m *Subject) *SubjectDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *SubjectClient) DeleteOneID(id string) *SubjectDeleteOne { + builder := c.Delete().Where(subject.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &SubjectDeleteOne{builder} +} + +// Query returns a query builder for Subject. +func (c *SubjectClient) Query() *SubjectQuery { + return &SubjectQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeSubject}, + inters: c.Interceptors(), + } +} + +// Get returns a Subject entity by its id. +func (c *SubjectClient) Get(ctx context.Context, id string) (*Subject, error) { + return c.Query().Where(subject.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *SubjectClient) GetX(ctx context.Context, id string) *Subject { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *SubjectClient) Hooks() []Hook { + return c.hooks.Subject +} + +// Interceptors returns the client interceptors. +func (c *SubjectClient) Interceptors() []Interceptor { + return c.inters.Subject +} + +func (c *SubjectClient) mutate(ctx context.Context, m *SubjectMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&SubjectCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&SubjectUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&SubjectUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&SubjectDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown Subject mutation op: %q", m.Op()) + } +} + +// SubscriptionClient is a client for the Subscription schema. +type SubscriptionClient struct { + config +} + +// NewSubscriptionClient returns a client for the Subscription from the given config. +func NewSubscriptionClient(c config) *SubscriptionClient { + return &SubscriptionClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `subscription.Hooks(f(g(h())))`. +func (c *SubscriptionClient) Use(hooks ...Hook) { + c.hooks.Subscription = append(c.hooks.Subscription, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `subscription.Intercept(f(g(h())))`. +func (c *SubscriptionClient) Intercept(interceptors ...Interceptor) { + c.inters.Subscription = append(c.inters.Subscription, interceptors...) +} + +// Create returns a builder for creating a Subscription entity. +func (c *SubscriptionClient) Create() *SubscriptionCreate { + mutation := newSubscriptionMutation(c.config, OpCreate) + return &SubscriptionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Subscription entities. +func (c *SubscriptionClient) CreateBulk(builders ...*SubscriptionCreate) *SubscriptionCreateBulk { + return &SubscriptionCreateBulk{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 *SubscriptionClient) MapCreateBulk(slice any, setFunc func(*SubscriptionCreate, int)) *SubscriptionCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &SubscriptionCreateBulk{err: fmt.Errorf("calling to SubscriptionClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*SubscriptionCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &SubscriptionCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Subscription. +func (c *SubscriptionClient) Update() *SubscriptionUpdate { + mutation := newSubscriptionMutation(c.config, OpUpdate) + return &SubscriptionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *SubscriptionClient) UpdateOne(_m *Subscription) *SubscriptionUpdateOne { + mutation := newSubscriptionMutation(c.config, OpUpdateOne, withSubscription(_m)) + return &SubscriptionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *SubscriptionClient) UpdateOneID(id string) *SubscriptionUpdateOne { + mutation := newSubscriptionMutation(c.config, OpUpdateOne, withSubscriptionID(id)) + return &SubscriptionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Subscription. +func (c *SubscriptionClient) Delete() *SubscriptionDelete { + mutation := newSubscriptionMutation(c.config, OpDelete) + return &SubscriptionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *SubscriptionClient) DeleteOne(_m *Subscription) *SubscriptionDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *SubscriptionClient) DeleteOneID(id string) *SubscriptionDeleteOne { + builder := c.Delete().Where(subscription.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &SubscriptionDeleteOne{builder} +} + +// Query returns a query builder for Subscription. +func (c *SubscriptionClient) Query() *SubscriptionQuery { + return &SubscriptionQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeSubscription}, + inters: c.Interceptors(), + } +} + +// Get returns a Subscription entity by its id. +func (c *SubscriptionClient) Get(ctx context.Context, id string) (*Subscription, error) { + return c.Query().Where(subscription.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *SubscriptionClient) GetX(ctx context.Context, id string) *Subscription { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryPlan queries the plan edge of a Subscription. +func (c *SubscriptionClient) QueryPlan(_m *Subscription) *PlanQuery { + query := (&PlanClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscription.Table, subscription.FieldID, id), + sqlgraph.To(plan.Table, plan.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, subscription.PlanTable, subscription.PlanColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCustomer queries the customer edge of a Subscription. +func (c *SubscriptionClient) QueryCustomer(_m *Subscription) *CustomerQuery { + query := (&CustomerClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscription.Table, subscription.FieldID, id), + sqlgraph.To(customer.Table, customer.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, subscription.CustomerTable, subscription.CustomerColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryPhases queries the phases edge of a Subscription. +func (c *SubscriptionClient) QueryPhases(_m *Subscription) *SubscriptionPhaseQuery { + query := (&SubscriptionPhaseClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscription.Table, subscription.FieldID, id), + sqlgraph.To(subscriptionphase.Table, subscriptionphase.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, subscription.PhasesTable, subscription.PhasesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingLines queries the billing_lines edge of a Subscription. +func (c *SubscriptionClient) QueryBillingLines(_m *Subscription) *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscription.Table, subscription.FieldID, id), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, subscription.BillingLinesTable, subscription.BillingLinesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingSplitLineGroups queries the billing_split_line_groups edge of a Subscription. +func (c *SubscriptionClient) QueryBillingSplitLineGroups(_m *Subscription) *BillingInvoiceSplitLineGroupQuery { + query := (&BillingInvoiceSplitLineGroupClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscription.Table, subscription.FieldID, id), + sqlgraph.To(billinginvoicesplitlinegroup.Table, billinginvoicesplitlinegroup.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, subscription.BillingSplitLineGroupsTable, subscription.BillingSplitLineGroupsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargesUsageBased queries the charges_usage_based edge of a Subscription. +func (c *SubscriptionClient) QueryChargesUsageBased(_m *Subscription) *ChargeUsageBasedQuery { + query := (&ChargeUsageBasedClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscription.Table, subscription.FieldID, id), + sqlgraph.To(chargeusagebased.Table, chargeusagebased.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, subscription.ChargesUsageBasedTable, subscription.ChargesUsageBasedColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargesCreditPurchase queries the charges_credit_purchase edge of a Subscription. +func (c *SubscriptionClient) QueryChargesCreditPurchase(_m *Subscription) *ChargeCreditPurchaseQuery { + query := (&ChargeCreditPurchaseClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscription.Table, subscription.FieldID, id), + sqlgraph.To(chargecreditpurchase.Table, chargecreditpurchase.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, subscription.ChargesCreditPurchaseTable, subscription.ChargesCreditPurchaseColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargesFlatFee queries the charges_flat_fee edge of a Subscription. +func (c *SubscriptionClient) QueryChargesFlatFee(_m *Subscription) *ChargeFlatFeeQuery { + query := (&ChargeFlatFeeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscription.Table, subscription.FieldID, id), + sqlgraph.To(chargeflatfee.Table, chargeflatfee.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, subscription.ChargesFlatFeeTable, subscription.ChargesFlatFeeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryAddons queries the addons edge of a Subscription. +func (c *SubscriptionClient) QueryAddons(_m *Subscription) *SubscriptionAddonQuery { + query := (&SubscriptionAddonClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscription.Table, subscription.FieldID, id), + sqlgraph.To(subscriptionaddon.Table, subscriptionaddon.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, subscription.AddonsTable, subscription.AddonsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingSyncState queries the billing_sync_state edge of a Subscription. +func (c *SubscriptionClient) QueryBillingSyncState(_m *Subscription) *SubscriptionBillingSyncStateQuery { + query := (&SubscriptionBillingSyncStateClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscription.Table, subscription.FieldID, id), + sqlgraph.To(subscriptionbillingsyncstate.Table, subscriptionbillingsyncstate.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, subscription.BillingSyncStateTable, subscription.BillingSyncStateColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *SubscriptionClient) Hooks() []Hook { + return c.hooks.Subscription +} + +// Interceptors returns the client interceptors. +func (c *SubscriptionClient) Interceptors() []Interceptor { + return c.inters.Subscription +} + +func (c *SubscriptionClient) mutate(ctx context.Context, m *SubscriptionMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&SubscriptionCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&SubscriptionUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&SubscriptionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&SubscriptionDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown Subscription mutation op: %q", m.Op()) + } +} + +// SubscriptionAddonClient is a client for the SubscriptionAddon schema. +type SubscriptionAddonClient struct { + config +} + +// NewSubscriptionAddonClient returns a client for the SubscriptionAddon from the given config. +func NewSubscriptionAddonClient(c config) *SubscriptionAddonClient { + return &SubscriptionAddonClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `subscriptionaddon.Hooks(f(g(h())))`. +func (c *SubscriptionAddonClient) Use(hooks ...Hook) { + c.hooks.SubscriptionAddon = append(c.hooks.SubscriptionAddon, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `subscriptionaddon.Intercept(f(g(h())))`. +func (c *SubscriptionAddonClient) Intercept(interceptors ...Interceptor) { + c.inters.SubscriptionAddon = append(c.inters.SubscriptionAddon, interceptors...) +} + +// Create returns a builder for creating a SubscriptionAddon entity. +func (c *SubscriptionAddonClient) Create() *SubscriptionAddonCreate { + mutation := newSubscriptionAddonMutation(c.config, OpCreate) + return &SubscriptionAddonCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of SubscriptionAddon entities. +func (c *SubscriptionAddonClient) CreateBulk(builders ...*SubscriptionAddonCreate) *SubscriptionAddonCreateBulk { + return &SubscriptionAddonCreateBulk{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 *SubscriptionAddonClient) MapCreateBulk(slice any, setFunc func(*SubscriptionAddonCreate, int)) *SubscriptionAddonCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &SubscriptionAddonCreateBulk{err: fmt.Errorf("calling to SubscriptionAddonClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*SubscriptionAddonCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &SubscriptionAddonCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for SubscriptionAddon. +func (c *SubscriptionAddonClient) Update() *SubscriptionAddonUpdate { + mutation := newSubscriptionAddonMutation(c.config, OpUpdate) + return &SubscriptionAddonUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *SubscriptionAddonClient) UpdateOne(_m *SubscriptionAddon) *SubscriptionAddonUpdateOne { + mutation := newSubscriptionAddonMutation(c.config, OpUpdateOne, withSubscriptionAddon(_m)) + return &SubscriptionAddonUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *SubscriptionAddonClient) UpdateOneID(id string) *SubscriptionAddonUpdateOne { + mutation := newSubscriptionAddonMutation(c.config, OpUpdateOne, withSubscriptionAddonID(id)) + return &SubscriptionAddonUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for SubscriptionAddon. +func (c *SubscriptionAddonClient) Delete() *SubscriptionAddonDelete { + mutation := newSubscriptionAddonMutation(c.config, OpDelete) + return &SubscriptionAddonDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *SubscriptionAddonClient) DeleteOne(_m *SubscriptionAddon) *SubscriptionAddonDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *SubscriptionAddonClient) DeleteOneID(id string) *SubscriptionAddonDeleteOne { + builder := c.Delete().Where(subscriptionaddon.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &SubscriptionAddonDeleteOne{builder} +} + +// Query returns a query builder for SubscriptionAddon. +func (c *SubscriptionAddonClient) Query() *SubscriptionAddonQuery { + return &SubscriptionAddonQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeSubscriptionAddon}, + inters: c.Interceptors(), + } +} + +// Get returns a SubscriptionAddon entity by its id. +func (c *SubscriptionAddonClient) Get(ctx context.Context, id string) (*SubscriptionAddon, error) { + return c.Query().Where(subscriptionaddon.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *SubscriptionAddonClient) GetX(ctx context.Context, id string) *SubscriptionAddon { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QuerySubscription queries the subscription edge of a SubscriptionAddon. +func (c *SubscriptionAddonClient) QuerySubscription(_m *SubscriptionAddon) *SubscriptionQuery { + query := (&SubscriptionClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscriptionaddon.Table, subscriptionaddon.FieldID, id), + sqlgraph.To(subscription.Table, subscription.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, subscriptionaddon.SubscriptionTable, subscriptionaddon.SubscriptionColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryQuantities queries the quantities edge of a SubscriptionAddon. +func (c *SubscriptionAddonClient) QueryQuantities(_m *SubscriptionAddon) *SubscriptionAddonQuantityQuery { + query := (&SubscriptionAddonQuantityClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscriptionaddon.Table, subscriptionaddon.FieldID, id), + sqlgraph.To(subscriptionaddonquantity.Table, subscriptionaddonquantity.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, subscriptionaddon.QuantitiesTable, subscriptionaddon.QuantitiesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryAddon queries the addon edge of a SubscriptionAddon. +func (c *SubscriptionAddonClient) QueryAddon(_m *SubscriptionAddon) *AddonQuery { + query := (&AddonClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscriptionaddon.Table, subscriptionaddon.FieldID, id), + sqlgraph.To(addon.Table, addon.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, subscriptionaddon.AddonTable, subscriptionaddon.AddonColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *SubscriptionAddonClient) Hooks() []Hook { + return c.hooks.SubscriptionAddon +} + +// Interceptors returns the client interceptors. +func (c *SubscriptionAddonClient) Interceptors() []Interceptor { + return c.inters.SubscriptionAddon +} + +func (c *SubscriptionAddonClient) mutate(ctx context.Context, m *SubscriptionAddonMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&SubscriptionAddonCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&SubscriptionAddonUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&SubscriptionAddonUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&SubscriptionAddonDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown SubscriptionAddon mutation op: %q", m.Op()) + } +} + +// SubscriptionAddonQuantityClient is a client for the SubscriptionAddonQuantity schema. +type SubscriptionAddonQuantityClient struct { + config +} + +// NewSubscriptionAddonQuantityClient returns a client for the SubscriptionAddonQuantity from the given config. +func NewSubscriptionAddonQuantityClient(c config) *SubscriptionAddonQuantityClient { + return &SubscriptionAddonQuantityClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `subscriptionaddonquantity.Hooks(f(g(h())))`. +func (c *SubscriptionAddonQuantityClient) Use(hooks ...Hook) { + c.hooks.SubscriptionAddonQuantity = append(c.hooks.SubscriptionAddonQuantity, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `subscriptionaddonquantity.Intercept(f(g(h())))`. +func (c *SubscriptionAddonQuantityClient) Intercept(interceptors ...Interceptor) { + c.inters.SubscriptionAddonQuantity = append(c.inters.SubscriptionAddonQuantity, interceptors...) +} + +// Create returns a builder for creating a SubscriptionAddonQuantity entity. +func (c *SubscriptionAddonQuantityClient) Create() *SubscriptionAddonQuantityCreate { + mutation := newSubscriptionAddonQuantityMutation(c.config, OpCreate) + return &SubscriptionAddonQuantityCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of SubscriptionAddonQuantity entities. +func (c *SubscriptionAddonQuantityClient) CreateBulk(builders ...*SubscriptionAddonQuantityCreate) *SubscriptionAddonQuantityCreateBulk { + return &SubscriptionAddonQuantityCreateBulk{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 *SubscriptionAddonQuantityClient) MapCreateBulk(slice any, setFunc func(*SubscriptionAddonQuantityCreate, int)) *SubscriptionAddonQuantityCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &SubscriptionAddonQuantityCreateBulk{err: fmt.Errorf("calling to SubscriptionAddonQuantityClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*SubscriptionAddonQuantityCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &SubscriptionAddonQuantityCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for SubscriptionAddonQuantity. +func (c *SubscriptionAddonQuantityClient) Update() *SubscriptionAddonQuantityUpdate { + mutation := newSubscriptionAddonQuantityMutation(c.config, OpUpdate) + return &SubscriptionAddonQuantityUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *SubscriptionAddonQuantityClient) UpdateOne(_m *SubscriptionAddonQuantity) *SubscriptionAddonQuantityUpdateOne { + mutation := newSubscriptionAddonQuantityMutation(c.config, OpUpdateOne, withSubscriptionAddonQuantity(_m)) + return &SubscriptionAddonQuantityUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *SubscriptionAddonQuantityClient) UpdateOneID(id string) *SubscriptionAddonQuantityUpdateOne { + mutation := newSubscriptionAddonQuantityMutation(c.config, OpUpdateOne, withSubscriptionAddonQuantityID(id)) + return &SubscriptionAddonQuantityUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for SubscriptionAddonQuantity. +func (c *SubscriptionAddonQuantityClient) Delete() *SubscriptionAddonQuantityDelete { + mutation := newSubscriptionAddonQuantityMutation(c.config, OpDelete) + return &SubscriptionAddonQuantityDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *SubscriptionAddonQuantityClient) DeleteOne(_m *SubscriptionAddonQuantity) *SubscriptionAddonQuantityDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *SubscriptionAddonQuantityClient) DeleteOneID(id string) *SubscriptionAddonQuantityDeleteOne { + builder := c.Delete().Where(subscriptionaddonquantity.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &SubscriptionAddonQuantityDeleteOne{builder} +} + +// Query returns a query builder for SubscriptionAddonQuantity. +func (c *SubscriptionAddonQuantityClient) Query() *SubscriptionAddonQuantityQuery { + return &SubscriptionAddonQuantityQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeSubscriptionAddonQuantity}, + inters: c.Interceptors(), + } +} + +// Get returns a SubscriptionAddonQuantity entity by its id. +func (c *SubscriptionAddonQuantityClient) Get(ctx context.Context, id string) (*SubscriptionAddonQuantity, error) { + return c.Query().Where(subscriptionaddonquantity.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *SubscriptionAddonQuantityClient) GetX(ctx context.Context, id string) *SubscriptionAddonQuantity { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QuerySubscriptionAddon queries the subscription_addon edge of a SubscriptionAddonQuantity. +func (c *SubscriptionAddonQuantityClient) QuerySubscriptionAddon(_m *SubscriptionAddonQuantity) *SubscriptionAddonQuery { + query := (&SubscriptionAddonClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscriptionaddonquantity.Table, subscriptionaddonquantity.FieldID, id), + sqlgraph.To(subscriptionaddon.Table, subscriptionaddon.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, subscriptionaddonquantity.SubscriptionAddonTable, subscriptionaddonquantity.SubscriptionAddonColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *SubscriptionAddonQuantityClient) Hooks() []Hook { + return c.hooks.SubscriptionAddonQuantity +} + +// Interceptors returns the client interceptors. +func (c *SubscriptionAddonQuantityClient) Interceptors() []Interceptor { + return c.inters.SubscriptionAddonQuantity +} + +func (c *SubscriptionAddonQuantityClient) mutate(ctx context.Context, m *SubscriptionAddonQuantityMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&SubscriptionAddonQuantityCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&SubscriptionAddonQuantityUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&SubscriptionAddonQuantityUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&SubscriptionAddonQuantityDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown SubscriptionAddonQuantity mutation op: %q", m.Op()) + } +} + +// SubscriptionBillingSyncStateClient is a client for the SubscriptionBillingSyncState schema. +type SubscriptionBillingSyncStateClient struct { + config +} + +// NewSubscriptionBillingSyncStateClient returns a client for the SubscriptionBillingSyncState from the given config. +func NewSubscriptionBillingSyncStateClient(c config) *SubscriptionBillingSyncStateClient { + return &SubscriptionBillingSyncStateClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `subscriptionbillingsyncstate.Hooks(f(g(h())))`. +func (c *SubscriptionBillingSyncStateClient) Use(hooks ...Hook) { + c.hooks.SubscriptionBillingSyncState = append(c.hooks.SubscriptionBillingSyncState, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `subscriptionbillingsyncstate.Intercept(f(g(h())))`. +func (c *SubscriptionBillingSyncStateClient) Intercept(interceptors ...Interceptor) { + c.inters.SubscriptionBillingSyncState = append(c.inters.SubscriptionBillingSyncState, interceptors...) +} + +// Create returns a builder for creating a SubscriptionBillingSyncState entity. +func (c *SubscriptionBillingSyncStateClient) Create() *SubscriptionBillingSyncStateCreate { + mutation := newSubscriptionBillingSyncStateMutation(c.config, OpCreate) + return &SubscriptionBillingSyncStateCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of SubscriptionBillingSyncState entities. +func (c *SubscriptionBillingSyncStateClient) CreateBulk(builders ...*SubscriptionBillingSyncStateCreate) *SubscriptionBillingSyncStateCreateBulk { + return &SubscriptionBillingSyncStateCreateBulk{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 *SubscriptionBillingSyncStateClient) MapCreateBulk(slice any, setFunc func(*SubscriptionBillingSyncStateCreate, int)) *SubscriptionBillingSyncStateCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &SubscriptionBillingSyncStateCreateBulk{err: fmt.Errorf("calling to SubscriptionBillingSyncStateClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*SubscriptionBillingSyncStateCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &SubscriptionBillingSyncStateCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for SubscriptionBillingSyncState. +func (c *SubscriptionBillingSyncStateClient) Update() *SubscriptionBillingSyncStateUpdate { + mutation := newSubscriptionBillingSyncStateMutation(c.config, OpUpdate) + return &SubscriptionBillingSyncStateUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *SubscriptionBillingSyncStateClient) UpdateOne(_m *SubscriptionBillingSyncState) *SubscriptionBillingSyncStateUpdateOne { + mutation := newSubscriptionBillingSyncStateMutation(c.config, OpUpdateOne, withSubscriptionBillingSyncState(_m)) + return &SubscriptionBillingSyncStateUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *SubscriptionBillingSyncStateClient) UpdateOneID(id string) *SubscriptionBillingSyncStateUpdateOne { + mutation := newSubscriptionBillingSyncStateMutation(c.config, OpUpdateOne, withSubscriptionBillingSyncStateID(id)) + return &SubscriptionBillingSyncStateUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for SubscriptionBillingSyncState. +func (c *SubscriptionBillingSyncStateClient) Delete() *SubscriptionBillingSyncStateDelete { + mutation := newSubscriptionBillingSyncStateMutation(c.config, OpDelete) + return &SubscriptionBillingSyncStateDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *SubscriptionBillingSyncStateClient) DeleteOne(_m *SubscriptionBillingSyncState) *SubscriptionBillingSyncStateDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *SubscriptionBillingSyncStateClient) DeleteOneID(id string) *SubscriptionBillingSyncStateDeleteOne { + builder := c.Delete().Where(subscriptionbillingsyncstate.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &SubscriptionBillingSyncStateDeleteOne{builder} +} + +// Query returns a query builder for SubscriptionBillingSyncState. +func (c *SubscriptionBillingSyncStateClient) Query() *SubscriptionBillingSyncStateQuery { + return &SubscriptionBillingSyncStateQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeSubscriptionBillingSyncState}, + inters: c.Interceptors(), + } +} + +// Get returns a SubscriptionBillingSyncState entity by its id. +func (c *SubscriptionBillingSyncStateClient) Get(ctx context.Context, id string) (*SubscriptionBillingSyncState, error) { + return c.Query().Where(subscriptionbillingsyncstate.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *SubscriptionBillingSyncStateClient) GetX(ctx context.Context, id string) *SubscriptionBillingSyncState { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QuerySubscription queries the subscription edge of a SubscriptionBillingSyncState. +func (c *SubscriptionBillingSyncStateClient) QuerySubscription(_m *SubscriptionBillingSyncState) *SubscriptionQuery { + query := (&SubscriptionClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscriptionbillingsyncstate.Table, subscriptionbillingsyncstate.FieldID, id), + sqlgraph.To(subscription.Table, subscription.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, subscriptionbillingsyncstate.SubscriptionTable, subscriptionbillingsyncstate.SubscriptionColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *SubscriptionBillingSyncStateClient) Hooks() []Hook { + return c.hooks.SubscriptionBillingSyncState +} + +// Interceptors returns the client interceptors. +func (c *SubscriptionBillingSyncStateClient) Interceptors() []Interceptor { + return c.inters.SubscriptionBillingSyncState +} + +func (c *SubscriptionBillingSyncStateClient) mutate(ctx context.Context, m *SubscriptionBillingSyncStateMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&SubscriptionBillingSyncStateCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&SubscriptionBillingSyncStateUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&SubscriptionBillingSyncStateUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&SubscriptionBillingSyncStateDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown SubscriptionBillingSyncState mutation op: %q", m.Op()) + } +} + +// SubscriptionItemClient is a client for the SubscriptionItem schema. +type SubscriptionItemClient struct { + config +} + +// NewSubscriptionItemClient returns a client for the SubscriptionItem from the given config. +func NewSubscriptionItemClient(c config) *SubscriptionItemClient { + return &SubscriptionItemClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `subscriptionitem.Hooks(f(g(h())))`. +func (c *SubscriptionItemClient) Use(hooks ...Hook) { + c.hooks.SubscriptionItem = append(c.hooks.SubscriptionItem, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `subscriptionitem.Intercept(f(g(h())))`. +func (c *SubscriptionItemClient) Intercept(interceptors ...Interceptor) { + c.inters.SubscriptionItem = append(c.inters.SubscriptionItem, interceptors...) +} + +// Create returns a builder for creating a SubscriptionItem entity. +func (c *SubscriptionItemClient) Create() *SubscriptionItemCreate { + mutation := newSubscriptionItemMutation(c.config, OpCreate) + return &SubscriptionItemCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of SubscriptionItem entities. +func (c *SubscriptionItemClient) CreateBulk(builders ...*SubscriptionItemCreate) *SubscriptionItemCreateBulk { + return &SubscriptionItemCreateBulk{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 *SubscriptionItemClient) MapCreateBulk(slice any, setFunc func(*SubscriptionItemCreate, int)) *SubscriptionItemCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &SubscriptionItemCreateBulk{err: fmt.Errorf("calling to SubscriptionItemClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*SubscriptionItemCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &SubscriptionItemCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for SubscriptionItem. +func (c *SubscriptionItemClient) Update() *SubscriptionItemUpdate { + mutation := newSubscriptionItemMutation(c.config, OpUpdate) + return &SubscriptionItemUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *SubscriptionItemClient) UpdateOne(_m *SubscriptionItem) *SubscriptionItemUpdateOne { + mutation := newSubscriptionItemMutation(c.config, OpUpdateOne, withSubscriptionItem(_m)) + return &SubscriptionItemUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *SubscriptionItemClient) UpdateOneID(id string) *SubscriptionItemUpdateOne { + mutation := newSubscriptionItemMutation(c.config, OpUpdateOne, withSubscriptionItemID(id)) + return &SubscriptionItemUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for SubscriptionItem. +func (c *SubscriptionItemClient) Delete() *SubscriptionItemDelete { + mutation := newSubscriptionItemMutation(c.config, OpDelete) + return &SubscriptionItemDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *SubscriptionItemClient) DeleteOne(_m *SubscriptionItem) *SubscriptionItemDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *SubscriptionItemClient) DeleteOneID(id string) *SubscriptionItemDeleteOne { + builder := c.Delete().Where(subscriptionitem.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &SubscriptionItemDeleteOne{builder} +} + +// Query returns a query builder for SubscriptionItem. +func (c *SubscriptionItemClient) Query() *SubscriptionItemQuery { + return &SubscriptionItemQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeSubscriptionItem}, + inters: c.Interceptors(), + } +} + +// Get returns a SubscriptionItem entity by its id. +func (c *SubscriptionItemClient) Get(ctx context.Context, id string) (*SubscriptionItem, error) { + return c.Query().Where(subscriptionitem.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *SubscriptionItemClient) GetX(ctx context.Context, id string) *SubscriptionItem { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryPhase queries the phase edge of a SubscriptionItem. +func (c *SubscriptionItemClient) QueryPhase(_m *SubscriptionItem) *SubscriptionPhaseQuery { + query := (&SubscriptionPhaseClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscriptionitem.Table, subscriptionitem.FieldID, id), + sqlgraph.To(subscriptionphase.Table, subscriptionphase.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, subscriptionitem.PhaseTable, subscriptionitem.PhaseColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryEntitlement queries the entitlement edge of a SubscriptionItem. +func (c *SubscriptionItemClient) QueryEntitlement(_m *SubscriptionItem) *EntitlementQuery { + query := (&EntitlementClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscriptionitem.Table, subscriptionitem.FieldID, id), + sqlgraph.To(entitlement.Table, entitlement.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, subscriptionitem.EntitlementTable, subscriptionitem.EntitlementColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingLines queries the billing_lines edge of a SubscriptionItem. +func (c *SubscriptionItemClient) QueryBillingLines(_m *SubscriptionItem) *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscriptionitem.Table, subscriptionitem.FieldID, id), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, subscriptionitem.BillingLinesTable, subscriptionitem.BillingLinesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingSplitLineGroups queries the billing_split_line_groups edge of a SubscriptionItem. +func (c *SubscriptionItemClient) QueryBillingSplitLineGroups(_m *SubscriptionItem) *BillingInvoiceSplitLineGroupQuery { + query := (&BillingInvoiceSplitLineGroupClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscriptionitem.Table, subscriptionitem.FieldID, id), + sqlgraph.To(billinginvoicesplitlinegroup.Table, billinginvoicesplitlinegroup.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, subscriptionitem.BillingSplitLineGroupsTable, subscriptionitem.BillingSplitLineGroupsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargesUsageBased queries the charges_usage_based edge of a SubscriptionItem. +func (c *SubscriptionItemClient) QueryChargesUsageBased(_m *SubscriptionItem) *ChargeUsageBasedQuery { + query := (&ChargeUsageBasedClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscriptionitem.Table, subscriptionitem.FieldID, id), + sqlgraph.To(chargeusagebased.Table, chargeusagebased.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, subscriptionitem.ChargesUsageBasedTable, subscriptionitem.ChargesUsageBasedColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargesCreditPurchase queries the charges_credit_purchase edge of a SubscriptionItem. +func (c *SubscriptionItemClient) QueryChargesCreditPurchase(_m *SubscriptionItem) *ChargeCreditPurchaseQuery { + query := (&ChargeCreditPurchaseClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscriptionitem.Table, subscriptionitem.FieldID, id), + sqlgraph.To(chargecreditpurchase.Table, chargecreditpurchase.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, subscriptionitem.ChargesCreditPurchaseTable, subscriptionitem.ChargesCreditPurchaseColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargesFlatFee queries the charges_flat_fee edge of a SubscriptionItem. +func (c *SubscriptionItemClient) QueryChargesFlatFee(_m *SubscriptionItem) *ChargeFlatFeeQuery { + query := (&ChargeFlatFeeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscriptionitem.Table, subscriptionitem.FieldID, id), + sqlgraph.To(chargeflatfee.Table, chargeflatfee.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, subscriptionitem.ChargesFlatFeeTable, subscriptionitem.ChargesFlatFeeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryTaxCode queries the tax_code edge of a SubscriptionItem. +func (c *SubscriptionItemClient) QueryTaxCode(_m *SubscriptionItem) *TaxCodeQuery { + query := (&TaxCodeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscriptionitem.Table, subscriptionitem.FieldID, id), + sqlgraph.To(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, subscriptionitem.TaxCodeTable, subscriptionitem.TaxCodeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *SubscriptionItemClient) Hooks() []Hook { + return c.hooks.SubscriptionItem +} + +// Interceptors returns the client interceptors. +func (c *SubscriptionItemClient) Interceptors() []Interceptor { + return c.inters.SubscriptionItem +} + +func (c *SubscriptionItemClient) mutate(ctx context.Context, m *SubscriptionItemMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&SubscriptionItemCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&SubscriptionItemUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&SubscriptionItemUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&SubscriptionItemDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown SubscriptionItem mutation op: %q", m.Op()) + } +} + +// SubscriptionPhaseClient is a client for the SubscriptionPhase schema. +type SubscriptionPhaseClient struct { + config +} + +// NewSubscriptionPhaseClient returns a client for the SubscriptionPhase from the given config. +func NewSubscriptionPhaseClient(c config) *SubscriptionPhaseClient { + return &SubscriptionPhaseClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `subscriptionphase.Hooks(f(g(h())))`. +func (c *SubscriptionPhaseClient) Use(hooks ...Hook) { + c.hooks.SubscriptionPhase = append(c.hooks.SubscriptionPhase, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `subscriptionphase.Intercept(f(g(h())))`. +func (c *SubscriptionPhaseClient) Intercept(interceptors ...Interceptor) { + c.inters.SubscriptionPhase = append(c.inters.SubscriptionPhase, interceptors...) +} + +// Create returns a builder for creating a SubscriptionPhase entity. +func (c *SubscriptionPhaseClient) Create() *SubscriptionPhaseCreate { + mutation := newSubscriptionPhaseMutation(c.config, OpCreate) + return &SubscriptionPhaseCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of SubscriptionPhase entities. +func (c *SubscriptionPhaseClient) CreateBulk(builders ...*SubscriptionPhaseCreate) *SubscriptionPhaseCreateBulk { + return &SubscriptionPhaseCreateBulk{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 *SubscriptionPhaseClient) MapCreateBulk(slice any, setFunc func(*SubscriptionPhaseCreate, int)) *SubscriptionPhaseCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &SubscriptionPhaseCreateBulk{err: fmt.Errorf("calling to SubscriptionPhaseClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*SubscriptionPhaseCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &SubscriptionPhaseCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for SubscriptionPhase. +func (c *SubscriptionPhaseClient) Update() *SubscriptionPhaseUpdate { + mutation := newSubscriptionPhaseMutation(c.config, OpUpdate) + return &SubscriptionPhaseUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *SubscriptionPhaseClient) UpdateOne(_m *SubscriptionPhase) *SubscriptionPhaseUpdateOne { + mutation := newSubscriptionPhaseMutation(c.config, OpUpdateOne, withSubscriptionPhase(_m)) + return &SubscriptionPhaseUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *SubscriptionPhaseClient) UpdateOneID(id string) *SubscriptionPhaseUpdateOne { + mutation := newSubscriptionPhaseMutation(c.config, OpUpdateOne, withSubscriptionPhaseID(id)) + return &SubscriptionPhaseUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for SubscriptionPhase. +func (c *SubscriptionPhaseClient) Delete() *SubscriptionPhaseDelete { + mutation := newSubscriptionPhaseMutation(c.config, OpDelete) + return &SubscriptionPhaseDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *SubscriptionPhaseClient) DeleteOne(_m *SubscriptionPhase) *SubscriptionPhaseDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *SubscriptionPhaseClient) DeleteOneID(id string) *SubscriptionPhaseDeleteOne { + builder := c.Delete().Where(subscriptionphase.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &SubscriptionPhaseDeleteOne{builder} +} + +// Query returns a query builder for SubscriptionPhase. +func (c *SubscriptionPhaseClient) Query() *SubscriptionPhaseQuery { + return &SubscriptionPhaseQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeSubscriptionPhase}, + inters: c.Interceptors(), + } +} + +// Get returns a SubscriptionPhase entity by its id. +func (c *SubscriptionPhaseClient) Get(ctx context.Context, id string) (*SubscriptionPhase, error) { + return c.Query().Where(subscriptionphase.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *SubscriptionPhaseClient) GetX(ctx context.Context, id string) *SubscriptionPhase { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QuerySubscription queries the subscription edge of a SubscriptionPhase. +func (c *SubscriptionPhaseClient) QuerySubscription(_m *SubscriptionPhase) *SubscriptionQuery { + query := (&SubscriptionClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscriptionphase.Table, subscriptionphase.FieldID, id), + sqlgraph.To(subscription.Table, subscription.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, subscriptionphase.SubscriptionTable, subscriptionphase.SubscriptionColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryItems queries the items edge of a SubscriptionPhase. +func (c *SubscriptionPhaseClient) QueryItems(_m *SubscriptionPhase) *SubscriptionItemQuery { + query := (&SubscriptionItemClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscriptionphase.Table, subscriptionphase.FieldID, id), + sqlgraph.To(subscriptionitem.Table, subscriptionitem.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, subscriptionphase.ItemsTable, subscriptionphase.ItemsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingLines queries the billing_lines edge of a SubscriptionPhase. +func (c *SubscriptionPhaseClient) QueryBillingLines(_m *SubscriptionPhase) *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscriptionphase.Table, subscriptionphase.FieldID, id), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, subscriptionphase.BillingLinesTable, subscriptionphase.BillingLinesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingSplitLineGroups queries the billing_split_line_groups edge of a SubscriptionPhase. +func (c *SubscriptionPhaseClient) QueryBillingSplitLineGroups(_m *SubscriptionPhase) *BillingInvoiceSplitLineGroupQuery { + query := (&BillingInvoiceSplitLineGroupClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscriptionphase.Table, subscriptionphase.FieldID, id), + sqlgraph.To(billinginvoicesplitlinegroup.Table, billinginvoicesplitlinegroup.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, subscriptionphase.BillingSplitLineGroupsTable, subscriptionphase.BillingSplitLineGroupsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargesUsageBased queries the charges_usage_based edge of a SubscriptionPhase. +func (c *SubscriptionPhaseClient) QueryChargesUsageBased(_m *SubscriptionPhase) *ChargeUsageBasedQuery { + query := (&ChargeUsageBasedClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscriptionphase.Table, subscriptionphase.FieldID, id), + sqlgraph.To(chargeusagebased.Table, chargeusagebased.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, subscriptionphase.ChargesUsageBasedTable, subscriptionphase.ChargesUsageBasedColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargesCreditPurchase queries the charges_credit_purchase edge of a SubscriptionPhase. +func (c *SubscriptionPhaseClient) QueryChargesCreditPurchase(_m *SubscriptionPhase) *ChargeCreditPurchaseQuery { + query := (&ChargeCreditPurchaseClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscriptionphase.Table, subscriptionphase.FieldID, id), + sqlgraph.To(chargecreditpurchase.Table, chargecreditpurchase.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, subscriptionphase.ChargesCreditPurchaseTable, subscriptionphase.ChargesCreditPurchaseColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargesFlatFee queries the charges_flat_fee edge of a SubscriptionPhase. +func (c *SubscriptionPhaseClient) QueryChargesFlatFee(_m *SubscriptionPhase) *ChargeFlatFeeQuery { + query := (&ChargeFlatFeeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(subscriptionphase.Table, subscriptionphase.FieldID, id), + sqlgraph.To(chargeflatfee.Table, chargeflatfee.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, subscriptionphase.ChargesFlatFeeTable, subscriptionphase.ChargesFlatFeeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *SubscriptionPhaseClient) Hooks() []Hook { + return c.hooks.SubscriptionPhase +} + +// Interceptors returns the client interceptors. +func (c *SubscriptionPhaseClient) Interceptors() []Interceptor { + return c.inters.SubscriptionPhase +} + +func (c *SubscriptionPhaseClient) mutate(ctx context.Context, m *SubscriptionPhaseMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&SubscriptionPhaseCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&SubscriptionPhaseUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&SubscriptionPhaseUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&SubscriptionPhaseDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown SubscriptionPhase mutation op: %q", m.Op()) + } +} + +// TaxCodeClient is a client for the TaxCode schema. +type TaxCodeClient struct { + config +} + +// NewTaxCodeClient returns a client for the TaxCode from the given config. +func NewTaxCodeClient(c config) *TaxCodeClient { + return &TaxCodeClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `dbtaxcode.Hooks(f(g(h())))`. +func (c *TaxCodeClient) Use(hooks ...Hook) { + c.hooks.TaxCode = append(c.hooks.TaxCode, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `dbtaxcode.Intercept(f(g(h())))`. +func (c *TaxCodeClient) Intercept(interceptors ...Interceptor) { + c.inters.TaxCode = append(c.inters.TaxCode, interceptors...) +} + +// Create returns a builder for creating a TaxCode entity. +func (c *TaxCodeClient) Create() *TaxCodeCreate { + mutation := newTaxCodeMutation(c.config, OpCreate) + return &TaxCodeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of TaxCode entities. +func (c *TaxCodeClient) CreateBulk(builders ...*TaxCodeCreate) *TaxCodeCreateBulk { + return &TaxCodeCreateBulk{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 *TaxCodeClient) MapCreateBulk(slice any, setFunc func(*TaxCodeCreate, int)) *TaxCodeCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &TaxCodeCreateBulk{err: fmt.Errorf("calling to TaxCodeClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*TaxCodeCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &TaxCodeCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for TaxCode. +func (c *TaxCodeClient) Update() *TaxCodeUpdate { + mutation := newTaxCodeMutation(c.config, OpUpdate) + return &TaxCodeUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *TaxCodeClient) UpdateOne(_m *TaxCode) *TaxCodeUpdateOne { + mutation := newTaxCodeMutation(c.config, OpUpdateOne, withTaxCode(_m)) + return &TaxCodeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *TaxCodeClient) UpdateOneID(id string) *TaxCodeUpdateOne { + mutation := newTaxCodeMutation(c.config, OpUpdateOne, withTaxCodeID(id)) + return &TaxCodeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for TaxCode. +func (c *TaxCodeClient) Delete() *TaxCodeDelete { + mutation := newTaxCodeMutation(c.config, OpDelete) + return &TaxCodeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *TaxCodeClient) DeleteOne(_m *TaxCode) *TaxCodeDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *TaxCodeClient) DeleteOneID(id string) *TaxCodeDeleteOne { + builder := c.Delete().Where(dbtaxcode.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &TaxCodeDeleteOne{builder} +} + +// Query returns a query builder for TaxCode. +func (c *TaxCodeClient) Query() *TaxCodeQuery { + return &TaxCodeQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeTaxCode}, + inters: c.Interceptors(), + } +} + +// Get returns a TaxCode entity by its id. +func (c *TaxCodeClient) Get(ctx context.Context, id string) (*TaxCode, error) { + return c.Query().Where(dbtaxcode.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *TaxCodeClient) GetX(ctx context.Context, id string) *TaxCode { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryBillingWorkflowConfigs queries the billing_workflow_configs edge of a TaxCode. +func (c *TaxCodeClient) QueryBillingWorkflowConfigs(_m *TaxCode) *BillingWorkflowConfigQuery { + query := (&BillingWorkflowConfigClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbtaxcode.Table, dbtaxcode.FieldID, id), + sqlgraph.To(billingworkflowconfig.Table, billingworkflowconfig.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbtaxcode.BillingWorkflowConfigsTable, dbtaxcode.BillingWorkflowConfigsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingCustomerOverrides queries the billing_customer_overrides edge of a TaxCode. +func (c *TaxCodeClient) QueryBillingCustomerOverrides(_m *TaxCode) *BillingCustomerOverrideQuery { + query := (&BillingCustomerOverrideClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbtaxcode.Table, dbtaxcode.FieldID, id), + sqlgraph.To(billingcustomeroverride.Table, billingcustomeroverride.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbtaxcode.BillingCustomerOverridesTable, dbtaxcode.BillingCustomerOverridesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryBillingInvoiceLines queries the billing_invoice_lines edge of a TaxCode. +func (c *TaxCodeClient) QueryBillingInvoiceLines(_m *TaxCode) *BillingInvoiceLineQuery { + query := (&BillingInvoiceLineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbtaxcode.Table, dbtaxcode.FieldID, id), + sqlgraph.To(billinginvoiceline.Table, billinginvoiceline.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbtaxcode.BillingInvoiceLinesTable, dbtaxcode.BillingInvoiceLinesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubscriptionItems queries the subscription_items edge of a TaxCode. +func (c *TaxCodeClient) QuerySubscriptionItems(_m *TaxCode) *SubscriptionItemQuery { + query := (&SubscriptionItemClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbtaxcode.Table, dbtaxcode.FieldID, id), + sqlgraph.To(subscriptionitem.Table, subscriptionitem.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbtaxcode.SubscriptionItemsTable, dbtaxcode.SubscriptionItemsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryPlanRateCards queries the plan_rate_cards edge of a TaxCode. +func (c *TaxCodeClient) QueryPlanRateCards(_m *TaxCode) *PlanRateCardQuery { + query := (&PlanRateCardClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbtaxcode.Table, dbtaxcode.FieldID, id), + sqlgraph.To(planratecard.Table, planratecard.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbtaxcode.PlanRateCardsTable, dbtaxcode.PlanRateCardsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryAddonRateCards queries the addon_rate_cards edge of a TaxCode. +func (c *TaxCodeClient) QueryAddonRateCards(_m *TaxCode) *AddonRateCardQuery { + query := (&AddonRateCardClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbtaxcode.Table, dbtaxcode.FieldID, id), + sqlgraph.To(addonratecard.Table, addonratecard.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbtaxcode.AddonRateCardsTable, dbtaxcode.AddonRateCardsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargeFlatFees queries the charge_flat_fees edge of a TaxCode. +func (c *TaxCodeClient) QueryChargeFlatFees(_m *TaxCode) *ChargeFlatFeeQuery { + query := (&ChargeFlatFeeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbtaxcode.Table, dbtaxcode.FieldID, id), + sqlgraph.To(chargeflatfee.Table, chargeflatfee.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbtaxcode.ChargeFlatFeesTable, dbtaxcode.ChargeFlatFeesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargeFlatFeeOverrides queries the charge_flat_fee_overrides edge of a TaxCode. +func (c *TaxCodeClient) QueryChargeFlatFeeOverrides(_m *TaxCode) *ChargeFlatFeeOverrideQuery { + query := (&ChargeFlatFeeOverrideClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbtaxcode.Table, dbtaxcode.FieldID, id), + sqlgraph.To(chargeflatfeeoverride.Table, chargeflatfeeoverride.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbtaxcode.ChargeFlatFeeOverridesTable, dbtaxcode.ChargeFlatFeeOverridesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargeUsageBased queries the charge_usage_based edge of a TaxCode. +func (c *TaxCodeClient) QueryChargeUsageBased(_m *TaxCode) *ChargeUsageBasedQuery { + query := (&ChargeUsageBasedClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbtaxcode.Table, dbtaxcode.FieldID, id), + sqlgraph.To(chargeusagebased.Table, chargeusagebased.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbtaxcode.ChargeUsageBasedTable, dbtaxcode.ChargeUsageBasedColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargeUsageBasedOverrides queries the charge_usage_based_overrides edge of a TaxCode. +func (c *TaxCodeClient) QueryChargeUsageBasedOverrides(_m *TaxCode) *ChargeUsageBasedOverrideQuery { + query := (&ChargeUsageBasedOverrideClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbtaxcode.Table, dbtaxcode.FieldID, id), + sqlgraph.To(chargeusagebasedoverride.Table, chargeusagebasedoverride.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbtaxcode.ChargeUsageBasedOverridesTable, dbtaxcode.ChargeUsageBasedOverridesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChargeCreditPurchases queries the charge_credit_purchases edge of a TaxCode. +func (c *TaxCodeClient) QueryChargeCreditPurchases(_m *TaxCode) *ChargeCreditPurchaseQuery { + query := (&ChargeCreditPurchaseClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbtaxcode.Table, dbtaxcode.FieldID, id), + sqlgraph.To(chargecreditpurchase.Table, chargecreditpurchase.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbtaxcode.ChargeCreditPurchasesTable, dbtaxcode.ChargeCreditPurchasesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryOrganizationDefaultInvoicing queries the organization_default_invoicing edge of a TaxCode. +func (c *TaxCodeClient) QueryOrganizationDefaultInvoicing(_m *TaxCode) *OrganizationDefaultTaxCodesQuery { + query := (&OrganizationDefaultTaxCodesClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbtaxcode.Table, dbtaxcode.FieldID, id), + sqlgraph.To(organizationdefaulttaxcodes.Table, organizationdefaulttaxcodes.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbtaxcode.OrganizationDefaultInvoicingTable, dbtaxcode.OrganizationDefaultInvoicingColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryOrganizationDefaultCreditGrant queries the organization_default_credit_grant edge of a TaxCode. +func (c *TaxCodeClient) QueryOrganizationDefaultCreditGrant(_m *TaxCode) *OrganizationDefaultTaxCodesQuery { + query := (&OrganizationDefaultTaxCodesClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(dbtaxcode.Table, dbtaxcode.FieldID, id), + sqlgraph.To(organizationdefaulttaxcodes.Table, organizationdefaulttaxcodes.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbtaxcode.OrganizationDefaultCreditGrantTable, dbtaxcode.OrganizationDefaultCreditGrantColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *TaxCodeClient) Hooks() []Hook { + return c.hooks.TaxCode +} + +// Interceptors returns the client interceptors. +func (c *TaxCodeClient) Interceptors() []Interceptor { + return c.inters.TaxCode +} + +func (c *TaxCodeClient) mutate(ctx context.Context, m *TaxCodeMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&TaxCodeCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&TaxCodeUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&TaxCodeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&TaxCodeDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown TaxCode mutation op: %q", m.Op()) + } +} + +// UsageResetClient is a client for the UsageReset schema. +type UsageResetClient struct { + config +} + +// NewUsageResetClient returns a client for the UsageReset from the given config. +func NewUsageResetClient(c config) *UsageResetClient { + return &UsageResetClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `usagereset.Hooks(f(g(h())))`. +func (c *UsageResetClient) Use(hooks ...Hook) { + c.hooks.UsageReset = append(c.hooks.UsageReset, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `usagereset.Intercept(f(g(h())))`. +func (c *UsageResetClient) Intercept(interceptors ...Interceptor) { + c.inters.UsageReset = append(c.inters.UsageReset, interceptors...) +} + +// Create returns a builder for creating a UsageReset entity. +func (c *UsageResetClient) Create() *UsageResetCreate { + mutation := newUsageResetMutation(c.config, OpCreate) + return &UsageResetCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of UsageReset entities. +func (c *UsageResetClient) CreateBulk(builders ...*UsageResetCreate) *UsageResetCreateBulk { + return &UsageResetCreateBulk{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 *UsageResetClient) MapCreateBulk(slice any, setFunc func(*UsageResetCreate, int)) *UsageResetCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &UsageResetCreateBulk{err: fmt.Errorf("calling to UsageResetClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*UsageResetCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &UsageResetCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for UsageReset. +func (c *UsageResetClient) Update() *UsageResetUpdate { + mutation := newUsageResetMutation(c.config, OpUpdate) + return &UsageResetUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *UsageResetClient) UpdateOne(_m *UsageReset) *UsageResetUpdateOne { + mutation := newUsageResetMutation(c.config, OpUpdateOne, withUsageReset(_m)) + return &UsageResetUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *UsageResetClient) UpdateOneID(id string) *UsageResetUpdateOne { + mutation := newUsageResetMutation(c.config, OpUpdateOne, withUsageResetID(id)) + return &UsageResetUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for UsageReset. +func (c *UsageResetClient) Delete() *UsageResetDelete { + mutation := newUsageResetMutation(c.config, OpDelete) + return &UsageResetDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *UsageResetClient) DeleteOne(_m *UsageReset) *UsageResetDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *UsageResetClient) DeleteOneID(id string) *UsageResetDeleteOne { + builder := c.Delete().Where(usagereset.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &UsageResetDeleteOne{builder} +} + +// Query returns a query builder for UsageReset. +func (c *UsageResetClient) Query() *UsageResetQuery { + return &UsageResetQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeUsageReset}, + inters: c.Interceptors(), + } +} + +// Get returns a UsageReset entity by its id. +func (c *UsageResetClient) Get(ctx context.Context, id string) (*UsageReset, error) { + return c.Query().Where(usagereset.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *UsageResetClient) GetX(ctx context.Context, id string) *UsageReset { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryEntitlement queries the entitlement edge of a UsageReset. +func (c *UsageResetClient) QueryEntitlement(_m *UsageReset) *EntitlementQuery { + query := (&EntitlementClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(usagereset.Table, usagereset.FieldID, id), + sqlgraph.To(entitlement.Table, entitlement.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, usagereset.EntitlementTable, usagereset.EntitlementColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *UsageResetClient) Hooks() []Hook { + return c.hooks.UsageReset +} + +// Interceptors returns the client interceptors. +func (c *UsageResetClient) Interceptors() []Interceptor { + return c.inters.UsageReset +} + +func (c *UsageResetClient) mutate(ctx context.Context, m *UsageResetMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&UsageResetCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&UsageResetUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&UsageResetUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&UsageResetDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown UsageReset mutation op: %q", m.Op()) + } +} + +// hooks and interceptors per client, for fast access. +type ( + hooks struct { + Addon, AddonRateCard, App, AppCustomInvoicing, AppCustomInvoicingCustomer, + AppCustomer, AppStripe, AppStripeCustomer, BalanceSnapshot, + BillingCustomerLock, BillingCustomerOverride, BillingInvoice, + BillingInvoiceFlatFeeLineConfig, BillingInvoiceLine, + BillingInvoiceLineDiscount, BillingInvoiceLineUsageDiscount, + BillingInvoiceSplitLineGroup, BillingInvoiceUsageBasedLineConfig, + BillingInvoiceValidationIssue, BillingInvoiceWriteSchemaLevel, BillingProfile, + BillingSequenceNumbers, BillingStandardInvoiceDetailedLine, + BillingStandardInvoiceDetailedLineAmountDiscount, BillingWorkflowConfig, + Charge, ChargeCreditPurchase, ChargeCreditPurchaseCreditGrant, + ChargeCreditPurchaseExternalPayment, ChargeCreditPurchaseInvoicedPayment, + ChargeFlatFee, ChargeFlatFeeOverride, ChargeFlatFeeRun, + ChargeFlatFeeRunCreditAllocations, ChargeFlatFeeRunDetailedLine, + ChargeFlatFeeRunInvoicedUsage, ChargeFlatFeeRunPayment, ChargeUsageBased, + ChargeUsageBasedOverride, ChargeUsageBasedRunCreditAllocations, + ChargeUsageBasedRunDetailedLine, ChargeUsageBasedRunInvoicedUsage, + ChargeUsageBasedRunPayment, ChargeUsageBasedRuns, CreditRealizationLineage, + CreditRealizationLineageSegment, CurrencyCostBasis, CustomCurrency, Customer, + CustomerSubjects, Entitlement, Feature, Grant, LLMCostPrice, LedgerAccount, + LedgerBreakageRecord, LedgerCreditVoidRecord, LedgerCustomerAccount, + LedgerEntry, LedgerSubAccount, LedgerSubAccountRoute, LedgerTransaction, + LedgerTransactionGroup, Meter, NotificationChannel, NotificationEvent, + NotificationEventDeliveryStatus, NotificationRule, OrganizationDefaultTaxCodes, + Plan, PlanAddon, PlanPhase, PlanRateCard, Subject, Subscription, + SubscriptionAddon, SubscriptionAddonQuantity, SubscriptionBillingSyncState, + SubscriptionItem, SubscriptionPhase, TaxCode, UsageReset []ent.Hook + } + inters struct { + Addon, AddonRateCard, App, AppCustomInvoicing, AppCustomInvoicingCustomer, + AppCustomer, AppStripe, AppStripeCustomer, BalanceSnapshot, + BillingCustomerLock, BillingCustomerOverride, BillingInvoice, + BillingInvoiceFlatFeeLineConfig, BillingInvoiceLine, + BillingInvoiceLineDiscount, BillingInvoiceLineUsageDiscount, + BillingInvoiceSplitLineGroup, BillingInvoiceUsageBasedLineConfig, + BillingInvoiceValidationIssue, BillingInvoiceWriteSchemaLevel, BillingProfile, + BillingSequenceNumbers, BillingStandardInvoiceDetailedLine, + BillingStandardInvoiceDetailedLineAmountDiscount, BillingWorkflowConfig, + Charge, ChargeCreditPurchase, ChargeCreditPurchaseCreditGrant, + ChargeCreditPurchaseExternalPayment, ChargeCreditPurchaseInvoicedPayment, + ChargeFlatFee, ChargeFlatFeeOverride, ChargeFlatFeeRun, + ChargeFlatFeeRunCreditAllocations, ChargeFlatFeeRunDetailedLine, + ChargeFlatFeeRunInvoicedUsage, ChargeFlatFeeRunPayment, ChargeUsageBased, + ChargeUsageBasedOverride, ChargeUsageBasedRunCreditAllocations, + ChargeUsageBasedRunDetailedLine, ChargeUsageBasedRunInvoicedUsage, + ChargeUsageBasedRunPayment, ChargeUsageBasedRuns, ChargesSearchV1, + CreditRealizationLineage, CreditRealizationLineageSegment, CurrencyCostBasis, + CustomCurrency, Customer, CustomerSubjects, Entitlement, Feature, Grant, + LLMCostPrice, LedgerAccount, LedgerBreakageRecord, LedgerCreditVoidRecord, + LedgerCustomerAccount, LedgerEntry, LedgerSubAccount, LedgerSubAccountRoute, + LedgerTransaction, LedgerTransactionGroup, Meter, NotificationChannel, + NotificationEvent, NotificationEventDeliveryStatus, NotificationRule, + OrganizationDefaultTaxCodes, Plan, PlanAddon, PlanPhase, PlanRateCard, Subject, + Subscription, SubscriptionAddon, SubscriptionAddonQuantity, + SubscriptionBillingSyncState, SubscriptionItem, SubscriptionPhase, TaxCode, + UsageReset []ent.Interceptor + } +) + +// ExecContext allows calling the underlying ExecContext method of the driver if it is supported by it. +// See, database/sql#DB.ExecContext for more information. +func (c *config) ExecContext(ctx context.Context, query string, args ...any) (stdsql.Result, error) { + ex, ok := c.driver.(interface { + ExecContext(context.Context, string, ...any) (stdsql.Result, error) + }) + if !ok { + return nil, fmt.Errorf("Driver.ExecContext is not supported") + } + return ex.ExecContext(ctx, query, args...) +} + +// QueryContext allows calling the underlying QueryContext method of the driver if it is supported by it. +// See, database/sql#DB.QueryContext for more information. +func (c *config) QueryContext(ctx context.Context, query string, args ...any) (*stdsql.Rows, error) { + q, ok := c.driver.(interface { + QueryContext(context.Context, string, ...any) (*stdsql.Rows, error) + }) + if !ok { + return nil, fmt.Errorf("Driver.QueryContext is not supported") + } + return q.QueryContext(ctx, query, args...) +} diff --git a/ent/db/creditrealizationlineage.go b/ent/db/creditrealizationlineage.go new file mode 100644 index 0000000000000000000000000000000000000000..fceccdd6d82ded04d82ffb9bd2e7ce2d5383a73e --- /dev/null +++ b/ent/db/creditrealizationlineage.go @@ -0,0 +1,231 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/lib/pq" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/creditrealization" + "github.com/openmeterio/openmeter/openmeter/ent/db/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/creditrealizationlineage" + "github.com/openmeterio/openmeter/pkg/currencyx" +) + +// CreditRealizationLineage is the model entity for the CreditRealizationLineage schema. +type CreditRealizationLineage 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"` + // ChargeID holds the value of the "charge_id" field. + ChargeID string `json:"charge_id,omitempty"` + // RootRealizationID holds the value of the "root_realization_id" field. + RootRealizationID string `json:"root_realization_id,omitempty"` + // CustomerID holds the value of the "customer_id" field. + CustomerID string `json:"customer_id,omitempty"` + // Currency holds the value of the "currency" field. + Currency currencyx.Code `json:"currency,omitempty"` + // OriginKind holds the value of the "origin_kind" field. + OriginKind creditrealization.LineageOriginKind `json:"origin_kind,omitempty"` + // AdvanceFeatures holds the value of the "advance_features" field. + AdvanceFeatures pq.StringArray `json:"advance_features,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the CreditRealizationLineageQuery when eager-loading is set. + Edges CreditRealizationLineageEdges `json:"edges"` + selectValues sql.SelectValues +} + +// CreditRealizationLineageEdges holds the relations/edges for other nodes in the graph. +type CreditRealizationLineageEdges struct { + // Charge holds the value of the charge edge. + Charge *Charge `json:"charge,omitempty"` + // Segments holds the value of the segments edge. + Segments []*CreditRealizationLineageSegment `json:"segments,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 CreditRealizationLineageEdges) 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"} +} + +// SegmentsOrErr returns the Segments value or an error if the edge +// was not loaded in eager-loading. +func (e CreditRealizationLineageEdges) SegmentsOrErr() ([]*CreditRealizationLineageSegment, error) { + if e.loadedTypes[1] { + return e.Segments, nil + } + return nil, &NotLoadedError{edge: "segments"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*CreditRealizationLineage) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case creditrealizationlineage.FieldAdvanceFeatures: + values[i] = new(pq.StringArray) + case creditrealizationlineage.FieldID, creditrealizationlineage.FieldNamespace, creditrealizationlineage.FieldChargeID, creditrealizationlineage.FieldRootRealizationID, creditrealizationlineage.FieldCustomerID, creditrealizationlineage.FieldCurrency, creditrealizationlineage.FieldOriginKind: + values[i] = new(sql.NullString) + case creditrealizationlineage.FieldCreatedAt: + 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 CreditRealizationLineage fields. +func (_m *CreditRealizationLineage) 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 creditrealizationlineage.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 creditrealizationlineage.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 creditrealizationlineage.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 creditrealizationlineage.FieldRootRealizationID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field root_realization_id", values[i]) + } else if value.Valid { + _m.RootRealizationID = value.String + } + case creditrealizationlineage.FieldCustomerID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field customer_id", values[i]) + } else if value.Valid { + _m.CustomerID = value.String + } + case creditrealizationlineage.FieldCurrency: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field currency", values[i]) + } else if value.Valid { + _m.Currency = currencyx.Code(value.String) + } + case creditrealizationlineage.FieldOriginKind: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field origin_kind", values[i]) + } else if value.Valid { + _m.OriginKind = creditrealization.LineageOriginKind(value.String) + } + case creditrealizationlineage.FieldAdvanceFeatures: + if value, ok := values[i].(*pq.StringArray); !ok { + return fmt.Errorf("unexpected type %T for field advance_features", values[i]) + } else if value != nil { + _m.AdvanceFeatures = *value + } + case creditrealizationlineage.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 + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the CreditRealizationLineage. +// This includes values selected through modifiers, order, etc. +func (_m *CreditRealizationLineage) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryCharge queries the "charge" edge of the CreditRealizationLineage entity. +func (_m *CreditRealizationLineage) QueryCharge() *ChargeQuery { + return NewCreditRealizationLineageClient(_m.config).QueryCharge(_m) +} + +// QuerySegments queries the "segments" edge of the CreditRealizationLineage entity. +func (_m *CreditRealizationLineage) QuerySegments() *CreditRealizationLineageSegmentQuery { + return NewCreditRealizationLineageClient(_m.config).QuerySegments(_m) +} + +// Update returns a builder for updating this CreditRealizationLineage. +// Note that you need to call CreditRealizationLineage.Unwrap() before calling this method if this CreditRealizationLineage +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *CreditRealizationLineage) Update() *CreditRealizationLineageUpdateOne { + return NewCreditRealizationLineageClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the CreditRealizationLineage 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 *CreditRealizationLineage) Unwrap() *CreditRealizationLineage { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: CreditRealizationLineage is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *CreditRealizationLineage) String() string { + var builder strings.Builder + builder.WriteString("CreditRealizationLineage(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("charge_id=") + builder.WriteString(_m.ChargeID) + builder.WriteString(", ") + builder.WriteString("root_realization_id=") + builder.WriteString(_m.RootRealizationID) + builder.WriteString(", ") + builder.WriteString("customer_id=") + builder.WriteString(_m.CustomerID) + builder.WriteString(", ") + builder.WriteString("currency=") + builder.WriteString(fmt.Sprintf("%v", _m.Currency)) + builder.WriteString(", ") + builder.WriteString("origin_kind=") + builder.WriteString(fmt.Sprintf("%v", _m.OriginKind)) + builder.WriteString(", ") + builder.WriteString("advance_features=") + builder.WriteString(fmt.Sprintf("%v", _m.AdvanceFeatures)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// CreditRealizationLineages is a parsable slice of CreditRealizationLineage. +type CreditRealizationLineages []*CreditRealizationLineage diff --git a/ent/db/creditrealizationlineage/creditrealizationlineage.go b/ent/db/creditrealizationlineage/creditrealizationlineage.go new file mode 100644 index 0000000000000000000000000000000000000000..c96345bfeb8353487af567cde1fbd2a70d33d725 --- /dev/null +++ b/ent/db/creditrealizationlineage/creditrealizationlineage.go @@ -0,0 +1,188 @@ +// Code generated by ent, DO NOT EDIT. + +package creditrealizationlineage + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/creditrealization" +) + +const ( + // Label holds the string label denoting the creditrealizationlineage type in the database. + Label = "credit_realization_lineage" + // 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" + // FieldChargeID holds the string denoting the charge_id field in the database. + FieldChargeID = "charge_id" + // FieldRootRealizationID holds the string denoting the root_realization_id field in the database. + FieldRootRealizationID = "root_realization_id" + // FieldCustomerID holds the string denoting the customer_id field in the database. + FieldCustomerID = "customer_id" + // FieldCurrency holds the string denoting the currency field in the database. + FieldCurrency = "currency" + // FieldOriginKind holds the string denoting the origin_kind field in the database. + FieldOriginKind = "origin_kind" + // FieldAdvanceFeatures holds the string denoting the advance_features field in the database. + FieldAdvanceFeatures = "advance_features" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // EdgeCharge holds the string denoting the charge edge name in mutations. + EdgeCharge = "charge" + // EdgeSegments holds the string denoting the segments edge name in mutations. + EdgeSegments = "segments" + // Table holds the table name of the creditrealizationlineage in the database. + Table = "credit_realization_lineages" + // ChargeTable is the table that holds the charge relation/edge. + ChargeTable = "credit_realization_lineages" + // 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 = "charge_id" + // SegmentsTable is the table that holds the segments relation/edge. + SegmentsTable = "credit_realization_lineage_segments" + // SegmentsInverseTable is the table name for the CreditRealizationLineageSegment entity. + // It exists in this package in order to avoid circular dependency with the "creditrealizationlineagesegment" package. + SegmentsInverseTable = "credit_realization_lineage_segments" + // SegmentsColumn is the table column denoting the segments relation/edge. + SegmentsColumn = "lineage_id" +) + +// Columns holds all SQL columns for creditrealizationlineage fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldChargeID, + FieldRootRealizationID, + FieldCustomerID, + FieldCurrency, + FieldOriginKind, + FieldAdvanceFeatures, + FieldCreatedAt, +} + +// 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 + // ChargeIDValidator is a validator for the "charge_id" field. It is called by the builders before save. + ChargeIDValidator func(string) error + // RootRealizationIDValidator is a validator for the "root_realization_id" field. It is called by the builders before save. + RootRealizationIDValidator func(string) error + // CustomerIDValidator is a validator for the "customer_id" field. It is called by the builders before save. + CustomerIDValidator func(string) error + // CurrencyValidator is a validator for the "currency" field. It is called by the builders before save. + CurrencyValidator func(string) error + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// OriginKindValidator is a validator for the "origin_kind" field enum values. It is called by the builders before save. +func OriginKindValidator(ok creditrealization.LineageOriginKind) error { + switch ok { + case "real_credit", "advance": + return nil + default: + return fmt.Errorf("creditrealizationlineage: invalid enum value for origin_kind field: %q", ok) + } +} + +// OrderOption defines the ordering options for the CreditRealizationLineage 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() +} + +// ByChargeID orders the results by the charge_id field. +func ByChargeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChargeID, opts...).ToFunc() +} + +// ByRootRealizationID orders the results by the root_realization_id field. +func ByRootRealizationID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRootRealizationID, opts...).ToFunc() +} + +// ByCustomerID orders the results by the customer_id field. +func ByCustomerID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCustomerID, opts...).ToFunc() +} + +// ByCurrency orders the results by the currency field. +func ByCurrency(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCurrency, opts...).ToFunc() +} + +// ByOriginKind orders the results by the origin_kind field. +func ByOriginKind(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldOriginKind, opts...).ToFunc() +} + +// ByAdvanceFeatures orders the results by the advance_features field. +func ByAdvanceFeatures(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAdvanceFeatures, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, 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...)) + } +} + +// BySegmentsCount orders the results by segments count. +func BySegmentsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newSegmentsStep(), opts...) + } +} + +// BySegments orders the results by segments terms. +func BySegments(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSegmentsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newChargeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ChargeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ChargeTable, ChargeColumn), + ) +} +func newSegmentsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SegmentsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SegmentsTable, SegmentsColumn), + ) +} diff --git a/ent/db/creditrealizationlineage/where.go b/ent/db/creditrealizationlineage/where.go new file mode 100644 index 0000000000000000000000000000000000000000..63688cb8514e35f77181f92372b854fe627255a8 --- /dev/null +++ b/ent/db/creditrealizationlineage/where.go @@ -0,0 +1,630 @@ +// Code generated by ent, DO NOT EDIT. + +package creditrealizationlineage + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/lib/pq" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/creditrealization" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/currencyx" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldEQ(FieldNamespace, v)) +} + +// ChargeID applies equality check predicate on the "charge_id" field. It's identical to ChargeIDEQ. +func ChargeID(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldEQ(FieldChargeID, v)) +} + +// RootRealizationID applies equality check predicate on the "root_realization_id" field. It's identical to RootRealizationIDEQ. +func RootRealizationID(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldEQ(FieldRootRealizationID, v)) +} + +// CustomerID applies equality check predicate on the "customer_id" field. It's identical to CustomerIDEQ. +func CustomerID(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldEQ(FieldCustomerID, v)) +} + +// Currency applies equality check predicate on the "currency" field. It's identical to CurrencyEQ. +func Currency(v currencyx.Code) predicate.CreditRealizationLineage { + vc := string(v) + return predicate.CreditRealizationLineage(sql.FieldEQ(FieldCurrency, vc)) +} + +// AdvanceFeatures applies equality check predicate on the "advance_features" field. It's identical to AdvanceFeaturesEQ. +func AdvanceFeatures(v pq.StringArray) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldEQ(FieldAdvanceFeatures, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldEQ(FieldCreatedAt, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldContainsFold(FieldNamespace, v)) +} + +// ChargeIDEQ applies the EQ predicate on the "charge_id" field. +func ChargeIDEQ(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldEQ(FieldChargeID, v)) +} + +// ChargeIDNEQ applies the NEQ predicate on the "charge_id" field. +func ChargeIDNEQ(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldNEQ(FieldChargeID, v)) +} + +// ChargeIDIn applies the In predicate on the "charge_id" field. +func ChargeIDIn(vs ...string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldIn(FieldChargeID, vs...)) +} + +// ChargeIDNotIn applies the NotIn predicate on the "charge_id" field. +func ChargeIDNotIn(vs ...string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldNotIn(FieldChargeID, vs...)) +} + +// ChargeIDGT applies the GT predicate on the "charge_id" field. +func ChargeIDGT(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldGT(FieldChargeID, v)) +} + +// ChargeIDGTE applies the GTE predicate on the "charge_id" field. +func ChargeIDGTE(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldGTE(FieldChargeID, v)) +} + +// ChargeIDLT applies the LT predicate on the "charge_id" field. +func ChargeIDLT(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldLT(FieldChargeID, v)) +} + +// ChargeIDLTE applies the LTE predicate on the "charge_id" field. +func ChargeIDLTE(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldLTE(FieldChargeID, v)) +} + +// ChargeIDContains applies the Contains predicate on the "charge_id" field. +func ChargeIDContains(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldContains(FieldChargeID, v)) +} + +// ChargeIDHasPrefix applies the HasPrefix predicate on the "charge_id" field. +func ChargeIDHasPrefix(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldHasPrefix(FieldChargeID, v)) +} + +// ChargeIDHasSuffix applies the HasSuffix predicate on the "charge_id" field. +func ChargeIDHasSuffix(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldHasSuffix(FieldChargeID, v)) +} + +// ChargeIDEqualFold applies the EqualFold predicate on the "charge_id" field. +func ChargeIDEqualFold(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldEqualFold(FieldChargeID, v)) +} + +// ChargeIDContainsFold applies the ContainsFold predicate on the "charge_id" field. +func ChargeIDContainsFold(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldContainsFold(FieldChargeID, v)) +} + +// RootRealizationIDEQ applies the EQ predicate on the "root_realization_id" field. +func RootRealizationIDEQ(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldEQ(FieldRootRealizationID, v)) +} + +// RootRealizationIDNEQ applies the NEQ predicate on the "root_realization_id" field. +func RootRealizationIDNEQ(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldNEQ(FieldRootRealizationID, v)) +} + +// RootRealizationIDIn applies the In predicate on the "root_realization_id" field. +func RootRealizationIDIn(vs ...string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldIn(FieldRootRealizationID, vs...)) +} + +// RootRealizationIDNotIn applies the NotIn predicate on the "root_realization_id" field. +func RootRealizationIDNotIn(vs ...string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldNotIn(FieldRootRealizationID, vs...)) +} + +// RootRealizationIDGT applies the GT predicate on the "root_realization_id" field. +func RootRealizationIDGT(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldGT(FieldRootRealizationID, v)) +} + +// RootRealizationIDGTE applies the GTE predicate on the "root_realization_id" field. +func RootRealizationIDGTE(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldGTE(FieldRootRealizationID, v)) +} + +// RootRealizationIDLT applies the LT predicate on the "root_realization_id" field. +func RootRealizationIDLT(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldLT(FieldRootRealizationID, v)) +} + +// RootRealizationIDLTE applies the LTE predicate on the "root_realization_id" field. +func RootRealizationIDLTE(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldLTE(FieldRootRealizationID, v)) +} + +// RootRealizationIDContains applies the Contains predicate on the "root_realization_id" field. +func RootRealizationIDContains(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldContains(FieldRootRealizationID, v)) +} + +// RootRealizationIDHasPrefix applies the HasPrefix predicate on the "root_realization_id" field. +func RootRealizationIDHasPrefix(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldHasPrefix(FieldRootRealizationID, v)) +} + +// RootRealizationIDHasSuffix applies the HasSuffix predicate on the "root_realization_id" field. +func RootRealizationIDHasSuffix(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldHasSuffix(FieldRootRealizationID, v)) +} + +// RootRealizationIDEqualFold applies the EqualFold predicate on the "root_realization_id" field. +func RootRealizationIDEqualFold(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldEqualFold(FieldRootRealizationID, v)) +} + +// RootRealizationIDContainsFold applies the ContainsFold predicate on the "root_realization_id" field. +func RootRealizationIDContainsFold(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldContainsFold(FieldRootRealizationID, v)) +} + +// CustomerIDEQ applies the EQ predicate on the "customer_id" field. +func CustomerIDEQ(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldEQ(FieldCustomerID, v)) +} + +// CustomerIDNEQ applies the NEQ predicate on the "customer_id" field. +func CustomerIDNEQ(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldNEQ(FieldCustomerID, v)) +} + +// CustomerIDIn applies the In predicate on the "customer_id" field. +func CustomerIDIn(vs ...string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldIn(FieldCustomerID, vs...)) +} + +// CustomerIDNotIn applies the NotIn predicate on the "customer_id" field. +func CustomerIDNotIn(vs ...string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldNotIn(FieldCustomerID, vs...)) +} + +// CustomerIDGT applies the GT predicate on the "customer_id" field. +func CustomerIDGT(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldGT(FieldCustomerID, v)) +} + +// CustomerIDGTE applies the GTE predicate on the "customer_id" field. +func CustomerIDGTE(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldGTE(FieldCustomerID, v)) +} + +// CustomerIDLT applies the LT predicate on the "customer_id" field. +func CustomerIDLT(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldLT(FieldCustomerID, v)) +} + +// CustomerIDLTE applies the LTE predicate on the "customer_id" field. +func CustomerIDLTE(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldLTE(FieldCustomerID, v)) +} + +// CustomerIDContains applies the Contains predicate on the "customer_id" field. +func CustomerIDContains(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldContains(FieldCustomerID, v)) +} + +// CustomerIDHasPrefix applies the HasPrefix predicate on the "customer_id" field. +func CustomerIDHasPrefix(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldHasPrefix(FieldCustomerID, v)) +} + +// CustomerIDHasSuffix applies the HasSuffix predicate on the "customer_id" field. +func CustomerIDHasSuffix(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldHasSuffix(FieldCustomerID, v)) +} + +// CustomerIDEqualFold applies the EqualFold predicate on the "customer_id" field. +func CustomerIDEqualFold(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldEqualFold(FieldCustomerID, v)) +} + +// CustomerIDContainsFold applies the ContainsFold predicate on the "customer_id" field. +func CustomerIDContainsFold(v string) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldContainsFold(FieldCustomerID, v)) +} + +// CurrencyEQ applies the EQ predicate on the "currency" field. +func CurrencyEQ(v currencyx.Code) predicate.CreditRealizationLineage { + vc := string(v) + return predicate.CreditRealizationLineage(sql.FieldEQ(FieldCurrency, vc)) +} + +// CurrencyNEQ applies the NEQ predicate on the "currency" field. +func CurrencyNEQ(v currencyx.Code) predicate.CreditRealizationLineage { + vc := string(v) + return predicate.CreditRealizationLineage(sql.FieldNEQ(FieldCurrency, vc)) +} + +// CurrencyIn applies the In predicate on the "currency" field. +func CurrencyIn(vs ...currencyx.Code) predicate.CreditRealizationLineage { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.CreditRealizationLineage(sql.FieldIn(FieldCurrency, v...)) +} + +// CurrencyNotIn applies the NotIn predicate on the "currency" field. +func CurrencyNotIn(vs ...currencyx.Code) predicate.CreditRealizationLineage { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.CreditRealizationLineage(sql.FieldNotIn(FieldCurrency, v...)) +} + +// CurrencyGT applies the GT predicate on the "currency" field. +func CurrencyGT(v currencyx.Code) predicate.CreditRealizationLineage { + vc := string(v) + return predicate.CreditRealizationLineage(sql.FieldGT(FieldCurrency, vc)) +} + +// CurrencyGTE applies the GTE predicate on the "currency" field. +func CurrencyGTE(v currencyx.Code) predicate.CreditRealizationLineage { + vc := string(v) + return predicate.CreditRealizationLineage(sql.FieldGTE(FieldCurrency, vc)) +} + +// CurrencyLT applies the LT predicate on the "currency" field. +func CurrencyLT(v currencyx.Code) predicate.CreditRealizationLineage { + vc := string(v) + return predicate.CreditRealizationLineage(sql.FieldLT(FieldCurrency, vc)) +} + +// CurrencyLTE applies the LTE predicate on the "currency" field. +func CurrencyLTE(v currencyx.Code) predicate.CreditRealizationLineage { + vc := string(v) + return predicate.CreditRealizationLineage(sql.FieldLTE(FieldCurrency, vc)) +} + +// CurrencyContains applies the Contains predicate on the "currency" field. +func CurrencyContains(v currencyx.Code) predicate.CreditRealizationLineage { + vc := string(v) + return predicate.CreditRealizationLineage(sql.FieldContains(FieldCurrency, vc)) +} + +// CurrencyHasPrefix applies the HasPrefix predicate on the "currency" field. +func CurrencyHasPrefix(v currencyx.Code) predicate.CreditRealizationLineage { + vc := string(v) + return predicate.CreditRealizationLineage(sql.FieldHasPrefix(FieldCurrency, vc)) +} + +// CurrencyHasSuffix applies the HasSuffix predicate on the "currency" field. +func CurrencyHasSuffix(v currencyx.Code) predicate.CreditRealizationLineage { + vc := string(v) + return predicate.CreditRealizationLineage(sql.FieldHasSuffix(FieldCurrency, vc)) +} + +// CurrencyEqualFold applies the EqualFold predicate on the "currency" field. +func CurrencyEqualFold(v currencyx.Code) predicate.CreditRealizationLineage { + vc := string(v) + return predicate.CreditRealizationLineage(sql.FieldEqualFold(FieldCurrency, vc)) +} + +// CurrencyContainsFold applies the ContainsFold predicate on the "currency" field. +func CurrencyContainsFold(v currencyx.Code) predicate.CreditRealizationLineage { + vc := string(v) + return predicate.CreditRealizationLineage(sql.FieldContainsFold(FieldCurrency, vc)) +} + +// OriginKindEQ applies the EQ predicate on the "origin_kind" field. +func OriginKindEQ(v creditrealization.LineageOriginKind) predicate.CreditRealizationLineage { + vc := v + return predicate.CreditRealizationLineage(sql.FieldEQ(FieldOriginKind, vc)) +} + +// OriginKindNEQ applies the NEQ predicate on the "origin_kind" field. +func OriginKindNEQ(v creditrealization.LineageOriginKind) predicate.CreditRealizationLineage { + vc := v + return predicate.CreditRealizationLineage(sql.FieldNEQ(FieldOriginKind, vc)) +} + +// OriginKindIn applies the In predicate on the "origin_kind" field. +func OriginKindIn(vs ...creditrealization.LineageOriginKind) predicate.CreditRealizationLineage { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.CreditRealizationLineage(sql.FieldIn(FieldOriginKind, v...)) +} + +// OriginKindNotIn applies the NotIn predicate on the "origin_kind" field. +func OriginKindNotIn(vs ...creditrealization.LineageOriginKind) predicate.CreditRealizationLineage { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.CreditRealizationLineage(sql.FieldNotIn(FieldOriginKind, v...)) +} + +// AdvanceFeaturesEQ applies the EQ predicate on the "advance_features" field. +func AdvanceFeaturesEQ(v pq.StringArray) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldEQ(FieldAdvanceFeatures, v)) +} + +// AdvanceFeaturesNEQ applies the NEQ predicate on the "advance_features" field. +func AdvanceFeaturesNEQ(v pq.StringArray) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldNEQ(FieldAdvanceFeatures, v)) +} + +// AdvanceFeaturesIn applies the In predicate on the "advance_features" field. +func AdvanceFeaturesIn(vs ...pq.StringArray) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldIn(FieldAdvanceFeatures, vs...)) +} + +// AdvanceFeaturesNotIn applies the NotIn predicate on the "advance_features" field. +func AdvanceFeaturesNotIn(vs ...pq.StringArray) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldNotIn(FieldAdvanceFeatures, vs...)) +} + +// AdvanceFeaturesGT applies the GT predicate on the "advance_features" field. +func AdvanceFeaturesGT(v pq.StringArray) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldGT(FieldAdvanceFeatures, v)) +} + +// AdvanceFeaturesGTE applies the GTE predicate on the "advance_features" field. +func AdvanceFeaturesGTE(v pq.StringArray) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldGTE(FieldAdvanceFeatures, v)) +} + +// AdvanceFeaturesLT applies the LT predicate on the "advance_features" field. +func AdvanceFeaturesLT(v pq.StringArray) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldLT(FieldAdvanceFeatures, v)) +} + +// AdvanceFeaturesLTE applies the LTE predicate on the "advance_features" field. +func AdvanceFeaturesLTE(v pq.StringArray) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldLTE(FieldAdvanceFeatures, v)) +} + +// AdvanceFeaturesIsNil applies the IsNil predicate on the "advance_features" field. +func AdvanceFeaturesIsNil() predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldIsNull(FieldAdvanceFeatures)) +} + +// AdvanceFeaturesNotNil applies the NotNil predicate on the "advance_features" field. +func AdvanceFeaturesNotNil() predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldNotNull(FieldAdvanceFeatures)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.FieldLTE(FieldCreatedAt, v)) +} + +// HasCharge applies the HasEdge predicate on the "charge" edge. +func HasCharge() predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, 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.CreditRealizationLineage { + return predicate.CreditRealizationLineage(func(s *sql.Selector) { + step := newChargeStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSegments applies the HasEdge predicate on the "segments" edge. +func HasSegments() predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SegmentsTable, SegmentsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSegmentsWith applies the HasEdge predicate on the "segments" edge with a given conditions (other predicates). +func HasSegmentsWith(preds ...predicate.CreditRealizationLineageSegment) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(func(s *sql.Selector) { + step := newSegmentsStep() + 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.CreditRealizationLineage) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.CreditRealizationLineage) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.CreditRealizationLineage) predicate.CreditRealizationLineage { + return predicate.CreditRealizationLineage(sql.NotPredicates(p)) +} diff --git a/ent/db/creditrealizationlineage_create.go b/ent/db/creditrealizationlineage_create.go new file mode 100644 index 0000000000000000000000000000000000000000..43cf73e758b55305ff65f0be00f3e45ca5caa42a --- /dev/null +++ b/ent/db/creditrealizationlineage_create.go @@ -0,0 +1,703 @@ +// 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/lib/pq" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/creditrealization" + "github.com/openmeterio/openmeter/openmeter/ent/db/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/creditrealizationlineage" + "github.com/openmeterio/openmeter/openmeter/ent/db/creditrealizationlineagesegment" + "github.com/openmeterio/openmeter/pkg/currencyx" +) + +// CreditRealizationLineageCreate is the builder for creating a CreditRealizationLineage entity. +type CreditRealizationLineageCreate struct { + config + mutation *CreditRealizationLineageMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *CreditRealizationLineageCreate) SetNamespace(v string) *CreditRealizationLineageCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetChargeID sets the "charge_id" field. +func (_c *CreditRealizationLineageCreate) SetChargeID(v string) *CreditRealizationLineageCreate { + _c.mutation.SetChargeID(v) + return _c +} + +// SetRootRealizationID sets the "root_realization_id" field. +func (_c *CreditRealizationLineageCreate) SetRootRealizationID(v string) *CreditRealizationLineageCreate { + _c.mutation.SetRootRealizationID(v) + return _c +} + +// SetCustomerID sets the "customer_id" field. +func (_c *CreditRealizationLineageCreate) SetCustomerID(v string) *CreditRealizationLineageCreate { + _c.mutation.SetCustomerID(v) + return _c +} + +// SetCurrency sets the "currency" field. +func (_c *CreditRealizationLineageCreate) SetCurrency(v currencyx.Code) *CreditRealizationLineageCreate { + _c.mutation.SetCurrency(v) + return _c +} + +// SetOriginKind sets the "origin_kind" field. +func (_c *CreditRealizationLineageCreate) SetOriginKind(v creditrealization.LineageOriginKind) *CreditRealizationLineageCreate { + _c.mutation.SetOriginKind(v) + return _c +} + +// SetAdvanceFeatures sets the "advance_features" field. +func (_c *CreditRealizationLineageCreate) SetAdvanceFeatures(v pq.StringArray) *CreditRealizationLineageCreate { + _c.mutation.SetAdvanceFeatures(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *CreditRealizationLineageCreate) SetCreatedAt(v time.Time) *CreditRealizationLineageCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *CreditRealizationLineageCreate) SetNillableCreatedAt(v *time.Time) *CreditRealizationLineageCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *CreditRealizationLineageCreate) SetID(v string) *CreditRealizationLineageCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *CreditRealizationLineageCreate) SetNillableID(v *string) *CreditRealizationLineageCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetCharge sets the "charge" edge to the Charge entity. +func (_c *CreditRealizationLineageCreate) SetCharge(v *Charge) *CreditRealizationLineageCreate { + return _c.SetChargeID(v.ID) +} + +// AddSegmentIDs adds the "segments" edge to the CreditRealizationLineageSegment entity by IDs. +func (_c *CreditRealizationLineageCreate) AddSegmentIDs(ids ...string) *CreditRealizationLineageCreate { + _c.mutation.AddSegmentIDs(ids...) + return _c +} + +// AddSegments adds the "segments" edges to the CreditRealizationLineageSegment entity. +func (_c *CreditRealizationLineageCreate) AddSegments(v ...*CreditRealizationLineageSegment) *CreditRealizationLineageCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddSegmentIDs(ids...) +} + +// Mutation returns the CreditRealizationLineageMutation object of the builder. +func (_c *CreditRealizationLineageCreate) Mutation() *CreditRealizationLineageMutation { + return _c.mutation +} + +// Save creates the CreditRealizationLineage in the database. +func (_c *CreditRealizationLineageCreate) Save(ctx context.Context) (*CreditRealizationLineage, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *CreditRealizationLineageCreate) SaveX(ctx context.Context) *CreditRealizationLineage { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *CreditRealizationLineageCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *CreditRealizationLineageCreate) 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 *CreditRealizationLineageCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := creditrealizationlineage.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := creditrealizationlineage.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *CreditRealizationLineageCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "CreditRealizationLineage.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := creditrealizationlineage.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "CreditRealizationLineage.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.ChargeID(); !ok { + return &ValidationError{Name: "charge_id", err: errors.New(`db: missing required field "CreditRealizationLineage.charge_id"`)} + } + if v, ok := _c.mutation.ChargeID(); ok { + if err := creditrealizationlineage.ChargeIDValidator(v); err != nil { + return &ValidationError{Name: "charge_id", err: fmt.Errorf(`db: validator failed for field "CreditRealizationLineage.charge_id": %w`, err)} + } + } + if _, ok := _c.mutation.RootRealizationID(); !ok { + return &ValidationError{Name: "root_realization_id", err: errors.New(`db: missing required field "CreditRealizationLineage.root_realization_id"`)} + } + if v, ok := _c.mutation.RootRealizationID(); ok { + if err := creditrealizationlineage.RootRealizationIDValidator(v); err != nil { + return &ValidationError{Name: "root_realization_id", err: fmt.Errorf(`db: validator failed for field "CreditRealizationLineage.root_realization_id": %w`, err)} + } + } + if _, ok := _c.mutation.CustomerID(); !ok { + return &ValidationError{Name: "customer_id", err: errors.New(`db: missing required field "CreditRealizationLineage.customer_id"`)} + } + if v, ok := _c.mutation.CustomerID(); ok { + if err := creditrealizationlineage.CustomerIDValidator(v); err != nil { + return &ValidationError{Name: "customer_id", err: fmt.Errorf(`db: validator failed for field "CreditRealizationLineage.customer_id": %w`, err)} + } + } + if _, ok := _c.mutation.Currency(); !ok { + return &ValidationError{Name: "currency", err: errors.New(`db: missing required field "CreditRealizationLineage.currency"`)} + } + if v, ok := _c.mutation.Currency(); ok { + if err := creditrealizationlineage.CurrencyValidator(string(v)); err != nil { + return &ValidationError{Name: "currency", err: fmt.Errorf(`db: validator failed for field "CreditRealizationLineage.currency": %w`, err)} + } + } + if _, ok := _c.mutation.OriginKind(); !ok { + return &ValidationError{Name: "origin_kind", err: errors.New(`db: missing required field "CreditRealizationLineage.origin_kind"`)} + } + if v, ok := _c.mutation.OriginKind(); ok { + if err := creditrealizationlineage.OriginKindValidator(v); err != nil { + return &ValidationError{Name: "origin_kind", err: fmt.Errorf(`db: validator failed for field "CreditRealizationLineage.origin_kind": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "CreditRealizationLineage.created_at"`)} + } + if len(_c.mutation.ChargeIDs()) == 0 { + return &ValidationError{Name: "charge", err: errors.New(`db: missing required edge "CreditRealizationLineage.charge"`)} + } + return nil +} + +func (_c *CreditRealizationLineageCreate) sqlSave(ctx context.Context) (*CreditRealizationLineage, 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 CreditRealizationLineage.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *CreditRealizationLineageCreate) createSpec() (*CreditRealizationLineage, *sqlgraph.CreateSpec) { + var ( + _node = &CreditRealizationLineage{config: _c.config} + _spec = sqlgraph.NewCreateSpec(creditrealizationlineage.Table, sqlgraph.NewFieldSpec(creditrealizationlineage.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(creditrealizationlineage.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.RootRealizationID(); ok { + _spec.SetField(creditrealizationlineage.FieldRootRealizationID, field.TypeString, value) + _node.RootRealizationID = value + } + if value, ok := _c.mutation.CustomerID(); ok { + _spec.SetField(creditrealizationlineage.FieldCustomerID, field.TypeString, value) + _node.CustomerID = value + } + if value, ok := _c.mutation.Currency(); ok { + _spec.SetField(creditrealizationlineage.FieldCurrency, field.TypeString, value) + _node.Currency = value + } + if value, ok := _c.mutation.OriginKind(); ok { + _spec.SetField(creditrealizationlineage.FieldOriginKind, field.TypeEnum, value) + _node.OriginKind = value + } + if value, ok := _c.mutation.AdvanceFeatures(); ok { + _spec.SetField(creditrealizationlineage.FieldAdvanceFeatures, field.TypeOther, value) + _node.AdvanceFeatures = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(creditrealizationlineage.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if nodes := _c.mutation.ChargeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: creditrealizationlineage.ChargeTable, + Columns: []string{creditrealizationlineage.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.ChargeID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.SegmentsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: creditrealizationlineage.SegmentsTable, + Columns: []string{creditrealizationlineage.SegmentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(creditrealizationlineagesegment.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.CreditRealizationLineage.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.CreditRealizationLineageUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *CreditRealizationLineageCreate) OnConflict(opts ...sql.ConflictOption) *CreditRealizationLineageUpsertOne { + _c.conflict = opts + return &CreditRealizationLineageUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.CreditRealizationLineage.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *CreditRealizationLineageCreate) OnConflictColumns(columns ...string) *CreditRealizationLineageUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &CreditRealizationLineageUpsertOne{ + create: _c, + } +} + +type ( + // CreditRealizationLineageUpsertOne is the builder for "upsert"-ing + // one CreditRealizationLineage node. + CreditRealizationLineageUpsertOne struct { + create *CreditRealizationLineageCreate + } + + // CreditRealizationLineageUpsert is the "OnConflict" setter. + CreditRealizationLineageUpsert struct { + *sql.UpdateSet + } +) + +// 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.CreditRealizationLineage.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(creditrealizationlineage.FieldID) +// }), +// ). +// Exec(ctx) +func (u *CreditRealizationLineageUpsertOne) UpdateNewValues() *CreditRealizationLineageUpsertOne { + 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(creditrealizationlineage.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(creditrealizationlineage.FieldNamespace) + } + if _, exists := u.create.mutation.ChargeID(); exists { + s.SetIgnore(creditrealizationlineage.FieldChargeID) + } + if _, exists := u.create.mutation.RootRealizationID(); exists { + s.SetIgnore(creditrealizationlineage.FieldRootRealizationID) + } + if _, exists := u.create.mutation.CustomerID(); exists { + s.SetIgnore(creditrealizationlineage.FieldCustomerID) + } + if _, exists := u.create.mutation.Currency(); exists { + s.SetIgnore(creditrealizationlineage.FieldCurrency) + } + if _, exists := u.create.mutation.OriginKind(); exists { + s.SetIgnore(creditrealizationlineage.FieldOriginKind) + } + if _, exists := u.create.mutation.AdvanceFeatures(); exists { + s.SetIgnore(creditrealizationlineage.FieldAdvanceFeatures) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(creditrealizationlineage.FieldCreatedAt) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.CreditRealizationLineage.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *CreditRealizationLineageUpsertOne) Ignore() *CreditRealizationLineageUpsertOne { + 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 *CreditRealizationLineageUpsertOne) DoNothing() *CreditRealizationLineageUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the CreditRealizationLineageCreate.OnConflict +// documentation for more info. +func (u *CreditRealizationLineageUpsertOne) Update(set func(*CreditRealizationLineageUpsert)) *CreditRealizationLineageUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&CreditRealizationLineageUpsert{UpdateSet: update}) + })) + return u +} + +// Exec executes the query. +func (u *CreditRealizationLineageUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for CreditRealizationLineageCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *CreditRealizationLineageUpsertOne) 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 *CreditRealizationLineageUpsertOne) 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: CreditRealizationLineageUpsertOne.ID is not supported by MySQL driver. Use CreditRealizationLineageUpsertOne.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 *CreditRealizationLineageUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// CreditRealizationLineageCreateBulk is the builder for creating many CreditRealizationLineage entities in bulk. +type CreditRealizationLineageCreateBulk struct { + config + err error + builders []*CreditRealizationLineageCreate + conflict []sql.ConflictOption +} + +// Save creates the CreditRealizationLineage entities in the database. +func (_c *CreditRealizationLineageCreateBulk) Save(ctx context.Context) ([]*CreditRealizationLineage, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*CreditRealizationLineage, 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.(*CreditRealizationLineageMutation) + 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 *CreditRealizationLineageCreateBulk) SaveX(ctx context.Context) []*CreditRealizationLineage { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *CreditRealizationLineageCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *CreditRealizationLineageCreateBulk) 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.CreditRealizationLineage.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.CreditRealizationLineageUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *CreditRealizationLineageCreateBulk) OnConflict(opts ...sql.ConflictOption) *CreditRealizationLineageUpsertBulk { + _c.conflict = opts + return &CreditRealizationLineageUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.CreditRealizationLineage.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *CreditRealizationLineageCreateBulk) OnConflictColumns(columns ...string) *CreditRealizationLineageUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &CreditRealizationLineageUpsertBulk{ + create: _c, + } +} + +// CreditRealizationLineageUpsertBulk is the builder for "upsert"-ing +// a bulk of CreditRealizationLineage nodes. +type CreditRealizationLineageUpsertBulk struct { + create *CreditRealizationLineageCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.CreditRealizationLineage.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(creditrealizationlineage.FieldID) +// }), +// ). +// Exec(ctx) +func (u *CreditRealizationLineageUpsertBulk) UpdateNewValues() *CreditRealizationLineageUpsertBulk { + 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(creditrealizationlineage.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(creditrealizationlineage.FieldNamespace) + } + if _, exists := b.mutation.ChargeID(); exists { + s.SetIgnore(creditrealizationlineage.FieldChargeID) + } + if _, exists := b.mutation.RootRealizationID(); exists { + s.SetIgnore(creditrealizationlineage.FieldRootRealizationID) + } + if _, exists := b.mutation.CustomerID(); exists { + s.SetIgnore(creditrealizationlineage.FieldCustomerID) + } + if _, exists := b.mutation.Currency(); exists { + s.SetIgnore(creditrealizationlineage.FieldCurrency) + } + if _, exists := b.mutation.OriginKind(); exists { + s.SetIgnore(creditrealizationlineage.FieldOriginKind) + } + if _, exists := b.mutation.AdvanceFeatures(); exists { + s.SetIgnore(creditrealizationlineage.FieldAdvanceFeatures) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(creditrealizationlineage.FieldCreatedAt) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.CreditRealizationLineage.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *CreditRealizationLineageUpsertBulk) Ignore() *CreditRealizationLineageUpsertBulk { + 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 *CreditRealizationLineageUpsertBulk) DoNothing() *CreditRealizationLineageUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the CreditRealizationLineageCreateBulk.OnConflict +// documentation for more info. +func (u *CreditRealizationLineageUpsertBulk) Update(set func(*CreditRealizationLineageUpsert)) *CreditRealizationLineageUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&CreditRealizationLineageUpsert{UpdateSet: update}) + })) + return u +} + +// Exec executes the query. +func (u *CreditRealizationLineageUpsertBulk) 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 CreditRealizationLineageCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for CreditRealizationLineageCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *CreditRealizationLineageUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/creditrealizationlineage_delete.go b/ent/db/creditrealizationlineage_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..75de325fee5387a076fe09a128a9a11734d1c2fb --- /dev/null +++ b/ent/db/creditrealizationlineage_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/creditrealizationlineage" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// CreditRealizationLineageDelete is the builder for deleting a CreditRealizationLineage entity. +type CreditRealizationLineageDelete struct { + config + hooks []Hook + mutation *CreditRealizationLineageMutation +} + +// Where appends a list predicates to the CreditRealizationLineageDelete builder. +func (_d *CreditRealizationLineageDelete) Where(ps ...predicate.CreditRealizationLineage) *CreditRealizationLineageDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *CreditRealizationLineageDelete) 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 *CreditRealizationLineageDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *CreditRealizationLineageDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(creditrealizationlineage.Table, sqlgraph.NewFieldSpec(creditrealizationlineage.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 +} + +// CreditRealizationLineageDeleteOne is the builder for deleting a single CreditRealizationLineage entity. +type CreditRealizationLineageDeleteOne struct { + _d *CreditRealizationLineageDelete +} + +// Where appends a list predicates to the CreditRealizationLineageDelete builder. +func (_d *CreditRealizationLineageDeleteOne) Where(ps ...predicate.CreditRealizationLineage) *CreditRealizationLineageDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *CreditRealizationLineageDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{creditrealizationlineage.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *CreditRealizationLineageDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/creditrealizationlineage_query.go b/ent/db/creditrealizationlineage_query.go new file mode 100644 index 0000000000000000000000000000000000000000..42eb7270e91574fb9815b6565ce3055fa72fe156 --- /dev/null +++ b/ent/db/creditrealizationlineage_query.go @@ -0,0 +1,720 @@ +// 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/creditrealizationlineage" + "github.com/openmeterio/openmeter/openmeter/ent/db/creditrealizationlineagesegment" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// CreditRealizationLineageQuery is the builder for querying CreditRealizationLineage entities. +type CreditRealizationLineageQuery struct { + config + ctx *QueryContext + order []creditrealizationlineage.OrderOption + inters []Interceptor + predicates []predicate.CreditRealizationLineage + withCharge *ChargeQuery + withSegments *CreditRealizationLineageSegmentQuery + 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 CreditRealizationLineageQuery builder. +func (_q *CreditRealizationLineageQuery) Where(ps ...predicate.CreditRealizationLineage) *CreditRealizationLineageQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *CreditRealizationLineageQuery) Limit(limit int) *CreditRealizationLineageQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *CreditRealizationLineageQuery) Offset(offset int) *CreditRealizationLineageQuery { + _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 *CreditRealizationLineageQuery) Unique(unique bool) *CreditRealizationLineageQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *CreditRealizationLineageQuery) Order(o ...creditrealizationlineage.OrderOption) *CreditRealizationLineageQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryCharge chains the current query on the "charge" edge. +func (_q *CreditRealizationLineageQuery) 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(creditrealizationlineage.Table, creditrealizationlineage.FieldID, selector), + sqlgraph.To(charge.Table, charge.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, creditrealizationlineage.ChargeTable, creditrealizationlineage.ChargeColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySegments chains the current query on the "segments" edge. +func (_q *CreditRealizationLineageQuery) QuerySegments() *CreditRealizationLineageSegmentQuery { + query := (&CreditRealizationLineageSegmentClient{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(creditrealizationlineage.Table, creditrealizationlineage.FieldID, selector), + sqlgraph.To(creditrealizationlineagesegment.Table, creditrealizationlineagesegment.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, creditrealizationlineage.SegmentsTable, creditrealizationlineage.SegmentsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first CreditRealizationLineage entity from the query. +// Returns a *NotFoundError when no CreditRealizationLineage was found. +func (_q *CreditRealizationLineageQuery) First(ctx context.Context) (*CreditRealizationLineage, 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{creditrealizationlineage.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *CreditRealizationLineageQuery) FirstX(ctx context.Context) *CreditRealizationLineage { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first CreditRealizationLineage ID from the query. +// Returns a *NotFoundError when no CreditRealizationLineage ID was found. +func (_q *CreditRealizationLineageQuery) 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{creditrealizationlineage.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *CreditRealizationLineageQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single CreditRealizationLineage entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one CreditRealizationLineage entity is found. +// Returns a *NotFoundError when no CreditRealizationLineage entities are found. +func (_q *CreditRealizationLineageQuery) Only(ctx context.Context) (*CreditRealizationLineage, 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{creditrealizationlineage.Label} + default: + return nil, &NotSingularError{creditrealizationlineage.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *CreditRealizationLineageQuery) OnlyX(ctx context.Context) *CreditRealizationLineage { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only CreditRealizationLineage ID in the query. +// Returns a *NotSingularError when more than one CreditRealizationLineage ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *CreditRealizationLineageQuery) 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{creditrealizationlineage.Label} + default: + err = &NotSingularError{creditrealizationlineage.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *CreditRealizationLineageQuery) 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 CreditRealizationLineages. +func (_q *CreditRealizationLineageQuery) All(ctx context.Context) ([]*CreditRealizationLineage, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*CreditRealizationLineage, *CreditRealizationLineageQuery]() + return withInterceptors[[]*CreditRealizationLineage](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *CreditRealizationLineageQuery) AllX(ctx context.Context) []*CreditRealizationLineage { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of CreditRealizationLineage IDs. +func (_q *CreditRealizationLineageQuery) 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(creditrealizationlineage.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *CreditRealizationLineageQuery) 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 *CreditRealizationLineageQuery) 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[*CreditRealizationLineageQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *CreditRealizationLineageQuery) 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 *CreditRealizationLineageQuery) 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 *CreditRealizationLineageQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the CreditRealizationLineageQuery 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 *CreditRealizationLineageQuery) Clone() *CreditRealizationLineageQuery { + if _q == nil { + return nil + } + return &CreditRealizationLineageQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]creditrealizationlineage.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.CreditRealizationLineage{}, _q.predicates...), + withCharge: _q.withCharge.Clone(), + withSegments: _q.withSegments.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 *CreditRealizationLineageQuery) WithCharge(opts ...func(*ChargeQuery)) *CreditRealizationLineageQuery { + query := (&ChargeClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCharge = query + return _q +} + +// WithSegments tells the query-builder to eager-load the nodes that are connected to +// the "segments" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *CreditRealizationLineageQuery) WithSegments(opts ...func(*CreditRealizationLineageSegmentQuery)) *CreditRealizationLineageQuery { + query := (&CreditRealizationLineageSegmentClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSegments = 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.CreditRealizationLineage.Query(). +// GroupBy(creditrealizationlineage.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *CreditRealizationLineageQuery) GroupBy(field string, fields ...string) *CreditRealizationLineageGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &CreditRealizationLineageGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = creditrealizationlineage.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.CreditRealizationLineage.Query(). +// Select(creditrealizationlineage.FieldNamespace). +// Scan(ctx, &v) +func (_q *CreditRealizationLineageQuery) Select(fields ...string) *CreditRealizationLineageSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &CreditRealizationLineageSelect{CreditRealizationLineageQuery: _q} + sbuild.label = creditrealizationlineage.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a CreditRealizationLineageSelect configured with the given aggregations. +func (_q *CreditRealizationLineageQuery) Aggregate(fns ...AggregateFunc) *CreditRealizationLineageSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *CreditRealizationLineageQuery) 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 !creditrealizationlineage.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 *CreditRealizationLineageQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*CreditRealizationLineage, error) { + var ( + nodes = []*CreditRealizationLineage{} + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withCharge != nil, + _q.withSegments != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*CreditRealizationLineage).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &CreditRealizationLineage{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 *CreditRealizationLineage, e *Charge) { n.Edges.Charge = e }); err != nil { + return nil, err + } + } + if query := _q.withSegments; query != nil { + if err := _q.loadSegments(ctx, query, nodes, + func(n *CreditRealizationLineage) { n.Edges.Segments = []*CreditRealizationLineageSegment{} }, + func(n *CreditRealizationLineage, e *CreditRealizationLineageSegment) { + n.Edges.Segments = append(n.Edges.Segments, e) + }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *CreditRealizationLineageQuery) loadCharge(ctx context.Context, query *ChargeQuery, nodes []*CreditRealizationLineage, init func(*CreditRealizationLineage), assign func(*CreditRealizationLineage, *Charge)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*CreditRealizationLineage) + 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(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 "charge_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *CreditRealizationLineageQuery) loadSegments(ctx context.Context, query *CreditRealizationLineageSegmentQuery, nodes []*CreditRealizationLineage, init func(*CreditRealizationLineage), assign func(*CreditRealizationLineage, *CreditRealizationLineageSegment)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*CreditRealizationLineage) + 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(creditrealizationlineagesegment.FieldLineageID) + } + query.Where(predicate.CreditRealizationLineageSegment(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(creditrealizationlineage.SegmentsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.LineageID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "lineage_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *CreditRealizationLineageQuery) 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 *CreditRealizationLineageQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(creditrealizationlineage.Table, creditrealizationlineage.Columns, sqlgraph.NewFieldSpec(creditrealizationlineage.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, creditrealizationlineage.FieldID) + for i := range fields { + if fields[i] != creditrealizationlineage.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withCharge != nil { + _spec.Node.AddColumnOnce(creditrealizationlineage.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 *CreditRealizationLineageQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(creditrealizationlineage.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = creditrealizationlineage.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 *CreditRealizationLineageQuery) ForUpdate(opts ...sql.LockOption) *CreditRealizationLineageQuery { + 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 *CreditRealizationLineageQuery) ForShare(opts ...sql.LockOption) *CreditRealizationLineageQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// CreditRealizationLineageGroupBy is the group-by builder for CreditRealizationLineage entities. +type CreditRealizationLineageGroupBy struct { + selector + build *CreditRealizationLineageQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *CreditRealizationLineageGroupBy) Aggregate(fns ...AggregateFunc) *CreditRealizationLineageGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *CreditRealizationLineageGroupBy) 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[*CreditRealizationLineageQuery, *CreditRealizationLineageGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *CreditRealizationLineageGroupBy) sqlScan(ctx context.Context, root *CreditRealizationLineageQuery, 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) +} + +// CreditRealizationLineageSelect is the builder for selecting fields of CreditRealizationLineage entities. +type CreditRealizationLineageSelect struct { + *CreditRealizationLineageQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *CreditRealizationLineageSelect) Aggregate(fns ...AggregateFunc) *CreditRealizationLineageSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *CreditRealizationLineageSelect) 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[*CreditRealizationLineageQuery, *CreditRealizationLineageSelect](ctx, _s.CreditRealizationLineageQuery, _s, _s.inters, v) +} + +func (_s *CreditRealizationLineageSelect) sqlScan(ctx context.Context, root *CreditRealizationLineageQuery, 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/ent/db/creditrealizationlineage_update.go b/ent/db/creditrealizationlineage_update.go new file mode 100644 index 0000000000000000000000000000000000000000..8fc06ea6dfea37585dbc19de0b47b854863c12a0 --- /dev/null +++ b/ent/db/creditrealizationlineage_update.go @@ -0,0 +1,366 @@ +// 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/creditrealizationlineage" + "github.com/openmeterio/openmeter/openmeter/ent/db/creditrealizationlineagesegment" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// CreditRealizationLineageUpdate is the builder for updating CreditRealizationLineage entities. +type CreditRealizationLineageUpdate struct { + config + hooks []Hook + mutation *CreditRealizationLineageMutation +} + +// Where appends a list predicates to the CreditRealizationLineageUpdate builder. +func (_u *CreditRealizationLineageUpdate) Where(ps ...predicate.CreditRealizationLineage) *CreditRealizationLineageUpdate { + _u.mutation.Where(ps...) + return _u +} + +// AddSegmentIDs adds the "segments" edge to the CreditRealizationLineageSegment entity by IDs. +func (_u *CreditRealizationLineageUpdate) AddSegmentIDs(ids ...string) *CreditRealizationLineageUpdate { + _u.mutation.AddSegmentIDs(ids...) + return _u +} + +// AddSegments adds the "segments" edges to the CreditRealizationLineageSegment entity. +func (_u *CreditRealizationLineageUpdate) AddSegments(v ...*CreditRealizationLineageSegment) *CreditRealizationLineageUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSegmentIDs(ids...) +} + +// Mutation returns the CreditRealizationLineageMutation object of the builder. +func (_u *CreditRealizationLineageUpdate) Mutation() *CreditRealizationLineageMutation { + return _u.mutation +} + +// ClearSegments clears all "segments" edges to the CreditRealizationLineageSegment entity. +func (_u *CreditRealizationLineageUpdate) ClearSegments() *CreditRealizationLineageUpdate { + _u.mutation.ClearSegments() + return _u +} + +// RemoveSegmentIDs removes the "segments" edge to CreditRealizationLineageSegment entities by IDs. +func (_u *CreditRealizationLineageUpdate) RemoveSegmentIDs(ids ...string) *CreditRealizationLineageUpdate { + _u.mutation.RemoveSegmentIDs(ids...) + return _u +} + +// RemoveSegments removes "segments" edges to CreditRealizationLineageSegment entities. +func (_u *CreditRealizationLineageUpdate) RemoveSegments(v ...*CreditRealizationLineageSegment) *CreditRealizationLineageUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSegmentIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *CreditRealizationLineageUpdate) 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 *CreditRealizationLineageUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *CreditRealizationLineageUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *CreditRealizationLineageUpdate) 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 *CreditRealizationLineageUpdate) check() error { + if _u.mutation.ChargeCleared() && len(_u.mutation.ChargeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "CreditRealizationLineage.charge"`) + } + return nil +} + +func (_u *CreditRealizationLineageUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(creditrealizationlineage.Table, creditrealizationlineage.Columns, sqlgraph.NewFieldSpec(creditrealizationlineage.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 _u.mutation.AdvanceFeaturesCleared() { + _spec.ClearField(creditrealizationlineage.FieldAdvanceFeatures, field.TypeOther) + } + if _u.mutation.SegmentsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: creditrealizationlineage.SegmentsTable, + Columns: []string{creditrealizationlineage.SegmentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(creditrealizationlineagesegment.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSegmentsIDs(); len(nodes) > 0 && !_u.mutation.SegmentsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: creditrealizationlineage.SegmentsTable, + Columns: []string{creditrealizationlineage.SegmentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(creditrealizationlineagesegment.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.SegmentsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: creditrealizationlineage.SegmentsTable, + Columns: []string{creditrealizationlineage.SegmentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(creditrealizationlineagesegment.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{creditrealizationlineage.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// CreditRealizationLineageUpdateOne is the builder for updating a single CreditRealizationLineage entity. +type CreditRealizationLineageUpdateOne struct { + config + fields []string + hooks []Hook + mutation *CreditRealizationLineageMutation +} + +// AddSegmentIDs adds the "segments" edge to the CreditRealizationLineageSegment entity by IDs. +func (_u *CreditRealizationLineageUpdateOne) AddSegmentIDs(ids ...string) *CreditRealizationLineageUpdateOne { + _u.mutation.AddSegmentIDs(ids...) + return _u +} + +// AddSegments adds the "segments" edges to the CreditRealizationLineageSegment entity. +func (_u *CreditRealizationLineageUpdateOne) AddSegments(v ...*CreditRealizationLineageSegment) *CreditRealizationLineageUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSegmentIDs(ids...) +} + +// Mutation returns the CreditRealizationLineageMutation object of the builder. +func (_u *CreditRealizationLineageUpdateOne) Mutation() *CreditRealizationLineageMutation { + return _u.mutation +} + +// ClearSegments clears all "segments" edges to the CreditRealizationLineageSegment entity. +func (_u *CreditRealizationLineageUpdateOne) ClearSegments() *CreditRealizationLineageUpdateOne { + _u.mutation.ClearSegments() + return _u +} + +// RemoveSegmentIDs removes the "segments" edge to CreditRealizationLineageSegment entities by IDs. +func (_u *CreditRealizationLineageUpdateOne) RemoveSegmentIDs(ids ...string) *CreditRealizationLineageUpdateOne { + _u.mutation.RemoveSegmentIDs(ids...) + return _u +} + +// RemoveSegments removes "segments" edges to CreditRealizationLineageSegment entities. +func (_u *CreditRealizationLineageUpdateOne) RemoveSegments(v ...*CreditRealizationLineageSegment) *CreditRealizationLineageUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSegmentIDs(ids...) +} + +// Where appends a list predicates to the CreditRealizationLineageUpdate builder. +func (_u *CreditRealizationLineageUpdateOne) Where(ps ...predicate.CreditRealizationLineage) *CreditRealizationLineageUpdateOne { + _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 *CreditRealizationLineageUpdateOne) Select(field string, fields ...string) *CreditRealizationLineageUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated CreditRealizationLineage entity. +func (_u *CreditRealizationLineageUpdateOne) Save(ctx context.Context) (*CreditRealizationLineage, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *CreditRealizationLineageUpdateOne) SaveX(ctx context.Context) *CreditRealizationLineage { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *CreditRealizationLineageUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *CreditRealizationLineageUpdateOne) 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 *CreditRealizationLineageUpdateOne) check() error { + if _u.mutation.ChargeCleared() && len(_u.mutation.ChargeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "CreditRealizationLineage.charge"`) + } + return nil +} + +func (_u *CreditRealizationLineageUpdateOne) sqlSave(ctx context.Context) (_node *CreditRealizationLineage, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(creditrealizationlineage.Table, creditrealizationlineage.Columns, sqlgraph.NewFieldSpec(creditrealizationlineage.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "CreditRealizationLineage.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, creditrealizationlineage.FieldID) + for _, f := range fields { + if !creditrealizationlineage.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != creditrealizationlineage.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 _u.mutation.AdvanceFeaturesCleared() { + _spec.ClearField(creditrealizationlineage.FieldAdvanceFeatures, field.TypeOther) + } + if _u.mutation.SegmentsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: creditrealizationlineage.SegmentsTable, + Columns: []string{creditrealizationlineage.SegmentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(creditrealizationlineagesegment.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSegmentsIDs(); len(nodes) > 0 && !_u.mutation.SegmentsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: creditrealizationlineage.SegmentsTable, + Columns: []string{creditrealizationlineage.SegmentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(creditrealizationlineagesegment.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.SegmentsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: creditrealizationlineage.SegmentsTable, + Columns: []string{creditrealizationlineage.SegmentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(creditrealizationlineagesegment.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &CreditRealizationLineage{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{creditrealizationlineage.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/ent/db/creditrealizationlineagesegment.go b/ent/db/creditrealizationlineagesegment.go new file mode 100644 index 0000000000000000000000000000000000000000..3e398fd4d238be92f334c0f8b5f76c3bdfd101a3 --- /dev/null +++ b/ent/db/creditrealizationlineagesegment.go @@ -0,0 +1,226 @@ +// 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/models/creditrealization" + "github.com/openmeterio/openmeter/openmeter/ent/db/creditrealizationlineage" + "github.com/openmeterio/openmeter/openmeter/ent/db/creditrealizationlineagesegment" +) + +// CreditRealizationLineageSegment is the model entity for the CreditRealizationLineageSegment schema. +type CreditRealizationLineageSegment struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // LineageID holds the value of the "lineage_id" field. + LineageID string `json:"lineage_id,omitempty"` + // Amount holds the value of the "amount" field. + Amount alpacadecimal.Decimal `json:"amount,omitempty"` + // State holds the value of the "state" field. + State creditrealization.LineageSegmentState `json:"state,omitempty"` + // BackingTransactionGroupID holds the value of the "backing_transaction_group_id" field. + BackingTransactionGroupID *string `json:"backing_transaction_group_id,omitempty"` + // SourceState holds the value of the "source_state" field. + SourceState *creditrealization.LineageSegmentState `json:"source_state,omitempty"` + // SourceBackingTransactionGroupID holds the value of the "source_backing_transaction_group_id" field. + SourceBackingTransactionGroupID *string `json:"source_backing_transaction_group_id,omitempty"` + // ClosedAt holds the value of the "closed_at" field. + ClosedAt *time.Time `json:"closed_at,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the CreditRealizationLineageSegmentQuery when eager-loading is set. + Edges CreditRealizationLineageSegmentEdges `json:"edges"` + selectValues sql.SelectValues +} + +// CreditRealizationLineageSegmentEdges holds the relations/edges for other nodes in the graph. +type CreditRealizationLineageSegmentEdges struct { + // Lineage holds the value of the lineage edge. + Lineage *CreditRealizationLineage `json:"lineage,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// LineageOrErr returns the Lineage value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e CreditRealizationLineageSegmentEdges) LineageOrErr() (*CreditRealizationLineage, error) { + if e.Lineage != nil { + return e.Lineage, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: creditrealizationlineage.Label} + } + return nil, &NotLoadedError{edge: "lineage"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*CreditRealizationLineageSegment) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case creditrealizationlineagesegment.FieldAmount: + values[i] = new(alpacadecimal.Decimal) + case creditrealizationlineagesegment.FieldID, creditrealizationlineagesegment.FieldLineageID, creditrealizationlineagesegment.FieldState, creditrealizationlineagesegment.FieldBackingTransactionGroupID, creditrealizationlineagesegment.FieldSourceState, creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID: + values[i] = new(sql.NullString) + case creditrealizationlineagesegment.FieldClosedAt, creditrealizationlineagesegment.FieldCreatedAt: + 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 CreditRealizationLineageSegment fields. +func (_m *CreditRealizationLineageSegment) 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 creditrealizationlineagesegment.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 creditrealizationlineagesegment.FieldLineageID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field lineage_id", values[i]) + } else if value.Valid { + _m.LineageID = value.String + } + case creditrealizationlineagesegment.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 creditrealizationlineagesegment.FieldState: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field state", values[i]) + } else if value.Valid { + _m.State = creditrealization.LineageSegmentState(value.String) + } + case creditrealizationlineagesegment.FieldBackingTransactionGroupID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field backing_transaction_group_id", values[i]) + } else if value.Valid { + _m.BackingTransactionGroupID = new(string) + *_m.BackingTransactionGroupID = value.String + } + case creditrealizationlineagesegment.FieldSourceState: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field source_state", values[i]) + } else if value.Valid { + _m.SourceState = new(creditrealization.LineageSegmentState) + *_m.SourceState = creditrealization.LineageSegmentState(value.String) + } + case creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field source_backing_transaction_group_id", values[i]) + } else if value.Valid { + _m.SourceBackingTransactionGroupID = new(string) + *_m.SourceBackingTransactionGroupID = value.String + } + case creditrealizationlineagesegment.FieldClosedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field closed_at", values[i]) + } else if value.Valid { + _m.ClosedAt = new(time.Time) + *_m.ClosedAt = value.Time + } + case creditrealizationlineagesegment.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 + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the CreditRealizationLineageSegment. +// This includes values selected through modifiers, order, etc. +func (_m *CreditRealizationLineageSegment) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryLineage queries the "lineage" edge of the CreditRealizationLineageSegment entity. +func (_m *CreditRealizationLineageSegment) QueryLineage() *CreditRealizationLineageQuery { + return NewCreditRealizationLineageSegmentClient(_m.config).QueryLineage(_m) +} + +// Update returns a builder for updating this CreditRealizationLineageSegment. +// Note that you need to call CreditRealizationLineageSegment.Unwrap() before calling this method if this CreditRealizationLineageSegment +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *CreditRealizationLineageSegment) Update() *CreditRealizationLineageSegmentUpdateOne { + return NewCreditRealizationLineageSegmentClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the CreditRealizationLineageSegment 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 *CreditRealizationLineageSegment) Unwrap() *CreditRealizationLineageSegment { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: CreditRealizationLineageSegment is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *CreditRealizationLineageSegment) String() string { + var builder strings.Builder + builder.WriteString("CreditRealizationLineageSegment(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("lineage_id=") + builder.WriteString(_m.LineageID) + builder.WriteString(", ") + builder.WriteString("amount=") + builder.WriteString(fmt.Sprintf("%v", _m.Amount)) + builder.WriteString(", ") + builder.WriteString("state=") + builder.WriteString(fmt.Sprintf("%v", _m.State)) + builder.WriteString(", ") + if v := _m.BackingTransactionGroupID; v != nil { + builder.WriteString("backing_transaction_group_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SourceState; v != nil { + builder.WriteString("source_state=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.SourceBackingTransactionGroupID; v != nil { + builder.WriteString("source_backing_transaction_group_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.ClosedAt; v != nil { + builder.WriteString("closed_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// CreditRealizationLineageSegments is a parsable slice of CreditRealizationLineageSegment. +type CreditRealizationLineageSegments []*CreditRealizationLineageSegment diff --git a/ent/db/creditrealizationlineagesegment/creditrealizationlineagesegment.go b/ent/db/creditrealizationlineagesegment/creditrealizationlineagesegment.go new file mode 100644 index 0000000000000000000000000000000000000000..ce03df139c00de67bd37893a0118a023bf6bb246 --- /dev/null +++ b/ent/db/creditrealizationlineagesegment/creditrealizationlineagesegment.go @@ -0,0 +1,164 @@ +// Code generated by ent, DO NOT EDIT. + +package creditrealizationlineagesegment + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/creditrealization" +) + +const ( + // Label holds the string label denoting the creditrealizationlineagesegment type in the database. + Label = "credit_realization_lineage_segment" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldLineageID holds the string denoting the lineage_id field in the database. + FieldLineageID = "lineage_id" + // FieldAmount holds the string denoting the amount field in the database. + FieldAmount = "amount" + // FieldState holds the string denoting the state field in the database. + FieldState = "state" + // FieldBackingTransactionGroupID holds the string denoting the backing_transaction_group_id field in the database. + FieldBackingTransactionGroupID = "backing_transaction_group_id" + // FieldSourceState holds the string denoting the source_state field in the database. + FieldSourceState = "source_state" + // FieldSourceBackingTransactionGroupID holds the string denoting the source_backing_transaction_group_id field in the database. + FieldSourceBackingTransactionGroupID = "source_backing_transaction_group_id" + // FieldClosedAt holds the string denoting the closed_at field in the database. + FieldClosedAt = "closed_at" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // EdgeLineage holds the string denoting the lineage edge name in mutations. + EdgeLineage = "lineage" + // Table holds the table name of the creditrealizationlineagesegment in the database. + Table = "credit_realization_lineage_segments" + // LineageTable is the table that holds the lineage relation/edge. + LineageTable = "credit_realization_lineage_segments" + // LineageInverseTable is the table name for the CreditRealizationLineage entity. + // It exists in this package in order to avoid circular dependency with the "creditrealizationlineage" package. + LineageInverseTable = "credit_realization_lineages" + // LineageColumn is the table column denoting the lineage relation/edge. + LineageColumn = "lineage_id" +) + +// Columns holds all SQL columns for creditrealizationlineagesegment fields. +var Columns = []string{ + FieldID, + FieldLineageID, + FieldAmount, + FieldState, + FieldBackingTransactionGroupID, + FieldSourceState, + FieldSourceBackingTransactionGroupID, + FieldClosedAt, + FieldCreatedAt, +} + +// 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 ( + // LineageIDValidator is a validator for the "lineage_id" field. It is called by the builders before save. + LineageIDValidator func(string) error + // BackingTransactionGroupIDValidator is a validator for the "backing_transaction_group_id" field. It is called by the builders before save. + BackingTransactionGroupIDValidator func(string) error + // SourceBackingTransactionGroupIDValidator is a validator for the "source_backing_transaction_group_id" field. It is called by the builders before save. + SourceBackingTransactionGroupIDValidator func(string) error + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// StateValidator is a validator for the "state" field enum values. It is called by the builders before save. +func StateValidator(s creditrealization.LineageSegmentState) error { + switch s { + case "real_credit", "advance_uncovered", "advance_backfilled", "earnings_recognized": + return nil + default: + return fmt.Errorf("creditrealizationlineagesegment: invalid enum value for state field: %q", s) + } +} + +// SourceStateValidator is a validator for the "source_state" field enum values. It is called by the builders before save. +func SourceStateValidator(ss creditrealization.LineageSegmentState) error { + switch ss { + case "real_credit", "advance_uncovered", "advance_backfilled", "earnings_recognized": + return nil + default: + return fmt.Errorf("creditrealizationlineagesegment: invalid enum value for source_state field: %q", ss) + } +} + +// OrderOption defines the ordering options for the CreditRealizationLineageSegment 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() +} + +// ByLineageID orders the results by the lineage_id field. +func ByLineageID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLineageID, opts...).ToFunc() +} + +// ByAmount orders the results by the amount field. +func ByAmount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAmount, opts...).ToFunc() +} + +// ByState orders the results by the state field. +func ByState(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldState, opts...).ToFunc() +} + +// ByBackingTransactionGroupID orders the results by the backing_transaction_group_id field. +func ByBackingTransactionGroupID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBackingTransactionGroupID, opts...).ToFunc() +} + +// BySourceState orders the results by the source_state field. +func BySourceState(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSourceState, opts...).ToFunc() +} + +// BySourceBackingTransactionGroupID orders the results by the source_backing_transaction_group_id field. +func BySourceBackingTransactionGroupID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSourceBackingTransactionGroupID, opts...).ToFunc() +} + +// ByClosedAt orders the results by the closed_at field. +func ByClosedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldClosedAt, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByLineageField orders the results by lineage field. +func ByLineageField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newLineageStep(), sql.OrderByField(field, opts...)) + } +} +func newLineageStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LineageInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, LineageTable, LineageColumn), + ) +} diff --git a/ent/db/creditrealizationlineagesegment/where.go b/ent/db/creditrealizationlineagesegment/where.go new file mode 100644 index 0000000000000000000000000000000000000000..c7fc48fe5adffe2b9b77761b746865d26087577f --- /dev/null +++ b/ent/db/creditrealizationlineagesegment/where.go @@ -0,0 +1,551 @@ +// Code generated by ent, DO NOT EDIT. + +package creditrealizationlineagesegment + +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/creditrealization" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldContainsFold(FieldID, id)) +} + +// LineageID applies equality check predicate on the "lineage_id" field. It's identical to LineageIDEQ. +func LineageID(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldEQ(FieldLineageID, v)) +} + +// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ. +func Amount(v alpacadecimal.Decimal) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldEQ(FieldAmount, v)) +} + +// BackingTransactionGroupID applies equality check predicate on the "backing_transaction_group_id" field. It's identical to BackingTransactionGroupIDEQ. +func BackingTransactionGroupID(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldEQ(FieldBackingTransactionGroupID, v)) +} + +// SourceBackingTransactionGroupID applies equality check predicate on the "source_backing_transaction_group_id" field. It's identical to SourceBackingTransactionGroupIDEQ. +func SourceBackingTransactionGroupID(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldEQ(FieldSourceBackingTransactionGroupID, v)) +} + +// ClosedAt applies equality check predicate on the "closed_at" field. It's identical to ClosedAtEQ. +func ClosedAt(v time.Time) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldEQ(FieldClosedAt, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldEQ(FieldCreatedAt, v)) +} + +// LineageIDEQ applies the EQ predicate on the "lineage_id" field. +func LineageIDEQ(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldEQ(FieldLineageID, v)) +} + +// LineageIDNEQ applies the NEQ predicate on the "lineage_id" field. +func LineageIDNEQ(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldNEQ(FieldLineageID, v)) +} + +// LineageIDIn applies the In predicate on the "lineage_id" field. +func LineageIDIn(vs ...string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldIn(FieldLineageID, vs...)) +} + +// LineageIDNotIn applies the NotIn predicate on the "lineage_id" field. +func LineageIDNotIn(vs ...string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldNotIn(FieldLineageID, vs...)) +} + +// LineageIDGT applies the GT predicate on the "lineage_id" field. +func LineageIDGT(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldGT(FieldLineageID, v)) +} + +// LineageIDGTE applies the GTE predicate on the "lineage_id" field. +func LineageIDGTE(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldGTE(FieldLineageID, v)) +} + +// LineageIDLT applies the LT predicate on the "lineage_id" field. +func LineageIDLT(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldLT(FieldLineageID, v)) +} + +// LineageIDLTE applies the LTE predicate on the "lineage_id" field. +func LineageIDLTE(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldLTE(FieldLineageID, v)) +} + +// LineageIDContains applies the Contains predicate on the "lineage_id" field. +func LineageIDContains(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldContains(FieldLineageID, v)) +} + +// LineageIDHasPrefix applies the HasPrefix predicate on the "lineage_id" field. +func LineageIDHasPrefix(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldHasPrefix(FieldLineageID, v)) +} + +// LineageIDHasSuffix applies the HasSuffix predicate on the "lineage_id" field. +func LineageIDHasSuffix(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldHasSuffix(FieldLineageID, v)) +} + +// LineageIDEqualFold applies the EqualFold predicate on the "lineage_id" field. +func LineageIDEqualFold(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldEqualFold(FieldLineageID, v)) +} + +// LineageIDContainsFold applies the ContainsFold predicate on the "lineage_id" field. +func LineageIDContainsFold(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldContainsFold(FieldLineageID, v)) +} + +// AmountEQ applies the EQ predicate on the "amount" field. +func AmountEQ(v alpacadecimal.Decimal) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldEQ(FieldAmount, v)) +} + +// AmountNEQ applies the NEQ predicate on the "amount" field. +func AmountNEQ(v alpacadecimal.Decimal) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldNEQ(FieldAmount, v)) +} + +// AmountIn applies the In predicate on the "amount" field. +func AmountIn(vs ...alpacadecimal.Decimal) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldIn(FieldAmount, vs...)) +} + +// AmountNotIn applies the NotIn predicate on the "amount" field. +func AmountNotIn(vs ...alpacadecimal.Decimal) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldNotIn(FieldAmount, vs...)) +} + +// AmountGT applies the GT predicate on the "amount" field. +func AmountGT(v alpacadecimal.Decimal) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldGT(FieldAmount, v)) +} + +// AmountGTE applies the GTE predicate on the "amount" field. +func AmountGTE(v alpacadecimal.Decimal) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldGTE(FieldAmount, v)) +} + +// AmountLT applies the LT predicate on the "amount" field. +func AmountLT(v alpacadecimal.Decimal) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldLT(FieldAmount, v)) +} + +// AmountLTE applies the LTE predicate on the "amount" field. +func AmountLTE(v alpacadecimal.Decimal) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldLTE(FieldAmount, v)) +} + +// StateEQ applies the EQ predicate on the "state" field. +func StateEQ(v creditrealization.LineageSegmentState) predicate.CreditRealizationLineageSegment { + vc := v + return predicate.CreditRealizationLineageSegment(sql.FieldEQ(FieldState, vc)) +} + +// StateNEQ applies the NEQ predicate on the "state" field. +func StateNEQ(v creditrealization.LineageSegmentState) predicate.CreditRealizationLineageSegment { + vc := v + return predicate.CreditRealizationLineageSegment(sql.FieldNEQ(FieldState, vc)) +} + +// StateIn applies the In predicate on the "state" field. +func StateIn(vs ...creditrealization.LineageSegmentState) predicate.CreditRealizationLineageSegment { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.CreditRealizationLineageSegment(sql.FieldIn(FieldState, v...)) +} + +// StateNotIn applies the NotIn predicate on the "state" field. +func StateNotIn(vs ...creditrealization.LineageSegmentState) predicate.CreditRealizationLineageSegment { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.CreditRealizationLineageSegment(sql.FieldNotIn(FieldState, v...)) +} + +// BackingTransactionGroupIDEQ applies the EQ predicate on the "backing_transaction_group_id" field. +func BackingTransactionGroupIDEQ(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldEQ(FieldBackingTransactionGroupID, v)) +} + +// BackingTransactionGroupIDNEQ applies the NEQ predicate on the "backing_transaction_group_id" field. +func BackingTransactionGroupIDNEQ(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldNEQ(FieldBackingTransactionGroupID, v)) +} + +// BackingTransactionGroupIDIn applies the In predicate on the "backing_transaction_group_id" field. +func BackingTransactionGroupIDIn(vs ...string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldIn(FieldBackingTransactionGroupID, vs...)) +} + +// BackingTransactionGroupIDNotIn applies the NotIn predicate on the "backing_transaction_group_id" field. +func BackingTransactionGroupIDNotIn(vs ...string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldNotIn(FieldBackingTransactionGroupID, vs...)) +} + +// BackingTransactionGroupIDGT applies the GT predicate on the "backing_transaction_group_id" field. +func BackingTransactionGroupIDGT(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldGT(FieldBackingTransactionGroupID, v)) +} + +// BackingTransactionGroupIDGTE applies the GTE predicate on the "backing_transaction_group_id" field. +func BackingTransactionGroupIDGTE(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldGTE(FieldBackingTransactionGroupID, v)) +} + +// BackingTransactionGroupIDLT applies the LT predicate on the "backing_transaction_group_id" field. +func BackingTransactionGroupIDLT(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldLT(FieldBackingTransactionGroupID, v)) +} + +// BackingTransactionGroupIDLTE applies the LTE predicate on the "backing_transaction_group_id" field. +func BackingTransactionGroupIDLTE(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldLTE(FieldBackingTransactionGroupID, v)) +} + +// BackingTransactionGroupIDContains applies the Contains predicate on the "backing_transaction_group_id" field. +func BackingTransactionGroupIDContains(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldContains(FieldBackingTransactionGroupID, v)) +} + +// BackingTransactionGroupIDHasPrefix applies the HasPrefix predicate on the "backing_transaction_group_id" field. +func BackingTransactionGroupIDHasPrefix(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldHasPrefix(FieldBackingTransactionGroupID, v)) +} + +// BackingTransactionGroupIDHasSuffix applies the HasSuffix predicate on the "backing_transaction_group_id" field. +func BackingTransactionGroupIDHasSuffix(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldHasSuffix(FieldBackingTransactionGroupID, v)) +} + +// BackingTransactionGroupIDIsNil applies the IsNil predicate on the "backing_transaction_group_id" field. +func BackingTransactionGroupIDIsNil() predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldIsNull(FieldBackingTransactionGroupID)) +} + +// BackingTransactionGroupIDNotNil applies the NotNil predicate on the "backing_transaction_group_id" field. +func BackingTransactionGroupIDNotNil() predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldNotNull(FieldBackingTransactionGroupID)) +} + +// BackingTransactionGroupIDEqualFold applies the EqualFold predicate on the "backing_transaction_group_id" field. +func BackingTransactionGroupIDEqualFold(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldEqualFold(FieldBackingTransactionGroupID, v)) +} + +// BackingTransactionGroupIDContainsFold applies the ContainsFold predicate on the "backing_transaction_group_id" field. +func BackingTransactionGroupIDContainsFold(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldContainsFold(FieldBackingTransactionGroupID, v)) +} + +// SourceStateEQ applies the EQ predicate on the "source_state" field. +func SourceStateEQ(v creditrealization.LineageSegmentState) predicate.CreditRealizationLineageSegment { + vc := v + return predicate.CreditRealizationLineageSegment(sql.FieldEQ(FieldSourceState, vc)) +} + +// SourceStateNEQ applies the NEQ predicate on the "source_state" field. +func SourceStateNEQ(v creditrealization.LineageSegmentState) predicate.CreditRealizationLineageSegment { + vc := v + return predicate.CreditRealizationLineageSegment(sql.FieldNEQ(FieldSourceState, vc)) +} + +// SourceStateIn applies the In predicate on the "source_state" field. +func SourceStateIn(vs ...creditrealization.LineageSegmentState) predicate.CreditRealizationLineageSegment { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.CreditRealizationLineageSegment(sql.FieldIn(FieldSourceState, v...)) +} + +// SourceStateNotIn applies the NotIn predicate on the "source_state" field. +func SourceStateNotIn(vs ...creditrealization.LineageSegmentState) predicate.CreditRealizationLineageSegment { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.CreditRealizationLineageSegment(sql.FieldNotIn(FieldSourceState, v...)) +} + +// SourceStateIsNil applies the IsNil predicate on the "source_state" field. +func SourceStateIsNil() predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldIsNull(FieldSourceState)) +} + +// SourceStateNotNil applies the NotNil predicate on the "source_state" field. +func SourceStateNotNil() predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldNotNull(FieldSourceState)) +} + +// SourceBackingTransactionGroupIDEQ applies the EQ predicate on the "source_backing_transaction_group_id" field. +func SourceBackingTransactionGroupIDEQ(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldEQ(FieldSourceBackingTransactionGroupID, v)) +} + +// SourceBackingTransactionGroupIDNEQ applies the NEQ predicate on the "source_backing_transaction_group_id" field. +func SourceBackingTransactionGroupIDNEQ(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldNEQ(FieldSourceBackingTransactionGroupID, v)) +} + +// SourceBackingTransactionGroupIDIn applies the In predicate on the "source_backing_transaction_group_id" field. +func SourceBackingTransactionGroupIDIn(vs ...string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldIn(FieldSourceBackingTransactionGroupID, vs...)) +} + +// SourceBackingTransactionGroupIDNotIn applies the NotIn predicate on the "source_backing_transaction_group_id" field. +func SourceBackingTransactionGroupIDNotIn(vs ...string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldNotIn(FieldSourceBackingTransactionGroupID, vs...)) +} + +// SourceBackingTransactionGroupIDGT applies the GT predicate on the "source_backing_transaction_group_id" field. +func SourceBackingTransactionGroupIDGT(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldGT(FieldSourceBackingTransactionGroupID, v)) +} + +// SourceBackingTransactionGroupIDGTE applies the GTE predicate on the "source_backing_transaction_group_id" field. +func SourceBackingTransactionGroupIDGTE(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldGTE(FieldSourceBackingTransactionGroupID, v)) +} + +// SourceBackingTransactionGroupIDLT applies the LT predicate on the "source_backing_transaction_group_id" field. +func SourceBackingTransactionGroupIDLT(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldLT(FieldSourceBackingTransactionGroupID, v)) +} + +// SourceBackingTransactionGroupIDLTE applies the LTE predicate on the "source_backing_transaction_group_id" field. +func SourceBackingTransactionGroupIDLTE(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldLTE(FieldSourceBackingTransactionGroupID, v)) +} + +// SourceBackingTransactionGroupIDContains applies the Contains predicate on the "source_backing_transaction_group_id" field. +func SourceBackingTransactionGroupIDContains(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldContains(FieldSourceBackingTransactionGroupID, v)) +} + +// SourceBackingTransactionGroupIDHasPrefix applies the HasPrefix predicate on the "source_backing_transaction_group_id" field. +func SourceBackingTransactionGroupIDHasPrefix(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldHasPrefix(FieldSourceBackingTransactionGroupID, v)) +} + +// SourceBackingTransactionGroupIDHasSuffix applies the HasSuffix predicate on the "source_backing_transaction_group_id" field. +func SourceBackingTransactionGroupIDHasSuffix(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldHasSuffix(FieldSourceBackingTransactionGroupID, v)) +} + +// SourceBackingTransactionGroupIDIsNil applies the IsNil predicate on the "source_backing_transaction_group_id" field. +func SourceBackingTransactionGroupIDIsNil() predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldIsNull(FieldSourceBackingTransactionGroupID)) +} + +// SourceBackingTransactionGroupIDNotNil applies the NotNil predicate on the "source_backing_transaction_group_id" field. +func SourceBackingTransactionGroupIDNotNil() predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldNotNull(FieldSourceBackingTransactionGroupID)) +} + +// SourceBackingTransactionGroupIDEqualFold applies the EqualFold predicate on the "source_backing_transaction_group_id" field. +func SourceBackingTransactionGroupIDEqualFold(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldEqualFold(FieldSourceBackingTransactionGroupID, v)) +} + +// SourceBackingTransactionGroupIDContainsFold applies the ContainsFold predicate on the "source_backing_transaction_group_id" field. +func SourceBackingTransactionGroupIDContainsFold(v string) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldContainsFold(FieldSourceBackingTransactionGroupID, v)) +} + +// ClosedAtEQ applies the EQ predicate on the "closed_at" field. +func ClosedAtEQ(v time.Time) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldEQ(FieldClosedAt, v)) +} + +// ClosedAtNEQ applies the NEQ predicate on the "closed_at" field. +func ClosedAtNEQ(v time.Time) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldNEQ(FieldClosedAt, v)) +} + +// ClosedAtIn applies the In predicate on the "closed_at" field. +func ClosedAtIn(vs ...time.Time) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldIn(FieldClosedAt, vs...)) +} + +// ClosedAtNotIn applies the NotIn predicate on the "closed_at" field. +func ClosedAtNotIn(vs ...time.Time) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldNotIn(FieldClosedAt, vs...)) +} + +// ClosedAtGT applies the GT predicate on the "closed_at" field. +func ClosedAtGT(v time.Time) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldGT(FieldClosedAt, v)) +} + +// ClosedAtGTE applies the GTE predicate on the "closed_at" field. +func ClosedAtGTE(v time.Time) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldGTE(FieldClosedAt, v)) +} + +// ClosedAtLT applies the LT predicate on the "closed_at" field. +func ClosedAtLT(v time.Time) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldLT(FieldClosedAt, v)) +} + +// ClosedAtLTE applies the LTE predicate on the "closed_at" field. +func ClosedAtLTE(v time.Time) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldLTE(FieldClosedAt, v)) +} + +// ClosedAtIsNil applies the IsNil predicate on the "closed_at" field. +func ClosedAtIsNil() predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldIsNull(FieldClosedAt)) +} + +// ClosedAtNotNil applies the NotNil predicate on the "closed_at" field. +func ClosedAtNotNil() predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldNotNull(FieldClosedAt)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.FieldLTE(FieldCreatedAt, v)) +} + +// HasLineage applies the HasEdge predicate on the "lineage" edge. +func HasLineage() predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, LineageTable, LineageColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasLineageWith applies the HasEdge predicate on the "lineage" edge with a given conditions (other predicates). +func HasLineageWith(preds ...predicate.CreditRealizationLineage) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(func(s *sql.Selector) { + step := newLineageStep() + 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.CreditRealizationLineageSegment) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.CreditRealizationLineageSegment) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.CreditRealizationLineageSegment) predicate.CreditRealizationLineageSegment { + return predicate.CreditRealizationLineageSegment(sql.NotPredicates(p)) +} diff --git a/ent/db/creditrealizationlineagesegment_create.go b/ent/db/creditrealizationlineagesegment_create.go new file mode 100644 index 0000000000000000000000000000000000000000..bfadc7e3abefcf7465f126df28e9bcaecd59047c --- /dev/null +++ b/ent/db/creditrealizationlineagesegment_create.go @@ -0,0 +1,938 @@ +// 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/creditrealization" + "github.com/openmeterio/openmeter/openmeter/ent/db/creditrealizationlineage" + "github.com/openmeterio/openmeter/openmeter/ent/db/creditrealizationlineagesegment" +) + +// CreditRealizationLineageSegmentCreate is the builder for creating a CreditRealizationLineageSegment entity. +type CreditRealizationLineageSegmentCreate struct { + config + mutation *CreditRealizationLineageSegmentMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetLineageID sets the "lineage_id" field. +func (_c *CreditRealizationLineageSegmentCreate) SetLineageID(v string) *CreditRealizationLineageSegmentCreate { + _c.mutation.SetLineageID(v) + return _c +} + +// SetAmount sets the "amount" field. +func (_c *CreditRealizationLineageSegmentCreate) SetAmount(v alpacadecimal.Decimal) *CreditRealizationLineageSegmentCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetState sets the "state" field. +func (_c *CreditRealizationLineageSegmentCreate) SetState(v creditrealization.LineageSegmentState) *CreditRealizationLineageSegmentCreate { + _c.mutation.SetState(v) + return _c +} + +// SetBackingTransactionGroupID sets the "backing_transaction_group_id" field. +func (_c *CreditRealizationLineageSegmentCreate) SetBackingTransactionGroupID(v string) *CreditRealizationLineageSegmentCreate { + _c.mutation.SetBackingTransactionGroupID(v) + return _c +} + +// SetNillableBackingTransactionGroupID sets the "backing_transaction_group_id" field if the given value is not nil. +func (_c *CreditRealizationLineageSegmentCreate) SetNillableBackingTransactionGroupID(v *string) *CreditRealizationLineageSegmentCreate { + if v != nil { + _c.SetBackingTransactionGroupID(*v) + } + return _c +} + +// SetSourceState sets the "source_state" field. +func (_c *CreditRealizationLineageSegmentCreate) SetSourceState(v creditrealization.LineageSegmentState) *CreditRealizationLineageSegmentCreate { + _c.mutation.SetSourceState(v) + return _c +} + +// SetNillableSourceState sets the "source_state" field if the given value is not nil. +func (_c *CreditRealizationLineageSegmentCreate) SetNillableSourceState(v *creditrealization.LineageSegmentState) *CreditRealizationLineageSegmentCreate { + if v != nil { + _c.SetSourceState(*v) + } + return _c +} + +// SetSourceBackingTransactionGroupID sets the "source_backing_transaction_group_id" field. +func (_c *CreditRealizationLineageSegmentCreate) SetSourceBackingTransactionGroupID(v string) *CreditRealizationLineageSegmentCreate { + _c.mutation.SetSourceBackingTransactionGroupID(v) + return _c +} + +// SetNillableSourceBackingTransactionGroupID sets the "source_backing_transaction_group_id" field if the given value is not nil. +func (_c *CreditRealizationLineageSegmentCreate) SetNillableSourceBackingTransactionGroupID(v *string) *CreditRealizationLineageSegmentCreate { + if v != nil { + _c.SetSourceBackingTransactionGroupID(*v) + } + return _c +} + +// SetClosedAt sets the "closed_at" field. +func (_c *CreditRealizationLineageSegmentCreate) SetClosedAt(v time.Time) *CreditRealizationLineageSegmentCreate { + _c.mutation.SetClosedAt(v) + return _c +} + +// SetNillableClosedAt sets the "closed_at" field if the given value is not nil. +func (_c *CreditRealizationLineageSegmentCreate) SetNillableClosedAt(v *time.Time) *CreditRealizationLineageSegmentCreate { + if v != nil { + _c.SetClosedAt(*v) + } + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *CreditRealizationLineageSegmentCreate) SetCreatedAt(v time.Time) *CreditRealizationLineageSegmentCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *CreditRealizationLineageSegmentCreate) SetNillableCreatedAt(v *time.Time) *CreditRealizationLineageSegmentCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *CreditRealizationLineageSegmentCreate) SetID(v string) *CreditRealizationLineageSegmentCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *CreditRealizationLineageSegmentCreate) SetNillableID(v *string) *CreditRealizationLineageSegmentCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetLineage sets the "lineage" edge to the CreditRealizationLineage entity. +func (_c *CreditRealizationLineageSegmentCreate) SetLineage(v *CreditRealizationLineage) *CreditRealizationLineageSegmentCreate { + return _c.SetLineageID(v.ID) +} + +// Mutation returns the CreditRealizationLineageSegmentMutation object of the builder. +func (_c *CreditRealizationLineageSegmentCreate) Mutation() *CreditRealizationLineageSegmentMutation { + return _c.mutation +} + +// Save creates the CreditRealizationLineageSegment in the database. +func (_c *CreditRealizationLineageSegmentCreate) Save(ctx context.Context) (*CreditRealizationLineageSegment, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *CreditRealizationLineageSegmentCreate) SaveX(ctx context.Context) *CreditRealizationLineageSegment { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *CreditRealizationLineageSegmentCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *CreditRealizationLineageSegmentCreate) 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 *CreditRealizationLineageSegmentCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := creditrealizationlineagesegment.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := creditrealizationlineagesegment.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *CreditRealizationLineageSegmentCreate) check() error { + if _, ok := _c.mutation.LineageID(); !ok { + return &ValidationError{Name: "lineage_id", err: errors.New(`db: missing required field "CreditRealizationLineageSegment.lineage_id"`)} + } + if v, ok := _c.mutation.LineageID(); ok { + if err := creditrealizationlineagesegment.LineageIDValidator(v); err != nil { + return &ValidationError{Name: "lineage_id", err: fmt.Errorf(`db: validator failed for field "CreditRealizationLineageSegment.lineage_id": %w`, err)} + } + } + if _, ok := _c.mutation.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`db: missing required field "CreditRealizationLineageSegment.amount"`)} + } + if _, ok := _c.mutation.State(); !ok { + return &ValidationError{Name: "state", err: errors.New(`db: missing required field "CreditRealizationLineageSegment.state"`)} + } + if v, ok := _c.mutation.State(); ok { + if err := creditrealizationlineagesegment.StateValidator(v); err != nil { + return &ValidationError{Name: "state", err: fmt.Errorf(`db: validator failed for field "CreditRealizationLineageSegment.state": %w`, err)} + } + } + if v, ok := _c.mutation.BackingTransactionGroupID(); ok { + if err := creditrealizationlineagesegment.BackingTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "backing_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "CreditRealizationLineageSegment.backing_transaction_group_id": %w`, err)} + } + } + if v, ok := _c.mutation.SourceState(); ok { + if err := creditrealizationlineagesegment.SourceStateValidator(v); err != nil { + return &ValidationError{Name: "source_state", err: fmt.Errorf(`db: validator failed for field "CreditRealizationLineageSegment.source_state": %w`, err)} + } + } + if v, ok := _c.mutation.SourceBackingTransactionGroupID(); ok { + if err := creditrealizationlineagesegment.SourceBackingTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "source_backing_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "CreditRealizationLineageSegment.source_backing_transaction_group_id": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "CreditRealizationLineageSegment.created_at"`)} + } + if len(_c.mutation.LineageIDs()) == 0 { + return &ValidationError{Name: "lineage", err: errors.New(`db: missing required edge "CreditRealizationLineageSegment.lineage"`)} + } + return nil +} + +func (_c *CreditRealizationLineageSegmentCreate) sqlSave(ctx context.Context) (*CreditRealizationLineageSegment, 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 CreditRealizationLineageSegment.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *CreditRealizationLineageSegmentCreate) createSpec() (*CreditRealizationLineageSegment, *sqlgraph.CreateSpec) { + var ( + _node = &CreditRealizationLineageSegment{config: _c.config} + _spec = sqlgraph.NewCreateSpec(creditrealizationlineagesegment.Table, sqlgraph.NewFieldSpec(creditrealizationlineagesegment.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.Amount(); ok { + _spec.SetField(creditrealizationlineagesegment.FieldAmount, field.TypeOther, value) + _node.Amount = value + } + if value, ok := _c.mutation.State(); ok { + _spec.SetField(creditrealizationlineagesegment.FieldState, field.TypeEnum, value) + _node.State = value + } + if value, ok := _c.mutation.BackingTransactionGroupID(); ok { + _spec.SetField(creditrealizationlineagesegment.FieldBackingTransactionGroupID, field.TypeString, value) + _node.BackingTransactionGroupID = &value + } + if value, ok := _c.mutation.SourceState(); ok { + _spec.SetField(creditrealizationlineagesegment.FieldSourceState, field.TypeEnum, value) + _node.SourceState = &value + } + if value, ok := _c.mutation.SourceBackingTransactionGroupID(); ok { + _spec.SetField(creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID, field.TypeString, value) + _node.SourceBackingTransactionGroupID = &value + } + if value, ok := _c.mutation.ClosedAt(); ok { + _spec.SetField(creditrealizationlineagesegment.FieldClosedAt, field.TypeTime, value) + _node.ClosedAt = &value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(creditrealizationlineagesegment.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if nodes := _c.mutation.LineageIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: creditrealizationlineagesegment.LineageTable, + Columns: []string{creditrealizationlineagesegment.LineageColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(creditrealizationlineage.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.LineageID = 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.CreditRealizationLineageSegment.Create(). +// SetLineageID(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.CreditRealizationLineageSegmentUpsert) { +// SetLineageID(v+v). +// }). +// Exec(ctx) +func (_c *CreditRealizationLineageSegmentCreate) OnConflict(opts ...sql.ConflictOption) *CreditRealizationLineageSegmentUpsertOne { + _c.conflict = opts + return &CreditRealizationLineageSegmentUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.CreditRealizationLineageSegment.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *CreditRealizationLineageSegmentCreate) OnConflictColumns(columns ...string) *CreditRealizationLineageSegmentUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &CreditRealizationLineageSegmentUpsertOne{ + create: _c, + } +} + +type ( + // CreditRealizationLineageSegmentUpsertOne is the builder for "upsert"-ing + // one CreditRealizationLineageSegment node. + CreditRealizationLineageSegmentUpsertOne struct { + create *CreditRealizationLineageSegmentCreate + } + + // CreditRealizationLineageSegmentUpsert is the "OnConflict" setter. + CreditRealizationLineageSegmentUpsert struct { + *sql.UpdateSet + } +) + +// SetAmount sets the "amount" field. +func (u *CreditRealizationLineageSegmentUpsert) SetAmount(v alpacadecimal.Decimal) *CreditRealizationLineageSegmentUpsert { + u.Set(creditrealizationlineagesegment.FieldAmount, v) + return u +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *CreditRealizationLineageSegmentUpsert) UpdateAmount() *CreditRealizationLineageSegmentUpsert { + u.SetExcluded(creditrealizationlineagesegment.FieldAmount) + return u +} + +// SetBackingTransactionGroupID sets the "backing_transaction_group_id" field. +func (u *CreditRealizationLineageSegmentUpsert) SetBackingTransactionGroupID(v string) *CreditRealizationLineageSegmentUpsert { + u.Set(creditrealizationlineagesegment.FieldBackingTransactionGroupID, v) + return u +} + +// UpdateBackingTransactionGroupID sets the "backing_transaction_group_id" field to the value that was provided on create. +func (u *CreditRealizationLineageSegmentUpsert) UpdateBackingTransactionGroupID() *CreditRealizationLineageSegmentUpsert { + u.SetExcluded(creditrealizationlineagesegment.FieldBackingTransactionGroupID) + return u +} + +// ClearBackingTransactionGroupID clears the value of the "backing_transaction_group_id" field. +func (u *CreditRealizationLineageSegmentUpsert) ClearBackingTransactionGroupID() *CreditRealizationLineageSegmentUpsert { + u.SetNull(creditrealizationlineagesegment.FieldBackingTransactionGroupID) + return u +} + +// SetSourceState sets the "source_state" field. +func (u *CreditRealizationLineageSegmentUpsert) SetSourceState(v creditrealization.LineageSegmentState) *CreditRealizationLineageSegmentUpsert { + u.Set(creditrealizationlineagesegment.FieldSourceState, v) + return u +} + +// UpdateSourceState sets the "source_state" field to the value that was provided on create. +func (u *CreditRealizationLineageSegmentUpsert) UpdateSourceState() *CreditRealizationLineageSegmentUpsert { + u.SetExcluded(creditrealizationlineagesegment.FieldSourceState) + return u +} + +// ClearSourceState clears the value of the "source_state" field. +func (u *CreditRealizationLineageSegmentUpsert) ClearSourceState() *CreditRealizationLineageSegmentUpsert { + u.SetNull(creditrealizationlineagesegment.FieldSourceState) + return u +} + +// SetSourceBackingTransactionGroupID sets the "source_backing_transaction_group_id" field. +func (u *CreditRealizationLineageSegmentUpsert) SetSourceBackingTransactionGroupID(v string) *CreditRealizationLineageSegmentUpsert { + u.Set(creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID, v) + return u +} + +// UpdateSourceBackingTransactionGroupID sets the "source_backing_transaction_group_id" field to the value that was provided on create. +func (u *CreditRealizationLineageSegmentUpsert) UpdateSourceBackingTransactionGroupID() *CreditRealizationLineageSegmentUpsert { + u.SetExcluded(creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID) + return u +} + +// ClearSourceBackingTransactionGroupID clears the value of the "source_backing_transaction_group_id" field. +func (u *CreditRealizationLineageSegmentUpsert) ClearSourceBackingTransactionGroupID() *CreditRealizationLineageSegmentUpsert { + u.SetNull(creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID) + return u +} + +// SetClosedAt sets the "closed_at" field. +func (u *CreditRealizationLineageSegmentUpsert) SetClosedAt(v time.Time) *CreditRealizationLineageSegmentUpsert { + u.Set(creditrealizationlineagesegment.FieldClosedAt, v) + return u +} + +// UpdateClosedAt sets the "closed_at" field to the value that was provided on create. +func (u *CreditRealizationLineageSegmentUpsert) UpdateClosedAt() *CreditRealizationLineageSegmentUpsert { + u.SetExcluded(creditrealizationlineagesegment.FieldClosedAt) + return u +} + +// ClearClosedAt clears the value of the "closed_at" field. +func (u *CreditRealizationLineageSegmentUpsert) ClearClosedAt() *CreditRealizationLineageSegmentUpsert { + u.SetNull(creditrealizationlineagesegment.FieldClosedAt) + 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.CreditRealizationLineageSegment.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(creditrealizationlineagesegment.FieldID) +// }), +// ). +// Exec(ctx) +func (u *CreditRealizationLineageSegmentUpsertOne) UpdateNewValues() *CreditRealizationLineageSegmentUpsertOne { + 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(creditrealizationlineagesegment.FieldID) + } + if _, exists := u.create.mutation.LineageID(); exists { + s.SetIgnore(creditrealizationlineagesegment.FieldLineageID) + } + if _, exists := u.create.mutation.State(); exists { + s.SetIgnore(creditrealizationlineagesegment.FieldState) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(creditrealizationlineagesegment.FieldCreatedAt) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.CreditRealizationLineageSegment.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *CreditRealizationLineageSegmentUpsertOne) Ignore() *CreditRealizationLineageSegmentUpsertOne { + 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 *CreditRealizationLineageSegmentUpsertOne) DoNothing() *CreditRealizationLineageSegmentUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the CreditRealizationLineageSegmentCreate.OnConflict +// documentation for more info. +func (u *CreditRealizationLineageSegmentUpsertOne) Update(set func(*CreditRealizationLineageSegmentUpsert)) *CreditRealizationLineageSegmentUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&CreditRealizationLineageSegmentUpsert{UpdateSet: update}) + })) + return u +} + +// SetAmount sets the "amount" field. +func (u *CreditRealizationLineageSegmentUpsertOne) SetAmount(v alpacadecimal.Decimal) *CreditRealizationLineageSegmentUpsertOne { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *CreditRealizationLineageSegmentUpsertOne) UpdateAmount() *CreditRealizationLineageSegmentUpsertOne { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.UpdateAmount() + }) +} + +// SetBackingTransactionGroupID sets the "backing_transaction_group_id" field. +func (u *CreditRealizationLineageSegmentUpsertOne) SetBackingTransactionGroupID(v string) *CreditRealizationLineageSegmentUpsertOne { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.SetBackingTransactionGroupID(v) + }) +} + +// UpdateBackingTransactionGroupID sets the "backing_transaction_group_id" field to the value that was provided on create. +func (u *CreditRealizationLineageSegmentUpsertOne) UpdateBackingTransactionGroupID() *CreditRealizationLineageSegmentUpsertOne { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.UpdateBackingTransactionGroupID() + }) +} + +// ClearBackingTransactionGroupID clears the value of the "backing_transaction_group_id" field. +func (u *CreditRealizationLineageSegmentUpsertOne) ClearBackingTransactionGroupID() *CreditRealizationLineageSegmentUpsertOne { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.ClearBackingTransactionGroupID() + }) +} + +// SetSourceState sets the "source_state" field. +func (u *CreditRealizationLineageSegmentUpsertOne) SetSourceState(v creditrealization.LineageSegmentState) *CreditRealizationLineageSegmentUpsertOne { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.SetSourceState(v) + }) +} + +// UpdateSourceState sets the "source_state" field to the value that was provided on create. +func (u *CreditRealizationLineageSegmentUpsertOne) UpdateSourceState() *CreditRealizationLineageSegmentUpsertOne { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.UpdateSourceState() + }) +} + +// ClearSourceState clears the value of the "source_state" field. +func (u *CreditRealizationLineageSegmentUpsertOne) ClearSourceState() *CreditRealizationLineageSegmentUpsertOne { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.ClearSourceState() + }) +} + +// SetSourceBackingTransactionGroupID sets the "source_backing_transaction_group_id" field. +func (u *CreditRealizationLineageSegmentUpsertOne) SetSourceBackingTransactionGroupID(v string) *CreditRealizationLineageSegmentUpsertOne { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.SetSourceBackingTransactionGroupID(v) + }) +} + +// UpdateSourceBackingTransactionGroupID sets the "source_backing_transaction_group_id" field to the value that was provided on create. +func (u *CreditRealizationLineageSegmentUpsertOne) UpdateSourceBackingTransactionGroupID() *CreditRealizationLineageSegmentUpsertOne { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.UpdateSourceBackingTransactionGroupID() + }) +} + +// ClearSourceBackingTransactionGroupID clears the value of the "source_backing_transaction_group_id" field. +func (u *CreditRealizationLineageSegmentUpsertOne) ClearSourceBackingTransactionGroupID() *CreditRealizationLineageSegmentUpsertOne { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.ClearSourceBackingTransactionGroupID() + }) +} + +// SetClosedAt sets the "closed_at" field. +func (u *CreditRealizationLineageSegmentUpsertOne) SetClosedAt(v time.Time) *CreditRealizationLineageSegmentUpsertOne { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.SetClosedAt(v) + }) +} + +// UpdateClosedAt sets the "closed_at" field to the value that was provided on create. +func (u *CreditRealizationLineageSegmentUpsertOne) UpdateClosedAt() *CreditRealizationLineageSegmentUpsertOne { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.UpdateClosedAt() + }) +} + +// ClearClosedAt clears the value of the "closed_at" field. +func (u *CreditRealizationLineageSegmentUpsertOne) ClearClosedAt() *CreditRealizationLineageSegmentUpsertOne { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.ClearClosedAt() + }) +} + +// Exec executes the query. +func (u *CreditRealizationLineageSegmentUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for CreditRealizationLineageSegmentCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *CreditRealizationLineageSegmentUpsertOne) 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 *CreditRealizationLineageSegmentUpsertOne) 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: CreditRealizationLineageSegmentUpsertOne.ID is not supported by MySQL driver. Use CreditRealizationLineageSegmentUpsertOne.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 *CreditRealizationLineageSegmentUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// CreditRealizationLineageSegmentCreateBulk is the builder for creating many CreditRealizationLineageSegment entities in bulk. +type CreditRealizationLineageSegmentCreateBulk struct { + config + err error + builders []*CreditRealizationLineageSegmentCreate + conflict []sql.ConflictOption +} + +// Save creates the CreditRealizationLineageSegment entities in the database. +func (_c *CreditRealizationLineageSegmentCreateBulk) Save(ctx context.Context) ([]*CreditRealizationLineageSegment, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*CreditRealizationLineageSegment, 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.(*CreditRealizationLineageSegmentMutation) + 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 *CreditRealizationLineageSegmentCreateBulk) SaveX(ctx context.Context) []*CreditRealizationLineageSegment { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *CreditRealizationLineageSegmentCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *CreditRealizationLineageSegmentCreateBulk) 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.CreditRealizationLineageSegment.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.CreditRealizationLineageSegmentUpsert) { +// SetLineageID(v+v). +// }). +// Exec(ctx) +func (_c *CreditRealizationLineageSegmentCreateBulk) OnConflict(opts ...sql.ConflictOption) *CreditRealizationLineageSegmentUpsertBulk { + _c.conflict = opts + return &CreditRealizationLineageSegmentUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.CreditRealizationLineageSegment.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *CreditRealizationLineageSegmentCreateBulk) OnConflictColumns(columns ...string) *CreditRealizationLineageSegmentUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &CreditRealizationLineageSegmentUpsertBulk{ + create: _c, + } +} + +// CreditRealizationLineageSegmentUpsertBulk is the builder for "upsert"-ing +// a bulk of CreditRealizationLineageSegment nodes. +type CreditRealizationLineageSegmentUpsertBulk struct { + create *CreditRealizationLineageSegmentCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.CreditRealizationLineageSegment.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(creditrealizationlineagesegment.FieldID) +// }), +// ). +// Exec(ctx) +func (u *CreditRealizationLineageSegmentUpsertBulk) UpdateNewValues() *CreditRealizationLineageSegmentUpsertBulk { + 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(creditrealizationlineagesegment.FieldID) + } + if _, exists := b.mutation.LineageID(); exists { + s.SetIgnore(creditrealizationlineagesegment.FieldLineageID) + } + if _, exists := b.mutation.State(); exists { + s.SetIgnore(creditrealizationlineagesegment.FieldState) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(creditrealizationlineagesegment.FieldCreatedAt) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.CreditRealizationLineageSegment.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *CreditRealizationLineageSegmentUpsertBulk) Ignore() *CreditRealizationLineageSegmentUpsertBulk { + 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 *CreditRealizationLineageSegmentUpsertBulk) DoNothing() *CreditRealizationLineageSegmentUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the CreditRealizationLineageSegmentCreateBulk.OnConflict +// documentation for more info. +func (u *CreditRealizationLineageSegmentUpsertBulk) Update(set func(*CreditRealizationLineageSegmentUpsert)) *CreditRealizationLineageSegmentUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&CreditRealizationLineageSegmentUpsert{UpdateSet: update}) + })) + return u +} + +// SetAmount sets the "amount" field. +func (u *CreditRealizationLineageSegmentUpsertBulk) SetAmount(v alpacadecimal.Decimal) *CreditRealizationLineageSegmentUpsertBulk { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *CreditRealizationLineageSegmentUpsertBulk) UpdateAmount() *CreditRealizationLineageSegmentUpsertBulk { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.UpdateAmount() + }) +} + +// SetBackingTransactionGroupID sets the "backing_transaction_group_id" field. +func (u *CreditRealizationLineageSegmentUpsertBulk) SetBackingTransactionGroupID(v string) *CreditRealizationLineageSegmentUpsertBulk { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.SetBackingTransactionGroupID(v) + }) +} + +// UpdateBackingTransactionGroupID sets the "backing_transaction_group_id" field to the value that was provided on create. +func (u *CreditRealizationLineageSegmentUpsertBulk) UpdateBackingTransactionGroupID() *CreditRealizationLineageSegmentUpsertBulk { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.UpdateBackingTransactionGroupID() + }) +} + +// ClearBackingTransactionGroupID clears the value of the "backing_transaction_group_id" field. +func (u *CreditRealizationLineageSegmentUpsertBulk) ClearBackingTransactionGroupID() *CreditRealizationLineageSegmentUpsertBulk { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.ClearBackingTransactionGroupID() + }) +} + +// SetSourceState sets the "source_state" field. +func (u *CreditRealizationLineageSegmentUpsertBulk) SetSourceState(v creditrealization.LineageSegmentState) *CreditRealizationLineageSegmentUpsertBulk { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.SetSourceState(v) + }) +} + +// UpdateSourceState sets the "source_state" field to the value that was provided on create. +func (u *CreditRealizationLineageSegmentUpsertBulk) UpdateSourceState() *CreditRealizationLineageSegmentUpsertBulk { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.UpdateSourceState() + }) +} + +// ClearSourceState clears the value of the "source_state" field. +func (u *CreditRealizationLineageSegmentUpsertBulk) ClearSourceState() *CreditRealizationLineageSegmentUpsertBulk { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.ClearSourceState() + }) +} + +// SetSourceBackingTransactionGroupID sets the "source_backing_transaction_group_id" field. +func (u *CreditRealizationLineageSegmentUpsertBulk) SetSourceBackingTransactionGroupID(v string) *CreditRealizationLineageSegmentUpsertBulk { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.SetSourceBackingTransactionGroupID(v) + }) +} + +// UpdateSourceBackingTransactionGroupID sets the "source_backing_transaction_group_id" field to the value that was provided on create. +func (u *CreditRealizationLineageSegmentUpsertBulk) UpdateSourceBackingTransactionGroupID() *CreditRealizationLineageSegmentUpsertBulk { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.UpdateSourceBackingTransactionGroupID() + }) +} + +// ClearSourceBackingTransactionGroupID clears the value of the "source_backing_transaction_group_id" field. +func (u *CreditRealizationLineageSegmentUpsertBulk) ClearSourceBackingTransactionGroupID() *CreditRealizationLineageSegmentUpsertBulk { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.ClearSourceBackingTransactionGroupID() + }) +} + +// SetClosedAt sets the "closed_at" field. +func (u *CreditRealizationLineageSegmentUpsertBulk) SetClosedAt(v time.Time) *CreditRealizationLineageSegmentUpsertBulk { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.SetClosedAt(v) + }) +} + +// UpdateClosedAt sets the "closed_at" field to the value that was provided on create. +func (u *CreditRealizationLineageSegmentUpsertBulk) UpdateClosedAt() *CreditRealizationLineageSegmentUpsertBulk { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.UpdateClosedAt() + }) +} + +// ClearClosedAt clears the value of the "closed_at" field. +func (u *CreditRealizationLineageSegmentUpsertBulk) ClearClosedAt() *CreditRealizationLineageSegmentUpsertBulk { + return u.Update(func(s *CreditRealizationLineageSegmentUpsert) { + s.ClearClosedAt() + }) +} + +// Exec executes the query. +func (u *CreditRealizationLineageSegmentUpsertBulk) 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 CreditRealizationLineageSegmentCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for CreditRealizationLineageSegmentCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *CreditRealizationLineageSegmentUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/creditrealizationlineagesegment_delete.go b/ent/db/creditrealizationlineagesegment_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..426d55613e643095e5df3a9986f3f1d92a5da0a7 --- /dev/null +++ b/ent/db/creditrealizationlineagesegment_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/creditrealizationlineagesegment" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// CreditRealizationLineageSegmentDelete is the builder for deleting a CreditRealizationLineageSegment entity. +type CreditRealizationLineageSegmentDelete struct { + config + hooks []Hook + mutation *CreditRealizationLineageSegmentMutation +} + +// Where appends a list predicates to the CreditRealizationLineageSegmentDelete builder. +func (_d *CreditRealizationLineageSegmentDelete) Where(ps ...predicate.CreditRealizationLineageSegment) *CreditRealizationLineageSegmentDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *CreditRealizationLineageSegmentDelete) 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 *CreditRealizationLineageSegmentDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *CreditRealizationLineageSegmentDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(creditrealizationlineagesegment.Table, sqlgraph.NewFieldSpec(creditrealizationlineagesegment.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 +} + +// CreditRealizationLineageSegmentDeleteOne is the builder for deleting a single CreditRealizationLineageSegment entity. +type CreditRealizationLineageSegmentDeleteOne struct { + _d *CreditRealizationLineageSegmentDelete +} + +// Where appends a list predicates to the CreditRealizationLineageSegmentDelete builder. +func (_d *CreditRealizationLineageSegmentDeleteOne) Where(ps ...predicate.CreditRealizationLineageSegment) *CreditRealizationLineageSegmentDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *CreditRealizationLineageSegmentDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{creditrealizationlineagesegment.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *CreditRealizationLineageSegmentDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/creditrealizationlineagesegment_query.go b/ent/db/creditrealizationlineagesegment_query.go new file mode 100644 index 0000000000000000000000000000000000000000..8917e072ba531c743fde415e2995bf58450d2b44 --- /dev/null +++ b/ent/db/creditrealizationlineagesegment_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/creditrealizationlineage" + "github.com/openmeterio/openmeter/openmeter/ent/db/creditrealizationlineagesegment" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// CreditRealizationLineageSegmentQuery is the builder for querying CreditRealizationLineageSegment entities. +type CreditRealizationLineageSegmentQuery struct { + config + ctx *QueryContext + order []creditrealizationlineagesegment.OrderOption + inters []Interceptor + predicates []predicate.CreditRealizationLineageSegment + withLineage *CreditRealizationLineageQuery + 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 CreditRealizationLineageSegmentQuery builder. +func (_q *CreditRealizationLineageSegmentQuery) Where(ps ...predicate.CreditRealizationLineageSegment) *CreditRealizationLineageSegmentQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *CreditRealizationLineageSegmentQuery) Limit(limit int) *CreditRealizationLineageSegmentQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *CreditRealizationLineageSegmentQuery) Offset(offset int) *CreditRealizationLineageSegmentQuery { + _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 *CreditRealizationLineageSegmentQuery) Unique(unique bool) *CreditRealizationLineageSegmentQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *CreditRealizationLineageSegmentQuery) Order(o ...creditrealizationlineagesegment.OrderOption) *CreditRealizationLineageSegmentQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryLineage chains the current query on the "lineage" edge. +func (_q *CreditRealizationLineageSegmentQuery) QueryLineage() *CreditRealizationLineageQuery { + query := (&CreditRealizationLineageClient{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(creditrealizationlineagesegment.Table, creditrealizationlineagesegment.FieldID, selector), + sqlgraph.To(creditrealizationlineage.Table, creditrealizationlineage.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, creditrealizationlineagesegment.LineageTable, creditrealizationlineagesegment.LineageColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first CreditRealizationLineageSegment entity from the query. +// Returns a *NotFoundError when no CreditRealizationLineageSegment was found. +func (_q *CreditRealizationLineageSegmentQuery) First(ctx context.Context) (*CreditRealizationLineageSegment, 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{creditrealizationlineagesegment.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *CreditRealizationLineageSegmentQuery) FirstX(ctx context.Context) *CreditRealizationLineageSegment { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first CreditRealizationLineageSegment ID from the query. +// Returns a *NotFoundError when no CreditRealizationLineageSegment ID was found. +func (_q *CreditRealizationLineageSegmentQuery) 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{creditrealizationlineagesegment.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *CreditRealizationLineageSegmentQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single CreditRealizationLineageSegment entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one CreditRealizationLineageSegment entity is found. +// Returns a *NotFoundError when no CreditRealizationLineageSegment entities are found. +func (_q *CreditRealizationLineageSegmentQuery) Only(ctx context.Context) (*CreditRealizationLineageSegment, 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{creditrealizationlineagesegment.Label} + default: + return nil, &NotSingularError{creditrealizationlineagesegment.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *CreditRealizationLineageSegmentQuery) OnlyX(ctx context.Context) *CreditRealizationLineageSegment { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only CreditRealizationLineageSegment ID in the query. +// Returns a *NotSingularError when more than one CreditRealizationLineageSegment ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *CreditRealizationLineageSegmentQuery) 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{creditrealizationlineagesegment.Label} + default: + err = &NotSingularError{creditrealizationlineagesegment.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *CreditRealizationLineageSegmentQuery) 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 CreditRealizationLineageSegments. +func (_q *CreditRealizationLineageSegmentQuery) All(ctx context.Context) ([]*CreditRealizationLineageSegment, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*CreditRealizationLineageSegment, *CreditRealizationLineageSegmentQuery]() + return withInterceptors[[]*CreditRealizationLineageSegment](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *CreditRealizationLineageSegmentQuery) AllX(ctx context.Context) []*CreditRealizationLineageSegment { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of CreditRealizationLineageSegment IDs. +func (_q *CreditRealizationLineageSegmentQuery) 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(creditrealizationlineagesegment.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *CreditRealizationLineageSegmentQuery) 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 *CreditRealizationLineageSegmentQuery) 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[*CreditRealizationLineageSegmentQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *CreditRealizationLineageSegmentQuery) 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 *CreditRealizationLineageSegmentQuery) 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 *CreditRealizationLineageSegmentQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the CreditRealizationLineageSegmentQuery 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 *CreditRealizationLineageSegmentQuery) Clone() *CreditRealizationLineageSegmentQuery { + if _q == nil { + return nil + } + return &CreditRealizationLineageSegmentQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]creditrealizationlineagesegment.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.CreditRealizationLineageSegment{}, _q.predicates...), + withLineage: _q.withLineage.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithLineage tells the query-builder to eager-load the nodes that are connected to +// the "lineage" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *CreditRealizationLineageSegmentQuery) WithLineage(opts ...func(*CreditRealizationLineageQuery)) *CreditRealizationLineageSegmentQuery { + query := (&CreditRealizationLineageClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withLineage = 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 { +// LineageID string `json:"lineage_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.CreditRealizationLineageSegment.Query(). +// GroupBy(creditrealizationlineagesegment.FieldLineageID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *CreditRealizationLineageSegmentQuery) GroupBy(field string, fields ...string) *CreditRealizationLineageSegmentGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &CreditRealizationLineageSegmentGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = creditrealizationlineagesegment.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 { +// LineageID string `json:"lineage_id,omitempty"` +// } +// +// client.CreditRealizationLineageSegment.Query(). +// Select(creditrealizationlineagesegment.FieldLineageID). +// Scan(ctx, &v) +func (_q *CreditRealizationLineageSegmentQuery) Select(fields ...string) *CreditRealizationLineageSegmentSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &CreditRealizationLineageSegmentSelect{CreditRealizationLineageSegmentQuery: _q} + sbuild.label = creditrealizationlineagesegment.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a CreditRealizationLineageSegmentSelect configured with the given aggregations. +func (_q *CreditRealizationLineageSegmentQuery) Aggregate(fns ...AggregateFunc) *CreditRealizationLineageSegmentSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *CreditRealizationLineageSegmentQuery) 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 !creditrealizationlineagesegment.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 *CreditRealizationLineageSegmentQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*CreditRealizationLineageSegment, error) { + var ( + nodes = []*CreditRealizationLineageSegment{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withLineage != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*CreditRealizationLineageSegment).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &CreditRealizationLineageSegment{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.withLineage; query != nil { + if err := _q.loadLineage(ctx, query, nodes, nil, + func(n *CreditRealizationLineageSegment, e *CreditRealizationLineage) { n.Edges.Lineage = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *CreditRealizationLineageSegmentQuery) loadLineage(ctx context.Context, query *CreditRealizationLineageQuery, nodes []*CreditRealizationLineageSegment, init func(*CreditRealizationLineageSegment), assign func(*CreditRealizationLineageSegment, *CreditRealizationLineage)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*CreditRealizationLineageSegment) + for i := range nodes { + fk := nodes[i].LineageID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(creditrealizationlineage.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 "lineage_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *CreditRealizationLineageSegmentQuery) 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 *CreditRealizationLineageSegmentQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(creditrealizationlineagesegment.Table, creditrealizationlineagesegment.Columns, sqlgraph.NewFieldSpec(creditrealizationlineagesegment.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, creditrealizationlineagesegment.FieldID) + for i := range fields { + if fields[i] != creditrealizationlineagesegment.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withLineage != nil { + _spec.Node.AddColumnOnce(creditrealizationlineagesegment.FieldLineageID) + } + } + 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 *CreditRealizationLineageSegmentQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(creditrealizationlineagesegment.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = creditrealizationlineagesegment.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 *CreditRealizationLineageSegmentQuery) ForUpdate(opts ...sql.LockOption) *CreditRealizationLineageSegmentQuery { + 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 *CreditRealizationLineageSegmentQuery) ForShare(opts ...sql.LockOption) *CreditRealizationLineageSegmentQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// CreditRealizationLineageSegmentGroupBy is the group-by builder for CreditRealizationLineageSegment entities. +type CreditRealizationLineageSegmentGroupBy struct { + selector + build *CreditRealizationLineageSegmentQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *CreditRealizationLineageSegmentGroupBy) Aggregate(fns ...AggregateFunc) *CreditRealizationLineageSegmentGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *CreditRealizationLineageSegmentGroupBy) 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[*CreditRealizationLineageSegmentQuery, *CreditRealizationLineageSegmentGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *CreditRealizationLineageSegmentGroupBy) sqlScan(ctx context.Context, root *CreditRealizationLineageSegmentQuery, 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) +} + +// CreditRealizationLineageSegmentSelect is the builder for selecting fields of CreditRealizationLineageSegment entities. +type CreditRealizationLineageSegmentSelect struct { + *CreditRealizationLineageSegmentQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *CreditRealizationLineageSegmentSelect) Aggregate(fns ...AggregateFunc) *CreditRealizationLineageSegmentSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *CreditRealizationLineageSegmentSelect) 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[*CreditRealizationLineageSegmentQuery, *CreditRealizationLineageSegmentSelect](ctx, _s.CreditRealizationLineageSegmentQuery, _s, _s.inters, v) +} + +func (_s *CreditRealizationLineageSegmentSelect) sqlScan(ctx context.Context, root *CreditRealizationLineageSegmentQuery, 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/ent/db/creditrealizationlineagesegment_update.go b/ent/db/creditrealizationlineagesegment_update.go new file mode 100644 index 0000000000000000000000000000000000000000..8d199b022a54cbe339debce4d30d19f9422e8186 --- /dev/null +++ b/ent/db/creditrealizationlineagesegment_update.go @@ -0,0 +1,472 @@ +// 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/creditrealization" + "github.com/openmeterio/openmeter/openmeter/ent/db/creditrealizationlineagesegment" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// CreditRealizationLineageSegmentUpdate is the builder for updating CreditRealizationLineageSegment entities. +type CreditRealizationLineageSegmentUpdate struct { + config + hooks []Hook + mutation *CreditRealizationLineageSegmentMutation +} + +// Where appends a list predicates to the CreditRealizationLineageSegmentUpdate builder. +func (_u *CreditRealizationLineageSegmentUpdate) Where(ps ...predicate.CreditRealizationLineageSegment) *CreditRealizationLineageSegmentUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetAmount sets the "amount" field. +func (_u *CreditRealizationLineageSegmentUpdate) SetAmount(v alpacadecimal.Decimal) *CreditRealizationLineageSegmentUpdate { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *CreditRealizationLineageSegmentUpdate) SetNillableAmount(v *alpacadecimal.Decimal) *CreditRealizationLineageSegmentUpdate { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetBackingTransactionGroupID sets the "backing_transaction_group_id" field. +func (_u *CreditRealizationLineageSegmentUpdate) SetBackingTransactionGroupID(v string) *CreditRealizationLineageSegmentUpdate { + _u.mutation.SetBackingTransactionGroupID(v) + return _u +} + +// SetNillableBackingTransactionGroupID sets the "backing_transaction_group_id" field if the given value is not nil. +func (_u *CreditRealizationLineageSegmentUpdate) SetNillableBackingTransactionGroupID(v *string) *CreditRealizationLineageSegmentUpdate { + if v != nil { + _u.SetBackingTransactionGroupID(*v) + } + return _u +} + +// ClearBackingTransactionGroupID clears the value of the "backing_transaction_group_id" field. +func (_u *CreditRealizationLineageSegmentUpdate) ClearBackingTransactionGroupID() *CreditRealizationLineageSegmentUpdate { + _u.mutation.ClearBackingTransactionGroupID() + return _u +} + +// SetSourceState sets the "source_state" field. +func (_u *CreditRealizationLineageSegmentUpdate) SetSourceState(v creditrealization.LineageSegmentState) *CreditRealizationLineageSegmentUpdate { + _u.mutation.SetSourceState(v) + return _u +} + +// SetNillableSourceState sets the "source_state" field if the given value is not nil. +func (_u *CreditRealizationLineageSegmentUpdate) SetNillableSourceState(v *creditrealization.LineageSegmentState) *CreditRealizationLineageSegmentUpdate { + if v != nil { + _u.SetSourceState(*v) + } + return _u +} + +// ClearSourceState clears the value of the "source_state" field. +func (_u *CreditRealizationLineageSegmentUpdate) ClearSourceState() *CreditRealizationLineageSegmentUpdate { + _u.mutation.ClearSourceState() + return _u +} + +// SetSourceBackingTransactionGroupID sets the "source_backing_transaction_group_id" field. +func (_u *CreditRealizationLineageSegmentUpdate) SetSourceBackingTransactionGroupID(v string) *CreditRealizationLineageSegmentUpdate { + _u.mutation.SetSourceBackingTransactionGroupID(v) + return _u +} + +// SetNillableSourceBackingTransactionGroupID sets the "source_backing_transaction_group_id" field if the given value is not nil. +func (_u *CreditRealizationLineageSegmentUpdate) SetNillableSourceBackingTransactionGroupID(v *string) *CreditRealizationLineageSegmentUpdate { + if v != nil { + _u.SetSourceBackingTransactionGroupID(*v) + } + return _u +} + +// ClearSourceBackingTransactionGroupID clears the value of the "source_backing_transaction_group_id" field. +func (_u *CreditRealizationLineageSegmentUpdate) ClearSourceBackingTransactionGroupID() *CreditRealizationLineageSegmentUpdate { + _u.mutation.ClearSourceBackingTransactionGroupID() + return _u +} + +// SetClosedAt sets the "closed_at" field. +func (_u *CreditRealizationLineageSegmentUpdate) SetClosedAt(v time.Time) *CreditRealizationLineageSegmentUpdate { + _u.mutation.SetClosedAt(v) + return _u +} + +// SetNillableClosedAt sets the "closed_at" field if the given value is not nil. +func (_u *CreditRealizationLineageSegmentUpdate) SetNillableClosedAt(v *time.Time) *CreditRealizationLineageSegmentUpdate { + if v != nil { + _u.SetClosedAt(*v) + } + return _u +} + +// ClearClosedAt clears the value of the "closed_at" field. +func (_u *CreditRealizationLineageSegmentUpdate) ClearClosedAt() *CreditRealizationLineageSegmentUpdate { + _u.mutation.ClearClosedAt() + return _u +} + +// Mutation returns the CreditRealizationLineageSegmentMutation object of the builder. +func (_u *CreditRealizationLineageSegmentUpdate) Mutation() *CreditRealizationLineageSegmentMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *CreditRealizationLineageSegmentUpdate) 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 *CreditRealizationLineageSegmentUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *CreditRealizationLineageSegmentUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *CreditRealizationLineageSegmentUpdate) 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 *CreditRealizationLineageSegmentUpdate) check() error { + if v, ok := _u.mutation.BackingTransactionGroupID(); ok { + if err := creditrealizationlineagesegment.BackingTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "backing_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "CreditRealizationLineageSegment.backing_transaction_group_id": %w`, err)} + } + } + if v, ok := _u.mutation.SourceState(); ok { + if err := creditrealizationlineagesegment.SourceStateValidator(v); err != nil { + return &ValidationError{Name: "source_state", err: fmt.Errorf(`db: validator failed for field "CreditRealizationLineageSegment.source_state": %w`, err)} + } + } + if v, ok := _u.mutation.SourceBackingTransactionGroupID(); ok { + if err := creditrealizationlineagesegment.SourceBackingTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "source_backing_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "CreditRealizationLineageSegment.source_backing_transaction_group_id": %w`, err)} + } + } + if _u.mutation.LineageCleared() && len(_u.mutation.LineageIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "CreditRealizationLineageSegment.lineage"`) + } + return nil +} + +func (_u *CreditRealizationLineageSegmentUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(creditrealizationlineagesegment.Table, creditrealizationlineagesegment.Columns, sqlgraph.NewFieldSpec(creditrealizationlineagesegment.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.Amount(); ok { + _spec.SetField(creditrealizationlineagesegment.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.BackingTransactionGroupID(); ok { + _spec.SetField(creditrealizationlineagesegment.FieldBackingTransactionGroupID, field.TypeString, value) + } + if _u.mutation.BackingTransactionGroupIDCleared() { + _spec.ClearField(creditrealizationlineagesegment.FieldBackingTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.SourceState(); ok { + _spec.SetField(creditrealizationlineagesegment.FieldSourceState, field.TypeEnum, value) + } + if _u.mutation.SourceStateCleared() { + _spec.ClearField(creditrealizationlineagesegment.FieldSourceState, field.TypeEnum) + } + if value, ok := _u.mutation.SourceBackingTransactionGroupID(); ok { + _spec.SetField(creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID, field.TypeString, value) + } + if _u.mutation.SourceBackingTransactionGroupIDCleared() { + _spec.ClearField(creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.ClosedAt(); ok { + _spec.SetField(creditrealizationlineagesegment.FieldClosedAt, field.TypeTime, value) + } + if _u.mutation.ClosedAtCleared() { + _spec.ClearField(creditrealizationlineagesegment.FieldClosedAt, field.TypeTime) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{creditrealizationlineagesegment.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// CreditRealizationLineageSegmentUpdateOne is the builder for updating a single CreditRealizationLineageSegment entity. +type CreditRealizationLineageSegmentUpdateOne struct { + config + fields []string + hooks []Hook + mutation *CreditRealizationLineageSegmentMutation +} + +// SetAmount sets the "amount" field. +func (_u *CreditRealizationLineageSegmentUpdateOne) SetAmount(v alpacadecimal.Decimal) *CreditRealizationLineageSegmentUpdateOne { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *CreditRealizationLineageSegmentUpdateOne) SetNillableAmount(v *alpacadecimal.Decimal) *CreditRealizationLineageSegmentUpdateOne { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetBackingTransactionGroupID sets the "backing_transaction_group_id" field. +func (_u *CreditRealizationLineageSegmentUpdateOne) SetBackingTransactionGroupID(v string) *CreditRealizationLineageSegmentUpdateOne { + _u.mutation.SetBackingTransactionGroupID(v) + return _u +} + +// SetNillableBackingTransactionGroupID sets the "backing_transaction_group_id" field if the given value is not nil. +func (_u *CreditRealizationLineageSegmentUpdateOne) SetNillableBackingTransactionGroupID(v *string) *CreditRealizationLineageSegmentUpdateOne { + if v != nil { + _u.SetBackingTransactionGroupID(*v) + } + return _u +} + +// ClearBackingTransactionGroupID clears the value of the "backing_transaction_group_id" field. +func (_u *CreditRealizationLineageSegmentUpdateOne) ClearBackingTransactionGroupID() *CreditRealizationLineageSegmentUpdateOne { + _u.mutation.ClearBackingTransactionGroupID() + return _u +} + +// SetSourceState sets the "source_state" field. +func (_u *CreditRealizationLineageSegmentUpdateOne) SetSourceState(v creditrealization.LineageSegmentState) *CreditRealizationLineageSegmentUpdateOne { + _u.mutation.SetSourceState(v) + return _u +} + +// SetNillableSourceState sets the "source_state" field if the given value is not nil. +func (_u *CreditRealizationLineageSegmentUpdateOne) SetNillableSourceState(v *creditrealization.LineageSegmentState) *CreditRealizationLineageSegmentUpdateOne { + if v != nil { + _u.SetSourceState(*v) + } + return _u +} + +// ClearSourceState clears the value of the "source_state" field. +func (_u *CreditRealizationLineageSegmentUpdateOne) ClearSourceState() *CreditRealizationLineageSegmentUpdateOne { + _u.mutation.ClearSourceState() + return _u +} + +// SetSourceBackingTransactionGroupID sets the "source_backing_transaction_group_id" field. +func (_u *CreditRealizationLineageSegmentUpdateOne) SetSourceBackingTransactionGroupID(v string) *CreditRealizationLineageSegmentUpdateOne { + _u.mutation.SetSourceBackingTransactionGroupID(v) + return _u +} + +// SetNillableSourceBackingTransactionGroupID sets the "source_backing_transaction_group_id" field if the given value is not nil. +func (_u *CreditRealizationLineageSegmentUpdateOne) SetNillableSourceBackingTransactionGroupID(v *string) *CreditRealizationLineageSegmentUpdateOne { + if v != nil { + _u.SetSourceBackingTransactionGroupID(*v) + } + return _u +} + +// ClearSourceBackingTransactionGroupID clears the value of the "source_backing_transaction_group_id" field. +func (_u *CreditRealizationLineageSegmentUpdateOne) ClearSourceBackingTransactionGroupID() *CreditRealizationLineageSegmentUpdateOne { + _u.mutation.ClearSourceBackingTransactionGroupID() + return _u +} + +// SetClosedAt sets the "closed_at" field. +func (_u *CreditRealizationLineageSegmentUpdateOne) SetClosedAt(v time.Time) *CreditRealizationLineageSegmentUpdateOne { + _u.mutation.SetClosedAt(v) + return _u +} + +// SetNillableClosedAt sets the "closed_at" field if the given value is not nil. +func (_u *CreditRealizationLineageSegmentUpdateOne) SetNillableClosedAt(v *time.Time) *CreditRealizationLineageSegmentUpdateOne { + if v != nil { + _u.SetClosedAt(*v) + } + return _u +} + +// ClearClosedAt clears the value of the "closed_at" field. +func (_u *CreditRealizationLineageSegmentUpdateOne) ClearClosedAt() *CreditRealizationLineageSegmentUpdateOne { + _u.mutation.ClearClosedAt() + return _u +} + +// Mutation returns the CreditRealizationLineageSegmentMutation object of the builder. +func (_u *CreditRealizationLineageSegmentUpdateOne) Mutation() *CreditRealizationLineageSegmentMutation { + return _u.mutation +} + +// Where appends a list predicates to the CreditRealizationLineageSegmentUpdate builder. +func (_u *CreditRealizationLineageSegmentUpdateOne) Where(ps ...predicate.CreditRealizationLineageSegment) *CreditRealizationLineageSegmentUpdateOne { + _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 *CreditRealizationLineageSegmentUpdateOne) Select(field string, fields ...string) *CreditRealizationLineageSegmentUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated CreditRealizationLineageSegment entity. +func (_u *CreditRealizationLineageSegmentUpdateOne) Save(ctx context.Context) (*CreditRealizationLineageSegment, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *CreditRealizationLineageSegmentUpdateOne) SaveX(ctx context.Context) *CreditRealizationLineageSegment { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *CreditRealizationLineageSegmentUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *CreditRealizationLineageSegmentUpdateOne) 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 *CreditRealizationLineageSegmentUpdateOne) check() error { + if v, ok := _u.mutation.BackingTransactionGroupID(); ok { + if err := creditrealizationlineagesegment.BackingTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "backing_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "CreditRealizationLineageSegment.backing_transaction_group_id": %w`, err)} + } + } + if v, ok := _u.mutation.SourceState(); ok { + if err := creditrealizationlineagesegment.SourceStateValidator(v); err != nil { + return &ValidationError{Name: "source_state", err: fmt.Errorf(`db: validator failed for field "CreditRealizationLineageSegment.source_state": %w`, err)} + } + } + if v, ok := _u.mutation.SourceBackingTransactionGroupID(); ok { + if err := creditrealizationlineagesegment.SourceBackingTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "source_backing_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "CreditRealizationLineageSegment.source_backing_transaction_group_id": %w`, err)} + } + } + if _u.mutation.LineageCleared() && len(_u.mutation.LineageIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "CreditRealizationLineageSegment.lineage"`) + } + return nil +} + +func (_u *CreditRealizationLineageSegmentUpdateOne) sqlSave(ctx context.Context) (_node *CreditRealizationLineageSegment, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(creditrealizationlineagesegment.Table, creditrealizationlineagesegment.Columns, sqlgraph.NewFieldSpec(creditrealizationlineagesegment.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "CreditRealizationLineageSegment.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, creditrealizationlineagesegment.FieldID) + for _, f := range fields { + if !creditrealizationlineagesegment.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != creditrealizationlineagesegment.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.Amount(); ok { + _spec.SetField(creditrealizationlineagesegment.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.BackingTransactionGroupID(); ok { + _spec.SetField(creditrealizationlineagesegment.FieldBackingTransactionGroupID, field.TypeString, value) + } + if _u.mutation.BackingTransactionGroupIDCleared() { + _spec.ClearField(creditrealizationlineagesegment.FieldBackingTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.SourceState(); ok { + _spec.SetField(creditrealizationlineagesegment.FieldSourceState, field.TypeEnum, value) + } + if _u.mutation.SourceStateCleared() { + _spec.ClearField(creditrealizationlineagesegment.FieldSourceState, field.TypeEnum) + } + if value, ok := _u.mutation.SourceBackingTransactionGroupID(); ok { + _spec.SetField(creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID, field.TypeString, value) + } + if _u.mutation.SourceBackingTransactionGroupIDCleared() { + _spec.ClearField(creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.ClosedAt(); ok { + _spec.SetField(creditrealizationlineagesegment.FieldClosedAt, field.TypeTime, value) + } + if _u.mutation.ClosedAtCleared() { + _spec.ClearField(creditrealizationlineagesegment.FieldClosedAt, field.TypeTime) + } + _node = &CreditRealizationLineageSegment{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{creditrealizationlineagesegment.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/ent/db/currencycostbasis.go b/ent/db/currencycostbasis.go new file mode 100644 index 0000000000000000000000000000000000000000..786bb0f224d409113e3edf284628607e200e28ca --- /dev/null +++ b/ent/db/currencycostbasis.go @@ -0,0 +1,231 @@ +// 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/ent/db/currencycostbasis" + "github.com/openmeterio/openmeter/openmeter/ent/db/customcurrency" + "github.com/openmeterio/openmeter/pkg/currencyx" +) + +// CurrencyCostBasis is the model entity for the CurrencyCostBasis schema. +type CurrencyCostBasis 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"` + // CurrencyID holds the value of the "currency_id" field. + CurrencyID string `json:"currency_id,omitempty"` + // FiatCode holds the value of the "fiat_code" field. + FiatCode currencyx.Code `json:"fiat_code,omitempty"` + // Rate holds the value of the "rate" field. + Rate alpacadecimal.Decimal `json:"rate,omitempty"` + // EffectiveFrom holds the value of the "effective_from" field. + EffectiveFrom time.Time `json:"effective_from,omitempty"` + // EffectiveTo holds the value of the "effective_to" field. + EffectiveTo *time.Time `json:"effective_to,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the CurrencyCostBasisQuery when eager-loading is set. + Edges CurrencyCostBasisEdges `json:"edges"` + selectValues sql.SelectValues +} + +// CurrencyCostBasisEdges holds the relations/edges for other nodes in the graph. +type CurrencyCostBasisEdges struct { + // Currency holds the value of the currency edge. + Currency *CustomCurrency `json:"currency,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// CurrencyOrErr returns the Currency value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e CurrencyCostBasisEdges) CurrencyOrErr() (*CustomCurrency, error) { + if e.Currency != nil { + return e.Currency, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: customcurrency.Label} + } + return nil, &NotLoadedError{edge: "currency"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*CurrencyCostBasis) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case currencycostbasis.FieldRate: + values[i] = new(alpacadecimal.Decimal) + case currencycostbasis.FieldID, currencycostbasis.FieldNamespace, currencycostbasis.FieldCurrencyID, currencycostbasis.FieldFiatCode: + values[i] = new(sql.NullString) + case currencycostbasis.FieldCreatedAt, currencycostbasis.FieldUpdatedAt, currencycostbasis.FieldDeletedAt, currencycostbasis.FieldEffectiveFrom, currencycostbasis.FieldEffectiveTo: + 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 CurrencyCostBasis fields. +func (_m *CurrencyCostBasis) 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 currencycostbasis.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 currencycostbasis.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 currencycostbasis.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 currencycostbasis.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 currencycostbasis.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 currencycostbasis.FieldCurrencyID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field currency_id", values[i]) + } else if value.Valid { + _m.CurrencyID = value.String + } + case currencycostbasis.FieldFiatCode: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field fiat_code", values[i]) + } else if value.Valid { + _m.FiatCode = currencyx.Code(value.String) + } + case currencycostbasis.FieldRate: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field rate", values[i]) + } else if value != nil { + _m.Rate = *value + } + case currencycostbasis.FieldEffectiveFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field effective_from", values[i]) + } else if value.Valid { + _m.EffectiveFrom = value.Time + } + case currencycostbasis.FieldEffectiveTo: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field effective_to", values[i]) + } else if value.Valid { + _m.EffectiveTo = new(time.Time) + *_m.EffectiveTo = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the CurrencyCostBasis. +// This includes values selected through modifiers, order, etc. +func (_m *CurrencyCostBasis) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryCurrency queries the "currency" edge of the CurrencyCostBasis entity. +func (_m *CurrencyCostBasis) QueryCurrency() *CustomCurrencyQuery { + return NewCurrencyCostBasisClient(_m.config).QueryCurrency(_m) +} + +// Update returns a builder for updating this CurrencyCostBasis. +// Note that you need to call CurrencyCostBasis.Unwrap() before calling this method if this CurrencyCostBasis +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *CurrencyCostBasis) Update() *CurrencyCostBasisUpdateOne { + return NewCurrencyCostBasisClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the CurrencyCostBasis 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 *CurrencyCostBasis) Unwrap() *CurrencyCostBasis { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: CurrencyCostBasis is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *CurrencyCostBasis) String() string { + var builder strings.Builder + builder.WriteString("CurrencyCostBasis(") + 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("currency_id=") + builder.WriteString(_m.CurrencyID) + builder.WriteString(", ") + builder.WriteString("fiat_code=") + builder.WriteString(fmt.Sprintf("%v", _m.FiatCode)) + builder.WriteString(", ") + builder.WriteString("rate=") + builder.WriteString(fmt.Sprintf("%v", _m.Rate)) + builder.WriteString(", ") + builder.WriteString("effective_from=") + builder.WriteString(_m.EffectiveFrom.Format(time.ANSIC)) + builder.WriteString(", ") + if v := _m.EffectiveTo; v != nil { + builder.WriteString("effective_to=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteByte(')') + return builder.String() +} + +// CurrencyCostBases is a parsable slice of CurrencyCostBasis. +type CurrencyCostBases []*CurrencyCostBasis diff --git a/ent/db/currencycostbasis/currencycostbasis.go b/ent/db/currencycostbasis/currencycostbasis.go new file mode 100644 index 0000000000000000000000000000000000000000..2420172ebc314488cd03d5513c2140cef78794a0 --- /dev/null +++ b/ent/db/currencycostbasis/currencycostbasis.go @@ -0,0 +1,152 @@ +// Code generated by ent, DO NOT EDIT. + +package currencycostbasis + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the currencycostbasis type in the database. + Label = "currency_cost_basis" + // 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" + // FieldCurrencyID holds the string denoting the currency_id field in the database. + FieldCurrencyID = "currency_id" + // FieldFiatCode holds the string denoting the fiat_code field in the database. + FieldFiatCode = "fiat_code" + // FieldRate holds the string denoting the rate field in the database. + FieldRate = "rate" + // FieldEffectiveFrom holds the string denoting the effective_from field in the database. + FieldEffectiveFrom = "effective_from" + // FieldEffectiveTo holds the string denoting the effective_to field in the database. + FieldEffectiveTo = "effective_to" + // EdgeCurrency holds the string denoting the currency edge name in mutations. + EdgeCurrency = "currency" + // Table holds the table name of the currencycostbasis in the database. + Table = "currency_cost_bases" + // CurrencyTable is the table that holds the currency relation/edge. + CurrencyTable = "currency_cost_bases" + // CurrencyInverseTable is the table name for the CustomCurrency entity. + // It exists in this package in order to avoid circular dependency with the "customcurrency" package. + CurrencyInverseTable = "custom_currencies" + // CurrencyColumn is the table column denoting the currency relation/edge. + CurrencyColumn = "currency_id" +) + +// Columns holds all SQL columns for currencycostbasis fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldCurrencyID, + FieldFiatCode, + FieldRate, + FieldEffectiveFrom, + FieldEffectiveTo, +} + +// 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 + // FiatCodeValidator is a validator for the "fiat_code" field. It is called by the builders before save. + FiatCodeValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// OrderOption defines the ordering options for the CurrencyCostBasis 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() +} + +// ByCurrencyID orders the results by the currency_id field. +func ByCurrencyID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCurrencyID, opts...).ToFunc() +} + +// ByFiatCode orders the results by the fiat_code field. +func ByFiatCode(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFiatCode, opts...).ToFunc() +} + +// ByRate orders the results by the rate field. +func ByRate(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRate, opts...).ToFunc() +} + +// ByEffectiveFrom orders the results by the effective_from field. +func ByEffectiveFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEffectiveFrom, opts...).ToFunc() +} + +// ByEffectiveTo orders the results by the effective_to field. +func ByEffectiveTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEffectiveTo, opts...).ToFunc() +} + +// ByCurrencyField orders the results by currency field. +func ByCurrencyField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCurrencyStep(), sql.OrderByField(field, opts...)) + } +} +func newCurrencyStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CurrencyInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, CurrencyTable, CurrencyColumn), + ) +} diff --git a/ent/db/currencycostbasis/where.go b/ent/db/currencycostbasis/where.go new file mode 100644 index 0000000000000000000000000000000000000000..cbb673efd3325b8f2a801505436dc149f6b48d6c --- /dev/null +++ b/ent/db/currencycostbasis/where.go @@ -0,0 +1,626 @@ +// Code generated by ent, DO NOT EDIT. + +package currencycostbasis + +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" + "github.com/openmeterio/openmeter/pkg/currencyx" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(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.CurrencyCostBasis { + return predicate.CurrencyCostBasis(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.CurrencyCostBasis { + return predicate.CurrencyCostBasis(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.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldEQ(FieldDeletedAt, v)) +} + +// CurrencyID applies equality check predicate on the "currency_id" field. It's identical to CurrencyIDEQ. +func CurrencyID(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldEQ(FieldCurrencyID, v)) +} + +// FiatCode applies equality check predicate on the "fiat_code" field. It's identical to FiatCodeEQ. +func FiatCode(v currencyx.Code) predicate.CurrencyCostBasis { + vc := string(v) + return predicate.CurrencyCostBasis(sql.FieldEQ(FieldFiatCode, vc)) +} + +// Rate applies equality check predicate on the "rate" field. It's identical to RateEQ. +func Rate(v alpacadecimal.Decimal) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldEQ(FieldRate, v)) +} + +// EffectiveFrom applies equality check predicate on the "effective_from" field. It's identical to EffectiveFromEQ. +func EffectiveFrom(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldEQ(FieldEffectiveFrom, v)) +} + +// EffectiveTo applies equality check predicate on the "effective_to" field. It's identical to EffectiveToEQ. +func EffectiveTo(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldEQ(FieldEffectiveTo, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldNotNull(FieldDeletedAt)) +} + +// CurrencyIDEQ applies the EQ predicate on the "currency_id" field. +func CurrencyIDEQ(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldEQ(FieldCurrencyID, v)) +} + +// CurrencyIDNEQ applies the NEQ predicate on the "currency_id" field. +func CurrencyIDNEQ(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldNEQ(FieldCurrencyID, v)) +} + +// CurrencyIDIn applies the In predicate on the "currency_id" field. +func CurrencyIDIn(vs ...string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldIn(FieldCurrencyID, vs...)) +} + +// CurrencyIDNotIn applies the NotIn predicate on the "currency_id" field. +func CurrencyIDNotIn(vs ...string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldNotIn(FieldCurrencyID, vs...)) +} + +// CurrencyIDGT applies the GT predicate on the "currency_id" field. +func CurrencyIDGT(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldGT(FieldCurrencyID, v)) +} + +// CurrencyIDGTE applies the GTE predicate on the "currency_id" field. +func CurrencyIDGTE(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldGTE(FieldCurrencyID, v)) +} + +// CurrencyIDLT applies the LT predicate on the "currency_id" field. +func CurrencyIDLT(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldLT(FieldCurrencyID, v)) +} + +// CurrencyIDLTE applies the LTE predicate on the "currency_id" field. +func CurrencyIDLTE(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldLTE(FieldCurrencyID, v)) +} + +// CurrencyIDContains applies the Contains predicate on the "currency_id" field. +func CurrencyIDContains(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldContains(FieldCurrencyID, v)) +} + +// CurrencyIDHasPrefix applies the HasPrefix predicate on the "currency_id" field. +func CurrencyIDHasPrefix(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldHasPrefix(FieldCurrencyID, v)) +} + +// CurrencyIDHasSuffix applies the HasSuffix predicate on the "currency_id" field. +func CurrencyIDHasSuffix(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldHasSuffix(FieldCurrencyID, v)) +} + +// CurrencyIDEqualFold applies the EqualFold predicate on the "currency_id" field. +func CurrencyIDEqualFold(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldEqualFold(FieldCurrencyID, v)) +} + +// CurrencyIDContainsFold applies the ContainsFold predicate on the "currency_id" field. +func CurrencyIDContainsFold(v string) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldContainsFold(FieldCurrencyID, v)) +} + +// FiatCodeEQ applies the EQ predicate on the "fiat_code" field. +func FiatCodeEQ(v currencyx.Code) predicate.CurrencyCostBasis { + vc := string(v) + return predicate.CurrencyCostBasis(sql.FieldEQ(FieldFiatCode, vc)) +} + +// FiatCodeNEQ applies the NEQ predicate on the "fiat_code" field. +func FiatCodeNEQ(v currencyx.Code) predicate.CurrencyCostBasis { + vc := string(v) + return predicate.CurrencyCostBasis(sql.FieldNEQ(FieldFiatCode, vc)) +} + +// FiatCodeIn applies the In predicate on the "fiat_code" field. +func FiatCodeIn(vs ...currencyx.Code) predicate.CurrencyCostBasis { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.CurrencyCostBasis(sql.FieldIn(FieldFiatCode, v...)) +} + +// FiatCodeNotIn applies the NotIn predicate on the "fiat_code" field. +func FiatCodeNotIn(vs ...currencyx.Code) predicate.CurrencyCostBasis { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.CurrencyCostBasis(sql.FieldNotIn(FieldFiatCode, v...)) +} + +// FiatCodeGT applies the GT predicate on the "fiat_code" field. +func FiatCodeGT(v currencyx.Code) predicate.CurrencyCostBasis { + vc := string(v) + return predicate.CurrencyCostBasis(sql.FieldGT(FieldFiatCode, vc)) +} + +// FiatCodeGTE applies the GTE predicate on the "fiat_code" field. +func FiatCodeGTE(v currencyx.Code) predicate.CurrencyCostBasis { + vc := string(v) + return predicate.CurrencyCostBasis(sql.FieldGTE(FieldFiatCode, vc)) +} + +// FiatCodeLT applies the LT predicate on the "fiat_code" field. +func FiatCodeLT(v currencyx.Code) predicate.CurrencyCostBasis { + vc := string(v) + return predicate.CurrencyCostBasis(sql.FieldLT(FieldFiatCode, vc)) +} + +// FiatCodeLTE applies the LTE predicate on the "fiat_code" field. +func FiatCodeLTE(v currencyx.Code) predicate.CurrencyCostBasis { + vc := string(v) + return predicate.CurrencyCostBasis(sql.FieldLTE(FieldFiatCode, vc)) +} + +// FiatCodeContains applies the Contains predicate on the "fiat_code" field. +func FiatCodeContains(v currencyx.Code) predicate.CurrencyCostBasis { + vc := string(v) + return predicate.CurrencyCostBasis(sql.FieldContains(FieldFiatCode, vc)) +} + +// FiatCodeHasPrefix applies the HasPrefix predicate on the "fiat_code" field. +func FiatCodeHasPrefix(v currencyx.Code) predicate.CurrencyCostBasis { + vc := string(v) + return predicate.CurrencyCostBasis(sql.FieldHasPrefix(FieldFiatCode, vc)) +} + +// FiatCodeHasSuffix applies the HasSuffix predicate on the "fiat_code" field. +func FiatCodeHasSuffix(v currencyx.Code) predicate.CurrencyCostBasis { + vc := string(v) + return predicate.CurrencyCostBasis(sql.FieldHasSuffix(FieldFiatCode, vc)) +} + +// FiatCodeEqualFold applies the EqualFold predicate on the "fiat_code" field. +func FiatCodeEqualFold(v currencyx.Code) predicate.CurrencyCostBasis { + vc := string(v) + return predicate.CurrencyCostBasis(sql.FieldEqualFold(FieldFiatCode, vc)) +} + +// FiatCodeContainsFold applies the ContainsFold predicate on the "fiat_code" field. +func FiatCodeContainsFold(v currencyx.Code) predicate.CurrencyCostBasis { + vc := string(v) + return predicate.CurrencyCostBasis(sql.FieldContainsFold(FieldFiatCode, vc)) +} + +// RateEQ applies the EQ predicate on the "rate" field. +func RateEQ(v alpacadecimal.Decimal) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldEQ(FieldRate, v)) +} + +// RateNEQ applies the NEQ predicate on the "rate" field. +func RateNEQ(v alpacadecimal.Decimal) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldNEQ(FieldRate, v)) +} + +// RateIn applies the In predicate on the "rate" field. +func RateIn(vs ...alpacadecimal.Decimal) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldIn(FieldRate, vs...)) +} + +// RateNotIn applies the NotIn predicate on the "rate" field. +func RateNotIn(vs ...alpacadecimal.Decimal) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldNotIn(FieldRate, vs...)) +} + +// RateGT applies the GT predicate on the "rate" field. +func RateGT(v alpacadecimal.Decimal) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldGT(FieldRate, v)) +} + +// RateGTE applies the GTE predicate on the "rate" field. +func RateGTE(v alpacadecimal.Decimal) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldGTE(FieldRate, v)) +} + +// RateLT applies the LT predicate on the "rate" field. +func RateLT(v alpacadecimal.Decimal) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldLT(FieldRate, v)) +} + +// RateLTE applies the LTE predicate on the "rate" field. +func RateLTE(v alpacadecimal.Decimal) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldLTE(FieldRate, v)) +} + +// EffectiveFromEQ applies the EQ predicate on the "effective_from" field. +func EffectiveFromEQ(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldEQ(FieldEffectiveFrom, v)) +} + +// EffectiveFromNEQ applies the NEQ predicate on the "effective_from" field. +func EffectiveFromNEQ(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldNEQ(FieldEffectiveFrom, v)) +} + +// EffectiveFromIn applies the In predicate on the "effective_from" field. +func EffectiveFromIn(vs ...time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldIn(FieldEffectiveFrom, vs...)) +} + +// EffectiveFromNotIn applies the NotIn predicate on the "effective_from" field. +func EffectiveFromNotIn(vs ...time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldNotIn(FieldEffectiveFrom, vs...)) +} + +// EffectiveFromGT applies the GT predicate on the "effective_from" field. +func EffectiveFromGT(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldGT(FieldEffectiveFrom, v)) +} + +// EffectiveFromGTE applies the GTE predicate on the "effective_from" field. +func EffectiveFromGTE(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldGTE(FieldEffectiveFrom, v)) +} + +// EffectiveFromLT applies the LT predicate on the "effective_from" field. +func EffectiveFromLT(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldLT(FieldEffectiveFrom, v)) +} + +// EffectiveFromLTE applies the LTE predicate on the "effective_from" field. +func EffectiveFromLTE(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldLTE(FieldEffectiveFrom, v)) +} + +// EffectiveToEQ applies the EQ predicate on the "effective_to" field. +func EffectiveToEQ(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldEQ(FieldEffectiveTo, v)) +} + +// EffectiveToNEQ applies the NEQ predicate on the "effective_to" field. +func EffectiveToNEQ(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldNEQ(FieldEffectiveTo, v)) +} + +// EffectiveToIn applies the In predicate on the "effective_to" field. +func EffectiveToIn(vs ...time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldIn(FieldEffectiveTo, vs...)) +} + +// EffectiveToNotIn applies the NotIn predicate on the "effective_to" field. +func EffectiveToNotIn(vs ...time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldNotIn(FieldEffectiveTo, vs...)) +} + +// EffectiveToGT applies the GT predicate on the "effective_to" field. +func EffectiveToGT(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldGT(FieldEffectiveTo, v)) +} + +// EffectiveToGTE applies the GTE predicate on the "effective_to" field. +func EffectiveToGTE(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldGTE(FieldEffectiveTo, v)) +} + +// EffectiveToLT applies the LT predicate on the "effective_to" field. +func EffectiveToLT(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldLT(FieldEffectiveTo, v)) +} + +// EffectiveToLTE applies the LTE predicate on the "effective_to" field. +func EffectiveToLTE(v time.Time) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldLTE(FieldEffectiveTo, v)) +} + +// EffectiveToIsNil applies the IsNil predicate on the "effective_to" field. +func EffectiveToIsNil() predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldIsNull(FieldEffectiveTo)) +} + +// EffectiveToNotNil applies the NotNil predicate on the "effective_to" field. +func EffectiveToNotNil() predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.FieldNotNull(FieldEffectiveTo)) +} + +// HasCurrency applies the HasEdge predicate on the "currency" edge. +func HasCurrency() predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, CurrencyTable, CurrencyColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCurrencyWith applies the HasEdge predicate on the "currency" edge with a given conditions (other predicates). +func HasCurrencyWith(preds ...predicate.CustomCurrency) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(func(s *sql.Selector) { + step := newCurrencyStep() + 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.CurrencyCostBasis) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.CurrencyCostBasis) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.CurrencyCostBasis) predicate.CurrencyCostBasis { + return predicate.CurrencyCostBasis(sql.NotPredicates(p)) +} diff --git a/ent/db/currencycostbasis_create.go b/ent/db/currencycostbasis_create.go new file mode 100644 index 0000000000000000000000000000000000000000..98ba67b7c0354343ea55de8e04534565615fda46 --- /dev/null +++ b/ent/db/currencycostbasis_create.go @@ -0,0 +1,782 @@ +// 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/currencycostbasis" + "github.com/openmeterio/openmeter/openmeter/ent/db/customcurrency" + "github.com/openmeterio/openmeter/pkg/currencyx" +) + +// CurrencyCostBasisCreate is the builder for creating a CurrencyCostBasis entity. +type CurrencyCostBasisCreate struct { + config + mutation *CurrencyCostBasisMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *CurrencyCostBasisCreate) SetNamespace(v string) *CurrencyCostBasisCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *CurrencyCostBasisCreate) SetCreatedAt(v time.Time) *CurrencyCostBasisCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *CurrencyCostBasisCreate) SetNillableCreatedAt(v *time.Time) *CurrencyCostBasisCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *CurrencyCostBasisCreate) SetUpdatedAt(v time.Time) *CurrencyCostBasisCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *CurrencyCostBasisCreate) SetNillableUpdatedAt(v *time.Time) *CurrencyCostBasisCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *CurrencyCostBasisCreate) SetDeletedAt(v time.Time) *CurrencyCostBasisCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *CurrencyCostBasisCreate) SetNillableDeletedAt(v *time.Time) *CurrencyCostBasisCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetCurrencyID sets the "currency_id" field. +func (_c *CurrencyCostBasisCreate) SetCurrencyID(v string) *CurrencyCostBasisCreate { + _c.mutation.SetCurrencyID(v) + return _c +} + +// SetFiatCode sets the "fiat_code" field. +func (_c *CurrencyCostBasisCreate) SetFiatCode(v currencyx.Code) *CurrencyCostBasisCreate { + _c.mutation.SetFiatCode(v) + return _c +} + +// SetRate sets the "rate" field. +func (_c *CurrencyCostBasisCreate) SetRate(v alpacadecimal.Decimal) *CurrencyCostBasisCreate { + _c.mutation.SetRate(v) + return _c +} + +// SetEffectiveFrom sets the "effective_from" field. +func (_c *CurrencyCostBasisCreate) SetEffectiveFrom(v time.Time) *CurrencyCostBasisCreate { + _c.mutation.SetEffectiveFrom(v) + return _c +} + +// SetEffectiveTo sets the "effective_to" field. +func (_c *CurrencyCostBasisCreate) SetEffectiveTo(v time.Time) *CurrencyCostBasisCreate { + _c.mutation.SetEffectiveTo(v) + return _c +} + +// SetNillableEffectiveTo sets the "effective_to" field if the given value is not nil. +func (_c *CurrencyCostBasisCreate) SetNillableEffectiveTo(v *time.Time) *CurrencyCostBasisCreate { + if v != nil { + _c.SetEffectiveTo(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *CurrencyCostBasisCreate) SetID(v string) *CurrencyCostBasisCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *CurrencyCostBasisCreate) SetNillableID(v *string) *CurrencyCostBasisCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetCurrency sets the "currency" edge to the CustomCurrency entity. +func (_c *CurrencyCostBasisCreate) SetCurrency(v *CustomCurrency) *CurrencyCostBasisCreate { + return _c.SetCurrencyID(v.ID) +} + +// Mutation returns the CurrencyCostBasisMutation object of the builder. +func (_c *CurrencyCostBasisCreate) Mutation() *CurrencyCostBasisMutation { + return _c.mutation +} + +// Save creates the CurrencyCostBasis in the database. +func (_c *CurrencyCostBasisCreate) Save(ctx context.Context) (*CurrencyCostBasis, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *CurrencyCostBasisCreate) SaveX(ctx context.Context) *CurrencyCostBasis { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *CurrencyCostBasisCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *CurrencyCostBasisCreate) 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 *CurrencyCostBasisCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := currencycostbasis.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := currencycostbasis.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := currencycostbasis.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *CurrencyCostBasisCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "CurrencyCostBasis.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := currencycostbasis.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "CurrencyCostBasis.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "CurrencyCostBasis.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "CurrencyCostBasis.updated_at"`)} + } + if _, ok := _c.mutation.CurrencyID(); !ok { + return &ValidationError{Name: "currency_id", err: errors.New(`db: missing required field "CurrencyCostBasis.currency_id"`)} + } + if _, ok := _c.mutation.FiatCode(); !ok { + return &ValidationError{Name: "fiat_code", err: errors.New(`db: missing required field "CurrencyCostBasis.fiat_code"`)} + } + if v, ok := _c.mutation.FiatCode(); ok { + if err := currencycostbasis.FiatCodeValidator(string(v)); err != nil { + return &ValidationError{Name: "fiat_code", err: fmt.Errorf(`db: validator failed for field "CurrencyCostBasis.fiat_code": %w`, err)} + } + } + if _, ok := _c.mutation.Rate(); !ok { + return &ValidationError{Name: "rate", err: errors.New(`db: missing required field "CurrencyCostBasis.rate"`)} + } + if _, ok := _c.mutation.EffectiveFrom(); !ok { + return &ValidationError{Name: "effective_from", err: errors.New(`db: missing required field "CurrencyCostBasis.effective_from"`)} + } + if len(_c.mutation.CurrencyIDs()) == 0 { + return &ValidationError{Name: "currency", err: errors.New(`db: missing required edge "CurrencyCostBasis.currency"`)} + } + return nil +} + +func (_c *CurrencyCostBasisCreate) sqlSave(ctx context.Context) (*CurrencyCostBasis, 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 CurrencyCostBasis.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *CurrencyCostBasisCreate) createSpec() (*CurrencyCostBasis, *sqlgraph.CreateSpec) { + var ( + _node = &CurrencyCostBasis{config: _c.config} + _spec = sqlgraph.NewCreateSpec(currencycostbasis.Table, sqlgraph.NewFieldSpec(currencycostbasis.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(currencycostbasis.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(currencycostbasis.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(currencycostbasis.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(currencycostbasis.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.FiatCode(); ok { + _spec.SetField(currencycostbasis.FieldFiatCode, field.TypeString, value) + _node.FiatCode = value + } + if value, ok := _c.mutation.Rate(); ok { + _spec.SetField(currencycostbasis.FieldRate, field.TypeOther, value) + _node.Rate = value + } + if value, ok := _c.mutation.EffectiveFrom(); ok { + _spec.SetField(currencycostbasis.FieldEffectiveFrom, field.TypeTime, value) + _node.EffectiveFrom = value + } + if value, ok := _c.mutation.EffectiveTo(); ok { + _spec.SetField(currencycostbasis.FieldEffectiveTo, field.TypeTime, value) + _node.EffectiveTo = &value + } + if nodes := _c.mutation.CurrencyIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: currencycostbasis.CurrencyTable, + Columns: []string{currencycostbasis.CurrencyColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(customcurrency.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.CurrencyID = 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.CurrencyCostBasis.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.CurrencyCostBasisUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *CurrencyCostBasisCreate) OnConflict(opts ...sql.ConflictOption) *CurrencyCostBasisUpsertOne { + _c.conflict = opts + return &CurrencyCostBasisUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.CurrencyCostBasis.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *CurrencyCostBasisCreate) OnConflictColumns(columns ...string) *CurrencyCostBasisUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &CurrencyCostBasisUpsertOne{ + create: _c, + } +} + +type ( + // CurrencyCostBasisUpsertOne is the builder for "upsert"-ing + // one CurrencyCostBasis node. + CurrencyCostBasisUpsertOne struct { + create *CurrencyCostBasisCreate + } + + // CurrencyCostBasisUpsert is the "OnConflict" setter. + CurrencyCostBasisUpsert struct { + *sql.UpdateSet + } +) + +// SetUpdatedAt sets the "updated_at" field. +func (u *CurrencyCostBasisUpsert) SetUpdatedAt(v time.Time) *CurrencyCostBasisUpsert { + u.Set(currencycostbasis.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *CurrencyCostBasisUpsert) UpdateUpdatedAt() *CurrencyCostBasisUpsert { + u.SetExcluded(currencycostbasis.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *CurrencyCostBasisUpsert) SetDeletedAt(v time.Time) *CurrencyCostBasisUpsert { + u.Set(currencycostbasis.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *CurrencyCostBasisUpsert) UpdateDeletedAt() *CurrencyCostBasisUpsert { + u.SetExcluded(currencycostbasis.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *CurrencyCostBasisUpsert) ClearDeletedAt() *CurrencyCostBasisUpsert { + u.SetNull(currencycostbasis.FieldDeletedAt) + 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.CurrencyCostBasis.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(currencycostbasis.FieldID) +// }), +// ). +// Exec(ctx) +func (u *CurrencyCostBasisUpsertOne) UpdateNewValues() *CurrencyCostBasisUpsertOne { + 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(currencycostbasis.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(currencycostbasis.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(currencycostbasis.FieldCreatedAt) + } + if _, exists := u.create.mutation.CurrencyID(); exists { + s.SetIgnore(currencycostbasis.FieldCurrencyID) + } + if _, exists := u.create.mutation.FiatCode(); exists { + s.SetIgnore(currencycostbasis.FieldFiatCode) + } + if _, exists := u.create.mutation.Rate(); exists { + s.SetIgnore(currencycostbasis.FieldRate) + } + if _, exists := u.create.mutation.EffectiveFrom(); exists { + s.SetIgnore(currencycostbasis.FieldEffectiveFrom) + } + if _, exists := u.create.mutation.EffectiveTo(); exists { + s.SetIgnore(currencycostbasis.FieldEffectiveTo) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.CurrencyCostBasis.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *CurrencyCostBasisUpsertOne) Ignore() *CurrencyCostBasisUpsertOne { + 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 *CurrencyCostBasisUpsertOne) DoNothing() *CurrencyCostBasisUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the CurrencyCostBasisCreate.OnConflict +// documentation for more info. +func (u *CurrencyCostBasisUpsertOne) Update(set func(*CurrencyCostBasisUpsert)) *CurrencyCostBasisUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&CurrencyCostBasisUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *CurrencyCostBasisUpsertOne) SetUpdatedAt(v time.Time) *CurrencyCostBasisUpsertOne { + return u.Update(func(s *CurrencyCostBasisUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *CurrencyCostBasisUpsertOne) UpdateUpdatedAt() *CurrencyCostBasisUpsertOne { + return u.Update(func(s *CurrencyCostBasisUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *CurrencyCostBasisUpsertOne) SetDeletedAt(v time.Time) *CurrencyCostBasisUpsertOne { + return u.Update(func(s *CurrencyCostBasisUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *CurrencyCostBasisUpsertOne) UpdateDeletedAt() *CurrencyCostBasisUpsertOne { + return u.Update(func(s *CurrencyCostBasisUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *CurrencyCostBasisUpsertOne) ClearDeletedAt() *CurrencyCostBasisUpsertOne { + return u.Update(func(s *CurrencyCostBasisUpsert) { + s.ClearDeletedAt() + }) +} + +// Exec executes the query. +func (u *CurrencyCostBasisUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for CurrencyCostBasisCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *CurrencyCostBasisUpsertOne) 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 *CurrencyCostBasisUpsertOne) 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: CurrencyCostBasisUpsertOne.ID is not supported by MySQL driver. Use CurrencyCostBasisUpsertOne.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 *CurrencyCostBasisUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// CurrencyCostBasisCreateBulk is the builder for creating many CurrencyCostBasis entities in bulk. +type CurrencyCostBasisCreateBulk struct { + config + err error + builders []*CurrencyCostBasisCreate + conflict []sql.ConflictOption +} + +// Save creates the CurrencyCostBasis entities in the database. +func (_c *CurrencyCostBasisCreateBulk) Save(ctx context.Context) ([]*CurrencyCostBasis, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*CurrencyCostBasis, 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.(*CurrencyCostBasisMutation) + 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 *CurrencyCostBasisCreateBulk) SaveX(ctx context.Context) []*CurrencyCostBasis { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *CurrencyCostBasisCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *CurrencyCostBasisCreateBulk) 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.CurrencyCostBasis.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.CurrencyCostBasisUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *CurrencyCostBasisCreateBulk) OnConflict(opts ...sql.ConflictOption) *CurrencyCostBasisUpsertBulk { + _c.conflict = opts + return &CurrencyCostBasisUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.CurrencyCostBasis.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *CurrencyCostBasisCreateBulk) OnConflictColumns(columns ...string) *CurrencyCostBasisUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &CurrencyCostBasisUpsertBulk{ + create: _c, + } +} + +// CurrencyCostBasisUpsertBulk is the builder for "upsert"-ing +// a bulk of CurrencyCostBasis nodes. +type CurrencyCostBasisUpsertBulk struct { + create *CurrencyCostBasisCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.CurrencyCostBasis.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(currencycostbasis.FieldID) +// }), +// ). +// Exec(ctx) +func (u *CurrencyCostBasisUpsertBulk) UpdateNewValues() *CurrencyCostBasisUpsertBulk { + 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(currencycostbasis.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(currencycostbasis.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(currencycostbasis.FieldCreatedAt) + } + if _, exists := b.mutation.CurrencyID(); exists { + s.SetIgnore(currencycostbasis.FieldCurrencyID) + } + if _, exists := b.mutation.FiatCode(); exists { + s.SetIgnore(currencycostbasis.FieldFiatCode) + } + if _, exists := b.mutation.Rate(); exists { + s.SetIgnore(currencycostbasis.FieldRate) + } + if _, exists := b.mutation.EffectiveFrom(); exists { + s.SetIgnore(currencycostbasis.FieldEffectiveFrom) + } + if _, exists := b.mutation.EffectiveTo(); exists { + s.SetIgnore(currencycostbasis.FieldEffectiveTo) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.CurrencyCostBasis.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *CurrencyCostBasisUpsertBulk) Ignore() *CurrencyCostBasisUpsertBulk { + 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 *CurrencyCostBasisUpsertBulk) DoNothing() *CurrencyCostBasisUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the CurrencyCostBasisCreateBulk.OnConflict +// documentation for more info. +func (u *CurrencyCostBasisUpsertBulk) Update(set func(*CurrencyCostBasisUpsert)) *CurrencyCostBasisUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&CurrencyCostBasisUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *CurrencyCostBasisUpsertBulk) SetUpdatedAt(v time.Time) *CurrencyCostBasisUpsertBulk { + return u.Update(func(s *CurrencyCostBasisUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *CurrencyCostBasisUpsertBulk) UpdateUpdatedAt() *CurrencyCostBasisUpsertBulk { + return u.Update(func(s *CurrencyCostBasisUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *CurrencyCostBasisUpsertBulk) SetDeletedAt(v time.Time) *CurrencyCostBasisUpsertBulk { + return u.Update(func(s *CurrencyCostBasisUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *CurrencyCostBasisUpsertBulk) UpdateDeletedAt() *CurrencyCostBasisUpsertBulk { + return u.Update(func(s *CurrencyCostBasisUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *CurrencyCostBasisUpsertBulk) ClearDeletedAt() *CurrencyCostBasisUpsertBulk { + return u.Update(func(s *CurrencyCostBasisUpsert) { + s.ClearDeletedAt() + }) +} + +// Exec executes the query. +func (u *CurrencyCostBasisUpsertBulk) 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 CurrencyCostBasisCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for CurrencyCostBasisCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *CurrencyCostBasisUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/currencycostbasis_delete.go b/ent/db/currencycostbasis_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..6219c25c272a6dad37f8077dae90643046fe4871 --- /dev/null +++ b/ent/db/currencycostbasis_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/currencycostbasis" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// CurrencyCostBasisDelete is the builder for deleting a CurrencyCostBasis entity. +type CurrencyCostBasisDelete struct { + config + hooks []Hook + mutation *CurrencyCostBasisMutation +} + +// Where appends a list predicates to the CurrencyCostBasisDelete builder. +func (_d *CurrencyCostBasisDelete) Where(ps ...predicate.CurrencyCostBasis) *CurrencyCostBasisDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *CurrencyCostBasisDelete) 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 *CurrencyCostBasisDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *CurrencyCostBasisDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(currencycostbasis.Table, sqlgraph.NewFieldSpec(currencycostbasis.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 +} + +// CurrencyCostBasisDeleteOne is the builder for deleting a single CurrencyCostBasis entity. +type CurrencyCostBasisDeleteOne struct { + _d *CurrencyCostBasisDelete +} + +// Where appends a list predicates to the CurrencyCostBasisDelete builder. +func (_d *CurrencyCostBasisDeleteOne) Where(ps ...predicate.CurrencyCostBasis) *CurrencyCostBasisDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *CurrencyCostBasisDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{currencycostbasis.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *CurrencyCostBasisDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/currencycostbasis_query.go b/ent/db/currencycostbasis_query.go new file mode 100644 index 0000000000000000000000000000000000000000..ea1eb9c0cd307e524fc18c91a43e0c40de72647b --- /dev/null +++ b/ent/db/currencycostbasis_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/currencycostbasis" + "github.com/openmeterio/openmeter/openmeter/ent/db/customcurrency" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// CurrencyCostBasisQuery is the builder for querying CurrencyCostBasis entities. +type CurrencyCostBasisQuery struct { + config + ctx *QueryContext + order []currencycostbasis.OrderOption + inters []Interceptor + predicates []predicate.CurrencyCostBasis + withCurrency *CustomCurrencyQuery + 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 CurrencyCostBasisQuery builder. +func (_q *CurrencyCostBasisQuery) Where(ps ...predicate.CurrencyCostBasis) *CurrencyCostBasisQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *CurrencyCostBasisQuery) Limit(limit int) *CurrencyCostBasisQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *CurrencyCostBasisQuery) Offset(offset int) *CurrencyCostBasisQuery { + _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 *CurrencyCostBasisQuery) Unique(unique bool) *CurrencyCostBasisQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *CurrencyCostBasisQuery) Order(o ...currencycostbasis.OrderOption) *CurrencyCostBasisQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryCurrency chains the current query on the "currency" edge. +func (_q *CurrencyCostBasisQuery) QueryCurrency() *CustomCurrencyQuery { + query := (&CustomCurrencyClient{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(currencycostbasis.Table, currencycostbasis.FieldID, selector), + sqlgraph.To(customcurrency.Table, customcurrency.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, currencycostbasis.CurrencyTable, currencycostbasis.CurrencyColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first CurrencyCostBasis entity from the query. +// Returns a *NotFoundError when no CurrencyCostBasis was found. +func (_q *CurrencyCostBasisQuery) First(ctx context.Context) (*CurrencyCostBasis, 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{currencycostbasis.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *CurrencyCostBasisQuery) FirstX(ctx context.Context) *CurrencyCostBasis { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first CurrencyCostBasis ID from the query. +// Returns a *NotFoundError when no CurrencyCostBasis ID was found. +func (_q *CurrencyCostBasisQuery) 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{currencycostbasis.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *CurrencyCostBasisQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single CurrencyCostBasis entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one CurrencyCostBasis entity is found. +// Returns a *NotFoundError when no CurrencyCostBasis entities are found. +func (_q *CurrencyCostBasisQuery) Only(ctx context.Context) (*CurrencyCostBasis, 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{currencycostbasis.Label} + default: + return nil, &NotSingularError{currencycostbasis.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *CurrencyCostBasisQuery) OnlyX(ctx context.Context) *CurrencyCostBasis { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only CurrencyCostBasis ID in the query. +// Returns a *NotSingularError when more than one CurrencyCostBasis ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *CurrencyCostBasisQuery) 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{currencycostbasis.Label} + default: + err = &NotSingularError{currencycostbasis.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *CurrencyCostBasisQuery) 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 CurrencyCostBases. +func (_q *CurrencyCostBasisQuery) All(ctx context.Context) ([]*CurrencyCostBasis, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*CurrencyCostBasis, *CurrencyCostBasisQuery]() + return withInterceptors[[]*CurrencyCostBasis](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *CurrencyCostBasisQuery) AllX(ctx context.Context) []*CurrencyCostBasis { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of CurrencyCostBasis IDs. +func (_q *CurrencyCostBasisQuery) 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(currencycostbasis.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *CurrencyCostBasisQuery) 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 *CurrencyCostBasisQuery) 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[*CurrencyCostBasisQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *CurrencyCostBasisQuery) 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 *CurrencyCostBasisQuery) 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 *CurrencyCostBasisQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the CurrencyCostBasisQuery 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 *CurrencyCostBasisQuery) Clone() *CurrencyCostBasisQuery { + if _q == nil { + return nil + } + return &CurrencyCostBasisQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]currencycostbasis.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.CurrencyCostBasis{}, _q.predicates...), + withCurrency: _q.withCurrency.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithCurrency tells the query-builder to eager-load the nodes that are connected to +// the "currency" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *CurrencyCostBasisQuery) WithCurrency(opts ...func(*CustomCurrencyQuery)) *CurrencyCostBasisQuery { + query := (&CustomCurrencyClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCurrency = 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.CurrencyCostBasis.Query(). +// GroupBy(currencycostbasis.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *CurrencyCostBasisQuery) GroupBy(field string, fields ...string) *CurrencyCostBasisGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &CurrencyCostBasisGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = currencycostbasis.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.CurrencyCostBasis.Query(). +// Select(currencycostbasis.FieldNamespace). +// Scan(ctx, &v) +func (_q *CurrencyCostBasisQuery) Select(fields ...string) *CurrencyCostBasisSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &CurrencyCostBasisSelect{CurrencyCostBasisQuery: _q} + sbuild.label = currencycostbasis.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a CurrencyCostBasisSelect configured with the given aggregations. +func (_q *CurrencyCostBasisQuery) Aggregate(fns ...AggregateFunc) *CurrencyCostBasisSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *CurrencyCostBasisQuery) 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 !currencycostbasis.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 *CurrencyCostBasisQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*CurrencyCostBasis, error) { + var ( + nodes = []*CurrencyCostBasis{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withCurrency != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*CurrencyCostBasis).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &CurrencyCostBasis{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.withCurrency; query != nil { + if err := _q.loadCurrency(ctx, query, nodes, nil, + func(n *CurrencyCostBasis, e *CustomCurrency) { n.Edges.Currency = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *CurrencyCostBasisQuery) loadCurrency(ctx context.Context, query *CustomCurrencyQuery, nodes []*CurrencyCostBasis, init func(*CurrencyCostBasis), assign func(*CurrencyCostBasis, *CustomCurrency)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*CurrencyCostBasis) + for i := range nodes { + fk := nodes[i].CurrencyID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(customcurrency.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 "currency_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *CurrencyCostBasisQuery) 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 *CurrencyCostBasisQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(currencycostbasis.Table, currencycostbasis.Columns, sqlgraph.NewFieldSpec(currencycostbasis.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, currencycostbasis.FieldID) + for i := range fields { + if fields[i] != currencycostbasis.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withCurrency != nil { + _spec.Node.AddColumnOnce(currencycostbasis.FieldCurrencyID) + } + } + 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 *CurrencyCostBasisQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(currencycostbasis.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = currencycostbasis.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 *CurrencyCostBasisQuery) ForUpdate(opts ...sql.LockOption) *CurrencyCostBasisQuery { + 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 *CurrencyCostBasisQuery) ForShare(opts ...sql.LockOption) *CurrencyCostBasisQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// CurrencyCostBasisGroupBy is the group-by builder for CurrencyCostBasis entities. +type CurrencyCostBasisGroupBy struct { + selector + build *CurrencyCostBasisQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *CurrencyCostBasisGroupBy) Aggregate(fns ...AggregateFunc) *CurrencyCostBasisGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *CurrencyCostBasisGroupBy) 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[*CurrencyCostBasisQuery, *CurrencyCostBasisGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *CurrencyCostBasisGroupBy) sqlScan(ctx context.Context, root *CurrencyCostBasisQuery, 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) +} + +// CurrencyCostBasisSelect is the builder for selecting fields of CurrencyCostBasis entities. +type CurrencyCostBasisSelect struct { + *CurrencyCostBasisQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *CurrencyCostBasisSelect) Aggregate(fns ...AggregateFunc) *CurrencyCostBasisSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *CurrencyCostBasisSelect) 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[*CurrencyCostBasisQuery, *CurrencyCostBasisSelect](ctx, _s.CurrencyCostBasisQuery, _s, _s.inters, v) +} + +func (_s *CurrencyCostBasisSelect) sqlScan(ctx context.Context, root *CurrencyCostBasisQuery, 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/ent/db/currencycostbasis_update.go b/ent/db/currencycostbasis_update.go new file mode 100644 index 0000000000000000000000000000000000000000..d8ce4aff150fefff918abdd8771dd5b138c5e3a0 --- /dev/null +++ b/ent/db/currencycostbasis_update.go @@ -0,0 +1,292 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/currencycostbasis" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// CurrencyCostBasisUpdate is the builder for updating CurrencyCostBasis entities. +type CurrencyCostBasisUpdate struct { + config + hooks []Hook + mutation *CurrencyCostBasisMutation +} + +// Where appends a list predicates to the CurrencyCostBasisUpdate builder. +func (_u *CurrencyCostBasisUpdate) Where(ps ...predicate.CurrencyCostBasis) *CurrencyCostBasisUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *CurrencyCostBasisUpdate) SetUpdatedAt(v time.Time) *CurrencyCostBasisUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *CurrencyCostBasisUpdate) SetDeletedAt(v time.Time) *CurrencyCostBasisUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *CurrencyCostBasisUpdate) SetNillableDeletedAt(v *time.Time) *CurrencyCostBasisUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *CurrencyCostBasisUpdate) ClearDeletedAt() *CurrencyCostBasisUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// Mutation returns the CurrencyCostBasisMutation object of the builder. +func (_u *CurrencyCostBasisUpdate) Mutation() *CurrencyCostBasisMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *CurrencyCostBasisUpdate) 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 *CurrencyCostBasisUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *CurrencyCostBasisUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *CurrencyCostBasisUpdate) 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 *CurrencyCostBasisUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := currencycostbasis.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *CurrencyCostBasisUpdate) check() error { + if _u.mutation.CurrencyCleared() && len(_u.mutation.CurrencyIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "CurrencyCostBasis.currency"`) + } + return nil +} + +func (_u *CurrencyCostBasisUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(currencycostbasis.Table, currencycostbasis.Columns, sqlgraph.NewFieldSpec(currencycostbasis.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(currencycostbasis.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(currencycostbasis.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(currencycostbasis.FieldDeletedAt, field.TypeTime) + } + if _u.mutation.EffectiveToCleared() { + _spec.ClearField(currencycostbasis.FieldEffectiveTo, field.TypeTime) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{currencycostbasis.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// CurrencyCostBasisUpdateOne is the builder for updating a single CurrencyCostBasis entity. +type CurrencyCostBasisUpdateOne struct { + config + fields []string + hooks []Hook + mutation *CurrencyCostBasisMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *CurrencyCostBasisUpdateOne) SetUpdatedAt(v time.Time) *CurrencyCostBasisUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *CurrencyCostBasisUpdateOne) SetDeletedAt(v time.Time) *CurrencyCostBasisUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *CurrencyCostBasisUpdateOne) SetNillableDeletedAt(v *time.Time) *CurrencyCostBasisUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *CurrencyCostBasisUpdateOne) ClearDeletedAt() *CurrencyCostBasisUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// Mutation returns the CurrencyCostBasisMutation object of the builder. +func (_u *CurrencyCostBasisUpdateOne) Mutation() *CurrencyCostBasisMutation { + return _u.mutation +} + +// Where appends a list predicates to the CurrencyCostBasisUpdate builder. +func (_u *CurrencyCostBasisUpdateOne) Where(ps ...predicate.CurrencyCostBasis) *CurrencyCostBasisUpdateOne { + _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 *CurrencyCostBasisUpdateOne) Select(field string, fields ...string) *CurrencyCostBasisUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated CurrencyCostBasis entity. +func (_u *CurrencyCostBasisUpdateOne) Save(ctx context.Context) (*CurrencyCostBasis, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *CurrencyCostBasisUpdateOne) SaveX(ctx context.Context) *CurrencyCostBasis { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *CurrencyCostBasisUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *CurrencyCostBasisUpdateOne) 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 *CurrencyCostBasisUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := currencycostbasis.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *CurrencyCostBasisUpdateOne) check() error { + if _u.mutation.CurrencyCleared() && len(_u.mutation.CurrencyIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "CurrencyCostBasis.currency"`) + } + return nil +} + +func (_u *CurrencyCostBasisUpdateOne) sqlSave(ctx context.Context) (_node *CurrencyCostBasis, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(currencycostbasis.Table, currencycostbasis.Columns, sqlgraph.NewFieldSpec(currencycostbasis.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "CurrencyCostBasis.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, currencycostbasis.FieldID) + for _, f := range fields { + if !currencycostbasis.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != currencycostbasis.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(currencycostbasis.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(currencycostbasis.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(currencycostbasis.FieldDeletedAt, field.TypeTime) + } + if _u.mutation.EffectiveToCleared() { + _spec.ClearField(currencycostbasis.FieldEffectiveTo, field.TypeTime) + } + _node = &CurrencyCostBasis{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{currencycostbasis.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/ent/db/cursor.go b/ent/db/cursor.go new file mode 100644 index 0000000000000000000000000000000000000000..b06c64cd148815959a9d8f6119adf81f52758faa --- /dev/null +++ b/ent/db/cursor.go @@ -0,0 +1,3837 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "github.com/openmeterio/openmeter/pkg/pagination/v2" + "github.com/samber/lo" +) + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *AddonQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*Addon], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*Addon]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*Addon]{}, err + } + + if items == nil { + items = make([]*Addon, 0) + } + + result := pagination.Result[*Addon]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *AddonRateCardQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*AddonRateCard], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*AddonRateCard]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*AddonRateCard]{}, err + } + + if items == nil { + items = make([]*AddonRateCard, 0) + } + + result := pagination.Result[*AddonRateCard]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *AppQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*App], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*App]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*App]{}, err + } + + if items == nil { + items = make([]*App, 0) + } + + result := pagination.Result[*App]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *AppCustomInvoicingQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*AppCustomInvoicing], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*AppCustomInvoicing]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*AppCustomInvoicing]{}, err + } + + if items == nil { + items = make([]*AppCustomInvoicing, 0) + } + + result := pagination.Result[*AppCustomInvoicing]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *AppCustomInvoicingCustomerQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*AppCustomInvoicingCustomer], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*AppCustomInvoicingCustomer]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*AppCustomInvoicingCustomer]{}, err + } + + if items == nil { + items = make([]*AppCustomInvoicingCustomer, 0) + } + + result := pagination.Result[*AppCustomInvoicingCustomer]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *AppCustomerQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*AppCustomer], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*AppCustomer]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*AppCustomer]{}, err + } + + if items == nil { + items = make([]*AppCustomer, 0) + } + + result := pagination.Result[*AppCustomer]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *AppStripeQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*AppStripe], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*AppStripe]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*AppStripe]{}, err + } + + if items == nil { + items = make([]*AppStripe, 0) + } + + result := pagination.Result[*AppStripe]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *AppStripeCustomerQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*AppStripeCustomer], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*AppStripeCustomer]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*AppStripeCustomer]{}, err + } + + if items == nil { + items = make([]*AppStripeCustomer, 0) + } + + result := pagination.Result[*AppStripeCustomer]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *BalanceSnapshotQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*BalanceSnapshot], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*BalanceSnapshot]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*BalanceSnapshot]{}, err + } + + if items == nil { + items = make([]*BalanceSnapshot, 0) + } + + result := pagination.Result[*BalanceSnapshot]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *BillingCustomerOverrideQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*BillingCustomerOverride], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*BillingCustomerOverride]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*BillingCustomerOverride]{}, err + } + + if items == nil { + items = make([]*BillingCustomerOverride, 0) + } + + result := pagination.Result[*BillingCustomerOverride]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *BillingInvoiceQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*BillingInvoice], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*BillingInvoice]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*BillingInvoice]{}, err + } + + if items == nil { + items = make([]*BillingInvoice, 0) + } + + result := pagination.Result[*BillingInvoice]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *BillingInvoiceLineQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*BillingInvoiceLine], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*BillingInvoiceLine]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*BillingInvoiceLine]{}, err + } + + if items == nil { + items = make([]*BillingInvoiceLine, 0) + } + + result := pagination.Result[*BillingInvoiceLine]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *BillingInvoiceLineDiscountQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*BillingInvoiceLineDiscount], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*BillingInvoiceLineDiscount]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*BillingInvoiceLineDiscount]{}, err + } + + if items == nil { + items = make([]*BillingInvoiceLineDiscount, 0) + } + + result := pagination.Result[*BillingInvoiceLineDiscount]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *BillingInvoiceLineUsageDiscountQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*BillingInvoiceLineUsageDiscount], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*BillingInvoiceLineUsageDiscount]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*BillingInvoiceLineUsageDiscount]{}, err + } + + if items == nil { + items = make([]*BillingInvoiceLineUsageDiscount, 0) + } + + result := pagination.Result[*BillingInvoiceLineUsageDiscount]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *BillingInvoiceSplitLineGroupQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*BillingInvoiceSplitLineGroup], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*BillingInvoiceSplitLineGroup]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*BillingInvoiceSplitLineGroup]{}, err + } + + if items == nil { + items = make([]*BillingInvoiceSplitLineGroup, 0) + } + + result := pagination.Result[*BillingInvoiceSplitLineGroup]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *BillingInvoiceValidationIssueQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*BillingInvoiceValidationIssue], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*BillingInvoiceValidationIssue]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*BillingInvoiceValidationIssue]{}, err + } + + if items == nil { + items = make([]*BillingInvoiceValidationIssue, 0) + } + + result := pagination.Result[*BillingInvoiceValidationIssue]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *BillingProfileQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*BillingProfile], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*BillingProfile]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*BillingProfile]{}, err + } + + if items == nil { + items = make([]*BillingProfile, 0) + } + + result := pagination.Result[*BillingProfile]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *BillingStandardInvoiceDetailedLineQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*BillingStandardInvoiceDetailedLine], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*BillingStandardInvoiceDetailedLine]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*BillingStandardInvoiceDetailedLine]{}, err + } + + if items == nil { + items = make([]*BillingStandardInvoiceDetailedLine, 0) + } + + result := pagination.Result[*BillingStandardInvoiceDetailedLine]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *BillingStandardInvoiceDetailedLineAmountDiscountQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*BillingStandardInvoiceDetailedLineAmountDiscount], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*BillingStandardInvoiceDetailedLineAmountDiscount]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*BillingStandardInvoiceDetailedLineAmountDiscount]{}, err + } + + if items == nil { + items = make([]*BillingStandardInvoiceDetailedLineAmountDiscount, 0) + } + + result := pagination.Result[*BillingStandardInvoiceDetailedLineAmountDiscount]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *BillingWorkflowConfigQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*BillingWorkflowConfig], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*BillingWorkflowConfig]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*BillingWorkflowConfig]{}, err + } + + if items == nil { + items = make([]*BillingWorkflowConfig, 0) + } + + result := pagination.Result[*BillingWorkflowConfig]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *ChargeQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*Charge], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*Charge]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*Charge]{}, err + } + + if items == nil { + items = make([]*Charge, 0) + } + + result := pagination.Result[*Charge]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *ChargeCreditPurchaseQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*ChargeCreditPurchase], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*ChargeCreditPurchase]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*ChargeCreditPurchase]{}, err + } + + if items == nil { + items = make([]*ChargeCreditPurchase, 0) + } + + result := pagination.Result[*ChargeCreditPurchase]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *ChargeCreditPurchaseCreditGrantQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*ChargeCreditPurchaseCreditGrant], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*ChargeCreditPurchaseCreditGrant]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*ChargeCreditPurchaseCreditGrant]{}, err + } + + if items == nil { + items = make([]*ChargeCreditPurchaseCreditGrant, 0) + } + + result := pagination.Result[*ChargeCreditPurchaseCreditGrant]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *ChargeCreditPurchaseExternalPaymentQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*ChargeCreditPurchaseExternalPayment], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*ChargeCreditPurchaseExternalPayment]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*ChargeCreditPurchaseExternalPayment]{}, err + } + + if items == nil { + items = make([]*ChargeCreditPurchaseExternalPayment, 0) + } + + result := pagination.Result[*ChargeCreditPurchaseExternalPayment]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *ChargeCreditPurchaseInvoicedPaymentQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*ChargeCreditPurchaseInvoicedPayment], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*ChargeCreditPurchaseInvoicedPayment]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*ChargeCreditPurchaseInvoicedPayment]{}, err + } + + if items == nil { + items = make([]*ChargeCreditPurchaseInvoicedPayment, 0) + } + + result := pagination.Result[*ChargeCreditPurchaseInvoicedPayment]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *ChargeFlatFeeQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*ChargeFlatFee], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*ChargeFlatFee]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*ChargeFlatFee]{}, err + } + + if items == nil { + items = make([]*ChargeFlatFee, 0) + } + + result := pagination.Result[*ChargeFlatFee]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *ChargeFlatFeeRunQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*ChargeFlatFeeRun], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*ChargeFlatFeeRun]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*ChargeFlatFeeRun]{}, err + } + + if items == nil { + items = make([]*ChargeFlatFeeRun, 0) + } + + result := pagination.Result[*ChargeFlatFeeRun]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *ChargeFlatFeeRunCreditAllocationsQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*ChargeFlatFeeRunCreditAllocations], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*ChargeFlatFeeRunCreditAllocations]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*ChargeFlatFeeRunCreditAllocations]{}, err + } + + if items == nil { + items = make([]*ChargeFlatFeeRunCreditAllocations, 0) + } + + result := pagination.Result[*ChargeFlatFeeRunCreditAllocations]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *ChargeFlatFeeRunDetailedLineQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*ChargeFlatFeeRunDetailedLine], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*ChargeFlatFeeRunDetailedLine]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*ChargeFlatFeeRunDetailedLine]{}, err + } + + if items == nil { + items = make([]*ChargeFlatFeeRunDetailedLine, 0) + } + + result := pagination.Result[*ChargeFlatFeeRunDetailedLine]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *ChargeFlatFeeRunInvoicedUsageQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*ChargeFlatFeeRunInvoicedUsage], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*ChargeFlatFeeRunInvoicedUsage]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*ChargeFlatFeeRunInvoicedUsage]{}, err + } + + if items == nil { + items = make([]*ChargeFlatFeeRunInvoicedUsage, 0) + } + + result := pagination.Result[*ChargeFlatFeeRunInvoicedUsage]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *ChargeFlatFeeRunPaymentQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*ChargeFlatFeeRunPayment], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*ChargeFlatFeeRunPayment]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*ChargeFlatFeeRunPayment]{}, err + } + + if items == nil { + items = make([]*ChargeFlatFeeRunPayment, 0) + } + + result := pagination.Result[*ChargeFlatFeeRunPayment]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *ChargeUsageBasedQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*ChargeUsageBased], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*ChargeUsageBased]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*ChargeUsageBased]{}, err + } + + if items == nil { + items = make([]*ChargeUsageBased, 0) + } + + result := pagination.Result[*ChargeUsageBased]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *ChargeUsageBasedRunCreditAllocationsQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*ChargeUsageBasedRunCreditAllocations], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*ChargeUsageBasedRunCreditAllocations]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*ChargeUsageBasedRunCreditAllocations]{}, err + } + + if items == nil { + items = make([]*ChargeUsageBasedRunCreditAllocations, 0) + } + + result := pagination.Result[*ChargeUsageBasedRunCreditAllocations]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *ChargeUsageBasedRunDetailedLineQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*ChargeUsageBasedRunDetailedLine], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*ChargeUsageBasedRunDetailedLine]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*ChargeUsageBasedRunDetailedLine]{}, err + } + + if items == nil { + items = make([]*ChargeUsageBasedRunDetailedLine, 0) + } + + result := pagination.Result[*ChargeUsageBasedRunDetailedLine]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *ChargeUsageBasedRunInvoicedUsageQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*ChargeUsageBasedRunInvoicedUsage], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*ChargeUsageBasedRunInvoicedUsage]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*ChargeUsageBasedRunInvoicedUsage]{}, err + } + + if items == nil { + items = make([]*ChargeUsageBasedRunInvoicedUsage, 0) + } + + result := pagination.Result[*ChargeUsageBasedRunInvoicedUsage]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *ChargeUsageBasedRunPaymentQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*ChargeUsageBasedRunPayment], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*ChargeUsageBasedRunPayment]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*ChargeUsageBasedRunPayment]{}, err + } + + if items == nil { + items = make([]*ChargeUsageBasedRunPayment, 0) + } + + result := pagination.Result[*ChargeUsageBasedRunPayment]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *ChargeUsageBasedRunsQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*ChargeUsageBasedRuns], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*ChargeUsageBasedRuns]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*ChargeUsageBasedRuns]{}, err + } + + if items == nil { + items = make([]*ChargeUsageBasedRuns, 0) + } + + result := pagination.Result[*ChargeUsageBasedRuns]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *ChargesSearchV1Query) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*ChargesSearchV1], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*ChargesSearchV1]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*ChargesSearchV1]{}, err + } + + if items == nil { + items = make([]*ChargesSearchV1, 0) + } + + result := pagination.Result[*ChargesSearchV1]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *CreditRealizationLineageQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*CreditRealizationLineage], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*CreditRealizationLineage]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*CreditRealizationLineage]{}, err + } + + if items == nil { + items = make([]*CreditRealizationLineage, 0) + } + + result := pagination.Result[*CreditRealizationLineage]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *CreditRealizationLineageSegmentQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*CreditRealizationLineageSegment], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*CreditRealizationLineageSegment]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*CreditRealizationLineageSegment]{}, err + } + + if items == nil { + items = make([]*CreditRealizationLineageSegment, 0) + } + + result := pagination.Result[*CreditRealizationLineageSegment]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *CurrencyCostBasisQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*CurrencyCostBasis], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*CurrencyCostBasis]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*CurrencyCostBasis]{}, err + } + + if items == nil { + items = make([]*CurrencyCostBasis, 0) + } + + result := pagination.Result[*CurrencyCostBasis]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *CustomCurrencyQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*CustomCurrency], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*CustomCurrency]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*CustomCurrency]{}, err + } + + if items == nil { + items = make([]*CustomCurrency, 0) + } + + result := pagination.Result[*CustomCurrency]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *CustomerQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*Customer], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*Customer]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*Customer]{}, err + } + + if items == nil { + items = make([]*Customer, 0) + } + + result := pagination.Result[*Customer]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *CustomerSubjectsQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*CustomerSubjects], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*CustomerSubjects]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*CustomerSubjects]{}, err + } + + if items == nil { + items = make([]*CustomerSubjects, 0) + } + + result := pagination.Result[*CustomerSubjects]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *EntitlementQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*Entitlement], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*Entitlement]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*Entitlement]{}, err + } + + if items == nil { + items = make([]*Entitlement, 0) + } + + result := pagination.Result[*Entitlement]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *FeatureQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*Feature], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*Feature]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*Feature]{}, err + } + + if items == nil { + items = make([]*Feature, 0) + } + + result := pagination.Result[*Feature]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *GrantQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*Grant], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*Grant]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*Grant]{}, err + } + + if items == nil { + items = make([]*Grant, 0) + } + + result := pagination.Result[*Grant]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *LLMCostPriceQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*LLMCostPrice], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*LLMCostPrice]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*LLMCostPrice]{}, err + } + + if items == nil { + items = make([]*LLMCostPrice, 0) + } + + result := pagination.Result[*LLMCostPrice]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *LedgerAccountQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*LedgerAccount], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*LedgerAccount]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*LedgerAccount]{}, err + } + + if items == nil { + items = make([]*LedgerAccount, 0) + } + + result := pagination.Result[*LedgerAccount]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *LedgerBreakageRecordQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*LedgerBreakageRecord], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*LedgerBreakageRecord]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*LedgerBreakageRecord]{}, err + } + + if items == nil { + items = make([]*LedgerBreakageRecord, 0) + } + + result := pagination.Result[*LedgerBreakageRecord]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *LedgerCreditVoidRecordQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*LedgerCreditVoidRecord], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*LedgerCreditVoidRecord]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*LedgerCreditVoidRecord]{}, err + } + + if items == nil { + items = make([]*LedgerCreditVoidRecord, 0) + } + + result := pagination.Result[*LedgerCreditVoidRecord]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *LedgerCustomerAccountQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*LedgerCustomerAccount], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*LedgerCustomerAccount]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*LedgerCustomerAccount]{}, err + } + + if items == nil { + items = make([]*LedgerCustomerAccount, 0) + } + + result := pagination.Result[*LedgerCustomerAccount]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *LedgerEntryQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*LedgerEntry], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*LedgerEntry]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*LedgerEntry]{}, err + } + + if items == nil { + items = make([]*LedgerEntry, 0) + } + + result := pagination.Result[*LedgerEntry]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *LedgerSubAccountQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*LedgerSubAccount], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*LedgerSubAccount]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*LedgerSubAccount]{}, err + } + + if items == nil { + items = make([]*LedgerSubAccount, 0) + } + + result := pagination.Result[*LedgerSubAccount]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *LedgerSubAccountRouteQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*LedgerSubAccountRoute], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*LedgerSubAccountRoute]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*LedgerSubAccountRoute]{}, err + } + + if items == nil { + items = make([]*LedgerSubAccountRoute, 0) + } + + result := pagination.Result[*LedgerSubAccountRoute]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *LedgerTransactionQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*LedgerTransaction], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*LedgerTransaction]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*LedgerTransaction]{}, err + } + + if items == nil { + items = make([]*LedgerTransaction, 0) + } + + result := pagination.Result[*LedgerTransaction]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *LedgerTransactionGroupQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*LedgerTransactionGroup], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*LedgerTransactionGroup]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*LedgerTransactionGroup]{}, err + } + + if items == nil { + items = make([]*LedgerTransactionGroup, 0) + } + + result := pagination.Result[*LedgerTransactionGroup]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *MeterQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*Meter], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*Meter]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*Meter]{}, err + } + + if items == nil { + items = make([]*Meter, 0) + } + + result := pagination.Result[*Meter]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *NotificationChannelQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*NotificationChannel], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*NotificationChannel]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*NotificationChannel]{}, err + } + + if items == nil { + items = make([]*NotificationChannel, 0) + } + + result := pagination.Result[*NotificationChannel]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *NotificationEventQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*NotificationEvent], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*NotificationEvent]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*NotificationEvent]{}, err + } + + if items == nil { + items = make([]*NotificationEvent, 0) + } + + result := pagination.Result[*NotificationEvent]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *NotificationEventDeliveryStatusQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*NotificationEventDeliveryStatus], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*NotificationEventDeliveryStatus]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*NotificationEventDeliveryStatus]{}, err + } + + if items == nil { + items = make([]*NotificationEventDeliveryStatus, 0) + } + + result := pagination.Result[*NotificationEventDeliveryStatus]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *NotificationRuleQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*NotificationRule], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*NotificationRule]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*NotificationRule]{}, err + } + + if items == nil { + items = make([]*NotificationRule, 0) + } + + result := pagination.Result[*NotificationRule]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *OrganizationDefaultTaxCodesQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*OrganizationDefaultTaxCodes], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*OrganizationDefaultTaxCodes]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*OrganizationDefaultTaxCodes]{}, err + } + + if items == nil { + items = make([]*OrganizationDefaultTaxCodes, 0) + } + + result := pagination.Result[*OrganizationDefaultTaxCodes]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *PlanQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*Plan], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*Plan]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*Plan]{}, err + } + + if items == nil { + items = make([]*Plan, 0) + } + + result := pagination.Result[*Plan]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *PlanAddonQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*PlanAddon], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*PlanAddon]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*PlanAddon]{}, err + } + + if items == nil { + items = make([]*PlanAddon, 0) + } + + result := pagination.Result[*PlanAddon]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *PlanPhaseQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*PlanPhase], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*PlanPhase]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*PlanPhase]{}, err + } + + if items == nil { + items = make([]*PlanPhase, 0) + } + + result := pagination.Result[*PlanPhase]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *PlanRateCardQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*PlanRateCard], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*PlanRateCard]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*PlanRateCard]{}, err + } + + if items == nil { + items = make([]*PlanRateCard, 0) + } + + result := pagination.Result[*PlanRateCard]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *SubjectQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*Subject], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*Subject]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*Subject]{}, err + } + + if items == nil { + items = make([]*Subject, 0) + } + + result := pagination.Result[*Subject]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *SubscriptionQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*Subscription], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*Subscription]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*Subscription]{}, err + } + + if items == nil { + items = make([]*Subscription, 0) + } + + result := pagination.Result[*Subscription]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *SubscriptionAddonQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*SubscriptionAddon], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*SubscriptionAddon]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*SubscriptionAddon]{}, err + } + + if items == nil { + items = make([]*SubscriptionAddon, 0) + } + + result := pagination.Result[*SubscriptionAddon]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *SubscriptionAddonQuantityQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*SubscriptionAddonQuantity], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*SubscriptionAddonQuantity]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*SubscriptionAddonQuantity]{}, err + } + + if items == nil { + items = make([]*SubscriptionAddonQuantity, 0) + } + + result := pagination.Result[*SubscriptionAddonQuantity]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *SubscriptionItemQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*SubscriptionItem], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*SubscriptionItem]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*SubscriptionItem]{}, err + } + + if items == nil { + items = make([]*SubscriptionItem, 0) + } + + result := pagination.Result[*SubscriptionItem]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *SubscriptionPhaseQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*SubscriptionPhase], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*SubscriptionPhase]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*SubscriptionPhase]{}, err + } + + if items == nil { + items = make([]*SubscriptionPhase, 0) + } + + result := pagination.Result[*SubscriptionPhase]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *TaxCodeQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*TaxCode], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*TaxCode]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*TaxCode]{}, err + } + + if items == nil { + items = make([]*TaxCode, 0) + } + + result := pagination.Result[*TaxCode]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} + +// Cursor runs the query and returns a cursor-paginated response. +// Ordering is always by created_at asc, id asc. +func (_m *UsageResetQuery) Cursor(ctx context.Context, cursor *pagination.Cursor) (pagination.Result[*UsageReset], error) { + if cursor != nil { + if err := cursor.Validate(); err != nil { + return pagination.Result[*UsageReset]{}, fmt.Errorf("invalid cursor: %w", err) + } + + _m.Where(func(s *sql.Selector) { + s.Where( + sql.Or( + sql.GT(s.C("created_at"), cursor.Time), + sql.And( + sql.EQ(s.C("created_at"), cursor.Time), + sql.P(func(b *sql.Builder) { + b.WriteString("CAST(") + b.WriteString(s.C("id")) + b.WriteString(" AS TEXT) > ") + b.Args(cursor.ID) + }), + ), + ), + ) + }) + } + + _m.Order(func(s *sql.Selector) { + s.OrderBy(sql.Asc(s.C("created_at")), sql.Asc(s.C("id"))) + }) + + items, err := _m.All(ctx) + if err != nil { + return pagination.Result[*UsageReset]{}, err + } + + if items == nil { + items = make([]*UsageReset, 0) + } + + result := pagination.Result[*UsageReset]{ + Items: items, + } + + if len(items) > 0 { + last := items[len(items)-1] + result.NextCursor = lo.ToPtr(pagination.NewCursor(last.CreatedAt, fmt.Sprint(last.ID))) + } + + return result, nil +} diff --git a/ent/db/customcurrency.go b/ent/db/customcurrency.go new file mode 100644 index 0000000000000000000000000000000000000000..e8c65b8c381b2d9b9b8ba6fa58f8fc595cb614a5 --- /dev/null +++ b/ent/db/customcurrency.go @@ -0,0 +1,199 @@ +// 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/customcurrency" +) + +// CustomCurrency is the model entity for the CustomCurrency schema. +type CustomCurrency 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"` + // Code holds the value of the "code" field. + Code string `json:"code,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Symbol holds the value of the "symbol" field. + Symbol string `json:"symbol,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the CustomCurrencyQuery when eager-loading is set. + Edges CustomCurrencyEdges `json:"edges"` + selectValues sql.SelectValues +} + +// CustomCurrencyEdges holds the relations/edges for other nodes in the graph. +type CustomCurrencyEdges struct { + // CostBasisHistory holds the value of the cost_basis_history edge. + CostBasisHistory []*CurrencyCostBasis `json:"cost_basis_history,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// CostBasisHistoryOrErr returns the CostBasisHistory value or an error if the edge +// was not loaded in eager-loading. +func (e CustomCurrencyEdges) CostBasisHistoryOrErr() ([]*CurrencyCostBasis, error) { + if e.loadedTypes[0] { + return e.CostBasisHistory, nil + } + return nil, &NotLoadedError{edge: "cost_basis_history"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*CustomCurrency) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case customcurrency.FieldID, customcurrency.FieldNamespace, customcurrency.FieldCode, customcurrency.FieldName, customcurrency.FieldSymbol: + values[i] = new(sql.NullString) + case customcurrency.FieldCreatedAt, customcurrency.FieldUpdatedAt, customcurrency.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 CustomCurrency fields. +func (_m *CustomCurrency) 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 customcurrency.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 customcurrency.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 customcurrency.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 customcurrency.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 customcurrency.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 customcurrency.FieldCode: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field code", values[i]) + } else if value.Valid { + _m.Code = value.String + } + case customcurrency.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case customcurrency.FieldSymbol: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field symbol", values[i]) + } else if value.Valid { + _m.Symbol = 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 CustomCurrency. +// This includes values selected through modifiers, order, etc. +func (_m *CustomCurrency) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryCostBasisHistory queries the "cost_basis_history" edge of the CustomCurrency entity. +func (_m *CustomCurrency) QueryCostBasisHistory() *CurrencyCostBasisQuery { + return NewCustomCurrencyClient(_m.config).QueryCostBasisHistory(_m) +} + +// Update returns a builder for updating this CustomCurrency. +// Note that you need to call CustomCurrency.Unwrap() before calling this method if this CustomCurrency +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *CustomCurrency) Update() *CustomCurrencyUpdateOne { + return NewCustomCurrencyClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the CustomCurrency 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 *CustomCurrency) Unwrap() *CustomCurrency { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: CustomCurrency is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *CustomCurrency) String() string { + var builder strings.Builder + builder.WriteString("CustomCurrency(") + 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("code=") + builder.WriteString(_m.Code) + builder.WriteString(", ") + builder.WriteString("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + builder.WriteString("symbol=") + builder.WriteString(_m.Symbol) + builder.WriteByte(')') + return builder.String() +} + +// CustomCurrencies is a parsable slice of CustomCurrency. +type CustomCurrencies []*CustomCurrency diff --git a/ent/db/customcurrency/customcurrency.go b/ent/db/customcurrency/customcurrency.go new file mode 100644 index 0000000000000000000000000000000000000000..b75965f3b077eed571a2dda80fc65fd9aaeb4508 --- /dev/null +++ b/ent/db/customcurrency/customcurrency.go @@ -0,0 +1,147 @@ +// Code generated by ent, DO NOT EDIT. + +package customcurrency + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the customcurrency type in the database. + Label = "custom_currency" + // 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" + // FieldCode holds the string denoting the code field in the database. + FieldCode = "code" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldSymbol holds the string denoting the symbol field in the database. + FieldSymbol = "symbol" + // EdgeCostBasisHistory holds the string denoting the cost_basis_history edge name in mutations. + EdgeCostBasisHistory = "cost_basis_history" + // Table holds the table name of the customcurrency in the database. + Table = "custom_currencies" + // CostBasisHistoryTable is the table that holds the cost_basis_history relation/edge. + CostBasisHistoryTable = "currency_cost_bases" + // CostBasisHistoryInverseTable is the table name for the CurrencyCostBasis entity. + // It exists in this package in order to avoid circular dependency with the "currencycostbasis" package. + CostBasisHistoryInverseTable = "currency_cost_bases" + // CostBasisHistoryColumn is the table column denoting the cost_basis_history relation/edge. + CostBasisHistoryColumn = "currency_id" +) + +// Columns holds all SQL columns for customcurrency fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldCode, + FieldName, + FieldSymbol, +} + +// 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 + // CodeValidator is a validator for the "code" field. It is called by the builders before save. + CodeValidator func(string) error + // NameValidator is a validator for the "name" field. It is called by the builders before save. + NameValidator func(string) error + // SymbolValidator is a validator for the "symbol" field. It is called by the builders before save. + SymbolValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// OrderOption defines the ordering options for the CustomCurrency 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() +} + +// ByCode orders the results by the code field. +func ByCode(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCode, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// BySymbol orders the results by the symbol field. +func BySymbol(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSymbol, opts...).ToFunc() +} + +// ByCostBasisHistoryCount orders the results by cost_basis_history count. +func ByCostBasisHistoryCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newCostBasisHistoryStep(), opts...) + } +} + +// ByCostBasisHistory orders the results by cost_basis_history terms. +func ByCostBasisHistory(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCostBasisHistoryStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newCostBasisHistoryStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CostBasisHistoryInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, CostBasisHistoryTable, CostBasisHistoryColumn), + ) +} diff --git a/ent/db/customcurrency/where.go b/ent/db/customcurrency/where.go new file mode 100644 index 0000000000000000000000000000000000000000..5eb91073e835ace7890c050671573fa2b632a271 --- /dev/null +++ b/ent/db/customcurrency/where.go @@ -0,0 +1,529 @@ +// Code generated by ent, DO NOT EDIT. + +package customcurrency + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(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.CustomCurrency { + return predicate.CustomCurrency(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.CustomCurrency { + return predicate.CustomCurrency(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.CustomCurrency { + return predicate.CustomCurrency(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Code applies equality check predicate on the "code" field. It's identical to CodeEQ. +func Code(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldEQ(FieldCode, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldEQ(FieldName, v)) +} + +// Symbol applies equality check predicate on the "symbol" field. It's identical to SymbolEQ. +func Symbol(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldEQ(FieldSymbol, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldNotNull(FieldDeletedAt)) +} + +// CodeEQ applies the EQ predicate on the "code" field. +func CodeEQ(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldEQ(FieldCode, v)) +} + +// CodeNEQ applies the NEQ predicate on the "code" field. +func CodeNEQ(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldNEQ(FieldCode, v)) +} + +// CodeIn applies the In predicate on the "code" field. +func CodeIn(vs ...string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldIn(FieldCode, vs...)) +} + +// CodeNotIn applies the NotIn predicate on the "code" field. +func CodeNotIn(vs ...string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldNotIn(FieldCode, vs...)) +} + +// CodeGT applies the GT predicate on the "code" field. +func CodeGT(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldGT(FieldCode, v)) +} + +// CodeGTE applies the GTE predicate on the "code" field. +func CodeGTE(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldGTE(FieldCode, v)) +} + +// CodeLT applies the LT predicate on the "code" field. +func CodeLT(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldLT(FieldCode, v)) +} + +// CodeLTE applies the LTE predicate on the "code" field. +func CodeLTE(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldLTE(FieldCode, v)) +} + +// CodeContains applies the Contains predicate on the "code" field. +func CodeContains(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldContains(FieldCode, v)) +} + +// CodeHasPrefix applies the HasPrefix predicate on the "code" field. +func CodeHasPrefix(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldHasPrefix(FieldCode, v)) +} + +// CodeHasSuffix applies the HasSuffix predicate on the "code" field. +func CodeHasSuffix(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldHasSuffix(FieldCode, v)) +} + +// CodeEqualFold applies the EqualFold predicate on the "code" field. +func CodeEqualFold(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldEqualFold(FieldCode, v)) +} + +// CodeContainsFold applies the ContainsFold predicate on the "code" field. +func CodeContainsFold(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldContainsFold(FieldCode, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldContainsFold(FieldName, v)) +} + +// SymbolEQ applies the EQ predicate on the "symbol" field. +func SymbolEQ(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldEQ(FieldSymbol, v)) +} + +// SymbolNEQ applies the NEQ predicate on the "symbol" field. +func SymbolNEQ(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldNEQ(FieldSymbol, v)) +} + +// SymbolIn applies the In predicate on the "symbol" field. +func SymbolIn(vs ...string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldIn(FieldSymbol, vs...)) +} + +// SymbolNotIn applies the NotIn predicate on the "symbol" field. +func SymbolNotIn(vs ...string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldNotIn(FieldSymbol, vs...)) +} + +// SymbolGT applies the GT predicate on the "symbol" field. +func SymbolGT(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldGT(FieldSymbol, v)) +} + +// SymbolGTE applies the GTE predicate on the "symbol" field. +func SymbolGTE(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldGTE(FieldSymbol, v)) +} + +// SymbolLT applies the LT predicate on the "symbol" field. +func SymbolLT(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldLT(FieldSymbol, v)) +} + +// SymbolLTE applies the LTE predicate on the "symbol" field. +func SymbolLTE(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldLTE(FieldSymbol, v)) +} + +// SymbolContains applies the Contains predicate on the "symbol" field. +func SymbolContains(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldContains(FieldSymbol, v)) +} + +// SymbolHasPrefix applies the HasPrefix predicate on the "symbol" field. +func SymbolHasPrefix(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldHasPrefix(FieldSymbol, v)) +} + +// SymbolHasSuffix applies the HasSuffix predicate on the "symbol" field. +func SymbolHasSuffix(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldHasSuffix(FieldSymbol, v)) +} + +// SymbolEqualFold applies the EqualFold predicate on the "symbol" field. +func SymbolEqualFold(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldEqualFold(FieldSymbol, v)) +} + +// SymbolContainsFold applies the ContainsFold predicate on the "symbol" field. +func SymbolContainsFold(v string) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.FieldContainsFold(FieldSymbol, v)) +} + +// HasCostBasisHistory applies the HasEdge predicate on the "cost_basis_history" edge. +func HasCostBasisHistory() predicate.CustomCurrency { + return predicate.CustomCurrency(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, CostBasisHistoryTable, CostBasisHistoryColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCostBasisHistoryWith applies the HasEdge predicate on the "cost_basis_history" edge with a given conditions (other predicates). +func HasCostBasisHistoryWith(preds ...predicate.CurrencyCostBasis) predicate.CustomCurrency { + return predicate.CustomCurrency(func(s *sql.Selector) { + step := newCostBasisHistoryStep() + 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.CustomCurrency) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.CustomCurrency) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.CustomCurrency) predicate.CustomCurrency { + return predicate.CustomCurrency(sql.NotPredicates(p)) +} diff --git a/ent/db/customcurrency_create.go b/ent/db/customcurrency_create.go new file mode 100644 index 0000000000000000000000000000000000000000..788bc95746fca22c60a86bb6e800108411e5d1fe --- /dev/null +++ b/ent/db/customcurrency_create.go @@ -0,0 +1,825 @@ +// 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/currencycostbasis" + "github.com/openmeterio/openmeter/openmeter/ent/db/customcurrency" +) + +// CustomCurrencyCreate is the builder for creating a CustomCurrency entity. +type CustomCurrencyCreate struct { + config + mutation *CustomCurrencyMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *CustomCurrencyCreate) SetNamespace(v string) *CustomCurrencyCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *CustomCurrencyCreate) SetCreatedAt(v time.Time) *CustomCurrencyCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *CustomCurrencyCreate) SetNillableCreatedAt(v *time.Time) *CustomCurrencyCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *CustomCurrencyCreate) SetUpdatedAt(v time.Time) *CustomCurrencyCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *CustomCurrencyCreate) SetNillableUpdatedAt(v *time.Time) *CustomCurrencyCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *CustomCurrencyCreate) SetDeletedAt(v time.Time) *CustomCurrencyCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *CustomCurrencyCreate) SetNillableDeletedAt(v *time.Time) *CustomCurrencyCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetCode sets the "code" field. +func (_c *CustomCurrencyCreate) SetCode(v string) *CustomCurrencyCreate { + _c.mutation.SetCode(v) + return _c +} + +// SetName sets the "name" field. +func (_c *CustomCurrencyCreate) SetName(v string) *CustomCurrencyCreate { + _c.mutation.SetName(v) + return _c +} + +// SetSymbol sets the "symbol" field. +func (_c *CustomCurrencyCreate) SetSymbol(v string) *CustomCurrencyCreate { + _c.mutation.SetSymbol(v) + return _c +} + +// SetID sets the "id" field. +func (_c *CustomCurrencyCreate) SetID(v string) *CustomCurrencyCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *CustomCurrencyCreate) SetNillableID(v *string) *CustomCurrencyCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// AddCostBasisHistoryIDs adds the "cost_basis_history" edge to the CurrencyCostBasis entity by IDs. +func (_c *CustomCurrencyCreate) AddCostBasisHistoryIDs(ids ...string) *CustomCurrencyCreate { + _c.mutation.AddCostBasisHistoryIDs(ids...) + return _c +} + +// AddCostBasisHistory adds the "cost_basis_history" edges to the CurrencyCostBasis entity. +func (_c *CustomCurrencyCreate) AddCostBasisHistory(v ...*CurrencyCostBasis) *CustomCurrencyCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddCostBasisHistoryIDs(ids...) +} + +// Mutation returns the CustomCurrencyMutation object of the builder. +func (_c *CustomCurrencyCreate) Mutation() *CustomCurrencyMutation { + return _c.mutation +} + +// Save creates the CustomCurrency in the database. +func (_c *CustomCurrencyCreate) Save(ctx context.Context) (*CustomCurrency, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *CustomCurrencyCreate) SaveX(ctx context.Context) *CustomCurrency { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *CustomCurrencyCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *CustomCurrencyCreate) 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 *CustomCurrencyCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := customcurrency.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := customcurrency.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := customcurrency.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *CustomCurrencyCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "CustomCurrency.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := customcurrency.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "CustomCurrency.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "CustomCurrency.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "CustomCurrency.updated_at"`)} + } + if _, ok := _c.mutation.Code(); !ok { + return &ValidationError{Name: "code", err: errors.New(`db: missing required field "CustomCurrency.code"`)} + } + if v, ok := _c.mutation.Code(); ok { + if err := customcurrency.CodeValidator(v); err != nil { + return &ValidationError{Name: "code", err: fmt.Errorf(`db: validator failed for field "CustomCurrency.code": %w`, err)} + } + } + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "CustomCurrency.name"`)} + } + if v, ok := _c.mutation.Name(); ok { + if err := customcurrency.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "CustomCurrency.name": %w`, err)} + } + } + if _, ok := _c.mutation.Symbol(); !ok { + return &ValidationError{Name: "symbol", err: errors.New(`db: missing required field "CustomCurrency.symbol"`)} + } + if v, ok := _c.mutation.Symbol(); ok { + if err := customcurrency.SymbolValidator(v); err != nil { + return &ValidationError{Name: "symbol", err: fmt.Errorf(`db: validator failed for field "CustomCurrency.symbol": %w`, err)} + } + } + return nil +} + +func (_c *CustomCurrencyCreate) sqlSave(ctx context.Context) (*CustomCurrency, 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 CustomCurrency.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *CustomCurrencyCreate) createSpec() (*CustomCurrency, *sqlgraph.CreateSpec) { + var ( + _node = &CustomCurrency{config: _c.config} + _spec = sqlgraph.NewCreateSpec(customcurrency.Table, sqlgraph.NewFieldSpec(customcurrency.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(customcurrency.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(customcurrency.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(customcurrency.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(customcurrency.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Code(); ok { + _spec.SetField(customcurrency.FieldCode, field.TypeString, value) + _node.Code = value + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(customcurrency.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Symbol(); ok { + _spec.SetField(customcurrency.FieldSymbol, field.TypeString, value) + _node.Symbol = value + } + if nodes := _c.mutation.CostBasisHistoryIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customcurrency.CostBasisHistoryTable, + Columns: []string{customcurrency.CostBasisHistoryColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(currencycostbasis.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.CustomCurrency.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.CustomCurrencyUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *CustomCurrencyCreate) OnConflict(opts ...sql.ConflictOption) *CustomCurrencyUpsertOne { + _c.conflict = opts + return &CustomCurrencyUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.CustomCurrency.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *CustomCurrencyCreate) OnConflictColumns(columns ...string) *CustomCurrencyUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &CustomCurrencyUpsertOne{ + create: _c, + } +} + +type ( + // CustomCurrencyUpsertOne is the builder for "upsert"-ing + // one CustomCurrency node. + CustomCurrencyUpsertOne struct { + create *CustomCurrencyCreate + } + + // CustomCurrencyUpsert is the "OnConflict" setter. + CustomCurrencyUpsert struct { + *sql.UpdateSet + } +) + +// SetUpdatedAt sets the "updated_at" field. +func (u *CustomCurrencyUpsert) SetUpdatedAt(v time.Time) *CustomCurrencyUpsert { + u.Set(customcurrency.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *CustomCurrencyUpsert) UpdateUpdatedAt() *CustomCurrencyUpsert { + u.SetExcluded(customcurrency.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *CustomCurrencyUpsert) SetDeletedAt(v time.Time) *CustomCurrencyUpsert { + u.Set(customcurrency.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *CustomCurrencyUpsert) UpdateDeletedAt() *CustomCurrencyUpsert { + u.SetExcluded(customcurrency.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *CustomCurrencyUpsert) ClearDeletedAt() *CustomCurrencyUpsert { + u.SetNull(customcurrency.FieldDeletedAt) + return u +} + +// SetName sets the "name" field. +func (u *CustomCurrencyUpsert) SetName(v string) *CustomCurrencyUpsert { + u.Set(customcurrency.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *CustomCurrencyUpsert) UpdateName() *CustomCurrencyUpsert { + u.SetExcluded(customcurrency.FieldName) + return u +} + +// SetSymbol sets the "symbol" field. +func (u *CustomCurrencyUpsert) SetSymbol(v string) *CustomCurrencyUpsert { + u.Set(customcurrency.FieldSymbol, v) + return u +} + +// UpdateSymbol sets the "symbol" field to the value that was provided on create. +func (u *CustomCurrencyUpsert) UpdateSymbol() *CustomCurrencyUpsert { + u.SetExcluded(customcurrency.FieldSymbol) + 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.CustomCurrency.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(customcurrency.FieldID) +// }), +// ). +// Exec(ctx) +func (u *CustomCurrencyUpsertOne) UpdateNewValues() *CustomCurrencyUpsertOne { + 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(customcurrency.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(customcurrency.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(customcurrency.FieldCreatedAt) + } + if _, exists := u.create.mutation.Code(); exists { + s.SetIgnore(customcurrency.FieldCode) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.CustomCurrency.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *CustomCurrencyUpsertOne) Ignore() *CustomCurrencyUpsertOne { + 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 *CustomCurrencyUpsertOne) DoNothing() *CustomCurrencyUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the CustomCurrencyCreate.OnConflict +// documentation for more info. +func (u *CustomCurrencyUpsertOne) Update(set func(*CustomCurrencyUpsert)) *CustomCurrencyUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&CustomCurrencyUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *CustomCurrencyUpsertOne) SetUpdatedAt(v time.Time) *CustomCurrencyUpsertOne { + return u.Update(func(s *CustomCurrencyUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *CustomCurrencyUpsertOne) UpdateUpdatedAt() *CustomCurrencyUpsertOne { + return u.Update(func(s *CustomCurrencyUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *CustomCurrencyUpsertOne) SetDeletedAt(v time.Time) *CustomCurrencyUpsertOne { + return u.Update(func(s *CustomCurrencyUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *CustomCurrencyUpsertOne) UpdateDeletedAt() *CustomCurrencyUpsertOne { + return u.Update(func(s *CustomCurrencyUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *CustomCurrencyUpsertOne) ClearDeletedAt() *CustomCurrencyUpsertOne { + return u.Update(func(s *CustomCurrencyUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *CustomCurrencyUpsertOne) SetName(v string) *CustomCurrencyUpsertOne { + return u.Update(func(s *CustomCurrencyUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *CustomCurrencyUpsertOne) UpdateName() *CustomCurrencyUpsertOne { + return u.Update(func(s *CustomCurrencyUpsert) { + s.UpdateName() + }) +} + +// SetSymbol sets the "symbol" field. +func (u *CustomCurrencyUpsertOne) SetSymbol(v string) *CustomCurrencyUpsertOne { + return u.Update(func(s *CustomCurrencyUpsert) { + s.SetSymbol(v) + }) +} + +// UpdateSymbol sets the "symbol" field to the value that was provided on create. +func (u *CustomCurrencyUpsertOne) UpdateSymbol() *CustomCurrencyUpsertOne { + return u.Update(func(s *CustomCurrencyUpsert) { + s.UpdateSymbol() + }) +} + +// Exec executes the query. +func (u *CustomCurrencyUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for CustomCurrencyCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *CustomCurrencyUpsertOne) 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 *CustomCurrencyUpsertOne) 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: CustomCurrencyUpsertOne.ID is not supported by MySQL driver. Use CustomCurrencyUpsertOne.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 *CustomCurrencyUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// CustomCurrencyCreateBulk is the builder for creating many CustomCurrency entities in bulk. +type CustomCurrencyCreateBulk struct { + config + err error + builders []*CustomCurrencyCreate + conflict []sql.ConflictOption +} + +// Save creates the CustomCurrency entities in the database. +func (_c *CustomCurrencyCreateBulk) Save(ctx context.Context) ([]*CustomCurrency, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*CustomCurrency, 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.(*CustomCurrencyMutation) + 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 *CustomCurrencyCreateBulk) SaveX(ctx context.Context) []*CustomCurrency { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *CustomCurrencyCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *CustomCurrencyCreateBulk) 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.CustomCurrency.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.CustomCurrencyUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *CustomCurrencyCreateBulk) OnConflict(opts ...sql.ConflictOption) *CustomCurrencyUpsertBulk { + _c.conflict = opts + return &CustomCurrencyUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.CustomCurrency.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *CustomCurrencyCreateBulk) OnConflictColumns(columns ...string) *CustomCurrencyUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &CustomCurrencyUpsertBulk{ + create: _c, + } +} + +// CustomCurrencyUpsertBulk is the builder for "upsert"-ing +// a bulk of CustomCurrency nodes. +type CustomCurrencyUpsertBulk struct { + create *CustomCurrencyCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.CustomCurrency.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(customcurrency.FieldID) +// }), +// ). +// Exec(ctx) +func (u *CustomCurrencyUpsertBulk) UpdateNewValues() *CustomCurrencyUpsertBulk { + 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(customcurrency.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(customcurrency.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(customcurrency.FieldCreatedAt) + } + if _, exists := b.mutation.Code(); exists { + s.SetIgnore(customcurrency.FieldCode) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.CustomCurrency.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *CustomCurrencyUpsertBulk) Ignore() *CustomCurrencyUpsertBulk { + 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 *CustomCurrencyUpsertBulk) DoNothing() *CustomCurrencyUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the CustomCurrencyCreateBulk.OnConflict +// documentation for more info. +func (u *CustomCurrencyUpsertBulk) Update(set func(*CustomCurrencyUpsert)) *CustomCurrencyUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&CustomCurrencyUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *CustomCurrencyUpsertBulk) SetUpdatedAt(v time.Time) *CustomCurrencyUpsertBulk { + return u.Update(func(s *CustomCurrencyUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *CustomCurrencyUpsertBulk) UpdateUpdatedAt() *CustomCurrencyUpsertBulk { + return u.Update(func(s *CustomCurrencyUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *CustomCurrencyUpsertBulk) SetDeletedAt(v time.Time) *CustomCurrencyUpsertBulk { + return u.Update(func(s *CustomCurrencyUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *CustomCurrencyUpsertBulk) UpdateDeletedAt() *CustomCurrencyUpsertBulk { + return u.Update(func(s *CustomCurrencyUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *CustomCurrencyUpsertBulk) ClearDeletedAt() *CustomCurrencyUpsertBulk { + return u.Update(func(s *CustomCurrencyUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *CustomCurrencyUpsertBulk) SetName(v string) *CustomCurrencyUpsertBulk { + return u.Update(func(s *CustomCurrencyUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *CustomCurrencyUpsertBulk) UpdateName() *CustomCurrencyUpsertBulk { + return u.Update(func(s *CustomCurrencyUpsert) { + s.UpdateName() + }) +} + +// SetSymbol sets the "symbol" field. +func (u *CustomCurrencyUpsertBulk) SetSymbol(v string) *CustomCurrencyUpsertBulk { + return u.Update(func(s *CustomCurrencyUpsert) { + s.SetSymbol(v) + }) +} + +// UpdateSymbol sets the "symbol" field to the value that was provided on create. +func (u *CustomCurrencyUpsertBulk) UpdateSymbol() *CustomCurrencyUpsertBulk { + return u.Update(func(s *CustomCurrencyUpsert) { + s.UpdateSymbol() + }) +} + +// Exec executes the query. +func (u *CustomCurrencyUpsertBulk) 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 CustomCurrencyCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for CustomCurrencyCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *CustomCurrencyUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/customcurrency_delete.go b/ent/db/customcurrency_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..86a086f97b700342e390fb3e983c1905a6bee8ef --- /dev/null +++ b/ent/db/customcurrency_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/customcurrency" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// CustomCurrencyDelete is the builder for deleting a CustomCurrency entity. +type CustomCurrencyDelete struct { + config + hooks []Hook + mutation *CustomCurrencyMutation +} + +// Where appends a list predicates to the CustomCurrencyDelete builder. +func (_d *CustomCurrencyDelete) Where(ps ...predicate.CustomCurrency) *CustomCurrencyDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *CustomCurrencyDelete) 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 *CustomCurrencyDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *CustomCurrencyDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(customcurrency.Table, sqlgraph.NewFieldSpec(customcurrency.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 +} + +// CustomCurrencyDeleteOne is the builder for deleting a single CustomCurrency entity. +type CustomCurrencyDeleteOne struct { + _d *CustomCurrencyDelete +} + +// Where appends a list predicates to the CustomCurrencyDelete builder. +func (_d *CustomCurrencyDeleteOne) Where(ps ...predicate.CustomCurrency) *CustomCurrencyDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *CustomCurrencyDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{customcurrency.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *CustomCurrencyDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/customcurrency_query.go b/ent/db/customcurrency_query.go new file mode 100644 index 0000000000000000000000000000000000000000..c60f04cbdcfd646866b5881bff74b3d7d708a2ec --- /dev/null +++ b/ent/db/customcurrency_query.go @@ -0,0 +1,645 @@ +// 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/currencycostbasis" + "github.com/openmeterio/openmeter/openmeter/ent/db/customcurrency" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// CustomCurrencyQuery is the builder for querying CustomCurrency entities. +type CustomCurrencyQuery struct { + config + ctx *QueryContext + order []customcurrency.OrderOption + inters []Interceptor + predicates []predicate.CustomCurrency + withCostBasisHistory *CurrencyCostBasisQuery + 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 CustomCurrencyQuery builder. +func (_q *CustomCurrencyQuery) Where(ps ...predicate.CustomCurrency) *CustomCurrencyQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *CustomCurrencyQuery) Limit(limit int) *CustomCurrencyQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *CustomCurrencyQuery) Offset(offset int) *CustomCurrencyQuery { + _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 *CustomCurrencyQuery) Unique(unique bool) *CustomCurrencyQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *CustomCurrencyQuery) Order(o ...customcurrency.OrderOption) *CustomCurrencyQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryCostBasisHistory chains the current query on the "cost_basis_history" edge. +func (_q *CustomCurrencyQuery) QueryCostBasisHistory() *CurrencyCostBasisQuery { + query := (&CurrencyCostBasisClient{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(customcurrency.Table, customcurrency.FieldID, selector), + sqlgraph.To(currencycostbasis.Table, currencycostbasis.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, customcurrency.CostBasisHistoryTable, customcurrency.CostBasisHistoryColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first CustomCurrency entity from the query. +// Returns a *NotFoundError when no CustomCurrency was found. +func (_q *CustomCurrencyQuery) First(ctx context.Context) (*CustomCurrency, 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{customcurrency.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *CustomCurrencyQuery) FirstX(ctx context.Context) *CustomCurrency { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first CustomCurrency ID from the query. +// Returns a *NotFoundError when no CustomCurrency ID was found. +func (_q *CustomCurrencyQuery) 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{customcurrency.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *CustomCurrencyQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single CustomCurrency entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one CustomCurrency entity is found. +// Returns a *NotFoundError when no CustomCurrency entities are found. +func (_q *CustomCurrencyQuery) Only(ctx context.Context) (*CustomCurrency, 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{customcurrency.Label} + default: + return nil, &NotSingularError{customcurrency.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *CustomCurrencyQuery) OnlyX(ctx context.Context) *CustomCurrency { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only CustomCurrency ID in the query. +// Returns a *NotSingularError when more than one CustomCurrency ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *CustomCurrencyQuery) 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{customcurrency.Label} + default: + err = &NotSingularError{customcurrency.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *CustomCurrencyQuery) 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 CustomCurrencies. +func (_q *CustomCurrencyQuery) All(ctx context.Context) ([]*CustomCurrency, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*CustomCurrency, *CustomCurrencyQuery]() + return withInterceptors[[]*CustomCurrency](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *CustomCurrencyQuery) AllX(ctx context.Context) []*CustomCurrency { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of CustomCurrency IDs. +func (_q *CustomCurrencyQuery) 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(customcurrency.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *CustomCurrencyQuery) 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 *CustomCurrencyQuery) 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[*CustomCurrencyQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *CustomCurrencyQuery) 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 *CustomCurrencyQuery) 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 *CustomCurrencyQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the CustomCurrencyQuery 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 *CustomCurrencyQuery) Clone() *CustomCurrencyQuery { + if _q == nil { + return nil + } + return &CustomCurrencyQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]customcurrency.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.CustomCurrency{}, _q.predicates...), + withCostBasisHistory: _q.withCostBasisHistory.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithCostBasisHistory tells the query-builder to eager-load the nodes that are connected to +// the "cost_basis_history" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *CustomCurrencyQuery) WithCostBasisHistory(opts ...func(*CurrencyCostBasisQuery)) *CustomCurrencyQuery { + query := (&CurrencyCostBasisClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCostBasisHistory = 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.CustomCurrency.Query(). +// GroupBy(customcurrency.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *CustomCurrencyQuery) GroupBy(field string, fields ...string) *CustomCurrencyGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &CustomCurrencyGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = customcurrency.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.CustomCurrency.Query(). +// Select(customcurrency.FieldNamespace). +// Scan(ctx, &v) +func (_q *CustomCurrencyQuery) Select(fields ...string) *CustomCurrencySelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &CustomCurrencySelect{CustomCurrencyQuery: _q} + sbuild.label = customcurrency.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a CustomCurrencySelect configured with the given aggregations. +func (_q *CustomCurrencyQuery) Aggregate(fns ...AggregateFunc) *CustomCurrencySelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *CustomCurrencyQuery) 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 !customcurrency.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 *CustomCurrencyQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*CustomCurrency, error) { + var ( + nodes = []*CustomCurrency{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withCostBasisHistory != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*CustomCurrency).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &CustomCurrency{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.withCostBasisHistory; query != nil { + if err := _q.loadCostBasisHistory(ctx, query, nodes, + func(n *CustomCurrency) { n.Edges.CostBasisHistory = []*CurrencyCostBasis{} }, + func(n *CustomCurrency, e *CurrencyCostBasis) { + n.Edges.CostBasisHistory = append(n.Edges.CostBasisHistory, e) + }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *CustomCurrencyQuery) loadCostBasisHistory(ctx context.Context, query *CurrencyCostBasisQuery, nodes []*CustomCurrency, init func(*CustomCurrency), assign func(*CustomCurrency, *CurrencyCostBasis)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*CustomCurrency) + 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(currencycostbasis.FieldCurrencyID) + } + query.Where(predicate.CurrencyCostBasis(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(customcurrency.CostBasisHistoryColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.CurrencyID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "currency_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *CustomCurrencyQuery) 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 *CustomCurrencyQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(customcurrency.Table, customcurrency.Columns, sqlgraph.NewFieldSpec(customcurrency.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, customcurrency.FieldID) + for i := range fields { + if fields[i] != customcurrency.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 *CustomCurrencyQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(customcurrency.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = customcurrency.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 *CustomCurrencyQuery) ForUpdate(opts ...sql.LockOption) *CustomCurrencyQuery { + 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 *CustomCurrencyQuery) ForShare(opts ...sql.LockOption) *CustomCurrencyQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// CustomCurrencyGroupBy is the group-by builder for CustomCurrency entities. +type CustomCurrencyGroupBy struct { + selector + build *CustomCurrencyQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *CustomCurrencyGroupBy) Aggregate(fns ...AggregateFunc) *CustomCurrencyGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *CustomCurrencyGroupBy) 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[*CustomCurrencyQuery, *CustomCurrencyGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *CustomCurrencyGroupBy) sqlScan(ctx context.Context, root *CustomCurrencyQuery, 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) +} + +// CustomCurrencySelect is the builder for selecting fields of CustomCurrency entities. +type CustomCurrencySelect struct { + *CustomCurrencyQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *CustomCurrencySelect) Aggregate(fns ...AggregateFunc) *CustomCurrencySelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *CustomCurrencySelect) 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[*CustomCurrencyQuery, *CustomCurrencySelect](ctx, _s.CustomCurrencyQuery, _s, _s.inters, v) +} + +func (_s *CustomCurrencySelect) sqlScan(ctx context.Context, root *CustomCurrencyQuery, 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/ent/db/customcurrency_update.go b/ent/db/customcurrency_update.go new file mode 100644 index 0000000000000000000000000000000000000000..d3b678e36a7ae88fc4ae1d67955e489e4bb67c16 --- /dev/null +++ b/ent/db/customcurrency_update.go @@ -0,0 +1,531 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/currencycostbasis" + "github.com/openmeterio/openmeter/openmeter/ent/db/customcurrency" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// CustomCurrencyUpdate is the builder for updating CustomCurrency entities. +type CustomCurrencyUpdate struct { + config + hooks []Hook + mutation *CustomCurrencyMutation +} + +// Where appends a list predicates to the CustomCurrencyUpdate builder. +func (_u *CustomCurrencyUpdate) Where(ps ...predicate.CustomCurrency) *CustomCurrencyUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *CustomCurrencyUpdate) SetUpdatedAt(v time.Time) *CustomCurrencyUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *CustomCurrencyUpdate) SetDeletedAt(v time.Time) *CustomCurrencyUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *CustomCurrencyUpdate) SetNillableDeletedAt(v *time.Time) *CustomCurrencyUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *CustomCurrencyUpdate) ClearDeletedAt() *CustomCurrencyUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *CustomCurrencyUpdate) SetName(v string) *CustomCurrencyUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *CustomCurrencyUpdate) SetNillableName(v *string) *CustomCurrencyUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetSymbol sets the "symbol" field. +func (_u *CustomCurrencyUpdate) SetSymbol(v string) *CustomCurrencyUpdate { + _u.mutation.SetSymbol(v) + return _u +} + +// SetNillableSymbol sets the "symbol" field if the given value is not nil. +func (_u *CustomCurrencyUpdate) SetNillableSymbol(v *string) *CustomCurrencyUpdate { + if v != nil { + _u.SetSymbol(*v) + } + return _u +} + +// AddCostBasisHistoryIDs adds the "cost_basis_history" edge to the CurrencyCostBasis entity by IDs. +func (_u *CustomCurrencyUpdate) AddCostBasisHistoryIDs(ids ...string) *CustomCurrencyUpdate { + _u.mutation.AddCostBasisHistoryIDs(ids...) + return _u +} + +// AddCostBasisHistory adds the "cost_basis_history" edges to the CurrencyCostBasis entity. +func (_u *CustomCurrencyUpdate) AddCostBasisHistory(v ...*CurrencyCostBasis) *CustomCurrencyUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddCostBasisHistoryIDs(ids...) +} + +// Mutation returns the CustomCurrencyMutation object of the builder. +func (_u *CustomCurrencyUpdate) Mutation() *CustomCurrencyMutation { + return _u.mutation +} + +// ClearCostBasisHistory clears all "cost_basis_history" edges to the CurrencyCostBasis entity. +func (_u *CustomCurrencyUpdate) ClearCostBasisHistory() *CustomCurrencyUpdate { + _u.mutation.ClearCostBasisHistory() + return _u +} + +// RemoveCostBasisHistoryIDs removes the "cost_basis_history" edge to CurrencyCostBasis entities by IDs. +func (_u *CustomCurrencyUpdate) RemoveCostBasisHistoryIDs(ids ...string) *CustomCurrencyUpdate { + _u.mutation.RemoveCostBasisHistoryIDs(ids...) + return _u +} + +// RemoveCostBasisHistory removes "cost_basis_history" edges to CurrencyCostBasis entities. +func (_u *CustomCurrencyUpdate) RemoveCostBasisHistory(v ...*CurrencyCostBasis) *CustomCurrencyUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveCostBasisHistoryIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *CustomCurrencyUpdate) 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 *CustomCurrencyUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *CustomCurrencyUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *CustomCurrencyUpdate) 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 *CustomCurrencyUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := customcurrency.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *CustomCurrencyUpdate) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := customcurrency.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "CustomCurrency.name": %w`, err)} + } + } + if v, ok := _u.mutation.Symbol(); ok { + if err := customcurrency.SymbolValidator(v); err != nil { + return &ValidationError{Name: "symbol", err: fmt.Errorf(`db: validator failed for field "CustomCurrency.symbol": %w`, err)} + } + } + return nil +} + +func (_u *CustomCurrencyUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(customcurrency.Table, customcurrency.Columns, sqlgraph.NewFieldSpec(customcurrency.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(customcurrency.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(customcurrency.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(customcurrency.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(customcurrency.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Symbol(); ok { + _spec.SetField(customcurrency.FieldSymbol, field.TypeString, value) + } + if _u.mutation.CostBasisHistoryCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customcurrency.CostBasisHistoryTable, + Columns: []string{customcurrency.CostBasisHistoryColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(currencycostbasis.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedCostBasisHistoryIDs(); len(nodes) > 0 && !_u.mutation.CostBasisHistoryCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customcurrency.CostBasisHistoryTable, + Columns: []string{customcurrency.CostBasisHistoryColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(currencycostbasis.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.CostBasisHistoryIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customcurrency.CostBasisHistoryTable, + Columns: []string{customcurrency.CostBasisHistoryColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(currencycostbasis.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{customcurrency.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// CustomCurrencyUpdateOne is the builder for updating a single CustomCurrency entity. +type CustomCurrencyUpdateOne struct { + config + fields []string + hooks []Hook + mutation *CustomCurrencyMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *CustomCurrencyUpdateOne) SetUpdatedAt(v time.Time) *CustomCurrencyUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *CustomCurrencyUpdateOne) SetDeletedAt(v time.Time) *CustomCurrencyUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *CustomCurrencyUpdateOne) SetNillableDeletedAt(v *time.Time) *CustomCurrencyUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *CustomCurrencyUpdateOne) ClearDeletedAt() *CustomCurrencyUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *CustomCurrencyUpdateOne) SetName(v string) *CustomCurrencyUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *CustomCurrencyUpdateOne) SetNillableName(v *string) *CustomCurrencyUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetSymbol sets the "symbol" field. +func (_u *CustomCurrencyUpdateOne) SetSymbol(v string) *CustomCurrencyUpdateOne { + _u.mutation.SetSymbol(v) + return _u +} + +// SetNillableSymbol sets the "symbol" field if the given value is not nil. +func (_u *CustomCurrencyUpdateOne) SetNillableSymbol(v *string) *CustomCurrencyUpdateOne { + if v != nil { + _u.SetSymbol(*v) + } + return _u +} + +// AddCostBasisHistoryIDs adds the "cost_basis_history" edge to the CurrencyCostBasis entity by IDs. +func (_u *CustomCurrencyUpdateOne) AddCostBasisHistoryIDs(ids ...string) *CustomCurrencyUpdateOne { + _u.mutation.AddCostBasisHistoryIDs(ids...) + return _u +} + +// AddCostBasisHistory adds the "cost_basis_history" edges to the CurrencyCostBasis entity. +func (_u *CustomCurrencyUpdateOne) AddCostBasisHistory(v ...*CurrencyCostBasis) *CustomCurrencyUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddCostBasisHistoryIDs(ids...) +} + +// Mutation returns the CustomCurrencyMutation object of the builder. +func (_u *CustomCurrencyUpdateOne) Mutation() *CustomCurrencyMutation { + return _u.mutation +} + +// ClearCostBasisHistory clears all "cost_basis_history" edges to the CurrencyCostBasis entity. +func (_u *CustomCurrencyUpdateOne) ClearCostBasisHistory() *CustomCurrencyUpdateOne { + _u.mutation.ClearCostBasisHistory() + return _u +} + +// RemoveCostBasisHistoryIDs removes the "cost_basis_history" edge to CurrencyCostBasis entities by IDs. +func (_u *CustomCurrencyUpdateOne) RemoveCostBasisHistoryIDs(ids ...string) *CustomCurrencyUpdateOne { + _u.mutation.RemoveCostBasisHistoryIDs(ids...) + return _u +} + +// RemoveCostBasisHistory removes "cost_basis_history" edges to CurrencyCostBasis entities. +func (_u *CustomCurrencyUpdateOne) RemoveCostBasisHistory(v ...*CurrencyCostBasis) *CustomCurrencyUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveCostBasisHistoryIDs(ids...) +} + +// Where appends a list predicates to the CustomCurrencyUpdate builder. +func (_u *CustomCurrencyUpdateOne) Where(ps ...predicate.CustomCurrency) *CustomCurrencyUpdateOne { + _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 *CustomCurrencyUpdateOne) Select(field string, fields ...string) *CustomCurrencyUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated CustomCurrency entity. +func (_u *CustomCurrencyUpdateOne) Save(ctx context.Context) (*CustomCurrency, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *CustomCurrencyUpdateOne) SaveX(ctx context.Context) *CustomCurrency { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *CustomCurrencyUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *CustomCurrencyUpdateOne) 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 *CustomCurrencyUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := customcurrency.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *CustomCurrencyUpdateOne) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := customcurrency.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "CustomCurrency.name": %w`, err)} + } + } + if v, ok := _u.mutation.Symbol(); ok { + if err := customcurrency.SymbolValidator(v); err != nil { + return &ValidationError{Name: "symbol", err: fmt.Errorf(`db: validator failed for field "CustomCurrency.symbol": %w`, err)} + } + } + return nil +} + +func (_u *CustomCurrencyUpdateOne) sqlSave(ctx context.Context) (_node *CustomCurrency, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(customcurrency.Table, customcurrency.Columns, sqlgraph.NewFieldSpec(customcurrency.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "CustomCurrency.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, customcurrency.FieldID) + for _, f := range fields { + if !customcurrency.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != customcurrency.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(customcurrency.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(customcurrency.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(customcurrency.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(customcurrency.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Symbol(); ok { + _spec.SetField(customcurrency.FieldSymbol, field.TypeString, value) + } + if _u.mutation.CostBasisHistoryCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customcurrency.CostBasisHistoryTable, + Columns: []string{customcurrency.CostBasisHistoryColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(currencycostbasis.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedCostBasisHistoryIDs(); len(nodes) > 0 && !_u.mutation.CostBasisHistoryCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customcurrency.CostBasisHistoryTable, + Columns: []string{customcurrency.CostBasisHistoryColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(currencycostbasis.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.CostBasisHistoryIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customcurrency.CostBasisHistoryTable, + Columns: []string{customcurrency.CostBasisHistoryColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(currencycostbasis.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &CustomCurrency{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{customcurrency.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/ent/db/customer.go b/ent/db/customer.go new file mode 100644 index 0000000000000000000000000000000000000000..cfe9ca4a943df3cdc1f316193eb5e79110f18166 --- /dev/null +++ b/ent/db/customer.go @@ -0,0 +1,490 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/billingcustomeroverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/customer" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// Customer is the model entity for the Customer schema. +type Customer 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"` + // Metadata holds the value of the "metadata" field. + Metadata map[string]string `json:"metadata,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"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Description holds the value of the "description" field. + Description *string `json:"description,omitempty"` + // BillingAddressCountry holds the value of the "billing_address_country" field. + BillingAddressCountry *models.CountryCode `json:"billing_address_country,omitempty"` + // BillingAddressPostalCode holds the value of the "billing_address_postal_code" field. + BillingAddressPostalCode *string `json:"billing_address_postal_code,omitempty"` + // BillingAddressState holds the value of the "billing_address_state" field. + BillingAddressState *string `json:"billing_address_state,omitempty"` + // BillingAddressCity holds the value of the "billing_address_city" field. + BillingAddressCity *string `json:"billing_address_city,omitempty"` + // BillingAddressLine1 holds the value of the "billing_address_line1" field. + BillingAddressLine1 *string `json:"billing_address_line1,omitempty"` + // BillingAddressLine2 holds the value of the "billing_address_line2" field. + BillingAddressLine2 *string `json:"billing_address_line2,omitempty"` + // BillingAddressPhoneNumber holds the value of the "billing_address_phone_number" field. + BillingAddressPhoneNumber *string `json:"billing_address_phone_number,omitempty"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,omitempty"` + // Key holds the value of the "key" field. + Key string `json:"key,omitempty"` + // PrimaryEmail holds the value of the "primary_email" field. + PrimaryEmail *string `json:"primary_email,omitempty"` + // Currency holds the value of the "currency" field. + Currency *currencyx.Code `json:"currency,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the CustomerQuery when eager-loading is set. + Edges CustomerEdges `json:"edges"` + selectValues sql.SelectValues +} + +// CustomerEdges holds the relations/edges for other nodes in the graph. +type CustomerEdges struct { + // Apps holds the value of the apps edge. + Apps []*AppCustomer `json:"apps,omitempty"` + // Subjects holds the value of the subjects edge. + Subjects []*CustomerSubjects `json:"subjects,omitempty"` + // BillingCustomerOverride holds the value of the billing_customer_override edge. + BillingCustomerOverride *BillingCustomerOverride `json:"billing_customer_override,omitempty"` + // BillingInvoice holds the value of the billing_invoice edge. + BillingInvoice []*BillingInvoice `json:"billing_invoice,omitempty"` + // Subscription holds the value of the subscription edge. + Subscription []*Subscription `json:"subscription,omitempty"` + // Entitlements holds the value of the entitlements edge. + Entitlements []*Entitlement `json:"entitlements,omitempty"` + // ChargesCreditPurchase holds the value of the charges_credit_purchase edge. + ChargesCreditPurchase []*ChargeCreditPurchase `json:"charges_credit_purchase,omitempty"` + // ChargesFlatFee holds the value of the charges_flat_fee edge. + ChargesFlatFee []*ChargeFlatFee `json:"charges_flat_fee,omitempty"` + // ChargesUsageBased holds the value of the charges_usage_based edge. + ChargesUsageBased []*ChargeUsageBased `json:"charges_usage_based,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [9]bool +} + +// AppsOrErr returns the Apps value or an error if the edge +// was not loaded in eager-loading. +func (e CustomerEdges) AppsOrErr() ([]*AppCustomer, error) { + if e.loadedTypes[0] { + return e.Apps, nil + } + return nil, &NotLoadedError{edge: "apps"} +} + +// SubjectsOrErr returns the Subjects value or an error if the edge +// was not loaded in eager-loading. +func (e CustomerEdges) SubjectsOrErr() ([]*CustomerSubjects, error) { + if e.loadedTypes[1] { + return e.Subjects, nil + } + return nil, &NotLoadedError{edge: "subjects"} +} + +// BillingCustomerOverrideOrErr returns the BillingCustomerOverride value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e CustomerEdges) BillingCustomerOverrideOrErr() (*BillingCustomerOverride, error) { + if e.BillingCustomerOverride != nil { + return e.BillingCustomerOverride, nil + } else if e.loadedTypes[2] { + return nil, &NotFoundError{label: billingcustomeroverride.Label} + } + return nil, &NotLoadedError{edge: "billing_customer_override"} +} + +// BillingInvoiceOrErr returns the BillingInvoice value or an error if the edge +// was not loaded in eager-loading. +func (e CustomerEdges) BillingInvoiceOrErr() ([]*BillingInvoice, error) { + if e.loadedTypes[3] { + return e.BillingInvoice, nil + } + return nil, &NotLoadedError{edge: "billing_invoice"} +} + +// SubscriptionOrErr returns the Subscription value or an error if the edge +// was not loaded in eager-loading. +func (e CustomerEdges) SubscriptionOrErr() ([]*Subscription, error) { + if e.loadedTypes[4] { + return e.Subscription, nil + } + return nil, &NotLoadedError{edge: "subscription"} +} + +// EntitlementsOrErr returns the Entitlements value or an error if the edge +// was not loaded in eager-loading. +func (e CustomerEdges) EntitlementsOrErr() ([]*Entitlement, error) { + if e.loadedTypes[5] { + return e.Entitlements, nil + } + return nil, &NotLoadedError{edge: "entitlements"} +} + +// ChargesCreditPurchaseOrErr returns the ChargesCreditPurchase value or an error if the edge +// was not loaded in eager-loading. +func (e CustomerEdges) ChargesCreditPurchaseOrErr() ([]*ChargeCreditPurchase, error) { + if e.loadedTypes[6] { + return e.ChargesCreditPurchase, nil + } + return nil, &NotLoadedError{edge: "charges_credit_purchase"} +} + +// ChargesFlatFeeOrErr returns the ChargesFlatFee value or an error if the edge +// was not loaded in eager-loading. +func (e CustomerEdges) ChargesFlatFeeOrErr() ([]*ChargeFlatFee, error) { + if e.loadedTypes[7] { + return e.ChargesFlatFee, nil + } + return nil, &NotLoadedError{edge: "charges_flat_fee"} +} + +// ChargesUsageBasedOrErr returns the ChargesUsageBased value or an error if the edge +// was not loaded in eager-loading. +func (e CustomerEdges) ChargesUsageBasedOrErr() ([]*ChargeUsageBased, error) { + if e.loadedTypes[8] { + return e.ChargesUsageBased, nil + } + return nil, &NotLoadedError{edge: "charges_usage_based"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Customer) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case customer.FieldMetadata, customer.FieldAnnotations: + values[i] = new([]byte) + case customer.FieldID, customer.FieldNamespace, customer.FieldName, customer.FieldDescription, customer.FieldBillingAddressCountry, customer.FieldBillingAddressPostalCode, customer.FieldBillingAddressState, customer.FieldBillingAddressCity, customer.FieldBillingAddressLine1, customer.FieldBillingAddressLine2, customer.FieldBillingAddressPhoneNumber, customer.FieldKey, customer.FieldPrimaryEmail, customer.FieldCurrency: + values[i] = new(sql.NullString) + case customer.FieldCreatedAt, customer.FieldUpdatedAt, customer.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 Customer fields. +func (_m *Customer) 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 customer.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 customer.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 customer.FieldMetadata: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field metadata", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Metadata); err != nil { + return fmt.Errorf("unmarshal field metadata: %w", err) + } + } + case customer.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 customer.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 customer.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 customer.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case customer.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + _m.Description = new(string) + *_m.Description = value.String + } + case customer.FieldBillingAddressCountry: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field billing_address_country", values[i]) + } else if value.Valid { + _m.BillingAddressCountry = new(models.CountryCode) + *_m.BillingAddressCountry = models.CountryCode(value.String) + } + case customer.FieldBillingAddressPostalCode: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field billing_address_postal_code", values[i]) + } else if value.Valid { + _m.BillingAddressPostalCode = new(string) + *_m.BillingAddressPostalCode = value.String + } + case customer.FieldBillingAddressState: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field billing_address_state", values[i]) + } else if value.Valid { + _m.BillingAddressState = new(string) + *_m.BillingAddressState = value.String + } + case customer.FieldBillingAddressCity: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field billing_address_city", values[i]) + } else if value.Valid { + _m.BillingAddressCity = new(string) + *_m.BillingAddressCity = value.String + } + case customer.FieldBillingAddressLine1: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field billing_address_line1", values[i]) + } else if value.Valid { + _m.BillingAddressLine1 = new(string) + *_m.BillingAddressLine1 = value.String + } + case customer.FieldBillingAddressLine2: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field billing_address_line2", values[i]) + } else if value.Valid { + _m.BillingAddressLine2 = new(string) + *_m.BillingAddressLine2 = value.String + } + case customer.FieldBillingAddressPhoneNumber: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field billing_address_phone_number", values[i]) + } else if value.Valid { + _m.BillingAddressPhoneNumber = new(string) + *_m.BillingAddressPhoneNumber = value.String + } + case customer.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 customer.FieldKey: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field key", values[i]) + } else if value.Valid { + _m.Key = value.String + } + case customer.FieldPrimaryEmail: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field primary_email", values[i]) + } else if value.Valid { + _m.PrimaryEmail = new(string) + *_m.PrimaryEmail = value.String + } + case customer.FieldCurrency: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field currency", values[i]) + } else if value.Valid { + _m.Currency = new(currencyx.Code) + *_m.Currency = currencyx.Code(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 Customer. +// This includes values selected through modifiers, order, etc. +func (_m *Customer) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryApps queries the "apps" edge of the Customer entity. +func (_m *Customer) QueryApps() *AppCustomerQuery { + return NewCustomerClient(_m.config).QueryApps(_m) +} + +// QuerySubjects queries the "subjects" edge of the Customer entity. +func (_m *Customer) QuerySubjects() *CustomerSubjectsQuery { + return NewCustomerClient(_m.config).QuerySubjects(_m) +} + +// QueryBillingCustomerOverride queries the "billing_customer_override" edge of the Customer entity. +func (_m *Customer) QueryBillingCustomerOverride() *BillingCustomerOverrideQuery { + return NewCustomerClient(_m.config).QueryBillingCustomerOverride(_m) +} + +// QueryBillingInvoice queries the "billing_invoice" edge of the Customer entity. +func (_m *Customer) QueryBillingInvoice() *BillingInvoiceQuery { + return NewCustomerClient(_m.config).QueryBillingInvoice(_m) +} + +// QuerySubscription queries the "subscription" edge of the Customer entity. +func (_m *Customer) QuerySubscription() *SubscriptionQuery { + return NewCustomerClient(_m.config).QuerySubscription(_m) +} + +// QueryEntitlements queries the "entitlements" edge of the Customer entity. +func (_m *Customer) QueryEntitlements() *EntitlementQuery { + return NewCustomerClient(_m.config).QueryEntitlements(_m) +} + +// QueryChargesCreditPurchase queries the "charges_credit_purchase" edge of the Customer entity. +func (_m *Customer) QueryChargesCreditPurchase() *ChargeCreditPurchaseQuery { + return NewCustomerClient(_m.config).QueryChargesCreditPurchase(_m) +} + +// QueryChargesFlatFee queries the "charges_flat_fee" edge of the Customer entity. +func (_m *Customer) QueryChargesFlatFee() *ChargeFlatFeeQuery { + return NewCustomerClient(_m.config).QueryChargesFlatFee(_m) +} + +// QueryChargesUsageBased queries the "charges_usage_based" edge of the Customer entity. +func (_m *Customer) QueryChargesUsageBased() *ChargeUsageBasedQuery { + return NewCustomerClient(_m.config).QueryChargesUsageBased(_m) +} + +// Update returns a builder for updating this Customer. +// Note that you need to call Customer.Unwrap() before calling this method if this Customer +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Customer) Update() *CustomerUpdateOne { + return NewCustomerClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Customer 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 *Customer) Unwrap() *Customer { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: Customer is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Customer) String() string { + var builder strings.Builder + builder.WriteString("Customer(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("metadata=") + builder.WriteString(fmt.Sprintf("%v", _m.Metadata)) + 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("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + if v := _m.Description; v != nil { + builder.WriteString("description=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.BillingAddressCountry; v != nil { + builder.WriteString("billing_address_country=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.BillingAddressPostalCode; v != nil { + builder.WriteString("billing_address_postal_code=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.BillingAddressState; v != nil { + builder.WriteString("billing_address_state=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.BillingAddressCity; v != nil { + builder.WriteString("billing_address_city=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.BillingAddressLine1; v != nil { + builder.WriteString("billing_address_line1=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.BillingAddressLine2; v != nil { + builder.WriteString("billing_address_line2=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.BillingAddressPhoneNumber; v != nil { + builder.WriteString("billing_address_phone_number=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + builder.WriteString(", ") + builder.WriteString("key=") + builder.WriteString(_m.Key) + builder.WriteString(", ") + if v := _m.PrimaryEmail; v != nil { + builder.WriteString("primary_email=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.Currency; v != nil { + builder.WriteString("currency=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteByte(')') + return builder.String() +} + +// Customers is a parsable slice of Customer. +type Customers []*Customer diff --git a/ent/db/customer/customer.go b/ent/db/customer/customer.go new file mode 100644 index 0000000000000000000000000000000000000000..32c652119ceec2f60746e8a67bc0b207eea0d7a9 --- /dev/null +++ b/ent/db/customer/customer.go @@ -0,0 +1,456 @@ +// Code generated by ent, DO NOT EDIT. + +package customer + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the customer type in the database. + Label = "customer" + // 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" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // 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" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // FieldBillingAddressCountry holds the string denoting the billing_address_country field in the database. + FieldBillingAddressCountry = "billing_address_country" + // FieldBillingAddressPostalCode holds the string denoting the billing_address_postal_code field in the database. + FieldBillingAddressPostalCode = "billing_address_postal_code" + // FieldBillingAddressState holds the string denoting the billing_address_state field in the database. + FieldBillingAddressState = "billing_address_state" + // FieldBillingAddressCity holds the string denoting the billing_address_city field in the database. + FieldBillingAddressCity = "billing_address_city" + // FieldBillingAddressLine1 holds the string denoting the billing_address_line1 field in the database. + FieldBillingAddressLine1 = "billing_address_line1" + // FieldBillingAddressLine2 holds the string denoting the billing_address_line2 field in the database. + FieldBillingAddressLine2 = "billing_address_line2" + // FieldBillingAddressPhoneNumber holds the string denoting the billing_address_phone_number field in the database. + FieldBillingAddressPhoneNumber = "billing_address_phone_number" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // FieldKey holds the string denoting the key field in the database. + FieldKey = "key" + // FieldPrimaryEmail holds the string denoting the primary_email field in the database. + FieldPrimaryEmail = "primary_email" + // FieldCurrency holds the string denoting the currency field in the database. + FieldCurrency = "currency" + // EdgeApps holds the string denoting the apps edge name in mutations. + EdgeApps = "apps" + // EdgeSubjects holds the string denoting the subjects edge name in mutations. + EdgeSubjects = "subjects" + // EdgeBillingCustomerOverride holds the string denoting the billing_customer_override edge name in mutations. + EdgeBillingCustomerOverride = "billing_customer_override" + // EdgeBillingInvoice holds the string denoting the billing_invoice edge name in mutations. + EdgeBillingInvoice = "billing_invoice" + // EdgeSubscription holds the string denoting the subscription edge name in mutations. + EdgeSubscription = "subscription" + // EdgeEntitlements holds the string denoting the entitlements edge name in mutations. + EdgeEntitlements = "entitlements" + // EdgeChargesCreditPurchase holds the string denoting the charges_credit_purchase edge name in mutations. + EdgeChargesCreditPurchase = "charges_credit_purchase" + // EdgeChargesFlatFee holds the string denoting the charges_flat_fee edge name in mutations. + EdgeChargesFlatFee = "charges_flat_fee" + // EdgeChargesUsageBased holds the string denoting the charges_usage_based edge name in mutations. + EdgeChargesUsageBased = "charges_usage_based" + // Table holds the table name of the customer in the database. + Table = "customers" + // AppsTable is the table that holds the apps relation/edge. + AppsTable = "app_customers" + // AppsInverseTable is the table name for the AppCustomer entity. + // It exists in this package in order to avoid circular dependency with the "appcustomer" package. + AppsInverseTable = "app_customers" + // AppsColumn is the table column denoting the apps relation/edge. + AppsColumn = "customer_id" + // SubjectsTable is the table that holds the subjects relation/edge. + SubjectsTable = "customer_subjects" + // SubjectsInverseTable is the table name for the CustomerSubjects entity. + // It exists in this package in order to avoid circular dependency with the "customersubjects" package. + SubjectsInverseTable = "customer_subjects" + // SubjectsColumn is the table column denoting the subjects relation/edge. + SubjectsColumn = "customer_id" + // BillingCustomerOverrideTable is the table that holds the billing_customer_override relation/edge. + BillingCustomerOverrideTable = "billing_customer_overrides" + // BillingCustomerOverrideInverseTable is the table name for the BillingCustomerOverride entity. + // It exists in this package in order to avoid circular dependency with the "billingcustomeroverride" package. + BillingCustomerOverrideInverseTable = "billing_customer_overrides" + // BillingCustomerOverrideColumn is the table column denoting the billing_customer_override relation/edge. + BillingCustomerOverrideColumn = "customer_id" + // BillingInvoiceTable is the table that holds the billing_invoice relation/edge. + BillingInvoiceTable = "billing_invoices" + // BillingInvoiceInverseTable is the table name for the BillingInvoice entity. + // It exists in this package in order to avoid circular dependency with the "billinginvoice" package. + BillingInvoiceInverseTable = "billing_invoices" + // BillingInvoiceColumn is the table column denoting the billing_invoice relation/edge. + BillingInvoiceColumn = "customer_id" + // SubscriptionTable is the table that holds the subscription relation/edge. + SubscriptionTable = "subscriptions" + // SubscriptionInverseTable is the table name for the Subscription entity. + // It exists in this package in order to avoid circular dependency with the "subscription" package. + SubscriptionInverseTable = "subscriptions" + // SubscriptionColumn is the table column denoting the subscription relation/edge. + SubscriptionColumn = "customer_id" + // EntitlementsTable is the table that holds the entitlements relation/edge. + EntitlementsTable = "entitlements" + // EntitlementsInverseTable is the table name for the Entitlement entity. + // It exists in this package in order to avoid circular dependency with the "entitlement" package. + EntitlementsInverseTable = "entitlements" + // EntitlementsColumn is the table column denoting the entitlements relation/edge. + EntitlementsColumn = "customer_id" + // ChargesCreditPurchaseTable is the table that holds the charges_credit_purchase relation/edge. + ChargesCreditPurchaseTable = "charge_credit_purchases" + // ChargesCreditPurchaseInverseTable is the table name for the ChargeCreditPurchase entity. + // It exists in this package in order to avoid circular dependency with the "chargecreditpurchase" package. + ChargesCreditPurchaseInverseTable = "charge_credit_purchases" + // ChargesCreditPurchaseColumn is the table column denoting the charges_credit_purchase relation/edge. + ChargesCreditPurchaseColumn = "customer_id" + // ChargesFlatFeeTable is the table that holds the charges_flat_fee relation/edge. + ChargesFlatFeeTable = "charge_flat_fees" + // ChargesFlatFeeInverseTable is the table name for the ChargeFlatFee entity. + // It exists in this package in order to avoid circular dependency with the "chargeflatfee" package. + ChargesFlatFeeInverseTable = "charge_flat_fees" + // ChargesFlatFeeColumn is the table column denoting the charges_flat_fee relation/edge. + ChargesFlatFeeColumn = "customer_id" + // ChargesUsageBasedTable is the table that holds the charges_usage_based relation/edge. + ChargesUsageBasedTable = "charge_usage_based" + // ChargesUsageBasedInverseTable is the table name for the ChargeUsageBased entity. + // It exists in this package in order to avoid circular dependency with the "chargeusagebased" package. + ChargesUsageBasedInverseTable = "charge_usage_based" + // ChargesUsageBasedColumn is the table column denoting the charges_usage_based relation/edge. + ChargesUsageBasedColumn = "customer_id" +) + +// Columns holds all SQL columns for customer fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldMetadata, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldName, + FieldDescription, + FieldBillingAddressCountry, + FieldBillingAddressPostalCode, + FieldBillingAddressState, + FieldBillingAddressCity, + FieldBillingAddressLine1, + FieldBillingAddressLine2, + FieldBillingAddressPhoneNumber, + FieldAnnotations, + FieldKey, + FieldPrimaryEmail, + FieldCurrency, +} + +// 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 + // BillingAddressCountryValidator is a validator for the "billing_address_country" field. It is called by the builders before save. + BillingAddressCountryValidator func(string) error + // CurrencyValidator is a validator for the "currency" field. It is called by the builders before save. + CurrencyValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// OrderOption defines the ordering options for the Customer 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() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, opts...).ToFunc() +} + +// ByBillingAddressCountry orders the results by the billing_address_country field. +func ByBillingAddressCountry(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBillingAddressCountry, opts...).ToFunc() +} + +// ByBillingAddressPostalCode orders the results by the billing_address_postal_code field. +func ByBillingAddressPostalCode(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBillingAddressPostalCode, opts...).ToFunc() +} + +// ByBillingAddressState orders the results by the billing_address_state field. +func ByBillingAddressState(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBillingAddressState, opts...).ToFunc() +} + +// ByBillingAddressCity orders the results by the billing_address_city field. +func ByBillingAddressCity(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBillingAddressCity, opts...).ToFunc() +} + +// ByBillingAddressLine1 orders the results by the billing_address_line1 field. +func ByBillingAddressLine1(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBillingAddressLine1, opts...).ToFunc() +} + +// ByBillingAddressLine2 orders the results by the billing_address_line2 field. +func ByBillingAddressLine2(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBillingAddressLine2, opts...).ToFunc() +} + +// ByBillingAddressPhoneNumber orders the results by the billing_address_phone_number field. +func ByBillingAddressPhoneNumber(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBillingAddressPhoneNumber, opts...).ToFunc() +} + +// ByKey orders the results by the key field. +func ByKey(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldKey, opts...).ToFunc() +} + +// ByPrimaryEmail orders the results by the primary_email field. +func ByPrimaryEmail(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPrimaryEmail, opts...).ToFunc() +} + +// ByCurrency orders the results by the currency field. +func ByCurrency(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCurrency, opts...).ToFunc() +} + +// ByAppsCount orders the results by apps count. +func ByAppsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newAppsStep(), opts...) + } +} + +// ByApps orders the results by apps terms. +func ByApps(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newAppsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// BySubjectsCount orders the results by subjects count. +func BySubjectsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newSubjectsStep(), opts...) + } +} + +// BySubjects orders the results by subjects terms. +func BySubjects(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubjectsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByBillingCustomerOverrideField orders the results by billing_customer_override field. +func ByBillingCustomerOverrideField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBillingCustomerOverrideStep(), sql.OrderByField(field, opts...)) + } +} + +// ByBillingInvoiceCount orders the results by billing_invoice count. +func ByBillingInvoiceCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newBillingInvoiceStep(), opts...) + } +} + +// ByBillingInvoice orders the results by billing_invoice terms. +func ByBillingInvoice(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBillingInvoiceStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// BySubscriptionCount orders the results by subscription count. +func BySubscriptionCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newSubscriptionStep(), opts...) + } +} + +// BySubscription orders the results by subscription terms. +func BySubscription(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubscriptionStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByEntitlementsCount orders the results by entitlements count. +func ByEntitlementsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newEntitlementsStep(), opts...) + } +} + +// ByEntitlements orders the results by entitlements terms. +func ByEntitlements(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newEntitlementsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByChargesCreditPurchaseCount orders the results by charges_credit_purchase count. +func ByChargesCreditPurchaseCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newChargesCreditPurchaseStep(), opts...) + } +} + +// ByChargesCreditPurchase orders the results by charges_credit_purchase terms. +func ByChargesCreditPurchase(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newChargesCreditPurchaseStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByChargesFlatFeeCount orders the results by charges_flat_fee count. +func ByChargesFlatFeeCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newChargesFlatFeeStep(), opts...) + } +} + +// ByChargesFlatFee orders the results by charges_flat_fee terms. +func ByChargesFlatFee(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newChargesFlatFeeStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByChargesUsageBasedCount orders the results by charges_usage_based count. +func ByChargesUsageBasedCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newChargesUsageBasedStep(), opts...) + } +} + +// ByChargesUsageBased orders the results by charges_usage_based terms. +func ByChargesUsageBased(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newChargesUsageBasedStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newAppsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(AppsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, AppsTable, AppsColumn), + ) +} +func newSubjectsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SubjectsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SubjectsTable, SubjectsColumn), + ) +} +func newBillingCustomerOverrideStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BillingCustomerOverrideInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, BillingCustomerOverrideTable, BillingCustomerOverrideColumn), + ) +} +func newBillingInvoiceStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BillingInvoiceInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, BillingInvoiceTable, BillingInvoiceColumn), + ) +} +func newSubscriptionStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SubscriptionInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SubscriptionTable, SubscriptionColumn), + ) +} +func newEntitlementsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(EntitlementsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, EntitlementsTable, EntitlementsColumn), + ) +} +func newChargesCreditPurchaseStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ChargesCreditPurchaseInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ChargesCreditPurchaseTable, ChargesCreditPurchaseColumn), + ) +} +func newChargesFlatFeeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ChargesFlatFeeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ChargesFlatFeeTable, ChargesFlatFeeColumn), + ) +} +func newChargesUsageBasedStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ChargesUsageBasedInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ChargesUsageBasedTable, ChargesUsageBasedColumn), + ) +} diff --git a/ent/db/customer/where.go b/ent/db/customer/where.go new file mode 100644 index 0000000000000000000000000000000000000000..8e04a95b6a5692cdb2b4aa1b68f13a226afb110e --- /dev/null +++ b/ent/db/customer/where.go @@ -0,0 +1,1515 @@ +// Code generated by ent, DO NOT EDIT. + +package customer + +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/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.Customer { + return predicate.Customer(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.Customer { + return predicate.Customer(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.Customer { + return predicate.Customer(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.Customer { + return predicate.Customer(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.Customer { + return predicate.Customer(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.Customer { + return predicate.Customer(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.Customer { + return predicate.Customer(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.Customer { + return predicate.Customer(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.Customer { + return predicate.Customer(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.Customer { + return predicate.Customer(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.Customer { + return predicate.Customer(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.Customer { + return predicate.Customer(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.Customer { + return predicate.Customer(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldName, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldDescription, v)) +} + +// BillingAddressCountry applies equality check predicate on the "billing_address_country" field. It's identical to BillingAddressCountryEQ. +func BillingAddressCountry(v models.CountryCode) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldEQ(FieldBillingAddressCountry, vc)) +} + +// BillingAddressPostalCode applies equality check predicate on the "billing_address_postal_code" field. It's identical to BillingAddressPostalCodeEQ. +func BillingAddressPostalCode(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldBillingAddressPostalCode, v)) +} + +// BillingAddressState applies equality check predicate on the "billing_address_state" field. It's identical to BillingAddressStateEQ. +func BillingAddressState(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldBillingAddressState, v)) +} + +// BillingAddressCity applies equality check predicate on the "billing_address_city" field. It's identical to BillingAddressCityEQ. +func BillingAddressCity(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldBillingAddressCity, v)) +} + +// BillingAddressLine1 applies equality check predicate on the "billing_address_line1" field. It's identical to BillingAddressLine1EQ. +func BillingAddressLine1(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldBillingAddressLine1, v)) +} + +// BillingAddressLine2 applies equality check predicate on the "billing_address_line2" field. It's identical to BillingAddressLine2EQ. +func BillingAddressLine2(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldBillingAddressLine2, v)) +} + +// BillingAddressPhoneNumber applies equality check predicate on the "billing_address_phone_number" field. It's identical to BillingAddressPhoneNumberEQ. +func BillingAddressPhoneNumber(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldBillingAddressPhoneNumber, v)) +} + +// Key applies equality check predicate on the "key" field. It's identical to KeyEQ. +func Key(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldKey, v)) +} + +// PrimaryEmail applies equality check predicate on the "primary_email" field. It's identical to PrimaryEmailEQ. +func PrimaryEmail(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldPrimaryEmail, v)) +} + +// Currency applies equality check predicate on the "currency" field. It's identical to CurrencyEQ. +func Currency(v currencyx.Code) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldEQ(FieldCurrency, vc)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.Customer { + return predicate.Customer(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.Customer { + return predicate.Customer(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.Customer { + return predicate.Customer(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldContainsFold(FieldNamespace, v)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.Customer { + return predicate.Customer(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.Customer { + return predicate.Customer(sql.FieldNotNull(FieldMetadata)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Customer { + return predicate.Customer(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Customer { + return predicate.Customer(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Customer { + return predicate.Customer(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Customer { + return predicate.Customer(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Customer { + return predicate.Customer(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Customer { + return predicate.Customer(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Customer { + return predicate.Customer(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.Customer { + return predicate.Customer(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.Customer { + return predicate.Customer(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.Customer { + return predicate.Customer(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.Customer { + return predicate.Customer(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.Customer { + return predicate.Customer(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.Customer { + return predicate.Customer(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.Customer { + return predicate.Customer(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.Customer { + return predicate.Customer(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.Customer { + return predicate.Customer(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.Customer { + return predicate.Customer(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.Customer { + return predicate.Customer(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.Customer { + return predicate.Customer(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.Customer { + return predicate.Customer(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.Customer { + return predicate.Customer(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.Customer { + return predicate.Customer(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.Customer { + return predicate.Customer(sql.FieldNotNull(FieldDeletedAt)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.Customer { + return predicate.Customer(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.Customer { + return predicate.Customer(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.Customer { + return predicate.Customer(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldContainsFold(FieldName, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.Customer { + return predicate.Customer(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.Customer { + return predicate.Customer(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.Customer { + return predicate.Customer(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.Customer { + return predicate.Customer(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.Customer { + return predicate.Customer(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldContainsFold(FieldDescription, v)) +} + +// BillingAddressCountryEQ applies the EQ predicate on the "billing_address_country" field. +func BillingAddressCountryEQ(v models.CountryCode) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldEQ(FieldBillingAddressCountry, vc)) +} + +// BillingAddressCountryNEQ applies the NEQ predicate on the "billing_address_country" field. +func BillingAddressCountryNEQ(v models.CountryCode) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldNEQ(FieldBillingAddressCountry, vc)) +} + +// BillingAddressCountryIn applies the In predicate on the "billing_address_country" field. +func BillingAddressCountryIn(vs ...models.CountryCode) predicate.Customer { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.Customer(sql.FieldIn(FieldBillingAddressCountry, v...)) +} + +// BillingAddressCountryNotIn applies the NotIn predicate on the "billing_address_country" field. +func BillingAddressCountryNotIn(vs ...models.CountryCode) predicate.Customer { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.Customer(sql.FieldNotIn(FieldBillingAddressCountry, v...)) +} + +// BillingAddressCountryGT applies the GT predicate on the "billing_address_country" field. +func BillingAddressCountryGT(v models.CountryCode) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldGT(FieldBillingAddressCountry, vc)) +} + +// BillingAddressCountryGTE applies the GTE predicate on the "billing_address_country" field. +func BillingAddressCountryGTE(v models.CountryCode) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldGTE(FieldBillingAddressCountry, vc)) +} + +// BillingAddressCountryLT applies the LT predicate on the "billing_address_country" field. +func BillingAddressCountryLT(v models.CountryCode) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldLT(FieldBillingAddressCountry, vc)) +} + +// BillingAddressCountryLTE applies the LTE predicate on the "billing_address_country" field. +func BillingAddressCountryLTE(v models.CountryCode) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldLTE(FieldBillingAddressCountry, vc)) +} + +// BillingAddressCountryContains applies the Contains predicate on the "billing_address_country" field. +func BillingAddressCountryContains(v models.CountryCode) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldContains(FieldBillingAddressCountry, vc)) +} + +// BillingAddressCountryHasPrefix applies the HasPrefix predicate on the "billing_address_country" field. +func BillingAddressCountryHasPrefix(v models.CountryCode) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldHasPrefix(FieldBillingAddressCountry, vc)) +} + +// BillingAddressCountryHasSuffix applies the HasSuffix predicate on the "billing_address_country" field. +func BillingAddressCountryHasSuffix(v models.CountryCode) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldHasSuffix(FieldBillingAddressCountry, vc)) +} + +// BillingAddressCountryIsNil applies the IsNil predicate on the "billing_address_country" field. +func BillingAddressCountryIsNil() predicate.Customer { + return predicate.Customer(sql.FieldIsNull(FieldBillingAddressCountry)) +} + +// BillingAddressCountryNotNil applies the NotNil predicate on the "billing_address_country" field. +func BillingAddressCountryNotNil() predicate.Customer { + return predicate.Customer(sql.FieldNotNull(FieldBillingAddressCountry)) +} + +// BillingAddressCountryEqualFold applies the EqualFold predicate on the "billing_address_country" field. +func BillingAddressCountryEqualFold(v models.CountryCode) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldEqualFold(FieldBillingAddressCountry, vc)) +} + +// BillingAddressCountryContainsFold applies the ContainsFold predicate on the "billing_address_country" field. +func BillingAddressCountryContainsFold(v models.CountryCode) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldContainsFold(FieldBillingAddressCountry, vc)) +} + +// BillingAddressPostalCodeEQ applies the EQ predicate on the "billing_address_postal_code" field. +func BillingAddressPostalCodeEQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldBillingAddressPostalCode, v)) +} + +// BillingAddressPostalCodeNEQ applies the NEQ predicate on the "billing_address_postal_code" field. +func BillingAddressPostalCodeNEQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldNEQ(FieldBillingAddressPostalCode, v)) +} + +// BillingAddressPostalCodeIn applies the In predicate on the "billing_address_postal_code" field. +func BillingAddressPostalCodeIn(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldIn(FieldBillingAddressPostalCode, vs...)) +} + +// BillingAddressPostalCodeNotIn applies the NotIn predicate on the "billing_address_postal_code" field. +func BillingAddressPostalCodeNotIn(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldNotIn(FieldBillingAddressPostalCode, vs...)) +} + +// BillingAddressPostalCodeGT applies the GT predicate on the "billing_address_postal_code" field. +func BillingAddressPostalCodeGT(v string) predicate.Customer { + return predicate.Customer(sql.FieldGT(FieldBillingAddressPostalCode, v)) +} + +// BillingAddressPostalCodeGTE applies the GTE predicate on the "billing_address_postal_code" field. +func BillingAddressPostalCodeGTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldGTE(FieldBillingAddressPostalCode, v)) +} + +// BillingAddressPostalCodeLT applies the LT predicate on the "billing_address_postal_code" field. +func BillingAddressPostalCodeLT(v string) predicate.Customer { + return predicate.Customer(sql.FieldLT(FieldBillingAddressPostalCode, v)) +} + +// BillingAddressPostalCodeLTE applies the LTE predicate on the "billing_address_postal_code" field. +func BillingAddressPostalCodeLTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldLTE(FieldBillingAddressPostalCode, v)) +} + +// BillingAddressPostalCodeContains applies the Contains predicate on the "billing_address_postal_code" field. +func BillingAddressPostalCodeContains(v string) predicate.Customer { + return predicate.Customer(sql.FieldContains(FieldBillingAddressPostalCode, v)) +} + +// BillingAddressPostalCodeHasPrefix applies the HasPrefix predicate on the "billing_address_postal_code" field. +func BillingAddressPostalCodeHasPrefix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasPrefix(FieldBillingAddressPostalCode, v)) +} + +// BillingAddressPostalCodeHasSuffix applies the HasSuffix predicate on the "billing_address_postal_code" field. +func BillingAddressPostalCodeHasSuffix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasSuffix(FieldBillingAddressPostalCode, v)) +} + +// BillingAddressPostalCodeIsNil applies the IsNil predicate on the "billing_address_postal_code" field. +func BillingAddressPostalCodeIsNil() predicate.Customer { + return predicate.Customer(sql.FieldIsNull(FieldBillingAddressPostalCode)) +} + +// BillingAddressPostalCodeNotNil applies the NotNil predicate on the "billing_address_postal_code" field. +func BillingAddressPostalCodeNotNil() predicate.Customer { + return predicate.Customer(sql.FieldNotNull(FieldBillingAddressPostalCode)) +} + +// BillingAddressPostalCodeEqualFold applies the EqualFold predicate on the "billing_address_postal_code" field. +func BillingAddressPostalCodeEqualFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldEqualFold(FieldBillingAddressPostalCode, v)) +} + +// BillingAddressPostalCodeContainsFold applies the ContainsFold predicate on the "billing_address_postal_code" field. +func BillingAddressPostalCodeContainsFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldContainsFold(FieldBillingAddressPostalCode, v)) +} + +// BillingAddressStateEQ applies the EQ predicate on the "billing_address_state" field. +func BillingAddressStateEQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldBillingAddressState, v)) +} + +// BillingAddressStateNEQ applies the NEQ predicate on the "billing_address_state" field. +func BillingAddressStateNEQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldNEQ(FieldBillingAddressState, v)) +} + +// BillingAddressStateIn applies the In predicate on the "billing_address_state" field. +func BillingAddressStateIn(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldIn(FieldBillingAddressState, vs...)) +} + +// BillingAddressStateNotIn applies the NotIn predicate on the "billing_address_state" field. +func BillingAddressStateNotIn(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldNotIn(FieldBillingAddressState, vs...)) +} + +// BillingAddressStateGT applies the GT predicate on the "billing_address_state" field. +func BillingAddressStateGT(v string) predicate.Customer { + return predicate.Customer(sql.FieldGT(FieldBillingAddressState, v)) +} + +// BillingAddressStateGTE applies the GTE predicate on the "billing_address_state" field. +func BillingAddressStateGTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldGTE(FieldBillingAddressState, v)) +} + +// BillingAddressStateLT applies the LT predicate on the "billing_address_state" field. +func BillingAddressStateLT(v string) predicate.Customer { + return predicate.Customer(sql.FieldLT(FieldBillingAddressState, v)) +} + +// BillingAddressStateLTE applies the LTE predicate on the "billing_address_state" field. +func BillingAddressStateLTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldLTE(FieldBillingAddressState, v)) +} + +// BillingAddressStateContains applies the Contains predicate on the "billing_address_state" field. +func BillingAddressStateContains(v string) predicate.Customer { + return predicate.Customer(sql.FieldContains(FieldBillingAddressState, v)) +} + +// BillingAddressStateHasPrefix applies the HasPrefix predicate on the "billing_address_state" field. +func BillingAddressStateHasPrefix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasPrefix(FieldBillingAddressState, v)) +} + +// BillingAddressStateHasSuffix applies the HasSuffix predicate on the "billing_address_state" field. +func BillingAddressStateHasSuffix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasSuffix(FieldBillingAddressState, v)) +} + +// BillingAddressStateIsNil applies the IsNil predicate on the "billing_address_state" field. +func BillingAddressStateIsNil() predicate.Customer { + return predicate.Customer(sql.FieldIsNull(FieldBillingAddressState)) +} + +// BillingAddressStateNotNil applies the NotNil predicate on the "billing_address_state" field. +func BillingAddressStateNotNil() predicate.Customer { + return predicate.Customer(sql.FieldNotNull(FieldBillingAddressState)) +} + +// BillingAddressStateEqualFold applies the EqualFold predicate on the "billing_address_state" field. +func BillingAddressStateEqualFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldEqualFold(FieldBillingAddressState, v)) +} + +// BillingAddressStateContainsFold applies the ContainsFold predicate on the "billing_address_state" field. +func BillingAddressStateContainsFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldContainsFold(FieldBillingAddressState, v)) +} + +// BillingAddressCityEQ applies the EQ predicate on the "billing_address_city" field. +func BillingAddressCityEQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldBillingAddressCity, v)) +} + +// BillingAddressCityNEQ applies the NEQ predicate on the "billing_address_city" field. +func BillingAddressCityNEQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldNEQ(FieldBillingAddressCity, v)) +} + +// BillingAddressCityIn applies the In predicate on the "billing_address_city" field. +func BillingAddressCityIn(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldIn(FieldBillingAddressCity, vs...)) +} + +// BillingAddressCityNotIn applies the NotIn predicate on the "billing_address_city" field. +func BillingAddressCityNotIn(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldNotIn(FieldBillingAddressCity, vs...)) +} + +// BillingAddressCityGT applies the GT predicate on the "billing_address_city" field. +func BillingAddressCityGT(v string) predicate.Customer { + return predicate.Customer(sql.FieldGT(FieldBillingAddressCity, v)) +} + +// BillingAddressCityGTE applies the GTE predicate on the "billing_address_city" field. +func BillingAddressCityGTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldGTE(FieldBillingAddressCity, v)) +} + +// BillingAddressCityLT applies the LT predicate on the "billing_address_city" field. +func BillingAddressCityLT(v string) predicate.Customer { + return predicate.Customer(sql.FieldLT(FieldBillingAddressCity, v)) +} + +// BillingAddressCityLTE applies the LTE predicate on the "billing_address_city" field. +func BillingAddressCityLTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldLTE(FieldBillingAddressCity, v)) +} + +// BillingAddressCityContains applies the Contains predicate on the "billing_address_city" field. +func BillingAddressCityContains(v string) predicate.Customer { + return predicate.Customer(sql.FieldContains(FieldBillingAddressCity, v)) +} + +// BillingAddressCityHasPrefix applies the HasPrefix predicate on the "billing_address_city" field. +func BillingAddressCityHasPrefix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasPrefix(FieldBillingAddressCity, v)) +} + +// BillingAddressCityHasSuffix applies the HasSuffix predicate on the "billing_address_city" field. +func BillingAddressCityHasSuffix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasSuffix(FieldBillingAddressCity, v)) +} + +// BillingAddressCityIsNil applies the IsNil predicate on the "billing_address_city" field. +func BillingAddressCityIsNil() predicate.Customer { + return predicate.Customer(sql.FieldIsNull(FieldBillingAddressCity)) +} + +// BillingAddressCityNotNil applies the NotNil predicate on the "billing_address_city" field. +func BillingAddressCityNotNil() predicate.Customer { + return predicate.Customer(sql.FieldNotNull(FieldBillingAddressCity)) +} + +// BillingAddressCityEqualFold applies the EqualFold predicate on the "billing_address_city" field. +func BillingAddressCityEqualFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldEqualFold(FieldBillingAddressCity, v)) +} + +// BillingAddressCityContainsFold applies the ContainsFold predicate on the "billing_address_city" field. +func BillingAddressCityContainsFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldContainsFold(FieldBillingAddressCity, v)) +} + +// BillingAddressLine1EQ applies the EQ predicate on the "billing_address_line1" field. +func BillingAddressLine1EQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldBillingAddressLine1, v)) +} + +// BillingAddressLine1NEQ applies the NEQ predicate on the "billing_address_line1" field. +func BillingAddressLine1NEQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldNEQ(FieldBillingAddressLine1, v)) +} + +// BillingAddressLine1In applies the In predicate on the "billing_address_line1" field. +func BillingAddressLine1In(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldIn(FieldBillingAddressLine1, vs...)) +} + +// BillingAddressLine1NotIn applies the NotIn predicate on the "billing_address_line1" field. +func BillingAddressLine1NotIn(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldNotIn(FieldBillingAddressLine1, vs...)) +} + +// BillingAddressLine1GT applies the GT predicate on the "billing_address_line1" field. +func BillingAddressLine1GT(v string) predicate.Customer { + return predicate.Customer(sql.FieldGT(FieldBillingAddressLine1, v)) +} + +// BillingAddressLine1GTE applies the GTE predicate on the "billing_address_line1" field. +func BillingAddressLine1GTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldGTE(FieldBillingAddressLine1, v)) +} + +// BillingAddressLine1LT applies the LT predicate on the "billing_address_line1" field. +func BillingAddressLine1LT(v string) predicate.Customer { + return predicate.Customer(sql.FieldLT(FieldBillingAddressLine1, v)) +} + +// BillingAddressLine1LTE applies the LTE predicate on the "billing_address_line1" field. +func BillingAddressLine1LTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldLTE(FieldBillingAddressLine1, v)) +} + +// BillingAddressLine1Contains applies the Contains predicate on the "billing_address_line1" field. +func BillingAddressLine1Contains(v string) predicate.Customer { + return predicate.Customer(sql.FieldContains(FieldBillingAddressLine1, v)) +} + +// BillingAddressLine1HasPrefix applies the HasPrefix predicate on the "billing_address_line1" field. +func BillingAddressLine1HasPrefix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasPrefix(FieldBillingAddressLine1, v)) +} + +// BillingAddressLine1HasSuffix applies the HasSuffix predicate on the "billing_address_line1" field. +func BillingAddressLine1HasSuffix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasSuffix(FieldBillingAddressLine1, v)) +} + +// BillingAddressLine1IsNil applies the IsNil predicate on the "billing_address_line1" field. +func BillingAddressLine1IsNil() predicate.Customer { + return predicate.Customer(sql.FieldIsNull(FieldBillingAddressLine1)) +} + +// BillingAddressLine1NotNil applies the NotNil predicate on the "billing_address_line1" field. +func BillingAddressLine1NotNil() predicate.Customer { + return predicate.Customer(sql.FieldNotNull(FieldBillingAddressLine1)) +} + +// BillingAddressLine1EqualFold applies the EqualFold predicate on the "billing_address_line1" field. +func BillingAddressLine1EqualFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldEqualFold(FieldBillingAddressLine1, v)) +} + +// BillingAddressLine1ContainsFold applies the ContainsFold predicate on the "billing_address_line1" field. +func BillingAddressLine1ContainsFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldContainsFold(FieldBillingAddressLine1, v)) +} + +// BillingAddressLine2EQ applies the EQ predicate on the "billing_address_line2" field. +func BillingAddressLine2EQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldBillingAddressLine2, v)) +} + +// BillingAddressLine2NEQ applies the NEQ predicate on the "billing_address_line2" field. +func BillingAddressLine2NEQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldNEQ(FieldBillingAddressLine2, v)) +} + +// BillingAddressLine2In applies the In predicate on the "billing_address_line2" field. +func BillingAddressLine2In(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldIn(FieldBillingAddressLine2, vs...)) +} + +// BillingAddressLine2NotIn applies the NotIn predicate on the "billing_address_line2" field. +func BillingAddressLine2NotIn(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldNotIn(FieldBillingAddressLine2, vs...)) +} + +// BillingAddressLine2GT applies the GT predicate on the "billing_address_line2" field. +func BillingAddressLine2GT(v string) predicate.Customer { + return predicate.Customer(sql.FieldGT(FieldBillingAddressLine2, v)) +} + +// BillingAddressLine2GTE applies the GTE predicate on the "billing_address_line2" field. +func BillingAddressLine2GTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldGTE(FieldBillingAddressLine2, v)) +} + +// BillingAddressLine2LT applies the LT predicate on the "billing_address_line2" field. +func BillingAddressLine2LT(v string) predicate.Customer { + return predicate.Customer(sql.FieldLT(FieldBillingAddressLine2, v)) +} + +// BillingAddressLine2LTE applies the LTE predicate on the "billing_address_line2" field. +func BillingAddressLine2LTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldLTE(FieldBillingAddressLine2, v)) +} + +// BillingAddressLine2Contains applies the Contains predicate on the "billing_address_line2" field. +func BillingAddressLine2Contains(v string) predicate.Customer { + return predicate.Customer(sql.FieldContains(FieldBillingAddressLine2, v)) +} + +// BillingAddressLine2HasPrefix applies the HasPrefix predicate on the "billing_address_line2" field. +func BillingAddressLine2HasPrefix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasPrefix(FieldBillingAddressLine2, v)) +} + +// BillingAddressLine2HasSuffix applies the HasSuffix predicate on the "billing_address_line2" field. +func BillingAddressLine2HasSuffix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasSuffix(FieldBillingAddressLine2, v)) +} + +// BillingAddressLine2IsNil applies the IsNil predicate on the "billing_address_line2" field. +func BillingAddressLine2IsNil() predicate.Customer { + return predicate.Customer(sql.FieldIsNull(FieldBillingAddressLine2)) +} + +// BillingAddressLine2NotNil applies the NotNil predicate on the "billing_address_line2" field. +func BillingAddressLine2NotNil() predicate.Customer { + return predicate.Customer(sql.FieldNotNull(FieldBillingAddressLine2)) +} + +// BillingAddressLine2EqualFold applies the EqualFold predicate on the "billing_address_line2" field. +func BillingAddressLine2EqualFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldEqualFold(FieldBillingAddressLine2, v)) +} + +// BillingAddressLine2ContainsFold applies the ContainsFold predicate on the "billing_address_line2" field. +func BillingAddressLine2ContainsFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldContainsFold(FieldBillingAddressLine2, v)) +} + +// BillingAddressPhoneNumberEQ applies the EQ predicate on the "billing_address_phone_number" field. +func BillingAddressPhoneNumberEQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldBillingAddressPhoneNumber, v)) +} + +// BillingAddressPhoneNumberNEQ applies the NEQ predicate on the "billing_address_phone_number" field. +func BillingAddressPhoneNumberNEQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldNEQ(FieldBillingAddressPhoneNumber, v)) +} + +// BillingAddressPhoneNumberIn applies the In predicate on the "billing_address_phone_number" field. +func BillingAddressPhoneNumberIn(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldIn(FieldBillingAddressPhoneNumber, vs...)) +} + +// BillingAddressPhoneNumberNotIn applies the NotIn predicate on the "billing_address_phone_number" field. +func BillingAddressPhoneNumberNotIn(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldNotIn(FieldBillingAddressPhoneNumber, vs...)) +} + +// BillingAddressPhoneNumberGT applies the GT predicate on the "billing_address_phone_number" field. +func BillingAddressPhoneNumberGT(v string) predicate.Customer { + return predicate.Customer(sql.FieldGT(FieldBillingAddressPhoneNumber, v)) +} + +// BillingAddressPhoneNumberGTE applies the GTE predicate on the "billing_address_phone_number" field. +func BillingAddressPhoneNumberGTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldGTE(FieldBillingAddressPhoneNumber, v)) +} + +// BillingAddressPhoneNumberLT applies the LT predicate on the "billing_address_phone_number" field. +func BillingAddressPhoneNumberLT(v string) predicate.Customer { + return predicate.Customer(sql.FieldLT(FieldBillingAddressPhoneNumber, v)) +} + +// BillingAddressPhoneNumberLTE applies the LTE predicate on the "billing_address_phone_number" field. +func BillingAddressPhoneNumberLTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldLTE(FieldBillingAddressPhoneNumber, v)) +} + +// BillingAddressPhoneNumberContains applies the Contains predicate on the "billing_address_phone_number" field. +func BillingAddressPhoneNumberContains(v string) predicate.Customer { + return predicate.Customer(sql.FieldContains(FieldBillingAddressPhoneNumber, v)) +} + +// BillingAddressPhoneNumberHasPrefix applies the HasPrefix predicate on the "billing_address_phone_number" field. +func BillingAddressPhoneNumberHasPrefix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasPrefix(FieldBillingAddressPhoneNumber, v)) +} + +// BillingAddressPhoneNumberHasSuffix applies the HasSuffix predicate on the "billing_address_phone_number" field. +func BillingAddressPhoneNumberHasSuffix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasSuffix(FieldBillingAddressPhoneNumber, v)) +} + +// BillingAddressPhoneNumberIsNil applies the IsNil predicate on the "billing_address_phone_number" field. +func BillingAddressPhoneNumberIsNil() predicate.Customer { + return predicate.Customer(sql.FieldIsNull(FieldBillingAddressPhoneNumber)) +} + +// BillingAddressPhoneNumberNotNil applies the NotNil predicate on the "billing_address_phone_number" field. +func BillingAddressPhoneNumberNotNil() predicate.Customer { + return predicate.Customer(sql.FieldNotNull(FieldBillingAddressPhoneNumber)) +} + +// BillingAddressPhoneNumberEqualFold applies the EqualFold predicate on the "billing_address_phone_number" field. +func BillingAddressPhoneNumberEqualFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldEqualFold(FieldBillingAddressPhoneNumber, v)) +} + +// BillingAddressPhoneNumberContainsFold applies the ContainsFold predicate on the "billing_address_phone_number" field. +func BillingAddressPhoneNumberContainsFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldContainsFold(FieldBillingAddressPhoneNumber, v)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.Customer { + return predicate.Customer(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.Customer { + return predicate.Customer(sql.FieldNotNull(FieldAnnotations)) +} + +// KeyEQ applies the EQ predicate on the "key" field. +func KeyEQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldKey, v)) +} + +// KeyNEQ applies the NEQ predicate on the "key" field. +func KeyNEQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldNEQ(FieldKey, v)) +} + +// KeyIn applies the In predicate on the "key" field. +func KeyIn(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldIn(FieldKey, vs...)) +} + +// KeyNotIn applies the NotIn predicate on the "key" field. +func KeyNotIn(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldNotIn(FieldKey, vs...)) +} + +// KeyGT applies the GT predicate on the "key" field. +func KeyGT(v string) predicate.Customer { + return predicate.Customer(sql.FieldGT(FieldKey, v)) +} + +// KeyGTE applies the GTE predicate on the "key" field. +func KeyGTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldGTE(FieldKey, v)) +} + +// KeyLT applies the LT predicate on the "key" field. +func KeyLT(v string) predicate.Customer { + return predicate.Customer(sql.FieldLT(FieldKey, v)) +} + +// KeyLTE applies the LTE predicate on the "key" field. +func KeyLTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldLTE(FieldKey, v)) +} + +// KeyContains applies the Contains predicate on the "key" field. +func KeyContains(v string) predicate.Customer { + return predicate.Customer(sql.FieldContains(FieldKey, v)) +} + +// KeyHasPrefix applies the HasPrefix predicate on the "key" field. +func KeyHasPrefix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasPrefix(FieldKey, v)) +} + +// KeyHasSuffix applies the HasSuffix predicate on the "key" field. +func KeyHasSuffix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasSuffix(FieldKey, v)) +} + +// KeyIsNil applies the IsNil predicate on the "key" field. +func KeyIsNil() predicate.Customer { + return predicate.Customer(sql.FieldIsNull(FieldKey)) +} + +// KeyNotNil applies the NotNil predicate on the "key" field. +func KeyNotNil() predicate.Customer { + return predicate.Customer(sql.FieldNotNull(FieldKey)) +} + +// KeyEqualFold applies the EqualFold predicate on the "key" field. +func KeyEqualFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldEqualFold(FieldKey, v)) +} + +// KeyContainsFold applies the ContainsFold predicate on the "key" field. +func KeyContainsFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldContainsFold(FieldKey, v)) +} + +// PrimaryEmailEQ applies the EQ predicate on the "primary_email" field. +func PrimaryEmailEQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldEQ(FieldPrimaryEmail, v)) +} + +// PrimaryEmailNEQ applies the NEQ predicate on the "primary_email" field. +func PrimaryEmailNEQ(v string) predicate.Customer { + return predicate.Customer(sql.FieldNEQ(FieldPrimaryEmail, v)) +} + +// PrimaryEmailIn applies the In predicate on the "primary_email" field. +func PrimaryEmailIn(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldIn(FieldPrimaryEmail, vs...)) +} + +// PrimaryEmailNotIn applies the NotIn predicate on the "primary_email" field. +func PrimaryEmailNotIn(vs ...string) predicate.Customer { + return predicate.Customer(sql.FieldNotIn(FieldPrimaryEmail, vs...)) +} + +// PrimaryEmailGT applies the GT predicate on the "primary_email" field. +func PrimaryEmailGT(v string) predicate.Customer { + return predicate.Customer(sql.FieldGT(FieldPrimaryEmail, v)) +} + +// PrimaryEmailGTE applies the GTE predicate on the "primary_email" field. +func PrimaryEmailGTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldGTE(FieldPrimaryEmail, v)) +} + +// PrimaryEmailLT applies the LT predicate on the "primary_email" field. +func PrimaryEmailLT(v string) predicate.Customer { + return predicate.Customer(sql.FieldLT(FieldPrimaryEmail, v)) +} + +// PrimaryEmailLTE applies the LTE predicate on the "primary_email" field. +func PrimaryEmailLTE(v string) predicate.Customer { + return predicate.Customer(sql.FieldLTE(FieldPrimaryEmail, v)) +} + +// PrimaryEmailContains applies the Contains predicate on the "primary_email" field. +func PrimaryEmailContains(v string) predicate.Customer { + return predicate.Customer(sql.FieldContains(FieldPrimaryEmail, v)) +} + +// PrimaryEmailHasPrefix applies the HasPrefix predicate on the "primary_email" field. +func PrimaryEmailHasPrefix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasPrefix(FieldPrimaryEmail, v)) +} + +// PrimaryEmailHasSuffix applies the HasSuffix predicate on the "primary_email" field. +func PrimaryEmailHasSuffix(v string) predicate.Customer { + return predicate.Customer(sql.FieldHasSuffix(FieldPrimaryEmail, v)) +} + +// PrimaryEmailIsNil applies the IsNil predicate on the "primary_email" field. +func PrimaryEmailIsNil() predicate.Customer { + return predicate.Customer(sql.FieldIsNull(FieldPrimaryEmail)) +} + +// PrimaryEmailNotNil applies the NotNil predicate on the "primary_email" field. +func PrimaryEmailNotNil() predicate.Customer { + return predicate.Customer(sql.FieldNotNull(FieldPrimaryEmail)) +} + +// PrimaryEmailEqualFold applies the EqualFold predicate on the "primary_email" field. +func PrimaryEmailEqualFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldEqualFold(FieldPrimaryEmail, v)) +} + +// PrimaryEmailContainsFold applies the ContainsFold predicate on the "primary_email" field. +func PrimaryEmailContainsFold(v string) predicate.Customer { + return predicate.Customer(sql.FieldContainsFold(FieldPrimaryEmail, v)) +} + +// CurrencyEQ applies the EQ predicate on the "currency" field. +func CurrencyEQ(v currencyx.Code) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldEQ(FieldCurrency, vc)) +} + +// CurrencyNEQ applies the NEQ predicate on the "currency" field. +func CurrencyNEQ(v currencyx.Code) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldNEQ(FieldCurrency, vc)) +} + +// CurrencyIn applies the In predicate on the "currency" field. +func CurrencyIn(vs ...currencyx.Code) predicate.Customer { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.Customer(sql.FieldIn(FieldCurrency, v...)) +} + +// CurrencyNotIn applies the NotIn predicate on the "currency" field. +func CurrencyNotIn(vs ...currencyx.Code) predicate.Customer { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.Customer(sql.FieldNotIn(FieldCurrency, v...)) +} + +// CurrencyGT applies the GT predicate on the "currency" field. +func CurrencyGT(v currencyx.Code) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldGT(FieldCurrency, vc)) +} + +// CurrencyGTE applies the GTE predicate on the "currency" field. +func CurrencyGTE(v currencyx.Code) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldGTE(FieldCurrency, vc)) +} + +// CurrencyLT applies the LT predicate on the "currency" field. +func CurrencyLT(v currencyx.Code) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldLT(FieldCurrency, vc)) +} + +// CurrencyLTE applies the LTE predicate on the "currency" field. +func CurrencyLTE(v currencyx.Code) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldLTE(FieldCurrency, vc)) +} + +// CurrencyContains applies the Contains predicate on the "currency" field. +func CurrencyContains(v currencyx.Code) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldContains(FieldCurrency, vc)) +} + +// CurrencyHasPrefix applies the HasPrefix predicate on the "currency" field. +func CurrencyHasPrefix(v currencyx.Code) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldHasPrefix(FieldCurrency, vc)) +} + +// CurrencyHasSuffix applies the HasSuffix predicate on the "currency" field. +func CurrencyHasSuffix(v currencyx.Code) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldHasSuffix(FieldCurrency, vc)) +} + +// CurrencyIsNil applies the IsNil predicate on the "currency" field. +func CurrencyIsNil() predicate.Customer { + return predicate.Customer(sql.FieldIsNull(FieldCurrency)) +} + +// CurrencyNotNil applies the NotNil predicate on the "currency" field. +func CurrencyNotNil() predicate.Customer { + return predicate.Customer(sql.FieldNotNull(FieldCurrency)) +} + +// CurrencyEqualFold applies the EqualFold predicate on the "currency" field. +func CurrencyEqualFold(v currencyx.Code) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldEqualFold(FieldCurrency, vc)) +} + +// CurrencyContainsFold applies the ContainsFold predicate on the "currency" field. +func CurrencyContainsFold(v currencyx.Code) predicate.Customer { + vc := string(v) + return predicate.Customer(sql.FieldContainsFold(FieldCurrency, vc)) +} + +// HasApps applies the HasEdge predicate on the "apps" edge. +func HasApps() predicate.Customer { + return predicate.Customer(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, AppsTable, AppsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasAppsWith applies the HasEdge predicate on the "apps" edge with a given conditions (other predicates). +func HasAppsWith(preds ...predicate.AppCustomer) predicate.Customer { + return predicate.Customer(func(s *sql.Selector) { + step := newAppsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSubjects applies the HasEdge predicate on the "subjects" edge. +func HasSubjects() predicate.Customer { + return predicate.Customer(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SubjectsTable, SubjectsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubjectsWith applies the HasEdge predicate on the "subjects" edge with a given conditions (other predicates). +func HasSubjectsWith(preds ...predicate.CustomerSubjects) predicate.Customer { + return predicate.Customer(func(s *sql.Selector) { + step := newSubjectsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasBillingCustomerOverride applies the HasEdge predicate on the "billing_customer_override" edge. +func HasBillingCustomerOverride() predicate.Customer { + return predicate.Customer(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, BillingCustomerOverrideTable, BillingCustomerOverrideColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBillingCustomerOverrideWith applies the HasEdge predicate on the "billing_customer_override" edge with a given conditions (other predicates). +func HasBillingCustomerOverrideWith(preds ...predicate.BillingCustomerOverride) predicate.Customer { + return predicate.Customer(func(s *sql.Selector) { + step := newBillingCustomerOverrideStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasBillingInvoice applies the HasEdge predicate on the "billing_invoice" edge. +func HasBillingInvoice() predicate.Customer { + return predicate.Customer(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, BillingInvoiceTable, BillingInvoiceColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBillingInvoiceWith applies the HasEdge predicate on the "billing_invoice" edge with a given conditions (other predicates). +func HasBillingInvoiceWith(preds ...predicate.BillingInvoice) predicate.Customer { + return predicate.Customer(func(s *sql.Selector) { + step := newBillingInvoiceStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSubscription applies the HasEdge predicate on the "subscription" edge. +func HasSubscription() predicate.Customer { + return predicate.Customer(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SubscriptionTable, SubscriptionColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubscriptionWith applies the HasEdge predicate on the "subscription" edge with a given conditions (other predicates). +func HasSubscriptionWith(preds ...predicate.Subscription) predicate.Customer { + return predicate.Customer(func(s *sql.Selector) { + step := newSubscriptionStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasEntitlements applies the HasEdge predicate on the "entitlements" edge. +func HasEntitlements() predicate.Customer { + return predicate.Customer(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, EntitlementsTable, EntitlementsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasEntitlementsWith applies the HasEdge predicate on the "entitlements" edge with a given conditions (other predicates). +func HasEntitlementsWith(preds ...predicate.Entitlement) predicate.Customer { + return predicate.Customer(func(s *sql.Selector) { + step := newEntitlementsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasChargesCreditPurchase applies the HasEdge predicate on the "charges_credit_purchase" edge. +func HasChargesCreditPurchase() predicate.Customer { + return predicate.Customer(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ChargesCreditPurchaseTable, ChargesCreditPurchaseColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasChargesCreditPurchaseWith applies the HasEdge predicate on the "charges_credit_purchase" edge with a given conditions (other predicates). +func HasChargesCreditPurchaseWith(preds ...predicate.ChargeCreditPurchase) predicate.Customer { + return predicate.Customer(func(s *sql.Selector) { + step := newChargesCreditPurchaseStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasChargesFlatFee applies the HasEdge predicate on the "charges_flat_fee" edge. +func HasChargesFlatFee() predicate.Customer { + return predicate.Customer(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ChargesFlatFeeTable, ChargesFlatFeeColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasChargesFlatFeeWith applies the HasEdge predicate on the "charges_flat_fee" edge with a given conditions (other predicates). +func HasChargesFlatFeeWith(preds ...predicate.ChargeFlatFee) predicate.Customer { + return predicate.Customer(func(s *sql.Selector) { + step := newChargesFlatFeeStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasChargesUsageBased applies the HasEdge predicate on the "charges_usage_based" edge. +func HasChargesUsageBased() predicate.Customer { + return predicate.Customer(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ChargesUsageBasedTable, ChargesUsageBasedColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasChargesUsageBasedWith applies the HasEdge predicate on the "charges_usage_based" edge with a given conditions (other predicates). +func HasChargesUsageBasedWith(preds ...predicate.ChargeUsageBased) predicate.Customer { + return predicate.Customer(func(s *sql.Selector) { + step := newChargesUsageBasedStep() + 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.Customer) predicate.Customer { + return predicate.Customer(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Customer) predicate.Customer { + return predicate.Customer(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Customer) predicate.Customer { + return predicate.Customer(sql.NotPredicates(p)) +} diff --git a/ent/db/customer_create.go b/ent/db/customer_create.go new file mode 100644 index 0000000000000000000000000000000000000000..dd6760da00574916b52eeace81db129b9654e236 --- /dev/null +++ b/ent/db/customer_create.go @@ -0,0 +1,2008 @@ +// 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/appcustomer" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingcustomeroverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "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/customersubjects" + "github.com/openmeterio/openmeter/openmeter/ent/db/entitlement" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// CustomerCreate is the builder for creating a Customer entity. +type CustomerCreate struct { + config + mutation *CustomerMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *CustomerCreate) SetNamespace(v string) *CustomerCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetMetadata sets the "metadata" field. +func (_c *CustomerCreate) SetMetadata(v map[string]string) *CustomerCreate { + _c.mutation.SetMetadata(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *CustomerCreate) SetCreatedAt(v time.Time) *CustomerCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *CustomerCreate) SetNillableCreatedAt(v *time.Time) *CustomerCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *CustomerCreate) SetUpdatedAt(v time.Time) *CustomerCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *CustomerCreate) SetNillableUpdatedAt(v *time.Time) *CustomerCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *CustomerCreate) SetDeletedAt(v time.Time) *CustomerCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *CustomerCreate) SetNillableDeletedAt(v *time.Time) *CustomerCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetName sets the "name" field. +func (_c *CustomerCreate) SetName(v string) *CustomerCreate { + _c.mutation.SetName(v) + return _c +} + +// SetDescription sets the "description" field. +func (_c *CustomerCreate) SetDescription(v string) *CustomerCreate { + _c.mutation.SetDescription(v) + return _c +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_c *CustomerCreate) SetNillableDescription(v *string) *CustomerCreate { + if v != nil { + _c.SetDescription(*v) + } + return _c +} + +// SetBillingAddressCountry sets the "billing_address_country" field. +func (_c *CustomerCreate) SetBillingAddressCountry(v models.CountryCode) *CustomerCreate { + _c.mutation.SetBillingAddressCountry(v) + return _c +} + +// SetNillableBillingAddressCountry sets the "billing_address_country" field if the given value is not nil. +func (_c *CustomerCreate) SetNillableBillingAddressCountry(v *models.CountryCode) *CustomerCreate { + if v != nil { + _c.SetBillingAddressCountry(*v) + } + return _c +} + +// SetBillingAddressPostalCode sets the "billing_address_postal_code" field. +func (_c *CustomerCreate) SetBillingAddressPostalCode(v string) *CustomerCreate { + _c.mutation.SetBillingAddressPostalCode(v) + return _c +} + +// SetNillableBillingAddressPostalCode sets the "billing_address_postal_code" field if the given value is not nil. +func (_c *CustomerCreate) SetNillableBillingAddressPostalCode(v *string) *CustomerCreate { + if v != nil { + _c.SetBillingAddressPostalCode(*v) + } + return _c +} + +// SetBillingAddressState sets the "billing_address_state" field. +func (_c *CustomerCreate) SetBillingAddressState(v string) *CustomerCreate { + _c.mutation.SetBillingAddressState(v) + return _c +} + +// SetNillableBillingAddressState sets the "billing_address_state" field if the given value is not nil. +func (_c *CustomerCreate) SetNillableBillingAddressState(v *string) *CustomerCreate { + if v != nil { + _c.SetBillingAddressState(*v) + } + return _c +} + +// SetBillingAddressCity sets the "billing_address_city" field. +func (_c *CustomerCreate) SetBillingAddressCity(v string) *CustomerCreate { + _c.mutation.SetBillingAddressCity(v) + return _c +} + +// SetNillableBillingAddressCity sets the "billing_address_city" field if the given value is not nil. +func (_c *CustomerCreate) SetNillableBillingAddressCity(v *string) *CustomerCreate { + if v != nil { + _c.SetBillingAddressCity(*v) + } + return _c +} + +// SetBillingAddressLine1 sets the "billing_address_line1" field. +func (_c *CustomerCreate) SetBillingAddressLine1(v string) *CustomerCreate { + _c.mutation.SetBillingAddressLine1(v) + return _c +} + +// SetNillableBillingAddressLine1 sets the "billing_address_line1" field if the given value is not nil. +func (_c *CustomerCreate) SetNillableBillingAddressLine1(v *string) *CustomerCreate { + if v != nil { + _c.SetBillingAddressLine1(*v) + } + return _c +} + +// SetBillingAddressLine2 sets the "billing_address_line2" field. +func (_c *CustomerCreate) SetBillingAddressLine2(v string) *CustomerCreate { + _c.mutation.SetBillingAddressLine2(v) + return _c +} + +// SetNillableBillingAddressLine2 sets the "billing_address_line2" field if the given value is not nil. +func (_c *CustomerCreate) SetNillableBillingAddressLine2(v *string) *CustomerCreate { + if v != nil { + _c.SetBillingAddressLine2(*v) + } + return _c +} + +// SetBillingAddressPhoneNumber sets the "billing_address_phone_number" field. +func (_c *CustomerCreate) SetBillingAddressPhoneNumber(v string) *CustomerCreate { + _c.mutation.SetBillingAddressPhoneNumber(v) + return _c +} + +// SetNillableBillingAddressPhoneNumber sets the "billing_address_phone_number" field if the given value is not nil. +func (_c *CustomerCreate) SetNillableBillingAddressPhoneNumber(v *string) *CustomerCreate { + if v != nil { + _c.SetBillingAddressPhoneNumber(*v) + } + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *CustomerCreate) SetAnnotations(v models.Annotations) *CustomerCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetKey sets the "key" field. +func (_c *CustomerCreate) SetKey(v string) *CustomerCreate { + _c.mutation.SetKey(v) + return _c +} + +// SetNillableKey sets the "key" field if the given value is not nil. +func (_c *CustomerCreate) SetNillableKey(v *string) *CustomerCreate { + if v != nil { + _c.SetKey(*v) + } + return _c +} + +// SetPrimaryEmail sets the "primary_email" field. +func (_c *CustomerCreate) SetPrimaryEmail(v string) *CustomerCreate { + _c.mutation.SetPrimaryEmail(v) + return _c +} + +// SetNillablePrimaryEmail sets the "primary_email" field if the given value is not nil. +func (_c *CustomerCreate) SetNillablePrimaryEmail(v *string) *CustomerCreate { + if v != nil { + _c.SetPrimaryEmail(*v) + } + return _c +} + +// SetCurrency sets the "currency" field. +func (_c *CustomerCreate) SetCurrency(v currencyx.Code) *CustomerCreate { + _c.mutation.SetCurrency(v) + return _c +} + +// SetNillableCurrency sets the "currency" field if the given value is not nil. +func (_c *CustomerCreate) SetNillableCurrency(v *currencyx.Code) *CustomerCreate { + if v != nil { + _c.SetCurrency(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *CustomerCreate) SetID(v string) *CustomerCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *CustomerCreate) SetNillableID(v *string) *CustomerCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// AddAppIDs adds the "apps" edge to the AppCustomer entity by IDs. +func (_c *CustomerCreate) AddAppIDs(ids ...int) *CustomerCreate { + _c.mutation.AddAppIDs(ids...) + return _c +} + +// AddApps adds the "apps" edges to the AppCustomer entity. +func (_c *CustomerCreate) AddApps(v ...*AppCustomer) *CustomerCreate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddAppIDs(ids...) +} + +// AddSubjectIDs adds the "subjects" edge to the CustomerSubjects entity by IDs. +func (_c *CustomerCreate) AddSubjectIDs(ids ...int) *CustomerCreate { + _c.mutation.AddSubjectIDs(ids...) + return _c +} + +// AddSubjects adds the "subjects" edges to the CustomerSubjects entity. +func (_c *CustomerCreate) AddSubjects(v ...*CustomerSubjects) *CustomerCreate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddSubjectIDs(ids...) +} + +// SetBillingCustomerOverrideID sets the "billing_customer_override" edge to the BillingCustomerOverride entity by ID. +func (_c *CustomerCreate) SetBillingCustomerOverrideID(id string) *CustomerCreate { + _c.mutation.SetBillingCustomerOverrideID(id) + return _c +} + +// SetNillableBillingCustomerOverrideID sets the "billing_customer_override" edge to the BillingCustomerOverride entity by ID if the given value is not nil. +func (_c *CustomerCreate) SetNillableBillingCustomerOverrideID(id *string) *CustomerCreate { + if id != nil { + _c = _c.SetBillingCustomerOverrideID(*id) + } + return _c +} + +// SetBillingCustomerOverride sets the "billing_customer_override" edge to the BillingCustomerOverride entity. +func (_c *CustomerCreate) SetBillingCustomerOverride(v *BillingCustomerOverride) *CustomerCreate { + return _c.SetBillingCustomerOverrideID(v.ID) +} + +// AddBillingInvoiceIDs adds the "billing_invoice" edge to the BillingInvoice entity by IDs. +func (_c *CustomerCreate) AddBillingInvoiceIDs(ids ...string) *CustomerCreate { + _c.mutation.AddBillingInvoiceIDs(ids...) + return _c +} + +// AddBillingInvoice adds the "billing_invoice" edges to the BillingInvoice entity. +func (_c *CustomerCreate) AddBillingInvoice(v ...*BillingInvoice) *CustomerCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddBillingInvoiceIDs(ids...) +} + +// AddSubscriptionIDs adds the "subscription" edge to the Subscription entity by IDs. +func (_c *CustomerCreate) AddSubscriptionIDs(ids ...string) *CustomerCreate { + _c.mutation.AddSubscriptionIDs(ids...) + return _c +} + +// AddSubscription adds the "subscription" edges to the Subscription entity. +func (_c *CustomerCreate) AddSubscription(v ...*Subscription) *CustomerCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddSubscriptionIDs(ids...) +} + +// AddEntitlementIDs adds the "entitlements" edge to the Entitlement entity by IDs. +func (_c *CustomerCreate) AddEntitlementIDs(ids ...string) *CustomerCreate { + _c.mutation.AddEntitlementIDs(ids...) + return _c +} + +// AddEntitlements adds the "entitlements" edges to the Entitlement entity. +func (_c *CustomerCreate) AddEntitlements(v ...*Entitlement) *CustomerCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddEntitlementIDs(ids...) +} + +// AddChargesCreditPurchaseIDs adds the "charges_credit_purchase" edge to the ChargeCreditPurchase entity by IDs. +func (_c *CustomerCreate) AddChargesCreditPurchaseIDs(ids ...string) *CustomerCreate { + _c.mutation.AddChargesCreditPurchaseIDs(ids...) + return _c +} + +// AddChargesCreditPurchase adds the "charges_credit_purchase" edges to the ChargeCreditPurchase entity. +func (_c *CustomerCreate) AddChargesCreditPurchase(v ...*ChargeCreditPurchase) *CustomerCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddChargesCreditPurchaseIDs(ids...) +} + +// AddChargesFlatFeeIDs adds the "charges_flat_fee" edge to the ChargeFlatFee entity by IDs. +func (_c *CustomerCreate) AddChargesFlatFeeIDs(ids ...string) *CustomerCreate { + _c.mutation.AddChargesFlatFeeIDs(ids...) + return _c +} + +// AddChargesFlatFee adds the "charges_flat_fee" edges to the ChargeFlatFee entity. +func (_c *CustomerCreate) AddChargesFlatFee(v ...*ChargeFlatFee) *CustomerCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddChargesFlatFeeIDs(ids...) +} + +// AddChargesUsageBasedIDs adds the "charges_usage_based" edge to the ChargeUsageBased entity by IDs. +func (_c *CustomerCreate) AddChargesUsageBasedIDs(ids ...string) *CustomerCreate { + _c.mutation.AddChargesUsageBasedIDs(ids...) + return _c +} + +// AddChargesUsageBased adds the "charges_usage_based" edges to the ChargeUsageBased entity. +func (_c *CustomerCreate) AddChargesUsageBased(v ...*ChargeUsageBased) *CustomerCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddChargesUsageBasedIDs(ids...) +} + +// Mutation returns the CustomerMutation object of the builder. +func (_c *CustomerCreate) Mutation() *CustomerMutation { + return _c.mutation +} + +// Save creates the Customer in the database. +func (_c *CustomerCreate) Save(ctx context.Context) (*Customer, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *CustomerCreate) SaveX(ctx context.Context) *Customer { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *CustomerCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *CustomerCreate) 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 *CustomerCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := customer.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := customer.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := customer.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *CustomerCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "Customer.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := customer.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "Customer.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "Customer.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "Customer.updated_at"`)} + } + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "Customer.name"`)} + } + if v, ok := _c.mutation.BillingAddressCountry(); ok { + if err := customer.BillingAddressCountryValidator(string(v)); err != nil { + return &ValidationError{Name: "billing_address_country", err: fmt.Errorf(`db: validator failed for field "Customer.billing_address_country": %w`, err)} + } + } + if v, ok := _c.mutation.Currency(); ok { + if err := customer.CurrencyValidator(string(v)); err != nil { + return &ValidationError{Name: "currency", err: fmt.Errorf(`db: validator failed for field "Customer.currency": %w`, err)} + } + } + return nil +} + +func (_c *CustomerCreate) sqlSave(ctx context.Context) (*Customer, 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 Customer.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *CustomerCreate) createSpec() (*Customer, *sqlgraph.CreateSpec) { + var ( + _node = &Customer{config: _c.config} + _spec = sqlgraph.NewCreateSpec(customer.Table, sqlgraph.NewFieldSpec(customer.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(customer.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Metadata(); ok { + _spec.SetField(customer.FieldMetadata, field.TypeJSON, value) + _node.Metadata = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(customer.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(customer.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(customer.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(customer.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Description(); ok { + _spec.SetField(customer.FieldDescription, field.TypeString, value) + _node.Description = &value + } + if value, ok := _c.mutation.BillingAddressCountry(); ok { + _spec.SetField(customer.FieldBillingAddressCountry, field.TypeString, value) + _node.BillingAddressCountry = &value + } + if value, ok := _c.mutation.BillingAddressPostalCode(); ok { + _spec.SetField(customer.FieldBillingAddressPostalCode, field.TypeString, value) + _node.BillingAddressPostalCode = &value + } + if value, ok := _c.mutation.BillingAddressState(); ok { + _spec.SetField(customer.FieldBillingAddressState, field.TypeString, value) + _node.BillingAddressState = &value + } + if value, ok := _c.mutation.BillingAddressCity(); ok { + _spec.SetField(customer.FieldBillingAddressCity, field.TypeString, value) + _node.BillingAddressCity = &value + } + if value, ok := _c.mutation.BillingAddressLine1(); ok { + _spec.SetField(customer.FieldBillingAddressLine1, field.TypeString, value) + _node.BillingAddressLine1 = &value + } + if value, ok := _c.mutation.BillingAddressLine2(); ok { + _spec.SetField(customer.FieldBillingAddressLine2, field.TypeString, value) + _node.BillingAddressLine2 = &value + } + if value, ok := _c.mutation.BillingAddressPhoneNumber(); ok { + _spec.SetField(customer.FieldBillingAddressPhoneNumber, field.TypeString, value) + _node.BillingAddressPhoneNumber = &value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(customer.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.Key(); ok { + _spec.SetField(customer.FieldKey, field.TypeString, value) + _node.Key = value + } + if value, ok := _c.mutation.PrimaryEmail(); ok { + _spec.SetField(customer.FieldPrimaryEmail, field.TypeString, value) + _node.PrimaryEmail = &value + } + if value, ok := _c.mutation.Currency(); ok { + _spec.SetField(customer.FieldCurrency, field.TypeString, value) + _node.Currency = &value + } + if nodes := _c.mutation.AppsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.AppsTable, + Columns: []string{customer.AppsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(appcustomer.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.SubjectsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.SubjectsTable, + Columns: []string{customer.SubjectsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(customersubjects.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.BillingCustomerOverrideIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: customer.BillingCustomerOverrideTable, + Columns: []string{customer.BillingCustomerOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingcustomeroverride.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.BillingInvoiceIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.BillingInvoiceTable, + Columns: []string{customer.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.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.SubscriptionIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.SubscriptionTable, + Columns: []string{customer.SubscriptionColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscription.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.EntitlementsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.EntitlementsTable, + Columns: []string{customer.EntitlementsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(entitlement.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.ChargesCreditPurchaseIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesCreditPurchaseTable, + Columns: []string{customer.ChargesCreditPurchaseColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchase.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.ChargesFlatFeeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesFlatFeeTable, + Columns: []string{customer.ChargesFlatFeeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfee.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.ChargesUsageBasedIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesUsageBasedTable, + Columns: []string{customer.ChargesUsageBasedColumn}, + 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) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Customer.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.CustomerUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *CustomerCreate) OnConflict(opts ...sql.ConflictOption) *CustomerUpsertOne { + _c.conflict = opts + return &CustomerUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Customer.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *CustomerCreate) OnConflictColumns(columns ...string) *CustomerUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &CustomerUpsertOne{ + create: _c, + } +} + +type ( + // CustomerUpsertOne is the builder for "upsert"-ing + // one Customer node. + CustomerUpsertOne struct { + create *CustomerCreate + } + + // CustomerUpsert is the "OnConflict" setter. + CustomerUpsert struct { + *sql.UpdateSet + } +) + +// SetMetadata sets the "metadata" field. +func (u *CustomerUpsert) SetMetadata(v map[string]string) *CustomerUpsert { + u.Set(customer.FieldMetadata, v) + return u +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *CustomerUpsert) UpdateMetadata() *CustomerUpsert { + u.SetExcluded(customer.FieldMetadata) + return u +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *CustomerUpsert) ClearMetadata() *CustomerUpsert { + u.SetNull(customer.FieldMetadata) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *CustomerUpsert) SetUpdatedAt(v time.Time) *CustomerUpsert { + u.Set(customer.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *CustomerUpsert) UpdateUpdatedAt() *CustomerUpsert { + u.SetExcluded(customer.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *CustomerUpsert) SetDeletedAt(v time.Time) *CustomerUpsert { + u.Set(customer.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *CustomerUpsert) UpdateDeletedAt() *CustomerUpsert { + u.SetExcluded(customer.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *CustomerUpsert) ClearDeletedAt() *CustomerUpsert { + u.SetNull(customer.FieldDeletedAt) + return u +} + +// SetName sets the "name" field. +func (u *CustomerUpsert) SetName(v string) *CustomerUpsert { + u.Set(customer.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *CustomerUpsert) UpdateName() *CustomerUpsert { + u.SetExcluded(customer.FieldName) + return u +} + +// SetDescription sets the "description" field. +func (u *CustomerUpsert) SetDescription(v string) *CustomerUpsert { + u.Set(customer.FieldDescription, v) + return u +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *CustomerUpsert) UpdateDescription() *CustomerUpsert { + u.SetExcluded(customer.FieldDescription) + return u +} + +// ClearDescription clears the value of the "description" field. +func (u *CustomerUpsert) ClearDescription() *CustomerUpsert { + u.SetNull(customer.FieldDescription) + return u +} + +// SetBillingAddressCountry sets the "billing_address_country" field. +func (u *CustomerUpsert) SetBillingAddressCountry(v models.CountryCode) *CustomerUpsert { + u.Set(customer.FieldBillingAddressCountry, v) + return u +} + +// UpdateBillingAddressCountry sets the "billing_address_country" field to the value that was provided on create. +func (u *CustomerUpsert) UpdateBillingAddressCountry() *CustomerUpsert { + u.SetExcluded(customer.FieldBillingAddressCountry) + return u +} + +// ClearBillingAddressCountry clears the value of the "billing_address_country" field. +func (u *CustomerUpsert) ClearBillingAddressCountry() *CustomerUpsert { + u.SetNull(customer.FieldBillingAddressCountry) + return u +} + +// SetBillingAddressPostalCode sets the "billing_address_postal_code" field. +func (u *CustomerUpsert) SetBillingAddressPostalCode(v string) *CustomerUpsert { + u.Set(customer.FieldBillingAddressPostalCode, v) + return u +} + +// UpdateBillingAddressPostalCode sets the "billing_address_postal_code" field to the value that was provided on create. +func (u *CustomerUpsert) UpdateBillingAddressPostalCode() *CustomerUpsert { + u.SetExcluded(customer.FieldBillingAddressPostalCode) + return u +} + +// ClearBillingAddressPostalCode clears the value of the "billing_address_postal_code" field. +func (u *CustomerUpsert) ClearBillingAddressPostalCode() *CustomerUpsert { + u.SetNull(customer.FieldBillingAddressPostalCode) + return u +} + +// SetBillingAddressState sets the "billing_address_state" field. +func (u *CustomerUpsert) SetBillingAddressState(v string) *CustomerUpsert { + u.Set(customer.FieldBillingAddressState, v) + return u +} + +// UpdateBillingAddressState sets the "billing_address_state" field to the value that was provided on create. +func (u *CustomerUpsert) UpdateBillingAddressState() *CustomerUpsert { + u.SetExcluded(customer.FieldBillingAddressState) + return u +} + +// ClearBillingAddressState clears the value of the "billing_address_state" field. +func (u *CustomerUpsert) ClearBillingAddressState() *CustomerUpsert { + u.SetNull(customer.FieldBillingAddressState) + return u +} + +// SetBillingAddressCity sets the "billing_address_city" field. +func (u *CustomerUpsert) SetBillingAddressCity(v string) *CustomerUpsert { + u.Set(customer.FieldBillingAddressCity, v) + return u +} + +// UpdateBillingAddressCity sets the "billing_address_city" field to the value that was provided on create. +func (u *CustomerUpsert) UpdateBillingAddressCity() *CustomerUpsert { + u.SetExcluded(customer.FieldBillingAddressCity) + return u +} + +// ClearBillingAddressCity clears the value of the "billing_address_city" field. +func (u *CustomerUpsert) ClearBillingAddressCity() *CustomerUpsert { + u.SetNull(customer.FieldBillingAddressCity) + return u +} + +// SetBillingAddressLine1 sets the "billing_address_line1" field. +func (u *CustomerUpsert) SetBillingAddressLine1(v string) *CustomerUpsert { + u.Set(customer.FieldBillingAddressLine1, v) + return u +} + +// UpdateBillingAddressLine1 sets the "billing_address_line1" field to the value that was provided on create. +func (u *CustomerUpsert) UpdateBillingAddressLine1() *CustomerUpsert { + u.SetExcluded(customer.FieldBillingAddressLine1) + return u +} + +// ClearBillingAddressLine1 clears the value of the "billing_address_line1" field. +func (u *CustomerUpsert) ClearBillingAddressLine1() *CustomerUpsert { + u.SetNull(customer.FieldBillingAddressLine1) + return u +} + +// SetBillingAddressLine2 sets the "billing_address_line2" field. +func (u *CustomerUpsert) SetBillingAddressLine2(v string) *CustomerUpsert { + u.Set(customer.FieldBillingAddressLine2, v) + return u +} + +// UpdateBillingAddressLine2 sets the "billing_address_line2" field to the value that was provided on create. +func (u *CustomerUpsert) UpdateBillingAddressLine2() *CustomerUpsert { + u.SetExcluded(customer.FieldBillingAddressLine2) + return u +} + +// ClearBillingAddressLine2 clears the value of the "billing_address_line2" field. +func (u *CustomerUpsert) ClearBillingAddressLine2() *CustomerUpsert { + u.SetNull(customer.FieldBillingAddressLine2) + return u +} + +// SetBillingAddressPhoneNumber sets the "billing_address_phone_number" field. +func (u *CustomerUpsert) SetBillingAddressPhoneNumber(v string) *CustomerUpsert { + u.Set(customer.FieldBillingAddressPhoneNumber, v) + return u +} + +// UpdateBillingAddressPhoneNumber sets the "billing_address_phone_number" field to the value that was provided on create. +func (u *CustomerUpsert) UpdateBillingAddressPhoneNumber() *CustomerUpsert { + u.SetExcluded(customer.FieldBillingAddressPhoneNumber) + return u +} + +// ClearBillingAddressPhoneNumber clears the value of the "billing_address_phone_number" field. +func (u *CustomerUpsert) ClearBillingAddressPhoneNumber() *CustomerUpsert { + u.SetNull(customer.FieldBillingAddressPhoneNumber) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *CustomerUpsert) SetAnnotations(v models.Annotations) *CustomerUpsert { + u.Set(customer.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *CustomerUpsert) UpdateAnnotations() *CustomerUpsert { + u.SetExcluded(customer.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *CustomerUpsert) ClearAnnotations() *CustomerUpsert { + u.SetNull(customer.FieldAnnotations) + return u +} + +// SetKey sets the "key" field. +func (u *CustomerUpsert) SetKey(v string) *CustomerUpsert { + u.Set(customer.FieldKey, v) + return u +} + +// UpdateKey sets the "key" field to the value that was provided on create. +func (u *CustomerUpsert) UpdateKey() *CustomerUpsert { + u.SetExcluded(customer.FieldKey) + return u +} + +// ClearKey clears the value of the "key" field. +func (u *CustomerUpsert) ClearKey() *CustomerUpsert { + u.SetNull(customer.FieldKey) + return u +} + +// SetPrimaryEmail sets the "primary_email" field. +func (u *CustomerUpsert) SetPrimaryEmail(v string) *CustomerUpsert { + u.Set(customer.FieldPrimaryEmail, v) + return u +} + +// UpdatePrimaryEmail sets the "primary_email" field to the value that was provided on create. +func (u *CustomerUpsert) UpdatePrimaryEmail() *CustomerUpsert { + u.SetExcluded(customer.FieldPrimaryEmail) + return u +} + +// ClearPrimaryEmail clears the value of the "primary_email" field. +func (u *CustomerUpsert) ClearPrimaryEmail() *CustomerUpsert { + u.SetNull(customer.FieldPrimaryEmail) + return u +} + +// SetCurrency sets the "currency" field. +func (u *CustomerUpsert) SetCurrency(v currencyx.Code) *CustomerUpsert { + u.Set(customer.FieldCurrency, v) + return u +} + +// UpdateCurrency sets the "currency" field to the value that was provided on create. +func (u *CustomerUpsert) UpdateCurrency() *CustomerUpsert { + u.SetExcluded(customer.FieldCurrency) + return u +} + +// ClearCurrency clears the value of the "currency" field. +func (u *CustomerUpsert) ClearCurrency() *CustomerUpsert { + u.SetNull(customer.FieldCurrency) + 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.Customer.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(customer.FieldID) +// }), +// ). +// Exec(ctx) +func (u *CustomerUpsertOne) UpdateNewValues() *CustomerUpsertOne { + 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(customer.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(customer.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(customer.FieldCreatedAt) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Customer.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *CustomerUpsertOne) Ignore() *CustomerUpsertOne { + 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 *CustomerUpsertOne) DoNothing() *CustomerUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the CustomerCreate.OnConflict +// documentation for more info. +func (u *CustomerUpsertOne) Update(set func(*CustomerUpsert)) *CustomerUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&CustomerUpsert{UpdateSet: update}) + })) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *CustomerUpsertOne) SetMetadata(v map[string]string) *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *CustomerUpsertOne) UpdateMetadata() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *CustomerUpsertOne) ClearMetadata() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *CustomerUpsertOne) SetUpdatedAt(v time.Time) *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *CustomerUpsertOne) UpdateUpdatedAt() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *CustomerUpsertOne) SetDeletedAt(v time.Time) *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *CustomerUpsertOne) UpdateDeletedAt() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *CustomerUpsertOne) ClearDeletedAt() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *CustomerUpsertOne) SetName(v string) *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *CustomerUpsertOne) UpdateName() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *CustomerUpsertOne) SetDescription(v string) *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *CustomerUpsertOne) UpdateDescription() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *CustomerUpsertOne) ClearDescription() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.ClearDescription() + }) +} + +// SetBillingAddressCountry sets the "billing_address_country" field. +func (u *CustomerUpsertOne) SetBillingAddressCountry(v models.CountryCode) *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.SetBillingAddressCountry(v) + }) +} + +// UpdateBillingAddressCountry sets the "billing_address_country" field to the value that was provided on create. +func (u *CustomerUpsertOne) UpdateBillingAddressCountry() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.UpdateBillingAddressCountry() + }) +} + +// ClearBillingAddressCountry clears the value of the "billing_address_country" field. +func (u *CustomerUpsertOne) ClearBillingAddressCountry() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.ClearBillingAddressCountry() + }) +} + +// SetBillingAddressPostalCode sets the "billing_address_postal_code" field. +func (u *CustomerUpsertOne) SetBillingAddressPostalCode(v string) *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.SetBillingAddressPostalCode(v) + }) +} + +// UpdateBillingAddressPostalCode sets the "billing_address_postal_code" field to the value that was provided on create. +func (u *CustomerUpsertOne) UpdateBillingAddressPostalCode() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.UpdateBillingAddressPostalCode() + }) +} + +// ClearBillingAddressPostalCode clears the value of the "billing_address_postal_code" field. +func (u *CustomerUpsertOne) ClearBillingAddressPostalCode() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.ClearBillingAddressPostalCode() + }) +} + +// SetBillingAddressState sets the "billing_address_state" field. +func (u *CustomerUpsertOne) SetBillingAddressState(v string) *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.SetBillingAddressState(v) + }) +} + +// UpdateBillingAddressState sets the "billing_address_state" field to the value that was provided on create. +func (u *CustomerUpsertOne) UpdateBillingAddressState() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.UpdateBillingAddressState() + }) +} + +// ClearBillingAddressState clears the value of the "billing_address_state" field. +func (u *CustomerUpsertOne) ClearBillingAddressState() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.ClearBillingAddressState() + }) +} + +// SetBillingAddressCity sets the "billing_address_city" field. +func (u *CustomerUpsertOne) SetBillingAddressCity(v string) *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.SetBillingAddressCity(v) + }) +} + +// UpdateBillingAddressCity sets the "billing_address_city" field to the value that was provided on create. +func (u *CustomerUpsertOne) UpdateBillingAddressCity() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.UpdateBillingAddressCity() + }) +} + +// ClearBillingAddressCity clears the value of the "billing_address_city" field. +func (u *CustomerUpsertOne) ClearBillingAddressCity() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.ClearBillingAddressCity() + }) +} + +// SetBillingAddressLine1 sets the "billing_address_line1" field. +func (u *CustomerUpsertOne) SetBillingAddressLine1(v string) *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.SetBillingAddressLine1(v) + }) +} + +// UpdateBillingAddressLine1 sets the "billing_address_line1" field to the value that was provided on create. +func (u *CustomerUpsertOne) UpdateBillingAddressLine1() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.UpdateBillingAddressLine1() + }) +} + +// ClearBillingAddressLine1 clears the value of the "billing_address_line1" field. +func (u *CustomerUpsertOne) ClearBillingAddressLine1() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.ClearBillingAddressLine1() + }) +} + +// SetBillingAddressLine2 sets the "billing_address_line2" field. +func (u *CustomerUpsertOne) SetBillingAddressLine2(v string) *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.SetBillingAddressLine2(v) + }) +} + +// UpdateBillingAddressLine2 sets the "billing_address_line2" field to the value that was provided on create. +func (u *CustomerUpsertOne) UpdateBillingAddressLine2() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.UpdateBillingAddressLine2() + }) +} + +// ClearBillingAddressLine2 clears the value of the "billing_address_line2" field. +func (u *CustomerUpsertOne) ClearBillingAddressLine2() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.ClearBillingAddressLine2() + }) +} + +// SetBillingAddressPhoneNumber sets the "billing_address_phone_number" field. +func (u *CustomerUpsertOne) SetBillingAddressPhoneNumber(v string) *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.SetBillingAddressPhoneNumber(v) + }) +} + +// UpdateBillingAddressPhoneNumber sets the "billing_address_phone_number" field to the value that was provided on create. +func (u *CustomerUpsertOne) UpdateBillingAddressPhoneNumber() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.UpdateBillingAddressPhoneNumber() + }) +} + +// ClearBillingAddressPhoneNumber clears the value of the "billing_address_phone_number" field. +func (u *CustomerUpsertOne) ClearBillingAddressPhoneNumber() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.ClearBillingAddressPhoneNumber() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *CustomerUpsertOne) SetAnnotations(v models.Annotations) *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *CustomerUpsertOne) UpdateAnnotations() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *CustomerUpsertOne) ClearAnnotations() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.ClearAnnotations() + }) +} + +// SetKey sets the "key" field. +func (u *CustomerUpsertOne) SetKey(v string) *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.SetKey(v) + }) +} + +// UpdateKey sets the "key" field to the value that was provided on create. +func (u *CustomerUpsertOne) UpdateKey() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.UpdateKey() + }) +} + +// ClearKey clears the value of the "key" field. +func (u *CustomerUpsertOne) ClearKey() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.ClearKey() + }) +} + +// SetPrimaryEmail sets the "primary_email" field. +func (u *CustomerUpsertOne) SetPrimaryEmail(v string) *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.SetPrimaryEmail(v) + }) +} + +// UpdatePrimaryEmail sets the "primary_email" field to the value that was provided on create. +func (u *CustomerUpsertOne) UpdatePrimaryEmail() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.UpdatePrimaryEmail() + }) +} + +// ClearPrimaryEmail clears the value of the "primary_email" field. +func (u *CustomerUpsertOne) ClearPrimaryEmail() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.ClearPrimaryEmail() + }) +} + +// SetCurrency sets the "currency" field. +func (u *CustomerUpsertOne) SetCurrency(v currencyx.Code) *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.SetCurrency(v) + }) +} + +// UpdateCurrency sets the "currency" field to the value that was provided on create. +func (u *CustomerUpsertOne) UpdateCurrency() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.UpdateCurrency() + }) +} + +// ClearCurrency clears the value of the "currency" field. +func (u *CustomerUpsertOne) ClearCurrency() *CustomerUpsertOne { + return u.Update(func(s *CustomerUpsert) { + s.ClearCurrency() + }) +} + +// Exec executes the query. +func (u *CustomerUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for CustomerCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *CustomerUpsertOne) 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 *CustomerUpsertOne) 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: CustomerUpsertOne.ID is not supported by MySQL driver. Use CustomerUpsertOne.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 *CustomerUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// CustomerCreateBulk is the builder for creating many Customer entities in bulk. +type CustomerCreateBulk struct { + config + err error + builders []*CustomerCreate + conflict []sql.ConflictOption +} + +// Save creates the Customer entities in the database. +func (_c *CustomerCreateBulk) Save(ctx context.Context) ([]*Customer, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Customer, 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.(*CustomerMutation) + 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 *CustomerCreateBulk) SaveX(ctx context.Context) []*Customer { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *CustomerCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *CustomerCreateBulk) 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.Customer.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.CustomerUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *CustomerCreateBulk) OnConflict(opts ...sql.ConflictOption) *CustomerUpsertBulk { + _c.conflict = opts + return &CustomerUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Customer.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *CustomerCreateBulk) OnConflictColumns(columns ...string) *CustomerUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &CustomerUpsertBulk{ + create: _c, + } +} + +// CustomerUpsertBulk is the builder for "upsert"-ing +// a bulk of Customer nodes. +type CustomerUpsertBulk struct { + create *CustomerCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.Customer.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(customer.FieldID) +// }), +// ). +// Exec(ctx) +func (u *CustomerUpsertBulk) UpdateNewValues() *CustomerUpsertBulk { + 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(customer.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(customer.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(customer.FieldCreatedAt) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Customer.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *CustomerUpsertBulk) Ignore() *CustomerUpsertBulk { + 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 *CustomerUpsertBulk) DoNothing() *CustomerUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the CustomerCreateBulk.OnConflict +// documentation for more info. +func (u *CustomerUpsertBulk) Update(set func(*CustomerUpsert)) *CustomerUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&CustomerUpsert{UpdateSet: update}) + })) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *CustomerUpsertBulk) SetMetadata(v map[string]string) *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *CustomerUpsertBulk) UpdateMetadata() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *CustomerUpsertBulk) ClearMetadata() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *CustomerUpsertBulk) SetUpdatedAt(v time.Time) *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *CustomerUpsertBulk) UpdateUpdatedAt() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *CustomerUpsertBulk) SetDeletedAt(v time.Time) *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *CustomerUpsertBulk) UpdateDeletedAt() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *CustomerUpsertBulk) ClearDeletedAt() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *CustomerUpsertBulk) SetName(v string) *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *CustomerUpsertBulk) UpdateName() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *CustomerUpsertBulk) SetDescription(v string) *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *CustomerUpsertBulk) UpdateDescription() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *CustomerUpsertBulk) ClearDescription() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.ClearDescription() + }) +} + +// SetBillingAddressCountry sets the "billing_address_country" field. +func (u *CustomerUpsertBulk) SetBillingAddressCountry(v models.CountryCode) *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.SetBillingAddressCountry(v) + }) +} + +// UpdateBillingAddressCountry sets the "billing_address_country" field to the value that was provided on create. +func (u *CustomerUpsertBulk) UpdateBillingAddressCountry() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.UpdateBillingAddressCountry() + }) +} + +// ClearBillingAddressCountry clears the value of the "billing_address_country" field. +func (u *CustomerUpsertBulk) ClearBillingAddressCountry() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.ClearBillingAddressCountry() + }) +} + +// SetBillingAddressPostalCode sets the "billing_address_postal_code" field. +func (u *CustomerUpsertBulk) SetBillingAddressPostalCode(v string) *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.SetBillingAddressPostalCode(v) + }) +} + +// UpdateBillingAddressPostalCode sets the "billing_address_postal_code" field to the value that was provided on create. +func (u *CustomerUpsertBulk) UpdateBillingAddressPostalCode() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.UpdateBillingAddressPostalCode() + }) +} + +// ClearBillingAddressPostalCode clears the value of the "billing_address_postal_code" field. +func (u *CustomerUpsertBulk) ClearBillingAddressPostalCode() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.ClearBillingAddressPostalCode() + }) +} + +// SetBillingAddressState sets the "billing_address_state" field. +func (u *CustomerUpsertBulk) SetBillingAddressState(v string) *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.SetBillingAddressState(v) + }) +} + +// UpdateBillingAddressState sets the "billing_address_state" field to the value that was provided on create. +func (u *CustomerUpsertBulk) UpdateBillingAddressState() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.UpdateBillingAddressState() + }) +} + +// ClearBillingAddressState clears the value of the "billing_address_state" field. +func (u *CustomerUpsertBulk) ClearBillingAddressState() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.ClearBillingAddressState() + }) +} + +// SetBillingAddressCity sets the "billing_address_city" field. +func (u *CustomerUpsertBulk) SetBillingAddressCity(v string) *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.SetBillingAddressCity(v) + }) +} + +// UpdateBillingAddressCity sets the "billing_address_city" field to the value that was provided on create. +func (u *CustomerUpsertBulk) UpdateBillingAddressCity() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.UpdateBillingAddressCity() + }) +} + +// ClearBillingAddressCity clears the value of the "billing_address_city" field. +func (u *CustomerUpsertBulk) ClearBillingAddressCity() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.ClearBillingAddressCity() + }) +} + +// SetBillingAddressLine1 sets the "billing_address_line1" field. +func (u *CustomerUpsertBulk) SetBillingAddressLine1(v string) *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.SetBillingAddressLine1(v) + }) +} + +// UpdateBillingAddressLine1 sets the "billing_address_line1" field to the value that was provided on create. +func (u *CustomerUpsertBulk) UpdateBillingAddressLine1() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.UpdateBillingAddressLine1() + }) +} + +// ClearBillingAddressLine1 clears the value of the "billing_address_line1" field. +func (u *CustomerUpsertBulk) ClearBillingAddressLine1() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.ClearBillingAddressLine1() + }) +} + +// SetBillingAddressLine2 sets the "billing_address_line2" field. +func (u *CustomerUpsertBulk) SetBillingAddressLine2(v string) *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.SetBillingAddressLine2(v) + }) +} + +// UpdateBillingAddressLine2 sets the "billing_address_line2" field to the value that was provided on create. +func (u *CustomerUpsertBulk) UpdateBillingAddressLine2() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.UpdateBillingAddressLine2() + }) +} + +// ClearBillingAddressLine2 clears the value of the "billing_address_line2" field. +func (u *CustomerUpsertBulk) ClearBillingAddressLine2() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.ClearBillingAddressLine2() + }) +} + +// SetBillingAddressPhoneNumber sets the "billing_address_phone_number" field. +func (u *CustomerUpsertBulk) SetBillingAddressPhoneNumber(v string) *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.SetBillingAddressPhoneNumber(v) + }) +} + +// UpdateBillingAddressPhoneNumber sets the "billing_address_phone_number" field to the value that was provided on create. +func (u *CustomerUpsertBulk) UpdateBillingAddressPhoneNumber() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.UpdateBillingAddressPhoneNumber() + }) +} + +// ClearBillingAddressPhoneNumber clears the value of the "billing_address_phone_number" field. +func (u *CustomerUpsertBulk) ClearBillingAddressPhoneNumber() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.ClearBillingAddressPhoneNumber() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *CustomerUpsertBulk) SetAnnotations(v models.Annotations) *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *CustomerUpsertBulk) UpdateAnnotations() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *CustomerUpsertBulk) ClearAnnotations() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.ClearAnnotations() + }) +} + +// SetKey sets the "key" field. +func (u *CustomerUpsertBulk) SetKey(v string) *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.SetKey(v) + }) +} + +// UpdateKey sets the "key" field to the value that was provided on create. +func (u *CustomerUpsertBulk) UpdateKey() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.UpdateKey() + }) +} + +// ClearKey clears the value of the "key" field. +func (u *CustomerUpsertBulk) ClearKey() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.ClearKey() + }) +} + +// SetPrimaryEmail sets the "primary_email" field. +func (u *CustomerUpsertBulk) SetPrimaryEmail(v string) *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.SetPrimaryEmail(v) + }) +} + +// UpdatePrimaryEmail sets the "primary_email" field to the value that was provided on create. +func (u *CustomerUpsertBulk) UpdatePrimaryEmail() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.UpdatePrimaryEmail() + }) +} + +// ClearPrimaryEmail clears the value of the "primary_email" field. +func (u *CustomerUpsertBulk) ClearPrimaryEmail() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.ClearPrimaryEmail() + }) +} + +// SetCurrency sets the "currency" field. +func (u *CustomerUpsertBulk) SetCurrency(v currencyx.Code) *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.SetCurrency(v) + }) +} + +// UpdateCurrency sets the "currency" field to the value that was provided on create. +func (u *CustomerUpsertBulk) UpdateCurrency() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.UpdateCurrency() + }) +} + +// ClearCurrency clears the value of the "currency" field. +func (u *CustomerUpsertBulk) ClearCurrency() *CustomerUpsertBulk { + return u.Update(func(s *CustomerUpsert) { + s.ClearCurrency() + }) +} + +// Exec executes the query. +func (u *CustomerUpsertBulk) 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 CustomerCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for CustomerCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *CustomerUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/customer_delete.go b/ent/db/customer_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..45f3f897a97754d2e7bbf95193c68d7997c91f16 --- /dev/null +++ b/ent/db/customer_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/customer" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// CustomerDelete is the builder for deleting a Customer entity. +type CustomerDelete struct { + config + hooks []Hook + mutation *CustomerMutation +} + +// Where appends a list predicates to the CustomerDelete builder. +func (_d *CustomerDelete) Where(ps ...predicate.Customer) *CustomerDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *CustomerDelete) 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 *CustomerDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *CustomerDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(customer.Table, sqlgraph.NewFieldSpec(customer.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 +} + +// CustomerDeleteOne is the builder for deleting a single Customer entity. +type CustomerDeleteOne struct { + _d *CustomerDelete +} + +// Where appends a list predicates to the CustomerDelete builder. +func (_d *CustomerDeleteOne) Where(ps ...predicate.Customer) *CustomerDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *CustomerDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{customer.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *CustomerDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/customer_query.go b/ent/db/customer_query.go new file mode 100644 index 0000000000000000000000000000000000000000..853759a622caa2cef93ea070f0eac46f0a4802e0 --- /dev/null +++ b/ent/db/customer_query.go @@ -0,0 +1,1235 @@ +// 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/appcustomer" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingcustomeroverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "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/customersubjects" + "github.com/openmeterio/openmeter/openmeter/ent/db/entitlement" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" +) + +// CustomerQuery is the builder for querying Customer entities. +type CustomerQuery struct { + config + ctx *QueryContext + order []customer.OrderOption + inters []Interceptor + predicates []predicate.Customer + withApps *AppCustomerQuery + withSubjects *CustomerSubjectsQuery + withBillingCustomerOverride *BillingCustomerOverrideQuery + withBillingInvoice *BillingInvoiceQuery + withSubscription *SubscriptionQuery + withEntitlements *EntitlementQuery + withChargesCreditPurchase *ChargeCreditPurchaseQuery + withChargesFlatFee *ChargeFlatFeeQuery + withChargesUsageBased *ChargeUsageBasedQuery + 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 CustomerQuery builder. +func (_q *CustomerQuery) Where(ps ...predicate.Customer) *CustomerQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *CustomerQuery) Limit(limit int) *CustomerQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *CustomerQuery) Offset(offset int) *CustomerQuery { + _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 *CustomerQuery) Unique(unique bool) *CustomerQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *CustomerQuery) Order(o ...customer.OrderOption) *CustomerQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryApps chains the current query on the "apps" edge. +func (_q *CustomerQuery) QueryApps() *AppCustomerQuery { + query := (&AppCustomerClient{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(customer.Table, customer.FieldID, selector), + sqlgraph.To(appcustomer.Table, appcustomer.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, customer.AppsTable, customer.AppsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySubjects chains the current query on the "subjects" edge. +func (_q *CustomerQuery) QuerySubjects() *CustomerSubjectsQuery { + query := (&CustomerSubjectsClient{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(customer.Table, customer.FieldID, selector), + sqlgraph.To(customersubjects.Table, customersubjects.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, customer.SubjectsTable, customer.SubjectsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryBillingCustomerOverride chains the current query on the "billing_customer_override" edge. +func (_q *CustomerQuery) QueryBillingCustomerOverride() *BillingCustomerOverrideQuery { + query := (&BillingCustomerOverrideClient{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(customer.Table, customer.FieldID, selector), + sqlgraph.To(billingcustomeroverride.Table, billingcustomeroverride.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, customer.BillingCustomerOverrideTable, customer.BillingCustomerOverrideColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryBillingInvoice chains the current query on the "billing_invoice" edge. +func (_q *CustomerQuery) QueryBillingInvoice() *BillingInvoiceQuery { + query := (&BillingInvoiceClient{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(customer.Table, customer.FieldID, selector), + sqlgraph.To(billinginvoice.Table, billinginvoice.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, customer.BillingInvoiceTable, customer.BillingInvoiceColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySubscription chains the current query on the "subscription" edge. +func (_q *CustomerQuery) QuerySubscription() *SubscriptionQuery { + query := (&SubscriptionClient{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(customer.Table, customer.FieldID, selector), + sqlgraph.To(subscription.Table, subscription.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, customer.SubscriptionTable, customer.SubscriptionColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryEntitlements chains the current query on the "entitlements" edge. +func (_q *CustomerQuery) QueryEntitlements() *EntitlementQuery { + query := (&EntitlementClient{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(customer.Table, customer.FieldID, selector), + sqlgraph.To(entitlement.Table, entitlement.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, customer.EntitlementsTable, customer.EntitlementsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryChargesCreditPurchase chains the current query on the "charges_credit_purchase" edge. +func (_q *CustomerQuery) QueryChargesCreditPurchase() *ChargeCreditPurchaseQuery { + query := (&ChargeCreditPurchaseClient{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(customer.Table, customer.FieldID, selector), + sqlgraph.To(chargecreditpurchase.Table, chargecreditpurchase.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, customer.ChargesCreditPurchaseTable, customer.ChargesCreditPurchaseColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryChargesFlatFee chains the current query on the "charges_flat_fee" edge. +func (_q *CustomerQuery) QueryChargesFlatFee() *ChargeFlatFeeQuery { + query := (&ChargeFlatFeeClient{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(customer.Table, customer.FieldID, selector), + sqlgraph.To(chargeflatfee.Table, chargeflatfee.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, customer.ChargesFlatFeeTable, customer.ChargesFlatFeeColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryChargesUsageBased chains the current query on the "charges_usage_based" edge. +func (_q *CustomerQuery) QueryChargesUsageBased() *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(customer.Table, customer.FieldID, selector), + sqlgraph.To(chargeusagebased.Table, chargeusagebased.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, customer.ChargesUsageBasedTable, customer.ChargesUsageBasedColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Customer entity from the query. +// Returns a *NotFoundError when no Customer was found. +func (_q *CustomerQuery) First(ctx context.Context) (*Customer, 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{customer.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *CustomerQuery) FirstX(ctx context.Context) *Customer { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Customer ID from the query. +// Returns a *NotFoundError when no Customer ID was found. +func (_q *CustomerQuery) 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{customer.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *CustomerQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Customer entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Customer entity is found. +// Returns a *NotFoundError when no Customer entities are found. +func (_q *CustomerQuery) Only(ctx context.Context) (*Customer, 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{customer.Label} + default: + return nil, &NotSingularError{customer.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *CustomerQuery) OnlyX(ctx context.Context) *Customer { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Customer ID in the query. +// Returns a *NotSingularError when more than one Customer ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *CustomerQuery) 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{customer.Label} + default: + err = &NotSingularError{customer.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *CustomerQuery) 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 Customers. +func (_q *CustomerQuery) All(ctx context.Context) ([]*Customer, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Customer, *CustomerQuery]() + return withInterceptors[[]*Customer](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *CustomerQuery) AllX(ctx context.Context) []*Customer { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Customer IDs. +func (_q *CustomerQuery) 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(customer.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *CustomerQuery) 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 *CustomerQuery) 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[*CustomerQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *CustomerQuery) 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 *CustomerQuery) 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 *CustomerQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the CustomerQuery 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 *CustomerQuery) Clone() *CustomerQuery { + if _q == nil { + return nil + } + return &CustomerQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]customer.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Customer{}, _q.predicates...), + withApps: _q.withApps.Clone(), + withSubjects: _q.withSubjects.Clone(), + withBillingCustomerOverride: _q.withBillingCustomerOverride.Clone(), + withBillingInvoice: _q.withBillingInvoice.Clone(), + withSubscription: _q.withSubscription.Clone(), + withEntitlements: _q.withEntitlements.Clone(), + withChargesCreditPurchase: _q.withChargesCreditPurchase.Clone(), + withChargesFlatFee: _q.withChargesFlatFee.Clone(), + withChargesUsageBased: _q.withChargesUsageBased.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithApps tells the query-builder to eager-load the nodes that are connected to +// the "apps" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *CustomerQuery) WithApps(opts ...func(*AppCustomerQuery)) *CustomerQuery { + query := (&AppCustomerClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withApps = query + return _q +} + +// WithSubjects tells the query-builder to eager-load the nodes that are connected to +// the "subjects" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *CustomerQuery) WithSubjects(opts ...func(*CustomerSubjectsQuery)) *CustomerQuery { + query := (&CustomerSubjectsClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSubjects = query + return _q +} + +// WithBillingCustomerOverride tells the query-builder to eager-load the nodes that are connected to +// the "billing_customer_override" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *CustomerQuery) WithBillingCustomerOverride(opts ...func(*BillingCustomerOverrideQuery)) *CustomerQuery { + query := (&BillingCustomerOverrideClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingCustomerOverride = query + return _q +} + +// WithBillingInvoice tells the query-builder to eager-load the nodes that are connected to +// the "billing_invoice" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *CustomerQuery) WithBillingInvoice(opts ...func(*BillingInvoiceQuery)) *CustomerQuery { + query := (&BillingInvoiceClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBillingInvoice = query + return _q +} + +// WithSubscription tells the query-builder to eager-load the nodes that are connected to +// the "subscription" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *CustomerQuery) WithSubscription(opts ...func(*SubscriptionQuery)) *CustomerQuery { + query := (&SubscriptionClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSubscription = query + return _q +} + +// WithEntitlements tells the query-builder to eager-load the nodes that are connected to +// the "entitlements" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *CustomerQuery) WithEntitlements(opts ...func(*EntitlementQuery)) *CustomerQuery { + query := (&EntitlementClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withEntitlements = query + return _q +} + +// WithChargesCreditPurchase tells the query-builder to eager-load the nodes that are connected to +// the "charges_credit_purchase" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *CustomerQuery) WithChargesCreditPurchase(opts ...func(*ChargeCreditPurchaseQuery)) *CustomerQuery { + query := (&ChargeCreditPurchaseClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withChargesCreditPurchase = query + return _q +} + +// WithChargesFlatFee tells the query-builder to eager-load the nodes that are connected to +// the "charges_flat_fee" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *CustomerQuery) WithChargesFlatFee(opts ...func(*ChargeFlatFeeQuery)) *CustomerQuery { + query := (&ChargeFlatFeeClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withChargesFlatFee = query + return _q +} + +// WithChargesUsageBased tells the query-builder to eager-load the nodes that are connected to +// the "charges_usage_based" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *CustomerQuery) WithChargesUsageBased(opts ...func(*ChargeUsageBasedQuery)) *CustomerQuery { + query := (&ChargeUsageBasedClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withChargesUsageBased = 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.Customer.Query(). +// GroupBy(customer.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *CustomerQuery) GroupBy(field string, fields ...string) *CustomerGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &CustomerGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = customer.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.Customer.Query(). +// Select(customer.FieldNamespace). +// Scan(ctx, &v) +func (_q *CustomerQuery) Select(fields ...string) *CustomerSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &CustomerSelect{CustomerQuery: _q} + sbuild.label = customer.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a CustomerSelect configured with the given aggregations. +func (_q *CustomerQuery) Aggregate(fns ...AggregateFunc) *CustomerSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *CustomerQuery) 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 !customer.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 *CustomerQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Customer, error) { + var ( + nodes = []*Customer{} + _spec = _q.querySpec() + loadedTypes = [9]bool{ + _q.withApps != nil, + _q.withSubjects != nil, + _q.withBillingCustomerOverride != nil, + _q.withBillingInvoice != nil, + _q.withSubscription != nil, + _q.withEntitlements != nil, + _q.withChargesCreditPurchase != nil, + _q.withChargesFlatFee != nil, + _q.withChargesUsageBased != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Customer).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Customer{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.withApps; query != nil { + if err := _q.loadApps(ctx, query, nodes, + func(n *Customer) { n.Edges.Apps = []*AppCustomer{} }, + func(n *Customer, e *AppCustomer) { n.Edges.Apps = append(n.Edges.Apps, e) }); err != nil { + return nil, err + } + } + if query := _q.withSubjects; query != nil { + if err := _q.loadSubjects(ctx, query, nodes, + func(n *Customer) { n.Edges.Subjects = []*CustomerSubjects{} }, + func(n *Customer, e *CustomerSubjects) { n.Edges.Subjects = append(n.Edges.Subjects, e) }); err != nil { + return nil, err + } + } + if query := _q.withBillingCustomerOverride; query != nil { + if err := _q.loadBillingCustomerOverride(ctx, query, nodes, nil, + func(n *Customer, e *BillingCustomerOverride) { n.Edges.BillingCustomerOverride = e }); err != nil { + return nil, err + } + } + if query := _q.withBillingInvoice; query != nil { + if err := _q.loadBillingInvoice(ctx, query, nodes, + func(n *Customer) { n.Edges.BillingInvoice = []*BillingInvoice{} }, + func(n *Customer, e *BillingInvoice) { n.Edges.BillingInvoice = append(n.Edges.BillingInvoice, e) }); err != nil { + return nil, err + } + } + if query := _q.withSubscription; query != nil { + if err := _q.loadSubscription(ctx, query, nodes, + func(n *Customer) { n.Edges.Subscription = []*Subscription{} }, + func(n *Customer, e *Subscription) { n.Edges.Subscription = append(n.Edges.Subscription, e) }); err != nil { + return nil, err + } + } + if query := _q.withEntitlements; query != nil { + if err := _q.loadEntitlements(ctx, query, nodes, + func(n *Customer) { n.Edges.Entitlements = []*Entitlement{} }, + func(n *Customer, e *Entitlement) { n.Edges.Entitlements = append(n.Edges.Entitlements, e) }); err != nil { + return nil, err + } + } + if query := _q.withChargesCreditPurchase; query != nil { + if err := _q.loadChargesCreditPurchase(ctx, query, nodes, + func(n *Customer) { n.Edges.ChargesCreditPurchase = []*ChargeCreditPurchase{} }, + func(n *Customer, e *ChargeCreditPurchase) { + n.Edges.ChargesCreditPurchase = append(n.Edges.ChargesCreditPurchase, e) + }); err != nil { + return nil, err + } + } + if query := _q.withChargesFlatFee; query != nil { + if err := _q.loadChargesFlatFee(ctx, query, nodes, + func(n *Customer) { n.Edges.ChargesFlatFee = []*ChargeFlatFee{} }, + func(n *Customer, e *ChargeFlatFee) { n.Edges.ChargesFlatFee = append(n.Edges.ChargesFlatFee, e) }); err != nil { + return nil, err + } + } + if query := _q.withChargesUsageBased; query != nil { + if err := _q.loadChargesUsageBased(ctx, query, nodes, + func(n *Customer) { n.Edges.ChargesUsageBased = []*ChargeUsageBased{} }, + func(n *Customer, e *ChargeUsageBased) { + n.Edges.ChargesUsageBased = append(n.Edges.ChargesUsageBased, e) + }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *CustomerQuery) loadApps(ctx context.Context, query *AppCustomerQuery, nodes []*Customer, init func(*Customer), assign func(*Customer, *AppCustomer)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Customer) + 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(appcustomer.FieldCustomerID) + } + query.Where(predicate.AppCustomer(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(customer.AppsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.CustomerID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "customer_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *CustomerQuery) loadSubjects(ctx context.Context, query *CustomerSubjectsQuery, nodes []*Customer, init func(*Customer), assign func(*Customer, *CustomerSubjects)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Customer) + 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(customersubjects.FieldCustomerID) + } + query.Where(predicate.CustomerSubjects(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(customer.SubjectsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.CustomerID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "customer_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *CustomerQuery) loadBillingCustomerOverride(ctx context.Context, query *BillingCustomerOverrideQuery, nodes []*Customer, init func(*Customer), assign func(*Customer, *BillingCustomerOverride)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Customer) + 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(billingcustomeroverride.FieldCustomerID) + } + query.Where(predicate.BillingCustomerOverride(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(customer.BillingCustomerOverrideColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.CustomerID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "customer_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *CustomerQuery) loadBillingInvoice(ctx context.Context, query *BillingInvoiceQuery, nodes []*Customer, init func(*Customer), assign func(*Customer, *BillingInvoice)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Customer) + 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(billinginvoice.FieldCustomerID) + } + query.Where(predicate.BillingInvoice(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(customer.BillingInvoiceColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.CustomerID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "customer_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *CustomerQuery) loadSubscription(ctx context.Context, query *SubscriptionQuery, nodes []*Customer, init func(*Customer), assign func(*Customer, *Subscription)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Customer) + 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(subscription.FieldCustomerID) + } + query.Where(predicate.Subscription(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(customer.SubscriptionColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.CustomerID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "customer_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *CustomerQuery) loadEntitlements(ctx context.Context, query *EntitlementQuery, nodes []*Customer, init func(*Customer), assign func(*Customer, *Entitlement)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Customer) + 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(entitlement.FieldCustomerID) + } + query.Where(predicate.Entitlement(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(customer.EntitlementsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.CustomerID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "customer_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *CustomerQuery) loadChargesCreditPurchase(ctx context.Context, query *ChargeCreditPurchaseQuery, nodes []*Customer, init func(*Customer), assign func(*Customer, *ChargeCreditPurchase)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Customer) + 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(chargecreditpurchase.FieldCustomerID) + } + query.Where(predicate.ChargeCreditPurchase(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(customer.ChargesCreditPurchaseColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.CustomerID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "customer_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *CustomerQuery) loadChargesFlatFee(ctx context.Context, query *ChargeFlatFeeQuery, nodes []*Customer, init func(*Customer), assign func(*Customer, *ChargeFlatFee)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Customer) + 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(chargeflatfee.FieldCustomerID) + } + query.Where(predicate.ChargeFlatFee(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(customer.ChargesFlatFeeColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.CustomerID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "customer_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *CustomerQuery) loadChargesUsageBased(ctx context.Context, query *ChargeUsageBasedQuery, nodes []*Customer, init func(*Customer), assign func(*Customer, *ChargeUsageBased)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Customer) + 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(chargeusagebased.FieldCustomerID) + } + query.Where(predicate.ChargeUsageBased(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(customer.ChargesUsageBasedColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.CustomerID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "customer_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *CustomerQuery) 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 *CustomerQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(customer.Table, customer.Columns, sqlgraph.NewFieldSpec(customer.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, customer.FieldID) + for i := range fields { + if fields[i] != customer.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 *CustomerQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(customer.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = customer.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 *CustomerQuery) ForUpdate(opts ...sql.LockOption) *CustomerQuery { + 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 *CustomerQuery) ForShare(opts ...sql.LockOption) *CustomerQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// CustomerGroupBy is the group-by builder for Customer entities. +type CustomerGroupBy struct { + selector + build *CustomerQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *CustomerGroupBy) Aggregate(fns ...AggregateFunc) *CustomerGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *CustomerGroupBy) 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[*CustomerQuery, *CustomerGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *CustomerGroupBy) sqlScan(ctx context.Context, root *CustomerQuery, 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) +} + +// CustomerSelect is the builder for selecting fields of Customer entities. +type CustomerSelect struct { + *CustomerQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *CustomerSelect) Aggregate(fns ...AggregateFunc) *CustomerSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *CustomerSelect) 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[*CustomerQuery, *CustomerSelect](ctx, _s.CustomerQuery, _s, _s.inters, v) +} + +func (_s *CustomerSelect) sqlScan(ctx context.Context, root *CustomerQuery, 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/ent/db/customer_update.go b/ent/db/customer_update.go new file mode 100644 index 0000000000000000000000000000000000000000..723bc7a1ba896c429e55841693c769b3a3f49cd7 --- /dev/null +++ b/ent/db/customer_update.go @@ -0,0 +1,2393 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/appcustomer" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingcustomeroverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "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/customersubjects" + "github.com/openmeterio/openmeter/openmeter/ent/db/entitlement" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// CustomerUpdate is the builder for updating Customer entities. +type CustomerUpdate struct { + config + hooks []Hook + mutation *CustomerMutation +} + +// Where appends a list predicates to the CustomerUpdate builder. +func (_u *CustomerUpdate) Where(ps ...predicate.Customer) *CustomerUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *CustomerUpdate) SetMetadata(v map[string]string) *CustomerUpdate { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *CustomerUpdate) ClearMetadata() *CustomerUpdate { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *CustomerUpdate) SetUpdatedAt(v time.Time) *CustomerUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *CustomerUpdate) SetDeletedAt(v time.Time) *CustomerUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *CustomerUpdate) SetNillableDeletedAt(v *time.Time) *CustomerUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *CustomerUpdate) ClearDeletedAt() *CustomerUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *CustomerUpdate) SetName(v string) *CustomerUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *CustomerUpdate) SetNillableName(v *string) *CustomerUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *CustomerUpdate) SetDescription(v string) *CustomerUpdate { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *CustomerUpdate) SetNillableDescription(v *string) *CustomerUpdate { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *CustomerUpdate) ClearDescription() *CustomerUpdate { + _u.mutation.ClearDescription() + return _u +} + +// SetBillingAddressCountry sets the "billing_address_country" field. +func (_u *CustomerUpdate) SetBillingAddressCountry(v models.CountryCode) *CustomerUpdate { + _u.mutation.SetBillingAddressCountry(v) + return _u +} + +// SetNillableBillingAddressCountry sets the "billing_address_country" field if the given value is not nil. +func (_u *CustomerUpdate) SetNillableBillingAddressCountry(v *models.CountryCode) *CustomerUpdate { + if v != nil { + _u.SetBillingAddressCountry(*v) + } + return _u +} + +// ClearBillingAddressCountry clears the value of the "billing_address_country" field. +func (_u *CustomerUpdate) ClearBillingAddressCountry() *CustomerUpdate { + _u.mutation.ClearBillingAddressCountry() + return _u +} + +// SetBillingAddressPostalCode sets the "billing_address_postal_code" field. +func (_u *CustomerUpdate) SetBillingAddressPostalCode(v string) *CustomerUpdate { + _u.mutation.SetBillingAddressPostalCode(v) + return _u +} + +// SetNillableBillingAddressPostalCode sets the "billing_address_postal_code" field if the given value is not nil. +func (_u *CustomerUpdate) SetNillableBillingAddressPostalCode(v *string) *CustomerUpdate { + if v != nil { + _u.SetBillingAddressPostalCode(*v) + } + return _u +} + +// ClearBillingAddressPostalCode clears the value of the "billing_address_postal_code" field. +func (_u *CustomerUpdate) ClearBillingAddressPostalCode() *CustomerUpdate { + _u.mutation.ClearBillingAddressPostalCode() + return _u +} + +// SetBillingAddressState sets the "billing_address_state" field. +func (_u *CustomerUpdate) SetBillingAddressState(v string) *CustomerUpdate { + _u.mutation.SetBillingAddressState(v) + return _u +} + +// SetNillableBillingAddressState sets the "billing_address_state" field if the given value is not nil. +func (_u *CustomerUpdate) SetNillableBillingAddressState(v *string) *CustomerUpdate { + if v != nil { + _u.SetBillingAddressState(*v) + } + return _u +} + +// ClearBillingAddressState clears the value of the "billing_address_state" field. +func (_u *CustomerUpdate) ClearBillingAddressState() *CustomerUpdate { + _u.mutation.ClearBillingAddressState() + return _u +} + +// SetBillingAddressCity sets the "billing_address_city" field. +func (_u *CustomerUpdate) SetBillingAddressCity(v string) *CustomerUpdate { + _u.mutation.SetBillingAddressCity(v) + return _u +} + +// SetNillableBillingAddressCity sets the "billing_address_city" field if the given value is not nil. +func (_u *CustomerUpdate) SetNillableBillingAddressCity(v *string) *CustomerUpdate { + if v != nil { + _u.SetBillingAddressCity(*v) + } + return _u +} + +// ClearBillingAddressCity clears the value of the "billing_address_city" field. +func (_u *CustomerUpdate) ClearBillingAddressCity() *CustomerUpdate { + _u.mutation.ClearBillingAddressCity() + return _u +} + +// SetBillingAddressLine1 sets the "billing_address_line1" field. +func (_u *CustomerUpdate) SetBillingAddressLine1(v string) *CustomerUpdate { + _u.mutation.SetBillingAddressLine1(v) + return _u +} + +// SetNillableBillingAddressLine1 sets the "billing_address_line1" field if the given value is not nil. +func (_u *CustomerUpdate) SetNillableBillingAddressLine1(v *string) *CustomerUpdate { + if v != nil { + _u.SetBillingAddressLine1(*v) + } + return _u +} + +// ClearBillingAddressLine1 clears the value of the "billing_address_line1" field. +func (_u *CustomerUpdate) ClearBillingAddressLine1() *CustomerUpdate { + _u.mutation.ClearBillingAddressLine1() + return _u +} + +// SetBillingAddressLine2 sets the "billing_address_line2" field. +func (_u *CustomerUpdate) SetBillingAddressLine2(v string) *CustomerUpdate { + _u.mutation.SetBillingAddressLine2(v) + return _u +} + +// SetNillableBillingAddressLine2 sets the "billing_address_line2" field if the given value is not nil. +func (_u *CustomerUpdate) SetNillableBillingAddressLine2(v *string) *CustomerUpdate { + if v != nil { + _u.SetBillingAddressLine2(*v) + } + return _u +} + +// ClearBillingAddressLine2 clears the value of the "billing_address_line2" field. +func (_u *CustomerUpdate) ClearBillingAddressLine2() *CustomerUpdate { + _u.mutation.ClearBillingAddressLine2() + return _u +} + +// SetBillingAddressPhoneNumber sets the "billing_address_phone_number" field. +func (_u *CustomerUpdate) SetBillingAddressPhoneNumber(v string) *CustomerUpdate { + _u.mutation.SetBillingAddressPhoneNumber(v) + return _u +} + +// SetNillableBillingAddressPhoneNumber sets the "billing_address_phone_number" field if the given value is not nil. +func (_u *CustomerUpdate) SetNillableBillingAddressPhoneNumber(v *string) *CustomerUpdate { + if v != nil { + _u.SetBillingAddressPhoneNumber(*v) + } + return _u +} + +// ClearBillingAddressPhoneNumber clears the value of the "billing_address_phone_number" field. +func (_u *CustomerUpdate) ClearBillingAddressPhoneNumber() *CustomerUpdate { + _u.mutation.ClearBillingAddressPhoneNumber() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *CustomerUpdate) SetAnnotations(v models.Annotations) *CustomerUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *CustomerUpdate) ClearAnnotations() *CustomerUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetKey sets the "key" field. +func (_u *CustomerUpdate) SetKey(v string) *CustomerUpdate { + _u.mutation.SetKey(v) + return _u +} + +// SetNillableKey sets the "key" field if the given value is not nil. +func (_u *CustomerUpdate) SetNillableKey(v *string) *CustomerUpdate { + if v != nil { + _u.SetKey(*v) + } + return _u +} + +// ClearKey clears the value of the "key" field. +func (_u *CustomerUpdate) ClearKey() *CustomerUpdate { + _u.mutation.ClearKey() + return _u +} + +// SetPrimaryEmail sets the "primary_email" field. +func (_u *CustomerUpdate) SetPrimaryEmail(v string) *CustomerUpdate { + _u.mutation.SetPrimaryEmail(v) + return _u +} + +// SetNillablePrimaryEmail sets the "primary_email" field if the given value is not nil. +func (_u *CustomerUpdate) SetNillablePrimaryEmail(v *string) *CustomerUpdate { + if v != nil { + _u.SetPrimaryEmail(*v) + } + return _u +} + +// ClearPrimaryEmail clears the value of the "primary_email" field. +func (_u *CustomerUpdate) ClearPrimaryEmail() *CustomerUpdate { + _u.mutation.ClearPrimaryEmail() + return _u +} + +// SetCurrency sets the "currency" field. +func (_u *CustomerUpdate) SetCurrency(v currencyx.Code) *CustomerUpdate { + _u.mutation.SetCurrency(v) + return _u +} + +// SetNillableCurrency sets the "currency" field if the given value is not nil. +func (_u *CustomerUpdate) SetNillableCurrency(v *currencyx.Code) *CustomerUpdate { + if v != nil { + _u.SetCurrency(*v) + } + return _u +} + +// ClearCurrency clears the value of the "currency" field. +func (_u *CustomerUpdate) ClearCurrency() *CustomerUpdate { + _u.mutation.ClearCurrency() + return _u +} + +// AddAppIDs adds the "apps" edge to the AppCustomer entity by IDs. +func (_u *CustomerUpdate) AddAppIDs(ids ...int) *CustomerUpdate { + _u.mutation.AddAppIDs(ids...) + return _u +} + +// AddApps adds the "apps" edges to the AppCustomer entity. +func (_u *CustomerUpdate) AddApps(v ...*AppCustomer) *CustomerUpdate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddAppIDs(ids...) +} + +// AddSubjectIDs adds the "subjects" edge to the CustomerSubjects entity by IDs. +func (_u *CustomerUpdate) AddSubjectIDs(ids ...int) *CustomerUpdate { + _u.mutation.AddSubjectIDs(ids...) + return _u +} + +// AddSubjects adds the "subjects" edges to the CustomerSubjects entity. +func (_u *CustomerUpdate) AddSubjects(v ...*CustomerSubjects) *CustomerUpdate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSubjectIDs(ids...) +} + +// SetBillingCustomerOverrideID sets the "billing_customer_override" edge to the BillingCustomerOverride entity by ID. +func (_u *CustomerUpdate) SetBillingCustomerOverrideID(id string) *CustomerUpdate { + _u.mutation.SetBillingCustomerOverrideID(id) + return _u +} + +// SetNillableBillingCustomerOverrideID sets the "billing_customer_override" edge to the BillingCustomerOverride entity by ID if the given value is not nil. +func (_u *CustomerUpdate) SetNillableBillingCustomerOverrideID(id *string) *CustomerUpdate { + if id != nil { + _u = _u.SetBillingCustomerOverrideID(*id) + } + return _u +} + +// SetBillingCustomerOverride sets the "billing_customer_override" edge to the BillingCustomerOverride entity. +func (_u *CustomerUpdate) SetBillingCustomerOverride(v *BillingCustomerOverride) *CustomerUpdate { + return _u.SetBillingCustomerOverrideID(v.ID) +} + +// AddBillingInvoiceIDs adds the "billing_invoice" edge to the BillingInvoice entity by IDs. +func (_u *CustomerUpdate) AddBillingInvoiceIDs(ids ...string) *CustomerUpdate { + _u.mutation.AddBillingInvoiceIDs(ids...) + return _u +} + +// AddBillingInvoice adds the "billing_invoice" edges to the BillingInvoice entity. +func (_u *CustomerUpdate) AddBillingInvoice(v ...*BillingInvoice) *CustomerUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddBillingInvoiceIDs(ids...) +} + +// AddSubscriptionIDs adds the "subscription" edge to the Subscription entity by IDs. +func (_u *CustomerUpdate) AddSubscriptionIDs(ids ...string) *CustomerUpdate { + _u.mutation.AddSubscriptionIDs(ids...) + return _u +} + +// AddSubscription adds the "subscription" edges to the Subscription entity. +func (_u *CustomerUpdate) AddSubscription(v ...*Subscription) *CustomerUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSubscriptionIDs(ids...) +} + +// AddEntitlementIDs adds the "entitlements" edge to the Entitlement entity by IDs. +func (_u *CustomerUpdate) AddEntitlementIDs(ids ...string) *CustomerUpdate { + _u.mutation.AddEntitlementIDs(ids...) + return _u +} + +// AddEntitlements adds the "entitlements" edges to the Entitlement entity. +func (_u *CustomerUpdate) AddEntitlements(v ...*Entitlement) *CustomerUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddEntitlementIDs(ids...) +} + +// AddChargesCreditPurchaseIDs adds the "charges_credit_purchase" edge to the ChargeCreditPurchase entity by IDs. +func (_u *CustomerUpdate) AddChargesCreditPurchaseIDs(ids ...string) *CustomerUpdate { + _u.mutation.AddChargesCreditPurchaseIDs(ids...) + return _u +} + +// AddChargesCreditPurchase adds the "charges_credit_purchase" edges to the ChargeCreditPurchase entity. +func (_u *CustomerUpdate) AddChargesCreditPurchase(v ...*ChargeCreditPurchase) *CustomerUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddChargesCreditPurchaseIDs(ids...) +} + +// AddChargesFlatFeeIDs adds the "charges_flat_fee" edge to the ChargeFlatFee entity by IDs. +func (_u *CustomerUpdate) AddChargesFlatFeeIDs(ids ...string) *CustomerUpdate { + _u.mutation.AddChargesFlatFeeIDs(ids...) + return _u +} + +// AddChargesFlatFee adds the "charges_flat_fee" edges to the ChargeFlatFee entity. +func (_u *CustomerUpdate) AddChargesFlatFee(v ...*ChargeFlatFee) *CustomerUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddChargesFlatFeeIDs(ids...) +} + +// AddChargesUsageBasedIDs adds the "charges_usage_based" edge to the ChargeUsageBased entity by IDs. +func (_u *CustomerUpdate) AddChargesUsageBasedIDs(ids ...string) *CustomerUpdate { + _u.mutation.AddChargesUsageBasedIDs(ids...) + return _u +} + +// AddChargesUsageBased adds the "charges_usage_based" edges to the ChargeUsageBased entity. +func (_u *CustomerUpdate) AddChargesUsageBased(v ...*ChargeUsageBased) *CustomerUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddChargesUsageBasedIDs(ids...) +} + +// Mutation returns the CustomerMutation object of the builder. +func (_u *CustomerUpdate) Mutation() *CustomerMutation { + return _u.mutation +} + +// ClearApps clears all "apps" edges to the AppCustomer entity. +func (_u *CustomerUpdate) ClearApps() *CustomerUpdate { + _u.mutation.ClearApps() + return _u +} + +// RemoveAppIDs removes the "apps" edge to AppCustomer entities by IDs. +func (_u *CustomerUpdate) RemoveAppIDs(ids ...int) *CustomerUpdate { + _u.mutation.RemoveAppIDs(ids...) + return _u +} + +// RemoveApps removes "apps" edges to AppCustomer entities. +func (_u *CustomerUpdate) RemoveApps(v ...*AppCustomer) *CustomerUpdate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveAppIDs(ids...) +} + +// ClearSubjects clears all "subjects" edges to the CustomerSubjects entity. +func (_u *CustomerUpdate) ClearSubjects() *CustomerUpdate { + _u.mutation.ClearSubjects() + return _u +} + +// RemoveSubjectIDs removes the "subjects" edge to CustomerSubjects entities by IDs. +func (_u *CustomerUpdate) RemoveSubjectIDs(ids ...int) *CustomerUpdate { + _u.mutation.RemoveSubjectIDs(ids...) + return _u +} + +// RemoveSubjects removes "subjects" edges to CustomerSubjects entities. +func (_u *CustomerUpdate) RemoveSubjects(v ...*CustomerSubjects) *CustomerUpdate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSubjectIDs(ids...) +} + +// ClearBillingCustomerOverride clears the "billing_customer_override" edge to the BillingCustomerOverride entity. +func (_u *CustomerUpdate) ClearBillingCustomerOverride() *CustomerUpdate { + _u.mutation.ClearBillingCustomerOverride() + return _u +} + +// ClearBillingInvoice clears all "billing_invoice" edges to the BillingInvoice entity. +func (_u *CustomerUpdate) ClearBillingInvoice() *CustomerUpdate { + _u.mutation.ClearBillingInvoice() + return _u +} + +// RemoveBillingInvoiceIDs removes the "billing_invoice" edge to BillingInvoice entities by IDs. +func (_u *CustomerUpdate) RemoveBillingInvoiceIDs(ids ...string) *CustomerUpdate { + _u.mutation.RemoveBillingInvoiceIDs(ids...) + return _u +} + +// RemoveBillingInvoice removes "billing_invoice" edges to BillingInvoice entities. +func (_u *CustomerUpdate) RemoveBillingInvoice(v ...*BillingInvoice) *CustomerUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveBillingInvoiceIDs(ids...) +} + +// ClearSubscription clears all "subscription" edges to the Subscription entity. +func (_u *CustomerUpdate) ClearSubscription() *CustomerUpdate { + _u.mutation.ClearSubscription() + return _u +} + +// RemoveSubscriptionIDs removes the "subscription" edge to Subscription entities by IDs. +func (_u *CustomerUpdate) RemoveSubscriptionIDs(ids ...string) *CustomerUpdate { + _u.mutation.RemoveSubscriptionIDs(ids...) + return _u +} + +// RemoveSubscription removes "subscription" edges to Subscription entities. +func (_u *CustomerUpdate) RemoveSubscription(v ...*Subscription) *CustomerUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSubscriptionIDs(ids...) +} + +// ClearEntitlements clears all "entitlements" edges to the Entitlement entity. +func (_u *CustomerUpdate) ClearEntitlements() *CustomerUpdate { + _u.mutation.ClearEntitlements() + return _u +} + +// RemoveEntitlementIDs removes the "entitlements" edge to Entitlement entities by IDs. +func (_u *CustomerUpdate) RemoveEntitlementIDs(ids ...string) *CustomerUpdate { + _u.mutation.RemoveEntitlementIDs(ids...) + return _u +} + +// RemoveEntitlements removes "entitlements" edges to Entitlement entities. +func (_u *CustomerUpdate) RemoveEntitlements(v ...*Entitlement) *CustomerUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveEntitlementIDs(ids...) +} + +// ClearChargesCreditPurchase clears all "charges_credit_purchase" edges to the ChargeCreditPurchase entity. +func (_u *CustomerUpdate) ClearChargesCreditPurchase() *CustomerUpdate { + _u.mutation.ClearChargesCreditPurchase() + return _u +} + +// RemoveChargesCreditPurchaseIDs removes the "charges_credit_purchase" edge to ChargeCreditPurchase entities by IDs. +func (_u *CustomerUpdate) RemoveChargesCreditPurchaseIDs(ids ...string) *CustomerUpdate { + _u.mutation.RemoveChargesCreditPurchaseIDs(ids...) + return _u +} + +// RemoveChargesCreditPurchase removes "charges_credit_purchase" edges to ChargeCreditPurchase entities. +func (_u *CustomerUpdate) RemoveChargesCreditPurchase(v ...*ChargeCreditPurchase) *CustomerUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveChargesCreditPurchaseIDs(ids...) +} + +// ClearChargesFlatFee clears all "charges_flat_fee" edges to the ChargeFlatFee entity. +func (_u *CustomerUpdate) ClearChargesFlatFee() *CustomerUpdate { + _u.mutation.ClearChargesFlatFee() + return _u +} + +// RemoveChargesFlatFeeIDs removes the "charges_flat_fee" edge to ChargeFlatFee entities by IDs. +func (_u *CustomerUpdate) RemoveChargesFlatFeeIDs(ids ...string) *CustomerUpdate { + _u.mutation.RemoveChargesFlatFeeIDs(ids...) + return _u +} + +// RemoveChargesFlatFee removes "charges_flat_fee" edges to ChargeFlatFee entities. +func (_u *CustomerUpdate) RemoveChargesFlatFee(v ...*ChargeFlatFee) *CustomerUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveChargesFlatFeeIDs(ids...) +} + +// ClearChargesUsageBased clears all "charges_usage_based" edges to the ChargeUsageBased entity. +func (_u *CustomerUpdate) ClearChargesUsageBased() *CustomerUpdate { + _u.mutation.ClearChargesUsageBased() + return _u +} + +// RemoveChargesUsageBasedIDs removes the "charges_usage_based" edge to ChargeUsageBased entities by IDs. +func (_u *CustomerUpdate) RemoveChargesUsageBasedIDs(ids ...string) *CustomerUpdate { + _u.mutation.RemoveChargesUsageBasedIDs(ids...) + return _u +} + +// RemoveChargesUsageBased removes "charges_usage_based" edges to ChargeUsageBased entities. +func (_u *CustomerUpdate) RemoveChargesUsageBased(v ...*ChargeUsageBased) *CustomerUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveChargesUsageBasedIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *CustomerUpdate) 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 *CustomerUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *CustomerUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *CustomerUpdate) 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 *CustomerUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := customer.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *CustomerUpdate) check() error { + if v, ok := _u.mutation.BillingAddressCountry(); ok { + if err := customer.BillingAddressCountryValidator(string(v)); err != nil { + return &ValidationError{Name: "billing_address_country", err: fmt.Errorf(`db: validator failed for field "Customer.billing_address_country": %w`, err)} + } + } + if v, ok := _u.mutation.Currency(); ok { + if err := customer.CurrencyValidator(string(v)); err != nil { + return &ValidationError{Name: "currency", err: fmt.Errorf(`db: validator failed for field "Customer.currency": %w`, err)} + } + } + return nil +} + +func (_u *CustomerUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(customer.Table, customer.Columns, sqlgraph.NewFieldSpec(customer.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.Metadata(); ok { + _spec.SetField(customer.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(customer.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(customer.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(customer.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(customer.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(customer.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(customer.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(customer.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.BillingAddressCountry(); ok { + _spec.SetField(customer.FieldBillingAddressCountry, field.TypeString, value) + } + if _u.mutation.BillingAddressCountryCleared() { + _spec.ClearField(customer.FieldBillingAddressCountry, field.TypeString) + } + if value, ok := _u.mutation.BillingAddressPostalCode(); ok { + _spec.SetField(customer.FieldBillingAddressPostalCode, field.TypeString, value) + } + if _u.mutation.BillingAddressPostalCodeCleared() { + _spec.ClearField(customer.FieldBillingAddressPostalCode, field.TypeString) + } + if value, ok := _u.mutation.BillingAddressState(); ok { + _spec.SetField(customer.FieldBillingAddressState, field.TypeString, value) + } + if _u.mutation.BillingAddressStateCleared() { + _spec.ClearField(customer.FieldBillingAddressState, field.TypeString) + } + if value, ok := _u.mutation.BillingAddressCity(); ok { + _spec.SetField(customer.FieldBillingAddressCity, field.TypeString, value) + } + if _u.mutation.BillingAddressCityCleared() { + _spec.ClearField(customer.FieldBillingAddressCity, field.TypeString) + } + if value, ok := _u.mutation.BillingAddressLine1(); ok { + _spec.SetField(customer.FieldBillingAddressLine1, field.TypeString, value) + } + if _u.mutation.BillingAddressLine1Cleared() { + _spec.ClearField(customer.FieldBillingAddressLine1, field.TypeString) + } + if value, ok := _u.mutation.BillingAddressLine2(); ok { + _spec.SetField(customer.FieldBillingAddressLine2, field.TypeString, value) + } + if _u.mutation.BillingAddressLine2Cleared() { + _spec.ClearField(customer.FieldBillingAddressLine2, field.TypeString) + } + if value, ok := _u.mutation.BillingAddressPhoneNumber(); ok { + _spec.SetField(customer.FieldBillingAddressPhoneNumber, field.TypeString, value) + } + if _u.mutation.BillingAddressPhoneNumberCleared() { + _spec.ClearField(customer.FieldBillingAddressPhoneNumber, field.TypeString) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(customer.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(customer.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Key(); ok { + _spec.SetField(customer.FieldKey, field.TypeString, value) + } + if _u.mutation.KeyCleared() { + _spec.ClearField(customer.FieldKey, field.TypeString) + } + if value, ok := _u.mutation.PrimaryEmail(); ok { + _spec.SetField(customer.FieldPrimaryEmail, field.TypeString, value) + } + if _u.mutation.PrimaryEmailCleared() { + _spec.ClearField(customer.FieldPrimaryEmail, field.TypeString) + } + if value, ok := _u.mutation.Currency(); ok { + _spec.SetField(customer.FieldCurrency, field.TypeString, value) + } + if _u.mutation.CurrencyCleared() { + _spec.ClearField(customer.FieldCurrency, field.TypeString) + } + if _u.mutation.AppsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.AppsTable, + Columns: []string{customer.AppsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(appcustomer.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedAppsIDs(); len(nodes) > 0 && !_u.mutation.AppsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.AppsTable, + Columns: []string{customer.AppsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(appcustomer.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.AppsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.AppsTable, + Columns: []string{customer.AppsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(appcustomer.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.SubjectsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.SubjectsTable, + Columns: []string{customer.SubjectsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(customersubjects.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSubjectsIDs(); len(nodes) > 0 && !_u.mutation.SubjectsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.SubjectsTable, + Columns: []string{customer.SubjectsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(customersubjects.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.SubjectsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.SubjectsTable, + Columns: []string{customer.SubjectsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(customersubjects.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.BillingCustomerOverrideCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: customer.BillingCustomerOverrideTable, + Columns: []string{customer.BillingCustomerOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingcustomeroverride.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingCustomerOverrideIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: customer.BillingCustomerOverrideTable, + Columns: []string{customer.BillingCustomerOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingcustomeroverride.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.BillingInvoiceCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.BillingInvoiceTable, + Columns: []string{customer.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedBillingInvoiceIDs(); len(nodes) > 0 && !_u.mutation.BillingInvoiceCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.BillingInvoiceTable, + Columns: []string{customer.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.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.BillingInvoiceIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.BillingInvoiceTable, + Columns: []string{customer.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.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.SubscriptionCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.SubscriptionTable, + Columns: []string{customer.SubscriptionColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscription.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSubscriptionIDs(); len(nodes) > 0 && !_u.mutation.SubscriptionCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.SubscriptionTable, + Columns: []string{customer.SubscriptionColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscription.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.SubscriptionIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.SubscriptionTable, + Columns: []string{customer.SubscriptionColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscription.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.EntitlementsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.EntitlementsTable, + Columns: []string{customer.EntitlementsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(entitlement.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedEntitlementsIDs(); len(nodes) > 0 && !_u.mutation.EntitlementsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.EntitlementsTable, + Columns: []string{customer.EntitlementsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(entitlement.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.EntitlementsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.EntitlementsTable, + Columns: []string{customer.EntitlementsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(entitlement.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.ChargesCreditPurchaseCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesCreditPurchaseTable, + Columns: []string{customer.ChargesCreditPurchaseColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchase.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedChargesCreditPurchaseIDs(); len(nodes) > 0 && !_u.mutation.ChargesCreditPurchaseCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesCreditPurchaseTable, + Columns: []string{customer.ChargesCreditPurchaseColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchase.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.ChargesCreditPurchaseIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesCreditPurchaseTable, + Columns: []string{customer.ChargesCreditPurchaseColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchase.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.ChargesFlatFeeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesFlatFeeTable, + Columns: []string{customer.ChargesFlatFeeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfee.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedChargesFlatFeeIDs(); len(nodes) > 0 && !_u.mutation.ChargesFlatFeeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesFlatFeeTable, + Columns: []string{customer.ChargesFlatFeeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfee.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.ChargesFlatFeeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesFlatFeeTable, + Columns: []string{customer.ChargesFlatFeeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfee.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.ChargesUsageBasedCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesUsageBasedTable, + Columns: []string{customer.ChargesUsageBasedColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebased.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedChargesUsageBasedIDs(); len(nodes) > 0 && !_u.mutation.ChargesUsageBasedCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesUsageBasedTable, + Columns: []string{customer.ChargesUsageBasedColumn}, + 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.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ChargesUsageBasedIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesUsageBasedTable, + Columns: []string{customer.ChargesUsageBasedColumn}, + 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 _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{customer.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// CustomerUpdateOne is the builder for updating a single Customer entity. +type CustomerUpdateOne struct { + config + fields []string + hooks []Hook + mutation *CustomerMutation +} + +// SetMetadata sets the "metadata" field. +func (_u *CustomerUpdateOne) SetMetadata(v map[string]string) *CustomerUpdateOne { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *CustomerUpdateOne) ClearMetadata() *CustomerUpdateOne { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *CustomerUpdateOne) SetUpdatedAt(v time.Time) *CustomerUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *CustomerUpdateOne) SetDeletedAt(v time.Time) *CustomerUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *CustomerUpdateOne) SetNillableDeletedAt(v *time.Time) *CustomerUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *CustomerUpdateOne) ClearDeletedAt() *CustomerUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *CustomerUpdateOne) SetName(v string) *CustomerUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *CustomerUpdateOne) SetNillableName(v *string) *CustomerUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *CustomerUpdateOne) SetDescription(v string) *CustomerUpdateOne { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *CustomerUpdateOne) SetNillableDescription(v *string) *CustomerUpdateOne { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *CustomerUpdateOne) ClearDescription() *CustomerUpdateOne { + _u.mutation.ClearDescription() + return _u +} + +// SetBillingAddressCountry sets the "billing_address_country" field. +func (_u *CustomerUpdateOne) SetBillingAddressCountry(v models.CountryCode) *CustomerUpdateOne { + _u.mutation.SetBillingAddressCountry(v) + return _u +} + +// SetNillableBillingAddressCountry sets the "billing_address_country" field if the given value is not nil. +func (_u *CustomerUpdateOne) SetNillableBillingAddressCountry(v *models.CountryCode) *CustomerUpdateOne { + if v != nil { + _u.SetBillingAddressCountry(*v) + } + return _u +} + +// ClearBillingAddressCountry clears the value of the "billing_address_country" field. +func (_u *CustomerUpdateOne) ClearBillingAddressCountry() *CustomerUpdateOne { + _u.mutation.ClearBillingAddressCountry() + return _u +} + +// SetBillingAddressPostalCode sets the "billing_address_postal_code" field. +func (_u *CustomerUpdateOne) SetBillingAddressPostalCode(v string) *CustomerUpdateOne { + _u.mutation.SetBillingAddressPostalCode(v) + return _u +} + +// SetNillableBillingAddressPostalCode sets the "billing_address_postal_code" field if the given value is not nil. +func (_u *CustomerUpdateOne) SetNillableBillingAddressPostalCode(v *string) *CustomerUpdateOne { + if v != nil { + _u.SetBillingAddressPostalCode(*v) + } + return _u +} + +// ClearBillingAddressPostalCode clears the value of the "billing_address_postal_code" field. +func (_u *CustomerUpdateOne) ClearBillingAddressPostalCode() *CustomerUpdateOne { + _u.mutation.ClearBillingAddressPostalCode() + return _u +} + +// SetBillingAddressState sets the "billing_address_state" field. +func (_u *CustomerUpdateOne) SetBillingAddressState(v string) *CustomerUpdateOne { + _u.mutation.SetBillingAddressState(v) + return _u +} + +// SetNillableBillingAddressState sets the "billing_address_state" field if the given value is not nil. +func (_u *CustomerUpdateOne) SetNillableBillingAddressState(v *string) *CustomerUpdateOne { + if v != nil { + _u.SetBillingAddressState(*v) + } + return _u +} + +// ClearBillingAddressState clears the value of the "billing_address_state" field. +func (_u *CustomerUpdateOne) ClearBillingAddressState() *CustomerUpdateOne { + _u.mutation.ClearBillingAddressState() + return _u +} + +// SetBillingAddressCity sets the "billing_address_city" field. +func (_u *CustomerUpdateOne) SetBillingAddressCity(v string) *CustomerUpdateOne { + _u.mutation.SetBillingAddressCity(v) + return _u +} + +// SetNillableBillingAddressCity sets the "billing_address_city" field if the given value is not nil. +func (_u *CustomerUpdateOne) SetNillableBillingAddressCity(v *string) *CustomerUpdateOne { + if v != nil { + _u.SetBillingAddressCity(*v) + } + return _u +} + +// ClearBillingAddressCity clears the value of the "billing_address_city" field. +func (_u *CustomerUpdateOne) ClearBillingAddressCity() *CustomerUpdateOne { + _u.mutation.ClearBillingAddressCity() + return _u +} + +// SetBillingAddressLine1 sets the "billing_address_line1" field. +func (_u *CustomerUpdateOne) SetBillingAddressLine1(v string) *CustomerUpdateOne { + _u.mutation.SetBillingAddressLine1(v) + return _u +} + +// SetNillableBillingAddressLine1 sets the "billing_address_line1" field if the given value is not nil. +func (_u *CustomerUpdateOne) SetNillableBillingAddressLine1(v *string) *CustomerUpdateOne { + if v != nil { + _u.SetBillingAddressLine1(*v) + } + return _u +} + +// ClearBillingAddressLine1 clears the value of the "billing_address_line1" field. +func (_u *CustomerUpdateOne) ClearBillingAddressLine1() *CustomerUpdateOne { + _u.mutation.ClearBillingAddressLine1() + return _u +} + +// SetBillingAddressLine2 sets the "billing_address_line2" field. +func (_u *CustomerUpdateOne) SetBillingAddressLine2(v string) *CustomerUpdateOne { + _u.mutation.SetBillingAddressLine2(v) + return _u +} + +// SetNillableBillingAddressLine2 sets the "billing_address_line2" field if the given value is not nil. +func (_u *CustomerUpdateOne) SetNillableBillingAddressLine2(v *string) *CustomerUpdateOne { + if v != nil { + _u.SetBillingAddressLine2(*v) + } + return _u +} + +// ClearBillingAddressLine2 clears the value of the "billing_address_line2" field. +func (_u *CustomerUpdateOne) ClearBillingAddressLine2() *CustomerUpdateOne { + _u.mutation.ClearBillingAddressLine2() + return _u +} + +// SetBillingAddressPhoneNumber sets the "billing_address_phone_number" field. +func (_u *CustomerUpdateOne) SetBillingAddressPhoneNumber(v string) *CustomerUpdateOne { + _u.mutation.SetBillingAddressPhoneNumber(v) + return _u +} + +// SetNillableBillingAddressPhoneNumber sets the "billing_address_phone_number" field if the given value is not nil. +func (_u *CustomerUpdateOne) SetNillableBillingAddressPhoneNumber(v *string) *CustomerUpdateOne { + if v != nil { + _u.SetBillingAddressPhoneNumber(*v) + } + return _u +} + +// ClearBillingAddressPhoneNumber clears the value of the "billing_address_phone_number" field. +func (_u *CustomerUpdateOne) ClearBillingAddressPhoneNumber() *CustomerUpdateOne { + _u.mutation.ClearBillingAddressPhoneNumber() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *CustomerUpdateOne) SetAnnotations(v models.Annotations) *CustomerUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *CustomerUpdateOne) ClearAnnotations() *CustomerUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetKey sets the "key" field. +func (_u *CustomerUpdateOne) SetKey(v string) *CustomerUpdateOne { + _u.mutation.SetKey(v) + return _u +} + +// SetNillableKey sets the "key" field if the given value is not nil. +func (_u *CustomerUpdateOne) SetNillableKey(v *string) *CustomerUpdateOne { + if v != nil { + _u.SetKey(*v) + } + return _u +} + +// ClearKey clears the value of the "key" field. +func (_u *CustomerUpdateOne) ClearKey() *CustomerUpdateOne { + _u.mutation.ClearKey() + return _u +} + +// SetPrimaryEmail sets the "primary_email" field. +func (_u *CustomerUpdateOne) SetPrimaryEmail(v string) *CustomerUpdateOne { + _u.mutation.SetPrimaryEmail(v) + return _u +} + +// SetNillablePrimaryEmail sets the "primary_email" field if the given value is not nil. +func (_u *CustomerUpdateOne) SetNillablePrimaryEmail(v *string) *CustomerUpdateOne { + if v != nil { + _u.SetPrimaryEmail(*v) + } + return _u +} + +// ClearPrimaryEmail clears the value of the "primary_email" field. +func (_u *CustomerUpdateOne) ClearPrimaryEmail() *CustomerUpdateOne { + _u.mutation.ClearPrimaryEmail() + return _u +} + +// SetCurrency sets the "currency" field. +func (_u *CustomerUpdateOne) SetCurrency(v currencyx.Code) *CustomerUpdateOne { + _u.mutation.SetCurrency(v) + return _u +} + +// SetNillableCurrency sets the "currency" field if the given value is not nil. +func (_u *CustomerUpdateOne) SetNillableCurrency(v *currencyx.Code) *CustomerUpdateOne { + if v != nil { + _u.SetCurrency(*v) + } + return _u +} + +// ClearCurrency clears the value of the "currency" field. +func (_u *CustomerUpdateOne) ClearCurrency() *CustomerUpdateOne { + _u.mutation.ClearCurrency() + return _u +} + +// AddAppIDs adds the "apps" edge to the AppCustomer entity by IDs. +func (_u *CustomerUpdateOne) AddAppIDs(ids ...int) *CustomerUpdateOne { + _u.mutation.AddAppIDs(ids...) + return _u +} + +// AddApps adds the "apps" edges to the AppCustomer entity. +func (_u *CustomerUpdateOne) AddApps(v ...*AppCustomer) *CustomerUpdateOne { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddAppIDs(ids...) +} + +// AddSubjectIDs adds the "subjects" edge to the CustomerSubjects entity by IDs. +func (_u *CustomerUpdateOne) AddSubjectIDs(ids ...int) *CustomerUpdateOne { + _u.mutation.AddSubjectIDs(ids...) + return _u +} + +// AddSubjects adds the "subjects" edges to the CustomerSubjects entity. +func (_u *CustomerUpdateOne) AddSubjects(v ...*CustomerSubjects) *CustomerUpdateOne { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSubjectIDs(ids...) +} + +// SetBillingCustomerOverrideID sets the "billing_customer_override" edge to the BillingCustomerOverride entity by ID. +func (_u *CustomerUpdateOne) SetBillingCustomerOverrideID(id string) *CustomerUpdateOne { + _u.mutation.SetBillingCustomerOverrideID(id) + return _u +} + +// SetNillableBillingCustomerOverrideID sets the "billing_customer_override" edge to the BillingCustomerOverride entity by ID if the given value is not nil. +func (_u *CustomerUpdateOne) SetNillableBillingCustomerOverrideID(id *string) *CustomerUpdateOne { + if id != nil { + _u = _u.SetBillingCustomerOverrideID(*id) + } + return _u +} + +// SetBillingCustomerOverride sets the "billing_customer_override" edge to the BillingCustomerOverride entity. +func (_u *CustomerUpdateOne) SetBillingCustomerOverride(v *BillingCustomerOverride) *CustomerUpdateOne { + return _u.SetBillingCustomerOverrideID(v.ID) +} + +// AddBillingInvoiceIDs adds the "billing_invoice" edge to the BillingInvoice entity by IDs. +func (_u *CustomerUpdateOne) AddBillingInvoiceIDs(ids ...string) *CustomerUpdateOne { + _u.mutation.AddBillingInvoiceIDs(ids...) + return _u +} + +// AddBillingInvoice adds the "billing_invoice" edges to the BillingInvoice entity. +func (_u *CustomerUpdateOne) AddBillingInvoice(v ...*BillingInvoice) *CustomerUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddBillingInvoiceIDs(ids...) +} + +// AddSubscriptionIDs adds the "subscription" edge to the Subscription entity by IDs. +func (_u *CustomerUpdateOne) AddSubscriptionIDs(ids ...string) *CustomerUpdateOne { + _u.mutation.AddSubscriptionIDs(ids...) + return _u +} + +// AddSubscription adds the "subscription" edges to the Subscription entity. +func (_u *CustomerUpdateOne) AddSubscription(v ...*Subscription) *CustomerUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSubscriptionIDs(ids...) +} + +// AddEntitlementIDs adds the "entitlements" edge to the Entitlement entity by IDs. +func (_u *CustomerUpdateOne) AddEntitlementIDs(ids ...string) *CustomerUpdateOne { + _u.mutation.AddEntitlementIDs(ids...) + return _u +} + +// AddEntitlements adds the "entitlements" edges to the Entitlement entity. +func (_u *CustomerUpdateOne) AddEntitlements(v ...*Entitlement) *CustomerUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddEntitlementIDs(ids...) +} + +// AddChargesCreditPurchaseIDs adds the "charges_credit_purchase" edge to the ChargeCreditPurchase entity by IDs. +func (_u *CustomerUpdateOne) AddChargesCreditPurchaseIDs(ids ...string) *CustomerUpdateOne { + _u.mutation.AddChargesCreditPurchaseIDs(ids...) + return _u +} + +// AddChargesCreditPurchase adds the "charges_credit_purchase" edges to the ChargeCreditPurchase entity. +func (_u *CustomerUpdateOne) AddChargesCreditPurchase(v ...*ChargeCreditPurchase) *CustomerUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddChargesCreditPurchaseIDs(ids...) +} + +// AddChargesFlatFeeIDs adds the "charges_flat_fee" edge to the ChargeFlatFee entity by IDs. +func (_u *CustomerUpdateOne) AddChargesFlatFeeIDs(ids ...string) *CustomerUpdateOne { + _u.mutation.AddChargesFlatFeeIDs(ids...) + return _u +} + +// AddChargesFlatFee adds the "charges_flat_fee" edges to the ChargeFlatFee entity. +func (_u *CustomerUpdateOne) AddChargesFlatFee(v ...*ChargeFlatFee) *CustomerUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddChargesFlatFeeIDs(ids...) +} + +// AddChargesUsageBasedIDs adds the "charges_usage_based" edge to the ChargeUsageBased entity by IDs. +func (_u *CustomerUpdateOne) AddChargesUsageBasedIDs(ids ...string) *CustomerUpdateOne { + _u.mutation.AddChargesUsageBasedIDs(ids...) + return _u +} + +// AddChargesUsageBased adds the "charges_usage_based" edges to the ChargeUsageBased entity. +func (_u *CustomerUpdateOne) AddChargesUsageBased(v ...*ChargeUsageBased) *CustomerUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddChargesUsageBasedIDs(ids...) +} + +// Mutation returns the CustomerMutation object of the builder. +func (_u *CustomerUpdateOne) Mutation() *CustomerMutation { + return _u.mutation +} + +// ClearApps clears all "apps" edges to the AppCustomer entity. +func (_u *CustomerUpdateOne) ClearApps() *CustomerUpdateOne { + _u.mutation.ClearApps() + return _u +} + +// RemoveAppIDs removes the "apps" edge to AppCustomer entities by IDs. +func (_u *CustomerUpdateOne) RemoveAppIDs(ids ...int) *CustomerUpdateOne { + _u.mutation.RemoveAppIDs(ids...) + return _u +} + +// RemoveApps removes "apps" edges to AppCustomer entities. +func (_u *CustomerUpdateOne) RemoveApps(v ...*AppCustomer) *CustomerUpdateOne { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveAppIDs(ids...) +} + +// ClearSubjects clears all "subjects" edges to the CustomerSubjects entity. +func (_u *CustomerUpdateOne) ClearSubjects() *CustomerUpdateOne { + _u.mutation.ClearSubjects() + return _u +} + +// RemoveSubjectIDs removes the "subjects" edge to CustomerSubjects entities by IDs. +func (_u *CustomerUpdateOne) RemoveSubjectIDs(ids ...int) *CustomerUpdateOne { + _u.mutation.RemoveSubjectIDs(ids...) + return _u +} + +// RemoveSubjects removes "subjects" edges to CustomerSubjects entities. +func (_u *CustomerUpdateOne) RemoveSubjects(v ...*CustomerSubjects) *CustomerUpdateOne { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSubjectIDs(ids...) +} + +// ClearBillingCustomerOverride clears the "billing_customer_override" edge to the BillingCustomerOverride entity. +func (_u *CustomerUpdateOne) ClearBillingCustomerOverride() *CustomerUpdateOne { + _u.mutation.ClearBillingCustomerOverride() + return _u +} + +// ClearBillingInvoice clears all "billing_invoice" edges to the BillingInvoice entity. +func (_u *CustomerUpdateOne) ClearBillingInvoice() *CustomerUpdateOne { + _u.mutation.ClearBillingInvoice() + return _u +} + +// RemoveBillingInvoiceIDs removes the "billing_invoice" edge to BillingInvoice entities by IDs. +func (_u *CustomerUpdateOne) RemoveBillingInvoiceIDs(ids ...string) *CustomerUpdateOne { + _u.mutation.RemoveBillingInvoiceIDs(ids...) + return _u +} + +// RemoveBillingInvoice removes "billing_invoice" edges to BillingInvoice entities. +func (_u *CustomerUpdateOne) RemoveBillingInvoice(v ...*BillingInvoice) *CustomerUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveBillingInvoiceIDs(ids...) +} + +// ClearSubscription clears all "subscription" edges to the Subscription entity. +func (_u *CustomerUpdateOne) ClearSubscription() *CustomerUpdateOne { + _u.mutation.ClearSubscription() + return _u +} + +// RemoveSubscriptionIDs removes the "subscription" edge to Subscription entities by IDs. +func (_u *CustomerUpdateOne) RemoveSubscriptionIDs(ids ...string) *CustomerUpdateOne { + _u.mutation.RemoveSubscriptionIDs(ids...) + return _u +} + +// RemoveSubscription removes "subscription" edges to Subscription entities. +func (_u *CustomerUpdateOne) RemoveSubscription(v ...*Subscription) *CustomerUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSubscriptionIDs(ids...) +} + +// ClearEntitlements clears all "entitlements" edges to the Entitlement entity. +func (_u *CustomerUpdateOne) ClearEntitlements() *CustomerUpdateOne { + _u.mutation.ClearEntitlements() + return _u +} + +// RemoveEntitlementIDs removes the "entitlements" edge to Entitlement entities by IDs. +func (_u *CustomerUpdateOne) RemoveEntitlementIDs(ids ...string) *CustomerUpdateOne { + _u.mutation.RemoveEntitlementIDs(ids...) + return _u +} + +// RemoveEntitlements removes "entitlements" edges to Entitlement entities. +func (_u *CustomerUpdateOne) RemoveEntitlements(v ...*Entitlement) *CustomerUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveEntitlementIDs(ids...) +} + +// ClearChargesCreditPurchase clears all "charges_credit_purchase" edges to the ChargeCreditPurchase entity. +func (_u *CustomerUpdateOne) ClearChargesCreditPurchase() *CustomerUpdateOne { + _u.mutation.ClearChargesCreditPurchase() + return _u +} + +// RemoveChargesCreditPurchaseIDs removes the "charges_credit_purchase" edge to ChargeCreditPurchase entities by IDs. +func (_u *CustomerUpdateOne) RemoveChargesCreditPurchaseIDs(ids ...string) *CustomerUpdateOne { + _u.mutation.RemoveChargesCreditPurchaseIDs(ids...) + return _u +} + +// RemoveChargesCreditPurchase removes "charges_credit_purchase" edges to ChargeCreditPurchase entities. +func (_u *CustomerUpdateOne) RemoveChargesCreditPurchase(v ...*ChargeCreditPurchase) *CustomerUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveChargesCreditPurchaseIDs(ids...) +} + +// ClearChargesFlatFee clears all "charges_flat_fee" edges to the ChargeFlatFee entity. +func (_u *CustomerUpdateOne) ClearChargesFlatFee() *CustomerUpdateOne { + _u.mutation.ClearChargesFlatFee() + return _u +} + +// RemoveChargesFlatFeeIDs removes the "charges_flat_fee" edge to ChargeFlatFee entities by IDs. +func (_u *CustomerUpdateOne) RemoveChargesFlatFeeIDs(ids ...string) *CustomerUpdateOne { + _u.mutation.RemoveChargesFlatFeeIDs(ids...) + return _u +} + +// RemoveChargesFlatFee removes "charges_flat_fee" edges to ChargeFlatFee entities. +func (_u *CustomerUpdateOne) RemoveChargesFlatFee(v ...*ChargeFlatFee) *CustomerUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveChargesFlatFeeIDs(ids...) +} + +// ClearChargesUsageBased clears all "charges_usage_based" edges to the ChargeUsageBased entity. +func (_u *CustomerUpdateOne) ClearChargesUsageBased() *CustomerUpdateOne { + _u.mutation.ClearChargesUsageBased() + return _u +} + +// RemoveChargesUsageBasedIDs removes the "charges_usage_based" edge to ChargeUsageBased entities by IDs. +func (_u *CustomerUpdateOne) RemoveChargesUsageBasedIDs(ids ...string) *CustomerUpdateOne { + _u.mutation.RemoveChargesUsageBasedIDs(ids...) + return _u +} + +// RemoveChargesUsageBased removes "charges_usage_based" edges to ChargeUsageBased entities. +func (_u *CustomerUpdateOne) RemoveChargesUsageBased(v ...*ChargeUsageBased) *CustomerUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveChargesUsageBasedIDs(ids...) +} + +// Where appends a list predicates to the CustomerUpdate builder. +func (_u *CustomerUpdateOne) Where(ps ...predicate.Customer) *CustomerUpdateOne { + _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 *CustomerUpdateOne) Select(field string, fields ...string) *CustomerUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Customer entity. +func (_u *CustomerUpdateOne) Save(ctx context.Context) (*Customer, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *CustomerUpdateOne) SaveX(ctx context.Context) *Customer { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *CustomerUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *CustomerUpdateOne) 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 *CustomerUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := customer.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *CustomerUpdateOne) check() error { + if v, ok := _u.mutation.BillingAddressCountry(); ok { + if err := customer.BillingAddressCountryValidator(string(v)); err != nil { + return &ValidationError{Name: "billing_address_country", err: fmt.Errorf(`db: validator failed for field "Customer.billing_address_country": %w`, err)} + } + } + if v, ok := _u.mutation.Currency(); ok { + if err := customer.CurrencyValidator(string(v)); err != nil { + return &ValidationError{Name: "currency", err: fmt.Errorf(`db: validator failed for field "Customer.currency": %w`, err)} + } + } + return nil +} + +func (_u *CustomerUpdateOne) sqlSave(ctx context.Context) (_node *Customer, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(customer.Table, customer.Columns, sqlgraph.NewFieldSpec(customer.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "Customer.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, customer.FieldID) + for _, f := range fields { + if !customer.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != customer.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.Metadata(); ok { + _spec.SetField(customer.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(customer.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(customer.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(customer.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(customer.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(customer.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(customer.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(customer.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.BillingAddressCountry(); ok { + _spec.SetField(customer.FieldBillingAddressCountry, field.TypeString, value) + } + if _u.mutation.BillingAddressCountryCleared() { + _spec.ClearField(customer.FieldBillingAddressCountry, field.TypeString) + } + if value, ok := _u.mutation.BillingAddressPostalCode(); ok { + _spec.SetField(customer.FieldBillingAddressPostalCode, field.TypeString, value) + } + if _u.mutation.BillingAddressPostalCodeCleared() { + _spec.ClearField(customer.FieldBillingAddressPostalCode, field.TypeString) + } + if value, ok := _u.mutation.BillingAddressState(); ok { + _spec.SetField(customer.FieldBillingAddressState, field.TypeString, value) + } + if _u.mutation.BillingAddressStateCleared() { + _spec.ClearField(customer.FieldBillingAddressState, field.TypeString) + } + if value, ok := _u.mutation.BillingAddressCity(); ok { + _spec.SetField(customer.FieldBillingAddressCity, field.TypeString, value) + } + if _u.mutation.BillingAddressCityCleared() { + _spec.ClearField(customer.FieldBillingAddressCity, field.TypeString) + } + if value, ok := _u.mutation.BillingAddressLine1(); ok { + _spec.SetField(customer.FieldBillingAddressLine1, field.TypeString, value) + } + if _u.mutation.BillingAddressLine1Cleared() { + _spec.ClearField(customer.FieldBillingAddressLine1, field.TypeString) + } + if value, ok := _u.mutation.BillingAddressLine2(); ok { + _spec.SetField(customer.FieldBillingAddressLine2, field.TypeString, value) + } + if _u.mutation.BillingAddressLine2Cleared() { + _spec.ClearField(customer.FieldBillingAddressLine2, field.TypeString) + } + if value, ok := _u.mutation.BillingAddressPhoneNumber(); ok { + _spec.SetField(customer.FieldBillingAddressPhoneNumber, field.TypeString, value) + } + if _u.mutation.BillingAddressPhoneNumberCleared() { + _spec.ClearField(customer.FieldBillingAddressPhoneNumber, field.TypeString) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(customer.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(customer.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Key(); ok { + _spec.SetField(customer.FieldKey, field.TypeString, value) + } + if _u.mutation.KeyCleared() { + _spec.ClearField(customer.FieldKey, field.TypeString) + } + if value, ok := _u.mutation.PrimaryEmail(); ok { + _spec.SetField(customer.FieldPrimaryEmail, field.TypeString, value) + } + if _u.mutation.PrimaryEmailCleared() { + _spec.ClearField(customer.FieldPrimaryEmail, field.TypeString) + } + if value, ok := _u.mutation.Currency(); ok { + _spec.SetField(customer.FieldCurrency, field.TypeString, value) + } + if _u.mutation.CurrencyCleared() { + _spec.ClearField(customer.FieldCurrency, field.TypeString) + } + if _u.mutation.AppsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.AppsTable, + Columns: []string{customer.AppsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(appcustomer.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedAppsIDs(); len(nodes) > 0 && !_u.mutation.AppsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.AppsTable, + Columns: []string{customer.AppsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(appcustomer.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.AppsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.AppsTable, + Columns: []string{customer.AppsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(appcustomer.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.SubjectsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.SubjectsTable, + Columns: []string{customer.SubjectsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(customersubjects.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSubjectsIDs(); len(nodes) > 0 && !_u.mutation.SubjectsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.SubjectsTable, + Columns: []string{customer.SubjectsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(customersubjects.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.SubjectsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.SubjectsTable, + Columns: []string{customer.SubjectsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(customersubjects.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.BillingCustomerOverrideCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: customer.BillingCustomerOverrideTable, + Columns: []string{customer.BillingCustomerOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingcustomeroverride.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BillingCustomerOverrideIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: customer.BillingCustomerOverrideTable, + Columns: []string{customer.BillingCustomerOverrideColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billingcustomeroverride.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.BillingInvoiceCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.BillingInvoiceTable, + Columns: []string{customer.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedBillingInvoiceIDs(); len(nodes) > 0 && !_u.mutation.BillingInvoiceCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.BillingInvoiceTable, + Columns: []string{customer.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.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.BillingInvoiceIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.BillingInvoiceTable, + Columns: []string{customer.BillingInvoiceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(billinginvoice.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.SubscriptionCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.SubscriptionTable, + Columns: []string{customer.SubscriptionColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscription.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSubscriptionIDs(); len(nodes) > 0 && !_u.mutation.SubscriptionCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.SubscriptionTable, + Columns: []string{customer.SubscriptionColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscription.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.SubscriptionIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.SubscriptionTable, + Columns: []string{customer.SubscriptionColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscription.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.EntitlementsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.EntitlementsTable, + Columns: []string{customer.EntitlementsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(entitlement.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedEntitlementsIDs(); len(nodes) > 0 && !_u.mutation.EntitlementsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.EntitlementsTable, + Columns: []string{customer.EntitlementsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(entitlement.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.EntitlementsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.EntitlementsTable, + Columns: []string{customer.EntitlementsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(entitlement.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.ChargesCreditPurchaseCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesCreditPurchaseTable, + Columns: []string{customer.ChargesCreditPurchaseColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchase.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedChargesCreditPurchaseIDs(); len(nodes) > 0 && !_u.mutation.ChargesCreditPurchaseCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesCreditPurchaseTable, + Columns: []string{customer.ChargesCreditPurchaseColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchase.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.ChargesCreditPurchaseIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesCreditPurchaseTable, + Columns: []string{customer.ChargesCreditPurchaseColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargecreditpurchase.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.ChargesFlatFeeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesFlatFeeTable, + Columns: []string{customer.ChargesFlatFeeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfee.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedChargesFlatFeeIDs(); len(nodes) > 0 && !_u.mutation.ChargesFlatFeeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesFlatFeeTable, + Columns: []string{customer.ChargesFlatFeeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfee.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.ChargesFlatFeeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesFlatFeeTable, + Columns: []string{customer.ChargesFlatFeeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfee.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.ChargesUsageBasedCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesUsageBasedTable, + Columns: []string{customer.ChargesUsageBasedColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebased.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedChargesUsageBasedIDs(); len(nodes) > 0 && !_u.mutation.ChargesUsageBasedCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesUsageBasedTable, + Columns: []string{customer.ChargesUsageBasedColumn}, + 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.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ChargesUsageBasedIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: customer.ChargesUsageBasedTable, + Columns: []string{customer.ChargesUsageBasedColumn}, + 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) + } + _node = &Customer{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{customer.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/ent/db/customersubjects.go b/ent/db/customersubjects.go new file mode 100644 index 0000000000000000000000000000000000000000..91545b00466ab55cb28e45c7297998f4b743ca9f --- /dev/null +++ b/ent/db/customersubjects.go @@ -0,0 +1,182 @@ +// 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/customer" + "github.com/openmeterio/openmeter/openmeter/ent/db/customersubjects" +) + +// CustomerSubjects is the model entity for the CustomerSubjects schema. +type CustomerSubjects struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Namespace holds the value of the "namespace" field. + Namespace string `json:"namespace,omitempty"` + // CustomerID holds the value of the "customer_id" field. + CustomerID string `json:"customer_id,omitempty"` + // SubjectKey holds the value of the "subject_key" field. + SubjectKey string `json:"subject_key,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // DeletedAt holds the value of the "deleted_at" field. + DeletedAt *time.Time `json:"deleted_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the CustomerSubjectsQuery when eager-loading is set. + Edges CustomerSubjectsEdges `json:"edges"` + selectValues sql.SelectValues +} + +// CustomerSubjectsEdges holds the relations/edges for other nodes in the graph. +type CustomerSubjectsEdges struct { + // Customer holds the value of the customer edge. + Customer *Customer `json:"customer,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// CustomerOrErr returns the Customer value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e CustomerSubjectsEdges) CustomerOrErr() (*Customer, error) { + if e.Customer != nil { + return e.Customer, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: customer.Label} + } + return nil, &NotLoadedError{edge: "customer"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*CustomerSubjects) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case customersubjects.FieldID: + values[i] = new(sql.NullInt64) + case customersubjects.FieldNamespace, customersubjects.FieldCustomerID, customersubjects.FieldSubjectKey: + values[i] = new(sql.NullString) + case customersubjects.FieldCreatedAt, customersubjects.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 CustomerSubjects fields. +func (_m *CustomerSubjects) 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 customersubjects.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int(value.Int64) + case customersubjects.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 customersubjects.FieldCustomerID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field customer_id", values[i]) + } else if value.Valid { + _m.CustomerID = value.String + } + case customersubjects.FieldSubjectKey: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field subject_key", values[i]) + } else if value.Valid { + _m.SubjectKey = value.String + } + case customersubjects.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 customersubjects.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 + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the CustomerSubjects. +// This includes values selected through modifiers, order, etc. +func (_m *CustomerSubjects) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryCustomer queries the "customer" edge of the CustomerSubjects entity. +func (_m *CustomerSubjects) QueryCustomer() *CustomerQuery { + return NewCustomerSubjectsClient(_m.config).QueryCustomer(_m) +} + +// Update returns a builder for updating this CustomerSubjects. +// Note that you need to call CustomerSubjects.Unwrap() before calling this method if this CustomerSubjects +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *CustomerSubjects) Update() *CustomerSubjectsUpdateOne { + return NewCustomerSubjectsClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the CustomerSubjects 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 *CustomerSubjects) Unwrap() *CustomerSubjects { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: CustomerSubjects is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *CustomerSubjects) String() string { + var builder strings.Builder + builder.WriteString("CustomerSubjects(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("customer_id=") + builder.WriteString(_m.CustomerID) + builder.WriteString(", ") + builder.WriteString("subject_key=") + builder.WriteString(_m.SubjectKey) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + if v := _m.DeletedAt; v != nil { + builder.WriteString("deleted_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteByte(')') + return builder.String() +} + +// CustomerSubjectsSlice is a parsable slice of CustomerSubjects. +type CustomerSubjectsSlice []*CustomerSubjects diff --git a/ent/db/customersubjects/customersubjects.go b/ent/db/customersubjects/customersubjects.go new file mode 100644 index 0000000000000000000000000000000000000000..9f292c2026f94f75fdd79b1638734d787b766613 --- /dev/null +++ b/ent/db/customersubjects/customersubjects.go @@ -0,0 +1,116 @@ +// Code generated by ent, DO NOT EDIT. + +package customersubjects + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the customersubjects type in the database. + Label = "customer_subjects" + // 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" + // FieldCustomerID holds the string denoting the customer_id field in the database. + FieldCustomerID = "customer_id" + // FieldSubjectKey holds the string denoting the subject_key field in the database. + FieldSubjectKey = "subject_key" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldDeletedAt holds the string denoting the deleted_at field in the database. + FieldDeletedAt = "deleted_at" + // EdgeCustomer holds the string denoting the customer edge name in mutations. + EdgeCustomer = "customer" + // Table holds the table name of the customersubjects in the database. + Table = "customer_subjects" + // CustomerTable is the table that holds the customer relation/edge. + CustomerTable = "customer_subjects" + // CustomerInverseTable is the table name for the Customer entity. + // It exists in this package in order to avoid circular dependency with the "customer" package. + CustomerInverseTable = "customers" + // CustomerColumn is the table column denoting the customer relation/edge. + CustomerColumn = "customer_id" +) + +// Columns holds all SQL columns for customersubjects fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldCustomerID, + FieldSubjectKey, + FieldCreatedAt, + FieldDeletedAt, +} + +// 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 + // CustomerIDValidator is a validator for the "customer_id" field. It is called by the builders before save. + CustomerIDValidator func(string) error + // SubjectKeyValidator is a validator for the "subject_key" field. It is called by the builders before save. + SubjectKeyValidator func(string) error + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time +) + +// OrderOption defines the ordering options for the CustomerSubjects 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() +} + +// ByCustomerID orders the results by the customer_id field. +func ByCustomerID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCustomerID, opts...).ToFunc() +} + +// BySubjectKey orders the results by the subject_key field. +func BySubjectKey(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSubjectKey, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByDeletedAt orders the results by the deleted_at field. +func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDeletedAt, opts...).ToFunc() +} + +// ByCustomerField orders the results by customer field. +func ByCustomerField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCustomerStep(), sql.OrderByField(field, opts...)) + } +} +func newCustomerStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CustomerInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, CustomerTable, CustomerColumn), + ) +} diff --git a/ent/db/customersubjects/where.go b/ent/db/customersubjects/where.go new file mode 100644 index 0000000000000000000000000000000000000000..e732e1def9097513c77c17e6076068d673d560f2 --- /dev/null +++ b/ent/db/customersubjects/where.go @@ -0,0 +1,404 @@ +// Code generated by ent, DO NOT EDIT. + +package customersubjects + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldLTE(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldEQ(FieldNamespace, v)) +} + +// CustomerID applies equality check predicate on the "customer_id" field. It's identical to CustomerIDEQ. +func CustomerID(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldEQ(FieldCustomerID, v)) +} + +// SubjectKey applies equality check predicate on the "subject_key" field. It's identical to SubjectKeyEQ. +func SubjectKey(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldEQ(FieldSubjectKey, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldEQ(FieldCreatedAt, v)) +} + +// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ. +func DeletedAt(v time.Time) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldEQ(FieldDeletedAt, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CustomerIDEQ applies the EQ predicate on the "customer_id" field. +func CustomerIDEQ(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldEQ(FieldCustomerID, v)) +} + +// CustomerIDNEQ applies the NEQ predicate on the "customer_id" field. +func CustomerIDNEQ(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldNEQ(FieldCustomerID, v)) +} + +// CustomerIDIn applies the In predicate on the "customer_id" field. +func CustomerIDIn(vs ...string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldIn(FieldCustomerID, vs...)) +} + +// CustomerIDNotIn applies the NotIn predicate on the "customer_id" field. +func CustomerIDNotIn(vs ...string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldNotIn(FieldCustomerID, vs...)) +} + +// CustomerIDGT applies the GT predicate on the "customer_id" field. +func CustomerIDGT(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldGT(FieldCustomerID, v)) +} + +// CustomerIDGTE applies the GTE predicate on the "customer_id" field. +func CustomerIDGTE(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldGTE(FieldCustomerID, v)) +} + +// CustomerIDLT applies the LT predicate on the "customer_id" field. +func CustomerIDLT(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldLT(FieldCustomerID, v)) +} + +// CustomerIDLTE applies the LTE predicate on the "customer_id" field. +func CustomerIDLTE(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldLTE(FieldCustomerID, v)) +} + +// CustomerIDContains applies the Contains predicate on the "customer_id" field. +func CustomerIDContains(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldContains(FieldCustomerID, v)) +} + +// CustomerIDHasPrefix applies the HasPrefix predicate on the "customer_id" field. +func CustomerIDHasPrefix(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldHasPrefix(FieldCustomerID, v)) +} + +// CustomerIDHasSuffix applies the HasSuffix predicate on the "customer_id" field. +func CustomerIDHasSuffix(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldHasSuffix(FieldCustomerID, v)) +} + +// CustomerIDEqualFold applies the EqualFold predicate on the "customer_id" field. +func CustomerIDEqualFold(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldEqualFold(FieldCustomerID, v)) +} + +// CustomerIDContainsFold applies the ContainsFold predicate on the "customer_id" field. +func CustomerIDContainsFold(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldContainsFold(FieldCustomerID, v)) +} + +// SubjectKeyEQ applies the EQ predicate on the "subject_key" field. +func SubjectKeyEQ(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldEQ(FieldSubjectKey, v)) +} + +// SubjectKeyNEQ applies the NEQ predicate on the "subject_key" field. +func SubjectKeyNEQ(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldNEQ(FieldSubjectKey, v)) +} + +// SubjectKeyIn applies the In predicate on the "subject_key" field. +func SubjectKeyIn(vs ...string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldIn(FieldSubjectKey, vs...)) +} + +// SubjectKeyNotIn applies the NotIn predicate on the "subject_key" field. +func SubjectKeyNotIn(vs ...string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldNotIn(FieldSubjectKey, vs...)) +} + +// SubjectKeyGT applies the GT predicate on the "subject_key" field. +func SubjectKeyGT(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldGT(FieldSubjectKey, v)) +} + +// SubjectKeyGTE applies the GTE predicate on the "subject_key" field. +func SubjectKeyGTE(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldGTE(FieldSubjectKey, v)) +} + +// SubjectKeyLT applies the LT predicate on the "subject_key" field. +func SubjectKeyLT(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldLT(FieldSubjectKey, v)) +} + +// SubjectKeyLTE applies the LTE predicate on the "subject_key" field. +func SubjectKeyLTE(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldLTE(FieldSubjectKey, v)) +} + +// SubjectKeyContains applies the Contains predicate on the "subject_key" field. +func SubjectKeyContains(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldContains(FieldSubjectKey, v)) +} + +// SubjectKeyHasPrefix applies the HasPrefix predicate on the "subject_key" field. +func SubjectKeyHasPrefix(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldHasPrefix(FieldSubjectKey, v)) +} + +// SubjectKeyHasSuffix applies the HasSuffix predicate on the "subject_key" field. +func SubjectKeyHasSuffix(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldHasSuffix(FieldSubjectKey, v)) +} + +// SubjectKeyEqualFold applies the EqualFold predicate on the "subject_key" field. +func SubjectKeyEqualFold(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldEqualFold(FieldSubjectKey, v)) +} + +// SubjectKeyContainsFold applies the ContainsFold predicate on the "subject_key" field. +func SubjectKeyContainsFold(v string) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldContainsFold(FieldSubjectKey, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldLTE(FieldCreatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.FieldNotNull(FieldDeletedAt)) +} + +// HasCustomer applies the HasEdge predicate on the "customer" edge. +func HasCustomer() predicate.CustomerSubjects { + return predicate.CustomerSubjects(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, CustomerTable, CustomerColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCustomerWith applies the HasEdge predicate on the "customer" edge with a given conditions (other predicates). +func HasCustomerWith(preds ...predicate.Customer) predicate.CustomerSubjects { + return predicate.CustomerSubjects(func(s *sql.Selector) { + step := newCustomerStep() + 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.CustomerSubjects) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.CustomerSubjects) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.CustomerSubjects) predicate.CustomerSubjects { + return predicate.CustomerSubjects(sql.NotPredicates(p)) +} diff --git a/ent/db/customersubjects_create.go b/ent/db/customersubjects_create.go new file mode 100644 index 0000000000000000000000000000000000000000..755e42e3c4a15480f327610d7fba62d9d921d5a1 --- /dev/null +++ b/ent/db/customersubjects_create.go @@ -0,0 +1,617 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/customer" + "github.com/openmeterio/openmeter/openmeter/ent/db/customersubjects" +) + +// CustomerSubjectsCreate is the builder for creating a CustomerSubjects entity. +type CustomerSubjectsCreate struct { + config + mutation *CustomerSubjectsMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *CustomerSubjectsCreate) SetNamespace(v string) *CustomerSubjectsCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCustomerID sets the "customer_id" field. +func (_c *CustomerSubjectsCreate) SetCustomerID(v string) *CustomerSubjectsCreate { + _c.mutation.SetCustomerID(v) + return _c +} + +// SetSubjectKey sets the "subject_key" field. +func (_c *CustomerSubjectsCreate) SetSubjectKey(v string) *CustomerSubjectsCreate { + _c.mutation.SetSubjectKey(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *CustomerSubjectsCreate) SetCreatedAt(v time.Time) *CustomerSubjectsCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *CustomerSubjectsCreate) SetNillableCreatedAt(v *time.Time) *CustomerSubjectsCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *CustomerSubjectsCreate) SetDeletedAt(v time.Time) *CustomerSubjectsCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *CustomerSubjectsCreate) SetNillableDeletedAt(v *time.Time) *CustomerSubjectsCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetCustomer sets the "customer" edge to the Customer entity. +func (_c *CustomerSubjectsCreate) SetCustomer(v *Customer) *CustomerSubjectsCreate { + return _c.SetCustomerID(v.ID) +} + +// Mutation returns the CustomerSubjectsMutation object of the builder. +func (_c *CustomerSubjectsCreate) Mutation() *CustomerSubjectsMutation { + return _c.mutation +} + +// Save creates the CustomerSubjects in the database. +func (_c *CustomerSubjectsCreate) Save(ctx context.Context) (*CustomerSubjects, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *CustomerSubjectsCreate) SaveX(ctx context.Context) *CustomerSubjects { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *CustomerSubjectsCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *CustomerSubjectsCreate) 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 *CustomerSubjectsCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := customersubjects.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *CustomerSubjectsCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "CustomerSubjects.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := customersubjects.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "CustomerSubjects.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CustomerID(); !ok { + return &ValidationError{Name: "customer_id", err: errors.New(`db: missing required field "CustomerSubjects.customer_id"`)} + } + if v, ok := _c.mutation.CustomerID(); ok { + if err := customersubjects.CustomerIDValidator(v); err != nil { + return &ValidationError{Name: "customer_id", err: fmt.Errorf(`db: validator failed for field "CustomerSubjects.customer_id": %w`, err)} + } + } + if _, ok := _c.mutation.SubjectKey(); !ok { + return &ValidationError{Name: "subject_key", err: errors.New(`db: missing required field "CustomerSubjects.subject_key"`)} + } + if v, ok := _c.mutation.SubjectKey(); ok { + if err := customersubjects.SubjectKeyValidator(v); err != nil { + return &ValidationError{Name: "subject_key", err: fmt.Errorf(`db: validator failed for field "CustomerSubjects.subject_key": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "CustomerSubjects.created_at"`)} + } + if len(_c.mutation.CustomerIDs()) == 0 { + return &ValidationError{Name: "customer", err: errors.New(`db: missing required edge "CustomerSubjects.customer"`)} + } + return nil +} + +func (_c *CustomerSubjectsCreate) sqlSave(ctx context.Context) (*CustomerSubjects, 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 + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *CustomerSubjectsCreate) createSpec() (*CustomerSubjects, *sqlgraph.CreateSpec) { + var ( + _node = &CustomerSubjects{config: _c.config} + _spec = sqlgraph.NewCreateSpec(customersubjects.Table, sqlgraph.NewFieldSpec(customersubjects.FieldID, field.TypeInt)) + ) + _spec.OnConflict = _c.conflict + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(customersubjects.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.SubjectKey(); ok { + _spec.SetField(customersubjects.FieldSubjectKey, field.TypeString, value) + _node.SubjectKey = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(customersubjects.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(customersubjects.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if nodes := _c.mutation.CustomerIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: customersubjects.CustomerTable, + Columns: []string{customersubjects.CustomerColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(customer.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.CustomerID = 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.CustomerSubjects.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.CustomerSubjectsUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *CustomerSubjectsCreate) OnConflict(opts ...sql.ConflictOption) *CustomerSubjectsUpsertOne { + _c.conflict = opts + return &CustomerSubjectsUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.CustomerSubjects.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *CustomerSubjectsCreate) OnConflictColumns(columns ...string) *CustomerSubjectsUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &CustomerSubjectsUpsertOne{ + create: _c, + } +} + +type ( + // CustomerSubjectsUpsertOne is the builder for "upsert"-ing + // one CustomerSubjects node. + CustomerSubjectsUpsertOne struct { + create *CustomerSubjectsCreate + } + + // CustomerSubjectsUpsert is the "OnConflict" setter. + CustomerSubjectsUpsert struct { + *sql.UpdateSet + } +) + +// SetDeletedAt sets the "deleted_at" field. +func (u *CustomerSubjectsUpsert) SetDeletedAt(v time.Time) *CustomerSubjectsUpsert { + u.Set(customersubjects.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *CustomerSubjectsUpsert) UpdateDeletedAt() *CustomerSubjectsUpsert { + u.SetExcluded(customersubjects.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *CustomerSubjectsUpsert) ClearDeletedAt() *CustomerSubjectsUpsert { + u.SetNull(customersubjects.FieldDeletedAt) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create. +// Using this option is equivalent to using: +// +// client.CustomerSubjects.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *CustomerSubjectsUpsertOne) UpdateNewValues() *CustomerSubjectsUpsertOne { + 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.Namespace(); exists { + s.SetIgnore(customersubjects.FieldNamespace) + } + if _, exists := u.create.mutation.CustomerID(); exists { + s.SetIgnore(customersubjects.FieldCustomerID) + } + if _, exists := u.create.mutation.SubjectKey(); exists { + s.SetIgnore(customersubjects.FieldSubjectKey) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(customersubjects.FieldCreatedAt) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.CustomerSubjects.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *CustomerSubjectsUpsertOne) Ignore() *CustomerSubjectsUpsertOne { + 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 *CustomerSubjectsUpsertOne) DoNothing() *CustomerSubjectsUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the CustomerSubjectsCreate.OnConflict +// documentation for more info. +func (u *CustomerSubjectsUpsertOne) Update(set func(*CustomerSubjectsUpsert)) *CustomerSubjectsUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&CustomerSubjectsUpsert{UpdateSet: update}) + })) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *CustomerSubjectsUpsertOne) SetDeletedAt(v time.Time) *CustomerSubjectsUpsertOne { + return u.Update(func(s *CustomerSubjectsUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *CustomerSubjectsUpsertOne) UpdateDeletedAt() *CustomerSubjectsUpsertOne { + return u.Update(func(s *CustomerSubjectsUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *CustomerSubjectsUpsertOne) ClearDeletedAt() *CustomerSubjectsUpsertOne { + return u.Update(func(s *CustomerSubjectsUpsert) { + s.ClearDeletedAt() + }) +} + +// Exec executes the query. +func (u *CustomerSubjectsUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for CustomerSubjectsCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *CustomerSubjectsUpsertOne) 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 *CustomerSubjectsUpsertOne) ID(ctx context.Context) (id int, err error) { + 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 *CustomerSubjectsUpsertOne) IDX(ctx context.Context) int { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// CustomerSubjectsCreateBulk is the builder for creating many CustomerSubjects entities in bulk. +type CustomerSubjectsCreateBulk struct { + config + err error + builders []*CustomerSubjectsCreate + conflict []sql.ConflictOption +} + +// Save creates the CustomerSubjects entities in the database. +func (_c *CustomerSubjectsCreateBulk) Save(ctx context.Context) ([]*CustomerSubjects, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*CustomerSubjects, 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.(*CustomerSubjectsMutation) + 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 + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + 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 *CustomerSubjectsCreateBulk) SaveX(ctx context.Context) []*CustomerSubjects { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *CustomerSubjectsCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *CustomerSubjectsCreateBulk) 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.CustomerSubjects.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.CustomerSubjectsUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *CustomerSubjectsCreateBulk) OnConflict(opts ...sql.ConflictOption) *CustomerSubjectsUpsertBulk { + _c.conflict = opts + return &CustomerSubjectsUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.CustomerSubjects.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *CustomerSubjectsCreateBulk) OnConflictColumns(columns ...string) *CustomerSubjectsUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &CustomerSubjectsUpsertBulk{ + create: _c, + } +} + +// CustomerSubjectsUpsertBulk is the builder for "upsert"-ing +// a bulk of CustomerSubjects nodes. +type CustomerSubjectsUpsertBulk struct { + create *CustomerSubjectsCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.CustomerSubjects.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *CustomerSubjectsUpsertBulk) UpdateNewValues() *CustomerSubjectsUpsertBulk { + 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.Namespace(); exists { + s.SetIgnore(customersubjects.FieldNamespace) + } + if _, exists := b.mutation.CustomerID(); exists { + s.SetIgnore(customersubjects.FieldCustomerID) + } + if _, exists := b.mutation.SubjectKey(); exists { + s.SetIgnore(customersubjects.FieldSubjectKey) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(customersubjects.FieldCreatedAt) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.CustomerSubjects.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *CustomerSubjectsUpsertBulk) Ignore() *CustomerSubjectsUpsertBulk { + 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 *CustomerSubjectsUpsertBulk) DoNothing() *CustomerSubjectsUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the CustomerSubjectsCreateBulk.OnConflict +// documentation for more info. +func (u *CustomerSubjectsUpsertBulk) Update(set func(*CustomerSubjectsUpsert)) *CustomerSubjectsUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&CustomerSubjectsUpsert{UpdateSet: update}) + })) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *CustomerSubjectsUpsertBulk) SetDeletedAt(v time.Time) *CustomerSubjectsUpsertBulk { + return u.Update(func(s *CustomerSubjectsUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *CustomerSubjectsUpsertBulk) UpdateDeletedAt() *CustomerSubjectsUpsertBulk { + return u.Update(func(s *CustomerSubjectsUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *CustomerSubjectsUpsertBulk) ClearDeletedAt() *CustomerSubjectsUpsertBulk { + return u.Update(func(s *CustomerSubjectsUpsert) { + s.ClearDeletedAt() + }) +} + +// Exec executes the query. +func (u *CustomerSubjectsUpsertBulk) 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 CustomerSubjectsCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for CustomerSubjectsCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *CustomerSubjectsUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/customersubjects_delete.go b/ent/db/customersubjects_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..9df440028ba2c501e3287aed513ce79761158abe --- /dev/null +++ b/ent/db/customersubjects_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/customersubjects" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// CustomerSubjectsDelete is the builder for deleting a CustomerSubjects entity. +type CustomerSubjectsDelete struct { + config + hooks []Hook + mutation *CustomerSubjectsMutation +} + +// Where appends a list predicates to the CustomerSubjectsDelete builder. +func (_d *CustomerSubjectsDelete) Where(ps ...predicate.CustomerSubjects) *CustomerSubjectsDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *CustomerSubjectsDelete) 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 *CustomerSubjectsDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *CustomerSubjectsDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(customersubjects.Table, sqlgraph.NewFieldSpec(customersubjects.FieldID, field.TypeInt)) + 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 +} + +// CustomerSubjectsDeleteOne is the builder for deleting a single CustomerSubjects entity. +type CustomerSubjectsDeleteOne struct { + _d *CustomerSubjectsDelete +} + +// Where appends a list predicates to the CustomerSubjectsDelete builder. +func (_d *CustomerSubjectsDeleteOne) Where(ps ...predicate.CustomerSubjects) *CustomerSubjectsDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *CustomerSubjectsDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{customersubjects.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *CustomerSubjectsDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/customersubjects_query.go b/ent/db/customersubjects_query.go new file mode 100644 index 0000000000000000000000000000000000000000..d9cc978695078c1e8171719b1ca569d787bc43f7 --- /dev/null +++ b/ent/db/customersubjects_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/customer" + "github.com/openmeterio/openmeter/openmeter/ent/db/customersubjects" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// CustomerSubjectsQuery is the builder for querying CustomerSubjects entities. +type CustomerSubjectsQuery struct { + config + ctx *QueryContext + order []customersubjects.OrderOption + inters []Interceptor + predicates []predicate.CustomerSubjects + withCustomer *CustomerQuery + 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 CustomerSubjectsQuery builder. +func (_q *CustomerSubjectsQuery) Where(ps ...predicate.CustomerSubjects) *CustomerSubjectsQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *CustomerSubjectsQuery) Limit(limit int) *CustomerSubjectsQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *CustomerSubjectsQuery) Offset(offset int) *CustomerSubjectsQuery { + _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 *CustomerSubjectsQuery) Unique(unique bool) *CustomerSubjectsQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *CustomerSubjectsQuery) Order(o ...customersubjects.OrderOption) *CustomerSubjectsQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryCustomer chains the current query on the "customer" edge. +func (_q *CustomerSubjectsQuery) QueryCustomer() *CustomerQuery { + query := (&CustomerClient{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(customersubjects.Table, customersubjects.FieldID, selector), + sqlgraph.To(customer.Table, customer.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, customersubjects.CustomerTable, customersubjects.CustomerColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first CustomerSubjects entity from the query. +// Returns a *NotFoundError when no CustomerSubjects was found. +func (_q *CustomerSubjectsQuery) First(ctx context.Context) (*CustomerSubjects, 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{customersubjects.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *CustomerSubjectsQuery) FirstX(ctx context.Context) *CustomerSubjects { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first CustomerSubjects ID from the query. +// Returns a *NotFoundError when no CustomerSubjects ID was found. +func (_q *CustomerSubjectsQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{customersubjects.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *CustomerSubjectsQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single CustomerSubjects entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one CustomerSubjects entity is found. +// Returns a *NotFoundError when no CustomerSubjects entities are found. +func (_q *CustomerSubjectsQuery) Only(ctx context.Context) (*CustomerSubjects, 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{customersubjects.Label} + default: + return nil, &NotSingularError{customersubjects.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *CustomerSubjectsQuery) OnlyX(ctx context.Context) *CustomerSubjects { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only CustomerSubjects ID in the query. +// Returns a *NotSingularError when more than one CustomerSubjects ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *CustomerSubjectsQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + 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{customersubjects.Label} + default: + err = &NotSingularError{customersubjects.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *CustomerSubjectsQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of CustomerSubjectsSlice. +func (_q *CustomerSubjectsQuery) All(ctx context.Context) ([]*CustomerSubjects, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*CustomerSubjects, *CustomerSubjectsQuery]() + return withInterceptors[[]*CustomerSubjects](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *CustomerSubjectsQuery) AllX(ctx context.Context) []*CustomerSubjects { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of CustomerSubjects IDs. +func (_q *CustomerSubjectsQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(customersubjects.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *CustomerSubjectsQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *CustomerSubjectsQuery) 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[*CustomerSubjectsQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *CustomerSubjectsQuery) 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 *CustomerSubjectsQuery) 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 *CustomerSubjectsQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the CustomerSubjectsQuery 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 *CustomerSubjectsQuery) Clone() *CustomerSubjectsQuery { + if _q == nil { + return nil + } + return &CustomerSubjectsQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]customersubjects.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.CustomerSubjects{}, _q.predicates...), + withCustomer: _q.withCustomer.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithCustomer tells the query-builder to eager-load the nodes that are connected to +// the "customer" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *CustomerSubjectsQuery) WithCustomer(opts ...func(*CustomerQuery)) *CustomerSubjectsQuery { + query := (&CustomerClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCustomer = 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.CustomerSubjects.Query(). +// GroupBy(customersubjects.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *CustomerSubjectsQuery) GroupBy(field string, fields ...string) *CustomerSubjectsGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &CustomerSubjectsGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = customersubjects.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.CustomerSubjects.Query(). +// Select(customersubjects.FieldNamespace). +// Scan(ctx, &v) +func (_q *CustomerSubjectsQuery) Select(fields ...string) *CustomerSubjectsSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &CustomerSubjectsSelect{CustomerSubjectsQuery: _q} + sbuild.label = customersubjects.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a CustomerSubjectsSelect configured with the given aggregations. +func (_q *CustomerSubjectsQuery) Aggregate(fns ...AggregateFunc) *CustomerSubjectsSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *CustomerSubjectsQuery) 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 !customersubjects.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 *CustomerSubjectsQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*CustomerSubjects, error) { + var ( + nodes = []*CustomerSubjects{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withCustomer != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*CustomerSubjects).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &CustomerSubjects{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.withCustomer; query != nil { + if err := _q.loadCustomer(ctx, query, nodes, nil, + func(n *CustomerSubjects, e *Customer) { n.Edges.Customer = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *CustomerSubjectsQuery) loadCustomer(ctx context.Context, query *CustomerQuery, nodes []*CustomerSubjects, init func(*CustomerSubjects), assign func(*CustomerSubjects, *Customer)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*CustomerSubjects) + for i := range nodes { + fk := nodes[i].CustomerID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(customer.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 "customer_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *CustomerSubjectsQuery) 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 *CustomerSubjectsQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(customersubjects.Table, customersubjects.Columns, sqlgraph.NewFieldSpec(customersubjects.FieldID, field.TypeInt)) + _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, customersubjects.FieldID) + for i := range fields { + if fields[i] != customersubjects.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withCustomer != nil { + _spec.Node.AddColumnOnce(customersubjects.FieldCustomerID) + } + } + 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 *CustomerSubjectsQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(customersubjects.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = customersubjects.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 *CustomerSubjectsQuery) ForUpdate(opts ...sql.LockOption) *CustomerSubjectsQuery { + 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 *CustomerSubjectsQuery) ForShare(opts ...sql.LockOption) *CustomerSubjectsQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// CustomerSubjectsGroupBy is the group-by builder for CustomerSubjects entities. +type CustomerSubjectsGroupBy struct { + selector + build *CustomerSubjectsQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *CustomerSubjectsGroupBy) Aggregate(fns ...AggregateFunc) *CustomerSubjectsGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *CustomerSubjectsGroupBy) 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[*CustomerSubjectsQuery, *CustomerSubjectsGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *CustomerSubjectsGroupBy) sqlScan(ctx context.Context, root *CustomerSubjectsQuery, 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) +} + +// CustomerSubjectsSelect is the builder for selecting fields of CustomerSubjects entities. +type CustomerSubjectsSelect struct { + *CustomerSubjectsQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *CustomerSubjectsSelect) Aggregate(fns ...AggregateFunc) *CustomerSubjectsSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *CustomerSubjectsSelect) 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[*CustomerSubjectsQuery, *CustomerSubjectsSelect](ctx, _s.CustomerSubjectsQuery, _s, _s.inters, v) +} + +func (_s *CustomerSubjectsSelect) sqlScan(ctx context.Context, root *CustomerSubjectsQuery, 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/ent/db/customersubjects_update.go b/ent/db/customersubjects_update.go new file mode 100644 index 0000000000000000000000000000000000000000..6251ee37dd975571c2093b9f541f37c1c23e2310 --- /dev/null +++ b/ent/db/customersubjects_update.go @@ -0,0 +1,250 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/customersubjects" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// CustomerSubjectsUpdate is the builder for updating CustomerSubjects entities. +type CustomerSubjectsUpdate struct { + config + hooks []Hook + mutation *CustomerSubjectsMutation +} + +// Where appends a list predicates to the CustomerSubjectsUpdate builder. +func (_u *CustomerSubjectsUpdate) Where(ps ...predicate.CustomerSubjects) *CustomerSubjectsUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *CustomerSubjectsUpdate) SetDeletedAt(v time.Time) *CustomerSubjectsUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *CustomerSubjectsUpdate) SetNillableDeletedAt(v *time.Time) *CustomerSubjectsUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *CustomerSubjectsUpdate) ClearDeletedAt() *CustomerSubjectsUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// Mutation returns the CustomerSubjectsMutation object of the builder. +func (_u *CustomerSubjectsUpdate) Mutation() *CustomerSubjectsMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *CustomerSubjectsUpdate) 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 *CustomerSubjectsUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *CustomerSubjectsUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *CustomerSubjectsUpdate) 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 *CustomerSubjectsUpdate) check() error { + if _u.mutation.CustomerCleared() && len(_u.mutation.CustomerIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "CustomerSubjects.customer"`) + } + return nil +} + +func (_u *CustomerSubjectsUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(customersubjects.Table, customersubjects.Columns, sqlgraph.NewFieldSpec(customersubjects.FieldID, field.TypeInt)) + 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.DeletedAt(); ok { + _spec.SetField(customersubjects.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(customersubjects.FieldDeletedAt, field.TypeTime) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{customersubjects.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// CustomerSubjectsUpdateOne is the builder for updating a single CustomerSubjects entity. +type CustomerSubjectsUpdateOne struct { + config + fields []string + hooks []Hook + mutation *CustomerSubjectsMutation +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *CustomerSubjectsUpdateOne) SetDeletedAt(v time.Time) *CustomerSubjectsUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *CustomerSubjectsUpdateOne) SetNillableDeletedAt(v *time.Time) *CustomerSubjectsUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *CustomerSubjectsUpdateOne) ClearDeletedAt() *CustomerSubjectsUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// Mutation returns the CustomerSubjectsMutation object of the builder. +func (_u *CustomerSubjectsUpdateOne) Mutation() *CustomerSubjectsMutation { + return _u.mutation +} + +// Where appends a list predicates to the CustomerSubjectsUpdate builder. +func (_u *CustomerSubjectsUpdateOne) Where(ps ...predicate.CustomerSubjects) *CustomerSubjectsUpdateOne { + _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 *CustomerSubjectsUpdateOne) Select(field string, fields ...string) *CustomerSubjectsUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated CustomerSubjects entity. +func (_u *CustomerSubjectsUpdateOne) Save(ctx context.Context) (*CustomerSubjects, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *CustomerSubjectsUpdateOne) SaveX(ctx context.Context) *CustomerSubjects { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *CustomerSubjectsUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *CustomerSubjectsUpdateOne) 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 *CustomerSubjectsUpdateOne) check() error { + if _u.mutation.CustomerCleared() && len(_u.mutation.CustomerIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "CustomerSubjects.customer"`) + } + return nil +} + +func (_u *CustomerSubjectsUpdateOne) sqlSave(ctx context.Context) (_node *CustomerSubjects, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(customersubjects.Table, customersubjects.Columns, sqlgraph.NewFieldSpec(customersubjects.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "CustomerSubjects.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, customersubjects.FieldID) + for _, f := range fields { + if !customersubjects.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != customersubjects.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.DeletedAt(); ok { + _spec.SetField(customersubjects.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(customersubjects.FieldDeletedAt, field.TypeTime) + } + _node = &CustomerSubjects{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{customersubjects.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/ent/db/ent.go b/ent/db/ent.go new file mode 100644 index 0000000000000000000000000000000000000000..43d484e43c9286a857b810b2ad465bda8332ea36 --- /dev/null +++ b/ent/db/ent.go @@ -0,0 +1,777 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "reflect" + "sync" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/ent/db/addon" + "github.com/openmeterio/openmeter/openmeter/ent/db/addonratecard" + + dbapp "github.com/openmeterio/openmeter/openmeter/ent/db/app" + "github.com/openmeterio/openmeter/openmeter/ent/db/appcustomer" + "github.com/openmeterio/openmeter/openmeter/ent/db/appcustominvoicing" + "github.com/openmeterio/openmeter/openmeter/ent/db/appcustominvoicingcustomer" + "github.com/openmeterio/openmeter/openmeter/ent/db/appstripe" + "github.com/openmeterio/openmeter/openmeter/ent/db/appstripecustomer" + "github.com/openmeterio/openmeter/openmeter/ent/db/balancesnapshot" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingcustomerlock" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingcustomeroverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceflatfeelineconfig" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicelinediscount" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicelineusagediscount" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicesplitlinegroup" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceusagebasedlineconfig" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicevalidationissue" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicewriteschemalevel" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingprofile" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingsequencenumbers" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingstandardinvoicedetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingstandardinvoicedetailedlineamountdiscount" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingworkflowconfig" + "github.com/openmeterio/openmeter/openmeter/ent/db/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchase" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchasecreditgrant" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchaseexternalpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchaseinvoicedpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeoverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerundetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargessearchv1" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedoverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrundetailedline" + "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/creditrealizationlineage" + "github.com/openmeterio/openmeter/openmeter/ent/db/creditrealizationlineagesegment" + "github.com/openmeterio/openmeter/openmeter/ent/db/currencycostbasis" + "github.com/openmeterio/openmeter/openmeter/ent/db/customcurrency" + "github.com/openmeterio/openmeter/openmeter/ent/db/customer" + "github.com/openmeterio/openmeter/openmeter/ent/db/customersubjects" + "github.com/openmeterio/openmeter/openmeter/ent/db/entitlement" + + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + + dbgrant "github.com/openmeterio/openmeter/openmeter/ent/db/grant" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgerbreakagerecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgercreditvoidrecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgercustomeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgerentry" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccountroute" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransaction" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransactiongroup" + "github.com/openmeterio/openmeter/openmeter/ent/db/llmcostprice" + + dbmeter "github.com/openmeterio/openmeter/openmeter/ent/db/meter" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationchannel" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationevent" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationeventdeliverystatus" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationrule" + "github.com/openmeterio/openmeter/openmeter/ent/db/organizationdefaulttaxcodes" + "github.com/openmeterio/openmeter/openmeter/ent/db/plan" + "github.com/openmeterio/openmeter/openmeter/ent/db/planaddon" + "github.com/openmeterio/openmeter/openmeter/ent/db/planphase" + "github.com/openmeterio/openmeter/openmeter/ent/db/planratecard" + "github.com/openmeterio/openmeter/openmeter/ent/db/subject" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionaddon" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionaddonquantity" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionbillingsyncstate" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionphase" + + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" + "github.com/openmeterio/openmeter/openmeter/ent/db/usagereset" +) + +// ent aliases to avoid import conflicts in user's code. +type ( + Op = ent.Op + Hook = ent.Hook + Value = ent.Value + Query = ent.Query + QueryContext = ent.QueryContext + Querier = ent.Querier + QuerierFunc = ent.QuerierFunc + Interceptor = ent.Interceptor + InterceptFunc = ent.InterceptFunc + Traverser = ent.Traverser + TraverseFunc = ent.TraverseFunc + Policy = ent.Policy + Mutator = ent.Mutator + Mutation = ent.Mutation + MutateFunc = ent.MutateFunc +) + +type clientCtxKey struct{} + +// FromContext returns a Client stored inside a context, or nil if there isn't one. +func FromContext(ctx context.Context) *Client { + c, _ := ctx.Value(clientCtxKey{}).(*Client) + return c +} + +// NewContext returns a new context with the given Client attached. +func NewContext(parent context.Context, c *Client) context.Context { + return context.WithValue(parent, clientCtxKey{}, c) +} + +type txCtxKey struct{} + +// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. +func TxFromContext(ctx context.Context) *Tx { + tx, _ := ctx.Value(txCtxKey{}).(*Tx) + return tx +} + +// NewTxContext returns a new context with the given Tx attached. +func NewTxContext(parent context.Context, tx *Tx) context.Context { + return context.WithValue(parent, txCtxKey{}, tx) +} + +// OrderFunc applies an ordering on the sql selector. +// Deprecated: Use Asc/Desc functions or the package builders instead. +type OrderFunc func(*sql.Selector) + +var ( + initCheck sync.Once + columnCheck sql.ColumnCheck +) + +// checkColumn checks if the column exists in the given table. +func checkColumn(t, c string) error { + initCheck.Do(func() { + columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ + addon.Table: addon.ValidColumn, + addonratecard.Table: addonratecard.ValidColumn, + dbapp.Table: dbapp.ValidColumn, + appcustominvoicing.Table: appcustominvoicing.ValidColumn, + appcustominvoicingcustomer.Table: appcustominvoicingcustomer.ValidColumn, + appcustomer.Table: appcustomer.ValidColumn, + appstripe.Table: appstripe.ValidColumn, + appstripecustomer.Table: appstripecustomer.ValidColumn, + balancesnapshot.Table: balancesnapshot.ValidColumn, + billingcustomerlock.Table: billingcustomerlock.ValidColumn, + billingcustomeroverride.Table: billingcustomeroverride.ValidColumn, + billinginvoice.Table: billinginvoice.ValidColumn, + billinginvoiceflatfeelineconfig.Table: billinginvoiceflatfeelineconfig.ValidColumn, + billinginvoiceline.Table: billinginvoiceline.ValidColumn, + billinginvoicelinediscount.Table: billinginvoicelinediscount.ValidColumn, + billinginvoicelineusagediscount.Table: billinginvoicelineusagediscount.ValidColumn, + billinginvoicesplitlinegroup.Table: billinginvoicesplitlinegroup.ValidColumn, + billinginvoiceusagebasedlineconfig.Table: billinginvoiceusagebasedlineconfig.ValidColumn, + billinginvoicevalidationissue.Table: billinginvoicevalidationissue.ValidColumn, + billinginvoicewriteschemalevel.Table: billinginvoicewriteschemalevel.ValidColumn, + billingprofile.Table: billingprofile.ValidColumn, + billingsequencenumbers.Table: billingsequencenumbers.ValidColumn, + billingstandardinvoicedetailedline.Table: billingstandardinvoicedetailedline.ValidColumn, + billingstandardinvoicedetailedlineamountdiscount.Table: billingstandardinvoicedetailedlineamountdiscount.ValidColumn, + billingworkflowconfig.Table: billingworkflowconfig.ValidColumn, + charge.Table: charge.ValidColumn, + chargecreditpurchase.Table: chargecreditpurchase.ValidColumn, + chargecreditpurchasecreditgrant.Table: chargecreditpurchasecreditgrant.ValidColumn, + chargecreditpurchaseexternalpayment.Table: chargecreditpurchaseexternalpayment.ValidColumn, + chargecreditpurchaseinvoicedpayment.Table: chargecreditpurchaseinvoicedpayment.ValidColumn, + chargeflatfee.Table: chargeflatfee.ValidColumn, + chargeflatfeeoverride.Table: chargeflatfeeoverride.ValidColumn, + chargeflatfeerun.Table: chargeflatfeerun.ValidColumn, + chargeflatfeeruncreditallocations.Table: chargeflatfeeruncreditallocations.ValidColumn, + chargeflatfeerundetailedline.Table: chargeflatfeerundetailedline.ValidColumn, + chargeflatfeeruninvoicedusage.Table: chargeflatfeeruninvoicedusage.ValidColumn, + chargeflatfeerunpayment.Table: chargeflatfeerunpayment.ValidColumn, + chargeusagebased.Table: chargeusagebased.ValidColumn, + chargeusagebasedoverride.Table: chargeusagebasedoverride.ValidColumn, + chargeusagebasedruncreditallocations.Table: chargeusagebasedruncreditallocations.ValidColumn, + chargeusagebasedrundetailedline.Table: chargeusagebasedrundetailedline.ValidColumn, + chargeusagebasedruninvoicedusage.Table: chargeusagebasedruninvoicedusage.ValidColumn, + chargeusagebasedrunpayment.Table: chargeusagebasedrunpayment.ValidColumn, + chargeusagebasedruns.Table: chargeusagebasedruns.ValidColumn, + chargessearchv1.Table: chargessearchv1.ValidColumn, + creditrealizationlineage.Table: creditrealizationlineage.ValidColumn, + creditrealizationlineagesegment.Table: creditrealizationlineagesegment.ValidColumn, + currencycostbasis.Table: currencycostbasis.ValidColumn, + customcurrency.Table: customcurrency.ValidColumn, + customer.Table: customer.ValidColumn, + customersubjects.Table: customersubjects.ValidColumn, + entitlement.Table: entitlement.ValidColumn, + dbfeature.Table: dbfeature.ValidColumn, + dbgrant.Table: dbgrant.ValidColumn, + llmcostprice.Table: llmcostprice.ValidColumn, + ledgeraccount.Table: ledgeraccount.ValidColumn, + ledgerbreakagerecord.Table: ledgerbreakagerecord.ValidColumn, + ledgercreditvoidrecord.Table: ledgercreditvoidrecord.ValidColumn, + ledgercustomeraccount.Table: ledgercustomeraccount.ValidColumn, + ledgerentry.Table: ledgerentry.ValidColumn, + ledgersubaccount.Table: ledgersubaccount.ValidColumn, + ledgersubaccountroute.Table: ledgersubaccountroute.ValidColumn, + ledgertransaction.Table: ledgertransaction.ValidColumn, + ledgertransactiongroup.Table: ledgertransactiongroup.ValidColumn, + dbmeter.Table: dbmeter.ValidColumn, + notificationchannel.Table: notificationchannel.ValidColumn, + notificationevent.Table: notificationevent.ValidColumn, + notificationeventdeliverystatus.Table: notificationeventdeliverystatus.ValidColumn, + notificationrule.Table: notificationrule.ValidColumn, + organizationdefaulttaxcodes.Table: organizationdefaulttaxcodes.ValidColumn, + plan.Table: plan.ValidColumn, + planaddon.Table: planaddon.ValidColumn, + planphase.Table: planphase.ValidColumn, + planratecard.Table: planratecard.ValidColumn, + subject.Table: subject.ValidColumn, + subscription.Table: subscription.ValidColumn, + subscriptionaddon.Table: subscriptionaddon.ValidColumn, + subscriptionaddonquantity.Table: subscriptionaddonquantity.ValidColumn, + subscriptionbillingsyncstate.Table: subscriptionbillingsyncstate.ValidColumn, + subscriptionitem.Table: subscriptionitem.ValidColumn, + subscriptionphase.Table: subscriptionphase.ValidColumn, + dbtaxcode.Table: dbtaxcode.ValidColumn, + usagereset.Table: usagereset.ValidColumn, + }) + }) + return columnCheck(t, c) +} + +// Asc applies the given fields in ASC order. +func Asc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("db: %w", err)}) + } + s.OrderBy(sql.Asc(s.C(f))) + } + } +} + +// Desc applies the given fields in DESC order. +func Desc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("db: %w", err)}) + } + s.OrderBy(sql.Desc(s.C(f))) + } + } +} + +// AggregateFunc applies an aggregation step on the group-by traversal/selector. +type AggregateFunc func(*sql.Selector) string + +// As is a pseudo aggregation function for renaming another other functions with custom names. For example: +// +// GroupBy(field1, field2). +// Aggregate(db.As(db.Sum(field1), "sum_field1"), (db.As(db.Sum(field2), "sum_field2")). +// Scan(ctx, &v) +func As(fn AggregateFunc, end string) AggregateFunc { + return func(s *sql.Selector) string { + return sql.As(fn(s), end) + } +} + +// Count applies the "count" aggregation function on each group. +func Count() AggregateFunc { + return func(s *sql.Selector) string { + return sql.Count("*") + } +} + +// Max applies the "max" aggregation function on the given field of each group. +func Max(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("db: %w", err)}) + return "" + } + return sql.Max(s.C(field)) + } +} + +// Mean applies the "mean" aggregation function on the given field of each group. +func Mean(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("db: %w", err)}) + return "" + } + return sql.Avg(s.C(field)) + } +} + +// Min applies the "min" aggregation function on the given field of each group. +func Min(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("db: %w", err)}) + return "" + } + return sql.Min(s.C(field)) + } +} + +// Sum applies the "sum" aggregation function on the given field of each group. +func Sum(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("db: %w", err)}) + return "" + } + return sql.Sum(s.C(field)) + } +} + +// ValidationError returns when validating a field or edge fails. +type ValidationError struct { + Name string // Field or edge name. + err error +} + +// Error implements the error interface. +func (e *ValidationError) Error() string { + return e.err.Error() +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ValidationError) Unwrap() error { + return e.err +} + +// IsValidationError returns a boolean indicating whether the error is a validation error. +func IsValidationError(err error) bool { + if err == nil { + return false + } + var e *ValidationError + return errors.As(err, &e) +} + +// NotFoundError returns when trying to fetch a specific entity and it was not found in the database. +type NotFoundError struct { + label string +} + +// Error implements the error interface. +func (e *NotFoundError) Error() string { + return "db: " + e.label + " not found" +} + +// IsNotFound returns a boolean indicating whether the error is a not found error. +func IsNotFound(err error) bool { + if err == nil { + return false + } + var e *NotFoundError + return errors.As(err, &e) +} + +// MaskNotFound masks not found error. +func MaskNotFound(err error) error { + if IsNotFound(err) { + return nil + } + return err +} + +// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database. +type NotSingularError struct { + label string +} + +// Error implements the error interface. +func (e *NotSingularError) Error() string { + return "db: " + e.label + " not singular" +} + +// IsNotSingular returns a boolean indicating whether the error is a not singular error. +func IsNotSingular(err error) bool { + if err == nil { + return false + } + var e *NotSingularError + return errors.As(err, &e) +} + +// NotLoadedError returns when trying to get a node that was not loaded by the query. +type NotLoadedError struct { + edge string +} + +// Error implements the error interface. +func (e *NotLoadedError) Error() string { + return "db: " + e.edge + " edge was not loaded" +} + +// IsNotLoaded returns a boolean indicating whether the error is a not loaded error. +func IsNotLoaded(err error) bool { + if err == nil { + return false + } + var e *NotLoadedError + return errors.As(err, &e) +} + +// ConstraintError returns when trying to create/update one or more entities and +// one or more of their constraints failed. For example, violation of edge or +// field uniqueness. +type ConstraintError struct { + msg string + wrap error +} + +// Error implements the error interface. +func (e ConstraintError) Error() string { + return "db: constraint failed: " + e.msg +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ConstraintError) Unwrap() error { + return e.wrap +} + +// IsConstraintError returns a boolean indicating whether the error is a constraint failure. +func IsConstraintError(err error) bool { + if err == nil { + return false + } + var e *ConstraintError + return errors.As(err, &e) +} + +// selector embedded by the different Select/GroupBy builders. +type selector struct { + label string + flds *[]string + fns []AggregateFunc + scan func(context.Context, any) error +} + +// ScanX is like Scan, but panics if an error occurs. +func (s *selector) ScanX(ctx context.Context, v any) { + if err := s.scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (s *selector) Strings(ctx context.Context) ([]string, error) { + if len(*s.flds) > 1 { + return nil, errors.New("db: Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (s *selector) StringsX(ctx context.Context) []string { + v, err := s.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (s *selector) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = s.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("db: Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (s *selector) StringX(ctx context.Context) string { + v, err := s.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (s *selector) Ints(ctx context.Context) ([]int, error) { + if len(*s.flds) > 1 { + return nil, errors.New("db: Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (s *selector) IntsX(ctx context.Context) []int { + v, err := s.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (s *selector) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = s.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("db: Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (s *selector) IntX(ctx context.Context) int { + v, err := s.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (s *selector) Float64s(ctx context.Context) ([]float64, error) { + if len(*s.flds) > 1 { + return nil, errors.New("db: Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (s *selector) Float64sX(ctx context.Context) []float64 { + v, err := s.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (s *selector) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = s.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("db: Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (s *selector) Float64X(ctx context.Context) float64 { + v, err := s.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (s *selector) Bools(ctx context.Context) ([]bool, error) { + if len(*s.flds) > 1 { + return nil, errors.New("db: Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (s *selector) BoolsX(ctx context.Context) []bool { + v, err := s.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (s *selector) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = s.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("db: Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (s *selector) BoolX(ctx context.Context) bool { + v, err := s.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +// withHooks invokes the builder operation with the given hooks, if any. +func withHooks[V Value, M any, PM interface { + *M + Mutation +}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) { + if len(hooks) == 0 { + return exec(ctx) + } + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutationT, ok := any(m).(PM) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + // Set the mutation to the builder. + *mutation = *mutationT + return exec(ctx) + }) + for i := len(hooks) - 1; i >= 0; i-- { + if hooks[i] == nil { + return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = hooks[i](mut) + } + v, err := mut.Mutate(ctx, mutation) + if err != nil { + return value, err + } + nv, ok := v.(V) + if !ok { + return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation) + } + return nv, nil +} + +// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist. +func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context { + if ent.QueryFromContext(ctx) == nil { + qc.Op = op + ctx = ent.NewQueryContext(ctx, qc) + } + return ctx +} + +func querierAll[V Value, Q interface { + sqlAll(context.Context, ...queryHook) (V, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlAll(ctx) + }) +} + +func querierCount[Q interface { + sqlCount(context.Context) (int, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlCount(ctx) + }) +} + +func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) { + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + rv, err := qr.Query(ctx, q) + if err != nil { + return v, err + } + vt, ok := rv.(V) + if !ok { + return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v) + } + return vt, nil +} + +func scanWithInterceptors[Q1 ent.Query, Q2 interface { + sqlScan(context.Context, Q1, any) error +}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error { + rv := reflect.ValueOf(v) + var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q1) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + if err := selectOrGroup.sqlScan(ctx, query, v); err != nil { + return nil, err + } + if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() { + return rv.Elem().Interface(), nil + } + return v, nil + }) + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + vv, err := qr.Query(ctx, rootQuery) + if err != nil { + return err + } + switch rv2 := reflect.ValueOf(vv); { + case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer: + case rv.Type() == rv2.Type(): + rv.Elem().Set(rv2.Elem()) + case rv.Elem().Type() == rv2.Type(): + rv.Elem().Set(rv2) + } + return nil +} + +// queryHook describes an internal hook for the different sqlAll methods. +type queryHook func(context.Context, *sqlgraph.QuerySpec) diff --git a/ent/db/entitlement.go b/ent/db/entitlement.go new file mode 100644 index 0000000000000000000000000000000000000000..20ef5d4bb29b8fe3dddb117e7fcd2c7ef765dd7b --- /dev/null +++ b/ent/db/entitlement.go @@ -0,0 +1,501 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/customer" + "github.com/openmeterio/openmeter/openmeter/ent/db/entitlement" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + "github.com/openmeterio/openmeter/pkg/datetime" + "github.com/openmeterio/openmeter/pkg/models" +) + +// Entitlement is the model entity for the Entitlement schema. +type Entitlement 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"` + // Metadata holds the value of the "metadata" field. + Metadata map[string]string `json:"metadata,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"` + // EntitlementType holds the value of the "entitlement_type" field. + EntitlementType entitlement.EntitlementType `json:"entitlement_type,omitempty"` + // FeatureID holds the value of the "feature_id" field. + FeatureID string `json:"feature_id,omitempty"` + // ActiveFrom holds the value of the "active_from" field. + ActiveFrom *time.Time `json:"active_from,omitempty"` + // ActiveTo holds the value of the "active_to" field. + ActiveTo *time.Time `json:"active_to,omitempty"` + // FeatureKey holds the value of the "feature_key" field. + FeatureKey string `json:"feature_key,omitempty"` + // CustomerID holds the value of the "customer_id" field. + CustomerID string `json:"customer_id,omitempty"` + // MeasureUsageFrom holds the value of the "measure_usage_from" field. + MeasureUsageFrom *time.Time `json:"measure_usage_from,omitempty"` + // IssueAfterReset holds the value of the "issue_after_reset" field. + IssueAfterReset *float64 `json:"issue_after_reset,omitempty"` + // IssueAfterResetPriority holds the value of the "issue_after_reset_priority" field. + IssueAfterResetPriority *uint8 `json:"issue_after_reset_priority,omitempty"` + // IsSoftLimit holds the value of the "is_soft_limit" field. + IsSoftLimit *bool `json:"is_soft_limit,omitempty"` + // PreserveOverageAtReset holds the value of the "preserve_overage_at_reset" field. + PreserveOverageAtReset *bool `json:"preserve_overage_at_reset,omitempty"` + // Config holds the value of the "config" field. + Config *string `json:"config,omitempty"` + // UsagePeriodInterval holds the value of the "usage_period_interval" field. + UsagePeriodInterval *datetime.ISODurationString `json:"usage_period_interval,omitempty"` + // Historically this field had been overwritten with each anchor reset, now we keep the original anchor time and the value is populated from the last reset which is queried dynamically + UsagePeriodAnchor *time.Time `json:"usage_period_anchor,omitempty"` + // CurrentUsagePeriodStart holds the value of the "current_usage_period_start" field. + CurrentUsagePeriodStart *time.Time `json:"current_usage_period_start,omitempty"` + // CurrentUsagePeriodEnd holds the value of the "current_usage_period_end" field. + CurrentUsagePeriodEnd *time.Time `json:"current_usage_period_end,omitempty"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the EntitlementQuery when eager-loading is set. + Edges EntitlementEdges `json:"edges"` + selectValues sql.SelectValues +} + +// EntitlementEdges holds the relations/edges for other nodes in the graph. +type EntitlementEdges struct { + // UsageReset holds the value of the usage_reset edge. + UsageReset []*UsageReset `json:"usage_reset,omitempty"` + // Grant holds the value of the grant edge. + Grant []*Grant `json:"grant,omitempty"` + // BalanceSnapshot holds the value of the balance_snapshot edge. + BalanceSnapshot []*BalanceSnapshot `json:"balance_snapshot,omitempty"` + // SubscriptionItem holds the value of the subscription_item edge. + SubscriptionItem []*SubscriptionItem `json:"subscription_item,omitempty"` + // Feature holds the value of the feature edge. + Feature *Feature `json:"feature,omitempty"` + // Customer holds the value of the customer edge. + Customer *Customer `json:"customer,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [6]bool +} + +// UsageResetOrErr returns the UsageReset value or an error if the edge +// was not loaded in eager-loading. +func (e EntitlementEdges) UsageResetOrErr() ([]*UsageReset, error) { + if e.loadedTypes[0] { + return e.UsageReset, nil + } + return nil, &NotLoadedError{edge: "usage_reset"} +} + +// GrantOrErr returns the Grant value or an error if the edge +// was not loaded in eager-loading. +func (e EntitlementEdges) GrantOrErr() ([]*Grant, error) { + if e.loadedTypes[1] { + return e.Grant, nil + } + return nil, &NotLoadedError{edge: "grant"} +} + +// BalanceSnapshotOrErr returns the BalanceSnapshot value or an error if the edge +// was not loaded in eager-loading. +func (e EntitlementEdges) BalanceSnapshotOrErr() ([]*BalanceSnapshot, error) { + if e.loadedTypes[2] { + return e.BalanceSnapshot, nil + } + return nil, &NotLoadedError{edge: "balance_snapshot"} +} + +// SubscriptionItemOrErr returns the SubscriptionItem value or an error if the edge +// was not loaded in eager-loading. +func (e EntitlementEdges) SubscriptionItemOrErr() ([]*SubscriptionItem, error) { + if e.loadedTypes[3] { + return e.SubscriptionItem, nil + } + return nil, &NotLoadedError{edge: "subscription_item"} +} + +// FeatureOrErr returns the Feature value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e EntitlementEdges) FeatureOrErr() (*Feature, error) { + if e.Feature != nil { + return e.Feature, nil + } else if e.loadedTypes[4] { + return nil, &NotFoundError{label: dbfeature.Label} + } + return nil, &NotLoadedError{edge: "feature"} +} + +// CustomerOrErr returns the Customer value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e EntitlementEdges) CustomerOrErr() (*Customer, error) { + if e.Customer != nil { + return e.Customer, nil + } else if e.loadedTypes[5] { + return nil, &NotFoundError{label: customer.Label} + } + return nil, &NotLoadedError{edge: "customer"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Entitlement) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case entitlement.FieldMetadata: + values[i] = new([]byte) + case entitlement.FieldIsSoftLimit, entitlement.FieldPreserveOverageAtReset: + values[i] = new(sql.NullBool) + case entitlement.FieldIssueAfterReset: + values[i] = new(sql.NullFloat64) + case entitlement.FieldIssueAfterResetPriority: + values[i] = new(sql.NullInt64) + case entitlement.FieldID, entitlement.FieldNamespace, entitlement.FieldEntitlementType, entitlement.FieldFeatureID, entitlement.FieldFeatureKey, entitlement.FieldCustomerID, entitlement.FieldConfig, entitlement.FieldUsagePeriodInterval: + values[i] = new(sql.NullString) + case entitlement.FieldCreatedAt, entitlement.FieldUpdatedAt, entitlement.FieldDeletedAt, entitlement.FieldActiveFrom, entitlement.FieldActiveTo, entitlement.FieldMeasureUsageFrom, entitlement.FieldUsagePeriodAnchor, entitlement.FieldCurrentUsagePeriodStart, entitlement.FieldCurrentUsagePeriodEnd: + values[i] = new(sql.NullTime) + case entitlement.FieldAnnotations: + values[i] = entitlement.ValueScanner.Annotations.ScanValue() + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Entitlement fields. +func (_m *Entitlement) 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 entitlement.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 entitlement.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 entitlement.FieldMetadata: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field metadata", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Metadata); err != nil { + return fmt.Errorf("unmarshal field metadata: %w", err) + } + } + case entitlement.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 entitlement.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 entitlement.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 entitlement.FieldEntitlementType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field entitlement_type", values[i]) + } else if value.Valid { + _m.EntitlementType = entitlement.EntitlementType(value.String) + } + case entitlement.FieldFeatureID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field feature_id", values[i]) + } else if value.Valid { + _m.FeatureID = value.String + } + case entitlement.FieldActiveFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field active_from", values[i]) + } else if value.Valid { + _m.ActiveFrom = new(time.Time) + *_m.ActiveFrom = value.Time + } + case entitlement.FieldActiveTo: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field active_to", values[i]) + } else if value.Valid { + _m.ActiveTo = new(time.Time) + *_m.ActiveTo = value.Time + } + case entitlement.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 entitlement.FieldCustomerID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field customer_id", values[i]) + } else if value.Valid { + _m.CustomerID = value.String + } + case entitlement.FieldMeasureUsageFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field measure_usage_from", values[i]) + } else if value.Valid { + _m.MeasureUsageFrom = new(time.Time) + *_m.MeasureUsageFrom = value.Time + } + case entitlement.FieldIssueAfterReset: + if value, ok := values[i].(*sql.NullFloat64); !ok { + return fmt.Errorf("unexpected type %T for field issue_after_reset", values[i]) + } else if value.Valid { + _m.IssueAfterReset = new(float64) + *_m.IssueAfterReset = value.Float64 + } + case entitlement.FieldIssueAfterResetPriority: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field issue_after_reset_priority", values[i]) + } else if value.Valid { + _m.IssueAfterResetPriority = new(uint8) + *_m.IssueAfterResetPriority = uint8(value.Int64) + } + case entitlement.FieldIsSoftLimit: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field is_soft_limit", values[i]) + } else if value.Valid { + _m.IsSoftLimit = new(bool) + *_m.IsSoftLimit = value.Bool + } + case entitlement.FieldPreserveOverageAtReset: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field preserve_overage_at_reset", values[i]) + } else if value.Valid { + _m.PreserveOverageAtReset = new(bool) + *_m.PreserveOverageAtReset = value.Bool + } + case entitlement.FieldConfig: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field config", values[i]) + } else if value.Valid { + _m.Config = new(string) + *_m.Config = value.String + } + case entitlement.FieldUsagePeriodInterval: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field usage_period_interval", values[i]) + } else if value.Valid { + _m.UsagePeriodInterval = new(datetime.ISODurationString) + *_m.UsagePeriodInterval = datetime.ISODurationString(value.String) + } + case entitlement.FieldUsagePeriodAnchor: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field usage_period_anchor", values[i]) + } else if value.Valid { + _m.UsagePeriodAnchor = new(time.Time) + *_m.UsagePeriodAnchor = value.Time + } + case entitlement.FieldCurrentUsagePeriodStart: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field current_usage_period_start", values[i]) + } else if value.Valid { + _m.CurrentUsagePeriodStart = new(time.Time) + *_m.CurrentUsagePeriodStart = value.Time + } + case entitlement.FieldCurrentUsagePeriodEnd: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field current_usage_period_end", values[i]) + } else if value.Valid { + _m.CurrentUsagePeriodEnd = new(time.Time) + *_m.CurrentUsagePeriodEnd = value.Time + } + case entitlement.FieldAnnotations: + if value, err := entitlement.ValueScanner.Annotations.FromValue(values[i]); err != nil { + return err + } else { + _m.Annotations = value + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Entitlement. +// This includes values selected through modifiers, order, etc. +func (_m *Entitlement) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryUsageReset queries the "usage_reset" edge of the Entitlement entity. +func (_m *Entitlement) QueryUsageReset() *UsageResetQuery { + return NewEntitlementClient(_m.config).QueryUsageReset(_m) +} + +// QueryGrant queries the "grant" edge of the Entitlement entity. +func (_m *Entitlement) QueryGrant() *GrantQuery { + return NewEntitlementClient(_m.config).QueryGrant(_m) +} + +// QueryBalanceSnapshot queries the "balance_snapshot" edge of the Entitlement entity. +func (_m *Entitlement) QueryBalanceSnapshot() *BalanceSnapshotQuery { + return NewEntitlementClient(_m.config).QueryBalanceSnapshot(_m) +} + +// QuerySubscriptionItem queries the "subscription_item" edge of the Entitlement entity. +func (_m *Entitlement) QuerySubscriptionItem() *SubscriptionItemQuery { + return NewEntitlementClient(_m.config).QuerySubscriptionItem(_m) +} + +// QueryFeature queries the "feature" edge of the Entitlement entity. +func (_m *Entitlement) QueryFeature() *FeatureQuery { + return NewEntitlementClient(_m.config).QueryFeature(_m) +} + +// QueryCustomer queries the "customer" edge of the Entitlement entity. +func (_m *Entitlement) QueryCustomer() *CustomerQuery { + return NewEntitlementClient(_m.config).QueryCustomer(_m) +} + +// Update returns a builder for updating this Entitlement. +// Note that you need to call Entitlement.Unwrap() before calling this method if this Entitlement +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Entitlement) Update() *EntitlementUpdateOne { + return NewEntitlementClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Entitlement 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 *Entitlement) Unwrap() *Entitlement { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: Entitlement is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Entitlement) String() string { + var builder strings.Builder + builder.WriteString("Entitlement(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("metadata=") + builder.WriteString(fmt.Sprintf("%v", _m.Metadata)) + 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("entitlement_type=") + builder.WriteString(fmt.Sprintf("%v", _m.EntitlementType)) + builder.WriteString(", ") + builder.WriteString("feature_id=") + builder.WriteString(_m.FeatureID) + builder.WriteString(", ") + if v := _m.ActiveFrom; v != nil { + builder.WriteString("active_from=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + if v := _m.ActiveTo; v != nil { + builder.WriteString("active_to=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + builder.WriteString("feature_key=") + builder.WriteString(_m.FeatureKey) + builder.WriteString(", ") + builder.WriteString("customer_id=") + builder.WriteString(_m.CustomerID) + builder.WriteString(", ") + if v := _m.MeasureUsageFrom; v != nil { + builder.WriteString("measure_usage_from=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + if v := _m.IssueAfterReset; v != nil { + builder.WriteString("issue_after_reset=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.IssueAfterResetPriority; v != nil { + builder.WriteString("issue_after_reset_priority=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.IsSoftLimit; v != nil { + builder.WriteString("is_soft_limit=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.PreserveOverageAtReset; v != nil { + builder.WriteString("preserve_overage_at_reset=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.Config; v != nil { + builder.WriteString("config=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.UsagePeriodInterval; v != nil { + builder.WriteString("usage_period_interval=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.UsagePeriodAnchor; v != nil { + builder.WriteString("usage_period_anchor=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + if v := _m.CurrentUsagePeriodStart; v != nil { + builder.WriteString("current_usage_period_start=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + if v := _m.CurrentUsagePeriodEnd; v != nil { + builder.WriteString("current_usage_period_end=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + builder.WriteByte(')') + return builder.String() +} + +// Entitlements is a parsable slice of Entitlement. +type Entitlements []*Entitlement diff --git a/ent/db/entitlement/entitlement.go b/ent/db/entitlement/entitlement.go new file mode 100644 index 0000000000000000000000000000000000000000..212e29e2b3c3bc1beed710d0ccea8d6cf736d971 --- /dev/null +++ b/ent/db/entitlement/entitlement.go @@ -0,0 +1,425 @@ +// Code generated by ent, DO NOT EDIT. + +package entitlement + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/pkg/models" +) + +const ( + // Label holds the string label denoting the entitlement type in the database. + Label = "entitlement" + // 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" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // 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" + // FieldEntitlementType holds the string denoting the entitlement_type field in the database. + FieldEntitlementType = "entitlement_type" + // FieldFeatureID holds the string denoting the feature_id field in the database. + FieldFeatureID = "feature_id" + // FieldActiveFrom holds the string denoting the active_from field in the database. + FieldActiveFrom = "active_from" + // FieldActiveTo holds the string denoting the active_to field in the database. + FieldActiveTo = "active_to" + // FieldFeatureKey holds the string denoting the feature_key field in the database. + FieldFeatureKey = "feature_key" + // FieldCustomerID holds the string denoting the customer_id field in the database. + FieldCustomerID = "customer_id" + // FieldMeasureUsageFrom holds the string denoting the measure_usage_from field in the database. + FieldMeasureUsageFrom = "measure_usage_from" + // FieldIssueAfterReset holds the string denoting the issue_after_reset field in the database. + FieldIssueAfterReset = "issue_after_reset" + // FieldIssueAfterResetPriority holds the string denoting the issue_after_reset_priority field in the database. + FieldIssueAfterResetPriority = "issue_after_reset_priority" + // FieldIsSoftLimit holds the string denoting the is_soft_limit field in the database. + FieldIsSoftLimit = "is_soft_limit" + // FieldPreserveOverageAtReset holds the string denoting the preserve_overage_at_reset field in the database. + FieldPreserveOverageAtReset = "preserve_overage_at_reset" + // FieldConfig holds the string denoting the config field in the database. + FieldConfig = "config" + // FieldUsagePeriodInterval holds the string denoting the usage_period_interval field in the database. + FieldUsagePeriodInterval = "usage_period_interval" + // FieldUsagePeriodAnchor holds the string denoting the usage_period_anchor field in the database. + FieldUsagePeriodAnchor = "usage_period_anchor" + // FieldCurrentUsagePeriodStart holds the string denoting the current_usage_period_start field in the database. + FieldCurrentUsagePeriodStart = "current_usage_period_start" + // FieldCurrentUsagePeriodEnd holds the string denoting the current_usage_period_end field in the database. + FieldCurrentUsagePeriodEnd = "current_usage_period_end" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // EdgeUsageReset holds the string denoting the usage_reset edge name in mutations. + EdgeUsageReset = "usage_reset" + // EdgeGrant holds the string denoting the grant edge name in mutations. + EdgeGrant = "grant" + // EdgeBalanceSnapshot holds the string denoting the balance_snapshot edge name in mutations. + EdgeBalanceSnapshot = "balance_snapshot" + // EdgeSubscriptionItem holds the string denoting the subscription_item edge name in mutations. + EdgeSubscriptionItem = "subscription_item" + // EdgeFeature holds the string denoting the feature edge name in mutations. + EdgeFeature = "feature" + // EdgeCustomer holds the string denoting the customer edge name in mutations. + EdgeCustomer = "customer" + // Table holds the table name of the entitlement in the database. + Table = "entitlements" + // UsageResetTable is the table that holds the usage_reset relation/edge. + UsageResetTable = "usage_resets" + // UsageResetInverseTable is the table name for the UsageReset entity. + // It exists in this package in order to avoid circular dependency with the "usagereset" package. + UsageResetInverseTable = "usage_resets" + // UsageResetColumn is the table column denoting the usage_reset relation/edge. + UsageResetColumn = "entitlement_id" + // GrantTable is the table that holds the grant relation/edge. + GrantTable = "grants" + // GrantInverseTable is the table name for the Grant entity. + // It exists in this package in order to avoid circular dependency with the "dbgrant" package. + GrantInverseTable = "grants" + // GrantColumn is the table column denoting the grant relation/edge. + GrantColumn = "owner_id" + // BalanceSnapshotTable is the table that holds the balance_snapshot relation/edge. + BalanceSnapshotTable = "balance_snapshots" + // BalanceSnapshotInverseTable is the table name for the BalanceSnapshot entity. + // It exists in this package in order to avoid circular dependency with the "balancesnapshot" package. + BalanceSnapshotInverseTable = "balance_snapshots" + // BalanceSnapshotColumn is the table column denoting the balance_snapshot relation/edge. + BalanceSnapshotColumn = "owner_id" + // SubscriptionItemTable is the table that holds the subscription_item relation/edge. + SubscriptionItemTable = "subscription_items" + // SubscriptionItemInverseTable is the table name for the SubscriptionItem entity. + // It exists in this package in order to avoid circular dependency with the "subscriptionitem" package. + SubscriptionItemInverseTable = "subscription_items" + // SubscriptionItemColumn is the table column denoting the subscription_item relation/edge. + SubscriptionItemColumn = "entitlement_id" + // FeatureTable is the table that holds the feature relation/edge. + FeatureTable = "entitlements" + // FeatureInverseTable is the table name for the Feature entity. + // It exists in this package in order to avoid circular dependency with the "dbfeature" package. + FeatureInverseTable = "features" + // FeatureColumn is the table column denoting the feature relation/edge. + FeatureColumn = "feature_id" + // CustomerTable is the table that holds the customer relation/edge. + CustomerTable = "entitlements" + // CustomerInverseTable is the table name for the Customer entity. + // It exists in this package in order to avoid circular dependency with the "customer" package. + CustomerInverseTable = "customers" + // CustomerColumn is the table column denoting the customer relation/edge. + CustomerColumn = "customer_id" +) + +// Columns holds all SQL columns for entitlement fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldMetadata, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldEntitlementType, + FieldFeatureID, + FieldActiveFrom, + FieldActiveTo, + FieldFeatureKey, + FieldCustomerID, + FieldMeasureUsageFrom, + FieldIssueAfterReset, + FieldIssueAfterResetPriority, + FieldIsSoftLimit, + FieldPreserveOverageAtReset, + FieldConfig, + FieldUsagePeriodInterval, + FieldUsagePeriodAnchor, + FieldCurrentUsagePeriodStart, + FieldCurrentUsagePeriodEnd, + FieldAnnotations, +} + +// 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 + // 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 Entitlement fields. + ValueScanner struct { + Annotations field.TypeValueScanner[models.Annotations] + } +) + +// EntitlementType defines the type for the "entitlement_type" enum field. +type EntitlementType string + +// EntitlementType values. +const ( + EntitlementTypeMetered EntitlementType = "metered" + EntitlementTypeStatic EntitlementType = "static" + EntitlementTypeBoolean EntitlementType = "boolean" +) + +func (et EntitlementType) String() string { + return string(et) +} + +// EntitlementTypeValidator is a validator for the "entitlement_type" field enum values. It is called by the builders before save. +func EntitlementTypeValidator(et EntitlementType) error { + switch et { + case EntitlementTypeMetered, EntitlementTypeStatic, EntitlementTypeBoolean: + return nil + default: + return fmt.Errorf("entitlement: invalid enum value for entitlement_type field: %q", et) + } +} + +// OrderOption defines the ordering options for the Entitlement 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() +} + +// ByEntitlementType orders the results by the entitlement_type field. +func ByEntitlementType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEntitlementType, opts...).ToFunc() +} + +// ByFeatureID orders the results by the feature_id field. +func ByFeatureID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFeatureID, opts...).ToFunc() +} + +// ByActiveFrom orders the results by the active_from field. +func ByActiveFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldActiveFrom, opts...).ToFunc() +} + +// ByActiveTo orders the results by the active_to field. +func ByActiveTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldActiveTo, opts...).ToFunc() +} + +// ByFeatureKey orders the results by the feature_key field. +func ByFeatureKey(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFeatureKey, opts...).ToFunc() +} + +// ByCustomerID orders the results by the customer_id field. +func ByCustomerID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCustomerID, opts...).ToFunc() +} + +// ByMeasureUsageFrom orders the results by the measure_usage_from field. +func ByMeasureUsageFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMeasureUsageFrom, opts...).ToFunc() +} + +// ByIssueAfterReset orders the results by the issue_after_reset field. +func ByIssueAfterReset(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIssueAfterReset, opts...).ToFunc() +} + +// ByIssueAfterResetPriority orders the results by the issue_after_reset_priority field. +func ByIssueAfterResetPriority(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIssueAfterResetPriority, opts...).ToFunc() +} + +// ByIsSoftLimit orders the results by the is_soft_limit field. +func ByIsSoftLimit(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIsSoftLimit, opts...).ToFunc() +} + +// ByPreserveOverageAtReset orders the results by the preserve_overage_at_reset field. +func ByPreserveOverageAtReset(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPreserveOverageAtReset, opts...).ToFunc() +} + +// ByConfig orders the results by the config field. +func ByConfig(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldConfig, opts...).ToFunc() +} + +// ByUsagePeriodInterval orders the results by the usage_period_interval field. +func ByUsagePeriodInterval(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUsagePeriodInterval, opts...).ToFunc() +} + +// ByUsagePeriodAnchor orders the results by the usage_period_anchor field. +func ByUsagePeriodAnchor(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUsagePeriodAnchor, opts...).ToFunc() +} + +// ByCurrentUsagePeriodStart orders the results by the current_usage_period_start field. +func ByCurrentUsagePeriodStart(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCurrentUsagePeriodStart, opts...).ToFunc() +} + +// ByCurrentUsagePeriodEnd orders the results by the current_usage_period_end field. +func ByCurrentUsagePeriodEnd(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCurrentUsagePeriodEnd, opts...).ToFunc() +} + +// ByAnnotations orders the results by the annotations field. +func ByAnnotations(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAnnotations, opts...).ToFunc() +} + +// ByUsageResetCount orders the results by usage_reset count. +func ByUsageResetCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newUsageResetStep(), opts...) + } +} + +// ByUsageReset orders the results by usage_reset terms. +func ByUsageReset(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUsageResetStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByGrantCount orders the results by grant count. +func ByGrantCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newGrantStep(), opts...) + } +} + +// ByGrant orders the results by grant terms. +func ByGrant(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newGrantStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByBalanceSnapshotCount orders the results by balance_snapshot count. +func ByBalanceSnapshotCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newBalanceSnapshotStep(), opts...) + } +} + +// ByBalanceSnapshot orders the results by balance_snapshot terms. +func ByBalanceSnapshot(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBalanceSnapshotStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// BySubscriptionItemCount orders the results by subscription_item count. +func BySubscriptionItemCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newSubscriptionItemStep(), opts...) + } +} + +// BySubscriptionItem orders the results by subscription_item terms. +func BySubscriptionItem(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubscriptionItemStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByFeatureField orders the results by feature field. +func ByFeatureField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newFeatureStep(), sql.OrderByField(field, opts...)) + } +} + +// ByCustomerField orders the results by customer field. +func ByCustomerField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCustomerStep(), sql.OrderByField(field, opts...)) + } +} +func newUsageResetStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UsageResetInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, UsageResetTable, UsageResetColumn), + ) +} +func newGrantStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(GrantInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, GrantTable, GrantColumn), + ) +} +func newBalanceSnapshotStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BalanceSnapshotInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, BalanceSnapshotTable, BalanceSnapshotColumn), + ) +} +func newSubscriptionItemStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SubscriptionItemInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SubscriptionItemTable, SubscriptionItemColumn), + ) +} +func newFeatureStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(FeatureInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, FeatureTable, FeatureColumn), + ) +} +func newCustomerStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CustomerInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, CustomerTable, CustomerColumn), + ) +} diff --git a/ent/db/entitlement/where.go b/ent/db/entitlement/where.go new file mode 100644 index 0000000000000000000000000000000000000000..035dc5b1f900c5dc3ca663f4d31edb30eb897937 --- /dev/null +++ b/ent/db/entitlement/where.go @@ -0,0 +1,1355 @@ +// Code generated by ent, DO NOT EDIT. + +package entitlement + +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/pkg/datetime" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.Entitlement { + return predicate.Entitlement(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.Entitlement { + return predicate.Entitlement(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.Entitlement { + return predicate.Entitlement(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.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldDeletedAt, v)) +} + +// FeatureID applies equality check predicate on the "feature_id" field. It's identical to FeatureIDEQ. +func FeatureID(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldFeatureID, v)) +} + +// ActiveFrom applies equality check predicate on the "active_from" field. It's identical to ActiveFromEQ. +func ActiveFrom(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldActiveFrom, v)) +} + +// ActiveTo applies equality check predicate on the "active_to" field. It's identical to ActiveToEQ. +func ActiveTo(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldActiveTo, v)) +} + +// FeatureKey applies equality check predicate on the "feature_key" field. It's identical to FeatureKeyEQ. +func FeatureKey(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldFeatureKey, v)) +} + +// CustomerID applies equality check predicate on the "customer_id" field. It's identical to CustomerIDEQ. +func CustomerID(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldCustomerID, v)) +} + +// MeasureUsageFrom applies equality check predicate on the "measure_usage_from" field. It's identical to MeasureUsageFromEQ. +func MeasureUsageFrom(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldMeasureUsageFrom, v)) +} + +// IssueAfterReset applies equality check predicate on the "issue_after_reset" field. It's identical to IssueAfterResetEQ. +func IssueAfterReset(v float64) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldIssueAfterReset, v)) +} + +// IssueAfterResetPriority applies equality check predicate on the "issue_after_reset_priority" field. It's identical to IssueAfterResetPriorityEQ. +func IssueAfterResetPriority(v uint8) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldIssueAfterResetPriority, v)) +} + +// IsSoftLimit applies equality check predicate on the "is_soft_limit" field. It's identical to IsSoftLimitEQ. +func IsSoftLimit(v bool) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldIsSoftLimit, v)) +} + +// PreserveOverageAtReset applies equality check predicate on the "preserve_overage_at_reset" field. It's identical to PreserveOverageAtResetEQ. +func PreserveOverageAtReset(v bool) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldPreserveOverageAtReset, v)) +} + +// Config applies equality check predicate on the "config" field. It's identical to ConfigEQ. +func Config(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldConfig, v)) +} + +// UsagePeriodInterval applies equality check predicate on the "usage_period_interval" field. It's identical to UsagePeriodIntervalEQ. +func UsagePeriodInterval(v datetime.ISODurationString) predicate.Entitlement { + vc := string(v) + return predicate.Entitlement(sql.FieldEQ(FieldUsagePeriodInterval, vc)) +} + +// UsagePeriodAnchor applies equality check predicate on the "usage_period_anchor" field. It's identical to UsagePeriodAnchorEQ. +func UsagePeriodAnchor(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldUsagePeriodAnchor, v)) +} + +// CurrentUsagePeriodStart applies equality check predicate on the "current_usage_period_start" field. It's identical to CurrentUsagePeriodStartEQ. +func CurrentUsagePeriodStart(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldCurrentUsagePeriodStart, v)) +} + +// CurrentUsagePeriodEnd applies equality check predicate on the "current_usage_period_end" field. It's identical to CurrentUsagePeriodEndEQ. +func CurrentUsagePeriodEnd(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldCurrentUsagePeriodEnd, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldContainsFold(FieldNamespace, v)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotNull(FieldMetadata)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotNull(FieldDeletedAt)) +} + +// EntitlementTypeEQ applies the EQ predicate on the "entitlement_type" field. +func EntitlementTypeEQ(v EntitlementType) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldEntitlementType, v)) +} + +// EntitlementTypeNEQ applies the NEQ predicate on the "entitlement_type" field. +func EntitlementTypeNEQ(v EntitlementType) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNEQ(FieldEntitlementType, v)) +} + +// EntitlementTypeIn applies the In predicate on the "entitlement_type" field. +func EntitlementTypeIn(vs ...EntitlementType) predicate.Entitlement { + return predicate.Entitlement(sql.FieldIn(FieldEntitlementType, vs...)) +} + +// EntitlementTypeNotIn applies the NotIn predicate on the "entitlement_type" field. +func EntitlementTypeNotIn(vs ...EntitlementType) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotIn(FieldEntitlementType, vs...)) +} + +// FeatureIDEQ applies the EQ predicate on the "feature_id" field. +func FeatureIDEQ(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldFeatureID, v)) +} + +// FeatureIDNEQ applies the NEQ predicate on the "feature_id" field. +func FeatureIDNEQ(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNEQ(FieldFeatureID, v)) +} + +// FeatureIDIn applies the In predicate on the "feature_id" field. +func FeatureIDIn(vs ...string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldIn(FieldFeatureID, vs...)) +} + +// FeatureIDNotIn applies the NotIn predicate on the "feature_id" field. +func FeatureIDNotIn(vs ...string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotIn(FieldFeatureID, vs...)) +} + +// FeatureIDGT applies the GT predicate on the "feature_id" field. +func FeatureIDGT(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGT(FieldFeatureID, v)) +} + +// FeatureIDGTE applies the GTE predicate on the "feature_id" field. +func FeatureIDGTE(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGTE(FieldFeatureID, v)) +} + +// FeatureIDLT applies the LT predicate on the "feature_id" field. +func FeatureIDLT(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLT(FieldFeatureID, v)) +} + +// FeatureIDLTE applies the LTE predicate on the "feature_id" field. +func FeatureIDLTE(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLTE(FieldFeatureID, v)) +} + +// FeatureIDContains applies the Contains predicate on the "feature_id" field. +func FeatureIDContains(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldContains(FieldFeatureID, v)) +} + +// FeatureIDHasPrefix applies the HasPrefix predicate on the "feature_id" field. +func FeatureIDHasPrefix(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldHasPrefix(FieldFeatureID, v)) +} + +// FeatureIDHasSuffix applies the HasSuffix predicate on the "feature_id" field. +func FeatureIDHasSuffix(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldHasSuffix(FieldFeatureID, v)) +} + +// FeatureIDEqualFold applies the EqualFold predicate on the "feature_id" field. +func FeatureIDEqualFold(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEqualFold(FieldFeatureID, v)) +} + +// FeatureIDContainsFold applies the ContainsFold predicate on the "feature_id" field. +func FeatureIDContainsFold(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldContainsFold(FieldFeatureID, v)) +} + +// ActiveFromEQ applies the EQ predicate on the "active_from" field. +func ActiveFromEQ(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldActiveFrom, v)) +} + +// ActiveFromNEQ applies the NEQ predicate on the "active_from" field. +func ActiveFromNEQ(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNEQ(FieldActiveFrom, v)) +} + +// ActiveFromIn applies the In predicate on the "active_from" field. +func ActiveFromIn(vs ...time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldIn(FieldActiveFrom, vs...)) +} + +// ActiveFromNotIn applies the NotIn predicate on the "active_from" field. +func ActiveFromNotIn(vs ...time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotIn(FieldActiveFrom, vs...)) +} + +// ActiveFromGT applies the GT predicate on the "active_from" field. +func ActiveFromGT(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGT(FieldActiveFrom, v)) +} + +// ActiveFromGTE applies the GTE predicate on the "active_from" field. +func ActiveFromGTE(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGTE(FieldActiveFrom, v)) +} + +// ActiveFromLT applies the LT predicate on the "active_from" field. +func ActiveFromLT(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLT(FieldActiveFrom, v)) +} + +// ActiveFromLTE applies the LTE predicate on the "active_from" field. +func ActiveFromLTE(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLTE(FieldActiveFrom, v)) +} + +// ActiveFromIsNil applies the IsNil predicate on the "active_from" field. +func ActiveFromIsNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldIsNull(FieldActiveFrom)) +} + +// ActiveFromNotNil applies the NotNil predicate on the "active_from" field. +func ActiveFromNotNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotNull(FieldActiveFrom)) +} + +// ActiveToEQ applies the EQ predicate on the "active_to" field. +func ActiveToEQ(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldActiveTo, v)) +} + +// ActiveToNEQ applies the NEQ predicate on the "active_to" field. +func ActiveToNEQ(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNEQ(FieldActiveTo, v)) +} + +// ActiveToIn applies the In predicate on the "active_to" field. +func ActiveToIn(vs ...time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldIn(FieldActiveTo, vs...)) +} + +// ActiveToNotIn applies the NotIn predicate on the "active_to" field. +func ActiveToNotIn(vs ...time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotIn(FieldActiveTo, vs...)) +} + +// ActiveToGT applies the GT predicate on the "active_to" field. +func ActiveToGT(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGT(FieldActiveTo, v)) +} + +// ActiveToGTE applies the GTE predicate on the "active_to" field. +func ActiveToGTE(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGTE(FieldActiveTo, v)) +} + +// ActiveToLT applies the LT predicate on the "active_to" field. +func ActiveToLT(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLT(FieldActiveTo, v)) +} + +// ActiveToLTE applies the LTE predicate on the "active_to" field. +func ActiveToLTE(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLTE(FieldActiveTo, v)) +} + +// ActiveToIsNil applies the IsNil predicate on the "active_to" field. +func ActiveToIsNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldIsNull(FieldActiveTo)) +} + +// ActiveToNotNil applies the NotNil predicate on the "active_to" field. +func ActiveToNotNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotNull(FieldActiveTo)) +} + +// FeatureKeyEQ applies the EQ predicate on the "feature_key" field. +func FeatureKeyEQ(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldFeatureKey, v)) +} + +// FeatureKeyNEQ applies the NEQ predicate on the "feature_key" field. +func FeatureKeyNEQ(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNEQ(FieldFeatureKey, v)) +} + +// FeatureKeyIn applies the In predicate on the "feature_key" field. +func FeatureKeyIn(vs ...string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldIn(FieldFeatureKey, vs...)) +} + +// FeatureKeyNotIn applies the NotIn predicate on the "feature_key" field. +func FeatureKeyNotIn(vs ...string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotIn(FieldFeatureKey, vs...)) +} + +// FeatureKeyGT applies the GT predicate on the "feature_key" field. +func FeatureKeyGT(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGT(FieldFeatureKey, v)) +} + +// FeatureKeyGTE applies the GTE predicate on the "feature_key" field. +func FeatureKeyGTE(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGTE(FieldFeatureKey, v)) +} + +// FeatureKeyLT applies the LT predicate on the "feature_key" field. +func FeatureKeyLT(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLT(FieldFeatureKey, v)) +} + +// FeatureKeyLTE applies the LTE predicate on the "feature_key" field. +func FeatureKeyLTE(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLTE(FieldFeatureKey, v)) +} + +// FeatureKeyContains applies the Contains predicate on the "feature_key" field. +func FeatureKeyContains(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldContains(FieldFeatureKey, v)) +} + +// FeatureKeyHasPrefix applies the HasPrefix predicate on the "feature_key" field. +func FeatureKeyHasPrefix(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldHasPrefix(FieldFeatureKey, v)) +} + +// FeatureKeyHasSuffix applies the HasSuffix predicate on the "feature_key" field. +func FeatureKeyHasSuffix(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldHasSuffix(FieldFeatureKey, v)) +} + +// FeatureKeyEqualFold applies the EqualFold predicate on the "feature_key" field. +func FeatureKeyEqualFold(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEqualFold(FieldFeatureKey, v)) +} + +// FeatureKeyContainsFold applies the ContainsFold predicate on the "feature_key" field. +func FeatureKeyContainsFold(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldContainsFold(FieldFeatureKey, v)) +} + +// CustomerIDEQ applies the EQ predicate on the "customer_id" field. +func CustomerIDEQ(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldCustomerID, v)) +} + +// CustomerIDNEQ applies the NEQ predicate on the "customer_id" field. +func CustomerIDNEQ(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNEQ(FieldCustomerID, v)) +} + +// CustomerIDIn applies the In predicate on the "customer_id" field. +func CustomerIDIn(vs ...string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldIn(FieldCustomerID, vs...)) +} + +// CustomerIDNotIn applies the NotIn predicate on the "customer_id" field. +func CustomerIDNotIn(vs ...string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotIn(FieldCustomerID, vs...)) +} + +// CustomerIDGT applies the GT predicate on the "customer_id" field. +func CustomerIDGT(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGT(FieldCustomerID, v)) +} + +// CustomerIDGTE applies the GTE predicate on the "customer_id" field. +func CustomerIDGTE(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGTE(FieldCustomerID, v)) +} + +// CustomerIDLT applies the LT predicate on the "customer_id" field. +func CustomerIDLT(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLT(FieldCustomerID, v)) +} + +// CustomerIDLTE applies the LTE predicate on the "customer_id" field. +func CustomerIDLTE(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLTE(FieldCustomerID, v)) +} + +// CustomerIDContains applies the Contains predicate on the "customer_id" field. +func CustomerIDContains(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldContains(FieldCustomerID, v)) +} + +// CustomerIDHasPrefix applies the HasPrefix predicate on the "customer_id" field. +func CustomerIDHasPrefix(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldHasPrefix(FieldCustomerID, v)) +} + +// CustomerIDHasSuffix applies the HasSuffix predicate on the "customer_id" field. +func CustomerIDHasSuffix(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldHasSuffix(FieldCustomerID, v)) +} + +// CustomerIDEqualFold applies the EqualFold predicate on the "customer_id" field. +func CustomerIDEqualFold(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEqualFold(FieldCustomerID, v)) +} + +// CustomerIDContainsFold applies the ContainsFold predicate on the "customer_id" field. +func CustomerIDContainsFold(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldContainsFold(FieldCustomerID, v)) +} + +// MeasureUsageFromEQ applies the EQ predicate on the "measure_usage_from" field. +func MeasureUsageFromEQ(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldMeasureUsageFrom, v)) +} + +// MeasureUsageFromNEQ applies the NEQ predicate on the "measure_usage_from" field. +func MeasureUsageFromNEQ(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNEQ(FieldMeasureUsageFrom, v)) +} + +// MeasureUsageFromIn applies the In predicate on the "measure_usage_from" field. +func MeasureUsageFromIn(vs ...time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldIn(FieldMeasureUsageFrom, vs...)) +} + +// MeasureUsageFromNotIn applies the NotIn predicate on the "measure_usage_from" field. +func MeasureUsageFromNotIn(vs ...time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotIn(FieldMeasureUsageFrom, vs...)) +} + +// MeasureUsageFromGT applies the GT predicate on the "measure_usage_from" field. +func MeasureUsageFromGT(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGT(FieldMeasureUsageFrom, v)) +} + +// MeasureUsageFromGTE applies the GTE predicate on the "measure_usage_from" field. +func MeasureUsageFromGTE(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGTE(FieldMeasureUsageFrom, v)) +} + +// MeasureUsageFromLT applies the LT predicate on the "measure_usage_from" field. +func MeasureUsageFromLT(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLT(FieldMeasureUsageFrom, v)) +} + +// MeasureUsageFromLTE applies the LTE predicate on the "measure_usage_from" field. +func MeasureUsageFromLTE(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLTE(FieldMeasureUsageFrom, v)) +} + +// MeasureUsageFromIsNil applies the IsNil predicate on the "measure_usage_from" field. +func MeasureUsageFromIsNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldIsNull(FieldMeasureUsageFrom)) +} + +// MeasureUsageFromNotNil applies the NotNil predicate on the "measure_usage_from" field. +func MeasureUsageFromNotNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotNull(FieldMeasureUsageFrom)) +} + +// IssueAfterResetEQ applies the EQ predicate on the "issue_after_reset" field. +func IssueAfterResetEQ(v float64) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldIssueAfterReset, v)) +} + +// IssueAfterResetNEQ applies the NEQ predicate on the "issue_after_reset" field. +func IssueAfterResetNEQ(v float64) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNEQ(FieldIssueAfterReset, v)) +} + +// IssueAfterResetIn applies the In predicate on the "issue_after_reset" field. +func IssueAfterResetIn(vs ...float64) predicate.Entitlement { + return predicate.Entitlement(sql.FieldIn(FieldIssueAfterReset, vs...)) +} + +// IssueAfterResetNotIn applies the NotIn predicate on the "issue_after_reset" field. +func IssueAfterResetNotIn(vs ...float64) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotIn(FieldIssueAfterReset, vs...)) +} + +// IssueAfterResetGT applies the GT predicate on the "issue_after_reset" field. +func IssueAfterResetGT(v float64) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGT(FieldIssueAfterReset, v)) +} + +// IssueAfterResetGTE applies the GTE predicate on the "issue_after_reset" field. +func IssueAfterResetGTE(v float64) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGTE(FieldIssueAfterReset, v)) +} + +// IssueAfterResetLT applies the LT predicate on the "issue_after_reset" field. +func IssueAfterResetLT(v float64) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLT(FieldIssueAfterReset, v)) +} + +// IssueAfterResetLTE applies the LTE predicate on the "issue_after_reset" field. +func IssueAfterResetLTE(v float64) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLTE(FieldIssueAfterReset, v)) +} + +// IssueAfterResetIsNil applies the IsNil predicate on the "issue_after_reset" field. +func IssueAfterResetIsNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldIsNull(FieldIssueAfterReset)) +} + +// IssueAfterResetNotNil applies the NotNil predicate on the "issue_after_reset" field. +func IssueAfterResetNotNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotNull(FieldIssueAfterReset)) +} + +// IssueAfterResetPriorityEQ applies the EQ predicate on the "issue_after_reset_priority" field. +func IssueAfterResetPriorityEQ(v uint8) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldIssueAfterResetPriority, v)) +} + +// IssueAfterResetPriorityNEQ applies the NEQ predicate on the "issue_after_reset_priority" field. +func IssueAfterResetPriorityNEQ(v uint8) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNEQ(FieldIssueAfterResetPriority, v)) +} + +// IssueAfterResetPriorityIn applies the In predicate on the "issue_after_reset_priority" field. +func IssueAfterResetPriorityIn(vs ...uint8) predicate.Entitlement { + return predicate.Entitlement(sql.FieldIn(FieldIssueAfterResetPriority, vs...)) +} + +// IssueAfterResetPriorityNotIn applies the NotIn predicate on the "issue_after_reset_priority" field. +func IssueAfterResetPriorityNotIn(vs ...uint8) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotIn(FieldIssueAfterResetPriority, vs...)) +} + +// IssueAfterResetPriorityGT applies the GT predicate on the "issue_after_reset_priority" field. +func IssueAfterResetPriorityGT(v uint8) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGT(FieldIssueAfterResetPriority, v)) +} + +// IssueAfterResetPriorityGTE applies the GTE predicate on the "issue_after_reset_priority" field. +func IssueAfterResetPriorityGTE(v uint8) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGTE(FieldIssueAfterResetPriority, v)) +} + +// IssueAfterResetPriorityLT applies the LT predicate on the "issue_after_reset_priority" field. +func IssueAfterResetPriorityLT(v uint8) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLT(FieldIssueAfterResetPriority, v)) +} + +// IssueAfterResetPriorityLTE applies the LTE predicate on the "issue_after_reset_priority" field. +func IssueAfterResetPriorityLTE(v uint8) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLTE(FieldIssueAfterResetPriority, v)) +} + +// IssueAfterResetPriorityIsNil applies the IsNil predicate on the "issue_after_reset_priority" field. +func IssueAfterResetPriorityIsNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldIsNull(FieldIssueAfterResetPriority)) +} + +// IssueAfterResetPriorityNotNil applies the NotNil predicate on the "issue_after_reset_priority" field. +func IssueAfterResetPriorityNotNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotNull(FieldIssueAfterResetPriority)) +} + +// IsSoftLimitEQ applies the EQ predicate on the "is_soft_limit" field. +func IsSoftLimitEQ(v bool) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldIsSoftLimit, v)) +} + +// IsSoftLimitNEQ applies the NEQ predicate on the "is_soft_limit" field. +func IsSoftLimitNEQ(v bool) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNEQ(FieldIsSoftLimit, v)) +} + +// IsSoftLimitIsNil applies the IsNil predicate on the "is_soft_limit" field. +func IsSoftLimitIsNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldIsNull(FieldIsSoftLimit)) +} + +// IsSoftLimitNotNil applies the NotNil predicate on the "is_soft_limit" field. +func IsSoftLimitNotNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotNull(FieldIsSoftLimit)) +} + +// PreserveOverageAtResetEQ applies the EQ predicate on the "preserve_overage_at_reset" field. +func PreserveOverageAtResetEQ(v bool) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldPreserveOverageAtReset, v)) +} + +// PreserveOverageAtResetNEQ applies the NEQ predicate on the "preserve_overage_at_reset" field. +func PreserveOverageAtResetNEQ(v bool) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNEQ(FieldPreserveOverageAtReset, v)) +} + +// PreserveOverageAtResetIsNil applies the IsNil predicate on the "preserve_overage_at_reset" field. +func PreserveOverageAtResetIsNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldIsNull(FieldPreserveOverageAtReset)) +} + +// PreserveOverageAtResetNotNil applies the NotNil predicate on the "preserve_overage_at_reset" field. +func PreserveOverageAtResetNotNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotNull(FieldPreserveOverageAtReset)) +} + +// ConfigEQ applies the EQ predicate on the "config" field. +func ConfigEQ(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldConfig, v)) +} + +// ConfigNEQ applies the NEQ predicate on the "config" field. +func ConfigNEQ(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNEQ(FieldConfig, v)) +} + +// ConfigIn applies the In predicate on the "config" field. +func ConfigIn(vs ...string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldIn(FieldConfig, vs...)) +} + +// ConfigNotIn applies the NotIn predicate on the "config" field. +func ConfigNotIn(vs ...string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotIn(FieldConfig, vs...)) +} + +// ConfigGT applies the GT predicate on the "config" field. +func ConfigGT(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGT(FieldConfig, v)) +} + +// ConfigGTE applies the GTE predicate on the "config" field. +func ConfigGTE(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGTE(FieldConfig, v)) +} + +// ConfigLT applies the LT predicate on the "config" field. +func ConfigLT(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLT(FieldConfig, v)) +} + +// ConfigLTE applies the LTE predicate on the "config" field. +func ConfigLTE(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLTE(FieldConfig, v)) +} + +// ConfigContains applies the Contains predicate on the "config" field. +func ConfigContains(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldContains(FieldConfig, v)) +} + +// ConfigHasPrefix applies the HasPrefix predicate on the "config" field. +func ConfigHasPrefix(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldHasPrefix(FieldConfig, v)) +} + +// ConfigHasSuffix applies the HasSuffix predicate on the "config" field. +func ConfigHasSuffix(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldHasSuffix(FieldConfig, v)) +} + +// ConfigIsNil applies the IsNil predicate on the "config" field. +func ConfigIsNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldIsNull(FieldConfig)) +} + +// ConfigNotNil applies the NotNil predicate on the "config" field. +func ConfigNotNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotNull(FieldConfig)) +} + +// ConfigEqualFold applies the EqualFold predicate on the "config" field. +func ConfigEqualFold(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEqualFold(FieldConfig, v)) +} + +// ConfigContainsFold applies the ContainsFold predicate on the "config" field. +func ConfigContainsFold(v string) predicate.Entitlement { + return predicate.Entitlement(sql.FieldContainsFold(FieldConfig, v)) +} + +// UsagePeriodIntervalEQ applies the EQ predicate on the "usage_period_interval" field. +func UsagePeriodIntervalEQ(v datetime.ISODurationString) predicate.Entitlement { + vc := string(v) + return predicate.Entitlement(sql.FieldEQ(FieldUsagePeriodInterval, vc)) +} + +// UsagePeriodIntervalNEQ applies the NEQ predicate on the "usage_period_interval" field. +func UsagePeriodIntervalNEQ(v datetime.ISODurationString) predicate.Entitlement { + vc := string(v) + return predicate.Entitlement(sql.FieldNEQ(FieldUsagePeriodInterval, vc)) +} + +// UsagePeriodIntervalIn applies the In predicate on the "usage_period_interval" field. +func UsagePeriodIntervalIn(vs ...datetime.ISODurationString) predicate.Entitlement { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.Entitlement(sql.FieldIn(FieldUsagePeriodInterval, v...)) +} + +// UsagePeriodIntervalNotIn applies the NotIn predicate on the "usage_period_interval" field. +func UsagePeriodIntervalNotIn(vs ...datetime.ISODurationString) predicate.Entitlement { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.Entitlement(sql.FieldNotIn(FieldUsagePeriodInterval, v...)) +} + +// UsagePeriodIntervalGT applies the GT predicate on the "usage_period_interval" field. +func UsagePeriodIntervalGT(v datetime.ISODurationString) predicate.Entitlement { + vc := string(v) + return predicate.Entitlement(sql.FieldGT(FieldUsagePeriodInterval, vc)) +} + +// UsagePeriodIntervalGTE applies the GTE predicate on the "usage_period_interval" field. +func UsagePeriodIntervalGTE(v datetime.ISODurationString) predicate.Entitlement { + vc := string(v) + return predicate.Entitlement(sql.FieldGTE(FieldUsagePeriodInterval, vc)) +} + +// UsagePeriodIntervalLT applies the LT predicate on the "usage_period_interval" field. +func UsagePeriodIntervalLT(v datetime.ISODurationString) predicate.Entitlement { + vc := string(v) + return predicate.Entitlement(sql.FieldLT(FieldUsagePeriodInterval, vc)) +} + +// UsagePeriodIntervalLTE applies the LTE predicate on the "usage_period_interval" field. +func UsagePeriodIntervalLTE(v datetime.ISODurationString) predicate.Entitlement { + vc := string(v) + return predicate.Entitlement(sql.FieldLTE(FieldUsagePeriodInterval, vc)) +} + +// UsagePeriodIntervalContains applies the Contains predicate on the "usage_period_interval" field. +func UsagePeriodIntervalContains(v datetime.ISODurationString) predicate.Entitlement { + vc := string(v) + return predicate.Entitlement(sql.FieldContains(FieldUsagePeriodInterval, vc)) +} + +// UsagePeriodIntervalHasPrefix applies the HasPrefix predicate on the "usage_period_interval" field. +func UsagePeriodIntervalHasPrefix(v datetime.ISODurationString) predicate.Entitlement { + vc := string(v) + return predicate.Entitlement(sql.FieldHasPrefix(FieldUsagePeriodInterval, vc)) +} + +// UsagePeriodIntervalHasSuffix applies the HasSuffix predicate on the "usage_period_interval" field. +func UsagePeriodIntervalHasSuffix(v datetime.ISODurationString) predicate.Entitlement { + vc := string(v) + return predicate.Entitlement(sql.FieldHasSuffix(FieldUsagePeriodInterval, vc)) +} + +// UsagePeriodIntervalIsNil applies the IsNil predicate on the "usage_period_interval" field. +func UsagePeriodIntervalIsNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldIsNull(FieldUsagePeriodInterval)) +} + +// UsagePeriodIntervalNotNil applies the NotNil predicate on the "usage_period_interval" field. +func UsagePeriodIntervalNotNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotNull(FieldUsagePeriodInterval)) +} + +// UsagePeriodIntervalEqualFold applies the EqualFold predicate on the "usage_period_interval" field. +func UsagePeriodIntervalEqualFold(v datetime.ISODurationString) predicate.Entitlement { + vc := string(v) + return predicate.Entitlement(sql.FieldEqualFold(FieldUsagePeriodInterval, vc)) +} + +// UsagePeriodIntervalContainsFold applies the ContainsFold predicate on the "usage_period_interval" field. +func UsagePeriodIntervalContainsFold(v datetime.ISODurationString) predicate.Entitlement { + vc := string(v) + return predicate.Entitlement(sql.FieldContainsFold(FieldUsagePeriodInterval, vc)) +} + +// UsagePeriodAnchorEQ applies the EQ predicate on the "usage_period_anchor" field. +func UsagePeriodAnchorEQ(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldUsagePeriodAnchor, v)) +} + +// UsagePeriodAnchorNEQ applies the NEQ predicate on the "usage_period_anchor" field. +func UsagePeriodAnchorNEQ(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNEQ(FieldUsagePeriodAnchor, v)) +} + +// UsagePeriodAnchorIn applies the In predicate on the "usage_period_anchor" field. +func UsagePeriodAnchorIn(vs ...time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldIn(FieldUsagePeriodAnchor, vs...)) +} + +// UsagePeriodAnchorNotIn applies the NotIn predicate on the "usage_period_anchor" field. +func UsagePeriodAnchorNotIn(vs ...time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotIn(FieldUsagePeriodAnchor, vs...)) +} + +// UsagePeriodAnchorGT applies the GT predicate on the "usage_period_anchor" field. +func UsagePeriodAnchorGT(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGT(FieldUsagePeriodAnchor, v)) +} + +// UsagePeriodAnchorGTE applies the GTE predicate on the "usage_period_anchor" field. +func UsagePeriodAnchorGTE(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGTE(FieldUsagePeriodAnchor, v)) +} + +// UsagePeriodAnchorLT applies the LT predicate on the "usage_period_anchor" field. +func UsagePeriodAnchorLT(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLT(FieldUsagePeriodAnchor, v)) +} + +// UsagePeriodAnchorLTE applies the LTE predicate on the "usage_period_anchor" field. +func UsagePeriodAnchorLTE(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLTE(FieldUsagePeriodAnchor, v)) +} + +// UsagePeriodAnchorIsNil applies the IsNil predicate on the "usage_period_anchor" field. +func UsagePeriodAnchorIsNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldIsNull(FieldUsagePeriodAnchor)) +} + +// UsagePeriodAnchorNotNil applies the NotNil predicate on the "usage_period_anchor" field. +func UsagePeriodAnchorNotNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotNull(FieldUsagePeriodAnchor)) +} + +// CurrentUsagePeriodStartEQ applies the EQ predicate on the "current_usage_period_start" field. +func CurrentUsagePeriodStartEQ(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldCurrentUsagePeriodStart, v)) +} + +// CurrentUsagePeriodStartNEQ applies the NEQ predicate on the "current_usage_period_start" field. +func CurrentUsagePeriodStartNEQ(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNEQ(FieldCurrentUsagePeriodStart, v)) +} + +// CurrentUsagePeriodStartIn applies the In predicate on the "current_usage_period_start" field. +func CurrentUsagePeriodStartIn(vs ...time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldIn(FieldCurrentUsagePeriodStart, vs...)) +} + +// CurrentUsagePeriodStartNotIn applies the NotIn predicate on the "current_usage_period_start" field. +func CurrentUsagePeriodStartNotIn(vs ...time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotIn(FieldCurrentUsagePeriodStart, vs...)) +} + +// CurrentUsagePeriodStartGT applies the GT predicate on the "current_usage_period_start" field. +func CurrentUsagePeriodStartGT(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGT(FieldCurrentUsagePeriodStart, v)) +} + +// CurrentUsagePeriodStartGTE applies the GTE predicate on the "current_usage_period_start" field. +func CurrentUsagePeriodStartGTE(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGTE(FieldCurrentUsagePeriodStart, v)) +} + +// CurrentUsagePeriodStartLT applies the LT predicate on the "current_usage_period_start" field. +func CurrentUsagePeriodStartLT(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLT(FieldCurrentUsagePeriodStart, v)) +} + +// CurrentUsagePeriodStartLTE applies the LTE predicate on the "current_usage_period_start" field. +func CurrentUsagePeriodStartLTE(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLTE(FieldCurrentUsagePeriodStart, v)) +} + +// CurrentUsagePeriodStartIsNil applies the IsNil predicate on the "current_usage_period_start" field. +func CurrentUsagePeriodStartIsNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldIsNull(FieldCurrentUsagePeriodStart)) +} + +// CurrentUsagePeriodStartNotNil applies the NotNil predicate on the "current_usage_period_start" field. +func CurrentUsagePeriodStartNotNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotNull(FieldCurrentUsagePeriodStart)) +} + +// CurrentUsagePeriodEndEQ applies the EQ predicate on the "current_usage_period_end" field. +func CurrentUsagePeriodEndEQ(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldEQ(FieldCurrentUsagePeriodEnd, v)) +} + +// CurrentUsagePeriodEndNEQ applies the NEQ predicate on the "current_usage_period_end" field. +func CurrentUsagePeriodEndNEQ(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNEQ(FieldCurrentUsagePeriodEnd, v)) +} + +// CurrentUsagePeriodEndIn applies the In predicate on the "current_usage_period_end" field. +func CurrentUsagePeriodEndIn(vs ...time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldIn(FieldCurrentUsagePeriodEnd, vs...)) +} + +// CurrentUsagePeriodEndNotIn applies the NotIn predicate on the "current_usage_period_end" field. +func CurrentUsagePeriodEndNotIn(vs ...time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotIn(FieldCurrentUsagePeriodEnd, vs...)) +} + +// CurrentUsagePeriodEndGT applies the GT predicate on the "current_usage_period_end" field. +func CurrentUsagePeriodEndGT(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGT(FieldCurrentUsagePeriodEnd, v)) +} + +// CurrentUsagePeriodEndGTE applies the GTE predicate on the "current_usage_period_end" field. +func CurrentUsagePeriodEndGTE(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldGTE(FieldCurrentUsagePeriodEnd, v)) +} + +// CurrentUsagePeriodEndLT applies the LT predicate on the "current_usage_period_end" field. +func CurrentUsagePeriodEndLT(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLT(FieldCurrentUsagePeriodEnd, v)) +} + +// CurrentUsagePeriodEndLTE applies the LTE predicate on the "current_usage_period_end" field. +func CurrentUsagePeriodEndLTE(v time.Time) predicate.Entitlement { + return predicate.Entitlement(sql.FieldLTE(FieldCurrentUsagePeriodEnd, v)) +} + +// CurrentUsagePeriodEndIsNil applies the IsNil predicate on the "current_usage_period_end" field. +func CurrentUsagePeriodEndIsNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldIsNull(FieldCurrentUsagePeriodEnd)) +} + +// CurrentUsagePeriodEndNotNil applies the NotNil predicate on the "current_usage_period_end" field. +func CurrentUsagePeriodEndNotNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotNull(FieldCurrentUsagePeriodEnd)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.Entitlement { + return predicate.Entitlement(sql.FieldNotNull(FieldAnnotations)) +} + +// HasUsageReset applies the HasEdge predicate on the "usage_reset" edge. +func HasUsageReset() predicate.Entitlement { + return predicate.Entitlement(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, UsageResetTable, UsageResetColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUsageResetWith applies the HasEdge predicate on the "usage_reset" edge with a given conditions (other predicates). +func HasUsageResetWith(preds ...predicate.UsageReset) predicate.Entitlement { + return predicate.Entitlement(func(s *sql.Selector) { + step := newUsageResetStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasGrant applies the HasEdge predicate on the "grant" edge. +func HasGrant() predicate.Entitlement { + return predicate.Entitlement(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, GrantTable, GrantColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasGrantWith applies the HasEdge predicate on the "grant" edge with a given conditions (other predicates). +func HasGrantWith(preds ...predicate.Grant) predicate.Entitlement { + return predicate.Entitlement(func(s *sql.Selector) { + step := newGrantStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasBalanceSnapshot applies the HasEdge predicate on the "balance_snapshot" edge. +func HasBalanceSnapshot() predicate.Entitlement { + return predicate.Entitlement(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, BalanceSnapshotTable, BalanceSnapshotColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBalanceSnapshotWith applies the HasEdge predicate on the "balance_snapshot" edge with a given conditions (other predicates). +func HasBalanceSnapshotWith(preds ...predicate.BalanceSnapshot) predicate.Entitlement { + return predicate.Entitlement(func(s *sql.Selector) { + step := newBalanceSnapshotStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSubscriptionItem applies the HasEdge predicate on the "subscription_item" edge. +func HasSubscriptionItem() predicate.Entitlement { + return predicate.Entitlement(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SubscriptionItemTable, SubscriptionItemColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubscriptionItemWith applies the HasEdge predicate on the "subscription_item" edge with a given conditions (other predicates). +func HasSubscriptionItemWith(preds ...predicate.SubscriptionItem) predicate.Entitlement { + return predicate.Entitlement(func(s *sql.Selector) { + step := newSubscriptionItemStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasFeature applies the HasEdge predicate on the "feature" edge. +func HasFeature() predicate.Entitlement { + return predicate.Entitlement(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, FeatureTable, FeatureColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasFeatureWith applies the HasEdge predicate on the "feature" edge with a given conditions (other predicates). +func HasFeatureWith(preds ...predicate.Feature) predicate.Entitlement { + return predicate.Entitlement(func(s *sql.Selector) { + step := newFeatureStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasCustomer applies the HasEdge predicate on the "customer" edge. +func HasCustomer() predicate.Entitlement { + return predicate.Entitlement(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, CustomerTable, CustomerColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCustomerWith applies the HasEdge predicate on the "customer" edge with a given conditions (other predicates). +func HasCustomerWith(preds ...predicate.Customer) predicate.Entitlement { + return predicate.Entitlement(func(s *sql.Selector) { + step := newCustomerStep() + 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.Entitlement) predicate.Entitlement { + return predicate.Entitlement(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Entitlement) predicate.Entitlement { + return predicate.Entitlement(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Entitlement) predicate.Entitlement { + return predicate.Entitlement(sql.NotPredicates(p)) +} diff --git a/ent/db/entitlement_create.go b/ent/db/entitlement_create.go new file mode 100644 index 0000000000000000000000000000000000000000..340cb4112fbc35bc7e1009d667684fc0d958164f --- /dev/null +++ b/ent/db/entitlement_create.go @@ -0,0 +1,1621 @@ +// 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/balancesnapshot" + "github.com/openmeterio/openmeter/openmeter/ent/db/customer" + "github.com/openmeterio/openmeter/openmeter/ent/db/entitlement" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + dbgrant "github.com/openmeterio/openmeter/openmeter/ent/db/grant" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/openmeter/ent/db/usagereset" + "github.com/openmeterio/openmeter/pkg/datetime" + "github.com/openmeterio/openmeter/pkg/models" +) + +// EntitlementCreate is the builder for creating a Entitlement entity. +type EntitlementCreate struct { + config + mutation *EntitlementMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *EntitlementCreate) SetNamespace(v string) *EntitlementCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetMetadata sets the "metadata" field. +func (_c *EntitlementCreate) SetMetadata(v map[string]string) *EntitlementCreate { + _c.mutation.SetMetadata(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *EntitlementCreate) SetCreatedAt(v time.Time) *EntitlementCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *EntitlementCreate) SetNillableCreatedAt(v *time.Time) *EntitlementCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *EntitlementCreate) SetUpdatedAt(v time.Time) *EntitlementCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *EntitlementCreate) SetNillableUpdatedAt(v *time.Time) *EntitlementCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *EntitlementCreate) SetDeletedAt(v time.Time) *EntitlementCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *EntitlementCreate) SetNillableDeletedAt(v *time.Time) *EntitlementCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetEntitlementType sets the "entitlement_type" field. +func (_c *EntitlementCreate) SetEntitlementType(v entitlement.EntitlementType) *EntitlementCreate { + _c.mutation.SetEntitlementType(v) + return _c +} + +// SetFeatureID sets the "feature_id" field. +func (_c *EntitlementCreate) SetFeatureID(v string) *EntitlementCreate { + _c.mutation.SetFeatureID(v) + return _c +} + +// SetActiveFrom sets the "active_from" field. +func (_c *EntitlementCreate) SetActiveFrom(v time.Time) *EntitlementCreate { + _c.mutation.SetActiveFrom(v) + return _c +} + +// SetNillableActiveFrom sets the "active_from" field if the given value is not nil. +func (_c *EntitlementCreate) SetNillableActiveFrom(v *time.Time) *EntitlementCreate { + if v != nil { + _c.SetActiveFrom(*v) + } + return _c +} + +// SetActiveTo sets the "active_to" field. +func (_c *EntitlementCreate) SetActiveTo(v time.Time) *EntitlementCreate { + _c.mutation.SetActiveTo(v) + return _c +} + +// SetNillableActiveTo sets the "active_to" field if the given value is not nil. +func (_c *EntitlementCreate) SetNillableActiveTo(v *time.Time) *EntitlementCreate { + if v != nil { + _c.SetActiveTo(*v) + } + return _c +} + +// SetFeatureKey sets the "feature_key" field. +func (_c *EntitlementCreate) SetFeatureKey(v string) *EntitlementCreate { + _c.mutation.SetFeatureKey(v) + return _c +} + +// SetCustomerID sets the "customer_id" field. +func (_c *EntitlementCreate) SetCustomerID(v string) *EntitlementCreate { + _c.mutation.SetCustomerID(v) + return _c +} + +// SetMeasureUsageFrom sets the "measure_usage_from" field. +func (_c *EntitlementCreate) SetMeasureUsageFrom(v time.Time) *EntitlementCreate { + _c.mutation.SetMeasureUsageFrom(v) + return _c +} + +// SetNillableMeasureUsageFrom sets the "measure_usage_from" field if the given value is not nil. +func (_c *EntitlementCreate) SetNillableMeasureUsageFrom(v *time.Time) *EntitlementCreate { + if v != nil { + _c.SetMeasureUsageFrom(*v) + } + return _c +} + +// SetIssueAfterReset sets the "issue_after_reset" field. +func (_c *EntitlementCreate) SetIssueAfterReset(v float64) *EntitlementCreate { + _c.mutation.SetIssueAfterReset(v) + return _c +} + +// SetNillableIssueAfterReset sets the "issue_after_reset" field if the given value is not nil. +func (_c *EntitlementCreate) SetNillableIssueAfterReset(v *float64) *EntitlementCreate { + if v != nil { + _c.SetIssueAfterReset(*v) + } + return _c +} + +// SetIssueAfterResetPriority sets the "issue_after_reset_priority" field. +func (_c *EntitlementCreate) SetIssueAfterResetPriority(v uint8) *EntitlementCreate { + _c.mutation.SetIssueAfterResetPriority(v) + return _c +} + +// SetNillableIssueAfterResetPriority sets the "issue_after_reset_priority" field if the given value is not nil. +func (_c *EntitlementCreate) SetNillableIssueAfterResetPriority(v *uint8) *EntitlementCreate { + if v != nil { + _c.SetIssueAfterResetPriority(*v) + } + return _c +} + +// SetIsSoftLimit sets the "is_soft_limit" field. +func (_c *EntitlementCreate) SetIsSoftLimit(v bool) *EntitlementCreate { + _c.mutation.SetIsSoftLimit(v) + return _c +} + +// SetNillableIsSoftLimit sets the "is_soft_limit" field if the given value is not nil. +func (_c *EntitlementCreate) SetNillableIsSoftLimit(v *bool) *EntitlementCreate { + if v != nil { + _c.SetIsSoftLimit(*v) + } + return _c +} + +// SetPreserveOverageAtReset sets the "preserve_overage_at_reset" field. +func (_c *EntitlementCreate) SetPreserveOverageAtReset(v bool) *EntitlementCreate { + _c.mutation.SetPreserveOverageAtReset(v) + return _c +} + +// SetNillablePreserveOverageAtReset sets the "preserve_overage_at_reset" field if the given value is not nil. +func (_c *EntitlementCreate) SetNillablePreserveOverageAtReset(v *bool) *EntitlementCreate { + if v != nil { + _c.SetPreserveOverageAtReset(*v) + } + return _c +} + +// SetConfig sets the "config" field. +func (_c *EntitlementCreate) SetConfig(v string) *EntitlementCreate { + _c.mutation.SetConfig(v) + return _c +} + +// SetNillableConfig sets the "config" field if the given value is not nil. +func (_c *EntitlementCreate) SetNillableConfig(v *string) *EntitlementCreate { + if v != nil { + _c.SetConfig(*v) + } + return _c +} + +// SetUsagePeriodInterval sets the "usage_period_interval" field. +func (_c *EntitlementCreate) SetUsagePeriodInterval(v datetime.ISODurationString) *EntitlementCreate { + _c.mutation.SetUsagePeriodInterval(v) + return _c +} + +// SetNillableUsagePeriodInterval sets the "usage_period_interval" field if the given value is not nil. +func (_c *EntitlementCreate) SetNillableUsagePeriodInterval(v *datetime.ISODurationString) *EntitlementCreate { + if v != nil { + _c.SetUsagePeriodInterval(*v) + } + return _c +} + +// SetUsagePeriodAnchor sets the "usage_period_anchor" field. +func (_c *EntitlementCreate) SetUsagePeriodAnchor(v time.Time) *EntitlementCreate { + _c.mutation.SetUsagePeriodAnchor(v) + return _c +} + +// SetNillableUsagePeriodAnchor sets the "usage_period_anchor" field if the given value is not nil. +func (_c *EntitlementCreate) SetNillableUsagePeriodAnchor(v *time.Time) *EntitlementCreate { + if v != nil { + _c.SetUsagePeriodAnchor(*v) + } + return _c +} + +// SetCurrentUsagePeriodStart sets the "current_usage_period_start" field. +func (_c *EntitlementCreate) SetCurrentUsagePeriodStart(v time.Time) *EntitlementCreate { + _c.mutation.SetCurrentUsagePeriodStart(v) + return _c +} + +// SetNillableCurrentUsagePeriodStart sets the "current_usage_period_start" field if the given value is not nil. +func (_c *EntitlementCreate) SetNillableCurrentUsagePeriodStart(v *time.Time) *EntitlementCreate { + if v != nil { + _c.SetCurrentUsagePeriodStart(*v) + } + return _c +} + +// SetCurrentUsagePeriodEnd sets the "current_usage_period_end" field. +func (_c *EntitlementCreate) SetCurrentUsagePeriodEnd(v time.Time) *EntitlementCreate { + _c.mutation.SetCurrentUsagePeriodEnd(v) + return _c +} + +// SetNillableCurrentUsagePeriodEnd sets the "current_usage_period_end" field if the given value is not nil. +func (_c *EntitlementCreate) SetNillableCurrentUsagePeriodEnd(v *time.Time) *EntitlementCreate { + if v != nil { + _c.SetCurrentUsagePeriodEnd(*v) + } + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *EntitlementCreate) SetAnnotations(v models.Annotations) *EntitlementCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetID sets the "id" field. +func (_c *EntitlementCreate) SetID(v string) *EntitlementCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *EntitlementCreate) SetNillableID(v *string) *EntitlementCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// AddUsageResetIDs adds the "usage_reset" edge to the UsageReset entity by IDs. +func (_c *EntitlementCreate) AddUsageResetIDs(ids ...string) *EntitlementCreate { + _c.mutation.AddUsageResetIDs(ids...) + return _c +} + +// AddUsageReset adds the "usage_reset" edges to the UsageReset entity. +func (_c *EntitlementCreate) AddUsageReset(v ...*UsageReset) *EntitlementCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddUsageResetIDs(ids...) +} + +// AddGrantIDs adds the "grant" edge to the Grant entity by IDs. +func (_c *EntitlementCreate) AddGrantIDs(ids ...string) *EntitlementCreate { + _c.mutation.AddGrantIDs(ids...) + return _c +} + +// AddGrant adds the "grant" edges to the Grant entity. +func (_c *EntitlementCreate) AddGrant(v ...*Grant) *EntitlementCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddGrantIDs(ids...) +} + +// AddBalanceSnapshotIDs adds the "balance_snapshot" edge to the BalanceSnapshot entity by IDs. +func (_c *EntitlementCreate) AddBalanceSnapshotIDs(ids ...int) *EntitlementCreate { + _c.mutation.AddBalanceSnapshotIDs(ids...) + return _c +} + +// AddBalanceSnapshot adds the "balance_snapshot" edges to the BalanceSnapshot entity. +func (_c *EntitlementCreate) AddBalanceSnapshot(v ...*BalanceSnapshot) *EntitlementCreate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddBalanceSnapshotIDs(ids...) +} + +// AddSubscriptionItemIDs adds the "subscription_item" edge to the SubscriptionItem entity by IDs. +func (_c *EntitlementCreate) AddSubscriptionItemIDs(ids ...string) *EntitlementCreate { + _c.mutation.AddSubscriptionItemIDs(ids...) + return _c +} + +// AddSubscriptionItem adds the "subscription_item" edges to the SubscriptionItem entity. +func (_c *EntitlementCreate) AddSubscriptionItem(v ...*SubscriptionItem) *EntitlementCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddSubscriptionItemIDs(ids...) +} + +// SetFeature sets the "feature" edge to the Feature entity. +func (_c *EntitlementCreate) SetFeature(v *Feature) *EntitlementCreate { + return _c.SetFeatureID(v.ID) +} + +// SetCustomer sets the "customer" edge to the Customer entity. +func (_c *EntitlementCreate) SetCustomer(v *Customer) *EntitlementCreate { + return _c.SetCustomerID(v.ID) +} + +// Mutation returns the EntitlementMutation object of the builder. +func (_c *EntitlementCreate) Mutation() *EntitlementMutation { + return _c.mutation +} + +// Save creates the Entitlement in the database. +func (_c *EntitlementCreate) Save(ctx context.Context) (*Entitlement, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *EntitlementCreate) SaveX(ctx context.Context) *Entitlement { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *EntitlementCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *EntitlementCreate) 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 *EntitlementCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := entitlement.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := entitlement.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := entitlement.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *EntitlementCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "Entitlement.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := entitlement.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "Entitlement.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "Entitlement.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "Entitlement.updated_at"`)} + } + if _, ok := _c.mutation.EntitlementType(); !ok { + return &ValidationError{Name: "entitlement_type", err: errors.New(`db: missing required field "Entitlement.entitlement_type"`)} + } + if v, ok := _c.mutation.EntitlementType(); ok { + if err := entitlement.EntitlementTypeValidator(v); err != nil { + return &ValidationError{Name: "entitlement_type", err: fmt.Errorf(`db: validator failed for field "Entitlement.entitlement_type": %w`, err)} + } + } + if _, ok := _c.mutation.FeatureID(); !ok { + return &ValidationError{Name: "feature_id", err: errors.New(`db: missing required field "Entitlement.feature_id"`)} + } + if _, ok := _c.mutation.FeatureKey(); !ok { + return &ValidationError{Name: "feature_key", err: errors.New(`db: missing required field "Entitlement.feature_key"`)} + } + if v, ok := _c.mutation.FeatureKey(); ok { + if err := entitlement.FeatureKeyValidator(v); err != nil { + return &ValidationError{Name: "feature_key", err: fmt.Errorf(`db: validator failed for field "Entitlement.feature_key": %w`, err)} + } + } + if _, ok := _c.mutation.CustomerID(); !ok { + return &ValidationError{Name: "customer_id", err: errors.New(`db: missing required field "Entitlement.customer_id"`)} + } + if len(_c.mutation.FeatureIDs()) == 0 { + return &ValidationError{Name: "feature", err: errors.New(`db: missing required edge "Entitlement.feature"`)} + } + if len(_c.mutation.CustomerIDs()) == 0 { + return &ValidationError{Name: "customer", err: errors.New(`db: missing required edge "Entitlement.customer"`)} + } + return nil +} + +func (_c *EntitlementCreate) sqlSave(ctx context.Context) (*Entitlement, 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 Entitlement.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *EntitlementCreate) createSpec() (*Entitlement, *sqlgraph.CreateSpec, error) { + var ( + _node = &Entitlement{config: _c.config} + _spec = sqlgraph.NewCreateSpec(entitlement.Table, sqlgraph.NewFieldSpec(entitlement.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(entitlement.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Metadata(); ok { + _spec.SetField(entitlement.FieldMetadata, field.TypeJSON, value) + _node.Metadata = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(entitlement.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(entitlement.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(entitlement.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.EntitlementType(); ok { + _spec.SetField(entitlement.FieldEntitlementType, field.TypeEnum, value) + _node.EntitlementType = value + } + if value, ok := _c.mutation.ActiveFrom(); ok { + _spec.SetField(entitlement.FieldActiveFrom, field.TypeTime, value) + _node.ActiveFrom = &value + } + if value, ok := _c.mutation.ActiveTo(); ok { + _spec.SetField(entitlement.FieldActiveTo, field.TypeTime, value) + _node.ActiveTo = &value + } + if value, ok := _c.mutation.FeatureKey(); ok { + _spec.SetField(entitlement.FieldFeatureKey, field.TypeString, value) + _node.FeatureKey = value + } + if value, ok := _c.mutation.MeasureUsageFrom(); ok { + _spec.SetField(entitlement.FieldMeasureUsageFrom, field.TypeTime, value) + _node.MeasureUsageFrom = &value + } + if value, ok := _c.mutation.IssueAfterReset(); ok { + _spec.SetField(entitlement.FieldIssueAfterReset, field.TypeFloat64, value) + _node.IssueAfterReset = &value + } + if value, ok := _c.mutation.IssueAfterResetPriority(); ok { + _spec.SetField(entitlement.FieldIssueAfterResetPriority, field.TypeUint8, value) + _node.IssueAfterResetPriority = &value + } + if value, ok := _c.mutation.IsSoftLimit(); ok { + _spec.SetField(entitlement.FieldIsSoftLimit, field.TypeBool, value) + _node.IsSoftLimit = &value + } + if value, ok := _c.mutation.PreserveOverageAtReset(); ok { + _spec.SetField(entitlement.FieldPreserveOverageAtReset, field.TypeBool, value) + _node.PreserveOverageAtReset = &value + } + if value, ok := _c.mutation.Config(); ok { + _spec.SetField(entitlement.FieldConfig, field.TypeString, value) + _node.Config = &value + } + if value, ok := _c.mutation.UsagePeriodInterval(); ok { + _spec.SetField(entitlement.FieldUsagePeriodInterval, field.TypeString, value) + _node.UsagePeriodInterval = &value + } + if value, ok := _c.mutation.UsagePeriodAnchor(); ok { + _spec.SetField(entitlement.FieldUsagePeriodAnchor, field.TypeTime, value) + _node.UsagePeriodAnchor = &value + } + if value, ok := _c.mutation.CurrentUsagePeriodStart(); ok { + _spec.SetField(entitlement.FieldCurrentUsagePeriodStart, field.TypeTime, value) + _node.CurrentUsagePeriodStart = &value + } + if value, ok := _c.mutation.CurrentUsagePeriodEnd(); ok { + _spec.SetField(entitlement.FieldCurrentUsagePeriodEnd, field.TypeTime, value) + _node.CurrentUsagePeriodEnd = &value + } + if value, ok := _c.mutation.Annotations(); ok { + vv, err := entitlement.ValueScanner.Annotations.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(entitlement.FieldAnnotations, field.TypeString, vv) + _node.Annotations = value + } + if nodes := _c.mutation.UsageResetIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.UsageResetTable, + Columns: []string{entitlement.UsageResetColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usagereset.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.GrantIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.GrantTable, + Columns: []string{entitlement.GrantColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbgrant.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.BalanceSnapshotIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.BalanceSnapshotTable, + Columns: []string{entitlement.BalanceSnapshotColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(balancesnapshot.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.SubscriptionItemIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.SubscriptionItemTable, + Columns: []string{entitlement.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.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.FeatureIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: entitlement.FeatureTable, + Columns: []string{entitlement.FeatureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbfeature.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.FeatureID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.CustomerIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: entitlement.CustomerTable, + Columns: []string{entitlement.CustomerColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(customer.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.CustomerID = nodes[0] + _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.Entitlement.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.EntitlementUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *EntitlementCreate) OnConflict(opts ...sql.ConflictOption) *EntitlementUpsertOne { + _c.conflict = opts + return &EntitlementUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Entitlement.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *EntitlementCreate) OnConflictColumns(columns ...string) *EntitlementUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &EntitlementUpsertOne{ + create: _c, + } +} + +type ( + // EntitlementUpsertOne is the builder for "upsert"-ing + // one Entitlement node. + EntitlementUpsertOne struct { + create *EntitlementCreate + } + + // EntitlementUpsert is the "OnConflict" setter. + EntitlementUpsert struct { + *sql.UpdateSet + } +) + +// SetMetadata sets the "metadata" field. +func (u *EntitlementUpsert) SetMetadata(v map[string]string) *EntitlementUpsert { + u.Set(entitlement.FieldMetadata, v) + return u +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *EntitlementUpsert) UpdateMetadata() *EntitlementUpsert { + u.SetExcluded(entitlement.FieldMetadata) + return u +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *EntitlementUpsert) ClearMetadata() *EntitlementUpsert { + u.SetNull(entitlement.FieldMetadata) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *EntitlementUpsert) SetUpdatedAt(v time.Time) *EntitlementUpsert { + u.Set(entitlement.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *EntitlementUpsert) UpdateUpdatedAt() *EntitlementUpsert { + u.SetExcluded(entitlement.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *EntitlementUpsert) SetDeletedAt(v time.Time) *EntitlementUpsert { + u.Set(entitlement.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *EntitlementUpsert) UpdateDeletedAt() *EntitlementUpsert { + u.SetExcluded(entitlement.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *EntitlementUpsert) ClearDeletedAt() *EntitlementUpsert { + u.SetNull(entitlement.FieldDeletedAt) + return u +} + +// SetActiveTo sets the "active_to" field. +func (u *EntitlementUpsert) SetActiveTo(v time.Time) *EntitlementUpsert { + u.Set(entitlement.FieldActiveTo, v) + return u +} + +// UpdateActiveTo sets the "active_to" field to the value that was provided on create. +func (u *EntitlementUpsert) UpdateActiveTo() *EntitlementUpsert { + u.SetExcluded(entitlement.FieldActiveTo) + return u +} + +// ClearActiveTo clears the value of the "active_to" field. +func (u *EntitlementUpsert) ClearActiveTo() *EntitlementUpsert { + u.SetNull(entitlement.FieldActiveTo) + return u +} + +// SetConfig sets the "config" field. +func (u *EntitlementUpsert) SetConfig(v string) *EntitlementUpsert { + u.Set(entitlement.FieldConfig, v) + return u +} + +// UpdateConfig sets the "config" field to the value that was provided on create. +func (u *EntitlementUpsert) UpdateConfig() *EntitlementUpsert { + u.SetExcluded(entitlement.FieldConfig) + return u +} + +// ClearConfig clears the value of the "config" field. +func (u *EntitlementUpsert) ClearConfig() *EntitlementUpsert { + u.SetNull(entitlement.FieldConfig) + return u +} + +// SetUsagePeriodAnchor sets the "usage_period_anchor" field. +func (u *EntitlementUpsert) SetUsagePeriodAnchor(v time.Time) *EntitlementUpsert { + u.Set(entitlement.FieldUsagePeriodAnchor, v) + return u +} + +// UpdateUsagePeriodAnchor sets the "usage_period_anchor" field to the value that was provided on create. +func (u *EntitlementUpsert) UpdateUsagePeriodAnchor() *EntitlementUpsert { + u.SetExcluded(entitlement.FieldUsagePeriodAnchor) + return u +} + +// ClearUsagePeriodAnchor clears the value of the "usage_period_anchor" field. +func (u *EntitlementUpsert) ClearUsagePeriodAnchor() *EntitlementUpsert { + u.SetNull(entitlement.FieldUsagePeriodAnchor) + return u +} + +// SetCurrentUsagePeriodStart sets the "current_usage_period_start" field. +func (u *EntitlementUpsert) SetCurrentUsagePeriodStart(v time.Time) *EntitlementUpsert { + u.Set(entitlement.FieldCurrentUsagePeriodStart, v) + return u +} + +// UpdateCurrentUsagePeriodStart sets the "current_usage_period_start" field to the value that was provided on create. +func (u *EntitlementUpsert) UpdateCurrentUsagePeriodStart() *EntitlementUpsert { + u.SetExcluded(entitlement.FieldCurrentUsagePeriodStart) + return u +} + +// ClearCurrentUsagePeriodStart clears the value of the "current_usage_period_start" field. +func (u *EntitlementUpsert) ClearCurrentUsagePeriodStart() *EntitlementUpsert { + u.SetNull(entitlement.FieldCurrentUsagePeriodStart) + return u +} + +// SetCurrentUsagePeriodEnd sets the "current_usage_period_end" field. +func (u *EntitlementUpsert) SetCurrentUsagePeriodEnd(v time.Time) *EntitlementUpsert { + u.Set(entitlement.FieldCurrentUsagePeriodEnd, v) + return u +} + +// UpdateCurrentUsagePeriodEnd sets the "current_usage_period_end" field to the value that was provided on create. +func (u *EntitlementUpsert) UpdateCurrentUsagePeriodEnd() *EntitlementUpsert { + u.SetExcluded(entitlement.FieldCurrentUsagePeriodEnd) + return u +} + +// ClearCurrentUsagePeriodEnd clears the value of the "current_usage_period_end" field. +func (u *EntitlementUpsert) ClearCurrentUsagePeriodEnd() *EntitlementUpsert { + u.SetNull(entitlement.FieldCurrentUsagePeriodEnd) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *EntitlementUpsert) SetAnnotations(v models.Annotations) *EntitlementUpsert { + u.Set(entitlement.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *EntitlementUpsert) UpdateAnnotations() *EntitlementUpsert { + u.SetExcluded(entitlement.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *EntitlementUpsert) ClearAnnotations() *EntitlementUpsert { + u.SetNull(entitlement.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.Entitlement.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(entitlement.FieldID) +// }), +// ). +// Exec(ctx) +func (u *EntitlementUpsertOne) UpdateNewValues() *EntitlementUpsertOne { + 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(entitlement.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(entitlement.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(entitlement.FieldCreatedAt) + } + if _, exists := u.create.mutation.EntitlementType(); exists { + s.SetIgnore(entitlement.FieldEntitlementType) + } + if _, exists := u.create.mutation.FeatureID(); exists { + s.SetIgnore(entitlement.FieldFeatureID) + } + if _, exists := u.create.mutation.ActiveFrom(); exists { + s.SetIgnore(entitlement.FieldActiveFrom) + } + if _, exists := u.create.mutation.FeatureKey(); exists { + s.SetIgnore(entitlement.FieldFeatureKey) + } + if _, exists := u.create.mutation.CustomerID(); exists { + s.SetIgnore(entitlement.FieldCustomerID) + } + if _, exists := u.create.mutation.MeasureUsageFrom(); exists { + s.SetIgnore(entitlement.FieldMeasureUsageFrom) + } + if _, exists := u.create.mutation.IssueAfterReset(); exists { + s.SetIgnore(entitlement.FieldIssueAfterReset) + } + if _, exists := u.create.mutation.IssueAfterResetPriority(); exists { + s.SetIgnore(entitlement.FieldIssueAfterResetPriority) + } + if _, exists := u.create.mutation.IsSoftLimit(); exists { + s.SetIgnore(entitlement.FieldIsSoftLimit) + } + if _, exists := u.create.mutation.PreserveOverageAtReset(); exists { + s.SetIgnore(entitlement.FieldPreserveOverageAtReset) + } + if _, exists := u.create.mutation.UsagePeriodInterval(); exists { + s.SetIgnore(entitlement.FieldUsagePeriodInterval) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Entitlement.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *EntitlementUpsertOne) Ignore() *EntitlementUpsertOne { + 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 *EntitlementUpsertOne) DoNothing() *EntitlementUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the EntitlementCreate.OnConflict +// documentation for more info. +func (u *EntitlementUpsertOne) Update(set func(*EntitlementUpsert)) *EntitlementUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&EntitlementUpsert{UpdateSet: update}) + })) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *EntitlementUpsertOne) SetMetadata(v map[string]string) *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *EntitlementUpsertOne) UpdateMetadata() *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *EntitlementUpsertOne) ClearMetadata() *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *EntitlementUpsertOne) SetUpdatedAt(v time.Time) *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *EntitlementUpsertOne) UpdateUpdatedAt() *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *EntitlementUpsertOne) SetDeletedAt(v time.Time) *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *EntitlementUpsertOne) UpdateDeletedAt() *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *EntitlementUpsertOne) ClearDeletedAt() *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.ClearDeletedAt() + }) +} + +// SetActiveTo sets the "active_to" field. +func (u *EntitlementUpsertOne) SetActiveTo(v time.Time) *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.SetActiveTo(v) + }) +} + +// UpdateActiveTo sets the "active_to" field to the value that was provided on create. +func (u *EntitlementUpsertOne) UpdateActiveTo() *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.UpdateActiveTo() + }) +} + +// ClearActiveTo clears the value of the "active_to" field. +func (u *EntitlementUpsertOne) ClearActiveTo() *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.ClearActiveTo() + }) +} + +// SetConfig sets the "config" field. +func (u *EntitlementUpsertOne) SetConfig(v string) *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.SetConfig(v) + }) +} + +// UpdateConfig sets the "config" field to the value that was provided on create. +func (u *EntitlementUpsertOne) UpdateConfig() *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.UpdateConfig() + }) +} + +// ClearConfig clears the value of the "config" field. +func (u *EntitlementUpsertOne) ClearConfig() *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.ClearConfig() + }) +} + +// SetUsagePeriodAnchor sets the "usage_period_anchor" field. +func (u *EntitlementUpsertOne) SetUsagePeriodAnchor(v time.Time) *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.SetUsagePeriodAnchor(v) + }) +} + +// UpdateUsagePeriodAnchor sets the "usage_period_anchor" field to the value that was provided on create. +func (u *EntitlementUpsertOne) UpdateUsagePeriodAnchor() *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.UpdateUsagePeriodAnchor() + }) +} + +// ClearUsagePeriodAnchor clears the value of the "usage_period_anchor" field. +func (u *EntitlementUpsertOne) ClearUsagePeriodAnchor() *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.ClearUsagePeriodAnchor() + }) +} + +// SetCurrentUsagePeriodStart sets the "current_usage_period_start" field. +func (u *EntitlementUpsertOne) SetCurrentUsagePeriodStart(v time.Time) *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.SetCurrentUsagePeriodStart(v) + }) +} + +// UpdateCurrentUsagePeriodStart sets the "current_usage_period_start" field to the value that was provided on create. +func (u *EntitlementUpsertOne) UpdateCurrentUsagePeriodStart() *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.UpdateCurrentUsagePeriodStart() + }) +} + +// ClearCurrentUsagePeriodStart clears the value of the "current_usage_period_start" field. +func (u *EntitlementUpsertOne) ClearCurrentUsagePeriodStart() *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.ClearCurrentUsagePeriodStart() + }) +} + +// SetCurrentUsagePeriodEnd sets the "current_usage_period_end" field. +func (u *EntitlementUpsertOne) SetCurrentUsagePeriodEnd(v time.Time) *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.SetCurrentUsagePeriodEnd(v) + }) +} + +// UpdateCurrentUsagePeriodEnd sets the "current_usage_period_end" field to the value that was provided on create. +func (u *EntitlementUpsertOne) UpdateCurrentUsagePeriodEnd() *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.UpdateCurrentUsagePeriodEnd() + }) +} + +// ClearCurrentUsagePeriodEnd clears the value of the "current_usage_period_end" field. +func (u *EntitlementUpsertOne) ClearCurrentUsagePeriodEnd() *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.ClearCurrentUsagePeriodEnd() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *EntitlementUpsertOne) SetAnnotations(v models.Annotations) *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *EntitlementUpsertOne) UpdateAnnotations() *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *EntitlementUpsertOne) ClearAnnotations() *EntitlementUpsertOne { + return u.Update(func(s *EntitlementUpsert) { + s.ClearAnnotations() + }) +} + +// Exec executes the query. +func (u *EntitlementUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for EntitlementCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *EntitlementUpsertOne) 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 *EntitlementUpsertOne) 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: EntitlementUpsertOne.ID is not supported by MySQL driver. Use EntitlementUpsertOne.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 *EntitlementUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// EntitlementCreateBulk is the builder for creating many Entitlement entities in bulk. +type EntitlementCreateBulk struct { + config + err error + builders []*EntitlementCreate + conflict []sql.ConflictOption +} + +// Save creates the Entitlement entities in the database. +func (_c *EntitlementCreateBulk) Save(ctx context.Context) ([]*Entitlement, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Entitlement, 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.(*EntitlementMutation) + 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 *EntitlementCreateBulk) SaveX(ctx context.Context) []*Entitlement { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *EntitlementCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *EntitlementCreateBulk) 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.Entitlement.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.EntitlementUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *EntitlementCreateBulk) OnConflict(opts ...sql.ConflictOption) *EntitlementUpsertBulk { + _c.conflict = opts + return &EntitlementUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Entitlement.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *EntitlementCreateBulk) OnConflictColumns(columns ...string) *EntitlementUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &EntitlementUpsertBulk{ + create: _c, + } +} + +// EntitlementUpsertBulk is the builder for "upsert"-ing +// a bulk of Entitlement nodes. +type EntitlementUpsertBulk struct { + create *EntitlementCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.Entitlement.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(entitlement.FieldID) +// }), +// ). +// Exec(ctx) +func (u *EntitlementUpsertBulk) UpdateNewValues() *EntitlementUpsertBulk { + 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(entitlement.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(entitlement.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(entitlement.FieldCreatedAt) + } + if _, exists := b.mutation.EntitlementType(); exists { + s.SetIgnore(entitlement.FieldEntitlementType) + } + if _, exists := b.mutation.FeatureID(); exists { + s.SetIgnore(entitlement.FieldFeatureID) + } + if _, exists := b.mutation.ActiveFrom(); exists { + s.SetIgnore(entitlement.FieldActiveFrom) + } + if _, exists := b.mutation.FeatureKey(); exists { + s.SetIgnore(entitlement.FieldFeatureKey) + } + if _, exists := b.mutation.CustomerID(); exists { + s.SetIgnore(entitlement.FieldCustomerID) + } + if _, exists := b.mutation.MeasureUsageFrom(); exists { + s.SetIgnore(entitlement.FieldMeasureUsageFrom) + } + if _, exists := b.mutation.IssueAfterReset(); exists { + s.SetIgnore(entitlement.FieldIssueAfterReset) + } + if _, exists := b.mutation.IssueAfterResetPriority(); exists { + s.SetIgnore(entitlement.FieldIssueAfterResetPriority) + } + if _, exists := b.mutation.IsSoftLimit(); exists { + s.SetIgnore(entitlement.FieldIsSoftLimit) + } + if _, exists := b.mutation.PreserveOverageAtReset(); exists { + s.SetIgnore(entitlement.FieldPreserveOverageAtReset) + } + if _, exists := b.mutation.UsagePeriodInterval(); exists { + s.SetIgnore(entitlement.FieldUsagePeriodInterval) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Entitlement.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *EntitlementUpsertBulk) Ignore() *EntitlementUpsertBulk { + 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 *EntitlementUpsertBulk) DoNothing() *EntitlementUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the EntitlementCreateBulk.OnConflict +// documentation for more info. +func (u *EntitlementUpsertBulk) Update(set func(*EntitlementUpsert)) *EntitlementUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&EntitlementUpsert{UpdateSet: update}) + })) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *EntitlementUpsertBulk) SetMetadata(v map[string]string) *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *EntitlementUpsertBulk) UpdateMetadata() *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *EntitlementUpsertBulk) ClearMetadata() *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *EntitlementUpsertBulk) SetUpdatedAt(v time.Time) *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *EntitlementUpsertBulk) UpdateUpdatedAt() *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *EntitlementUpsertBulk) SetDeletedAt(v time.Time) *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *EntitlementUpsertBulk) UpdateDeletedAt() *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *EntitlementUpsertBulk) ClearDeletedAt() *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.ClearDeletedAt() + }) +} + +// SetActiveTo sets the "active_to" field. +func (u *EntitlementUpsertBulk) SetActiveTo(v time.Time) *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.SetActiveTo(v) + }) +} + +// UpdateActiveTo sets the "active_to" field to the value that was provided on create. +func (u *EntitlementUpsertBulk) UpdateActiveTo() *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.UpdateActiveTo() + }) +} + +// ClearActiveTo clears the value of the "active_to" field. +func (u *EntitlementUpsertBulk) ClearActiveTo() *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.ClearActiveTo() + }) +} + +// SetConfig sets the "config" field. +func (u *EntitlementUpsertBulk) SetConfig(v string) *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.SetConfig(v) + }) +} + +// UpdateConfig sets the "config" field to the value that was provided on create. +func (u *EntitlementUpsertBulk) UpdateConfig() *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.UpdateConfig() + }) +} + +// ClearConfig clears the value of the "config" field. +func (u *EntitlementUpsertBulk) ClearConfig() *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.ClearConfig() + }) +} + +// SetUsagePeriodAnchor sets the "usage_period_anchor" field. +func (u *EntitlementUpsertBulk) SetUsagePeriodAnchor(v time.Time) *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.SetUsagePeriodAnchor(v) + }) +} + +// UpdateUsagePeriodAnchor sets the "usage_period_anchor" field to the value that was provided on create. +func (u *EntitlementUpsertBulk) UpdateUsagePeriodAnchor() *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.UpdateUsagePeriodAnchor() + }) +} + +// ClearUsagePeriodAnchor clears the value of the "usage_period_anchor" field. +func (u *EntitlementUpsertBulk) ClearUsagePeriodAnchor() *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.ClearUsagePeriodAnchor() + }) +} + +// SetCurrentUsagePeriodStart sets the "current_usage_period_start" field. +func (u *EntitlementUpsertBulk) SetCurrentUsagePeriodStart(v time.Time) *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.SetCurrentUsagePeriodStart(v) + }) +} + +// UpdateCurrentUsagePeriodStart sets the "current_usage_period_start" field to the value that was provided on create. +func (u *EntitlementUpsertBulk) UpdateCurrentUsagePeriodStart() *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.UpdateCurrentUsagePeriodStart() + }) +} + +// ClearCurrentUsagePeriodStart clears the value of the "current_usage_period_start" field. +func (u *EntitlementUpsertBulk) ClearCurrentUsagePeriodStart() *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.ClearCurrentUsagePeriodStart() + }) +} + +// SetCurrentUsagePeriodEnd sets the "current_usage_period_end" field. +func (u *EntitlementUpsertBulk) SetCurrentUsagePeriodEnd(v time.Time) *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.SetCurrentUsagePeriodEnd(v) + }) +} + +// UpdateCurrentUsagePeriodEnd sets the "current_usage_period_end" field to the value that was provided on create. +func (u *EntitlementUpsertBulk) UpdateCurrentUsagePeriodEnd() *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.UpdateCurrentUsagePeriodEnd() + }) +} + +// ClearCurrentUsagePeriodEnd clears the value of the "current_usage_period_end" field. +func (u *EntitlementUpsertBulk) ClearCurrentUsagePeriodEnd() *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.ClearCurrentUsagePeriodEnd() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *EntitlementUpsertBulk) SetAnnotations(v models.Annotations) *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *EntitlementUpsertBulk) UpdateAnnotations() *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *EntitlementUpsertBulk) ClearAnnotations() *EntitlementUpsertBulk { + return u.Update(func(s *EntitlementUpsert) { + s.ClearAnnotations() + }) +} + +// Exec executes the query. +func (u *EntitlementUpsertBulk) 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 EntitlementCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for EntitlementCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *EntitlementUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/entitlement_delete.go b/ent/db/entitlement_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..c91c2c4ebe18611e9eac138c4c73c7064ebbf287 --- /dev/null +++ b/ent/db/entitlement_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/entitlement" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// EntitlementDelete is the builder for deleting a Entitlement entity. +type EntitlementDelete struct { + config + hooks []Hook + mutation *EntitlementMutation +} + +// Where appends a list predicates to the EntitlementDelete builder. +func (_d *EntitlementDelete) Where(ps ...predicate.Entitlement) *EntitlementDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *EntitlementDelete) 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 *EntitlementDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *EntitlementDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(entitlement.Table, sqlgraph.NewFieldSpec(entitlement.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 +} + +// EntitlementDeleteOne is the builder for deleting a single Entitlement entity. +type EntitlementDeleteOne struct { + _d *EntitlementDelete +} + +// Where appends a list predicates to the EntitlementDelete builder. +func (_d *EntitlementDeleteOne) Where(ps ...predicate.Entitlement) *EntitlementDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *EntitlementDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{entitlement.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *EntitlementDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/entitlement_query.go b/ent/db/entitlement_query.go new file mode 100644 index 0000000000000000000000000000000000000000..75001e60ea69ac3949e99cf4604f1dafcba85cab --- /dev/null +++ b/ent/db/entitlement_query.go @@ -0,0 +1,1020 @@ +// 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/balancesnapshot" + "github.com/openmeterio/openmeter/openmeter/ent/db/customer" + "github.com/openmeterio/openmeter/openmeter/ent/db/entitlement" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + dbgrant "github.com/openmeterio/openmeter/openmeter/ent/db/grant" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/openmeter/ent/db/usagereset" +) + +// EntitlementQuery is the builder for querying Entitlement entities. +type EntitlementQuery struct { + config + ctx *QueryContext + order []entitlement.OrderOption + inters []Interceptor + predicates []predicate.Entitlement + withUsageReset *UsageResetQuery + withGrant *GrantQuery + withBalanceSnapshot *BalanceSnapshotQuery + withSubscriptionItem *SubscriptionItemQuery + withFeature *FeatureQuery + withCustomer *CustomerQuery + 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 EntitlementQuery builder. +func (_q *EntitlementQuery) Where(ps ...predicate.Entitlement) *EntitlementQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *EntitlementQuery) Limit(limit int) *EntitlementQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *EntitlementQuery) Offset(offset int) *EntitlementQuery { + _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 *EntitlementQuery) Unique(unique bool) *EntitlementQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *EntitlementQuery) Order(o ...entitlement.OrderOption) *EntitlementQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryUsageReset chains the current query on the "usage_reset" edge. +func (_q *EntitlementQuery) QueryUsageReset() *UsageResetQuery { + query := (&UsageResetClient{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(entitlement.Table, entitlement.FieldID, selector), + sqlgraph.To(usagereset.Table, usagereset.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, entitlement.UsageResetTable, entitlement.UsageResetColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryGrant chains the current query on the "grant" edge. +func (_q *EntitlementQuery) QueryGrant() *GrantQuery { + query := (&GrantClient{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(entitlement.Table, entitlement.FieldID, selector), + sqlgraph.To(dbgrant.Table, dbgrant.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, entitlement.GrantTable, entitlement.GrantColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryBalanceSnapshot chains the current query on the "balance_snapshot" edge. +func (_q *EntitlementQuery) QueryBalanceSnapshot() *BalanceSnapshotQuery { + query := (&BalanceSnapshotClient{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(entitlement.Table, entitlement.FieldID, selector), + sqlgraph.To(balancesnapshot.Table, balancesnapshot.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, entitlement.BalanceSnapshotTable, entitlement.BalanceSnapshotColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySubscriptionItem chains the current query on the "subscription_item" edge. +func (_q *EntitlementQuery) QuerySubscriptionItem() *SubscriptionItemQuery { + query := (&SubscriptionItemClient{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(entitlement.Table, entitlement.FieldID, selector), + sqlgraph.To(subscriptionitem.Table, subscriptionitem.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, entitlement.SubscriptionItemTable, entitlement.SubscriptionItemColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryFeature chains the current query on the "feature" edge. +func (_q *EntitlementQuery) QueryFeature() *FeatureQuery { + query := (&FeatureClient{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(entitlement.Table, entitlement.FieldID, selector), + sqlgraph.To(dbfeature.Table, dbfeature.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, entitlement.FeatureTable, entitlement.FeatureColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCustomer chains the current query on the "customer" edge. +func (_q *EntitlementQuery) QueryCustomer() *CustomerQuery { + query := (&CustomerClient{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(entitlement.Table, entitlement.FieldID, selector), + sqlgraph.To(customer.Table, customer.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, entitlement.CustomerTable, entitlement.CustomerColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Entitlement entity from the query. +// Returns a *NotFoundError when no Entitlement was found. +func (_q *EntitlementQuery) First(ctx context.Context) (*Entitlement, 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{entitlement.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *EntitlementQuery) FirstX(ctx context.Context) *Entitlement { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Entitlement ID from the query. +// Returns a *NotFoundError when no Entitlement ID was found. +func (_q *EntitlementQuery) 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{entitlement.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *EntitlementQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Entitlement entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Entitlement entity is found. +// Returns a *NotFoundError when no Entitlement entities are found. +func (_q *EntitlementQuery) Only(ctx context.Context) (*Entitlement, 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{entitlement.Label} + default: + return nil, &NotSingularError{entitlement.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *EntitlementQuery) OnlyX(ctx context.Context) *Entitlement { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Entitlement ID in the query. +// Returns a *NotSingularError when more than one Entitlement ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *EntitlementQuery) 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{entitlement.Label} + default: + err = &NotSingularError{entitlement.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *EntitlementQuery) 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 Entitlements. +func (_q *EntitlementQuery) All(ctx context.Context) ([]*Entitlement, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Entitlement, *EntitlementQuery]() + return withInterceptors[[]*Entitlement](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *EntitlementQuery) AllX(ctx context.Context) []*Entitlement { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Entitlement IDs. +func (_q *EntitlementQuery) 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(entitlement.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *EntitlementQuery) 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 *EntitlementQuery) 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[*EntitlementQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *EntitlementQuery) 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 *EntitlementQuery) 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 *EntitlementQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the EntitlementQuery 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 *EntitlementQuery) Clone() *EntitlementQuery { + if _q == nil { + return nil + } + return &EntitlementQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]entitlement.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Entitlement{}, _q.predicates...), + withUsageReset: _q.withUsageReset.Clone(), + withGrant: _q.withGrant.Clone(), + withBalanceSnapshot: _q.withBalanceSnapshot.Clone(), + withSubscriptionItem: _q.withSubscriptionItem.Clone(), + withFeature: _q.withFeature.Clone(), + withCustomer: _q.withCustomer.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithUsageReset tells the query-builder to eager-load the nodes that are connected to +// the "usage_reset" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *EntitlementQuery) WithUsageReset(opts ...func(*UsageResetQuery)) *EntitlementQuery { + query := (&UsageResetClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withUsageReset = query + return _q +} + +// WithGrant tells the query-builder to eager-load the nodes that are connected to +// the "grant" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *EntitlementQuery) WithGrant(opts ...func(*GrantQuery)) *EntitlementQuery { + query := (&GrantClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withGrant = query + return _q +} + +// WithBalanceSnapshot tells the query-builder to eager-load the nodes that are connected to +// the "balance_snapshot" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *EntitlementQuery) WithBalanceSnapshot(opts ...func(*BalanceSnapshotQuery)) *EntitlementQuery { + query := (&BalanceSnapshotClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBalanceSnapshot = query + return _q +} + +// WithSubscriptionItem tells the query-builder to eager-load the nodes that are connected to +// the "subscription_item" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *EntitlementQuery) WithSubscriptionItem(opts ...func(*SubscriptionItemQuery)) *EntitlementQuery { + query := (&SubscriptionItemClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSubscriptionItem = query + return _q +} + +// WithFeature tells the query-builder to eager-load the nodes that are connected to +// the "feature" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *EntitlementQuery) WithFeature(opts ...func(*FeatureQuery)) *EntitlementQuery { + query := (&FeatureClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withFeature = query + return _q +} + +// WithCustomer tells the query-builder to eager-load the nodes that are connected to +// the "customer" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *EntitlementQuery) WithCustomer(opts ...func(*CustomerQuery)) *EntitlementQuery { + query := (&CustomerClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCustomer = 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.Entitlement.Query(). +// GroupBy(entitlement.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *EntitlementQuery) GroupBy(field string, fields ...string) *EntitlementGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &EntitlementGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = entitlement.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.Entitlement.Query(). +// Select(entitlement.FieldNamespace). +// Scan(ctx, &v) +func (_q *EntitlementQuery) Select(fields ...string) *EntitlementSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &EntitlementSelect{EntitlementQuery: _q} + sbuild.label = entitlement.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a EntitlementSelect configured with the given aggregations. +func (_q *EntitlementQuery) Aggregate(fns ...AggregateFunc) *EntitlementSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *EntitlementQuery) 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 !entitlement.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 *EntitlementQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Entitlement, error) { + var ( + nodes = []*Entitlement{} + _spec = _q.querySpec() + loadedTypes = [6]bool{ + _q.withUsageReset != nil, + _q.withGrant != nil, + _q.withBalanceSnapshot != nil, + _q.withSubscriptionItem != nil, + _q.withFeature != nil, + _q.withCustomer != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Entitlement).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Entitlement{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.withUsageReset; query != nil { + if err := _q.loadUsageReset(ctx, query, nodes, + func(n *Entitlement) { n.Edges.UsageReset = []*UsageReset{} }, + func(n *Entitlement, e *UsageReset) { n.Edges.UsageReset = append(n.Edges.UsageReset, e) }); err != nil { + return nil, err + } + } + if query := _q.withGrant; query != nil { + if err := _q.loadGrant(ctx, query, nodes, + func(n *Entitlement) { n.Edges.Grant = []*Grant{} }, + func(n *Entitlement, e *Grant) { n.Edges.Grant = append(n.Edges.Grant, e) }); err != nil { + return nil, err + } + } + if query := _q.withBalanceSnapshot; query != nil { + if err := _q.loadBalanceSnapshot(ctx, query, nodes, + func(n *Entitlement) { n.Edges.BalanceSnapshot = []*BalanceSnapshot{} }, + func(n *Entitlement, e *BalanceSnapshot) { n.Edges.BalanceSnapshot = append(n.Edges.BalanceSnapshot, e) }); err != nil { + return nil, err + } + } + if query := _q.withSubscriptionItem; query != nil { + if err := _q.loadSubscriptionItem(ctx, query, nodes, + func(n *Entitlement) { n.Edges.SubscriptionItem = []*SubscriptionItem{} }, + func(n *Entitlement, e *SubscriptionItem) { + n.Edges.SubscriptionItem = append(n.Edges.SubscriptionItem, e) + }); err != nil { + return nil, err + } + } + if query := _q.withFeature; query != nil { + if err := _q.loadFeature(ctx, query, nodes, nil, + func(n *Entitlement, e *Feature) { n.Edges.Feature = e }); err != nil { + return nil, err + } + } + if query := _q.withCustomer; query != nil { + if err := _q.loadCustomer(ctx, query, nodes, nil, + func(n *Entitlement, e *Customer) { n.Edges.Customer = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *EntitlementQuery) loadUsageReset(ctx context.Context, query *UsageResetQuery, nodes []*Entitlement, init func(*Entitlement), assign func(*Entitlement, *UsageReset)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Entitlement) + 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(usagereset.FieldEntitlementID) + } + query.Where(predicate.UsageReset(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(entitlement.UsageResetColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.EntitlementID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "entitlement_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *EntitlementQuery) loadGrant(ctx context.Context, query *GrantQuery, nodes []*Entitlement, init func(*Entitlement), assign func(*Entitlement, *Grant)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Entitlement) + 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(dbgrant.FieldOwnerID) + } + query.Where(predicate.Grant(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(entitlement.GrantColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.OwnerID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "owner_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *EntitlementQuery) loadBalanceSnapshot(ctx context.Context, query *BalanceSnapshotQuery, nodes []*Entitlement, init func(*Entitlement), assign func(*Entitlement, *BalanceSnapshot)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Entitlement) + 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(balancesnapshot.FieldOwnerID) + } + query.Where(predicate.BalanceSnapshot(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(entitlement.BalanceSnapshotColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.OwnerID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "owner_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *EntitlementQuery) loadSubscriptionItem(ctx context.Context, query *SubscriptionItemQuery, nodes []*Entitlement, init func(*Entitlement), assign func(*Entitlement, *SubscriptionItem)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Entitlement) + 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(subscriptionitem.FieldEntitlementID) + } + query.Where(predicate.SubscriptionItem(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(entitlement.SubscriptionItemColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.EntitlementID + if fk == nil { + return fmt.Errorf(`foreign-key "entitlement_id" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "entitlement_id" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *EntitlementQuery) loadFeature(ctx context.Context, query *FeatureQuery, nodes []*Entitlement, init func(*Entitlement), assign func(*Entitlement, *Feature)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*Entitlement) + for i := range nodes { + fk := nodes[i].FeatureID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(dbfeature.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 "feature_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *EntitlementQuery) loadCustomer(ctx context.Context, query *CustomerQuery, nodes []*Entitlement, init func(*Entitlement), assign func(*Entitlement, *Customer)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*Entitlement) + for i := range nodes { + fk := nodes[i].CustomerID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(customer.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 "customer_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *EntitlementQuery) 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 *EntitlementQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(entitlement.Table, entitlement.Columns, sqlgraph.NewFieldSpec(entitlement.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, entitlement.FieldID) + for i := range fields { + if fields[i] != entitlement.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withFeature != nil { + _spec.Node.AddColumnOnce(entitlement.FieldFeatureID) + } + if _q.withCustomer != nil { + _spec.Node.AddColumnOnce(entitlement.FieldCustomerID) + } + } + 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 *EntitlementQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(entitlement.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = entitlement.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 *EntitlementQuery) ForUpdate(opts ...sql.LockOption) *EntitlementQuery { + 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 *EntitlementQuery) ForShare(opts ...sql.LockOption) *EntitlementQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// EntitlementGroupBy is the group-by builder for Entitlement entities. +type EntitlementGroupBy struct { + selector + build *EntitlementQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *EntitlementGroupBy) Aggregate(fns ...AggregateFunc) *EntitlementGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *EntitlementGroupBy) 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[*EntitlementQuery, *EntitlementGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *EntitlementGroupBy) sqlScan(ctx context.Context, root *EntitlementQuery, 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) +} + +// EntitlementSelect is the builder for selecting fields of Entitlement entities. +type EntitlementSelect struct { + *EntitlementQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *EntitlementSelect) Aggregate(fns ...AggregateFunc) *EntitlementSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *EntitlementSelect) 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[*EntitlementQuery, *EntitlementSelect](ctx, _s.EntitlementQuery, _s, _s.inters, v) +} + +func (_s *EntitlementSelect) sqlScan(ctx context.Context, root *EntitlementQuery, 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/ent/db/entitlement_update.go b/ent/db/entitlement_update.go new file mode 100644 index 0000000000000000000000000000000000000000..656cc3929798cba0c78bdbb4d38d8add3e27de65 --- /dev/null +++ b/ent/db/entitlement_update.go @@ -0,0 +1,1327 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/balancesnapshot" + "github.com/openmeterio/openmeter/openmeter/ent/db/entitlement" + dbgrant "github.com/openmeterio/openmeter/openmeter/ent/db/grant" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/openmeter/ent/db/usagereset" + "github.com/openmeterio/openmeter/pkg/models" +) + +// EntitlementUpdate is the builder for updating Entitlement entities. +type EntitlementUpdate struct { + config + hooks []Hook + mutation *EntitlementMutation +} + +// Where appends a list predicates to the EntitlementUpdate builder. +func (_u *EntitlementUpdate) Where(ps ...predicate.Entitlement) *EntitlementUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *EntitlementUpdate) SetMetadata(v map[string]string) *EntitlementUpdate { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *EntitlementUpdate) ClearMetadata() *EntitlementUpdate { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *EntitlementUpdate) SetUpdatedAt(v time.Time) *EntitlementUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *EntitlementUpdate) SetDeletedAt(v time.Time) *EntitlementUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *EntitlementUpdate) SetNillableDeletedAt(v *time.Time) *EntitlementUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *EntitlementUpdate) ClearDeletedAt() *EntitlementUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetActiveTo sets the "active_to" field. +func (_u *EntitlementUpdate) SetActiveTo(v time.Time) *EntitlementUpdate { + _u.mutation.SetActiveTo(v) + return _u +} + +// SetNillableActiveTo sets the "active_to" field if the given value is not nil. +func (_u *EntitlementUpdate) SetNillableActiveTo(v *time.Time) *EntitlementUpdate { + if v != nil { + _u.SetActiveTo(*v) + } + return _u +} + +// ClearActiveTo clears the value of the "active_to" field. +func (_u *EntitlementUpdate) ClearActiveTo() *EntitlementUpdate { + _u.mutation.ClearActiveTo() + return _u +} + +// SetConfig sets the "config" field. +func (_u *EntitlementUpdate) SetConfig(v string) *EntitlementUpdate { + _u.mutation.SetConfig(v) + return _u +} + +// SetNillableConfig sets the "config" field if the given value is not nil. +func (_u *EntitlementUpdate) SetNillableConfig(v *string) *EntitlementUpdate { + if v != nil { + _u.SetConfig(*v) + } + return _u +} + +// ClearConfig clears the value of the "config" field. +func (_u *EntitlementUpdate) ClearConfig() *EntitlementUpdate { + _u.mutation.ClearConfig() + return _u +} + +// SetUsagePeriodAnchor sets the "usage_period_anchor" field. +func (_u *EntitlementUpdate) SetUsagePeriodAnchor(v time.Time) *EntitlementUpdate { + _u.mutation.SetUsagePeriodAnchor(v) + return _u +} + +// SetNillableUsagePeriodAnchor sets the "usage_period_anchor" field if the given value is not nil. +func (_u *EntitlementUpdate) SetNillableUsagePeriodAnchor(v *time.Time) *EntitlementUpdate { + if v != nil { + _u.SetUsagePeriodAnchor(*v) + } + return _u +} + +// ClearUsagePeriodAnchor clears the value of the "usage_period_anchor" field. +func (_u *EntitlementUpdate) ClearUsagePeriodAnchor() *EntitlementUpdate { + _u.mutation.ClearUsagePeriodAnchor() + return _u +} + +// SetCurrentUsagePeriodStart sets the "current_usage_period_start" field. +func (_u *EntitlementUpdate) SetCurrentUsagePeriodStart(v time.Time) *EntitlementUpdate { + _u.mutation.SetCurrentUsagePeriodStart(v) + return _u +} + +// SetNillableCurrentUsagePeriodStart sets the "current_usage_period_start" field if the given value is not nil. +func (_u *EntitlementUpdate) SetNillableCurrentUsagePeriodStart(v *time.Time) *EntitlementUpdate { + if v != nil { + _u.SetCurrentUsagePeriodStart(*v) + } + return _u +} + +// ClearCurrentUsagePeriodStart clears the value of the "current_usage_period_start" field. +func (_u *EntitlementUpdate) ClearCurrentUsagePeriodStart() *EntitlementUpdate { + _u.mutation.ClearCurrentUsagePeriodStart() + return _u +} + +// SetCurrentUsagePeriodEnd sets the "current_usage_period_end" field. +func (_u *EntitlementUpdate) SetCurrentUsagePeriodEnd(v time.Time) *EntitlementUpdate { + _u.mutation.SetCurrentUsagePeriodEnd(v) + return _u +} + +// SetNillableCurrentUsagePeriodEnd sets the "current_usage_period_end" field if the given value is not nil. +func (_u *EntitlementUpdate) SetNillableCurrentUsagePeriodEnd(v *time.Time) *EntitlementUpdate { + if v != nil { + _u.SetCurrentUsagePeriodEnd(*v) + } + return _u +} + +// ClearCurrentUsagePeriodEnd clears the value of the "current_usage_period_end" field. +func (_u *EntitlementUpdate) ClearCurrentUsagePeriodEnd() *EntitlementUpdate { + _u.mutation.ClearCurrentUsagePeriodEnd() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *EntitlementUpdate) SetAnnotations(v models.Annotations) *EntitlementUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *EntitlementUpdate) ClearAnnotations() *EntitlementUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// AddUsageResetIDs adds the "usage_reset" edge to the UsageReset entity by IDs. +func (_u *EntitlementUpdate) AddUsageResetIDs(ids ...string) *EntitlementUpdate { + _u.mutation.AddUsageResetIDs(ids...) + return _u +} + +// AddUsageReset adds the "usage_reset" edges to the UsageReset entity. +func (_u *EntitlementUpdate) AddUsageReset(v ...*UsageReset) *EntitlementUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddUsageResetIDs(ids...) +} + +// AddGrantIDs adds the "grant" edge to the Grant entity by IDs. +func (_u *EntitlementUpdate) AddGrantIDs(ids ...string) *EntitlementUpdate { + _u.mutation.AddGrantIDs(ids...) + return _u +} + +// AddGrant adds the "grant" edges to the Grant entity. +func (_u *EntitlementUpdate) AddGrant(v ...*Grant) *EntitlementUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddGrantIDs(ids...) +} + +// AddBalanceSnapshotIDs adds the "balance_snapshot" edge to the BalanceSnapshot entity by IDs. +func (_u *EntitlementUpdate) AddBalanceSnapshotIDs(ids ...int) *EntitlementUpdate { + _u.mutation.AddBalanceSnapshotIDs(ids...) + return _u +} + +// AddBalanceSnapshot adds the "balance_snapshot" edges to the BalanceSnapshot entity. +func (_u *EntitlementUpdate) AddBalanceSnapshot(v ...*BalanceSnapshot) *EntitlementUpdate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddBalanceSnapshotIDs(ids...) +} + +// AddSubscriptionItemIDs adds the "subscription_item" edge to the SubscriptionItem entity by IDs. +func (_u *EntitlementUpdate) AddSubscriptionItemIDs(ids ...string) *EntitlementUpdate { + _u.mutation.AddSubscriptionItemIDs(ids...) + return _u +} + +// AddSubscriptionItem adds the "subscription_item" edges to the SubscriptionItem entity. +func (_u *EntitlementUpdate) AddSubscriptionItem(v ...*SubscriptionItem) *EntitlementUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSubscriptionItemIDs(ids...) +} + +// Mutation returns the EntitlementMutation object of the builder. +func (_u *EntitlementUpdate) Mutation() *EntitlementMutation { + return _u.mutation +} + +// ClearUsageReset clears all "usage_reset" edges to the UsageReset entity. +func (_u *EntitlementUpdate) ClearUsageReset() *EntitlementUpdate { + _u.mutation.ClearUsageReset() + return _u +} + +// RemoveUsageResetIDs removes the "usage_reset" edge to UsageReset entities by IDs. +func (_u *EntitlementUpdate) RemoveUsageResetIDs(ids ...string) *EntitlementUpdate { + _u.mutation.RemoveUsageResetIDs(ids...) + return _u +} + +// RemoveUsageReset removes "usage_reset" edges to UsageReset entities. +func (_u *EntitlementUpdate) RemoveUsageReset(v ...*UsageReset) *EntitlementUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveUsageResetIDs(ids...) +} + +// ClearGrant clears all "grant" edges to the Grant entity. +func (_u *EntitlementUpdate) ClearGrant() *EntitlementUpdate { + _u.mutation.ClearGrant() + return _u +} + +// RemoveGrantIDs removes the "grant" edge to Grant entities by IDs. +func (_u *EntitlementUpdate) RemoveGrantIDs(ids ...string) *EntitlementUpdate { + _u.mutation.RemoveGrantIDs(ids...) + return _u +} + +// RemoveGrant removes "grant" edges to Grant entities. +func (_u *EntitlementUpdate) RemoveGrant(v ...*Grant) *EntitlementUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveGrantIDs(ids...) +} + +// ClearBalanceSnapshot clears all "balance_snapshot" edges to the BalanceSnapshot entity. +func (_u *EntitlementUpdate) ClearBalanceSnapshot() *EntitlementUpdate { + _u.mutation.ClearBalanceSnapshot() + return _u +} + +// RemoveBalanceSnapshotIDs removes the "balance_snapshot" edge to BalanceSnapshot entities by IDs. +func (_u *EntitlementUpdate) RemoveBalanceSnapshotIDs(ids ...int) *EntitlementUpdate { + _u.mutation.RemoveBalanceSnapshotIDs(ids...) + return _u +} + +// RemoveBalanceSnapshot removes "balance_snapshot" edges to BalanceSnapshot entities. +func (_u *EntitlementUpdate) RemoveBalanceSnapshot(v ...*BalanceSnapshot) *EntitlementUpdate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveBalanceSnapshotIDs(ids...) +} + +// ClearSubscriptionItem clears all "subscription_item" edges to the SubscriptionItem entity. +func (_u *EntitlementUpdate) ClearSubscriptionItem() *EntitlementUpdate { + _u.mutation.ClearSubscriptionItem() + return _u +} + +// RemoveSubscriptionItemIDs removes the "subscription_item" edge to SubscriptionItem entities by IDs. +func (_u *EntitlementUpdate) RemoveSubscriptionItemIDs(ids ...string) *EntitlementUpdate { + _u.mutation.RemoveSubscriptionItemIDs(ids...) + return _u +} + +// RemoveSubscriptionItem removes "subscription_item" edges to SubscriptionItem entities. +func (_u *EntitlementUpdate) RemoveSubscriptionItem(v ...*SubscriptionItem) *EntitlementUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSubscriptionItemIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *EntitlementUpdate) 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 *EntitlementUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *EntitlementUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *EntitlementUpdate) 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 *EntitlementUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := entitlement.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *EntitlementUpdate) check() error { + if _u.mutation.FeatureCleared() && len(_u.mutation.FeatureIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "Entitlement.feature"`) + } + if _u.mutation.CustomerCleared() && len(_u.mutation.CustomerIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "Entitlement.customer"`) + } + return nil +} + +func (_u *EntitlementUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(entitlement.Table, entitlement.Columns, sqlgraph.NewFieldSpec(entitlement.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.Metadata(); ok { + _spec.SetField(entitlement.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(entitlement.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(entitlement.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(entitlement.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(entitlement.FieldDeletedAt, field.TypeTime) + } + if _u.mutation.ActiveFromCleared() { + _spec.ClearField(entitlement.FieldActiveFrom, field.TypeTime) + } + if value, ok := _u.mutation.ActiveTo(); ok { + _spec.SetField(entitlement.FieldActiveTo, field.TypeTime, value) + } + if _u.mutation.ActiveToCleared() { + _spec.ClearField(entitlement.FieldActiveTo, field.TypeTime) + } + if _u.mutation.MeasureUsageFromCleared() { + _spec.ClearField(entitlement.FieldMeasureUsageFrom, field.TypeTime) + } + if _u.mutation.IssueAfterResetCleared() { + _spec.ClearField(entitlement.FieldIssueAfterReset, field.TypeFloat64) + } + if _u.mutation.IssueAfterResetPriorityCleared() { + _spec.ClearField(entitlement.FieldIssueAfterResetPriority, field.TypeUint8) + } + if _u.mutation.IsSoftLimitCleared() { + _spec.ClearField(entitlement.FieldIsSoftLimit, field.TypeBool) + } + if _u.mutation.PreserveOverageAtResetCleared() { + _spec.ClearField(entitlement.FieldPreserveOverageAtReset, field.TypeBool) + } + if value, ok := _u.mutation.Config(); ok { + _spec.SetField(entitlement.FieldConfig, field.TypeString, value) + } + if _u.mutation.ConfigCleared() { + _spec.ClearField(entitlement.FieldConfig, field.TypeString) + } + if _u.mutation.UsagePeriodIntervalCleared() { + _spec.ClearField(entitlement.FieldUsagePeriodInterval, field.TypeString) + } + if value, ok := _u.mutation.UsagePeriodAnchor(); ok { + _spec.SetField(entitlement.FieldUsagePeriodAnchor, field.TypeTime, value) + } + if _u.mutation.UsagePeriodAnchorCleared() { + _spec.ClearField(entitlement.FieldUsagePeriodAnchor, field.TypeTime) + } + if value, ok := _u.mutation.CurrentUsagePeriodStart(); ok { + _spec.SetField(entitlement.FieldCurrentUsagePeriodStart, field.TypeTime, value) + } + if _u.mutation.CurrentUsagePeriodStartCleared() { + _spec.ClearField(entitlement.FieldCurrentUsagePeriodStart, field.TypeTime) + } + if value, ok := _u.mutation.CurrentUsagePeriodEnd(); ok { + _spec.SetField(entitlement.FieldCurrentUsagePeriodEnd, field.TypeTime, value) + } + if _u.mutation.CurrentUsagePeriodEndCleared() { + _spec.ClearField(entitlement.FieldCurrentUsagePeriodEnd, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + vv, err := entitlement.ValueScanner.Annotations.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(entitlement.FieldAnnotations, field.TypeString, vv) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(entitlement.FieldAnnotations, field.TypeString) + } + if _u.mutation.UsageResetCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.UsageResetTable, + Columns: []string{entitlement.UsageResetColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usagereset.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedUsageResetIDs(); len(nodes) > 0 && !_u.mutation.UsageResetCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.UsageResetTable, + Columns: []string{entitlement.UsageResetColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usagereset.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.UsageResetIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.UsageResetTable, + Columns: []string{entitlement.UsageResetColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usagereset.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.GrantCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.GrantTable, + Columns: []string{entitlement.GrantColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbgrant.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedGrantIDs(); len(nodes) > 0 && !_u.mutation.GrantCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.GrantTable, + Columns: []string{entitlement.GrantColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbgrant.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.GrantIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.GrantTable, + Columns: []string{entitlement.GrantColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbgrant.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.BalanceSnapshotCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.BalanceSnapshotTable, + Columns: []string{entitlement.BalanceSnapshotColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(balancesnapshot.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedBalanceSnapshotIDs(); len(nodes) > 0 && !_u.mutation.BalanceSnapshotCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.BalanceSnapshotTable, + Columns: []string{entitlement.BalanceSnapshotColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(balancesnapshot.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BalanceSnapshotIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.BalanceSnapshotTable, + Columns: []string{entitlement.BalanceSnapshotColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(balancesnapshot.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.SubscriptionItemCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.SubscriptionItemTable, + Columns: []string{entitlement.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSubscriptionItemIDs(); len(nodes) > 0 && !_u.mutation.SubscriptionItemCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.SubscriptionItemTable, + Columns: []string{entitlement.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.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.SubscriptionItemIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.SubscriptionItemTable, + Columns: []string{entitlement.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.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{entitlement.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// EntitlementUpdateOne is the builder for updating a single Entitlement entity. +type EntitlementUpdateOne struct { + config + fields []string + hooks []Hook + mutation *EntitlementMutation +} + +// SetMetadata sets the "metadata" field. +func (_u *EntitlementUpdateOne) SetMetadata(v map[string]string) *EntitlementUpdateOne { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *EntitlementUpdateOne) ClearMetadata() *EntitlementUpdateOne { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *EntitlementUpdateOne) SetUpdatedAt(v time.Time) *EntitlementUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *EntitlementUpdateOne) SetDeletedAt(v time.Time) *EntitlementUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *EntitlementUpdateOne) SetNillableDeletedAt(v *time.Time) *EntitlementUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *EntitlementUpdateOne) ClearDeletedAt() *EntitlementUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetActiveTo sets the "active_to" field. +func (_u *EntitlementUpdateOne) SetActiveTo(v time.Time) *EntitlementUpdateOne { + _u.mutation.SetActiveTo(v) + return _u +} + +// SetNillableActiveTo sets the "active_to" field if the given value is not nil. +func (_u *EntitlementUpdateOne) SetNillableActiveTo(v *time.Time) *EntitlementUpdateOne { + if v != nil { + _u.SetActiveTo(*v) + } + return _u +} + +// ClearActiveTo clears the value of the "active_to" field. +func (_u *EntitlementUpdateOne) ClearActiveTo() *EntitlementUpdateOne { + _u.mutation.ClearActiveTo() + return _u +} + +// SetConfig sets the "config" field. +func (_u *EntitlementUpdateOne) SetConfig(v string) *EntitlementUpdateOne { + _u.mutation.SetConfig(v) + return _u +} + +// SetNillableConfig sets the "config" field if the given value is not nil. +func (_u *EntitlementUpdateOne) SetNillableConfig(v *string) *EntitlementUpdateOne { + if v != nil { + _u.SetConfig(*v) + } + return _u +} + +// ClearConfig clears the value of the "config" field. +func (_u *EntitlementUpdateOne) ClearConfig() *EntitlementUpdateOne { + _u.mutation.ClearConfig() + return _u +} + +// SetUsagePeriodAnchor sets the "usage_period_anchor" field. +func (_u *EntitlementUpdateOne) SetUsagePeriodAnchor(v time.Time) *EntitlementUpdateOne { + _u.mutation.SetUsagePeriodAnchor(v) + return _u +} + +// SetNillableUsagePeriodAnchor sets the "usage_period_anchor" field if the given value is not nil. +func (_u *EntitlementUpdateOne) SetNillableUsagePeriodAnchor(v *time.Time) *EntitlementUpdateOne { + if v != nil { + _u.SetUsagePeriodAnchor(*v) + } + return _u +} + +// ClearUsagePeriodAnchor clears the value of the "usage_period_anchor" field. +func (_u *EntitlementUpdateOne) ClearUsagePeriodAnchor() *EntitlementUpdateOne { + _u.mutation.ClearUsagePeriodAnchor() + return _u +} + +// SetCurrentUsagePeriodStart sets the "current_usage_period_start" field. +func (_u *EntitlementUpdateOne) SetCurrentUsagePeriodStart(v time.Time) *EntitlementUpdateOne { + _u.mutation.SetCurrentUsagePeriodStart(v) + return _u +} + +// SetNillableCurrentUsagePeriodStart sets the "current_usage_period_start" field if the given value is not nil. +func (_u *EntitlementUpdateOne) SetNillableCurrentUsagePeriodStart(v *time.Time) *EntitlementUpdateOne { + if v != nil { + _u.SetCurrentUsagePeriodStart(*v) + } + return _u +} + +// ClearCurrentUsagePeriodStart clears the value of the "current_usage_period_start" field. +func (_u *EntitlementUpdateOne) ClearCurrentUsagePeriodStart() *EntitlementUpdateOne { + _u.mutation.ClearCurrentUsagePeriodStart() + return _u +} + +// SetCurrentUsagePeriodEnd sets the "current_usage_period_end" field. +func (_u *EntitlementUpdateOne) SetCurrentUsagePeriodEnd(v time.Time) *EntitlementUpdateOne { + _u.mutation.SetCurrentUsagePeriodEnd(v) + return _u +} + +// SetNillableCurrentUsagePeriodEnd sets the "current_usage_period_end" field if the given value is not nil. +func (_u *EntitlementUpdateOne) SetNillableCurrentUsagePeriodEnd(v *time.Time) *EntitlementUpdateOne { + if v != nil { + _u.SetCurrentUsagePeriodEnd(*v) + } + return _u +} + +// ClearCurrentUsagePeriodEnd clears the value of the "current_usage_period_end" field. +func (_u *EntitlementUpdateOne) ClearCurrentUsagePeriodEnd() *EntitlementUpdateOne { + _u.mutation.ClearCurrentUsagePeriodEnd() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *EntitlementUpdateOne) SetAnnotations(v models.Annotations) *EntitlementUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *EntitlementUpdateOne) ClearAnnotations() *EntitlementUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// AddUsageResetIDs adds the "usage_reset" edge to the UsageReset entity by IDs. +func (_u *EntitlementUpdateOne) AddUsageResetIDs(ids ...string) *EntitlementUpdateOne { + _u.mutation.AddUsageResetIDs(ids...) + return _u +} + +// AddUsageReset adds the "usage_reset" edges to the UsageReset entity. +func (_u *EntitlementUpdateOne) AddUsageReset(v ...*UsageReset) *EntitlementUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddUsageResetIDs(ids...) +} + +// AddGrantIDs adds the "grant" edge to the Grant entity by IDs. +func (_u *EntitlementUpdateOne) AddGrantIDs(ids ...string) *EntitlementUpdateOne { + _u.mutation.AddGrantIDs(ids...) + return _u +} + +// AddGrant adds the "grant" edges to the Grant entity. +func (_u *EntitlementUpdateOne) AddGrant(v ...*Grant) *EntitlementUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddGrantIDs(ids...) +} + +// AddBalanceSnapshotIDs adds the "balance_snapshot" edge to the BalanceSnapshot entity by IDs. +func (_u *EntitlementUpdateOne) AddBalanceSnapshotIDs(ids ...int) *EntitlementUpdateOne { + _u.mutation.AddBalanceSnapshotIDs(ids...) + return _u +} + +// AddBalanceSnapshot adds the "balance_snapshot" edges to the BalanceSnapshot entity. +func (_u *EntitlementUpdateOne) AddBalanceSnapshot(v ...*BalanceSnapshot) *EntitlementUpdateOne { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddBalanceSnapshotIDs(ids...) +} + +// AddSubscriptionItemIDs adds the "subscription_item" edge to the SubscriptionItem entity by IDs. +func (_u *EntitlementUpdateOne) AddSubscriptionItemIDs(ids ...string) *EntitlementUpdateOne { + _u.mutation.AddSubscriptionItemIDs(ids...) + return _u +} + +// AddSubscriptionItem adds the "subscription_item" edges to the SubscriptionItem entity. +func (_u *EntitlementUpdateOne) AddSubscriptionItem(v ...*SubscriptionItem) *EntitlementUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSubscriptionItemIDs(ids...) +} + +// Mutation returns the EntitlementMutation object of the builder. +func (_u *EntitlementUpdateOne) Mutation() *EntitlementMutation { + return _u.mutation +} + +// ClearUsageReset clears all "usage_reset" edges to the UsageReset entity. +func (_u *EntitlementUpdateOne) ClearUsageReset() *EntitlementUpdateOne { + _u.mutation.ClearUsageReset() + return _u +} + +// RemoveUsageResetIDs removes the "usage_reset" edge to UsageReset entities by IDs. +func (_u *EntitlementUpdateOne) RemoveUsageResetIDs(ids ...string) *EntitlementUpdateOne { + _u.mutation.RemoveUsageResetIDs(ids...) + return _u +} + +// RemoveUsageReset removes "usage_reset" edges to UsageReset entities. +func (_u *EntitlementUpdateOne) RemoveUsageReset(v ...*UsageReset) *EntitlementUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveUsageResetIDs(ids...) +} + +// ClearGrant clears all "grant" edges to the Grant entity. +func (_u *EntitlementUpdateOne) ClearGrant() *EntitlementUpdateOne { + _u.mutation.ClearGrant() + return _u +} + +// RemoveGrantIDs removes the "grant" edge to Grant entities by IDs. +func (_u *EntitlementUpdateOne) RemoveGrantIDs(ids ...string) *EntitlementUpdateOne { + _u.mutation.RemoveGrantIDs(ids...) + return _u +} + +// RemoveGrant removes "grant" edges to Grant entities. +func (_u *EntitlementUpdateOne) RemoveGrant(v ...*Grant) *EntitlementUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveGrantIDs(ids...) +} + +// ClearBalanceSnapshot clears all "balance_snapshot" edges to the BalanceSnapshot entity. +func (_u *EntitlementUpdateOne) ClearBalanceSnapshot() *EntitlementUpdateOne { + _u.mutation.ClearBalanceSnapshot() + return _u +} + +// RemoveBalanceSnapshotIDs removes the "balance_snapshot" edge to BalanceSnapshot entities by IDs. +func (_u *EntitlementUpdateOne) RemoveBalanceSnapshotIDs(ids ...int) *EntitlementUpdateOne { + _u.mutation.RemoveBalanceSnapshotIDs(ids...) + return _u +} + +// RemoveBalanceSnapshot removes "balance_snapshot" edges to BalanceSnapshot entities. +func (_u *EntitlementUpdateOne) RemoveBalanceSnapshot(v ...*BalanceSnapshot) *EntitlementUpdateOne { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveBalanceSnapshotIDs(ids...) +} + +// ClearSubscriptionItem clears all "subscription_item" edges to the SubscriptionItem entity. +func (_u *EntitlementUpdateOne) ClearSubscriptionItem() *EntitlementUpdateOne { + _u.mutation.ClearSubscriptionItem() + return _u +} + +// RemoveSubscriptionItemIDs removes the "subscription_item" edge to SubscriptionItem entities by IDs. +func (_u *EntitlementUpdateOne) RemoveSubscriptionItemIDs(ids ...string) *EntitlementUpdateOne { + _u.mutation.RemoveSubscriptionItemIDs(ids...) + return _u +} + +// RemoveSubscriptionItem removes "subscription_item" edges to SubscriptionItem entities. +func (_u *EntitlementUpdateOne) RemoveSubscriptionItem(v ...*SubscriptionItem) *EntitlementUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSubscriptionItemIDs(ids...) +} + +// Where appends a list predicates to the EntitlementUpdate builder. +func (_u *EntitlementUpdateOne) Where(ps ...predicate.Entitlement) *EntitlementUpdateOne { + _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 *EntitlementUpdateOne) Select(field string, fields ...string) *EntitlementUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Entitlement entity. +func (_u *EntitlementUpdateOne) Save(ctx context.Context) (*Entitlement, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *EntitlementUpdateOne) SaveX(ctx context.Context) *Entitlement { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *EntitlementUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *EntitlementUpdateOne) 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 *EntitlementUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := entitlement.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *EntitlementUpdateOne) check() error { + if _u.mutation.FeatureCleared() && len(_u.mutation.FeatureIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "Entitlement.feature"`) + } + if _u.mutation.CustomerCleared() && len(_u.mutation.CustomerIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "Entitlement.customer"`) + } + return nil +} + +func (_u *EntitlementUpdateOne) sqlSave(ctx context.Context) (_node *Entitlement, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(entitlement.Table, entitlement.Columns, sqlgraph.NewFieldSpec(entitlement.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "Entitlement.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, entitlement.FieldID) + for _, f := range fields { + if !entitlement.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != entitlement.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.Metadata(); ok { + _spec.SetField(entitlement.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(entitlement.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(entitlement.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(entitlement.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(entitlement.FieldDeletedAt, field.TypeTime) + } + if _u.mutation.ActiveFromCleared() { + _spec.ClearField(entitlement.FieldActiveFrom, field.TypeTime) + } + if value, ok := _u.mutation.ActiveTo(); ok { + _spec.SetField(entitlement.FieldActiveTo, field.TypeTime, value) + } + if _u.mutation.ActiveToCleared() { + _spec.ClearField(entitlement.FieldActiveTo, field.TypeTime) + } + if _u.mutation.MeasureUsageFromCleared() { + _spec.ClearField(entitlement.FieldMeasureUsageFrom, field.TypeTime) + } + if _u.mutation.IssueAfterResetCleared() { + _spec.ClearField(entitlement.FieldIssueAfterReset, field.TypeFloat64) + } + if _u.mutation.IssueAfterResetPriorityCleared() { + _spec.ClearField(entitlement.FieldIssueAfterResetPriority, field.TypeUint8) + } + if _u.mutation.IsSoftLimitCleared() { + _spec.ClearField(entitlement.FieldIsSoftLimit, field.TypeBool) + } + if _u.mutation.PreserveOverageAtResetCleared() { + _spec.ClearField(entitlement.FieldPreserveOverageAtReset, field.TypeBool) + } + if value, ok := _u.mutation.Config(); ok { + _spec.SetField(entitlement.FieldConfig, field.TypeString, value) + } + if _u.mutation.ConfigCleared() { + _spec.ClearField(entitlement.FieldConfig, field.TypeString) + } + if _u.mutation.UsagePeriodIntervalCleared() { + _spec.ClearField(entitlement.FieldUsagePeriodInterval, field.TypeString) + } + if value, ok := _u.mutation.UsagePeriodAnchor(); ok { + _spec.SetField(entitlement.FieldUsagePeriodAnchor, field.TypeTime, value) + } + if _u.mutation.UsagePeriodAnchorCleared() { + _spec.ClearField(entitlement.FieldUsagePeriodAnchor, field.TypeTime) + } + if value, ok := _u.mutation.CurrentUsagePeriodStart(); ok { + _spec.SetField(entitlement.FieldCurrentUsagePeriodStart, field.TypeTime, value) + } + if _u.mutation.CurrentUsagePeriodStartCleared() { + _spec.ClearField(entitlement.FieldCurrentUsagePeriodStart, field.TypeTime) + } + if value, ok := _u.mutation.CurrentUsagePeriodEnd(); ok { + _spec.SetField(entitlement.FieldCurrentUsagePeriodEnd, field.TypeTime, value) + } + if _u.mutation.CurrentUsagePeriodEndCleared() { + _spec.ClearField(entitlement.FieldCurrentUsagePeriodEnd, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + vv, err := entitlement.ValueScanner.Annotations.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(entitlement.FieldAnnotations, field.TypeString, vv) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(entitlement.FieldAnnotations, field.TypeString) + } + if _u.mutation.UsageResetCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.UsageResetTable, + Columns: []string{entitlement.UsageResetColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usagereset.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedUsageResetIDs(); len(nodes) > 0 && !_u.mutation.UsageResetCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.UsageResetTable, + Columns: []string{entitlement.UsageResetColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usagereset.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.UsageResetIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.UsageResetTable, + Columns: []string{entitlement.UsageResetColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usagereset.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.GrantCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.GrantTable, + Columns: []string{entitlement.GrantColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbgrant.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedGrantIDs(); len(nodes) > 0 && !_u.mutation.GrantCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.GrantTable, + Columns: []string{entitlement.GrantColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbgrant.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.GrantIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.GrantTable, + Columns: []string{entitlement.GrantColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbgrant.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.BalanceSnapshotCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.BalanceSnapshotTable, + Columns: []string{entitlement.BalanceSnapshotColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(balancesnapshot.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedBalanceSnapshotIDs(); len(nodes) > 0 && !_u.mutation.BalanceSnapshotCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.BalanceSnapshotTable, + Columns: []string{entitlement.BalanceSnapshotColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(balancesnapshot.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.BalanceSnapshotIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.BalanceSnapshotTable, + Columns: []string{entitlement.BalanceSnapshotColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(balancesnapshot.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.SubscriptionItemCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.SubscriptionItemTable, + Columns: []string{entitlement.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSubscriptionItemIDs(); len(nodes) > 0 && !_u.mutation.SubscriptionItemCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.SubscriptionItemTable, + Columns: []string{entitlement.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.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.SubscriptionItemIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: entitlement.SubscriptionItemTable, + Columns: []string{entitlement.SubscriptionItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(subscriptionitem.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &Entitlement{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{entitlement.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/ent/db/entmixinaccessor.go b/ent/db/entmixinaccessor.go new file mode 100644 index 0000000000000000000000000000000000000000..63c874edf977610c5d3d6ca27f9ea1a1670202a8 --- /dev/null +++ b/ent/db/entmixinaccessor.go @@ -0,0 +1,2982 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "time" + + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/billing" + "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/payment" + "github.com/openmeterio/openmeter/openmeter/billing/models/creditsapplied" + "github.com/openmeterio/openmeter/openmeter/billing/models/stddetailedline" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +func (e *Addon) GetID() string { + return e.ID +} + +func (e *Addon) GetNamespace() string { + return e.Namespace +} + +func (e *Addon) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *Addon) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *Addon) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *Addon) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *Addon) GetName() string { + return e.Name +} + +func (e *Addon) GetDescription() *string { + return e.Description +} + +func (e *Addon) GetKey() string { + return e.Key +} + +func (e *AddonRateCard) GetID() string { + return e.ID +} + +func (e *AddonRateCard) GetNamespace() string { + return e.Namespace +} + +func (e *AddonRateCard) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *AddonRateCard) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *AddonRateCard) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *AddonRateCard) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *AddonRateCard) GetName() string { + return e.Name +} + +func (e *AddonRateCard) GetDescription() *string { + return e.Description +} + +func (e *AddonRateCard) GetKey() string { + return e.Key +} + +func (e *AddonRateCard) GetTaxCodeID() *string { + return e.TaxCodeID +} + +func (e *AddonRateCard) GetTaxBehavior() *productcatalog.TaxBehavior { + return e.TaxBehavior +} + +func (e *App) GetID() string { + return e.ID +} + +func (e *App) GetNamespace() string { + return e.Namespace +} + +func (e *App) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *App) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *App) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *App) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *App) GetName() string { + return e.Name +} + +func (e *App) GetDescription() *string { + return e.Description +} + +func (e *AppCustomInvoicing) GetID() string { + return e.ID +} + +func (e *AppCustomInvoicing) GetNamespace() string { + return e.Namespace +} + +func (e *AppCustomInvoicing) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *AppCustomInvoicing) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *AppCustomInvoicing) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *AppCustomInvoicingCustomer) GetNamespace() string { + return e.Namespace +} + +func (e *AppCustomInvoicingCustomer) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *AppCustomInvoicingCustomer) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *AppCustomInvoicingCustomer) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *AppCustomInvoicingCustomer) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *AppCustomer) GetNamespace() string { + return e.Namespace +} + +func (e *AppCustomer) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *AppCustomer) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *AppCustomer) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *AppStripe) GetID() string { + return e.ID +} + +func (e *AppStripe) GetNamespace() string { + return e.Namespace +} + +func (e *AppStripe) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *AppStripe) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *AppStripe) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *AppStripeCustomer) GetNamespace() string { + return e.Namespace +} + +func (e *AppStripeCustomer) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *AppStripeCustomer) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *AppStripeCustomer) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *BalanceSnapshot) GetNamespace() string { + return e.Namespace +} + +func (e *BalanceSnapshot) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *BalanceSnapshot) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *BalanceSnapshot) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *BillingCustomerLock) GetID() string { + return e.ID +} + +func (e *BillingCustomerLock) GetNamespace() string { + return e.Namespace +} + +func (e *BillingCustomerOverride) GetID() string { + return e.ID +} + +func (e *BillingCustomerOverride) GetNamespace() string { + return e.Namespace +} + +func (e *BillingCustomerOverride) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *BillingCustomerOverride) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *BillingCustomerOverride) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *BillingCustomerOverride) GetTaxCodeID() *string { + return e.TaxCodeID +} + +func (e *BillingCustomerOverride) GetTaxBehavior() *productcatalog.TaxBehavior { + return e.TaxBehavior +} + +func (e *BillingInvoice) GetID() string { + return e.ID +} + +func (e *BillingInvoice) GetNamespace() string { + return e.Namespace +} + +func (e *BillingInvoice) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *BillingInvoice) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *BillingInvoice) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *BillingInvoice) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *BillingInvoice) GetSupplierAddressCountry() *models.CountryCode { + return e.SupplierAddressCountry +} + +func (e *BillingInvoice) GetSupplierAddressPostalCode() *string { + return e.SupplierAddressPostalCode +} + +func (e *BillingInvoice) GetSupplierAddressState() *string { + return e.SupplierAddressState +} + +func (e *BillingInvoice) GetSupplierAddressCity() *string { + return e.SupplierAddressCity +} + +func (e *BillingInvoice) GetSupplierAddressLine1() *string { + return e.SupplierAddressLine1 +} + +func (e *BillingInvoice) GetSupplierAddressLine2() *string { + return e.SupplierAddressLine2 +} + +func (e *BillingInvoice) GetSupplierAddressPhoneNumber() *string { + return e.SupplierAddressPhoneNumber +} + +func (e *BillingInvoice) GetCustomerAddressCountry() *models.CountryCode { + return e.CustomerAddressCountry +} + +func (e *BillingInvoice) GetCustomerAddressPostalCode() *string { + return e.CustomerAddressPostalCode +} + +func (e *BillingInvoice) GetCustomerAddressState() *string { + return e.CustomerAddressState +} + +func (e *BillingInvoice) GetCustomerAddressCity() *string { + return e.CustomerAddressCity +} + +func (e *BillingInvoice) GetCustomerAddressLine1() *string { + return e.CustomerAddressLine1 +} + +func (e *BillingInvoice) GetCustomerAddressLine2() *string { + return e.CustomerAddressLine2 +} + +func (e *BillingInvoice) GetCustomerAddressPhoneNumber() *string { + return e.CustomerAddressPhoneNumber +} + +func (e *BillingInvoice) GetAmount() alpacadecimal.Decimal { + return e.Amount +} + +func (e *BillingInvoice) GetTaxesTotal() alpacadecimal.Decimal { + return e.TaxesTotal +} + +func (e *BillingInvoice) GetTaxesInclusiveTotal() alpacadecimal.Decimal { + return e.TaxesInclusiveTotal +} + +func (e *BillingInvoice) GetTaxesExclusiveTotal() alpacadecimal.Decimal { + return e.TaxesExclusiveTotal +} + +func (e *BillingInvoice) GetChargesTotal() alpacadecimal.Decimal { + return e.ChargesTotal +} + +func (e *BillingInvoice) GetDiscountsTotal() alpacadecimal.Decimal { + return e.DiscountsTotal +} + +func (e *BillingInvoice) GetCreditsTotal() alpacadecimal.Decimal { + return e.CreditsTotal +} + +func (e *BillingInvoice) GetTotal() alpacadecimal.Decimal { + return e.Total +} + +func (e *BillingInvoice) GetInvoicingAppExternalID() *string { + return e.InvoicingAppExternalID +} + +func (e *BillingInvoice) GetPaymentAppExternalID() *string { + return e.PaymentAppExternalID +} + +func (e *BillingInvoice) GetTaxAppExternalID() *string { + return e.TaxAppExternalID +} + +func (e *BillingInvoiceFlatFeeLineConfig) GetID() string { + return e.ID +} + +func (e *BillingInvoiceFlatFeeLineConfig) GetNamespace() string { + return e.Namespace +} + +func (e *BillingInvoiceLine) GetID() string { + return e.ID +} + +func (e *BillingInvoiceLine) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *BillingInvoiceLine) GetNamespace() string { + return e.Namespace +} + +func (e *BillingInvoiceLine) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *BillingInvoiceLine) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *BillingInvoiceLine) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *BillingInvoiceLine) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *BillingInvoiceLine) GetName() string { + return e.Name +} + +func (e *BillingInvoiceLine) GetDescription() *string { + return e.Description +} + +func (e *BillingInvoiceLine) GetCurrency() currencyx.Code { + return e.Currency +} + +func (e *BillingInvoiceLine) GetTaxConfig() billing.TaxConfig { + return e.TaxConfig +} + +func (e *BillingInvoiceLine) GetTaxCodeID() *string { + return e.TaxCodeID +} + +func (e *BillingInvoiceLine) GetTaxBehavior() *productcatalog.TaxBehavior { + return e.TaxBehavior +} + +func (e *BillingInvoiceLine) GetAmount() alpacadecimal.Decimal { + return e.Amount +} + +func (e *BillingInvoiceLine) GetTaxesTotal() alpacadecimal.Decimal { + return e.TaxesTotal +} + +func (e *BillingInvoiceLine) GetTaxesInclusiveTotal() alpacadecimal.Decimal { + return e.TaxesInclusiveTotal +} + +func (e *BillingInvoiceLine) GetTaxesExclusiveTotal() alpacadecimal.Decimal { + return e.TaxesExclusiveTotal +} + +func (e *BillingInvoiceLine) GetChargesTotal() alpacadecimal.Decimal { + return e.ChargesTotal +} + +func (e *BillingInvoiceLine) GetDiscountsTotal() alpacadecimal.Decimal { + return e.DiscountsTotal +} + +func (e *BillingInvoiceLine) GetCreditsTotal() alpacadecimal.Decimal { + return e.CreditsTotal +} + +func (e *BillingInvoiceLine) GetTotal() alpacadecimal.Decimal { + return e.Total +} + +func (e *BillingInvoiceLine) GetInvoicingAppExternalID() *string { + return e.InvoicingAppExternalID +} + +func (e *BillingInvoiceLineDiscount) GetID() string { + return e.ID +} + +func (e *BillingInvoiceLineDiscount) GetNamespace() string { + return e.Namespace +} + +func (e *BillingInvoiceLineDiscount) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *BillingInvoiceLineDiscount) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *BillingInvoiceLineDiscount) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *BillingInvoiceLineDiscount) GetInvoicingAppExternalID() *string { + return e.InvoicingAppExternalID +} + +func (e *BillingInvoiceLineDiscount) GetLineID() string { + return e.LineID +} + +func (e *BillingInvoiceLineDiscount) GetChildUniqueReferenceID() *string { + return e.ChildUniqueReferenceID +} + +func (e *BillingInvoiceLineDiscount) GetDescription() *string { + return e.Description +} + +func (e *BillingInvoiceLineDiscount) GetReason() billing.DiscountReasonType { + return e.Reason +} + +func (e *BillingInvoiceLineUsageDiscount) GetID() string { + return e.ID +} + +func (e *BillingInvoiceLineUsageDiscount) GetNamespace() string { + return e.Namespace +} + +func (e *BillingInvoiceLineUsageDiscount) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *BillingInvoiceLineUsageDiscount) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *BillingInvoiceLineUsageDiscount) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *BillingInvoiceLineUsageDiscount) GetInvoicingAppExternalID() *string { + return e.InvoicingAppExternalID +} + +func (e *BillingInvoiceLineUsageDiscount) GetLineID() string { + return e.LineID +} + +func (e *BillingInvoiceLineUsageDiscount) GetChildUniqueReferenceID() *string { + return e.ChildUniqueReferenceID +} + +func (e *BillingInvoiceLineUsageDiscount) GetDescription() *string { + return e.Description +} + +func (e *BillingInvoiceLineUsageDiscount) GetReason() billing.DiscountReasonType { + return e.Reason +} + +func (e *BillingInvoiceSplitLineGroup) GetID() string { + return e.ID +} + +func (e *BillingInvoiceSplitLineGroup) GetNamespace() string { + return e.Namespace +} + +func (e *BillingInvoiceSplitLineGroup) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *BillingInvoiceSplitLineGroup) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *BillingInvoiceSplitLineGroup) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *BillingInvoiceSplitLineGroup) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *BillingInvoiceSplitLineGroup) GetName() string { + return e.Name +} + +func (e *BillingInvoiceSplitLineGroup) GetDescription() *string { + return e.Description +} + +func (e *BillingInvoiceUsageBasedLineConfig) GetID() string { + return e.ID +} + +func (e *BillingInvoiceUsageBasedLineConfig) GetNamespace() string { + return e.Namespace +} + +func (e *BillingInvoiceValidationIssue) GetID() string { + return e.ID +} + +func (e *BillingInvoiceValidationIssue) GetNamespace() string { + return e.Namespace +} + +func (e *BillingInvoiceValidationIssue) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *BillingInvoiceValidationIssue) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *BillingInvoiceValidationIssue) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *BillingProfile) GetID() string { + return e.ID +} + +func (e *BillingProfile) GetNamespace() string { + return e.Namespace +} + +func (e *BillingProfile) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *BillingProfile) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *BillingProfile) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *BillingProfile) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *BillingProfile) GetName() string { + return e.Name +} + +func (e *BillingProfile) GetDescription() *string { + return e.Description +} + +func (e *BillingProfile) GetSupplierAddressCountry() *models.CountryCode { + return e.SupplierAddressCountry +} + +func (e *BillingProfile) GetSupplierAddressPostalCode() *string { + return e.SupplierAddressPostalCode +} + +func (e *BillingProfile) GetSupplierAddressState() *string { + return e.SupplierAddressState +} + +func (e *BillingProfile) GetSupplierAddressCity() *string { + return e.SupplierAddressCity +} + +func (e *BillingProfile) GetSupplierAddressLine1() *string { + return e.SupplierAddressLine1 +} + +func (e *BillingProfile) GetSupplierAddressLine2() *string { + return e.SupplierAddressLine2 +} + +func (e *BillingProfile) GetSupplierAddressPhoneNumber() *string { + return e.SupplierAddressPhoneNumber +} + +func (e *BillingSequenceNumbers) GetNamespace() string { + return e.Namespace +} + +func (e *BillingStandardInvoiceDetailedLine) GetID() string { + return e.ID +} + +func (e *BillingStandardInvoiceDetailedLine) GetCurrency() currencyx.Code { + return e.Currency +} + +func (e *BillingStandardInvoiceDetailedLine) GetServicePeriodStart() time.Time { + return e.ServicePeriodStart +} + +func (e *BillingStandardInvoiceDetailedLine) GetServicePeriodEnd() time.Time { + return e.ServicePeriodEnd +} + +func (e *BillingStandardInvoiceDetailedLine) GetQuantity() alpacadecimal.Decimal { + return e.Quantity +} + +func (e *BillingStandardInvoiceDetailedLine) GetInvoicingAppExternalID() *string { + return e.InvoicingAppExternalID +} + +func (e *BillingStandardInvoiceDetailedLine) GetChildUniqueReferenceID() string { + return e.ChildUniqueReferenceID +} + +func (e *BillingStandardInvoiceDetailedLine) GetPerUnitAmount() alpacadecimal.Decimal { + return e.PerUnitAmount +} + +func (e *BillingStandardInvoiceDetailedLine) GetCategory() stddetailedline.Category { + return e.Category +} + +func (e *BillingStandardInvoiceDetailedLine) GetPaymentTerm() productcatalog.PaymentTermType { + return e.PaymentTerm +} + +func (e *BillingStandardInvoiceDetailedLine) GetIndex() *int { + return e.Index +} + +func (e *BillingStandardInvoiceDetailedLine) GetCreditsApplied() *creditsapplied.CreditsApplied { + return e.CreditsApplied +} + +func (e *BillingStandardInvoiceDetailedLine) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *BillingStandardInvoiceDetailedLine) GetNamespace() string { + return e.Namespace +} + +func (e *BillingStandardInvoiceDetailedLine) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *BillingStandardInvoiceDetailedLine) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *BillingStandardInvoiceDetailedLine) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *BillingStandardInvoiceDetailedLine) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *BillingStandardInvoiceDetailedLine) GetName() string { + return e.Name +} + +func (e *BillingStandardInvoiceDetailedLine) GetDescription() *string { + return e.Description +} + +func (e *BillingStandardInvoiceDetailedLine) GetAmount() alpacadecimal.Decimal { + return e.Amount +} + +func (e *BillingStandardInvoiceDetailedLine) GetTaxesTotal() alpacadecimal.Decimal { + return e.TaxesTotal +} + +func (e *BillingStandardInvoiceDetailedLine) GetTaxesInclusiveTotal() alpacadecimal.Decimal { + return e.TaxesInclusiveTotal +} + +func (e *BillingStandardInvoiceDetailedLine) GetTaxesExclusiveTotal() alpacadecimal.Decimal { + return e.TaxesExclusiveTotal +} + +func (e *BillingStandardInvoiceDetailedLine) GetChargesTotal() alpacadecimal.Decimal { + return e.ChargesTotal +} + +func (e *BillingStandardInvoiceDetailedLine) GetDiscountsTotal() alpacadecimal.Decimal { + return e.DiscountsTotal +} + +func (e *BillingStandardInvoiceDetailedLine) GetCreditsTotal() alpacadecimal.Decimal { + return e.CreditsTotal +} + +func (e *BillingStandardInvoiceDetailedLine) GetTotal() alpacadecimal.Decimal { + return e.Total +} + +func (e *BillingStandardInvoiceDetailedLineAmountDiscount) GetID() string { + return e.ID +} + +func (e *BillingStandardInvoiceDetailedLineAmountDiscount) GetNamespace() string { + return e.Namespace +} + +func (e *BillingStandardInvoiceDetailedLineAmountDiscount) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *BillingStandardInvoiceDetailedLineAmountDiscount) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *BillingStandardInvoiceDetailedLineAmountDiscount) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *BillingStandardInvoiceDetailedLineAmountDiscount) GetInvoicingAppExternalID() *string { + return e.InvoicingAppExternalID +} + +func (e *BillingStandardInvoiceDetailedLineAmountDiscount) GetLineID() string { + return e.LineID +} + +func (e *BillingStandardInvoiceDetailedLineAmountDiscount) GetChildUniqueReferenceID() *string { + return e.ChildUniqueReferenceID +} + +func (e *BillingStandardInvoiceDetailedLineAmountDiscount) GetDescription() *string { + return e.Description +} + +func (e *BillingStandardInvoiceDetailedLineAmountDiscount) GetReason() billing.DiscountReasonType { + return e.Reason +} + +func (e *BillingWorkflowConfig) GetID() string { + return e.ID +} + +func (e *BillingWorkflowConfig) GetNamespace() string { + return e.Namespace +} + +func (e *BillingWorkflowConfig) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *BillingWorkflowConfig) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *BillingWorkflowConfig) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *BillingWorkflowConfig) GetTaxCodeID() *string { + return e.TaxCodeID +} + +func (e *BillingWorkflowConfig) GetTaxBehavior() *productcatalog.TaxBehavior { + return e.TaxBehavior +} + +func (e *Charge) GetID() string { + return e.ID +} + +func (e *Charge) GetNamespace() string { + return e.Namespace +} + +func (e *ChargeCreditPurchase) GetID() string { + return e.ID +} + +func (e *ChargeCreditPurchase) GetCustomerID() string { + return e.CustomerID +} + +func (e *ChargeCreditPurchase) GetServicePeriodFrom() time.Time { + return e.ServicePeriodFrom +} + +func (e *ChargeCreditPurchase) GetServicePeriodTo() time.Time { + return e.ServicePeriodTo +} + +func (e *ChargeCreditPurchase) GetBillingPeriodFrom() time.Time { + return e.BillingPeriodFrom +} + +func (e *ChargeCreditPurchase) GetBillingPeriodTo() time.Time { + return e.BillingPeriodTo +} + +func (e *ChargeCreditPurchase) GetFullServicePeriodFrom() time.Time { + return e.FullServicePeriodFrom +} + +func (e *ChargeCreditPurchase) GetFullServicePeriodTo() time.Time { + return e.FullServicePeriodTo +} + +func (e *ChargeCreditPurchase) GetStatus() meta.ChargeStatus { + return e.Status +} + +func (e *ChargeCreditPurchase) GetUniqueReferenceID() *string { + return e.UniqueReferenceID +} + +func (e *ChargeCreditPurchase) GetCurrency() currencyx.Code { + return e.Currency +} + +func (e *ChargeCreditPurchase) GetManagedBy() billing.InvoiceLineManagedBy { + return e.ManagedBy +} + +func (e *ChargeCreditPurchase) GetSubscriptionID() *string { + return e.SubscriptionID +} + +func (e *ChargeCreditPurchase) GetSubscriptionPhaseID() *string { + return e.SubscriptionPhaseID +} + +func (e *ChargeCreditPurchase) GetSubscriptionItemID() *string { + return e.SubscriptionItemID +} + +func (e *ChargeCreditPurchase) GetAdvanceAfter() *time.Time { + return e.AdvanceAfter +} + +func (e *ChargeCreditPurchase) GetTaxCodeID() string { + return e.TaxCodeID +} + +func (e *ChargeCreditPurchase) GetTaxBehavior() *productcatalog.TaxBehavior { + return e.TaxBehavior +} + +func (e *ChargeCreditPurchase) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *ChargeCreditPurchase) GetNamespace() string { + return e.Namespace +} + +func (e *ChargeCreditPurchase) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *ChargeCreditPurchase) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *ChargeCreditPurchase) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *ChargeCreditPurchase) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *ChargeCreditPurchase) GetName() string { + return e.Name +} + +func (e *ChargeCreditPurchase) GetDescription() *string { + return e.Description +} + +func (e *ChargeCreditPurchaseCreditGrant) GetID() string { + return e.ID +} + +func (e *ChargeCreditPurchaseCreditGrant) GetNamespace() string { + return e.Namespace +} + +func (e *ChargeCreditPurchaseCreditGrant) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *ChargeCreditPurchaseCreditGrant) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *ChargeCreditPurchaseCreditGrant) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *ChargeCreditPurchaseExternalPayment) GetID() string { + return e.ID +} + +func (e *ChargeCreditPurchaseExternalPayment) GetServicePeriodFrom() time.Time { + return e.ServicePeriodFrom +} + +func (e *ChargeCreditPurchaseExternalPayment) GetServicePeriodTo() time.Time { + return e.ServicePeriodTo +} + +func (e *ChargeCreditPurchaseExternalPayment) GetStatus() payment.Status { + return e.Status +} + +func (e *ChargeCreditPurchaseExternalPayment) GetAmount() alpacadecimal.Decimal { + return e.Amount +} + +func (e *ChargeCreditPurchaseExternalPayment) GetAuthorizedTransactionGroupID() *string { + return e.AuthorizedTransactionGroupID +} + +func (e *ChargeCreditPurchaseExternalPayment) GetAuthorizedAt() *time.Time { + return e.AuthorizedAt +} + +func (e *ChargeCreditPurchaseExternalPayment) GetSettledTransactionGroupID() *string { + return e.SettledTransactionGroupID +} + +func (e *ChargeCreditPurchaseExternalPayment) GetSettledAt() *time.Time { + return e.SettledAt +} + +func (e *ChargeCreditPurchaseExternalPayment) GetNamespace() string { + return e.Namespace +} + +func (e *ChargeCreditPurchaseExternalPayment) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *ChargeCreditPurchaseExternalPayment) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *ChargeCreditPurchaseExternalPayment) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *ChargeCreditPurchaseExternalPayment) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *ChargeCreditPurchaseInvoicedPayment) GetID() string { + return e.ID +} + +func (e *ChargeCreditPurchaseInvoicedPayment) GetLineID() string { + return e.LineID +} + +func (e *ChargeCreditPurchaseInvoicedPayment) GetInvoiceID() string { + return e.InvoiceID +} + +func (e *ChargeCreditPurchaseInvoicedPayment) GetServicePeriodFrom() time.Time { + return e.ServicePeriodFrom +} + +func (e *ChargeCreditPurchaseInvoicedPayment) GetServicePeriodTo() time.Time { + return e.ServicePeriodTo +} + +func (e *ChargeCreditPurchaseInvoicedPayment) GetStatus() payment.Status { + return e.Status +} + +func (e *ChargeCreditPurchaseInvoicedPayment) GetAmount() alpacadecimal.Decimal { + return e.Amount +} + +func (e *ChargeCreditPurchaseInvoicedPayment) GetAuthorizedTransactionGroupID() *string { + return e.AuthorizedTransactionGroupID +} + +func (e *ChargeCreditPurchaseInvoicedPayment) GetAuthorizedAt() *time.Time { + return e.AuthorizedAt +} + +func (e *ChargeCreditPurchaseInvoicedPayment) GetSettledTransactionGroupID() *string { + return e.SettledTransactionGroupID +} + +func (e *ChargeCreditPurchaseInvoicedPayment) GetSettledAt() *time.Time { + return e.SettledAt +} + +func (e *ChargeCreditPurchaseInvoicedPayment) GetNamespace() string { + return e.Namespace +} + +func (e *ChargeCreditPurchaseInvoicedPayment) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *ChargeCreditPurchaseInvoicedPayment) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *ChargeCreditPurchaseInvoicedPayment) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *ChargeCreditPurchaseInvoicedPayment) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *ChargeFlatFee) GetID() string { + return e.ID +} + +func (e *ChargeFlatFee) GetCustomerID() string { + return e.CustomerID +} + +func (e *ChargeFlatFee) GetServicePeriodFrom() time.Time { + return e.ServicePeriodFrom +} + +func (e *ChargeFlatFee) GetServicePeriodTo() time.Time { + return e.ServicePeriodTo +} + +func (e *ChargeFlatFee) GetBillingPeriodFrom() time.Time { + return e.BillingPeriodFrom +} + +func (e *ChargeFlatFee) GetBillingPeriodTo() time.Time { + return e.BillingPeriodTo +} + +func (e *ChargeFlatFee) GetFullServicePeriodFrom() time.Time { + return e.FullServicePeriodFrom +} + +func (e *ChargeFlatFee) GetFullServicePeriodTo() time.Time { + return e.FullServicePeriodTo +} + +func (e *ChargeFlatFee) GetStatus() meta.ChargeStatus { + return e.Status +} + +func (e *ChargeFlatFee) GetUniqueReferenceID() *string { + return e.UniqueReferenceID +} + +func (e *ChargeFlatFee) GetCurrency() currencyx.Code { + return e.Currency +} + +func (e *ChargeFlatFee) GetManagedBy() billing.InvoiceLineManagedBy { + return e.ManagedBy +} + +func (e *ChargeFlatFee) GetSubscriptionID() *string { + return e.SubscriptionID +} + +func (e *ChargeFlatFee) GetSubscriptionPhaseID() *string { + return e.SubscriptionPhaseID +} + +func (e *ChargeFlatFee) GetSubscriptionItemID() *string { + return e.SubscriptionItemID +} + +func (e *ChargeFlatFee) GetAdvanceAfter() *time.Time { + return e.AdvanceAfter +} + +func (e *ChargeFlatFee) GetTaxCodeID() string { + return e.TaxCodeID +} + +func (e *ChargeFlatFee) GetTaxBehavior() *productcatalog.TaxBehavior { + return e.TaxBehavior +} + +func (e *ChargeFlatFee) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *ChargeFlatFee) GetNamespace() string { + return e.Namespace +} + +func (e *ChargeFlatFee) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *ChargeFlatFee) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *ChargeFlatFee) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *ChargeFlatFee) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *ChargeFlatFee) GetName() string { + return e.Name +} + +func (e *ChargeFlatFee) GetDescription() *string { + return e.Description +} + +func (e *ChargeFlatFeeOverride) GetID() string { + return e.ID +} + +func (e *ChargeFlatFeeOverride) GetNamespace() string { + return e.Namespace +} + +func (e *ChargeFlatFeeRun) GetID() string { + return e.ID +} + +func (e *ChargeFlatFeeRun) GetNamespace() string { + return e.Namespace +} + +func (e *ChargeFlatFeeRun) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *ChargeFlatFeeRun) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *ChargeFlatFeeRun) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *ChargeFlatFeeRun) GetAmount() alpacadecimal.Decimal { + return e.Amount +} + +func (e *ChargeFlatFeeRun) GetTaxesTotal() alpacadecimal.Decimal { + return e.TaxesTotal +} + +func (e *ChargeFlatFeeRun) GetTaxesInclusiveTotal() alpacadecimal.Decimal { + return e.TaxesInclusiveTotal +} + +func (e *ChargeFlatFeeRun) GetTaxesExclusiveTotal() alpacadecimal.Decimal { + return e.TaxesExclusiveTotal +} + +func (e *ChargeFlatFeeRun) GetChargesTotal() alpacadecimal.Decimal { + return e.ChargesTotal +} + +func (e *ChargeFlatFeeRun) GetDiscountsTotal() alpacadecimal.Decimal { + return e.DiscountsTotal +} + +func (e *ChargeFlatFeeRun) GetCreditsTotal() alpacadecimal.Decimal { + return e.CreditsTotal +} + +func (e *ChargeFlatFeeRun) GetTotal() alpacadecimal.Decimal { + return e.Total +} + +func (e *ChargeFlatFeeRunCreditAllocations) GetID() string { + return e.ID +} + +func (e *ChargeFlatFeeRunCreditAllocations) GetLineID() *string { + return e.LineID +} + +func (e *ChargeFlatFeeRunCreditAllocations) GetAmount() alpacadecimal.Decimal { + return e.Amount +} + +func (e *ChargeFlatFeeRunCreditAllocations) GetServicePeriodFrom() time.Time { + return e.ServicePeriodFrom +} + +func (e *ChargeFlatFeeRunCreditAllocations) GetServicePeriodTo() time.Time { + return e.ServicePeriodTo +} + +func (e *ChargeFlatFeeRunCreditAllocations) GetLedgerTransactionGroupID() string { + return e.LedgerTransactionGroupID +} + +func (e *ChargeFlatFeeRunCreditAllocations) GetSortHint() int { + return e.SortHint +} + +func (e *ChargeFlatFeeRunCreditAllocations) GetType() creditrealization.Type { + return e.Type +} + +func (e *ChargeFlatFeeRunCreditAllocations) GetCorrectsRealizationID() *string { + return e.CorrectsRealizationID +} + +func (e *ChargeFlatFeeRunCreditAllocations) GetNamespace() string { + return e.Namespace +} + +func (e *ChargeFlatFeeRunCreditAllocations) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *ChargeFlatFeeRunCreditAllocations) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *ChargeFlatFeeRunCreditAllocations) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *ChargeFlatFeeRunCreditAllocations) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *ChargeFlatFeeRunDetailedLine) GetID() string { + return e.ID +} + +func (e *ChargeFlatFeeRunDetailedLine) GetCurrency() currencyx.Code { + return e.Currency +} + +func (e *ChargeFlatFeeRunDetailedLine) GetServicePeriodStart() time.Time { + return e.ServicePeriodStart +} + +func (e *ChargeFlatFeeRunDetailedLine) GetServicePeriodEnd() time.Time { + return e.ServicePeriodEnd +} + +func (e *ChargeFlatFeeRunDetailedLine) GetQuantity() alpacadecimal.Decimal { + return e.Quantity +} + +func (e *ChargeFlatFeeRunDetailedLine) GetInvoicingAppExternalID() *string { + return e.InvoicingAppExternalID +} + +func (e *ChargeFlatFeeRunDetailedLine) GetChildUniqueReferenceID() string { + return e.ChildUniqueReferenceID +} + +func (e *ChargeFlatFeeRunDetailedLine) GetPerUnitAmount() alpacadecimal.Decimal { + return e.PerUnitAmount +} + +func (e *ChargeFlatFeeRunDetailedLine) GetCategory() stddetailedline.Category { + return e.Category +} + +func (e *ChargeFlatFeeRunDetailedLine) GetPaymentTerm() productcatalog.PaymentTermType { + return e.PaymentTerm +} + +func (e *ChargeFlatFeeRunDetailedLine) GetIndex() *int { + return e.Index +} + +func (e *ChargeFlatFeeRunDetailedLine) GetCreditsApplied() *creditsapplied.CreditsApplied { + return e.CreditsApplied +} + +func (e *ChargeFlatFeeRunDetailedLine) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *ChargeFlatFeeRunDetailedLine) GetNamespace() string { + return e.Namespace +} + +func (e *ChargeFlatFeeRunDetailedLine) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *ChargeFlatFeeRunDetailedLine) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *ChargeFlatFeeRunDetailedLine) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *ChargeFlatFeeRunDetailedLine) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *ChargeFlatFeeRunDetailedLine) GetName() string { + return e.Name +} + +func (e *ChargeFlatFeeRunDetailedLine) GetDescription() *string { + return e.Description +} + +func (e *ChargeFlatFeeRunDetailedLine) GetAmount() alpacadecimal.Decimal { + return e.Amount +} + +func (e *ChargeFlatFeeRunDetailedLine) GetTaxesTotal() alpacadecimal.Decimal { + return e.TaxesTotal +} + +func (e *ChargeFlatFeeRunDetailedLine) GetTaxesInclusiveTotal() alpacadecimal.Decimal { + return e.TaxesInclusiveTotal +} + +func (e *ChargeFlatFeeRunDetailedLine) GetTaxesExclusiveTotal() alpacadecimal.Decimal { + return e.TaxesExclusiveTotal +} + +func (e *ChargeFlatFeeRunDetailedLine) GetChargesTotal() alpacadecimal.Decimal { + return e.ChargesTotal +} + +func (e *ChargeFlatFeeRunDetailedLine) GetDiscountsTotal() alpacadecimal.Decimal { + return e.DiscountsTotal +} + +func (e *ChargeFlatFeeRunDetailedLine) GetCreditsTotal() alpacadecimal.Decimal { + return e.CreditsTotal +} + +func (e *ChargeFlatFeeRunDetailedLine) GetTotal() alpacadecimal.Decimal { + return e.Total +} + +func (e *ChargeFlatFeeRunInvoicedUsage) GetID() string { + return e.ID +} + +func (e *ChargeFlatFeeRunInvoicedUsage) GetServicePeriodFrom() time.Time { + return e.ServicePeriodFrom +} + +func (e *ChargeFlatFeeRunInvoicedUsage) GetServicePeriodTo() time.Time { + return e.ServicePeriodTo +} + +func (e *ChargeFlatFeeRunInvoicedUsage) GetLedgerTransactionGroupID() *string { + return e.LedgerTransactionGroupID +} + +func (e *ChargeFlatFeeRunInvoicedUsage) GetNamespace() string { + return e.Namespace +} + +func (e *ChargeFlatFeeRunInvoicedUsage) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *ChargeFlatFeeRunInvoicedUsage) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *ChargeFlatFeeRunInvoicedUsage) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *ChargeFlatFeeRunInvoicedUsage) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *ChargeFlatFeeRunInvoicedUsage) GetAmount() alpacadecimal.Decimal { + return e.Amount +} + +func (e *ChargeFlatFeeRunInvoicedUsage) GetTaxesTotal() alpacadecimal.Decimal { + return e.TaxesTotal +} + +func (e *ChargeFlatFeeRunInvoicedUsage) GetTaxesInclusiveTotal() alpacadecimal.Decimal { + return e.TaxesInclusiveTotal +} + +func (e *ChargeFlatFeeRunInvoicedUsage) GetTaxesExclusiveTotal() alpacadecimal.Decimal { + return e.TaxesExclusiveTotal +} + +func (e *ChargeFlatFeeRunInvoicedUsage) GetChargesTotal() alpacadecimal.Decimal { + return e.ChargesTotal +} + +func (e *ChargeFlatFeeRunInvoicedUsage) GetDiscountsTotal() alpacadecimal.Decimal { + return e.DiscountsTotal +} + +func (e *ChargeFlatFeeRunInvoicedUsage) GetCreditsTotal() alpacadecimal.Decimal { + return e.CreditsTotal +} + +func (e *ChargeFlatFeeRunInvoicedUsage) GetTotal() alpacadecimal.Decimal { + return e.Total +} + +func (e *ChargeFlatFeeRunPayment) GetID() string { + return e.ID +} + +func (e *ChargeFlatFeeRunPayment) GetLineID() string { + return e.LineID +} + +func (e *ChargeFlatFeeRunPayment) GetInvoiceID() string { + return e.InvoiceID +} + +func (e *ChargeFlatFeeRunPayment) GetServicePeriodFrom() time.Time { + return e.ServicePeriodFrom +} + +func (e *ChargeFlatFeeRunPayment) GetServicePeriodTo() time.Time { + return e.ServicePeriodTo +} + +func (e *ChargeFlatFeeRunPayment) GetStatus() payment.Status { + return e.Status +} + +func (e *ChargeFlatFeeRunPayment) GetAmount() alpacadecimal.Decimal { + return e.Amount +} + +func (e *ChargeFlatFeeRunPayment) GetAuthorizedTransactionGroupID() *string { + return e.AuthorizedTransactionGroupID +} + +func (e *ChargeFlatFeeRunPayment) GetAuthorizedAt() *time.Time { + return e.AuthorizedAt +} + +func (e *ChargeFlatFeeRunPayment) GetSettledTransactionGroupID() *string { + return e.SettledTransactionGroupID +} + +func (e *ChargeFlatFeeRunPayment) GetSettledAt() *time.Time { + return e.SettledAt +} + +func (e *ChargeFlatFeeRunPayment) GetNamespace() string { + return e.Namespace +} + +func (e *ChargeFlatFeeRunPayment) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *ChargeFlatFeeRunPayment) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *ChargeFlatFeeRunPayment) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *ChargeFlatFeeRunPayment) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *ChargeUsageBased) GetID() string { + return e.ID +} + +func (e *ChargeUsageBased) GetCustomerID() string { + return e.CustomerID +} + +func (e *ChargeUsageBased) GetServicePeriodFrom() time.Time { + return e.ServicePeriodFrom +} + +func (e *ChargeUsageBased) GetServicePeriodTo() time.Time { + return e.ServicePeriodTo +} + +func (e *ChargeUsageBased) GetBillingPeriodFrom() time.Time { + return e.BillingPeriodFrom +} + +func (e *ChargeUsageBased) GetBillingPeriodTo() time.Time { + return e.BillingPeriodTo +} + +func (e *ChargeUsageBased) GetFullServicePeriodFrom() time.Time { + return e.FullServicePeriodFrom +} + +func (e *ChargeUsageBased) GetFullServicePeriodTo() time.Time { + return e.FullServicePeriodTo +} + +func (e *ChargeUsageBased) GetStatus() meta.ChargeStatus { + return e.Status +} + +func (e *ChargeUsageBased) GetUniqueReferenceID() *string { + return e.UniqueReferenceID +} + +func (e *ChargeUsageBased) GetCurrency() currencyx.Code { + return e.Currency +} + +func (e *ChargeUsageBased) GetManagedBy() billing.InvoiceLineManagedBy { + return e.ManagedBy +} + +func (e *ChargeUsageBased) GetSubscriptionID() *string { + return e.SubscriptionID +} + +func (e *ChargeUsageBased) GetSubscriptionPhaseID() *string { + return e.SubscriptionPhaseID +} + +func (e *ChargeUsageBased) GetSubscriptionItemID() *string { + return e.SubscriptionItemID +} + +func (e *ChargeUsageBased) GetAdvanceAfter() *time.Time { + return e.AdvanceAfter +} + +func (e *ChargeUsageBased) GetTaxCodeID() string { + return e.TaxCodeID +} + +func (e *ChargeUsageBased) GetTaxBehavior() *productcatalog.TaxBehavior { + return e.TaxBehavior +} + +func (e *ChargeUsageBased) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *ChargeUsageBased) GetNamespace() string { + return e.Namespace +} + +func (e *ChargeUsageBased) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *ChargeUsageBased) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *ChargeUsageBased) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *ChargeUsageBased) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *ChargeUsageBased) GetName() string { + return e.Name +} + +func (e *ChargeUsageBased) GetDescription() *string { + return e.Description +} + +func (e *ChargeUsageBasedOverride) GetID() string { + return e.ID +} + +func (e *ChargeUsageBasedOverride) 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) GetSortHint() int { + return e.SortHint +} + +func (e *ChargeUsageBasedRunCreditAllocations) GetType() creditrealization.Type { + return e.Type +} + +func (e *ChargeUsageBasedRunCreditAllocations) GetCorrectsRealizationID() *string { + return e.CorrectsRealizationID +} + +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 *ChargeUsageBasedRunDetailedLine) GetID() string { + return e.ID +} + +func (e *ChargeUsageBasedRunDetailedLine) GetCurrency() currencyx.Code { + return e.Currency +} + +func (e *ChargeUsageBasedRunDetailedLine) GetServicePeriodStart() time.Time { + return e.ServicePeriodStart +} + +func (e *ChargeUsageBasedRunDetailedLine) GetServicePeriodEnd() time.Time { + return e.ServicePeriodEnd +} + +func (e *ChargeUsageBasedRunDetailedLine) GetQuantity() alpacadecimal.Decimal { + return e.Quantity +} + +func (e *ChargeUsageBasedRunDetailedLine) GetInvoicingAppExternalID() *string { + return e.InvoicingAppExternalID +} + +func (e *ChargeUsageBasedRunDetailedLine) GetChildUniqueReferenceID() string { + return e.ChildUniqueReferenceID +} + +func (e *ChargeUsageBasedRunDetailedLine) GetPerUnitAmount() alpacadecimal.Decimal { + return e.PerUnitAmount +} + +func (e *ChargeUsageBasedRunDetailedLine) GetCategory() stddetailedline.Category { + return e.Category +} + +func (e *ChargeUsageBasedRunDetailedLine) GetPaymentTerm() productcatalog.PaymentTermType { + return e.PaymentTerm +} + +func (e *ChargeUsageBasedRunDetailedLine) GetIndex() *int { + return e.Index +} + +func (e *ChargeUsageBasedRunDetailedLine) GetCreditsApplied() *creditsapplied.CreditsApplied { + return e.CreditsApplied +} + +func (e *ChargeUsageBasedRunDetailedLine) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *ChargeUsageBasedRunDetailedLine) GetNamespace() string { + return e.Namespace +} + +func (e *ChargeUsageBasedRunDetailedLine) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *ChargeUsageBasedRunDetailedLine) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *ChargeUsageBasedRunDetailedLine) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *ChargeUsageBasedRunDetailedLine) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *ChargeUsageBasedRunDetailedLine) GetName() string { + return e.Name +} + +func (e *ChargeUsageBasedRunDetailedLine) GetDescription() *string { + return e.Description +} + +func (e *ChargeUsageBasedRunDetailedLine) GetAmount() alpacadecimal.Decimal { + return e.Amount +} + +func (e *ChargeUsageBasedRunDetailedLine) GetTaxesTotal() alpacadecimal.Decimal { + return e.TaxesTotal +} + +func (e *ChargeUsageBasedRunDetailedLine) GetTaxesInclusiveTotal() alpacadecimal.Decimal { + return e.TaxesInclusiveTotal +} + +func (e *ChargeUsageBasedRunDetailedLine) GetTaxesExclusiveTotal() alpacadecimal.Decimal { + return e.TaxesExclusiveTotal +} + +func (e *ChargeUsageBasedRunDetailedLine) GetChargesTotal() alpacadecimal.Decimal { + return e.ChargesTotal +} + +func (e *ChargeUsageBasedRunDetailedLine) GetDiscountsTotal() alpacadecimal.Decimal { + return e.DiscountsTotal +} + +func (e *ChargeUsageBasedRunDetailedLine) GetCreditsTotal() alpacadecimal.Decimal { + return e.CreditsTotal +} + +func (e *ChargeUsageBasedRunDetailedLine) GetTotal() alpacadecimal.Decimal { + return e.Total +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetID() string { + return e.ID +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetServicePeriodFrom() time.Time { + return e.ServicePeriodFrom +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetServicePeriodTo() time.Time { + return e.ServicePeriodTo +} + +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) GetInvoiceID() string { + return e.InvoiceID +} + +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 *ChargeUsageBasedRuns) GetAmount() alpacadecimal.Decimal { + return e.Amount +} + +func (e *ChargeUsageBasedRuns) GetTaxesTotal() alpacadecimal.Decimal { + return e.TaxesTotal +} + +func (e *ChargeUsageBasedRuns) GetTaxesInclusiveTotal() alpacadecimal.Decimal { + return e.TaxesInclusiveTotal +} + +func (e *ChargeUsageBasedRuns) GetTaxesExclusiveTotal() alpacadecimal.Decimal { + return e.TaxesExclusiveTotal +} + +func (e *ChargeUsageBasedRuns) GetChargesTotal() alpacadecimal.Decimal { + return e.ChargesTotal +} + +func (e *ChargeUsageBasedRuns) GetDiscountsTotal() alpacadecimal.Decimal { + return e.DiscountsTotal +} + +func (e *ChargeUsageBasedRuns) GetCreditsTotal() alpacadecimal.Decimal { + return e.CreditsTotal +} + +func (e *ChargeUsageBasedRuns) GetTotal() alpacadecimal.Decimal { + return e.Total +} + +func (e *CreditRealizationLineage) GetID() string { + return e.ID +} + +func (e *CreditRealizationLineage) GetNamespace() string { + return e.Namespace +} + +func (e *CreditRealizationLineageSegment) GetID() string { + return e.ID +} + +func (e *CurrencyCostBasis) GetID() string { + return e.ID +} + +func (e *CurrencyCostBasis) GetNamespace() string { + return e.Namespace +} + +func (e *CurrencyCostBasis) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *CurrencyCostBasis) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *CurrencyCostBasis) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *CustomCurrency) GetID() string { + return e.ID +} + +func (e *CustomCurrency) GetNamespace() string { + return e.Namespace +} + +func (e *CustomCurrency) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *CustomCurrency) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *CustomCurrency) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *Customer) GetID() string { + return e.ID +} + +func (e *Customer) GetNamespace() string { + return e.Namespace +} + +func (e *Customer) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *Customer) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *Customer) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *Customer) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *Customer) GetName() string { + return e.Name +} + +func (e *Customer) GetDescription() *string { + return e.Description +} + +func (e *Customer) GetBillingAddressCountry() *models.CountryCode { + return e.BillingAddressCountry +} + +func (e *Customer) GetBillingAddressPostalCode() *string { + return e.BillingAddressPostalCode +} + +func (e *Customer) GetBillingAddressState() *string { + return e.BillingAddressState +} + +func (e *Customer) GetBillingAddressCity() *string { + return e.BillingAddressCity +} + +func (e *Customer) GetBillingAddressLine1() *string { + return e.BillingAddressLine1 +} + +func (e *Customer) GetBillingAddressLine2() *string { + return e.BillingAddressLine2 +} + +func (e *Customer) GetBillingAddressPhoneNumber() *string { + return e.BillingAddressPhoneNumber +} + +func (e *Customer) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *CustomerSubjects) GetNamespace() string { + return e.Namespace +} + +func (e *Entitlement) GetID() string { + return e.ID +} + +func (e *Entitlement) GetNamespace() string { + return e.Namespace +} + +func (e *Entitlement) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *Entitlement) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *Entitlement) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *Entitlement) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *Feature) GetID() string { + return e.ID +} + +func (e *Feature) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *Feature) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *Feature) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *Feature) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *Grant) GetID() string { + return e.ID +} + +func (e *Grant) GetNamespace() string { + return e.Namespace +} + +func (e *Grant) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *Grant) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *Grant) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *Grant) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *LLMCostPrice) GetID() string { + return e.ID +} + +func (e *LLMCostPrice) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *LLMCostPrice) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *LLMCostPrice) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *LLMCostPrice) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *LedgerAccount) GetID() string { + return e.ID +} + +func (e *LedgerAccount) GetNamespace() string { + return e.Namespace +} + +func (e *LedgerAccount) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *LedgerAccount) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *LedgerAccount) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *LedgerAccount) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *LedgerBreakageRecord) GetID() string { + return e.ID +} + +func (e *LedgerBreakageRecord) GetNamespace() string { + return e.Namespace +} + +func (e *LedgerBreakageRecord) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *LedgerBreakageRecord) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *LedgerBreakageRecord) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *LedgerBreakageRecord) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *LedgerCreditVoidRecord) GetID() string { + return e.ID +} + +func (e *LedgerCreditVoidRecord) GetNamespace() string { + return e.Namespace +} + +func (e *LedgerCreditVoidRecord) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *LedgerCreditVoidRecord) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *LedgerCreditVoidRecord) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *LedgerCreditVoidRecord) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *LedgerCustomerAccount) GetID() string { + return e.ID +} + +func (e *LedgerCustomerAccount) GetNamespace() string { + return e.Namespace +} + +func (e *LedgerCustomerAccount) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *LedgerCustomerAccount) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *LedgerCustomerAccount) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *LedgerEntry) GetID() string { + return e.ID +} + +func (e *LedgerEntry) GetNamespace() string { + return e.Namespace +} + +func (e *LedgerEntry) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *LedgerEntry) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *LedgerEntry) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *LedgerEntry) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *LedgerSubAccount) GetID() string { + return e.ID +} + +func (e *LedgerSubAccount) GetNamespace() string { + return e.Namespace +} + +func (e *LedgerSubAccount) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *LedgerSubAccount) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *LedgerSubAccount) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *LedgerSubAccount) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *LedgerSubAccountRoute) GetID() string { + return e.ID +} + +func (e *LedgerSubAccountRoute) GetNamespace() string { + return e.Namespace +} + +func (e *LedgerSubAccountRoute) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *LedgerSubAccountRoute) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *LedgerSubAccountRoute) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *LedgerTransaction) GetID() string { + return e.ID +} + +func (e *LedgerTransaction) GetNamespace() string { + return e.Namespace +} + +func (e *LedgerTransaction) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *LedgerTransaction) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *LedgerTransaction) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *LedgerTransaction) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *LedgerTransactionGroup) GetID() string { + return e.ID +} + +func (e *LedgerTransactionGroup) GetNamespace() string { + return e.Namespace +} + +func (e *LedgerTransactionGroup) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *LedgerTransactionGroup) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *LedgerTransactionGroup) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *LedgerTransactionGroup) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *Meter) GetID() string { + return e.ID +} + +func (e *Meter) GetNamespace() string { + return e.Namespace +} + +func (e *Meter) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *Meter) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *Meter) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *Meter) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *Meter) GetName() string { + return e.Name +} + +func (e *Meter) GetDescription() *string { + return e.Description +} + +func (e *Meter) GetKey() string { + return e.Key +} + +func (e *Meter) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *NotificationChannel) GetID() string { + return e.ID +} + +func (e *NotificationChannel) GetNamespace() string { + return e.Namespace +} + +func (e *NotificationChannel) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *NotificationChannel) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *NotificationChannel) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *NotificationChannel) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *NotificationChannel) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *NotificationEvent) GetID() string { + return e.ID +} + +func (e *NotificationEvent) GetNamespace() string { + return e.Namespace +} + +func (e *NotificationEvent) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *NotificationEventDeliveryStatus) GetID() string { + return e.ID +} + +func (e *NotificationEventDeliveryStatus) GetNamespace() string { + return e.Namespace +} + +func (e *NotificationEventDeliveryStatus) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *NotificationRule) GetID() string { + return e.ID +} + +func (e *NotificationRule) GetNamespace() string { + return e.Namespace +} + +func (e *NotificationRule) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *NotificationRule) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *NotificationRule) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *NotificationRule) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *NotificationRule) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *OrganizationDefaultTaxCodes) GetID() string { + return e.ID +} + +func (e *OrganizationDefaultTaxCodes) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *OrganizationDefaultTaxCodes) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *OrganizationDefaultTaxCodes) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *Plan) GetID() string { + return e.ID +} + +func (e *Plan) GetNamespace() string { + return e.Namespace +} + +func (e *Plan) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *Plan) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *Plan) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *Plan) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *Plan) GetName() string { + return e.Name +} + +func (e *Plan) GetDescription() *string { + return e.Description +} + +func (e *Plan) GetKey() string { + return e.Key +} + +func (e *PlanAddon) GetID() string { + return e.ID +} + +func (e *PlanAddon) GetNamespace() string { + return e.Namespace +} + +func (e *PlanAddon) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *PlanAddon) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *PlanAddon) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *PlanAddon) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *PlanAddon) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *PlanPhase) GetID() string { + return e.ID +} + +func (e *PlanPhase) GetNamespace() string { + return e.Namespace +} + +func (e *PlanPhase) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *PlanPhase) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *PlanPhase) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *PlanPhase) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *PlanPhase) GetName() string { + return e.Name +} + +func (e *PlanPhase) GetDescription() *string { + return e.Description +} + +func (e *PlanPhase) GetKey() string { + return e.Key +} + +func (e *PlanRateCard) GetID() string { + return e.ID +} + +func (e *PlanRateCard) GetNamespace() string { + return e.Namespace +} + +func (e *PlanRateCard) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *PlanRateCard) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *PlanRateCard) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *PlanRateCard) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *PlanRateCard) GetName() string { + return e.Name +} + +func (e *PlanRateCard) GetDescription() *string { + return e.Description +} + +func (e *PlanRateCard) GetKey() string { + return e.Key +} + +func (e *PlanRateCard) GetTaxCodeID() *string { + return e.TaxCodeID +} + +func (e *PlanRateCard) GetTaxBehavior() *productcatalog.TaxBehavior { + return e.TaxBehavior +} + +func (e *Subject) GetID() string { + return e.ID +} + +func (e *Subject) GetNamespace() string { + return e.Namespace +} + +func (e *Subject) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *Subject) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *Subject) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *Subscription) GetID() string { + return e.ID +} + +func (e *Subscription) GetNamespace() string { + return e.Namespace +} + +func (e *Subscription) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *Subscription) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *Subscription) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *Subscription) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *Subscription) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *Subscription) GetActiveFrom() time.Time { + return e.ActiveFrom +} + +func (e *Subscription) GetActiveTo() *time.Time { + return e.ActiveTo +} + +func (e *SubscriptionAddon) GetID() string { + return e.ID +} + +func (e *SubscriptionAddon) GetNamespace() string { + return e.Namespace +} + +func (e *SubscriptionAddon) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *SubscriptionAddon) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *SubscriptionAddon) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *SubscriptionAddon) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *SubscriptionAddonQuantity) GetID() string { + return e.ID +} + +func (e *SubscriptionAddonQuantity) GetNamespace() string { + return e.Namespace +} + +func (e *SubscriptionAddonQuantity) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *SubscriptionAddonQuantity) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *SubscriptionAddonQuantity) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *SubscriptionBillingSyncState) GetID() string { + return e.ID +} + +func (e *SubscriptionBillingSyncState) GetNamespace() string { + return e.Namespace +} + +func (e *SubscriptionItem) GetID() string { + return e.ID +} + +func (e *SubscriptionItem) GetNamespace() string { + return e.Namespace +} + +func (e *SubscriptionItem) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *SubscriptionItem) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *SubscriptionItem) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *SubscriptionItem) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *SubscriptionItem) GetTaxCodeID() *string { + return e.TaxCodeID +} + +func (e *SubscriptionItem) GetTaxBehavior() *productcatalog.TaxBehavior { + return e.TaxBehavior +} + +func (e *SubscriptionPhase) GetID() string { + return e.ID +} + +func (e *SubscriptionPhase) GetNamespace() string { + return e.Namespace +} + +func (e *SubscriptionPhase) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *SubscriptionPhase) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *SubscriptionPhase) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *SubscriptionPhase) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *TaxCode) GetID() string { + return e.ID +} + +func (e *TaxCode) GetNamespace() string { + return e.Namespace +} + +func (e *TaxCode) GetMetadata() map[string]string { + return e.Metadata +} + +func (e *TaxCode) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *TaxCode) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *TaxCode) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *TaxCode) GetName() string { + return e.Name +} + +func (e *TaxCode) GetDescription() *string { + return e.Description +} + +func (e *TaxCode) GetKey() string { + return e.Key +} + +func (e *TaxCode) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *UsageReset) GetID() string { + return e.ID +} + +func (e *UsageReset) GetNamespace() string { + return e.Namespace +} + +func (e *UsageReset) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *UsageReset) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *UsageReset) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *UsageReset) GetDeletedAt() *time.Time { + return e.DeletedAt +} diff --git a/ent/db/enttest/enttest.go b/ent/db/enttest/enttest.go new file mode 100644 index 0000000000000000000000000000000000000000..d696355e7ddf9d1de9b902417f026d46bd678d0f --- /dev/null +++ b/ent/db/enttest/enttest.go @@ -0,0 +1,84 @@ +// Code generated by ent, DO NOT EDIT. + +package enttest + +import ( + "context" + + "github.com/openmeterio/openmeter/openmeter/ent/db" + // required by schema hooks. + _ "github.com/openmeterio/openmeter/openmeter/ent/db/runtime" + + "entgo.io/ent/dialect/sql/schema" + "github.com/openmeterio/openmeter/openmeter/ent/db/migrate" +) + +type ( + // TestingT is the interface that is shared between + // testing.T and testing.B and used by enttest. + TestingT interface { + FailNow() + Error(...any) + } + + // Option configures client creation. + Option func(*options) + + options struct { + opts []db.Option + migrateOpts []schema.MigrateOption + } +) + +// WithOptions forwards options to client creation. +func WithOptions(opts ...db.Option) Option { + return func(o *options) { + o.opts = append(o.opts, opts...) + } +} + +// WithMigrateOptions forwards options to auto migration. +func WithMigrateOptions(opts ...schema.MigrateOption) Option { + return func(o *options) { + o.migrateOpts = append(o.migrateOpts, opts...) + } +} + +func newOptions(opts []Option) *options { + o := &options{} + for _, opt := range opts { + opt(o) + } + return o +} + +// Open calls db.Open and auto-run migration. +func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *db.Client { + o := newOptions(opts) + c, err := db.Open(driverName, dataSourceName, o.opts...) + if err != nil { + t.Error(err) + t.FailNow() + } + migrateSchema(t, c, o) + return c +} + +// NewClient calls db.NewClient and auto-run migration. +func NewClient(t TestingT, opts ...Option) *db.Client { + o := newOptions(opts) + c := db.NewClient(o.opts...) + migrateSchema(t, c, o) + return c +} +func migrateSchema(t TestingT, c *db.Client, o *options) { + tables, err := schema.CopyTables(migrate.Tables) + if err != nil { + t.Error(err) + t.FailNow() + } + if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } +} diff --git a/ent/db/expose.go b/ent/db/expose.go new file mode 100644 index 0000000000000000000000000000000000000000..a3d2ce40461a3963c51675fcb3e011afc5ac43a2 --- /dev/null +++ b/ent/db/expose.go @@ -0,0 +1,258 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "github.com/openmeterio/openmeter/pkg/framework/entutils" +) + +func (c *Client) GetConfig() *entutils.RawEntConfig { + return &entutils.RawEntConfig{ + Driver: c.config.driver, + Debug: c.config.debug, + Log: c.config.log, + } +} + +// ignores hooks and intersectors +type ExposedTxDriver struct { + Driver *txDriver +} + +var _ entutils.Transactable = (*ExposedTxDriver)(nil) + +func (d *ExposedTxDriver) Rollback() error { + return d.Driver.tx.Rollback() +} + +func (d *ExposedTxDriver) Commit() error { + return d.Driver.tx.Commit() +} + +func (d *ExposedTxDriver) SavePoint(name string) error { + _, err := d.Driver.ExecContext(context.Background(), "SAVEPOINT "+name) + return err +} + +func (d *ExposedTxDriver) RollbackTo(name string) error { + _, err := d.Driver.ExecContext(context.Background(), "ROLLBACK TO "+name) + return err +} + +func (d *ExposedTxDriver) Release(name string) error { + _, err := d.Driver.ExecContext(context.Background(), "RELEASE SAVEPOINT "+name) + return err +} + +// HijackTx returns a new transaction driver with the provided options. +// The returned transaction can later be used to instanciate new clients. +func (c *Client) HijackTx(ctx context.Context, opts *sql.TxOptions) (context.Context, *entutils.RawEntConfig, *ExposedTxDriver, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, nil, nil, errors.New("ent: cannot start a transaction within a transaction") + } + tx, err := c.driver.(interface { + BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) + }).BeginTx(ctx, opts) + if err != nil { + return nil, nil, nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + + driver := &txDriver{tx: tx, drv: c.driver} + + cfg := c.config + cfg.driver = &txDriver{tx: tx, drv: c.driver} + return ctx, &entutils.RawEntConfig{ + Driver: cfg.driver, + Debug: cfg.debug, + Log: cfg.log, + }, &ExposedTxDriver{Driver: driver}, nil +} + +// NewTxClientFromConfig creates a new transactional client from a (hijacked) configuration. +func NewTxClientFromRawConfig(ctx context.Context, cfg entutils.RawEntConfig) *Tx { + config := config{ + driver: cfg.Driver, + debug: cfg.Debug, + log: cfg.Log, + hooks: &hooks{}, + inters: &inters{}, + } + + return &Tx{ + ctx: ctx, + config: config, + // Clients templated from defined schemas + + Addon: NewAddonClient(config), + + AddonRateCard: NewAddonRateCardClient(config), + + App: NewAppClient(config), + + AppCustomInvoicing: NewAppCustomInvoicingClient(config), + + AppCustomInvoicingCustomer: NewAppCustomInvoicingCustomerClient(config), + + AppCustomer: NewAppCustomerClient(config), + + AppStripe: NewAppStripeClient(config), + + AppStripeCustomer: NewAppStripeCustomerClient(config), + + BalanceSnapshot: NewBalanceSnapshotClient(config), + + BillingCustomerLock: NewBillingCustomerLockClient(config), + + BillingCustomerOverride: NewBillingCustomerOverrideClient(config), + + BillingInvoice: NewBillingInvoiceClient(config), + + BillingInvoiceFlatFeeLineConfig: NewBillingInvoiceFlatFeeLineConfigClient(config), + + BillingInvoiceLine: NewBillingInvoiceLineClient(config), + + BillingInvoiceLineDiscount: NewBillingInvoiceLineDiscountClient(config), + + BillingInvoiceLineUsageDiscount: NewBillingInvoiceLineUsageDiscountClient(config), + + BillingInvoiceSplitLineGroup: NewBillingInvoiceSplitLineGroupClient(config), + + BillingInvoiceUsageBasedLineConfig: NewBillingInvoiceUsageBasedLineConfigClient(config), + + BillingInvoiceValidationIssue: NewBillingInvoiceValidationIssueClient(config), + + BillingInvoiceWriteSchemaLevel: NewBillingInvoiceWriteSchemaLevelClient(config), + + BillingProfile: NewBillingProfileClient(config), + + BillingSequenceNumbers: NewBillingSequenceNumbersClient(config), + + BillingStandardInvoiceDetailedLine: NewBillingStandardInvoiceDetailedLineClient(config), + + BillingStandardInvoiceDetailedLineAmountDiscount: NewBillingStandardInvoiceDetailedLineAmountDiscountClient(config), + + BillingWorkflowConfig: NewBillingWorkflowConfigClient(config), + + Charge: NewChargeClient(config), + + ChargeCreditPurchase: NewChargeCreditPurchaseClient(config), + + ChargeCreditPurchaseCreditGrant: NewChargeCreditPurchaseCreditGrantClient(config), + + ChargeCreditPurchaseExternalPayment: NewChargeCreditPurchaseExternalPaymentClient(config), + + ChargeCreditPurchaseInvoicedPayment: NewChargeCreditPurchaseInvoicedPaymentClient(config), + + ChargeFlatFee: NewChargeFlatFeeClient(config), + + ChargeFlatFeeOverride: NewChargeFlatFeeOverrideClient(config), + + ChargeFlatFeeRun: NewChargeFlatFeeRunClient(config), + + ChargeFlatFeeRunCreditAllocations: NewChargeFlatFeeRunCreditAllocationsClient(config), + + ChargeFlatFeeRunDetailedLine: NewChargeFlatFeeRunDetailedLineClient(config), + + ChargeFlatFeeRunInvoicedUsage: NewChargeFlatFeeRunInvoicedUsageClient(config), + + ChargeFlatFeeRunPayment: NewChargeFlatFeeRunPaymentClient(config), + + ChargeUsageBased: NewChargeUsageBasedClient(config), + + ChargeUsageBasedOverride: NewChargeUsageBasedOverrideClient(config), + + ChargeUsageBasedRunCreditAllocations: NewChargeUsageBasedRunCreditAllocationsClient(config), + + ChargeUsageBasedRunDetailedLine: NewChargeUsageBasedRunDetailedLineClient(config), + + ChargeUsageBasedRunInvoicedUsage: NewChargeUsageBasedRunInvoicedUsageClient(config), + + ChargeUsageBasedRunPayment: NewChargeUsageBasedRunPaymentClient(config), + + ChargeUsageBasedRuns: NewChargeUsageBasedRunsClient(config), + + ChargesSearchV1: NewChargesSearchV1Client(config), + + CreditRealizationLineage: NewCreditRealizationLineageClient(config), + + CreditRealizationLineageSegment: NewCreditRealizationLineageSegmentClient(config), + + CurrencyCostBasis: NewCurrencyCostBasisClient(config), + + CustomCurrency: NewCustomCurrencyClient(config), + + Customer: NewCustomerClient(config), + + CustomerSubjects: NewCustomerSubjectsClient(config), + + Entitlement: NewEntitlementClient(config), + + Feature: NewFeatureClient(config), + + Grant: NewGrantClient(config), + + LLMCostPrice: NewLLMCostPriceClient(config), + + LedgerAccount: NewLedgerAccountClient(config), + + LedgerBreakageRecord: NewLedgerBreakageRecordClient(config), + + LedgerCreditVoidRecord: NewLedgerCreditVoidRecordClient(config), + + LedgerCustomerAccount: NewLedgerCustomerAccountClient(config), + + LedgerEntry: NewLedgerEntryClient(config), + + LedgerSubAccount: NewLedgerSubAccountClient(config), + + LedgerSubAccountRoute: NewLedgerSubAccountRouteClient(config), + + LedgerTransaction: NewLedgerTransactionClient(config), + + LedgerTransactionGroup: NewLedgerTransactionGroupClient(config), + + Meter: NewMeterClient(config), + + NotificationChannel: NewNotificationChannelClient(config), + + NotificationEvent: NewNotificationEventClient(config), + + NotificationEventDeliveryStatus: NewNotificationEventDeliveryStatusClient(config), + + NotificationRule: NewNotificationRuleClient(config), + + OrganizationDefaultTaxCodes: NewOrganizationDefaultTaxCodesClient(config), + + Plan: NewPlanClient(config), + + PlanAddon: NewPlanAddonClient(config), + + PlanPhase: NewPlanPhaseClient(config), + + PlanRateCard: NewPlanRateCardClient(config), + + Subject: NewSubjectClient(config), + + Subscription: NewSubscriptionClient(config), + + SubscriptionAddon: NewSubscriptionAddonClient(config), + + SubscriptionAddonQuantity: NewSubscriptionAddonQuantityClient(config), + + SubscriptionBillingSyncState: NewSubscriptionBillingSyncStateClient(config), + + SubscriptionItem: NewSubscriptionItemClient(config), + + SubscriptionPhase: NewSubscriptionPhaseClient(config), + + TaxCode: NewTaxCodeClient(config), + + UsageReset: NewUsageResetClient(config), + } +} diff --git a/ent/db/feature.go b/ent/db/feature.go new file mode 100644 index 0000000000000000000000000000000000000000..4cd5842e63a2ec8d5a575d18fc1852aed3e0c4f1 --- /dev/null +++ b/ent/db/feature.go @@ -0,0 +1,501 @@ +// 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" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + dbmeter "github.com/openmeterio/openmeter/openmeter/ent/db/meter" + "github.com/openmeterio/openmeter/openmeter/productcatalog/feature" +) + +// Feature is the model entity for the Feature schema. +type Feature struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,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"` + // Metadata holds the value of the "metadata" field. + Metadata map[string]string `json:"metadata,omitempty"` + // Namespace holds the value of the "namespace" field. + Namespace string `json:"namespace,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Description holds the value of the "description" field. + Description *string `json:"description,omitempty"` + // Key holds the value of the "key" field. + Key string `json:"key,omitempty"` + // MeterSlug holds the value of the "meter_slug" field. + MeterSlug *string `json:"meter_slug,omitempty"` + // MeterID holds the value of the "meter_id" field. + MeterID *string `json:"meter_id,omitempty"` + // MeterGroupByFilters holds the value of the "meter_group_by_filters" field. + MeterGroupByFilters map[string]string `json:"meter_group_by_filters,omitempty"` + // AdvancedMeterGroupByFilters holds the value of the "advanced_meter_group_by_filters" field. + AdvancedMeterGroupByFilters feature.MeterGroupByFilters `json:"advanced_meter_group_by_filters,omitempty"` + // UnitCostType holds the value of the "unit_cost_type" field. + UnitCostType *string `json:"unit_cost_type,omitempty"` + // UnitCostManualAmount holds the value of the "unit_cost_manual_amount" field. + UnitCostManualAmount *alpacadecimal.Decimal `json:"unit_cost_manual_amount,omitempty"` + // UnitCostLlmProviderProperty holds the value of the "unit_cost_llm_provider_property" field. + UnitCostLlmProviderProperty *string `json:"unit_cost_llm_provider_property,omitempty"` + // UnitCostLlmProvider holds the value of the "unit_cost_llm_provider" field. + UnitCostLlmProvider *string `json:"unit_cost_llm_provider,omitempty"` + // UnitCostLlmModelProperty holds the value of the "unit_cost_llm_model_property" field. + UnitCostLlmModelProperty *string `json:"unit_cost_llm_model_property,omitempty"` + // UnitCostLlmModel holds the value of the "unit_cost_llm_model" field. + UnitCostLlmModel *string `json:"unit_cost_llm_model,omitempty"` + // UnitCostLlmTokenTypeProperty holds the value of the "unit_cost_llm_token_type_property" field. + UnitCostLlmTokenTypeProperty *string `json:"unit_cost_llm_token_type_property,omitempty"` + // UnitCostLlmTokenType holds the value of the "unit_cost_llm_token_type" field. + UnitCostLlmTokenType *string `json:"unit_cost_llm_token_type,omitempty"` + // ArchivedAt holds the value of the "archived_at" field. + ArchivedAt *time.Time `json:"archived_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the FeatureQuery when eager-loading is set. + Edges FeatureEdges `json:"edges"` + selectValues sql.SelectValues +} + +// FeatureEdges holds the relations/edges for other nodes in the graph. +type FeatureEdges struct { + // Entitlement holds the value of the entitlement edge. + Entitlement []*Entitlement `json:"entitlement,omitempty"` + // Ratecard holds the value of the ratecard edge. + Ratecard []*PlanRateCard `json:"ratecard,omitempty"` + // AddonRatecard holds the value of the addon_ratecard edge. + AddonRatecard []*AddonRateCard `json:"addon_ratecard,omitempty"` + // UsageBasedCharges holds the value of the usage_based_charges edge. + UsageBasedCharges []*ChargeUsageBased `json:"usage_based_charges,omitempty"` + // UsageBasedRuns holds the value of the usage_based_runs edge. + UsageBasedRuns []*ChargeUsageBasedRuns `json:"usage_based_runs,omitempty"` + // FlatFeeCharges holds the value of the flat_fee_charges edge. + FlatFeeCharges []*ChargeFlatFee `json:"flat_fee_charges,omitempty"` + // Meter holds the value of the meter edge. + Meter *Meter `json:"meter,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [7]bool +} + +// EntitlementOrErr returns the Entitlement value or an error if the edge +// was not loaded in eager-loading. +func (e FeatureEdges) EntitlementOrErr() ([]*Entitlement, error) { + if e.loadedTypes[0] { + return e.Entitlement, nil + } + return nil, &NotLoadedError{edge: "entitlement"} +} + +// RatecardOrErr returns the Ratecard value or an error if the edge +// was not loaded in eager-loading. +func (e FeatureEdges) RatecardOrErr() ([]*PlanRateCard, error) { + if e.loadedTypes[1] { + return e.Ratecard, nil + } + return nil, &NotLoadedError{edge: "ratecard"} +} + +// AddonRatecardOrErr returns the AddonRatecard value or an error if the edge +// was not loaded in eager-loading. +func (e FeatureEdges) AddonRatecardOrErr() ([]*AddonRateCard, error) { + if e.loadedTypes[2] { + return e.AddonRatecard, nil + } + return nil, &NotLoadedError{edge: "addon_ratecard"} +} + +// UsageBasedChargesOrErr returns the UsageBasedCharges value or an error if the edge +// was not loaded in eager-loading. +func (e FeatureEdges) UsageBasedChargesOrErr() ([]*ChargeUsageBased, error) { + if e.loadedTypes[3] { + return e.UsageBasedCharges, nil + } + return nil, &NotLoadedError{edge: "usage_based_charges"} +} + +// UsageBasedRunsOrErr returns the UsageBasedRuns value or an error if the edge +// was not loaded in eager-loading. +func (e FeatureEdges) UsageBasedRunsOrErr() ([]*ChargeUsageBasedRuns, error) { + if e.loadedTypes[4] { + return e.UsageBasedRuns, nil + } + return nil, &NotLoadedError{edge: "usage_based_runs"} +} + +// FlatFeeChargesOrErr returns the FlatFeeCharges value or an error if the edge +// was not loaded in eager-loading. +func (e FeatureEdges) FlatFeeChargesOrErr() ([]*ChargeFlatFee, error) { + if e.loadedTypes[5] { + return e.FlatFeeCharges, nil + } + return nil, &NotLoadedError{edge: "flat_fee_charges"} +} + +// MeterOrErr returns the Meter value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e FeatureEdges) MeterOrErr() (*Meter, error) { + if e.Meter != nil { + return e.Meter, nil + } else if e.loadedTypes[6] { + return nil, &NotFoundError{label: dbmeter.Label} + } + return nil, &NotLoadedError{edge: "meter"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Feature) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case dbfeature.FieldUnitCostManualAmount: + values[i] = &sql.NullScanner{S: new(alpacadecimal.Decimal)} + case dbfeature.FieldMetadata, dbfeature.FieldMeterGroupByFilters, dbfeature.FieldAdvancedMeterGroupByFilters: + values[i] = new([]byte) + case dbfeature.FieldID, dbfeature.FieldNamespace, dbfeature.FieldName, dbfeature.FieldDescription, dbfeature.FieldKey, dbfeature.FieldMeterSlug, dbfeature.FieldMeterID, dbfeature.FieldUnitCostType, dbfeature.FieldUnitCostLlmProviderProperty, dbfeature.FieldUnitCostLlmProvider, dbfeature.FieldUnitCostLlmModelProperty, dbfeature.FieldUnitCostLlmModel, dbfeature.FieldUnitCostLlmTokenTypeProperty, dbfeature.FieldUnitCostLlmTokenType: + values[i] = new(sql.NullString) + case dbfeature.FieldCreatedAt, dbfeature.FieldUpdatedAt, dbfeature.FieldDeletedAt, dbfeature.FieldArchivedAt: + 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 Feature fields. +func (_m *Feature) 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 dbfeature.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 dbfeature.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 dbfeature.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 dbfeature.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 dbfeature.FieldMetadata: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field metadata", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Metadata); err != nil { + return fmt.Errorf("unmarshal field metadata: %w", err) + } + } + case dbfeature.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 dbfeature.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case dbfeature.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + _m.Description = new(string) + *_m.Description = value.String + } + case dbfeature.FieldKey: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field key", values[i]) + } else if value.Valid { + _m.Key = value.String + } + case dbfeature.FieldMeterSlug: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field meter_slug", values[i]) + } else if value.Valid { + _m.MeterSlug = new(string) + *_m.MeterSlug = value.String + } + case dbfeature.FieldMeterID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field meter_id", values[i]) + } else if value.Valid { + _m.MeterID = new(string) + *_m.MeterID = value.String + } + case dbfeature.FieldMeterGroupByFilters: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field meter_group_by_filters", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.MeterGroupByFilters); err != nil { + return fmt.Errorf("unmarshal field meter_group_by_filters: %w", err) + } + } + case dbfeature.FieldAdvancedMeterGroupByFilters: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field advanced_meter_group_by_filters", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.AdvancedMeterGroupByFilters); err != nil { + return fmt.Errorf("unmarshal field advanced_meter_group_by_filters: %w", err) + } + } + case dbfeature.FieldUnitCostType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field unit_cost_type", values[i]) + } else if value.Valid { + _m.UnitCostType = new(string) + *_m.UnitCostType = value.String + } + case dbfeature.FieldUnitCostManualAmount: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field unit_cost_manual_amount", values[i]) + } else if value.Valid { + _m.UnitCostManualAmount = new(alpacadecimal.Decimal) + *_m.UnitCostManualAmount = *value.S.(*alpacadecimal.Decimal) + } + case dbfeature.FieldUnitCostLlmProviderProperty: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field unit_cost_llm_provider_property", values[i]) + } else if value.Valid { + _m.UnitCostLlmProviderProperty = new(string) + *_m.UnitCostLlmProviderProperty = value.String + } + case dbfeature.FieldUnitCostLlmProvider: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field unit_cost_llm_provider", values[i]) + } else if value.Valid { + _m.UnitCostLlmProvider = new(string) + *_m.UnitCostLlmProvider = value.String + } + case dbfeature.FieldUnitCostLlmModelProperty: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field unit_cost_llm_model_property", values[i]) + } else if value.Valid { + _m.UnitCostLlmModelProperty = new(string) + *_m.UnitCostLlmModelProperty = value.String + } + case dbfeature.FieldUnitCostLlmModel: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field unit_cost_llm_model", values[i]) + } else if value.Valid { + _m.UnitCostLlmModel = new(string) + *_m.UnitCostLlmModel = value.String + } + case dbfeature.FieldUnitCostLlmTokenTypeProperty: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field unit_cost_llm_token_type_property", values[i]) + } else if value.Valid { + _m.UnitCostLlmTokenTypeProperty = new(string) + *_m.UnitCostLlmTokenTypeProperty = value.String + } + case dbfeature.FieldUnitCostLlmTokenType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field unit_cost_llm_token_type", values[i]) + } else if value.Valid { + _m.UnitCostLlmTokenType = new(string) + *_m.UnitCostLlmTokenType = value.String + } + case dbfeature.FieldArchivedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field archived_at", values[i]) + } else if value.Valid { + _m.ArchivedAt = new(time.Time) + *_m.ArchivedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Feature. +// This includes values selected through modifiers, order, etc. +func (_m *Feature) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryEntitlement queries the "entitlement" edge of the Feature entity. +func (_m *Feature) QueryEntitlement() *EntitlementQuery { + return NewFeatureClient(_m.config).QueryEntitlement(_m) +} + +// QueryRatecard queries the "ratecard" edge of the Feature entity. +func (_m *Feature) QueryRatecard() *PlanRateCardQuery { + return NewFeatureClient(_m.config).QueryRatecard(_m) +} + +// QueryAddonRatecard queries the "addon_ratecard" edge of the Feature entity. +func (_m *Feature) QueryAddonRatecard() *AddonRateCardQuery { + return NewFeatureClient(_m.config).QueryAddonRatecard(_m) +} + +// QueryUsageBasedCharges queries the "usage_based_charges" edge of the Feature entity. +func (_m *Feature) QueryUsageBasedCharges() *ChargeUsageBasedQuery { + return NewFeatureClient(_m.config).QueryUsageBasedCharges(_m) +} + +// QueryUsageBasedRuns queries the "usage_based_runs" edge of the Feature entity. +func (_m *Feature) QueryUsageBasedRuns() *ChargeUsageBasedRunsQuery { + return NewFeatureClient(_m.config).QueryUsageBasedRuns(_m) +} + +// QueryFlatFeeCharges queries the "flat_fee_charges" edge of the Feature entity. +func (_m *Feature) QueryFlatFeeCharges() *ChargeFlatFeeQuery { + return NewFeatureClient(_m.config).QueryFlatFeeCharges(_m) +} + +// QueryMeter queries the "meter" edge of the Feature entity. +func (_m *Feature) QueryMeter() *MeterQuery { + return NewFeatureClient(_m.config).QueryMeter(_m) +} + +// Update returns a builder for updating this Feature. +// Note that you need to call Feature.Unwrap() before calling this method if this Feature +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Feature) Update() *FeatureUpdateOne { + return NewFeatureClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Feature 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 *Feature) Unwrap() *Feature { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: Feature is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Feature) String() string { + var builder strings.Builder + builder.WriteString("Feature(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + 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("metadata=") + builder.WriteString(fmt.Sprintf("%v", _m.Metadata)) + builder.WriteString(", ") + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + if v := _m.Description; v != nil { + builder.WriteString("description=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("key=") + builder.WriteString(_m.Key) + builder.WriteString(", ") + if v := _m.MeterSlug; v != nil { + builder.WriteString("meter_slug=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.MeterID; v != nil { + builder.WriteString("meter_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("meter_group_by_filters=") + builder.WriteString(fmt.Sprintf("%v", _m.MeterGroupByFilters)) + builder.WriteString(", ") + builder.WriteString("advanced_meter_group_by_filters=") + builder.WriteString(fmt.Sprintf("%v", _m.AdvancedMeterGroupByFilters)) + builder.WriteString(", ") + if v := _m.UnitCostType; v != nil { + builder.WriteString("unit_cost_type=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.UnitCostManualAmount; v != nil { + builder.WriteString("unit_cost_manual_amount=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.UnitCostLlmProviderProperty; v != nil { + builder.WriteString("unit_cost_llm_provider_property=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.UnitCostLlmProvider; v != nil { + builder.WriteString("unit_cost_llm_provider=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.UnitCostLlmModelProperty; v != nil { + builder.WriteString("unit_cost_llm_model_property=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.UnitCostLlmModel; v != nil { + builder.WriteString("unit_cost_llm_model=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.UnitCostLlmTokenTypeProperty; v != nil { + builder.WriteString("unit_cost_llm_token_type_property=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.UnitCostLlmTokenType; v != nil { + builder.WriteString("unit_cost_llm_token_type=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.ArchivedAt; v != nil { + builder.WriteString("archived_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteByte(')') + return builder.String() +} + +// Features is a parsable slice of Feature. +type Features []*Feature diff --git a/ent/db/feature/feature.go b/ent/db/feature/feature.go new file mode 100644 index 0000000000000000000000000000000000000000..31b9042abdb84996cc1fa90c340ba08331f0d090 --- /dev/null +++ b/ent/db/feature/feature.go @@ -0,0 +1,417 @@ +// Code generated by ent, DO NOT EDIT. + +package dbfeature + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the feature type in the database. + Label = "feature" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // 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" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // FieldNamespace holds the string denoting the namespace field in the database. + FieldNamespace = "namespace" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // FieldKey holds the string denoting the key field in the database. + FieldKey = "key" + // FieldMeterSlug holds the string denoting the meter_slug field in the database. + FieldMeterSlug = "meter_slug" + // FieldMeterID holds the string denoting the meter_id field in the database. + FieldMeterID = "meter_id" + // FieldMeterGroupByFilters holds the string denoting the meter_group_by_filters field in the database. + FieldMeterGroupByFilters = "meter_group_by_filters" + // FieldAdvancedMeterGroupByFilters holds the string denoting the advanced_meter_group_by_filters field in the database. + FieldAdvancedMeterGroupByFilters = "advanced_meter_group_by_filters" + // FieldUnitCostType holds the string denoting the unit_cost_type field in the database. + FieldUnitCostType = "unit_cost_type" + // FieldUnitCostManualAmount holds the string denoting the unit_cost_manual_amount field in the database. + FieldUnitCostManualAmount = "unit_cost_manual_amount" + // FieldUnitCostLlmProviderProperty holds the string denoting the unit_cost_llm_provider_property field in the database. + FieldUnitCostLlmProviderProperty = "unit_cost_llm_provider_property" + // FieldUnitCostLlmProvider holds the string denoting the unit_cost_llm_provider field in the database. + FieldUnitCostLlmProvider = "unit_cost_llm_provider" + // FieldUnitCostLlmModelProperty holds the string denoting the unit_cost_llm_model_property field in the database. + FieldUnitCostLlmModelProperty = "unit_cost_llm_model_property" + // FieldUnitCostLlmModel holds the string denoting the unit_cost_llm_model field in the database. + FieldUnitCostLlmModel = "unit_cost_llm_model" + // FieldUnitCostLlmTokenTypeProperty holds the string denoting the unit_cost_llm_token_type_property field in the database. + FieldUnitCostLlmTokenTypeProperty = "unit_cost_llm_token_type_property" + // FieldUnitCostLlmTokenType holds the string denoting the unit_cost_llm_token_type field in the database. + FieldUnitCostLlmTokenType = "unit_cost_llm_token_type" + // FieldArchivedAt holds the string denoting the archived_at field in the database. + FieldArchivedAt = "archived_at" + // EdgeEntitlement holds the string denoting the entitlement edge name in mutations. + EdgeEntitlement = "entitlement" + // EdgeRatecard holds the string denoting the ratecard edge name in mutations. + EdgeRatecard = "ratecard" + // EdgeAddonRatecard holds the string denoting the addon_ratecard edge name in mutations. + EdgeAddonRatecard = "addon_ratecard" + // EdgeUsageBasedCharges holds the string denoting the usage_based_charges edge name in mutations. + EdgeUsageBasedCharges = "usage_based_charges" + // EdgeUsageBasedRuns holds the string denoting the usage_based_runs edge name in mutations. + EdgeUsageBasedRuns = "usage_based_runs" + // EdgeFlatFeeCharges holds the string denoting the flat_fee_charges edge name in mutations. + EdgeFlatFeeCharges = "flat_fee_charges" + // EdgeMeter holds the string denoting the meter edge name in mutations. + EdgeMeter = "meter" + // Table holds the table name of the feature in the database. + Table = "features" + // EntitlementTable is the table that holds the entitlement relation/edge. + EntitlementTable = "entitlements" + // EntitlementInverseTable is the table name for the Entitlement entity. + // It exists in this package in order to avoid circular dependency with the "entitlement" package. + EntitlementInverseTable = "entitlements" + // EntitlementColumn is the table column denoting the entitlement relation/edge. + EntitlementColumn = "feature_id" + // RatecardTable is the table that holds the ratecard relation/edge. + RatecardTable = "plan_rate_cards" + // RatecardInverseTable is the table name for the PlanRateCard entity. + // It exists in this package in order to avoid circular dependency with the "planratecard" package. + RatecardInverseTable = "plan_rate_cards" + // RatecardColumn is the table column denoting the ratecard relation/edge. + RatecardColumn = "feature_id" + // AddonRatecardTable is the table that holds the addon_ratecard relation/edge. + AddonRatecardTable = "addon_rate_cards" + // AddonRatecardInverseTable is the table name for the AddonRateCard entity. + // It exists in this package in order to avoid circular dependency with the "addonratecard" package. + AddonRatecardInverseTable = "addon_rate_cards" + // AddonRatecardColumn is the table column denoting the addon_ratecard relation/edge. + AddonRatecardColumn = "feature_id" + // UsageBasedChargesTable is the table that holds the usage_based_charges relation/edge. + UsageBasedChargesTable = "charge_usage_based" + // UsageBasedChargesInverseTable is the table name for the ChargeUsageBased entity. + // It exists in this package in order to avoid circular dependency with the "chargeusagebased" package. + UsageBasedChargesInverseTable = "charge_usage_based" + // UsageBasedChargesColumn is the table column denoting the usage_based_charges relation/edge. + UsageBasedChargesColumn = "feature_id" + // UsageBasedRunsTable is the table that holds the usage_based_runs relation/edge. + UsageBasedRunsTable = "charge_usage_based_runs" + // UsageBasedRunsInverseTable is the table name for the ChargeUsageBasedRuns entity. + // It exists in this package in order to avoid circular dependency with the "chargeusagebasedruns" package. + UsageBasedRunsInverseTable = "charge_usage_based_runs" + // UsageBasedRunsColumn is the table column denoting the usage_based_runs relation/edge. + UsageBasedRunsColumn = "feature_id" + // FlatFeeChargesTable is the table that holds the flat_fee_charges relation/edge. + FlatFeeChargesTable = "charge_flat_fees" + // FlatFeeChargesInverseTable is the table name for the ChargeFlatFee entity. + // It exists in this package in order to avoid circular dependency with the "chargeflatfee" package. + FlatFeeChargesInverseTable = "charge_flat_fees" + // FlatFeeChargesColumn is the table column denoting the flat_fee_charges relation/edge. + FlatFeeChargesColumn = "feature_id" + // MeterTable is the table that holds the meter relation/edge. + MeterTable = "features" + // MeterInverseTable is the table name for the Meter entity. + // It exists in this package in order to avoid circular dependency with the "dbmeter" package. + MeterInverseTable = "meters" + // MeterColumn is the table column denoting the meter relation/edge. + MeterColumn = "meter_id" +) + +// Columns holds all SQL columns for feature fields. +var Columns = []string{ + FieldID, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldMetadata, + FieldNamespace, + FieldName, + FieldDescription, + FieldKey, + FieldMeterSlug, + FieldMeterID, + FieldMeterGroupByFilters, + FieldAdvancedMeterGroupByFilters, + FieldUnitCostType, + FieldUnitCostManualAmount, + FieldUnitCostLlmProviderProperty, + FieldUnitCostLlmProvider, + FieldUnitCostLlmModelProperty, + FieldUnitCostLlmModel, + FieldUnitCostLlmTokenTypeProperty, + FieldUnitCostLlmTokenType, + FieldArchivedAt, +} + +// 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 ( + // 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 + // NamespaceValidator is a validator for the "namespace" field. It is called by the builders before save. + NamespaceValidator func(string) error + // NameValidator is a validator for the "name" field. It is called by the builders before save. + NameValidator func(string) error + // DescriptionValidator is a validator for the "description" field. It is called by the builders before save. + DescriptionValidator func(string) error + // KeyValidator is a validator for the "key" field. It is called by the builders before save. + KeyValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// OrderOption defines the ordering options for the Feature 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() +} + +// 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() +} + +// ByNamespace orders the results by the namespace field. +func ByNamespace(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldNamespace, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, opts...).ToFunc() +} + +// ByKey orders the results by the key field. +func ByKey(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldKey, opts...).ToFunc() +} + +// ByMeterSlug orders the results by the meter_slug field. +func ByMeterSlug(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMeterSlug, opts...).ToFunc() +} + +// ByMeterID orders the results by the meter_id field. +func ByMeterID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMeterID, opts...).ToFunc() +} + +// ByUnitCostType orders the results by the unit_cost_type field. +func ByUnitCostType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUnitCostType, opts...).ToFunc() +} + +// ByUnitCostManualAmount orders the results by the unit_cost_manual_amount field. +func ByUnitCostManualAmount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUnitCostManualAmount, opts...).ToFunc() +} + +// ByUnitCostLlmProviderProperty orders the results by the unit_cost_llm_provider_property field. +func ByUnitCostLlmProviderProperty(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUnitCostLlmProviderProperty, opts...).ToFunc() +} + +// ByUnitCostLlmProvider orders the results by the unit_cost_llm_provider field. +func ByUnitCostLlmProvider(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUnitCostLlmProvider, opts...).ToFunc() +} + +// ByUnitCostLlmModelProperty orders the results by the unit_cost_llm_model_property field. +func ByUnitCostLlmModelProperty(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUnitCostLlmModelProperty, opts...).ToFunc() +} + +// ByUnitCostLlmModel orders the results by the unit_cost_llm_model field. +func ByUnitCostLlmModel(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUnitCostLlmModel, opts...).ToFunc() +} + +// ByUnitCostLlmTokenTypeProperty orders the results by the unit_cost_llm_token_type_property field. +func ByUnitCostLlmTokenTypeProperty(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUnitCostLlmTokenTypeProperty, opts...).ToFunc() +} + +// ByUnitCostLlmTokenType orders the results by the unit_cost_llm_token_type field. +func ByUnitCostLlmTokenType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUnitCostLlmTokenType, opts...).ToFunc() +} + +// ByArchivedAt orders the results by the archived_at field. +func ByArchivedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldArchivedAt, opts...).ToFunc() +} + +// ByEntitlementCount orders the results by entitlement count. +func ByEntitlementCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newEntitlementStep(), opts...) + } +} + +// ByEntitlement orders the results by entitlement terms. +func ByEntitlement(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newEntitlementStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByRatecardCount orders the results by ratecard count. +func ByRatecardCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newRatecardStep(), opts...) + } +} + +// ByRatecard orders the results by ratecard terms. +func ByRatecard(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newRatecardStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByAddonRatecardCount orders the results by addon_ratecard count. +func ByAddonRatecardCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newAddonRatecardStep(), opts...) + } +} + +// ByAddonRatecard orders the results by addon_ratecard terms. +func ByAddonRatecard(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newAddonRatecardStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByUsageBasedChargesCount orders the results by usage_based_charges count. +func ByUsageBasedChargesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newUsageBasedChargesStep(), opts...) + } +} + +// ByUsageBasedCharges orders the results by usage_based_charges terms. +func ByUsageBasedCharges(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUsageBasedChargesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByUsageBasedRunsCount orders the results by usage_based_runs count. +func ByUsageBasedRunsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newUsageBasedRunsStep(), opts...) + } +} + +// ByUsageBasedRuns orders the results by usage_based_runs terms. +func ByUsageBasedRuns(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUsageBasedRunsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByFlatFeeChargesCount orders the results by flat_fee_charges count. +func ByFlatFeeChargesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newFlatFeeChargesStep(), opts...) + } +} + +// ByFlatFeeCharges orders the results by flat_fee_charges terms. +func ByFlatFeeCharges(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newFlatFeeChargesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByMeterField orders the results by meter field. +func ByMeterField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newMeterStep(), sql.OrderByField(field, opts...)) + } +} +func newEntitlementStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(EntitlementInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, EntitlementTable, EntitlementColumn), + ) +} +func newRatecardStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RatecardInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, RatecardTable, RatecardColumn), + ) +} +func newAddonRatecardStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(AddonRatecardInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, AddonRatecardTable, AddonRatecardColumn), + ) +} +func newUsageBasedChargesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UsageBasedChargesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, UsageBasedChargesTable, UsageBasedChargesColumn), + ) +} +func newUsageBasedRunsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UsageBasedRunsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, UsageBasedRunsTable, UsageBasedRunsColumn), + ) +} +func newFlatFeeChargesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(FlatFeeChargesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, FlatFeeChargesTable, FlatFeeChargesColumn), + ) +} +func newMeterStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(MeterInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, MeterTable, MeterColumn), + ) +} diff --git a/ent/db/feature/where.go b/ent/db/feature/where.go new file mode 100644 index 0000000000000000000000000000000000000000..ac1bfdfe0ab32b7750bafe75460d0994f1e92d39 --- /dev/null +++ b/ent/db/feature/where.go @@ -0,0 +1,1538 @@ +// Code generated by ent, DO NOT EDIT. + +package dbfeature + +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.Feature { + return predicate.Feature(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.Feature { + return predicate.Feature(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.Feature { + return predicate.Feature(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.Feature { + return predicate.Feature(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.Feature { + return predicate.Feature(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.Feature { + return predicate.Feature(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.Feature { + return predicate.Feature(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.Feature { + return predicate.Feature(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.Feature { + return predicate.Feature(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.Feature { + return predicate.Feature(sql.FieldContainsFold(FieldID, id)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.Feature { + return predicate.Feature(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.Feature { + return predicate.Feature(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.Feature { + return predicate.Feature(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldNamespace, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldName, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldDescription, v)) +} + +// Key applies equality check predicate on the "key" field. It's identical to KeyEQ. +func Key(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldKey, v)) +} + +// MeterSlug applies equality check predicate on the "meter_slug" field. It's identical to MeterSlugEQ. +func MeterSlug(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldMeterSlug, v)) +} + +// MeterID applies equality check predicate on the "meter_id" field. It's identical to MeterIDEQ. +func MeterID(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldMeterID, v)) +} + +// UnitCostType applies equality check predicate on the "unit_cost_type" field. It's identical to UnitCostTypeEQ. +func UnitCostType(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldUnitCostType, v)) +} + +// UnitCostManualAmount applies equality check predicate on the "unit_cost_manual_amount" field. It's identical to UnitCostManualAmountEQ. +func UnitCostManualAmount(v alpacadecimal.Decimal) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldUnitCostManualAmount, v)) +} + +// UnitCostLlmProviderProperty applies equality check predicate on the "unit_cost_llm_provider_property" field. It's identical to UnitCostLlmProviderPropertyEQ. +func UnitCostLlmProviderProperty(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldUnitCostLlmProviderProperty, v)) +} + +// UnitCostLlmProvider applies equality check predicate on the "unit_cost_llm_provider" field. It's identical to UnitCostLlmProviderEQ. +func UnitCostLlmProvider(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldUnitCostLlmProvider, v)) +} + +// UnitCostLlmModelProperty applies equality check predicate on the "unit_cost_llm_model_property" field. It's identical to UnitCostLlmModelPropertyEQ. +func UnitCostLlmModelProperty(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldUnitCostLlmModelProperty, v)) +} + +// UnitCostLlmModel applies equality check predicate on the "unit_cost_llm_model" field. It's identical to UnitCostLlmModelEQ. +func UnitCostLlmModel(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldUnitCostLlmModel, v)) +} + +// UnitCostLlmTokenTypeProperty applies equality check predicate on the "unit_cost_llm_token_type_property" field. It's identical to UnitCostLlmTokenTypePropertyEQ. +func UnitCostLlmTokenTypeProperty(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldUnitCostLlmTokenTypeProperty, v)) +} + +// UnitCostLlmTokenType applies equality check predicate on the "unit_cost_llm_token_type" field. It's identical to UnitCostLlmTokenTypeEQ. +func UnitCostLlmTokenType(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldUnitCostLlmTokenType, v)) +} + +// ArchivedAt applies equality check predicate on the "archived_at" field. It's identical to ArchivedAtEQ. +func ArchivedAt(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldArchivedAt, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Feature { + return predicate.Feature(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Feature { + return predicate.Feature(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.Feature { + return predicate.Feature(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.Feature { + return predicate.Feature(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.Feature { + return predicate.Feature(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.Feature { + return predicate.Feature(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.Feature { + return predicate.Feature(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.Feature { + return predicate.Feature(sql.FieldNotNull(FieldDeletedAt)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.Feature { + return predicate.Feature(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.Feature { + return predicate.Feature(sql.FieldNotNull(FieldMetadata)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.Feature { + return predicate.Feature(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.Feature { + return predicate.Feature(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.Feature { + return predicate.Feature(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldContainsFold(FieldNamespace, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.Feature { + return predicate.Feature(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.Feature { + return predicate.Feature(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.Feature { + return predicate.Feature(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldContainsFold(FieldName, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.Feature { + return predicate.Feature(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.Feature { + return predicate.Feature(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.Feature { + return predicate.Feature(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.Feature { + return predicate.Feature(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.Feature { + return predicate.Feature(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldContainsFold(FieldDescription, v)) +} + +// KeyEQ applies the EQ predicate on the "key" field. +func KeyEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldKey, v)) +} + +// KeyNEQ applies the NEQ predicate on the "key" field. +func KeyNEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldNEQ(FieldKey, v)) +} + +// KeyIn applies the In predicate on the "key" field. +func KeyIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldIn(FieldKey, vs...)) +} + +// KeyNotIn applies the NotIn predicate on the "key" field. +func KeyNotIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldNotIn(FieldKey, vs...)) +} + +// KeyGT applies the GT predicate on the "key" field. +func KeyGT(v string) predicate.Feature { + return predicate.Feature(sql.FieldGT(FieldKey, v)) +} + +// KeyGTE applies the GTE predicate on the "key" field. +func KeyGTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldGTE(FieldKey, v)) +} + +// KeyLT applies the LT predicate on the "key" field. +func KeyLT(v string) predicate.Feature { + return predicate.Feature(sql.FieldLT(FieldKey, v)) +} + +// KeyLTE applies the LTE predicate on the "key" field. +func KeyLTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldLTE(FieldKey, v)) +} + +// KeyContains applies the Contains predicate on the "key" field. +func KeyContains(v string) predicate.Feature { + return predicate.Feature(sql.FieldContains(FieldKey, v)) +} + +// KeyHasPrefix applies the HasPrefix predicate on the "key" field. +func KeyHasPrefix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasPrefix(FieldKey, v)) +} + +// KeyHasSuffix applies the HasSuffix predicate on the "key" field. +func KeyHasSuffix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasSuffix(FieldKey, v)) +} + +// KeyEqualFold applies the EqualFold predicate on the "key" field. +func KeyEqualFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldEqualFold(FieldKey, v)) +} + +// KeyContainsFold applies the ContainsFold predicate on the "key" field. +func KeyContainsFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldContainsFold(FieldKey, v)) +} + +// MeterSlugEQ applies the EQ predicate on the "meter_slug" field. +func MeterSlugEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldMeterSlug, v)) +} + +// MeterSlugNEQ applies the NEQ predicate on the "meter_slug" field. +func MeterSlugNEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldNEQ(FieldMeterSlug, v)) +} + +// MeterSlugIn applies the In predicate on the "meter_slug" field. +func MeterSlugIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldIn(FieldMeterSlug, vs...)) +} + +// MeterSlugNotIn applies the NotIn predicate on the "meter_slug" field. +func MeterSlugNotIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldNotIn(FieldMeterSlug, vs...)) +} + +// MeterSlugGT applies the GT predicate on the "meter_slug" field. +func MeterSlugGT(v string) predicate.Feature { + return predicate.Feature(sql.FieldGT(FieldMeterSlug, v)) +} + +// MeterSlugGTE applies the GTE predicate on the "meter_slug" field. +func MeterSlugGTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldGTE(FieldMeterSlug, v)) +} + +// MeterSlugLT applies the LT predicate on the "meter_slug" field. +func MeterSlugLT(v string) predicate.Feature { + return predicate.Feature(sql.FieldLT(FieldMeterSlug, v)) +} + +// MeterSlugLTE applies the LTE predicate on the "meter_slug" field. +func MeterSlugLTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldLTE(FieldMeterSlug, v)) +} + +// MeterSlugContains applies the Contains predicate on the "meter_slug" field. +func MeterSlugContains(v string) predicate.Feature { + return predicate.Feature(sql.FieldContains(FieldMeterSlug, v)) +} + +// MeterSlugHasPrefix applies the HasPrefix predicate on the "meter_slug" field. +func MeterSlugHasPrefix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasPrefix(FieldMeterSlug, v)) +} + +// MeterSlugHasSuffix applies the HasSuffix predicate on the "meter_slug" field. +func MeterSlugHasSuffix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasSuffix(FieldMeterSlug, v)) +} + +// MeterSlugIsNil applies the IsNil predicate on the "meter_slug" field. +func MeterSlugIsNil() predicate.Feature { + return predicate.Feature(sql.FieldIsNull(FieldMeterSlug)) +} + +// MeterSlugNotNil applies the NotNil predicate on the "meter_slug" field. +func MeterSlugNotNil() predicate.Feature { + return predicate.Feature(sql.FieldNotNull(FieldMeterSlug)) +} + +// MeterSlugEqualFold applies the EqualFold predicate on the "meter_slug" field. +func MeterSlugEqualFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldEqualFold(FieldMeterSlug, v)) +} + +// MeterSlugContainsFold applies the ContainsFold predicate on the "meter_slug" field. +func MeterSlugContainsFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldContainsFold(FieldMeterSlug, v)) +} + +// MeterIDEQ applies the EQ predicate on the "meter_id" field. +func MeterIDEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldMeterID, v)) +} + +// MeterIDNEQ applies the NEQ predicate on the "meter_id" field. +func MeterIDNEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldNEQ(FieldMeterID, v)) +} + +// MeterIDIn applies the In predicate on the "meter_id" field. +func MeterIDIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldIn(FieldMeterID, vs...)) +} + +// MeterIDNotIn applies the NotIn predicate on the "meter_id" field. +func MeterIDNotIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldNotIn(FieldMeterID, vs...)) +} + +// MeterIDGT applies the GT predicate on the "meter_id" field. +func MeterIDGT(v string) predicate.Feature { + return predicate.Feature(sql.FieldGT(FieldMeterID, v)) +} + +// MeterIDGTE applies the GTE predicate on the "meter_id" field. +func MeterIDGTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldGTE(FieldMeterID, v)) +} + +// MeterIDLT applies the LT predicate on the "meter_id" field. +func MeterIDLT(v string) predicate.Feature { + return predicate.Feature(sql.FieldLT(FieldMeterID, v)) +} + +// MeterIDLTE applies the LTE predicate on the "meter_id" field. +func MeterIDLTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldLTE(FieldMeterID, v)) +} + +// MeterIDContains applies the Contains predicate on the "meter_id" field. +func MeterIDContains(v string) predicate.Feature { + return predicate.Feature(sql.FieldContains(FieldMeterID, v)) +} + +// MeterIDHasPrefix applies the HasPrefix predicate on the "meter_id" field. +func MeterIDHasPrefix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasPrefix(FieldMeterID, v)) +} + +// MeterIDHasSuffix applies the HasSuffix predicate on the "meter_id" field. +func MeterIDHasSuffix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasSuffix(FieldMeterID, v)) +} + +// MeterIDIsNil applies the IsNil predicate on the "meter_id" field. +func MeterIDIsNil() predicate.Feature { + return predicate.Feature(sql.FieldIsNull(FieldMeterID)) +} + +// MeterIDNotNil applies the NotNil predicate on the "meter_id" field. +func MeterIDNotNil() predicate.Feature { + return predicate.Feature(sql.FieldNotNull(FieldMeterID)) +} + +// MeterIDEqualFold applies the EqualFold predicate on the "meter_id" field. +func MeterIDEqualFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldEqualFold(FieldMeterID, v)) +} + +// MeterIDContainsFold applies the ContainsFold predicate on the "meter_id" field. +func MeterIDContainsFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldContainsFold(FieldMeterID, v)) +} + +// MeterGroupByFiltersIsNil applies the IsNil predicate on the "meter_group_by_filters" field. +func MeterGroupByFiltersIsNil() predicate.Feature { + return predicate.Feature(sql.FieldIsNull(FieldMeterGroupByFilters)) +} + +// MeterGroupByFiltersNotNil applies the NotNil predicate on the "meter_group_by_filters" field. +func MeterGroupByFiltersNotNil() predicate.Feature { + return predicate.Feature(sql.FieldNotNull(FieldMeterGroupByFilters)) +} + +// AdvancedMeterGroupByFiltersIsNil applies the IsNil predicate on the "advanced_meter_group_by_filters" field. +func AdvancedMeterGroupByFiltersIsNil() predicate.Feature { + return predicate.Feature(sql.FieldIsNull(FieldAdvancedMeterGroupByFilters)) +} + +// AdvancedMeterGroupByFiltersNotNil applies the NotNil predicate on the "advanced_meter_group_by_filters" field. +func AdvancedMeterGroupByFiltersNotNil() predicate.Feature { + return predicate.Feature(sql.FieldNotNull(FieldAdvancedMeterGroupByFilters)) +} + +// UnitCostTypeEQ applies the EQ predicate on the "unit_cost_type" field. +func UnitCostTypeEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldUnitCostType, v)) +} + +// UnitCostTypeNEQ applies the NEQ predicate on the "unit_cost_type" field. +func UnitCostTypeNEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldNEQ(FieldUnitCostType, v)) +} + +// UnitCostTypeIn applies the In predicate on the "unit_cost_type" field. +func UnitCostTypeIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldIn(FieldUnitCostType, vs...)) +} + +// UnitCostTypeNotIn applies the NotIn predicate on the "unit_cost_type" field. +func UnitCostTypeNotIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldNotIn(FieldUnitCostType, vs...)) +} + +// UnitCostTypeGT applies the GT predicate on the "unit_cost_type" field. +func UnitCostTypeGT(v string) predicate.Feature { + return predicate.Feature(sql.FieldGT(FieldUnitCostType, v)) +} + +// UnitCostTypeGTE applies the GTE predicate on the "unit_cost_type" field. +func UnitCostTypeGTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldGTE(FieldUnitCostType, v)) +} + +// UnitCostTypeLT applies the LT predicate on the "unit_cost_type" field. +func UnitCostTypeLT(v string) predicate.Feature { + return predicate.Feature(sql.FieldLT(FieldUnitCostType, v)) +} + +// UnitCostTypeLTE applies the LTE predicate on the "unit_cost_type" field. +func UnitCostTypeLTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldLTE(FieldUnitCostType, v)) +} + +// UnitCostTypeContains applies the Contains predicate on the "unit_cost_type" field. +func UnitCostTypeContains(v string) predicate.Feature { + return predicate.Feature(sql.FieldContains(FieldUnitCostType, v)) +} + +// UnitCostTypeHasPrefix applies the HasPrefix predicate on the "unit_cost_type" field. +func UnitCostTypeHasPrefix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasPrefix(FieldUnitCostType, v)) +} + +// UnitCostTypeHasSuffix applies the HasSuffix predicate on the "unit_cost_type" field. +func UnitCostTypeHasSuffix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasSuffix(FieldUnitCostType, v)) +} + +// UnitCostTypeIsNil applies the IsNil predicate on the "unit_cost_type" field. +func UnitCostTypeIsNil() predicate.Feature { + return predicate.Feature(sql.FieldIsNull(FieldUnitCostType)) +} + +// UnitCostTypeNotNil applies the NotNil predicate on the "unit_cost_type" field. +func UnitCostTypeNotNil() predicate.Feature { + return predicate.Feature(sql.FieldNotNull(FieldUnitCostType)) +} + +// UnitCostTypeEqualFold applies the EqualFold predicate on the "unit_cost_type" field. +func UnitCostTypeEqualFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldEqualFold(FieldUnitCostType, v)) +} + +// UnitCostTypeContainsFold applies the ContainsFold predicate on the "unit_cost_type" field. +func UnitCostTypeContainsFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldContainsFold(FieldUnitCostType, v)) +} + +// UnitCostManualAmountEQ applies the EQ predicate on the "unit_cost_manual_amount" field. +func UnitCostManualAmountEQ(v alpacadecimal.Decimal) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldUnitCostManualAmount, v)) +} + +// UnitCostManualAmountNEQ applies the NEQ predicate on the "unit_cost_manual_amount" field. +func UnitCostManualAmountNEQ(v alpacadecimal.Decimal) predicate.Feature { + return predicate.Feature(sql.FieldNEQ(FieldUnitCostManualAmount, v)) +} + +// UnitCostManualAmountIn applies the In predicate on the "unit_cost_manual_amount" field. +func UnitCostManualAmountIn(vs ...alpacadecimal.Decimal) predicate.Feature { + return predicate.Feature(sql.FieldIn(FieldUnitCostManualAmount, vs...)) +} + +// UnitCostManualAmountNotIn applies the NotIn predicate on the "unit_cost_manual_amount" field. +func UnitCostManualAmountNotIn(vs ...alpacadecimal.Decimal) predicate.Feature { + return predicate.Feature(sql.FieldNotIn(FieldUnitCostManualAmount, vs...)) +} + +// UnitCostManualAmountGT applies the GT predicate on the "unit_cost_manual_amount" field. +func UnitCostManualAmountGT(v alpacadecimal.Decimal) predicate.Feature { + return predicate.Feature(sql.FieldGT(FieldUnitCostManualAmount, v)) +} + +// UnitCostManualAmountGTE applies the GTE predicate on the "unit_cost_manual_amount" field. +func UnitCostManualAmountGTE(v alpacadecimal.Decimal) predicate.Feature { + return predicate.Feature(sql.FieldGTE(FieldUnitCostManualAmount, v)) +} + +// UnitCostManualAmountLT applies the LT predicate on the "unit_cost_manual_amount" field. +func UnitCostManualAmountLT(v alpacadecimal.Decimal) predicate.Feature { + return predicate.Feature(sql.FieldLT(FieldUnitCostManualAmount, v)) +} + +// UnitCostManualAmountLTE applies the LTE predicate on the "unit_cost_manual_amount" field. +func UnitCostManualAmountLTE(v alpacadecimal.Decimal) predicate.Feature { + return predicate.Feature(sql.FieldLTE(FieldUnitCostManualAmount, v)) +} + +// UnitCostManualAmountIsNil applies the IsNil predicate on the "unit_cost_manual_amount" field. +func UnitCostManualAmountIsNil() predicate.Feature { + return predicate.Feature(sql.FieldIsNull(FieldUnitCostManualAmount)) +} + +// UnitCostManualAmountNotNil applies the NotNil predicate on the "unit_cost_manual_amount" field. +func UnitCostManualAmountNotNil() predicate.Feature { + return predicate.Feature(sql.FieldNotNull(FieldUnitCostManualAmount)) +} + +// UnitCostLlmProviderPropertyEQ applies the EQ predicate on the "unit_cost_llm_provider_property" field. +func UnitCostLlmProviderPropertyEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldUnitCostLlmProviderProperty, v)) +} + +// UnitCostLlmProviderPropertyNEQ applies the NEQ predicate on the "unit_cost_llm_provider_property" field. +func UnitCostLlmProviderPropertyNEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldNEQ(FieldUnitCostLlmProviderProperty, v)) +} + +// UnitCostLlmProviderPropertyIn applies the In predicate on the "unit_cost_llm_provider_property" field. +func UnitCostLlmProviderPropertyIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldIn(FieldUnitCostLlmProviderProperty, vs...)) +} + +// UnitCostLlmProviderPropertyNotIn applies the NotIn predicate on the "unit_cost_llm_provider_property" field. +func UnitCostLlmProviderPropertyNotIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldNotIn(FieldUnitCostLlmProviderProperty, vs...)) +} + +// UnitCostLlmProviderPropertyGT applies the GT predicate on the "unit_cost_llm_provider_property" field. +func UnitCostLlmProviderPropertyGT(v string) predicate.Feature { + return predicate.Feature(sql.FieldGT(FieldUnitCostLlmProviderProperty, v)) +} + +// UnitCostLlmProviderPropertyGTE applies the GTE predicate on the "unit_cost_llm_provider_property" field. +func UnitCostLlmProviderPropertyGTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldGTE(FieldUnitCostLlmProviderProperty, v)) +} + +// UnitCostLlmProviderPropertyLT applies the LT predicate on the "unit_cost_llm_provider_property" field. +func UnitCostLlmProviderPropertyLT(v string) predicate.Feature { + return predicate.Feature(sql.FieldLT(FieldUnitCostLlmProviderProperty, v)) +} + +// UnitCostLlmProviderPropertyLTE applies the LTE predicate on the "unit_cost_llm_provider_property" field. +func UnitCostLlmProviderPropertyLTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldLTE(FieldUnitCostLlmProviderProperty, v)) +} + +// UnitCostLlmProviderPropertyContains applies the Contains predicate on the "unit_cost_llm_provider_property" field. +func UnitCostLlmProviderPropertyContains(v string) predicate.Feature { + return predicate.Feature(sql.FieldContains(FieldUnitCostLlmProviderProperty, v)) +} + +// UnitCostLlmProviderPropertyHasPrefix applies the HasPrefix predicate on the "unit_cost_llm_provider_property" field. +func UnitCostLlmProviderPropertyHasPrefix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasPrefix(FieldUnitCostLlmProviderProperty, v)) +} + +// UnitCostLlmProviderPropertyHasSuffix applies the HasSuffix predicate on the "unit_cost_llm_provider_property" field. +func UnitCostLlmProviderPropertyHasSuffix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasSuffix(FieldUnitCostLlmProviderProperty, v)) +} + +// UnitCostLlmProviderPropertyIsNil applies the IsNil predicate on the "unit_cost_llm_provider_property" field. +func UnitCostLlmProviderPropertyIsNil() predicate.Feature { + return predicate.Feature(sql.FieldIsNull(FieldUnitCostLlmProviderProperty)) +} + +// UnitCostLlmProviderPropertyNotNil applies the NotNil predicate on the "unit_cost_llm_provider_property" field. +func UnitCostLlmProviderPropertyNotNil() predicate.Feature { + return predicate.Feature(sql.FieldNotNull(FieldUnitCostLlmProviderProperty)) +} + +// UnitCostLlmProviderPropertyEqualFold applies the EqualFold predicate on the "unit_cost_llm_provider_property" field. +func UnitCostLlmProviderPropertyEqualFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldEqualFold(FieldUnitCostLlmProviderProperty, v)) +} + +// UnitCostLlmProviderPropertyContainsFold applies the ContainsFold predicate on the "unit_cost_llm_provider_property" field. +func UnitCostLlmProviderPropertyContainsFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldContainsFold(FieldUnitCostLlmProviderProperty, v)) +} + +// UnitCostLlmProviderEQ applies the EQ predicate on the "unit_cost_llm_provider" field. +func UnitCostLlmProviderEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldUnitCostLlmProvider, v)) +} + +// UnitCostLlmProviderNEQ applies the NEQ predicate on the "unit_cost_llm_provider" field. +func UnitCostLlmProviderNEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldNEQ(FieldUnitCostLlmProvider, v)) +} + +// UnitCostLlmProviderIn applies the In predicate on the "unit_cost_llm_provider" field. +func UnitCostLlmProviderIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldIn(FieldUnitCostLlmProvider, vs...)) +} + +// UnitCostLlmProviderNotIn applies the NotIn predicate on the "unit_cost_llm_provider" field. +func UnitCostLlmProviderNotIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldNotIn(FieldUnitCostLlmProvider, vs...)) +} + +// UnitCostLlmProviderGT applies the GT predicate on the "unit_cost_llm_provider" field. +func UnitCostLlmProviderGT(v string) predicate.Feature { + return predicate.Feature(sql.FieldGT(FieldUnitCostLlmProvider, v)) +} + +// UnitCostLlmProviderGTE applies the GTE predicate on the "unit_cost_llm_provider" field. +func UnitCostLlmProviderGTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldGTE(FieldUnitCostLlmProvider, v)) +} + +// UnitCostLlmProviderLT applies the LT predicate on the "unit_cost_llm_provider" field. +func UnitCostLlmProviderLT(v string) predicate.Feature { + return predicate.Feature(sql.FieldLT(FieldUnitCostLlmProvider, v)) +} + +// UnitCostLlmProviderLTE applies the LTE predicate on the "unit_cost_llm_provider" field. +func UnitCostLlmProviderLTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldLTE(FieldUnitCostLlmProvider, v)) +} + +// UnitCostLlmProviderContains applies the Contains predicate on the "unit_cost_llm_provider" field. +func UnitCostLlmProviderContains(v string) predicate.Feature { + return predicate.Feature(sql.FieldContains(FieldUnitCostLlmProvider, v)) +} + +// UnitCostLlmProviderHasPrefix applies the HasPrefix predicate on the "unit_cost_llm_provider" field. +func UnitCostLlmProviderHasPrefix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasPrefix(FieldUnitCostLlmProvider, v)) +} + +// UnitCostLlmProviderHasSuffix applies the HasSuffix predicate on the "unit_cost_llm_provider" field. +func UnitCostLlmProviderHasSuffix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasSuffix(FieldUnitCostLlmProvider, v)) +} + +// UnitCostLlmProviderIsNil applies the IsNil predicate on the "unit_cost_llm_provider" field. +func UnitCostLlmProviderIsNil() predicate.Feature { + return predicate.Feature(sql.FieldIsNull(FieldUnitCostLlmProvider)) +} + +// UnitCostLlmProviderNotNil applies the NotNil predicate on the "unit_cost_llm_provider" field. +func UnitCostLlmProviderNotNil() predicate.Feature { + return predicate.Feature(sql.FieldNotNull(FieldUnitCostLlmProvider)) +} + +// UnitCostLlmProviderEqualFold applies the EqualFold predicate on the "unit_cost_llm_provider" field. +func UnitCostLlmProviderEqualFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldEqualFold(FieldUnitCostLlmProvider, v)) +} + +// UnitCostLlmProviderContainsFold applies the ContainsFold predicate on the "unit_cost_llm_provider" field. +func UnitCostLlmProviderContainsFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldContainsFold(FieldUnitCostLlmProvider, v)) +} + +// UnitCostLlmModelPropertyEQ applies the EQ predicate on the "unit_cost_llm_model_property" field. +func UnitCostLlmModelPropertyEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldUnitCostLlmModelProperty, v)) +} + +// UnitCostLlmModelPropertyNEQ applies the NEQ predicate on the "unit_cost_llm_model_property" field. +func UnitCostLlmModelPropertyNEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldNEQ(FieldUnitCostLlmModelProperty, v)) +} + +// UnitCostLlmModelPropertyIn applies the In predicate on the "unit_cost_llm_model_property" field. +func UnitCostLlmModelPropertyIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldIn(FieldUnitCostLlmModelProperty, vs...)) +} + +// UnitCostLlmModelPropertyNotIn applies the NotIn predicate on the "unit_cost_llm_model_property" field. +func UnitCostLlmModelPropertyNotIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldNotIn(FieldUnitCostLlmModelProperty, vs...)) +} + +// UnitCostLlmModelPropertyGT applies the GT predicate on the "unit_cost_llm_model_property" field. +func UnitCostLlmModelPropertyGT(v string) predicate.Feature { + return predicate.Feature(sql.FieldGT(FieldUnitCostLlmModelProperty, v)) +} + +// UnitCostLlmModelPropertyGTE applies the GTE predicate on the "unit_cost_llm_model_property" field. +func UnitCostLlmModelPropertyGTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldGTE(FieldUnitCostLlmModelProperty, v)) +} + +// UnitCostLlmModelPropertyLT applies the LT predicate on the "unit_cost_llm_model_property" field. +func UnitCostLlmModelPropertyLT(v string) predicate.Feature { + return predicate.Feature(sql.FieldLT(FieldUnitCostLlmModelProperty, v)) +} + +// UnitCostLlmModelPropertyLTE applies the LTE predicate on the "unit_cost_llm_model_property" field. +func UnitCostLlmModelPropertyLTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldLTE(FieldUnitCostLlmModelProperty, v)) +} + +// UnitCostLlmModelPropertyContains applies the Contains predicate on the "unit_cost_llm_model_property" field. +func UnitCostLlmModelPropertyContains(v string) predicate.Feature { + return predicate.Feature(sql.FieldContains(FieldUnitCostLlmModelProperty, v)) +} + +// UnitCostLlmModelPropertyHasPrefix applies the HasPrefix predicate on the "unit_cost_llm_model_property" field. +func UnitCostLlmModelPropertyHasPrefix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasPrefix(FieldUnitCostLlmModelProperty, v)) +} + +// UnitCostLlmModelPropertyHasSuffix applies the HasSuffix predicate on the "unit_cost_llm_model_property" field. +func UnitCostLlmModelPropertyHasSuffix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasSuffix(FieldUnitCostLlmModelProperty, v)) +} + +// UnitCostLlmModelPropertyIsNil applies the IsNil predicate on the "unit_cost_llm_model_property" field. +func UnitCostLlmModelPropertyIsNil() predicate.Feature { + return predicate.Feature(sql.FieldIsNull(FieldUnitCostLlmModelProperty)) +} + +// UnitCostLlmModelPropertyNotNil applies the NotNil predicate on the "unit_cost_llm_model_property" field. +func UnitCostLlmModelPropertyNotNil() predicate.Feature { + return predicate.Feature(sql.FieldNotNull(FieldUnitCostLlmModelProperty)) +} + +// UnitCostLlmModelPropertyEqualFold applies the EqualFold predicate on the "unit_cost_llm_model_property" field. +func UnitCostLlmModelPropertyEqualFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldEqualFold(FieldUnitCostLlmModelProperty, v)) +} + +// UnitCostLlmModelPropertyContainsFold applies the ContainsFold predicate on the "unit_cost_llm_model_property" field. +func UnitCostLlmModelPropertyContainsFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldContainsFold(FieldUnitCostLlmModelProperty, v)) +} + +// UnitCostLlmModelEQ applies the EQ predicate on the "unit_cost_llm_model" field. +func UnitCostLlmModelEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldUnitCostLlmModel, v)) +} + +// UnitCostLlmModelNEQ applies the NEQ predicate on the "unit_cost_llm_model" field. +func UnitCostLlmModelNEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldNEQ(FieldUnitCostLlmModel, v)) +} + +// UnitCostLlmModelIn applies the In predicate on the "unit_cost_llm_model" field. +func UnitCostLlmModelIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldIn(FieldUnitCostLlmModel, vs...)) +} + +// UnitCostLlmModelNotIn applies the NotIn predicate on the "unit_cost_llm_model" field. +func UnitCostLlmModelNotIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldNotIn(FieldUnitCostLlmModel, vs...)) +} + +// UnitCostLlmModelGT applies the GT predicate on the "unit_cost_llm_model" field. +func UnitCostLlmModelGT(v string) predicate.Feature { + return predicate.Feature(sql.FieldGT(FieldUnitCostLlmModel, v)) +} + +// UnitCostLlmModelGTE applies the GTE predicate on the "unit_cost_llm_model" field. +func UnitCostLlmModelGTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldGTE(FieldUnitCostLlmModel, v)) +} + +// UnitCostLlmModelLT applies the LT predicate on the "unit_cost_llm_model" field. +func UnitCostLlmModelLT(v string) predicate.Feature { + return predicate.Feature(sql.FieldLT(FieldUnitCostLlmModel, v)) +} + +// UnitCostLlmModelLTE applies the LTE predicate on the "unit_cost_llm_model" field. +func UnitCostLlmModelLTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldLTE(FieldUnitCostLlmModel, v)) +} + +// UnitCostLlmModelContains applies the Contains predicate on the "unit_cost_llm_model" field. +func UnitCostLlmModelContains(v string) predicate.Feature { + return predicate.Feature(sql.FieldContains(FieldUnitCostLlmModel, v)) +} + +// UnitCostLlmModelHasPrefix applies the HasPrefix predicate on the "unit_cost_llm_model" field. +func UnitCostLlmModelHasPrefix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasPrefix(FieldUnitCostLlmModel, v)) +} + +// UnitCostLlmModelHasSuffix applies the HasSuffix predicate on the "unit_cost_llm_model" field. +func UnitCostLlmModelHasSuffix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasSuffix(FieldUnitCostLlmModel, v)) +} + +// UnitCostLlmModelIsNil applies the IsNil predicate on the "unit_cost_llm_model" field. +func UnitCostLlmModelIsNil() predicate.Feature { + return predicate.Feature(sql.FieldIsNull(FieldUnitCostLlmModel)) +} + +// UnitCostLlmModelNotNil applies the NotNil predicate on the "unit_cost_llm_model" field. +func UnitCostLlmModelNotNil() predicate.Feature { + return predicate.Feature(sql.FieldNotNull(FieldUnitCostLlmModel)) +} + +// UnitCostLlmModelEqualFold applies the EqualFold predicate on the "unit_cost_llm_model" field. +func UnitCostLlmModelEqualFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldEqualFold(FieldUnitCostLlmModel, v)) +} + +// UnitCostLlmModelContainsFold applies the ContainsFold predicate on the "unit_cost_llm_model" field. +func UnitCostLlmModelContainsFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldContainsFold(FieldUnitCostLlmModel, v)) +} + +// UnitCostLlmTokenTypePropertyEQ applies the EQ predicate on the "unit_cost_llm_token_type_property" field. +func UnitCostLlmTokenTypePropertyEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldUnitCostLlmTokenTypeProperty, v)) +} + +// UnitCostLlmTokenTypePropertyNEQ applies the NEQ predicate on the "unit_cost_llm_token_type_property" field. +func UnitCostLlmTokenTypePropertyNEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldNEQ(FieldUnitCostLlmTokenTypeProperty, v)) +} + +// UnitCostLlmTokenTypePropertyIn applies the In predicate on the "unit_cost_llm_token_type_property" field. +func UnitCostLlmTokenTypePropertyIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldIn(FieldUnitCostLlmTokenTypeProperty, vs...)) +} + +// UnitCostLlmTokenTypePropertyNotIn applies the NotIn predicate on the "unit_cost_llm_token_type_property" field. +func UnitCostLlmTokenTypePropertyNotIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldNotIn(FieldUnitCostLlmTokenTypeProperty, vs...)) +} + +// UnitCostLlmTokenTypePropertyGT applies the GT predicate on the "unit_cost_llm_token_type_property" field. +func UnitCostLlmTokenTypePropertyGT(v string) predicate.Feature { + return predicate.Feature(sql.FieldGT(FieldUnitCostLlmTokenTypeProperty, v)) +} + +// UnitCostLlmTokenTypePropertyGTE applies the GTE predicate on the "unit_cost_llm_token_type_property" field. +func UnitCostLlmTokenTypePropertyGTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldGTE(FieldUnitCostLlmTokenTypeProperty, v)) +} + +// UnitCostLlmTokenTypePropertyLT applies the LT predicate on the "unit_cost_llm_token_type_property" field. +func UnitCostLlmTokenTypePropertyLT(v string) predicate.Feature { + return predicate.Feature(sql.FieldLT(FieldUnitCostLlmTokenTypeProperty, v)) +} + +// UnitCostLlmTokenTypePropertyLTE applies the LTE predicate on the "unit_cost_llm_token_type_property" field. +func UnitCostLlmTokenTypePropertyLTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldLTE(FieldUnitCostLlmTokenTypeProperty, v)) +} + +// UnitCostLlmTokenTypePropertyContains applies the Contains predicate on the "unit_cost_llm_token_type_property" field. +func UnitCostLlmTokenTypePropertyContains(v string) predicate.Feature { + return predicate.Feature(sql.FieldContains(FieldUnitCostLlmTokenTypeProperty, v)) +} + +// UnitCostLlmTokenTypePropertyHasPrefix applies the HasPrefix predicate on the "unit_cost_llm_token_type_property" field. +func UnitCostLlmTokenTypePropertyHasPrefix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasPrefix(FieldUnitCostLlmTokenTypeProperty, v)) +} + +// UnitCostLlmTokenTypePropertyHasSuffix applies the HasSuffix predicate on the "unit_cost_llm_token_type_property" field. +func UnitCostLlmTokenTypePropertyHasSuffix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasSuffix(FieldUnitCostLlmTokenTypeProperty, v)) +} + +// UnitCostLlmTokenTypePropertyIsNil applies the IsNil predicate on the "unit_cost_llm_token_type_property" field. +func UnitCostLlmTokenTypePropertyIsNil() predicate.Feature { + return predicate.Feature(sql.FieldIsNull(FieldUnitCostLlmTokenTypeProperty)) +} + +// UnitCostLlmTokenTypePropertyNotNil applies the NotNil predicate on the "unit_cost_llm_token_type_property" field. +func UnitCostLlmTokenTypePropertyNotNil() predicate.Feature { + return predicate.Feature(sql.FieldNotNull(FieldUnitCostLlmTokenTypeProperty)) +} + +// UnitCostLlmTokenTypePropertyEqualFold applies the EqualFold predicate on the "unit_cost_llm_token_type_property" field. +func UnitCostLlmTokenTypePropertyEqualFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldEqualFold(FieldUnitCostLlmTokenTypeProperty, v)) +} + +// UnitCostLlmTokenTypePropertyContainsFold applies the ContainsFold predicate on the "unit_cost_llm_token_type_property" field. +func UnitCostLlmTokenTypePropertyContainsFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldContainsFold(FieldUnitCostLlmTokenTypeProperty, v)) +} + +// UnitCostLlmTokenTypeEQ applies the EQ predicate on the "unit_cost_llm_token_type" field. +func UnitCostLlmTokenTypeEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldUnitCostLlmTokenType, v)) +} + +// UnitCostLlmTokenTypeNEQ applies the NEQ predicate on the "unit_cost_llm_token_type" field. +func UnitCostLlmTokenTypeNEQ(v string) predicate.Feature { + return predicate.Feature(sql.FieldNEQ(FieldUnitCostLlmTokenType, v)) +} + +// UnitCostLlmTokenTypeIn applies the In predicate on the "unit_cost_llm_token_type" field. +func UnitCostLlmTokenTypeIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldIn(FieldUnitCostLlmTokenType, vs...)) +} + +// UnitCostLlmTokenTypeNotIn applies the NotIn predicate on the "unit_cost_llm_token_type" field. +func UnitCostLlmTokenTypeNotIn(vs ...string) predicate.Feature { + return predicate.Feature(sql.FieldNotIn(FieldUnitCostLlmTokenType, vs...)) +} + +// UnitCostLlmTokenTypeGT applies the GT predicate on the "unit_cost_llm_token_type" field. +func UnitCostLlmTokenTypeGT(v string) predicate.Feature { + return predicate.Feature(sql.FieldGT(FieldUnitCostLlmTokenType, v)) +} + +// UnitCostLlmTokenTypeGTE applies the GTE predicate on the "unit_cost_llm_token_type" field. +func UnitCostLlmTokenTypeGTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldGTE(FieldUnitCostLlmTokenType, v)) +} + +// UnitCostLlmTokenTypeLT applies the LT predicate on the "unit_cost_llm_token_type" field. +func UnitCostLlmTokenTypeLT(v string) predicate.Feature { + return predicate.Feature(sql.FieldLT(FieldUnitCostLlmTokenType, v)) +} + +// UnitCostLlmTokenTypeLTE applies the LTE predicate on the "unit_cost_llm_token_type" field. +func UnitCostLlmTokenTypeLTE(v string) predicate.Feature { + return predicate.Feature(sql.FieldLTE(FieldUnitCostLlmTokenType, v)) +} + +// UnitCostLlmTokenTypeContains applies the Contains predicate on the "unit_cost_llm_token_type" field. +func UnitCostLlmTokenTypeContains(v string) predicate.Feature { + return predicate.Feature(sql.FieldContains(FieldUnitCostLlmTokenType, v)) +} + +// UnitCostLlmTokenTypeHasPrefix applies the HasPrefix predicate on the "unit_cost_llm_token_type" field. +func UnitCostLlmTokenTypeHasPrefix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasPrefix(FieldUnitCostLlmTokenType, v)) +} + +// UnitCostLlmTokenTypeHasSuffix applies the HasSuffix predicate on the "unit_cost_llm_token_type" field. +func UnitCostLlmTokenTypeHasSuffix(v string) predicate.Feature { + return predicate.Feature(sql.FieldHasSuffix(FieldUnitCostLlmTokenType, v)) +} + +// UnitCostLlmTokenTypeIsNil applies the IsNil predicate on the "unit_cost_llm_token_type" field. +func UnitCostLlmTokenTypeIsNil() predicate.Feature { + return predicate.Feature(sql.FieldIsNull(FieldUnitCostLlmTokenType)) +} + +// UnitCostLlmTokenTypeNotNil applies the NotNil predicate on the "unit_cost_llm_token_type" field. +func UnitCostLlmTokenTypeNotNil() predicate.Feature { + return predicate.Feature(sql.FieldNotNull(FieldUnitCostLlmTokenType)) +} + +// UnitCostLlmTokenTypeEqualFold applies the EqualFold predicate on the "unit_cost_llm_token_type" field. +func UnitCostLlmTokenTypeEqualFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldEqualFold(FieldUnitCostLlmTokenType, v)) +} + +// UnitCostLlmTokenTypeContainsFold applies the ContainsFold predicate on the "unit_cost_llm_token_type" field. +func UnitCostLlmTokenTypeContainsFold(v string) predicate.Feature { + return predicate.Feature(sql.FieldContainsFold(FieldUnitCostLlmTokenType, v)) +} + +// ArchivedAtEQ applies the EQ predicate on the "archived_at" field. +func ArchivedAtEQ(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldEQ(FieldArchivedAt, v)) +} + +// ArchivedAtNEQ applies the NEQ predicate on the "archived_at" field. +func ArchivedAtNEQ(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldNEQ(FieldArchivedAt, v)) +} + +// ArchivedAtIn applies the In predicate on the "archived_at" field. +func ArchivedAtIn(vs ...time.Time) predicate.Feature { + return predicate.Feature(sql.FieldIn(FieldArchivedAt, vs...)) +} + +// ArchivedAtNotIn applies the NotIn predicate on the "archived_at" field. +func ArchivedAtNotIn(vs ...time.Time) predicate.Feature { + return predicate.Feature(sql.FieldNotIn(FieldArchivedAt, vs...)) +} + +// ArchivedAtGT applies the GT predicate on the "archived_at" field. +func ArchivedAtGT(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldGT(FieldArchivedAt, v)) +} + +// ArchivedAtGTE applies the GTE predicate on the "archived_at" field. +func ArchivedAtGTE(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldGTE(FieldArchivedAt, v)) +} + +// ArchivedAtLT applies the LT predicate on the "archived_at" field. +func ArchivedAtLT(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldLT(FieldArchivedAt, v)) +} + +// ArchivedAtLTE applies the LTE predicate on the "archived_at" field. +func ArchivedAtLTE(v time.Time) predicate.Feature { + return predicate.Feature(sql.FieldLTE(FieldArchivedAt, v)) +} + +// ArchivedAtIsNil applies the IsNil predicate on the "archived_at" field. +func ArchivedAtIsNil() predicate.Feature { + return predicate.Feature(sql.FieldIsNull(FieldArchivedAt)) +} + +// ArchivedAtNotNil applies the NotNil predicate on the "archived_at" field. +func ArchivedAtNotNil() predicate.Feature { + return predicate.Feature(sql.FieldNotNull(FieldArchivedAt)) +} + +// HasEntitlement applies the HasEdge predicate on the "entitlement" edge. +func HasEntitlement() predicate.Feature { + return predicate.Feature(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, EntitlementTable, EntitlementColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasEntitlementWith applies the HasEdge predicate on the "entitlement" edge with a given conditions (other predicates). +func HasEntitlementWith(preds ...predicate.Entitlement) predicate.Feature { + return predicate.Feature(func(s *sql.Selector) { + step := newEntitlementStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasRatecard applies the HasEdge predicate on the "ratecard" edge. +func HasRatecard() predicate.Feature { + return predicate.Feature(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, RatecardTable, RatecardColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasRatecardWith applies the HasEdge predicate on the "ratecard" edge with a given conditions (other predicates). +func HasRatecardWith(preds ...predicate.PlanRateCard) predicate.Feature { + return predicate.Feature(func(s *sql.Selector) { + step := newRatecardStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasAddonRatecard applies the HasEdge predicate on the "addon_ratecard" edge. +func HasAddonRatecard() predicate.Feature { + return predicate.Feature(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, AddonRatecardTable, AddonRatecardColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasAddonRatecardWith applies the HasEdge predicate on the "addon_ratecard" edge with a given conditions (other predicates). +func HasAddonRatecardWith(preds ...predicate.AddonRateCard) predicate.Feature { + return predicate.Feature(func(s *sql.Selector) { + step := newAddonRatecardStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasUsageBasedCharges applies the HasEdge predicate on the "usage_based_charges" edge. +func HasUsageBasedCharges() predicate.Feature { + return predicate.Feature(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, UsageBasedChargesTable, UsageBasedChargesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUsageBasedChargesWith applies the HasEdge predicate on the "usage_based_charges" edge with a given conditions (other predicates). +func HasUsageBasedChargesWith(preds ...predicate.ChargeUsageBased) predicate.Feature { + return predicate.Feature(func(s *sql.Selector) { + step := newUsageBasedChargesStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasUsageBasedRuns applies the HasEdge predicate on the "usage_based_runs" edge. +func HasUsageBasedRuns() predicate.Feature { + return predicate.Feature(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, UsageBasedRunsTable, UsageBasedRunsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUsageBasedRunsWith applies the HasEdge predicate on the "usage_based_runs" edge with a given conditions (other predicates). +func HasUsageBasedRunsWith(preds ...predicate.ChargeUsageBasedRuns) predicate.Feature { + return predicate.Feature(func(s *sql.Selector) { + step := newUsageBasedRunsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasFlatFeeCharges applies the HasEdge predicate on the "flat_fee_charges" edge. +func HasFlatFeeCharges() predicate.Feature { + return predicate.Feature(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, FlatFeeChargesTable, FlatFeeChargesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasFlatFeeChargesWith applies the HasEdge predicate on the "flat_fee_charges" edge with a given conditions (other predicates). +func HasFlatFeeChargesWith(preds ...predicate.ChargeFlatFee) predicate.Feature { + return predicate.Feature(func(s *sql.Selector) { + step := newFlatFeeChargesStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasMeter applies the HasEdge predicate on the "meter" edge. +func HasMeter() predicate.Feature { + return predicate.Feature(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, MeterTable, MeterColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasMeterWith applies the HasEdge predicate on the "meter" edge with a given conditions (other predicates). +func HasMeterWith(preds ...predicate.Meter) predicate.Feature { + return predicate.Feature(func(s *sql.Selector) { + step := newMeterStep() + 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.Feature) predicate.Feature { + return predicate.Feature(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Feature) predicate.Feature { + return predicate.Feature(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Feature) predicate.Feature { + return predicate.Feature(sql.NotPredicates(p)) +} diff --git a/ent/db/feature_create.go b/ent/db/feature_create.go new file mode 100644 index 0000000000000000000000000000000000000000..78035db273ce0bfc720110a5737b673eddd05372 --- /dev/null +++ b/ent/db/feature_create.go @@ -0,0 +1,1991 @@ +// 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/addonratecard" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/openmeter/ent/db/entitlement" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + dbmeter "github.com/openmeterio/openmeter/openmeter/ent/db/meter" + "github.com/openmeterio/openmeter/openmeter/ent/db/planratecard" + "github.com/openmeterio/openmeter/openmeter/productcatalog/feature" +) + +// FeatureCreate is the builder for creating a Feature entity. +type FeatureCreate struct { + config + mutation *FeatureMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetCreatedAt sets the "created_at" field. +func (_c *FeatureCreate) SetCreatedAt(v time.Time) *FeatureCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *FeatureCreate) SetNillableCreatedAt(v *time.Time) *FeatureCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *FeatureCreate) SetUpdatedAt(v time.Time) *FeatureCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *FeatureCreate) SetNillableUpdatedAt(v *time.Time) *FeatureCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *FeatureCreate) SetDeletedAt(v time.Time) *FeatureCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *FeatureCreate) SetNillableDeletedAt(v *time.Time) *FeatureCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetMetadata sets the "metadata" field. +func (_c *FeatureCreate) SetMetadata(v map[string]string) *FeatureCreate { + _c.mutation.SetMetadata(v) + return _c +} + +// SetNamespace sets the "namespace" field. +func (_c *FeatureCreate) SetNamespace(v string) *FeatureCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetName sets the "name" field. +func (_c *FeatureCreate) SetName(v string) *FeatureCreate { + _c.mutation.SetName(v) + return _c +} + +// SetDescription sets the "description" field. +func (_c *FeatureCreate) SetDescription(v string) *FeatureCreate { + _c.mutation.SetDescription(v) + return _c +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_c *FeatureCreate) SetNillableDescription(v *string) *FeatureCreate { + if v != nil { + _c.SetDescription(*v) + } + return _c +} + +// SetKey sets the "key" field. +func (_c *FeatureCreate) SetKey(v string) *FeatureCreate { + _c.mutation.SetKey(v) + return _c +} + +// SetMeterSlug sets the "meter_slug" field. +func (_c *FeatureCreate) SetMeterSlug(v string) *FeatureCreate { + _c.mutation.SetMeterSlug(v) + return _c +} + +// SetNillableMeterSlug sets the "meter_slug" field if the given value is not nil. +func (_c *FeatureCreate) SetNillableMeterSlug(v *string) *FeatureCreate { + if v != nil { + _c.SetMeterSlug(*v) + } + return _c +} + +// SetMeterID sets the "meter_id" field. +func (_c *FeatureCreate) SetMeterID(v string) *FeatureCreate { + _c.mutation.SetMeterID(v) + return _c +} + +// SetNillableMeterID sets the "meter_id" field if the given value is not nil. +func (_c *FeatureCreate) SetNillableMeterID(v *string) *FeatureCreate { + if v != nil { + _c.SetMeterID(*v) + } + return _c +} + +// SetMeterGroupByFilters sets the "meter_group_by_filters" field. +func (_c *FeatureCreate) SetMeterGroupByFilters(v map[string]string) *FeatureCreate { + _c.mutation.SetMeterGroupByFilters(v) + return _c +} + +// SetAdvancedMeterGroupByFilters sets the "advanced_meter_group_by_filters" field. +func (_c *FeatureCreate) SetAdvancedMeterGroupByFilters(v feature.MeterGroupByFilters) *FeatureCreate { + _c.mutation.SetAdvancedMeterGroupByFilters(v) + return _c +} + +// SetUnitCostType sets the "unit_cost_type" field. +func (_c *FeatureCreate) SetUnitCostType(v string) *FeatureCreate { + _c.mutation.SetUnitCostType(v) + return _c +} + +// SetNillableUnitCostType sets the "unit_cost_type" field if the given value is not nil. +func (_c *FeatureCreate) SetNillableUnitCostType(v *string) *FeatureCreate { + if v != nil { + _c.SetUnitCostType(*v) + } + return _c +} + +// SetUnitCostManualAmount sets the "unit_cost_manual_amount" field. +func (_c *FeatureCreate) SetUnitCostManualAmount(v alpacadecimal.Decimal) *FeatureCreate { + _c.mutation.SetUnitCostManualAmount(v) + return _c +} + +// SetNillableUnitCostManualAmount sets the "unit_cost_manual_amount" field if the given value is not nil. +func (_c *FeatureCreate) SetNillableUnitCostManualAmount(v *alpacadecimal.Decimal) *FeatureCreate { + if v != nil { + _c.SetUnitCostManualAmount(*v) + } + return _c +} + +// SetUnitCostLlmProviderProperty sets the "unit_cost_llm_provider_property" field. +func (_c *FeatureCreate) SetUnitCostLlmProviderProperty(v string) *FeatureCreate { + _c.mutation.SetUnitCostLlmProviderProperty(v) + return _c +} + +// SetNillableUnitCostLlmProviderProperty sets the "unit_cost_llm_provider_property" field if the given value is not nil. +func (_c *FeatureCreate) SetNillableUnitCostLlmProviderProperty(v *string) *FeatureCreate { + if v != nil { + _c.SetUnitCostLlmProviderProperty(*v) + } + return _c +} + +// SetUnitCostLlmProvider sets the "unit_cost_llm_provider" field. +func (_c *FeatureCreate) SetUnitCostLlmProvider(v string) *FeatureCreate { + _c.mutation.SetUnitCostLlmProvider(v) + return _c +} + +// SetNillableUnitCostLlmProvider sets the "unit_cost_llm_provider" field if the given value is not nil. +func (_c *FeatureCreate) SetNillableUnitCostLlmProvider(v *string) *FeatureCreate { + if v != nil { + _c.SetUnitCostLlmProvider(*v) + } + return _c +} + +// SetUnitCostLlmModelProperty sets the "unit_cost_llm_model_property" field. +func (_c *FeatureCreate) SetUnitCostLlmModelProperty(v string) *FeatureCreate { + _c.mutation.SetUnitCostLlmModelProperty(v) + return _c +} + +// SetNillableUnitCostLlmModelProperty sets the "unit_cost_llm_model_property" field if the given value is not nil. +func (_c *FeatureCreate) SetNillableUnitCostLlmModelProperty(v *string) *FeatureCreate { + if v != nil { + _c.SetUnitCostLlmModelProperty(*v) + } + return _c +} + +// SetUnitCostLlmModel sets the "unit_cost_llm_model" field. +func (_c *FeatureCreate) SetUnitCostLlmModel(v string) *FeatureCreate { + _c.mutation.SetUnitCostLlmModel(v) + return _c +} + +// SetNillableUnitCostLlmModel sets the "unit_cost_llm_model" field if the given value is not nil. +func (_c *FeatureCreate) SetNillableUnitCostLlmModel(v *string) *FeatureCreate { + if v != nil { + _c.SetUnitCostLlmModel(*v) + } + return _c +} + +// SetUnitCostLlmTokenTypeProperty sets the "unit_cost_llm_token_type_property" field. +func (_c *FeatureCreate) SetUnitCostLlmTokenTypeProperty(v string) *FeatureCreate { + _c.mutation.SetUnitCostLlmTokenTypeProperty(v) + return _c +} + +// SetNillableUnitCostLlmTokenTypeProperty sets the "unit_cost_llm_token_type_property" field if the given value is not nil. +func (_c *FeatureCreate) SetNillableUnitCostLlmTokenTypeProperty(v *string) *FeatureCreate { + if v != nil { + _c.SetUnitCostLlmTokenTypeProperty(*v) + } + return _c +} + +// SetUnitCostLlmTokenType sets the "unit_cost_llm_token_type" field. +func (_c *FeatureCreate) SetUnitCostLlmTokenType(v string) *FeatureCreate { + _c.mutation.SetUnitCostLlmTokenType(v) + return _c +} + +// SetNillableUnitCostLlmTokenType sets the "unit_cost_llm_token_type" field if the given value is not nil. +func (_c *FeatureCreate) SetNillableUnitCostLlmTokenType(v *string) *FeatureCreate { + if v != nil { + _c.SetUnitCostLlmTokenType(*v) + } + return _c +} + +// SetArchivedAt sets the "archived_at" field. +func (_c *FeatureCreate) SetArchivedAt(v time.Time) *FeatureCreate { + _c.mutation.SetArchivedAt(v) + return _c +} + +// SetNillableArchivedAt sets the "archived_at" field if the given value is not nil. +func (_c *FeatureCreate) SetNillableArchivedAt(v *time.Time) *FeatureCreate { + if v != nil { + _c.SetArchivedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *FeatureCreate) SetID(v string) *FeatureCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *FeatureCreate) SetNillableID(v *string) *FeatureCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// AddEntitlementIDs adds the "entitlement" edge to the Entitlement entity by IDs. +func (_c *FeatureCreate) AddEntitlementIDs(ids ...string) *FeatureCreate { + _c.mutation.AddEntitlementIDs(ids...) + return _c +} + +// AddEntitlement adds the "entitlement" edges to the Entitlement entity. +func (_c *FeatureCreate) AddEntitlement(v ...*Entitlement) *FeatureCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddEntitlementIDs(ids...) +} + +// AddRatecardIDs adds the "ratecard" edge to the PlanRateCard entity by IDs. +func (_c *FeatureCreate) AddRatecardIDs(ids ...string) *FeatureCreate { + _c.mutation.AddRatecardIDs(ids...) + return _c +} + +// AddRatecard adds the "ratecard" edges to the PlanRateCard entity. +func (_c *FeatureCreate) AddRatecard(v ...*PlanRateCard) *FeatureCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddRatecardIDs(ids...) +} + +// AddAddonRatecardIDs adds the "addon_ratecard" edge to the AddonRateCard entity by IDs. +func (_c *FeatureCreate) AddAddonRatecardIDs(ids ...string) *FeatureCreate { + _c.mutation.AddAddonRatecardIDs(ids...) + return _c +} + +// AddAddonRatecard adds the "addon_ratecard" edges to the AddonRateCard entity. +func (_c *FeatureCreate) AddAddonRatecard(v ...*AddonRateCard) *FeatureCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddAddonRatecardIDs(ids...) +} + +// AddUsageBasedChargeIDs adds the "usage_based_charges" edge to the ChargeUsageBased entity by IDs. +func (_c *FeatureCreate) AddUsageBasedChargeIDs(ids ...string) *FeatureCreate { + _c.mutation.AddUsageBasedChargeIDs(ids...) + return _c +} + +// AddUsageBasedCharges adds the "usage_based_charges" edges to the ChargeUsageBased entity. +func (_c *FeatureCreate) AddUsageBasedCharges(v ...*ChargeUsageBased) *FeatureCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddUsageBasedChargeIDs(ids...) +} + +// AddUsageBasedRunIDs adds the "usage_based_runs" edge to the ChargeUsageBasedRuns entity by IDs. +func (_c *FeatureCreate) AddUsageBasedRunIDs(ids ...string) *FeatureCreate { + _c.mutation.AddUsageBasedRunIDs(ids...) + return _c +} + +// AddUsageBasedRuns adds the "usage_based_runs" edges to the ChargeUsageBasedRuns entity. +func (_c *FeatureCreate) AddUsageBasedRuns(v ...*ChargeUsageBasedRuns) *FeatureCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddUsageBasedRunIDs(ids...) +} + +// AddFlatFeeChargeIDs adds the "flat_fee_charges" edge to the ChargeFlatFee entity by IDs. +func (_c *FeatureCreate) AddFlatFeeChargeIDs(ids ...string) *FeatureCreate { + _c.mutation.AddFlatFeeChargeIDs(ids...) + return _c +} + +// AddFlatFeeCharges adds the "flat_fee_charges" edges to the ChargeFlatFee entity. +func (_c *FeatureCreate) AddFlatFeeCharges(v ...*ChargeFlatFee) *FeatureCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddFlatFeeChargeIDs(ids...) +} + +// SetMeter sets the "meter" edge to the Meter entity. +func (_c *FeatureCreate) SetMeter(v *Meter) *FeatureCreate { + return _c.SetMeterID(v.ID) +} + +// Mutation returns the FeatureMutation object of the builder. +func (_c *FeatureCreate) Mutation() *FeatureMutation { + return _c.mutation +} + +// Save creates the Feature in the database. +func (_c *FeatureCreate) Save(ctx context.Context) (*Feature, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *FeatureCreate) SaveX(ctx context.Context) *Feature { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *FeatureCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *FeatureCreate) 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 *FeatureCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := dbfeature.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := dbfeature.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := dbfeature.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *FeatureCreate) check() error { + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "Feature.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "Feature.updated_at"`)} + } + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "Feature.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := dbfeature.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "Feature.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "Feature.name"`)} + } + if v, ok := _c.mutation.Name(); ok { + if err := dbfeature.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "Feature.name": %w`, err)} + } + } + if v, ok := _c.mutation.Description(); ok { + if err := dbfeature.DescriptionValidator(v); err != nil { + return &ValidationError{Name: "description", err: fmt.Errorf(`db: validator failed for field "Feature.description": %w`, err)} + } + } + if _, ok := _c.mutation.Key(); !ok { + return &ValidationError{Name: "key", err: errors.New(`db: missing required field "Feature.key"`)} + } + if v, ok := _c.mutation.Key(); ok { + if err := dbfeature.KeyValidator(v); err != nil { + return &ValidationError{Name: "key", err: fmt.Errorf(`db: validator failed for field "Feature.key": %w`, err)} + } + } + return nil +} + +func (_c *FeatureCreate) sqlSave(ctx context.Context) (*Feature, 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 Feature.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *FeatureCreate) createSpec() (*Feature, *sqlgraph.CreateSpec) { + var ( + _node = &Feature{config: _c.config} + _spec = sqlgraph.NewCreateSpec(dbfeature.Table, sqlgraph.NewFieldSpec(dbfeature.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.CreatedAt(); ok { + _spec.SetField(dbfeature.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(dbfeature.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(dbfeature.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Metadata(); ok { + _spec.SetField(dbfeature.FieldMetadata, field.TypeJSON, value) + _node.Metadata = value + } + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(dbfeature.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(dbfeature.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Description(); ok { + _spec.SetField(dbfeature.FieldDescription, field.TypeString, value) + _node.Description = &value + } + if value, ok := _c.mutation.Key(); ok { + _spec.SetField(dbfeature.FieldKey, field.TypeString, value) + _node.Key = value + } + if value, ok := _c.mutation.MeterSlug(); ok { + _spec.SetField(dbfeature.FieldMeterSlug, field.TypeString, value) + _node.MeterSlug = &value + } + if value, ok := _c.mutation.MeterGroupByFilters(); ok { + _spec.SetField(dbfeature.FieldMeterGroupByFilters, field.TypeJSON, value) + _node.MeterGroupByFilters = value + } + if value, ok := _c.mutation.AdvancedMeterGroupByFilters(); ok { + _spec.SetField(dbfeature.FieldAdvancedMeterGroupByFilters, field.TypeJSON, value) + _node.AdvancedMeterGroupByFilters = value + } + if value, ok := _c.mutation.UnitCostType(); ok { + _spec.SetField(dbfeature.FieldUnitCostType, field.TypeString, value) + _node.UnitCostType = &value + } + if value, ok := _c.mutation.UnitCostManualAmount(); ok { + _spec.SetField(dbfeature.FieldUnitCostManualAmount, field.TypeOther, value) + _node.UnitCostManualAmount = &value + } + if value, ok := _c.mutation.UnitCostLlmProviderProperty(); ok { + _spec.SetField(dbfeature.FieldUnitCostLlmProviderProperty, field.TypeString, value) + _node.UnitCostLlmProviderProperty = &value + } + if value, ok := _c.mutation.UnitCostLlmProvider(); ok { + _spec.SetField(dbfeature.FieldUnitCostLlmProvider, field.TypeString, value) + _node.UnitCostLlmProvider = &value + } + if value, ok := _c.mutation.UnitCostLlmModelProperty(); ok { + _spec.SetField(dbfeature.FieldUnitCostLlmModelProperty, field.TypeString, value) + _node.UnitCostLlmModelProperty = &value + } + if value, ok := _c.mutation.UnitCostLlmModel(); ok { + _spec.SetField(dbfeature.FieldUnitCostLlmModel, field.TypeString, value) + _node.UnitCostLlmModel = &value + } + if value, ok := _c.mutation.UnitCostLlmTokenTypeProperty(); ok { + _spec.SetField(dbfeature.FieldUnitCostLlmTokenTypeProperty, field.TypeString, value) + _node.UnitCostLlmTokenTypeProperty = &value + } + if value, ok := _c.mutation.UnitCostLlmTokenType(); ok { + _spec.SetField(dbfeature.FieldUnitCostLlmTokenType, field.TypeString, value) + _node.UnitCostLlmTokenType = &value + } + if value, ok := _c.mutation.ArchivedAt(); ok { + _spec.SetField(dbfeature.FieldArchivedAt, field.TypeTime, value) + _node.ArchivedAt = &value + } + if nodes := _c.mutation.EntitlementIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.EntitlementTable, + Columns: []string{dbfeature.EntitlementColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(entitlement.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.RatecardIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.RatecardTable, + Columns: []string{dbfeature.RatecardColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(planratecard.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.AddonRatecardIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.AddonRatecardTable, + Columns: []string{dbfeature.AddonRatecardColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(addonratecard.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.UsageBasedChargesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.UsageBasedChargesTable, + Columns: []string{dbfeature.UsageBasedChargesColumn}, + 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.UsageBasedRunsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.UsageBasedRunsTable, + Columns: []string{dbfeature.UsageBasedRunsColumn}, + 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) + } + if nodes := _c.mutation.FlatFeeChargesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.FlatFeeChargesTable, + Columns: []string{dbfeature.FlatFeeChargesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfee.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.MeterIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: dbfeature.MeterTable, + Columns: []string{dbfeature.MeterColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbmeter.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.MeterID = &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.Feature.Create(). +// SetCreatedAt(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.FeatureUpsert) { +// SetCreatedAt(v+v). +// }). +// Exec(ctx) +func (_c *FeatureCreate) OnConflict(opts ...sql.ConflictOption) *FeatureUpsertOne { + _c.conflict = opts + return &FeatureUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Feature.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *FeatureCreate) OnConflictColumns(columns ...string) *FeatureUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &FeatureUpsertOne{ + create: _c, + } +} + +type ( + // FeatureUpsertOne is the builder for "upsert"-ing + // one Feature node. + FeatureUpsertOne struct { + create *FeatureCreate + } + + // FeatureUpsert is the "OnConflict" setter. + FeatureUpsert struct { + *sql.UpdateSet + } +) + +// SetUpdatedAt sets the "updated_at" field. +func (u *FeatureUpsert) SetUpdatedAt(v time.Time) *FeatureUpsert { + u.Set(dbfeature.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *FeatureUpsert) UpdateUpdatedAt() *FeatureUpsert { + u.SetExcluded(dbfeature.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *FeatureUpsert) SetDeletedAt(v time.Time) *FeatureUpsert { + u.Set(dbfeature.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *FeatureUpsert) UpdateDeletedAt() *FeatureUpsert { + u.SetExcluded(dbfeature.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *FeatureUpsert) ClearDeletedAt() *FeatureUpsert { + u.SetNull(dbfeature.FieldDeletedAt) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *FeatureUpsert) SetMetadata(v map[string]string) *FeatureUpsert { + u.Set(dbfeature.FieldMetadata, v) + return u +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *FeatureUpsert) UpdateMetadata() *FeatureUpsert { + u.SetExcluded(dbfeature.FieldMetadata) + return u +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *FeatureUpsert) ClearMetadata() *FeatureUpsert { + u.SetNull(dbfeature.FieldMetadata) + return u +} + +// SetName sets the "name" field. +func (u *FeatureUpsert) SetName(v string) *FeatureUpsert { + u.Set(dbfeature.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *FeatureUpsert) UpdateName() *FeatureUpsert { + u.SetExcluded(dbfeature.FieldName) + return u +} + +// SetDescription sets the "description" field. +func (u *FeatureUpsert) SetDescription(v string) *FeatureUpsert { + u.Set(dbfeature.FieldDescription, v) + return u +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *FeatureUpsert) UpdateDescription() *FeatureUpsert { + u.SetExcluded(dbfeature.FieldDescription) + return u +} + +// ClearDescription clears the value of the "description" field. +func (u *FeatureUpsert) ClearDescription() *FeatureUpsert { + u.SetNull(dbfeature.FieldDescription) + return u +} + +// SetMeterGroupByFilters sets the "meter_group_by_filters" field. +func (u *FeatureUpsert) SetMeterGroupByFilters(v map[string]string) *FeatureUpsert { + u.Set(dbfeature.FieldMeterGroupByFilters, v) + return u +} + +// UpdateMeterGroupByFilters sets the "meter_group_by_filters" field to the value that was provided on create. +func (u *FeatureUpsert) UpdateMeterGroupByFilters() *FeatureUpsert { + u.SetExcluded(dbfeature.FieldMeterGroupByFilters) + return u +} + +// ClearMeterGroupByFilters clears the value of the "meter_group_by_filters" field. +func (u *FeatureUpsert) ClearMeterGroupByFilters() *FeatureUpsert { + u.SetNull(dbfeature.FieldMeterGroupByFilters) + return u +} + +// SetAdvancedMeterGroupByFilters sets the "advanced_meter_group_by_filters" field. +func (u *FeatureUpsert) SetAdvancedMeterGroupByFilters(v feature.MeterGroupByFilters) *FeatureUpsert { + u.Set(dbfeature.FieldAdvancedMeterGroupByFilters, v) + return u +} + +// UpdateAdvancedMeterGroupByFilters sets the "advanced_meter_group_by_filters" field to the value that was provided on create. +func (u *FeatureUpsert) UpdateAdvancedMeterGroupByFilters() *FeatureUpsert { + u.SetExcluded(dbfeature.FieldAdvancedMeterGroupByFilters) + return u +} + +// ClearAdvancedMeterGroupByFilters clears the value of the "advanced_meter_group_by_filters" field. +func (u *FeatureUpsert) ClearAdvancedMeterGroupByFilters() *FeatureUpsert { + u.SetNull(dbfeature.FieldAdvancedMeterGroupByFilters) + return u +} + +// SetUnitCostType sets the "unit_cost_type" field. +func (u *FeatureUpsert) SetUnitCostType(v string) *FeatureUpsert { + u.Set(dbfeature.FieldUnitCostType, v) + return u +} + +// UpdateUnitCostType sets the "unit_cost_type" field to the value that was provided on create. +func (u *FeatureUpsert) UpdateUnitCostType() *FeatureUpsert { + u.SetExcluded(dbfeature.FieldUnitCostType) + return u +} + +// ClearUnitCostType clears the value of the "unit_cost_type" field. +func (u *FeatureUpsert) ClearUnitCostType() *FeatureUpsert { + u.SetNull(dbfeature.FieldUnitCostType) + return u +} + +// SetUnitCostManualAmount sets the "unit_cost_manual_amount" field. +func (u *FeatureUpsert) SetUnitCostManualAmount(v alpacadecimal.Decimal) *FeatureUpsert { + u.Set(dbfeature.FieldUnitCostManualAmount, v) + return u +} + +// UpdateUnitCostManualAmount sets the "unit_cost_manual_amount" field to the value that was provided on create. +func (u *FeatureUpsert) UpdateUnitCostManualAmount() *FeatureUpsert { + u.SetExcluded(dbfeature.FieldUnitCostManualAmount) + return u +} + +// ClearUnitCostManualAmount clears the value of the "unit_cost_manual_amount" field. +func (u *FeatureUpsert) ClearUnitCostManualAmount() *FeatureUpsert { + u.SetNull(dbfeature.FieldUnitCostManualAmount) + return u +} + +// SetUnitCostLlmProviderProperty sets the "unit_cost_llm_provider_property" field. +func (u *FeatureUpsert) SetUnitCostLlmProviderProperty(v string) *FeatureUpsert { + u.Set(dbfeature.FieldUnitCostLlmProviderProperty, v) + return u +} + +// UpdateUnitCostLlmProviderProperty sets the "unit_cost_llm_provider_property" field to the value that was provided on create. +func (u *FeatureUpsert) UpdateUnitCostLlmProviderProperty() *FeatureUpsert { + u.SetExcluded(dbfeature.FieldUnitCostLlmProviderProperty) + return u +} + +// ClearUnitCostLlmProviderProperty clears the value of the "unit_cost_llm_provider_property" field. +func (u *FeatureUpsert) ClearUnitCostLlmProviderProperty() *FeatureUpsert { + u.SetNull(dbfeature.FieldUnitCostLlmProviderProperty) + return u +} + +// SetUnitCostLlmProvider sets the "unit_cost_llm_provider" field. +func (u *FeatureUpsert) SetUnitCostLlmProvider(v string) *FeatureUpsert { + u.Set(dbfeature.FieldUnitCostLlmProvider, v) + return u +} + +// UpdateUnitCostLlmProvider sets the "unit_cost_llm_provider" field to the value that was provided on create. +func (u *FeatureUpsert) UpdateUnitCostLlmProvider() *FeatureUpsert { + u.SetExcluded(dbfeature.FieldUnitCostLlmProvider) + return u +} + +// ClearUnitCostLlmProvider clears the value of the "unit_cost_llm_provider" field. +func (u *FeatureUpsert) ClearUnitCostLlmProvider() *FeatureUpsert { + u.SetNull(dbfeature.FieldUnitCostLlmProvider) + return u +} + +// SetUnitCostLlmModelProperty sets the "unit_cost_llm_model_property" field. +func (u *FeatureUpsert) SetUnitCostLlmModelProperty(v string) *FeatureUpsert { + u.Set(dbfeature.FieldUnitCostLlmModelProperty, v) + return u +} + +// UpdateUnitCostLlmModelProperty sets the "unit_cost_llm_model_property" field to the value that was provided on create. +func (u *FeatureUpsert) UpdateUnitCostLlmModelProperty() *FeatureUpsert { + u.SetExcluded(dbfeature.FieldUnitCostLlmModelProperty) + return u +} + +// ClearUnitCostLlmModelProperty clears the value of the "unit_cost_llm_model_property" field. +func (u *FeatureUpsert) ClearUnitCostLlmModelProperty() *FeatureUpsert { + u.SetNull(dbfeature.FieldUnitCostLlmModelProperty) + return u +} + +// SetUnitCostLlmModel sets the "unit_cost_llm_model" field. +func (u *FeatureUpsert) SetUnitCostLlmModel(v string) *FeatureUpsert { + u.Set(dbfeature.FieldUnitCostLlmModel, v) + return u +} + +// UpdateUnitCostLlmModel sets the "unit_cost_llm_model" field to the value that was provided on create. +func (u *FeatureUpsert) UpdateUnitCostLlmModel() *FeatureUpsert { + u.SetExcluded(dbfeature.FieldUnitCostLlmModel) + return u +} + +// ClearUnitCostLlmModel clears the value of the "unit_cost_llm_model" field. +func (u *FeatureUpsert) ClearUnitCostLlmModel() *FeatureUpsert { + u.SetNull(dbfeature.FieldUnitCostLlmModel) + return u +} + +// SetUnitCostLlmTokenTypeProperty sets the "unit_cost_llm_token_type_property" field. +func (u *FeatureUpsert) SetUnitCostLlmTokenTypeProperty(v string) *FeatureUpsert { + u.Set(dbfeature.FieldUnitCostLlmTokenTypeProperty, v) + return u +} + +// UpdateUnitCostLlmTokenTypeProperty sets the "unit_cost_llm_token_type_property" field to the value that was provided on create. +func (u *FeatureUpsert) UpdateUnitCostLlmTokenTypeProperty() *FeatureUpsert { + u.SetExcluded(dbfeature.FieldUnitCostLlmTokenTypeProperty) + return u +} + +// ClearUnitCostLlmTokenTypeProperty clears the value of the "unit_cost_llm_token_type_property" field. +func (u *FeatureUpsert) ClearUnitCostLlmTokenTypeProperty() *FeatureUpsert { + u.SetNull(dbfeature.FieldUnitCostLlmTokenTypeProperty) + return u +} + +// SetUnitCostLlmTokenType sets the "unit_cost_llm_token_type" field. +func (u *FeatureUpsert) SetUnitCostLlmTokenType(v string) *FeatureUpsert { + u.Set(dbfeature.FieldUnitCostLlmTokenType, v) + return u +} + +// UpdateUnitCostLlmTokenType sets the "unit_cost_llm_token_type" field to the value that was provided on create. +func (u *FeatureUpsert) UpdateUnitCostLlmTokenType() *FeatureUpsert { + u.SetExcluded(dbfeature.FieldUnitCostLlmTokenType) + return u +} + +// ClearUnitCostLlmTokenType clears the value of the "unit_cost_llm_token_type" field. +func (u *FeatureUpsert) ClearUnitCostLlmTokenType() *FeatureUpsert { + u.SetNull(dbfeature.FieldUnitCostLlmTokenType) + return u +} + +// SetArchivedAt sets the "archived_at" field. +func (u *FeatureUpsert) SetArchivedAt(v time.Time) *FeatureUpsert { + u.Set(dbfeature.FieldArchivedAt, v) + return u +} + +// UpdateArchivedAt sets the "archived_at" field to the value that was provided on create. +func (u *FeatureUpsert) UpdateArchivedAt() *FeatureUpsert { + u.SetExcluded(dbfeature.FieldArchivedAt) + return u +} + +// ClearArchivedAt clears the value of the "archived_at" field. +func (u *FeatureUpsert) ClearArchivedAt() *FeatureUpsert { + u.SetNull(dbfeature.FieldArchivedAt) + 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.Feature.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(dbfeature.FieldID) +// }), +// ). +// Exec(ctx) +func (u *FeatureUpsertOne) UpdateNewValues() *FeatureUpsertOne { + 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(dbfeature.FieldID) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(dbfeature.FieldCreatedAt) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(dbfeature.FieldNamespace) + } + if _, exists := u.create.mutation.Key(); exists { + s.SetIgnore(dbfeature.FieldKey) + } + if _, exists := u.create.mutation.MeterSlug(); exists { + s.SetIgnore(dbfeature.FieldMeterSlug) + } + if _, exists := u.create.mutation.MeterID(); exists { + s.SetIgnore(dbfeature.FieldMeterID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Feature.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *FeatureUpsertOne) Ignore() *FeatureUpsertOne { + 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 *FeatureUpsertOne) DoNothing() *FeatureUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the FeatureCreate.OnConflict +// documentation for more info. +func (u *FeatureUpsertOne) Update(set func(*FeatureUpsert)) *FeatureUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&FeatureUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *FeatureUpsertOne) SetUpdatedAt(v time.Time) *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *FeatureUpsertOne) UpdateUpdatedAt() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *FeatureUpsertOne) SetDeletedAt(v time.Time) *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *FeatureUpsertOne) UpdateDeletedAt() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *FeatureUpsertOne) ClearDeletedAt() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.ClearDeletedAt() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *FeatureUpsertOne) SetMetadata(v map[string]string) *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *FeatureUpsertOne) UpdateMetadata() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *FeatureUpsertOne) ClearMetadata() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.ClearMetadata() + }) +} + +// SetName sets the "name" field. +func (u *FeatureUpsertOne) SetName(v string) *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *FeatureUpsertOne) UpdateName() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *FeatureUpsertOne) SetDescription(v string) *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *FeatureUpsertOne) UpdateDescription() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *FeatureUpsertOne) ClearDescription() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.ClearDescription() + }) +} + +// SetMeterGroupByFilters sets the "meter_group_by_filters" field. +func (u *FeatureUpsertOne) SetMeterGroupByFilters(v map[string]string) *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.SetMeterGroupByFilters(v) + }) +} + +// UpdateMeterGroupByFilters sets the "meter_group_by_filters" field to the value that was provided on create. +func (u *FeatureUpsertOne) UpdateMeterGroupByFilters() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.UpdateMeterGroupByFilters() + }) +} + +// ClearMeterGroupByFilters clears the value of the "meter_group_by_filters" field. +func (u *FeatureUpsertOne) ClearMeterGroupByFilters() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.ClearMeterGroupByFilters() + }) +} + +// SetAdvancedMeterGroupByFilters sets the "advanced_meter_group_by_filters" field. +func (u *FeatureUpsertOne) SetAdvancedMeterGroupByFilters(v feature.MeterGroupByFilters) *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.SetAdvancedMeterGroupByFilters(v) + }) +} + +// UpdateAdvancedMeterGroupByFilters sets the "advanced_meter_group_by_filters" field to the value that was provided on create. +func (u *FeatureUpsertOne) UpdateAdvancedMeterGroupByFilters() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.UpdateAdvancedMeterGroupByFilters() + }) +} + +// ClearAdvancedMeterGroupByFilters clears the value of the "advanced_meter_group_by_filters" field. +func (u *FeatureUpsertOne) ClearAdvancedMeterGroupByFilters() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.ClearAdvancedMeterGroupByFilters() + }) +} + +// SetUnitCostType sets the "unit_cost_type" field. +func (u *FeatureUpsertOne) SetUnitCostType(v string) *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.SetUnitCostType(v) + }) +} + +// UpdateUnitCostType sets the "unit_cost_type" field to the value that was provided on create. +func (u *FeatureUpsertOne) UpdateUnitCostType() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.UpdateUnitCostType() + }) +} + +// ClearUnitCostType clears the value of the "unit_cost_type" field. +func (u *FeatureUpsertOne) ClearUnitCostType() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.ClearUnitCostType() + }) +} + +// SetUnitCostManualAmount sets the "unit_cost_manual_amount" field. +func (u *FeatureUpsertOne) SetUnitCostManualAmount(v alpacadecimal.Decimal) *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.SetUnitCostManualAmount(v) + }) +} + +// UpdateUnitCostManualAmount sets the "unit_cost_manual_amount" field to the value that was provided on create. +func (u *FeatureUpsertOne) UpdateUnitCostManualAmount() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.UpdateUnitCostManualAmount() + }) +} + +// ClearUnitCostManualAmount clears the value of the "unit_cost_manual_amount" field. +func (u *FeatureUpsertOne) ClearUnitCostManualAmount() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.ClearUnitCostManualAmount() + }) +} + +// SetUnitCostLlmProviderProperty sets the "unit_cost_llm_provider_property" field. +func (u *FeatureUpsertOne) SetUnitCostLlmProviderProperty(v string) *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.SetUnitCostLlmProviderProperty(v) + }) +} + +// UpdateUnitCostLlmProviderProperty sets the "unit_cost_llm_provider_property" field to the value that was provided on create. +func (u *FeatureUpsertOne) UpdateUnitCostLlmProviderProperty() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.UpdateUnitCostLlmProviderProperty() + }) +} + +// ClearUnitCostLlmProviderProperty clears the value of the "unit_cost_llm_provider_property" field. +func (u *FeatureUpsertOne) ClearUnitCostLlmProviderProperty() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.ClearUnitCostLlmProviderProperty() + }) +} + +// SetUnitCostLlmProvider sets the "unit_cost_llm_provider" field. +func (u *FeatureUpsertOne) SetUnitCostLlmProvider(v string) *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.SetUnitCostLlmProvider(v) + }) +} + +// UpdateUnitCostLlmProvider sets the "unit_cost_llm_provider" field to the value that was provided on create. +func (u *FeatureUpsertOne) UpdateUnitCostLlmProvider() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.UpdateUnitCostLlmProvider() + }) +} + +// ClearUnitCostLlmProvider clears the value of the "unit_cost_llm_provider" field. +func (u *FeatureUpsertOne) ClearUnitCostLlmProvider() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.ClearUnitCostLlmProvider() + }) +} + +// SetUnitCostLlmModelProperty sets the "unit_cost_llm_model_property" field. +func (u *FeatureUpsertOne) SetUnitCostLlmModelProperty(v string) *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.SetUnitCostLlmModelProperty(v) + }) +} + +// UpdateUnitCostLlmModelProperty sets the "unit_cost_llm_model_property" field to the value that was provided on create. +func (u *FeatureUpsertOne) UpdateUnitCostLlmModelProperty() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.UpdateUnitCostLlmModelProperty() + }) +} + +// ClearUnitCostLlmModelProperty clears the value of the "unit_cost_llm_model_property" field. +func (u *FeatureUpsertOne) ClearUnitCostLlmModelProperty() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.ClearUnitCostLlmModelProperty() + }) +} + +// SetUnitCostLlmModel sets the "unit_cost_llm_model" field. +func (u *FeatureUpsertOne) SetUnitCostLlmModel(v string) *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.SetUnitCostLlmModel(v) + }) +} + +// UpdateUnitCostLlmModel sets the "unit_cost_llm_model" field to the value that was provided on create. +func (u *FeatureUpsertOne) UpdateUnitCostLlmModel() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.UpdateUnitCostLlmModel() + }) +} + +// ClearUnitCostLlmModel clears the value of the "unit_cost_llm_model" field. +func (u *FeatureUpsertOne) ClearUnitCostLlmModel() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.ClearUnitCostLlmModel() + }) +} + +// SetUnitCostLlmTokenTypeProperty sets the "unit_cost_llm_token_type_property" field. +func (u *FeatureUpsertOne) SetUnitCostLlmTokenTypeProperty(v string) *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.SetUnitCostLlmTokenTypeProperty(v) + }) +} + +// UpdateUnitCostLlmTokenTypeProperty sets the "unit_cost_llm_token_type_property" field to the value that was provided on create. +func (u *FeatureUpsertOne) UpdateUnitCostLlmTokenTypeProperty() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.UpdateUnitCostLlmTokenTypeProperty() + }) +} + +// ClearUnitCostLlmTokenTypeProperty clears the value of the "unit_cost_llm_token_type_property" field. +func (u *FeatureUpsertOne) ClearUnitCostLlmTokenTypeProperty() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.ClearUnitCostLlmTokenTypeProperty() + }) +} + +// SetUnitCostLlmTokenType sets the "unit_cost_llm_token_type" field. +func (u *FeatureUpsertOne) SetUnitCostLlmTokenType(v string) *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.SetUnitCostLlmTokenType(v) + }) +} + +// UpdateUnitCostLlmTokenType sets the "unit_cost_llm_token_type" field to the value that was provided on create. +func (u *FeatureUpsertOne) UpdateUnitCostLlmTokenType() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.UpdateUnitCostLlmTokenType() + }) +} + +// ClearUnitCostLlmTokenType clears the value of the "unit_cost_llm_token_type" field. +func (u *FeatureUpsertOne) ClearUnitCostLlmTokenType() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.ClearUnitCostLlmTokenType() + }) +} + +// SetArchivedAt sets the "archived_at" field. +func (u *FeatureUpsertOne) SetArchivedAt(v time.Time) *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.SetArchivedAt(v) + }) +} + +// UpdateArchivedAt sets the "archived_at" field to the value that was provided on create. +func (u *FeatureUpsertOne) UpdateArchivedAt() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.UpdateArchivedAt() + }) +} + +// ClearArchivedAt clears the value of the "archived_at" field. +func (u *FeatureUpsertOne) ClearArchivedAt() *FeatureUpsertOne { + return u.Update(func(s *FeatureUpsert) { + s.ClearArchivedAt() + }) +} + +// Exec executes the query. +func (u *FeatureUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for FeatureCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *FeatureUpsertOne) 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 *FeatureUpsertOne) 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: FeatureUpsertOne.ID is not supported by MySQL driver. Use FeatureUpsertOne.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 *FeatureUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// FeatureCreateBulk is the builder for creating many Feature entities in bulk. +type FeatureCreateBulk struct { + config + err error + builders []*FeatureCreate + conflict []sql.ConflictOption +} + +// Save creates the Feature entities in the database. +func (_c *FeatureCreateBulk) Save(ctx context.Context) ([]*Feature, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Feature, 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.(*FeatureMutation) + 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 *FeatureCreateBulk) SaveX(ctx context.Context) []*Feature { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *FeatureCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *FeatureCreateBulk) 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.Feature.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.FeatureUpsert) { +// SetCreatedAt(v+v). +// }). +// Exec(ctx) +func (_c *FeatureCreateBulk) OnConflict(opts ...sql.ConflictOption) *FeatureUpsertBulk { + _c.conflict = opts + return &FeatureUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Feature.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *FeatureCreateBulk) OnConflictColumns(columns ...string) *FeatureUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &FeatureUpsertBulk{ + create: _c, + } +} + +// FeatureUpsertBulk is the builder for "upsert"-ing +// a bulk of Feature nodes. +type FeatureUpsertBulk struct { + create *FeatureCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.Feature.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(dbfeature.FieldID) +// }), +// ). +// Exec(ctx) +func (u *FeatureUpsertBulk) UpdateNewValues() *FeatureUpsertBulk { + 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(dbfeature.FieldID) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(dbfeature.FieldCreatedAt) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(dbfeature.FieldNamespace) + } + if _, exists := b.mutation.Key(); exists { + s.SetIgnore(dbfeature.FieldKey) + } + if _, exists := b.mutation.MeterSlug(); exists { + s.SetIgnore(dbfeature.FieldMeterSlug) + } + if _, exists := b.mutation.MeterID(); exists { + s.SetIgnore(dbfeature.FieldMeterID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Feature.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *FeatureUpsertBulk) Ignore() *FeatureUpsertBulk { + 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 *FeatureUpsertBulk) DoNothing() *FeatureUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the FeatureCreateBulk.OnConflict +// documentation for more info. +func (u *FeatureUpsertBulk) Update(set func(*FeatureUpsert)) *FeatureUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&FeatureUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *FeatureUpsertBulk) SetUpdatedAt(v time.Time) *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *FeatureUpsertBulk) UpdateUpdatedAt() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *FeatureUpsertBulk) SetDeletedAt(v time.Time) *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *FeatureUpsertBulk) UpdateDeletedAt() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *FeatureUpsertBulk) ClearDeletedAt() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.ClearDeletedAt() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *FeatureUpsertBulk) SetMetadata(v map[string]string) *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *FeatureUpsertBulk) UpdateMetadata() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *FeatureUpsertBulk) ClearMetadata() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.ClearMetadata() + }) +} + +// SetName sets the "name" field. +func (u *FeatureUpsertBulk) SetName(v string) *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *FeatureUpsertBulk) UpdateName() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *FeatureUpsertBulk) SetDescription(v string) *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *FeatureUpsertBulk) UpdateDescription() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *FeatureUpsertBulk) ClearDescription() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.ClearDescription() + }) +} + +// SetMeterGroupByFilters sets the "meter_group_by_filters" field. +func (u *FeatureUpsertBulk) SetMeterGroupByFilters(v map[string]string) *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.SetMeterGroupByFilters(v) + }) +} + +// UpdateMeterGroupByFilters sets the "meter_group_by_filters" field to the value that was provided on create. +func (u *FeatureUpsertBulk) UpdateMeterGroupByFilters() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.UpdateMeterGroupByFilters() + }) +} + +// ClearMeterGroupByFilters clears the value of the "meter_group_by_filters" field. +func (u *FeatureUpsertBulk) ClearMeterGroupByFilters() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.ClearMeterGroupByFilters() + }) +} + +// SetAdvancedMeterGroupByFilters sets the "advanced_meter_group_by_filters" field. +func (u *FeatureUpsertBulk) SetAdvancedMeterGroupByFilters(v feature.MeterGroupByFilters) *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.SetAdvancedMeterGroupByFilters(v) + }) +} + +// UpdateAdvancedMeterGroupByFilters sets the "advanced_meter_group_by_filters" field to the value that was provided on create. +func (u *FeatureUpsertBulk) UpdateAdvancedMeterGroupByFilters() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.UpdateAdvancedMeterGroupByFilters() + }) +} + +// ClearAdvancedMeterGroupByFilters clears the value of the "advanced_meter_group_by_filters" field. +func (u *FeatureUpsertBulk) ClearAdvancedMeterGroupByFilters() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.ClearAdvancedMeterGroupByFilters() + }) +} + +// SetUnitCostType sets the "unit_cost_type" field. +func (u *FeatureUpsertBulk) SetUnitCostType(v string) *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.SetUnitCostType(v) + }) +} + +// UpdateUnitCostType sets the "unit_cost_type" field to the value that was provided on create. +func (u *FeatureUpsertBulk) UpdateUnitCostType() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.UpdateUnitCostType() + }) +} + +// ClearUnitCostType clears the value of the "unit_cost_type" field. +func (u *FeatureUpsertBulk) ClearUnitCostType() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.ClearUnitCostType() + }) +} + +// SetUnitCostManualAmount sets the "unit_cost_manual_amount" field. +func (u *FeatureUpsertBulk) SetUnitCostManualAmount(v alpacadecimal.Decimal) *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.SetUnitCostManualAmount(v) + }) +} + +// UpdateUnitCostManualAmount sets the "unit_cost_manual_amount" field to the value that was provided on create. +func (u *FeatureUpsertBulk) UpdateUnitCostManualAmount() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.UpdateUnitCostManualAmount() + }) +} + +// ClearUnitCostManualAmount clears the value of the "unit_cost_manual_amount" field. +func (u *FeatureUpsertBulk) ClearUnitCostManualAmount() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.ClearUnitCostManualAmount() + }) +} + +// SetUnitCostLlmProviderProperty sets the "unit_cost_llm_provider_property" field. +func (u *FeatureUpsertBulk) SetUnitCostLlmProviderProperty(v string) *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.SetUnitCostLlmProviderProperty(v) + }) +} + +// UpdateUnitCostLlmProviderProperty sets the "unit_cost_llm_provider_property" field to the value that was provided on create. +func (u *FeatureUpsertBulk) UpdateUnitCostLlmProviderProperty() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.UpdateUnitCostLlmProviderProperty() + }) +} + +// ClearUnitCostLlmProviderProperty clears the value of the "unit_cost_llm_provider_property" field. +func (u *FeatureUpsertBulk) ClearUnitCostLlmProviderProperty() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.ClearUnitCostLlmProviderProperty() + }) +} + +// SetUnitCostLlmProvider sets the "unit_cost_llm_provider" field. +func (u *FeatureUpsertBulk) SetUnitCostLlmProvider(v string) *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.SetUnitCostLlmProvider(v) + }) +} + +// UpdateUnitCostLlmProvider sets the "unit_cost_llm_provider" field to the value that was provided on create. +func (u *FeatureUpsertBulk) UpdateUnitCostLlmProvider() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.UpdateUnitCostLlmProvider() + }) +} + +// ClearUnitCostLlmProvider clears the value of the "unit_cost_llm_provider" field. +func (u *FeatureUpsertBulk) ClearUnitCostLlmProvider() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.ClearUnitCostLlmProvider() + }) +} + +// SetUnitCostLlmModelProperty sets the "unit_cost_llm_model_property" field. +func (u *FeatureUpsertBulk) SetUnitCostLlmModelProperty(v string) *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.SetUnitCostLlmModelProperty(v) + }) +} + +// UpdateUnitCostLlmModelProperty sets the "unit_cost_llm_model_property" field to the value that was provided on create. +func (u *FeatureUpsertBulk) UpdateUnitCostLlmModelProperty() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.UpdateUnitCostLlmModelProperty() + }) +} + +// ClearUnitCostLlmModelProperty clears the value of the "unit_cost_llm_model_property" field. +func (u *FeatureUpsertBulk) ClearUnitCostLlmModelProperty() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.ClearUnitCostLlmModelProperty() + }) +} + +// SetUnitCostLlmModel sets the "unit_cost_llm_model" field. +func (u *FeatureUpsertBulk) SetUnitCostLlmModel(v string) *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.SetUnitCostLlmModel(v) + }) +} + +// UpdateUnitCostLlmModel sets the "unit_cost_llm_model" field to the value that was provided on create. +func (u *FeatureUpsertBulk) UpdateUnitCostLlmModel() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.UpdateUnitCostLlmModel() + }) +} + +// ClearUnitCostLlmModel clears the value of the "unit_cost_llm_model" field. +func (u *FeatureUpsertBulk) ClearUnitCostLlmModel() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.ClearUnitCostLlmModel() + }) +} + +// SetUnitCostLlmTokenTypeProperty sets the "unit_cost_llm_token_type_property" field. +func (u *FeatureUpsertBulk) SetUnitCostLlmTokenTypeProperty(v string) *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.SetUnitCostLlmTokenTypeProperty(v) + }) +} + +// UpdateUnitCostLlmTokenTypeProperty sets the "unit_cost_llm_token_type_property" field to the value that was provided on create. +func (u *FeatureUpsertBulk) UpdateUnitCostLlmTokenTypeProperty() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.UpdateUnitCostLlmTokenTypeProperty() + }) +} + +// ClearUnitCostLlmTokenTypeProperty clears the value of the "unit_cost_llm_token_type_property" field. +func (u *FeatureUpsertBulk) ClearUnitCostLlmTokenTypeProperty() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.ClearUnitCostLlmTokenTypeProperty() + }) +} + +// SetUnitCostLlmTokenType sets the "unit_cost_llm_token_type" field. +func (u *FeatureUpsertBulk) SetUnitCostLlmTokenType(v string) *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.SetUnitCostLlmTokenType(v) + }) +} + +// UpdateUnitCostLlmTokenType sets the "unit_cost_llm_token_type" field to the value that was provided on create. +func (u *FeatureUpsertBulk) UpdateUnitCostLlmTokenType() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.UpdateUnitCostLlmTokenType() + }) +} + +// ClearUnitCostLlmTokenType clears the value of the "unit_cost_llm_token_type" field. +func (u *FeatureUpsertBulk) ClearUnitCostLlmTokenType() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.ClearUnitCostLlmTokenType() + }) +} + +// SetArchivedAt sets the "archived_at" field. +func (u *FeatureUpsertBulk) SetArchivedAt(v time.Time) *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.SetArchivedAt(v) + }) +} + +// UpdateArchivedAt sets the "archived_at" field to the value that was provided on create. +func (u *FeatureUpsertBulk) UpdateArchivedAt() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.UpdateArchivedAt() + }) +} + +// ClearArchivedAt clears the value of the "archived_at" field. +func (u *FeatureUpsertBulk) ClearArchivedAt() *FeatureUpsertBulk { + return u.Update(func(s *FeatureUpsert) { + s.ClearArchivedAt() + }) +} + +// Exec executes the query. +func (u *FeatureUpsertBulk) 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 FeatureCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for FeatureCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *FeatureUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/feature_delete.go b/ent/db/feature_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..76d8ba3ed490ce1828933827d78e0c187347de83 --- /dev/null +++ b/ent/db/feature_delete.go @@ -0,0 +1,89 @@ +// 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/predicate" + + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" +) + +// FeatureDelete is the builder for deleting a Feature entity. +type FeatureDelete struct { + config + hooks []Hook + mutation *FeatureMutation +} + +// Where appends a list predicates to the FeatureDelete builder. +func (_d *FeatureDelete) Where(ps ...predicate.Feature) *FeatureDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *FeatureDelete) 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 *FeatureDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *FeatureDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(dbfeature.Table, sqlgraph.NewFieldSpec(dbfeature.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 +} + +// FeatureDeleteOne is the builder for deleting a single Feature entity. +type FeatureDeleteOne struct { + _d *FeatureDelete +} + +// Where appends a list predicates to the FeatureDelete builder. +func (_d *FeatureDeleteOne) Where(ps ...predicate.Feature) *FeatureDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *FeatureDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{dbfeature.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *FeatureDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/feature_query.go b/ent/db/feature_query.go new file mode 100644 index 0000000000000000000000000000000000000000..c427d7702c36701ed1e06b52a7b13c842f4df676 --- /dev/null +++ b/ent/db/feature_query.go @@ -0,0 +1,1102 @@ +// 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/addonratecard" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/openmeter/ent/db/entitlement" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + dbmeter "github.com/openmeterio/openmeter/openmeter/ent/db/meter" + "github.com/openmeterio/openmeter/openmeter/ent/db/planratecard" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// FeatureQuery is the builder for querying Feature entities. +type FeatureQuery struct { + config + ctx *QueryContext + order []dbfeature.OrderOption + inters []Interceptor + predicates []predicate.Feature + withEntitlement *EntitlementQuery + withRatecard *PlanRateCardQuery + withAddonRatecard *AddonRateCardQuery + withUsageBasedCharges *ChargeUsageBasedQuery + withUsageBasedRuns *ChargeUsageBasedRunsQuery + withFlatFeeCharges *ChargeFlatFeeQuery + withMeter *MeterQuery + 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 FeatureQuery builder. +func (_q *FeatureQuery) Where(ps ...predicate.Feature) *FeatureQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *FeatureQuery) Limit(limit int) *FeatureQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *FeatureQuery) Offset(offset int) *FeatureQuery { + _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 *FeatureQuery) Unique(unique bool) *FeatureQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *FeatureQuery) Order(o ...dbfeature.OrderOption) *FeatureQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryEntitlement chains the current query on the "entitlement" edge. +func (_q *FeatureQuery) QueryEntitlement() *EntitlementQuery { + query := (&EntitlementClient{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(dbfeature.Table, dbfeature.FieldID, selector), + sqlgraph.To(entitlement.Table, entitlement.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbfeature.EntitlementTable, dbfeature.EntitlementColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryRatecard chains the current query on the "ratecard" edge. +func (_q *FeatureQuery) QueryRatecard() *PlanRateCardQuery { + query := (&PlanRateCardClient{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(dbfeature.Table, dbfeature.FieldID, selector), + sqlgraph.To(planratecard.Table, planratecard.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbfeature.RatecardTable, dbfeature.RatecardColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryAddonRatecard chains the current query on the "addon_ratecard" edge. +func (_q *FeatureQuery) QueryAddonRatecard() *AddonRateCardQuery { + query := (&AddonRateCardClient{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(dbfeature.Table, dbfeature.FieldID, selector), + sqlgraph.To(addonratecard.Table, addonratecard.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbfeature.AddonRatecardTable, dbfeature.AddonRatecardColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryUsageBasedCharges chains the current query on the "usage_based_charges" edge. +func (_q *FeatureQuery) QueryUsageBasedCharges() *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(dbfeature.Table, dbfeature.FieldID, selector), + sqlgraph.To(chargeusagebased.Table, chargeusagebased.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbfeature.UsageBasedChargesTable, dbfeature.UsageBasedChargesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryUsageBasedRuns chains the current query on the "usage_based_runs" edge. +func (_q *FeatureQuery) QueryUsageBasedRuns() *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(dbfeature.Table, dbfeature.FieldID, selector), + sqlgraph.To(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbfeature.UsageBasedRunsTable, dbfeature.UsageBasedRunsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryFlatFeeCharges chains the current query on the "flat_fee_charges" edge. +func (_q *FeatureQuery) QueryFlatFeeCharges() *ChargeFlatFeeQuery { + query := (&ChargeFlatFeeClient{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(dbfeature.Table, dbfeature.FieldID, selector), + sqlgraph.To(chargeflatfee.Table, chargeflatfee.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbfeature.FlatFeeChargesTable, dbfeature.FlatFeeChargesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryMeter chains the current query on the "meter" edge. +func (_q *FeatureQuery) QueryMeter() *MeterQuery { + query := (&MeterClient{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(dbfeature.Table, dbfeature.FieldID, selector), + sqlgraph.To(dbmeter.Table, dbmeter.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, dbfeature.MeterTable, dbfeature.MeterColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Feature entity from the query. +// Returns a *NotFoundError when no Feature was found. +func (_q *FeatureQuery) First(ctx context.Context) (*Feature, 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{dbfeature.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *FeatureQuery) FirstX(ctx context.Context) *Feature { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Feature ID from the query. +// Returns a *NotFoundError when no Feature ID was found. +func (_q *FeatureQuery) 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{dbfeature.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *FeatureQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Feature entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Feature entity is found. +// Returns a *NotFoundError when no Feature entities are found. +func (_q *FeatureQuery) Only(ctx context.Context) (*Feature, 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{dbfeature.Label} + default: + return nil, &NotSingularError{dbfeature.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *FeatureQuery) OnlyX(ctx context.Context) *Feature { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Feature ID in the query. +// Returns a *NotSingularError when more than one Feature ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *FeatureQuery) 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{dbfeature.Label} + default: + err = &NotSingularError{dbfeature.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *FeatureQuery) 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 Features. +func (_q *FeatureQuery) All(ctx context.Context) ([]*Feature, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Feature, *FeatureQuery]() + return withInterceptors[[]*Feature](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *FeatureQuery) AllX(ctx context.Context) []*Feature { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Feature IDs. +func (_q *FeatureQuery) 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(dbfeature.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *FeatureQuery) 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 *FeatureQuery) 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[*FeatureQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *FeatureQuery) 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 *FeatureQuery) 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 *FeatureQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the FeatureQuery 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 *FeatureQuery) Clone() *FeatureQuery { + if _q == nil { + return nil + } + return &FeatureQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]dbfeature.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Feature{}, _q.predicates...), + withEntitlement: _q.withEntitlement.Clone(), + withRatecard: _q.withRatecard.Clone(), + withAddonRatecard: _q.withAddonRatecard.Clone(), + withUsageBasedCharges: _q.withUsageBasedCharges.Clone(), + withUsageBasedRuns: _q.withUsageBasedRuns.Clone(), + withFlatFeeCharges: _q.withFlatFeeCharges.Clone(), + withMeter: _q.withMeter.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithEntitlement tells the query-builder to eager-load the nodes that are connected to +// the "entitlement" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *FeatureQuery) WithEntitlement(opts ...func(*EntitlementQuery)) *FeatureQuery { + query := (&EntitlementClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withEntitlement = query + return _q +} + +// WithRatecard tells the query-builder to eager-load the nodes that are connected to +// the "ratecard" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *FeatureQuery) WithRatecard(opts ...func(*PlanRateCardQuery)) *FeatureQuery { + query := (&PlanRateCardClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withRatecard = query + return _q +} + +// WithAddonRatecard tells the query-builder to eager-load the nodes that are connected to +// the "addon_ratecard" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *FeatureQuery) WithAddonRatecard(opts ...func(*AddonRateCardQuery)) *FeatureQuery { + query := (&AddonRateCardClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withAddonRatecard = query + return _q +} + +// WithUsageBasedCharges tells the query-builder to eager-load the nodes that are connected to +// the "usage_based_charges" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *FeatureQuery) WithUsageBasedCharges(opts ...func(*ChargeUsageBasedQuery)) *FeatureQuery { + query := (&ChargeUsageBasedClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withUsageBasedCharges = query + return _q +} + +// WithUsageBasedRuns tells the query-builder to eager-load the nodes that are connected to +// the "usage_based_runs" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *FeatureQuery) WithUsageBasedRuns(opts ...func(*ChargeUsageBasedRunsQuery)) *FeatureQuery { + query := (&ChargeUsageBasedRunsClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withUsageBasedRuns = query + return _q +} + +// WithFlatFeeCharges tells the query-builder to eager-load the nodes that are connected to +// the "flat_fee_charges" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *FeatureQuery) WithFlatFeeCharges(opts ...func(*ChargeFlatFeeQuery)) *FeatureQuery { + query := (&ChargeFlatFeeClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withFlatFeeCharges = query + return _q +} + +// WithMeter tells the query-builder to eager-load the nodes that are connected to +// the "meter" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *FeatureQuery) WithMeter(opts ...func(*MeterQuery)) *FeatureQuery { + query := (&MeterClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withMeter = 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 { +// CreatedAt time.Time `json:"created_at,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Feature.Query(). +// GroupBy(dbfeature.FieldCreatedAt). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *FeatureQuery) GroupBy(field string, fields ...string) *FeatureGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &FeatureGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = dbfeature.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 { +// CreatedAt time.Time `json:"created_at,omitempty"` +// } +// +// client.Feature.Query(). +// Select(dbfeature.FieldCreatedAt). +// Scan(ctx, &v) +func (_q *FeatureQuery) Select(fields ...string) *FeatureSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &FeatureSelect{FeatureQuery: _q} + sbuild.label = dbfeature.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a FeatureSelect configured with the given aggregations. +func (_q *FeatureQuery) Aggregate(fns ...AggregateFunc) *FeatureSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *FeatureQuery) 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 !dbfeature.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 *FeatureQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Feature, error) { + var ( + nodes = []*Feature{} + _spec = _q.querySpec() + loadedTypes = [7]bool{ + _q.withEntitlement != nil, + _q.withRatecard != nil, + _q.withAddonRatecard != nil, + _q.withUsageBasedCharges != nil, + _q.withUsageBasedRuns != nil, + _q.withFlatFeeCharges != nil, + _q.withMeter != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Feature).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Feature{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.withEntitlement; query != nil { + if err := _q.loadEntitlement(ctx, query, nodes, + func(n *Feature) { n.Edges.Entitlement = []*Entitlement{} }, + func(n *Feature, e *Entitlement) { n.Edges.Entitlement = append(n.Edges.Entitlement, e) }); err != nil { + return nil, err + } + } + if query := _q.withRatecard; query != nil { + if err := _q.loadRatecard(ctx, query, nodes, + func(n *Feature) { n.Edges.Ratecard = []*PlanRateCard{} }, + func(n *Feature, e *PlanRateCard) { n.Edges.Ratecard = append(n.Edges.Ratecard, e) }); err != nil { + return nil, err + } + } + if query := _q.withAddonRatecard; query != nil { + if err := _q.loadAddonRatecard(ctx, query, nodes, + func(n *Feature) { n.Edges.AddonRatecard = []*AddonRateCard{} }, + func(n *Feature, e *AddonRateCard) { n.Edges.AddonRatecard = append(n.Edges.AddonRatecard, e) }); err != nil { + return nil, err + } + } + if query := _q.withUsageBasedCharges; query != nil { + if err := _q.loadUsageBasedCharges(ctx, query, nodes, + func(n *Feature) { n.Edges.UsageBasedCharges = []*ChargeUsageBased{} }, + func(n *Feature, e *ChargeUsageBased) { + n.Edges.UsageBasedCharges = append(n.Edges.UsageBasedCharges, e) + }); err != nil { + return nil, err + } + } + if query := _q.withUsageBasedRuns; query != nil { + if err := _q.loadUsageBasedRuns(ctx, query, nodes, + func(n *Feature) { n.Edges.UsageBasedRuns = []*ChargeUsageBasedRuns{} }, + func(n *Feature, e *ChargeUsageBasedRuns) { n.Edges.UsageBasedRuns = append(n.Edges.UsageBasedRuns, e) }); err != nil { + return nil, err + } + } + if query := _q.withFlatFeeCharges; query != nil { + if err := _q.loadFlatFeeCharges(ctx, query, nodes, + func(n *Feature) { n.Edges.FlatFeeCharges = []*ChargeFlatFee{} }, + func(n *Feature, e *ChargeFlatFee) { n.Edges.FlatFeeCharges = append(n.Edges.FlatFeeCharges, e) }); err != nil { + return nil, err + } + } + if query := _q.withMeter; query != nil { + if err := _q.loadMeter(ctx, query, nodes, nil, + func(n *Feature, e *Meter) { n.Edges.Meter = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *FeatureQuery) loadEntitlement(ctx context.Context, query *EntitlementQuery, nodes []*Feature, init func(*Feature), assign func(*Feature, *Entitlement)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Feature) + 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(entitlement.FieldFeatureID) + } + query.Where(predicate.Entitlement(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(dbfeature.EntitlementColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.FeatureID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "feature_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *FeatureQuery) loadRatecard(ctx context.Context, query *PlanRateCardQuery, nodes []*Feature, init func(*Feature), assign func(*Feature, *PlanRateCard)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Feature) + 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(planratecard.FieldFeatureID) + } + query.Where(predicate.PlanRateCard(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(dbfeature.RatecardColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.FeatureID + if fk == nil { + return fmt.Errorf(`foreign-key "feature_id" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "feature_id" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *FeatureQuery) loadAddonRatecard(ctx context.Context, query *AddonRateCardQuery, nodes []*Feature, init func(*Feature), assign func(*Feature, *AddonRateCard)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Feature) + 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(addonratecard.FieldFeatureID) + } + query.Where(predicate.AddonRateCard(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(dbfeature.AddonRatecardColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.FeatureID + if fk == nil { + return fmt.Errorf(`foreign-key "feature_id" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "feature_id" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *FeatureQuery) loadUsageBasedCharges(ctx context.Context, query *ChargeUsageBasedQuery, nodes []*Feature, init func(*Feature), assign func(*Feature, *ChargeUsageBased)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Feature) + 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(chargeusagebased.FieldFeatureID) + } + query.Where(predicate.ChargeUsageBased(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(dbfeature.UsageBasedChargesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.FeatureID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "feature_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *FeatureQuery) loadUsageBasedRuns(ctx context.Context, query *ChargeUsageBasedRunsQuery, nodes []*Feature, init func(*Feature), assign func(*Feature, *ChargeUsageBasedRuns)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Feature) + 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.FieldFeatureID) + } + query.Where(predicate.ChargeUsageBasedRuns(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(dbfeature.UsageBasedRunsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.FeatureID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "feature_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *FeatureQuery) loadFlatFeeCharges(ctx context.Context, query *ChargeFlatFeeQuery, nodes []*Feature, init func(*Feature), assign func(*Feature, *ChargeFlatFee)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Feature) + 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(chargeflatfee.FieldFeatureID) + } + query.Where(predicate.ChargeFlatFee(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(dbfeature.FlatFeeChargesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.FeatureID + if fk == nil { + return fmt.Errorf(`foreign-key "feature_id" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "feature_id" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *FeatureQuery) loadMeter(ctx context.Context, query *MeterQuery, nodes []*Feature, init func(*Feature), assign func(*Feature, *Meter)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*Feature) + for i := range nodes { + if nodes[i].MeterID == nil { + continue + } + fk := *nodes[i].MeterID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(dbmeter.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 "meter_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *FeatureQuery) 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 *FeatureQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(dbfeature.Table, dbfeature.Columns, sqlgraph.NewFieldSpec(dbfeature.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, dbfeature.FieldID) + for i := range fields { + if fields[i] != dbfeature.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withMeter != nil { + _spec.Node.AddColumnOnce(dbfeature.FieldMeterID) + } + } + 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 *FeatureQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(dbfeature.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = dbfeature.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 *FeatureQuery) ForUpdate(opts ...sql.LockOption) *FeatureQuery { + 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 *FeatureQuery) ForShare(opts ...sql.LockOption) *FeatureQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// FeatureGroupBy is the group-by builder for Feature entities. +type FeatureGroupBy struct { + selector + build *FeatureQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *FeatureGroupBy) Aggregate(fns ...AggregateFunc) *FeatureGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *FeatureGroupBy) 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[*FeatureQuery, *FeatureGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *FeatureGroupBy) sqlScan(ctx context.Context, root *FeatureQuery, 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) +} + +// FeatureSelect is the builder for selecting fields of Feature entities. +type FeatureSelect struct { + *FeatureQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *FeatureSelect) Aggregate(fns ...AggregateFunc) *FeatureSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *FeatureSelect) 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[*FeatureQuery, *FeatureSelect](ctx, _s.FeatureQuery, _s, _s.inters, v) +} + +func (_s *FeatureSelect) sqlScan(ctx context.Context, root *FeatureQuery, 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/ent/db/feature_update.go b/ent/db/feature_update.go new file mode 100644 index 0000000000000000000000000000000000000000..76bd66ce792ccfa2ce6d0acdc9349e084045793a --- /dev/null +++ b/ent/db/feature_update.go @@ -0,0 +1,1948 @@ +// 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/addonratecard" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/openmeter/ent/db/entitlement" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + "github.com/openmeterio/openmeter/openmeter/ent/db/planratecard" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/productcatalog/feature" +) + +// FeatureUpdate is the builder for updating Feature entities. +type FeatureUpdate struct { + config + hooks []Hook + mutation *FeatureMutation +} + +// Where appends a list predicates to the FeatureUpdate builder. +func (_u *FeatureUpdate) Where(ps ...predicate.Feature) *FeatureUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *FeatureUpdate) SetUpdatedAt(v time.Time) *FeatureUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *FeatureUpdate) SetDeletedAt(v time.Time) *FeatureUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *FeatureUpdate) SetNillableDeletedAt(v *time.Time) *FeatureUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *FeatureUpdate) ClearDeletedAt() *FeatureUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *FeatureUpdate) SetMetadata(v map[string]string) *FeatureUpdate { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *FeatureUpdate) ClearMetadata() *FeatureUpdate { + _u.mutation.ClearMetadata() + return _u +} + +// SetName sets the "name" field. +func (_u *FeatureUpdate) SetName(v string) *FeatureUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *FeatureUpdate) SetNillableName(v *string) *FeatureUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *FeatureUpdate) SetDescription(v string) *FeatureUpdate { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *FeatureUpdate) SetNillableDescription(v *string) *FeatureUpdate { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *FeatureUpdate) ClearDescription() *FeatureUpdate { + _u.mutation.ClearDescription() + return _u +} + +// SetMeterGroupByFilters sets the "meter_group_by_filters" field. +func (_u *FeatureUpdate) SetMeterGroupByFilters(v map[string]string) *FeatureUpdate { + _u.mutation.SetMeterGroupByFilters(v) + return _u +} + +// ClearMeterGroupByFilters clears the value of the "meter_group_by_filters" field. +func (_u *FeatureUpdate) ClearMeterGroupByFilters() *FeatureUpdate { + _u.mutation.ClearMeterGroupByFilters() + return _u +} + +// SetAdvancedMeterGroupByFilters sets the "advanced_meter_group_by_filters" field. +func (_u *FeatureUpdate) SetAdvancedMeterGroupByFilters(v feature.MeterGroupByFilters) *FeatureUpdate { + _u.mutation.SetAdvancedMeterGroupByFilters(v) + return _u +} + +// ClearAdvancedMeterGroupByFilters clears the value of the "advanced_meter_group_by_filters" field. +func (_u *FeatureUpdate) ClearAdvancedMeterGroupByFilters() *FeatureUpdate { + _u.mutation.ClearAdvancedMeterGroupByFilters() + return _u +} + +// SetUnitCostType sets the "unit_cost_type" field. +func (_u *FeatureUpdate) SetUnitCostType(v string) *FeatureUpdate { + _u.mutation.SetUnitCostType(v) + return _u +} + +// SetNillableUnitCostType sets the "unit_cost_type" field if the given value is not nil. +func (_u *FeatureUpdate) SetNillableUnitCostType(v *string) *FeatureUpdate { + if v != nil { + _u.SetUnitCostType(*v) + } + return _u +} + +// ClearUnitCostType clears the value of the "unit_cost_type" field. +func (_u *FeatureUpdate) ClearUnitCostType() *FeatureUpdate { + _u.mutation.ClearUnitCostType() + return _u +} + +// SetUnitCostManualAmount sets the "unit_cost_manual_amount" field. +func (_u *FeatureUpdate) SetUnitCostManualAmount(v alpacadecimal.Decimal) *FeatureUpdate { + _u.mutation.SetUnitCostManualAmount(v) + return _u +} + +// SetNillableUnitCostManualAmount sets the "unit_cost_manual_amount" field if the given value is not nil. +func (_u *FeatureUpdate) SetNillableUnitCostManualAmount(v *alpacadecimal.Decimal) *FeatureUpdate { + if v != nil { + _u.SetUnitCostManualAmount(*v) + } + return _u +} + +// ClearUnitCostManualAmount clears the value of the "unit_cost_manual_amount" field. +func (_u *FeatureUpdate) ClearUnitCostManualAmount() *FeatureUpdate { + _u.mutation.ClearUnitCostManualAmount() + return _u +} + +// SetUnitCostLlmProviderProperty sets the "unit_cost_llm_provider_property" field. +func (_u *FeatureUpdate) SetUnitCostLlmProviderProperty(v string) *FeatureUpdate { + _u.mutation.SetUnitCostLlmProviderProperty(v) + return _u +} + +// SetNillableUnitCostLlmProviderProperty sets the "unit_cost_llm_provider_property" field if the given value is not nil. +func (_u *FeatureUpdate) SetNillableUnitCostLlmProviderProperty(v *string) *FeatureUpdate { + if v != nil { + _u.SetUnitCostLlmProviderProperty(*v) + } + return _u +} + +// ClearUnitCostLlmProviderProperty clears the value of the "unit_cost_llm_provider_property" field. +func (_u *FeatureUpdate) ClearUnitCostLlmProviderProperty() *FeatureUpdate { + _u.mutation.ClearUnitCostLlmProviderProperty() + return _u +} + +// SetUnitCostLlmProvider sets the "unit_cost_llm_provider" field. +func (_u *FeatureUpdate) SetUnitCostLlmProvider(v string) *FeatureUpdate { + _u.mutation.SetUnitCostLlmProvider(v) + return _u +} + +// SetNillableUnitCostLlmProvider sets the "unit_cost_llm_provider" field if the given value is not nil. +func (_u *FeatureUpdate) SetNillableUnitCostLlmProvider(v *string) *FeatureUpdate { + if v != nil { + _u.SetUnitCostLlmProvider(*v) + } + return _u +} + +// ClearUnitCostLlmProvider clears the value of the "unit_cost_llm_provider" field. +func (_u *FeatureUpdate) ClearUnitCostLlmProvider() *FeatureUpdate { + _u.mutation.ClearUnitCostLlmProvider() + return _u +} + +// SetUnitCostLlmModelProperty sets the "unit_cost_llm_model_property" field. +func (_u *FeatureUpdate) SetUnitCostLlmModelProperty(v string) *FeatureUpdate { + _u.mutation.SetUnitCostLlmModelProperty(v) + return _u +} + +// SetNillableUnitCostLlmModelProperty sets the "unit_cost_llm_model_property" field if the given value is not nil. +func (_u *FeatureUpdate) SetNillableUnitCostLlmModelProperty(v *string) *FeatureUpdate { + if v != nil { + _u.SetUnitCostLlmModelProperty(*v) + } + return _u +} + +// ClearUnitCostLlmModelProperty clears the value of the "unit_cost_llm_model_property" field. +func (_u *FeatureUpdate) ClearUnitCostLlmModelProperty() *FeatureUpdate { + _u.mutation.ClearUnitCostLlmModelProperty() + return _u +} + +// SetUnitCostLlmModel sets the "unit_cost_llm_model" field. +func (_u *FeatureUpdate) SetUnitCostLlmModel(v string) *FeatureUpdate { + _u.mutation.SetUnitCostLlmModel(v) + return _u +} + +// SetNillableUnitCostLlmModel sets the "unit_cost_llm_model" field if the given value is not nil. +func (_u *FeatureUpdate) SetNillableUnitCostLlmModel(v *string) *FeatureUpdate { + if v != nil { + _u.SetUnitCostLlmModel(*v) + } + return _u +} + +// ClearUnitCostLlmModel clears the value of the "unit_cost_llm_model" field. +func (_u *FeatureUpdate) ClearUnitCostLlmModel() *FeatureUpdate { + _u.mutation.ClearUnitCostLlmModel() + return _u +} + +// SetUnitCostLlmTokenTypeProperty sets the "unit_cost_llm_token_type_property" field. +func (_u *FeatureUpdate) SetUnitCostLlmTokenTypeProperty(v string) *FeatureUpdate { + _u.mutation.SetUnitCostLlmTokenTypeProperty(v) + return _u +} + +// SetNillableUnitCostLlmTokenTypeProperty sets the "unit_cost_llm_token_type_property" field if the given value is not nil. +func (_u *FeatureUpdate) SetNillableUnitCostLlmTokenTypeProperty(v *string) *FeatureUpdate { + if v != nil { + _u.SetUnitCostLlmTokenTypeProperty(*v) + } + return _u +} + +// ClearUnitCostLlmTokenTypeProperty clears the value of the "unit_cost_llm_token_type_property" field. +func (_u *FeatureUpdate) ClearUnitCostLlmTokenTypeProperty() *FeatureUpdate { + _u.mutation.ClearUnitCostLlmTokenTypeProperty() + return _u +} + +// SetUnitCostLlmTokenType sets the "unit_cost_llm_token_type" field. +func (_u *FeatureUpdate) SetUnitCostLlmTokenType(v string) *FeatureUpdate { + _u.mutation.SetUnitCostLlmTokenType(v) + return _u +} + +// SetNillableUnitCostLlmTokenType sets the "unit_cost_llm_token_type" field if the given value is not nil. +func (_u *FeatureUpdate) SetNillableUnitCostLlmTokenType(v *string) *FeatureUpdate { + if v != nil { + _u.SetUnitCostLlmTokenType(*v) + } + return _u +} + +// ClearUnitCostLlmTokenType clears the value of the "unit_cost_llm_token_type" field. +func (_u *FeatureUpdate) ClearUnitCostLlmTokenType() *FeatureUpdate { + _u.mutation.ClearUnitCostLlmTokenType() + return _u +} + +// SetArchivedAt sets the "archived_at" field. +func (_u *FeatureUpdate) SetArchivedAt(v time.Time) *FeatureUpdate { + _u.mutation.SetArchivedAt(v) + return _u +} + +// SetNillableArchivedAt sets the "archived_at" field if the given value is not nil. +func (_u *FeatureUpdate) SetNillableArchivedAt(v *time.Time) *FeatureUpdate { + if v != nil { + _u.SetArchivedAt(*v) + } + return _u +} + +// ClearArchivedAt clears the value of the "archived_at" field. +func (_u *FeatureUpdate) ClearArchivedAt() *FeatureUpdate { + _u.mutation.ClearArchivedAt() + return _u +} + +// AddEntitlementIDs adds the "entitlement" edge to the Entitlement entity by IDs. +func (_u *FeatureUpdate) AddEntitlementIDs(ids ...string) *FeatureUpdate { + _u.mutation.AddEntitlementIDs(ids...) + return _u +} + +// AddEntitlement adds the "entitlement" edges to the Entitlement entity. +func (_u *FeatureUpdate) AddEntitlement(v ...*Entitlement) *FeatureUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddEntitlementIDs(ids...) +} + +// AddRatecardIDs adds the "ratecard" edge to the PlanRateCard entity by IDs. +func (_u *FeatureUpdate) AddRatecardIDs(ids ...string) *FeatureUpdate { + _u.mutation.AddRatecardIDs(ids...) + return _u +} + +// AddRatecard adds the "ratecard" edges to the PlanRateCard entity. +func (_u *FeatureUpdate) AddRatecard(v ...*PlanRateCard) *FeatureUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddRatecardIDs(ids...) +} + +// AddAddonRatecardIDs adds the "addon_ratecard" edge to the AddonRateCard entity by IDs. +func (_u *FeatureUpdate) AddAddonRatecardIDs(ids ...string) *FeatureUpdate { + _u.mutation.AddAddonRatecardIDs(ids...) + return _u +} + +// AddAddonRatecard adds the "addon_ratecard" edges to the AddonRateCard entity. +func (_u *FeatureUpdate) AddAddonRatecard(v ...*AddonRateCard) *FeatureUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddAddonRatecardIDs(ids...) +} + +// AddUsageBasedChargeIDs adds the "usage_based_charges" edge to the ChargeUsageBased entity by IDs. +func (_u *FeatureUpdate) AddUsageBasedChargeIDs(ids ...string) *FeatureUpdate { + _u.mutation.AddUsageBasedChargeIDs(ids...) + return _u +} + +// AddUsageBasedCharges adds the "usage_based_charges" edges to the ChargeUsageBased entity. +func (_u *FeatureUpdate) AddUsageBasedCharges(v ...*ChargeUsageBased) *FeatureUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddUsageBasedChargeIDs(ids...) +} + +// AddUsageBasedRunIDs adds the "usage_based_runs" edge to the ChargeUsageBasedRuns entity by IDs. +func (_u *FeatureUpdate) AddUsageBasedRunIDs(ids ...string) *FeatureUpdate { + _u.mutation.AddUsageBasedRunIDs(ids...) + return _u +} + +// AddUsageBasedRuns adds the "usage_based_runs" edges to the ChargeUsageBasedRuns entity. +func (_u *FeatureUpdate) AddUsageBasedRuns(v ...*ChargeUsageBasedRuns) *FeatureUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddUsageBasedRunIDs(ids...) +} + +// AddFlatFeeChargeIDs adds the "flat_fee_charges" edge to the ChargeFlatFee entity by IDs. +func (_u *FeatureUpdate) AddFlatFeeChargeIDs(ids ...string) *FeatureUpdate { + _u.mutation.AddFlatFeeChargeIDs(ids...) + return _u +} + +// AddFlatFeeCharges adds the "flat_fee_charges" edges to the ChargeFlatFee entity. +func (_u *FeatureUpdate) AddFlatFeeCharges(v ...*ChargeFlatFee) *FeatureUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddFlatFeeChargeIDs(ids...) +} + +// Mutation returns the FeatureMutation object of the builder. +func (_u *FeatureUpdate) Mutation() *FeatureMutation { + return _u.mutation +} + +// ClearEntitlement clears all "entitlement" edges to the Entitlement entity. +func (_u *FeatureUpdate) ClearEntitlement() *FeatureUpdate { + _u.mutation.ClearEntitlement() + return _u +} + +// RemoveEntitlementIDs removes the "entitlement" edge to Entitlement entities by IDs. +func (_u *FeatureUpdate) RemoveEntitlementIDs(ids ...string) *FeatureUpdate { + _u.mutation.RemoveEntitlementIDs(ids...) + return _u +} + +// RemoveEntitlement removes "entitlement" edges to Entitlement entities. +func (_u *FeatureUpdate) RemoveEntitlement(v ...*Entitlement) *FeatureUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveEntitlementIDs(ids...) +} + +// ClearRatecard clears all "ratecard" edges to the PlanRateCard entity. +func (_u *FeatureUpdate) ClearRatecard() *FeatureUpdate { + _u.mutation.ClearRatecard() + return _u +} + +// RemoveRatecardIDs removes the "ratecard" edge to PlanRateCard entities by IDs. +func (_u *FeatureUpdate) RemoveRatecardIDs(ids ...string) *FeatureUpdate { + _u.mutation.RemoveRatecardIDs(ids...) + return _u +} + +// RemoveRatecard removes "ratecard" edges to PlanRateCard entities. +func (_u *FeatureUpdate) RemoveRatecard(v ...*PlanRateCard) *FeatureUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveRatecardIDs(ids...) +} + +// ClearAddonRatecard clears all "addon_ratecard" edges to the AddonRateCard entity. +func (_u *FeatureUpdate) ClearAddonRatecard() *FeatureUpdate { + _u.mutation.ClearAddonRatecard() + return _u +} + +// RemoveAddonRatecardIDs removes the "addon_ratecard" edge to AddonRateCard entities by IDs. +func (_u *FeatureUpdate) RemoveAddonRatecardIDs(ids ...string) *FeatureUpdate { + _u.mutation.RemoveAddonRatecardIDs(ids...) + return _u +} + +// RemoveAddonRatecard removes "addon_ratecard" edges to AddonRateCard entities. +func (_u *FeatureUpdate) RemoveAddonRatecard(v ...*AddonRateCard) *FeatureUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveAddonRatecardIDs(ids...) +} + +// ClearUsageBasedCharges clears all "usage_based_charges" edges to the ChargeUsageBased entity. +func (_u *FeatureUpdate) ClearUsageBasedCharges() *FeatureUpdate { + _u.mutation.ClearUsageBasedCharges() + return _u +} + +// RemoveUsageBasedChargeIDs removes the "usage_based_charges" edge to ChargeUsageBased entities by IDs. +func (_u *FeatureUpdate) RemoveUsageBasedChargeIDs(ids ...string) *FeatureUpdate { + _u.mutation.RemoveUsageBasedChargeIDs(ids...) + return _u +} + +// RemoveUsageBasedCharges removes "usage_based_charges" edges to ChargeUsageBased entities. +func (_u *FeatureUpdate) RemoveUsageBasedCharges(v ...*ChargeUsageBased) *FeatureUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveUsageBasedChargeIDs(ids...) +} + +// ClearUsageBasedRuns clears all "usage_based_runs" edges to the ChargeUsageBasedRuns entity. +func (_u *FeatureUpdate) ClearUsageBasedRuns() *FeatureUpdate { + _u.mutation.ClearUsageBasedRuns() + return _u +} + +// RemoveUsageBasedRunIDs removes the "usage_based_runs" edge to ChargeUsageBasedRuns entities by IDs. +func (_u *FeatureUpdate) RemoveUsageBasedRunIDs(ids ...string) *FeatureUpdate { + _u.mutation.RemoveUsageBasedRunIDs(ids...) + return _u +} + +// RemoveUsageBasedRuns removes "usage_based_runs" edges to ChargeUsageBasedRuns entities. +func (_u *FeatureUpdate) RemoveUsageBasedRuns(v ...*ChargeUsageBasedRuns) *FeatureUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveUsageBasedRunIDs(ids...) +} + +// ClearFlatFeeCharges clears all "flat_fee_charges" edges to the ChargeFlatFee entity. +func (_u *FeatureUpdate) ClearFlatFeeCharges() *FeatureUpdate { + _u.mutation.ClearFlatFeeCharges() + return _u +} + +// RemoveFlatFeeChargeIDs removes the "flat_fee_charges" edge to ChargeFlatFee entities by IDs. +func (_u *FeatureUpdate) RemoveFlatFeeChargeIDs(ids ...string) *FeatureUpdate { + _u.mutation.RemoveFlatFeeChargeIDs(ids...) + return _u +} + +// RemoveFlatFeeCharges removes "flat_fee_charges" edges to ChargeFlatFee entities. +func (_u *FeatureUpdate) RemoveFlatFeeCharges(v ...*ChargeFlatFee) *FeatureUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveFlatFeeChargeIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *FeatureUpdate) 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 *FeatureUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *FeatureUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *FeatureUpdate) 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 *FeatureUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := dbfeature.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *FeatureUpdate) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := dbfeature.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "Feature.name": %w`, err)} + } + } + if v, ok := _u.mutation.Description(); ok { + if err := dbfeature.DescriptionValidator(v); err != nil { + return &ValidationError{Name: "description", err: fmt.Errorf(`db: validator failed for field "Feature.description": %w`, err)} + } + } + return nil +} + +func (_u *FeatureUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(dbfeature.Table, dbfeature.Columns, sqlgraph.NewFieldSpec(dbfeature.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(dbfeature.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(dbfeature.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(dbfeature.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(dbfeature.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(dbfeature.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(dbfeature.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(dbfeature.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(dbfeature.FieldDescription, field.TypeString) + } + if _u.mutation.MeterSlugCleared() { + _spec.ClearField(dbfeature.FieldMeterSlug, field.TypeString) + } + if value, ok := _u.mutation.MeterGroupByFilters(); ok { + _spec.SetField(dbfeature.FieldMeterGroupByFilters, field.TypeJSON, value) + } + if _u.mutation.MeterGroupByFiltersCleared() { + _spec.ClearField(dbfeature.FieldMeterGroupByFilters, field.TypeJSON) + } + if value, ok := _u.mutation.AdvancedMeterGroupByFilters(); ok { + _spec.SetField(dbfeature.FieldAdvancedMeterGroupByFilters, field.TypeJSON, value) + } + if _u.mutation.AdvancedMeterGroupByFiltersCleared() { + _spec.ClearField(dbfeature.FieldAdvancedMeterGroupByFilters, field.TypeJSON) + } + if value, ok := _u.mutation.UnitCostType(); ok { + _spec.SetField(dbfeature.FieldUnitCostType, field.TypeString, value) + } + if _u.mutation.UnitCostTypeCleared() { + _spec.ClearField(dbfeature.FieldUnitCostType, field.TypeString) + } + if value, ok := _u.mutation.UnitCostManualAmount(); ok { + _spec.SetField(dbfeature.FieldUnitCostManualAmount, field.TypeOther, value) + } + if _u.mutation.UnitCostManualAmountCleared() { + _spec.ClearField(dbfeature.FieldUnitCostManualAmount, field.TypeOther) + } + if value, ok := _u.mutation.UnitCostLlmProviderProperty(); ok { + _spec.SetField(dbfeature.FieldUnitCostLlmProviderProperty, field.TypeString, value) + } + if _u.mutation.UnitCostLlmProviderPropertyCleared() { + _spec.ClearField(dbfeature.FieldUnitCostLlmProviderProperty, field.TypeString) + } + if value, ok := _u.mutation.UnitCostLlmProvider(); ok { + _spec.SetField(dbfeature.FieldUnitCostLlmProvider, field.TypeString, value) + } + if _u.mutation.UnitCostLlmProviderCleared() { + _spec.ClearField(dbfeature.FieldUnitCostLlmProvider, field.TypeString) + } + if value, ok := _u.mutation.UnitCostLlmModelProperty(); ok { + _spec.SetField(dbfeature.FieldUnitCostLlmModelProperty, field.TypeString, value) + } + if _u.mutation.UnitCostLlmModelPropertyCleared() { + _spec.ClearField(dbfeature.FieldUnitCostLlmModelProperty, field.TypeString) + } + if value, ok := _u.mutation.UnitCostLlmModel(); ok { + _spec.SetField(dbfeature.FieldUnitCostLlmModel, field.TypeString, value) + } + if _u.mutation.UnitCostLlmModelCleared() { + _spec.ClearField(dbfeature.FieldUnitCostLlmModel, field.TypeString) + } + if value, ok := _u.mutation.UnitCostLlmTokenTypeProperty(); ok { + _spec.SetField(dbfeature.FieldUnitCostLlmTokenTypeProperty, field.TypeString, value) + } + if _u.mutation.UnitCostLlmTokenTypePropertyCleared() { + _spec.ClearField(dbfeature.FieldUnitCostLlmTokenTypeProperty, field.TypeString) + } + if value, ok := _u.mutation.UnitCostLlmTokenType(); ok { + _spec.SetField(dbfeature.FieldUnitCostLlmTokenType, field.TypeString, value) + } + if _u.mutation.UnitCostLlmTokenTypeCleared() { + _spec.ClearField(dbfeature.FieldUnitCostLlmTokenType, field.TypeString) + } + if value, ok := _u.mutation.ArchivedAt(); ok { + _spec.SetField(dbfeature.FieldArchivedAt, field.TypeTime, value) + } + if _u.mutation.ArchivedAtCleared() { + _spec.ClearField(dbfeature.FieldArchivedAt, field.TypeTime) + } + if _u.mutation.EntitlementCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.EntitlementTable, + Columns: []string{dbfeature.EntitlementColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(entitlement.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedEntitlementIDs(); len(nodes) > 0 && !_u.mutation.EntitlementCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.EntitlementTable, + Columns: []string{dbfeature.EntitlementColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(entitlement.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.EntitlementIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.EntitlementTable, + Columns: []string{dbfeature.EntitlementColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(entitlement.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.RatecardCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.RatecardTable, + Columns: []string{dbfeature.RatecardColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(planratecard.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedRatecardIDs(); len(nodes) > 0 && !_u.mutation.RatecardCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.RatecardTable, + Columns: []string{dbfeature.RatecardColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(planratecard.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.RatecardIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.RatecardTable, + Columns: []string{dbfeature.RatecardColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(planratecard.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.AddonRatecardCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.AddonRatecardTable, + Columns: []string{dbfeature.AddonRatecardColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(addonratecard.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedAddonRatecardIDs(); len(nodes) > 0 && !_u.mutation.AddonRatecardCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.AddonRatecardTable, + Columns: []string{dbfeature.AddonRatecardColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(addonratecard.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.AddonRatecardIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.AddonRatecardTable, + Columns: []string{dbfeature.AddonRatecardColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(addonratecard.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.UsageBasedChargesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.UsageBasedChargesTable, + Columns: []string{dbfeature.UsageBasedChargesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebased.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedUsageBasedChargesIDs(); len(nodes) > 0 && !_u.mutation.UsageBasedChargesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.UsageBasedChargesTable, + Columns: []string{dbfeature.UsageBasedChargesColumn}, + 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.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.UsageBasedChargesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.UsageBasedChargesTable, + Columns: []string{dbfeature.UsageBasedChargesColumn}, + 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.UsageBasedRunsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.UsageBasedRunsTable, + Columns: []string{dbfeature.UsageBasedRunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedUsageBasedRunsIDs(); len(nodes) > 0 && !_u.mutation.UsageBasedRunsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.UsageBasedRunsTable, + Columns: []string{dbfeature.UsageBasedRunsColumn}, + 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.UsageBasedRunsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.UsageBasedRunsTable, + Columns: []string{dbfeature.UsageBasedRunsColumn}, + 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 _u.mutation.FlatFeeChargesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.FlatFeeChargesTable, + Columns: []string{dbfeature.FlatFeeChargesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfee.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedFlatFeeChargesIDs(); len(nodes) > 0 && !_u.mutation.FlatFeeChargesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.FlatFeeChargesTable, + Columns: []string{dbfeature.FlatFeeChargesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfee.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.FlatFeeChargesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.FlatFeeChargesTable, + Columns: []string{dbfeature.FlatFeeChargesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfee.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{dbfeature.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// FeatureUpdateOne is the builder for updating a single Feature entity. +type FeatureUpdateOne struct { + config + fields []string + hooks []Hook + mutation *FeatureMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *FeatureUpdateOne) SetUpdatedAt(v time.Time) *FeatureUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *FeatureUpdateOne) SetDeletedAt(v time.Time) *FeatureUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *FeatureUpdateOne) SetNillableDeletedAt(v *time.Time) *FeatureUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *FeatureUpdateOne) ClearDeletedAt() *FeatureUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *FeatureUpdateOne) SetMetadata(v map[string]string) *FeatureUpdateOne { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *FeatureUpdateOne) ClearMetadata() *FeatureUpdateOne { + _u.mutation.ClearMetadata() + return _u +} + +// SetName sets the "name" field. +func (_u *FeatureUpdateOne) SetName(v string) *FeatureUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *FeatureUpdateOne) SetNillableName(v *string) *FeatureUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *FeatureUpdateOne) SetDescription(v string) *FeatureUpdateOne { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *FeatureUpdateOne) SetNillableDescription(v *string) *FeatureUpdateOne { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *FeatureUpdateOne) ClearDescription() *FeatureUpdateOne { + _u.mutation.ClearDescription() + return _u +} + +// SetMeterGroupByFilters sets the "meter_group_by_filters" field. +func (_u *FeatureUpdateOne) SetMeterGroupByFilters(v map[string]string) *FeatureUpdateOne { + _u.mutation.SetMeterGroupByFilters(v) + return _u +} + +// ClearMeterGroupByFilters clears the value of the "meter_group_by_filters" field. +func (_u *FeatureUpdateOne) ClearMeterGroupByFilters() *FeatureUpdateOne { + _u.mutation.ClearMeterGroupByFilters() + return _u +} + +// SetAdvancedMeterGroupByFilters sets the "advanced_meter_group_by_filters" field. +func (_u *FeatureUpdateOne) SetAdvancedMeterGroupByFilters(v feature.MeterGroupByFilters) *FeatureUpdateOne { + _u.mutation.SetAdvancedMeterGroupByFilters(v) + return _u +} + +// ClearAdvancedMeterGroupByFilters clears the value of the "advanced_meter_group_by_filters" field. +func (_u *FeatureUpdateOne) ClearAdvancedMeterGroupByFilters() *FeatureUpdateOne { + _u.mutation.ClearAdvancedMeterGroupByFilters() + return _u +} + +// SetUnitCostType sets the "unit_cost_type" field. +func (_u *FeatureUpdateOne) SetUnitCostType(v string) *FeatureUpdateOne { + _u.mutation.SetUnitCostType(v) + return _u +} + +// SetNillableUnitCostType sets the "unit_cost_type" field if the given value is not nil. +func (_u *FeatureUpdateOne) SetNillableUnitCostType(v *string) *FeatureUpdateOne { + if v != nil { + _u.SetUnitCostType(*v) + } + return _u +} + +// ClearUnitCostType clears the value of the "unit_cost_type" field. +func (_u *FeatureUpdateOne) ClearUnitCostType() *FeatureUpdateOne { + _u.mutation.ClearUnitCostType() + return _u +} + +// SetUnitCostManualAmount sets the "unit_cost_manual_amount" field. +func (_u *FeatureUpdateOne) SetUnitCostManualAmount(v alpacadecimal.Decimal) *FeatureUpdateOne { + _u.mutation.SetUnitCostManualAmount(v) + return _u +} + +// SetNillableUnitCostManualAmount sets the "unit_cost_manual_amount" field if the given value is not nil. +func (_u *FeatureUpdateOne) SetNillableUnitCostManualAmount(v *alpacadecimal.Decimal) *FeatureUpdateOne { + if v != nil { + _u.SetUnitCostManualAmount(*v) + } + return _u +} + +// ClearUnitCostManualAmount clears the value of the "unit_cost_manual_amount" field. +func (_u *FeatureUpdateOne) ClearUnitCostManualAmount() *FeatureUpdateOne { + _u.mutation.ClearUnitCostManualAmount() + return _u +} + +// SetUnitCostLlmProviderProperty sets the "unit_cost_llm_provider_property" field. +func (_u *FeatureUpdateOne) SetUnitCostLlmProviderProperty(v string) *FeatureUpdateOne { + _u.mutation.SetUnitCostLlmProviderProperty(v) + return _u +} + +// SetNillableUnitCostLlmProviderProperty sets the "unit_cost_llm_provider_property" field if the given value is not nil. +func (_u *FeatureUpdateOne) SetNillableUnitCostLlmProviderProperty(v *string) *FeatureUpdateOne { + if v != nil { + _u.SetUnitCostLlmProviderProperty(*v) + } + return _u +} + +// ClearUnitCostLlmProviderProperty clears the value of the "unit_cost_llm_provider_property" field. +func (_u *FeatureUpdateOne) ClearUnitCostLlmProviderProperty() *FeatureUpdateOne { + _u.mutation.ClearUnitCostLlmProviderProperty() + return _u +} + +// SetUnitCostLlmProvider sets the "unit_cost_llm_provider" field. +func (_u *FeatureUpdateOne) SetUnitCostLlmProvider(v string) *FeatureUpdateOne { + _u.mutation.SetUnitCostLlmProvider(v) + return _u +} + +// SetNillableUnitCostLlmProvider sets the "unit_cost_llm_provider" field if the given value is not nil. +func (_u *FeatureUpdateOne) SetNillableUnitCostLlmProvider(v *string) *FeatureUpdateOne { + if v != nil { + _u.SetUnitCostLlmProvider(*v) + } + return _u +} + +// ClearUnitCostLlmProvider clears the value of the "unit_cost_llm_provider" field. +func (_u *FeatureUpdateOne) ClearUnitCostLlmProvider() *FeatureUpdateOne { + _u.mutation.ClearUnitCostLlmProvider() + return _u +} + +// SetUnitCostLlmModelProperty sets the "unit_cost_llm_model_property" field. +func (_u *FeatureUpdateOne) SetUnitCostLlmModelProperty(v string) *FeatureUpdateOne { + _u.mutation.SetUnitCostLlmModelProperty(v) + return _u +} + +// SetNillableUnitCostLlmModelProperty sets the "unit_cost_llm_model_property" field if the given value is not nil. +func (_u *FeatureUpdateOne) SetNillableUnitCostLlmModelProperty(v *string) *FeatureUpdateOne { + if v != nil { + _u.SetUnitCostLlmModelProperty(*v) + } + return _u +} + +// ClearUnitCostLlmModelProperty clears the value of the "unit_cost_llm_model_property" field. +func (_u *FeatureUpdateOne) ClearUnitCostLlmModelProperty() *FeatureUpdateOne { + _u.mutation.ClearUnitCostLlmModelProperty() + return _u +} + +// SetUnitCostLlmModel sets the "unit_cost_llm_model" field. +func (_u *FeatureUpdateOne) SetUnitCostLlmModel(v string) *FeatureUpdateOne { + _u.mutation.SetUnitCostLlmModel(v) + return _u +} + +// SetNillableUnitCostLlmModel sets the "unit_cost_llm_model" field if the given value is not nil. +func (_u *FeatureUpdateOne) SetNillableUnitCostLlmModel(v *string) *FeatureUpdateOne { + if v != nil { + _u.SetUnitCostLlmModel(*v) + } + return _u +} + +// ClearUnitCostLlmModel clears the value of the "unit_cost_llm_model" field. +func (_u *FeatureUpdateOne) ClearUnitCostLlmModel() *FeatureUpdateOne { + _u.mutation.ClearUnitCostLlmModel() + return _u +} + +// SetUnitCostLlmTokenTypeProperty sets the "unit_cost_llm_token_type_property" field. +func (_u *FeatureUpdateOne) SetUnitCostLlmTokenTypeProperty(v string) *FeatureUpdateOne { + _u.mutation.SetUnitCostLlmTokenTypeProperty(v) + return _u +} + +// SetNillableUnitCostLlmTokenTypeProperty sets the "unit_cost_llm_token_type_property" field if the given value is not nil. +func (_u *FeatureUpdateOne) SetNillableUnitCostLlmTokenTypeProperty(v *string) *FeatureUpdateOne { + if v != nil { + _u.SetUnitCostLlmTokenTypeProperty(*v) + } + return _u +} + +// ClearUnitCostLlmTokenTypeProperty clears the value of the "unit_cost_llm_token_type_property" field. +func (_u *FeatureUpdateOne) ClearUnitCostLlmTokenTypeProperty() *FeatureUpdateOne { + _u.mutation.ClearUnitCostLlmTokenTypeProperty() + return _u +} + +// SetUnitCostLlmTokenType sets the "unit_cost_llm_token_type" field. +func (_u *FeatureUpdateOne) SetUnitCostLlmTokenType(v string) *FeatureUpdateOne { + _u.mutation.SetUnitCostLlmTokenType(v) + return _u +} + +// SetNillableUnitCostLlmTokenType sets the "unit_cost_llm_token_type" field if the given value is not nil. +func (_u *FeatureUpdateOne) SetNillableUnitCostLlmTokenType(v *string) *FeatureUpdateOne { + if v != nil { + _u.SetUnitCostLlmTokenType(*v) + } + return _u +} + +// ClearUnitCostLlmTokenType clears the value of the "unit_cost_llm_token_type" field. +func (_u *FeatureUpdateOne) ClearUnitCostLlmTokenType() *FeatureUpdateOne { + _u.mutation.ClearUnitCostLlmTokenType() + return _u +} + +// SetArchivedAt sets the "archived_at" field. +func (_u *FeatureUpdateOne) SetArchivedAt(v time.Time) *FeatureUpdateOne { + _u.mutation.SetArchivedAt(v) + return _u +} + +// SetNillableArchivedAt sets the "archived_at" field if the given value is not nil. +func (_u *FeatureUpdateOne) SetNillableArchivedAt(v *time.Time) *FeatureUpdateOne { + if v != nil { + _u.SetArchivedAt(*v) + } + return _u +} + +// ClearArchivedAt clears the value of the "archived_at" field. +func (_u *FeatureUpdateOne) ClearArchivedAt() *FeatureUpdateOne { + _u.mutation.ClearArchivedAt() + return _u +} + +// AddEntitlementIDs adds the "entitlement" edge to the Entitlement entity by IDs. +func (_u *FeatureUpdateOne) AddEntitlementIDs(ids ...string) *FeatureUpdateOne { + _u.mutation.AddEntitlementIDs(ids...) + return _u +} + +// AddEntitlement adds the "entitlement" edges to the Entitlement entity. +func (_u *FeatureUpdateOne) AddEntitlement(v ...*Entitlement) *FeatureUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddEntitlementIDs(ids...) +} + +// AddRatecardIDs adds the "ratecard" edge to the PlanRateCard entity by IDs. +func (_u *FeatureUpdateOne) AddRatecardIDs(ids ...string) *FeatureUpdateOne { + _u.mutation.AddRatecardIDs(ids...) + return _u +} + +// AddRatecard adds the "ratecard" edges to the PlanRateCard entity. +func (_u *FeatureUpdateOne) AddRatecard(v ...*PlanRateCard) *FeatureUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddRatecardIDs(ids...) +} + +// AddAddonRatecardIDs adds the "addon_ratecard" edge to the AddonRateCard entity by IDs. +func (_u *FeatureUpdateOne) AddAddonRatecardIDs(ids ...string) *FeatureUpdateOne { + _u.mutation.AddAddonRatecardIDs(ids...) + return _u +} + +// AddAddonRatecard adds the "addon_ratecard" edges to the AddonRateCard entity. +func (_u *FeatureUpdateOne) AddAddonRatecard(v ...*AddonRateCard) *FeatureUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddAddonRatecardIDs(ids...) +} + +// AddUsageBasedChargeIDs adds the "usage_based_charges" edge to the ChargeUsageBased entity by IDs. +func (_u *FeatureUpdateOne) AddUsageBasedChargeIDs(ids ...string) *FeatureUpdateOne { + _u.mutation.AddUsageBasedChargeIDs(ids...) + return _u +} + +// AddUsageBasedCharges adds the "usage_based_charges" edges to the ChargeUsageBased entity. +func (_u *FeatureUpdateOne) AddUsageBasedCharges(v ...*ChargeUsageBased) *FeatureUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddUsageBasedChargeIDs(ids...) +} + +// AddUsageBasedRunIDs adds the "usage_based_runs" edge to the ChargeUsageBasedRuns entity by IDs. +func (_u *FeatureUpdateOne) AddUsageBasedRunIDs(ids ...string) *FeatureUpdateOne { + _u.mutation.AddUsageBasedRunIDs(ids...) + return _u +} + +// AddUsageBasedRuns adds the "usage_based_runs" edges to the ChargeUsageBasedRuns entity. +func (_u *FeatureUpdateOne) AddUsageBasedRuns(v ...*ChargeUsageBasedRuns) *FeatureUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddUsageBasedRunIDs(ids...) +} + +// AddFlatFeeChargeIDs adds the "flat_fee_charges" edge to the ChargeFlatFee entity by IDs. +func (_u *FeatureUpdateOne) AddFlatFeeChargeIDs(ids ...string) *FeatureUpdateOne { + _u.mutation.AddFlatFeeChargeIDs(ids...) + return _u +} + +// AddFlatFeeCharges adds the "flat_fee_charges" edges to the ChargeFlatFee entity. +func (_u *FeatureUpdateOne) AddFlatFeeCharges(v ...*ChargeFlatFee) *FeatureUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddFlatFeeChargeIDs(ids...) +} + +// Mutation returns the FeatureMutation object of the builder. +func (_u *FeatureUpdateOne) Mutation() *FeatureMutation { + return _u.mutation +} + +// ClearEntitlement clears all "entitlement" edges to the Entitlement entity. +func (_u *FeatureUpdateOne) ClearEntitlement() *FeatureUpdateOne { + _u.mutation.ClearEntitlement() + return _u +} + +// RemoveEntitlementIDs removes the "entitlement" edge to Entitlement entities by IDs. +func (_u *FeatureUpdateOne) RemoveEntitlementIDs(ids ...string) *FeatureUpdateOne { + _u.mutation.RemoveEntitlementIDs(ids...) + return _u +} + +// RemoveEntitlement removes "entitlement" edges to Entitlement entities. +func (_u *FeatureUpdateOne) RemoveEntitlement(v ...*Entitlement) *FeatureUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveEntitlementIDs(ids...) +} + +// ClearRatecard clears all "ratecard" edges to the PlanRateCard entity. +func (_u *FeatureUpdateOne) ClearRatecard() *FeatureUpdateOne { + _u.mutation.ClearRatecard() + return _u +} + +// RemoveRatecardIDs removes the "ratecard" edge to PlanRateCard entities by IDs. +func (_u *FeatureUpdateOne) RemoveRatecardIDs(ids ...string) *FeatureUpdateOne { + _u.mutation.RemoveRatecardIDs(ids...) + return _u +} + +// RemoveRatecard removes "ratecard" edges to PlanRateCard entities. +func (_u *FeatureUpdateOne) RemoveRatecard(v ...*PlanRateCard) *FeatureUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveRatecardIDs(ids...) +} + +// ClearAddonRatecard clears all "addon_ratecard" edges to the AddonRateCard entity. +func (_u *FeatureUpdateOne) ClearAddonRatecard() *FeatureUpdateOne { + _u.mutation.ClearAddonRatecard() + return _u +} + +// RemoveAddonRatecardIDs removes the "addon_ratecard" edge to AddonRateCard entities by IDs. +func (_u *FeatureUpdateOne) RemoveAddonRatecardIDs(ids ...string) *FeatureUpdateOne { + _u.mutation.RemoveAddonRatecardIDs(ids...) + return _u +} + +// RemoveAddonRatecard removes "addon_ratecard" edges to AddonRateCard entities. +func (_u *FeatureUpdateOne) RemoveAddonRatecard(v ...*AddonRateCard) *FeatureUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveAddonRatecardIDs(ids...) +} + +// ClearUsageBasedCharges clears all "usage_based_charges" edges to the ChargeUsageBased entity. +func (_u *FeatureUpdateOne) ClearUsageBasedCharges() *FeatureUpdateOne { + _u.mutation.ClearUsageBasedCharges() + return _u +} + +// RemoveUsageBasedChargeIDs removes the "usage_based_charges" edge to ChargeUsageBased entities by IDs. +func (_u *FeatureUpdateOne) RemoveUsageBasedChargeIDs(ids ...string) *FeatureUpdateOne { + _u.mutation.RemoveUsageBasedChargeIDs(ids...) + return _u +} + +// RemoveUsageBasedCharges removes "usage_based_charges" edges to ChargeUsageBased entities. +func (_u *FeatureUpdateOne) RemoveUsageBasedCharges(v ...*ChargeUsageBased) *FeatureUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveUsageBasedChargeIDs(ids...) +} + +// ClearUsageBasedRuns clears all "usage_based_runs" edges to the ChargeUsageBasedRuns entity. +func (_u *FeatureUpdateOne) ClearUsageBasedRuns() *FeatureUpdateOne { + _u.mutation.ClearUsageBasedRuns() + return _u +} + +// RemoveUsageBasedRunIDs removes the "usage_based_runs" edge to ChargeUsageBasedRuns entities by IDs. +func (_u *FeatureUpdateOne) RemoveUsageBasedRunIDs(ids ...string) *FeatureUpdateOne { + _u.mutation.RemoveUsageBasedRunIDs(ids...) + return _u +} + +// RemoveUsageBasedRuns removes "usage_based_runs" edges to ChargeUsageBasedRuns entities. +func (_u *FeatureUpdateOne) RemoveUsageBasedRuns(v ...*ChargeUsageBasedRuns) *FeatureUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveUsageBasedRunIDs(ids...) +} + +// ClearFlatFeeCharges clears all "flat_fee_charges" edges to the ChargeFlatFee entity. +func (_u *FeatureUpdateOne) ClearFlatFeeCharges() *FeatureUpdateOne { + _u.mutation.ClearFlatFeeCharges() + return _u +} + +// RemoveFlatFeeChargeIDs removes the "flat_fee_charges" edge to ChargeFlatFee entities by IDs. +func (_u *FeatureUpdateOne) RemoveFlatFeeChargeIDs(ids ...string) *FeatureUpdateOne { + _u.mutation.RemoveFlatFeeChargeIDs(ids...) + return _u +} + +// RemoveFlatFeeCharges removes "flat_fee_charges" edges to ChargeFlatFee entities. +func (_u *FeatureUpdateOne) RemoveFlatFeeCharges(v ...*ChargeFlatFee) *FeatureUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveFlatFeeChargeIDs(ids...) +} + +// Where appends a list predicates to the FeatureUpdate builder. +func (_u *FeatureUpdateOne) Where(ps ...predicate.Feature) *FeatureUpdateOne { + _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 *FeatureUpdateOne) Select(field string, fields ...string) *FeatureUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Feature entity. +func (_u *FeatureUpdateOne) Save(ctx context.Context) (*Feature, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *FeatureUpdateOne) SaveX(ctx context.Context) *Feature { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *FeatureUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *FeatureUpdateOne) 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 *FeatureUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := dbfeature.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *FeatureUpdateOne) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := dbfeature.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "Feature.name": %w`, err)} + } + } + if v, ok := _u.mutation.Description(); ok { + if err := dbfeature.DescriptionValidator(v); err != nil { + return &ValidationError{Name: "description", err: fmt.Errorf(`db: validator failed for field "Feature.description": %w`, err)} + } + } + return nil +} + +func (_u *FeatureUpdateOne) sqlSave(ctx context.Context) (_node *Feature, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(dbfeature.Table, dbfeature.Columns, sqlgraph.NewFieldSpec(dbfeature.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "Feature.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, dbfeature.FieldID) + for _, f := range fields { + if !dbfeature.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != dbfeature.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(dbfeature.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(dbfeature.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(dbfeature.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(dbfeature.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(dbfeature.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(dbfeature.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(dbfeature.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(dbfeature.FieldDescription, field.TypeString) + } + if _u.mutation.MeterSlugCleared() { + _spec.ClearField(dbfeature.FieldMeterSlug, field.TypeString) + } + if value, ok := _u.mutation.MeterGroupByFilters(); ok { + _spec.SetField(dbfeature.FieldMeterGroupByFilters, field.TypeJSON, value) + } + if _u.mutation.MeterGroupByFiltersCleared() { + _spec.ClearField(dbfeature.FieldMeterGroupByFilters, field.TypeJSON) + } + if value, ok := _u.mutation.AdvancedMeterGroupByFilters(); ok { + _spec.SetField(dbfeature.FieldAdvancedMeterGroupByFilters, field.TypeJSON, value) + } + if _u.mutation.AdvancedMeterGroupByFiltersCleared() { + _spec.ClearField(dbfeature.FieldAdvancedMeterGroupByFilters, field.TypeJSON) + } + if value, ok := _u.mutation.UnitCostType(); ok { + _spec.SetField(dbfeature.FieldUnitCostType, field.TypeString, value) + } + if _u.mutation.UnitCostTypeCleared() { + _spec.ClearField(dbfeature.FieldUnitCostType, field.TypeString) + } + if value, ok := _u.mutation.UnitCostManualAmount(); ok { + _spec.SetField(dbfeature.FieldUnitCostManualAmount, field.TypeOther, value) + } + if _u.mutation.UnitCostManualAmountCleared() { + _spec.ClearField(dbfeature.FieldUnitCostManualAmount, field.TypeOther) + } + if value, ok := _u.mutation.UnitCostLlmProviderProperty(); ok { + _spec.SetField(dbfeature.FieldUnitCostLlmProviderProperty, field.TypeString, value) + } + if _u.mutation.UnitCostLlmProviderPropertyCleared() { + _spec.ClearField(dbfeature.FieldUnitCostLlmProviderProperty, field.TypeString) + } + if value, ok := _u.mutation.UnitCostLlmProvider(); ok { + _spec.SetField(dbfeature.FieldUnitCostLlmProvider, field.TypeString, value) + } + if _u.mutation.UnitCostLlmProviderCleared() { + _spec.ClearField(dbfeature.FieldUnitCostLlmProvider, field.TypeString) + } + if value, ok := _u.mutation.UnitCostLlmModelProperty(); ok { + _spec.SetField(dbfeature.FieldUnitCostLlmModelProperty, field.TypeString, value) + } + if _u.mutation.UnitCostLlmModelPropertyCleared() { + _spec.ClearField(dbfeature.FieldUnitCostLlmModelProperty, field.TypeString) + } + if value, ok := _u.mutation.UnitCostLlmModel(); ok { + _spec.SetField(dbfeature.FieldUnitCostLlmModel, field.TypeString, value) + } + if _u.mutation.UnitCostLlmModelCleared() { + _spec.ClearField(dbfeature.FieldUnitCostLlmModel, field.TypeString) + } + if value, ok := _u.mutation.UnitCostLlmTokenTypeProperty(); ok { + _spec.SetField(dbfeature.FieldUnitCostLlmTokenTypeProperty, field.TypeString, value) + } + if _u.mutation.UnitCostLlmTokenTypePropertyCleared() { + _spec.ClearField(dbfeature.FieldUnitCostLlmTokenTypeProperty, field.TypeString) + } + if value, ok := _u.mutation.UnitCostLlmTokenType(); ok { + _spec.SetField(dbfeature.FieldUnitCostLlmTokenType, field.TypeString, value) + } + if _u.mutation.UnitCostLlmTokenTypeCleared() { + _spec.ClearField(dbfeature.FieldUnitCostLlmTokenType, field.TypeString) + } + if value, ok := _u.mutation.ArchivedAt(); ok { + _spec.SetField(dbfeature.FieldArchivedAt, field.TypeTime, value) + } + if _u.mutation.ArchivedAtCleared() { + _spec.ClearField(dbfeature.FieldArchivedAt, field.TypeTime) + } + if _u.mutation.EntitlementCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.EntitlementTable, + Columns: []string{dbfeature.EntitlementColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(entitlement.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedEntitlementIDs(); len(nodes) > 0 && !_u.mutation.EntitlementCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.EntitlementTable, + Columns: []string{dbfeature.EntitlementColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(entitlement.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.EntitlementIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.EntitlementTable, + Columns: []string{dbfeature.EntitlementColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(entitlement.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.RatecardCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.RatecardTable, + Columns: []string{dbfeature.RatecardColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(planratecard.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedRatecardIDs(); len(nodes) > 0 && !_u.mutation.RatecardCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.RatecardTable, + Columns: []string{dbfeature.RatecardColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(planratecard.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.RatecardIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.RatecardTable, + Columns: []string{dbfeature.RatecardColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(planratecard.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.AddonRatecardCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.AddonRatecardTable, + Columns: []string{dbfeature.AddonRatecardColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(addonratecard.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedAddonRatecardIDs(); len(nodes) > 0 && !_u.mutation.AddonRatecardCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.AddonRatecardTable, + Columns: []string{dbfeature.AddonRatecardColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(addonratecard.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.AddonRatecardIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.AddonRatecardTable, + Columns: []string{dbfeature.AddonRatecardColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(addonratecard.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.UsageBasedChargesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.UsageBasedChargesTable, + Columns: []string{dbfeature.UsageBasedChargesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebased.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedUsageBasedChargesIDs(); len(nodes) > 0 && !_u.mutation.UsageBasedChargesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.UsageBasedChargesTable, + Columns: []string{dbfeature.UsageBasedChargesColumn}, + 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.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.UsageBasedChargesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.UsageBasedChargesTable, + Columns: []string{dbfeature.UsageBasedChargesColumn}, + 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.UsageBasedRunsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.UsageBasedRunsTable, + Columns: []string{dbfeature.UsageBasedRunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedUsageBasedRunsIDs(); len(nodes) > 0 && !_u.mutation.UsageBasedRunsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.UsageBasedRunsTable, + Columns: []string{dbfeature.UsageBasedRunsColumn}, + 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.UsageBasedRunsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.UsageBasedRunsTable, + Columns: []string{dbfeature.UsageBasedRunsColumn}, + 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 _u.mutation.FlatFeeChargesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.FlatFeeChargesTable, + Columns: []string{dbfeature.FlatFeeChargesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfee.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedFlatFeeChargesIDs(); len(nodes) > 0 && !_u.mutation.FlatFeeChargesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.FlatFeeChargesTable, + Columns: []string{dbfeature.FlatFeeChargesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfee.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.FlatFeeChargesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbfeature.FlatFeeChargesTable, + Columns: []string{dbfeature.FlatFeeChargesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeflatfee.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &Feature{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{dbfeature.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/ent/db/grant.go b/ent/db/grant.go new file mode 100644 index 0000000000000000000000000000000000000000..04b14eabbb74a87e240de2b05118237724eadef6 --- /dev/null +++ b/ent/db/grant.go @@ -0,0 +1,340 @@ +// 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/openmeterio/openmeter/openmeter/credit/grant" + "github.com/openmeterio/openmeter/openmeter/ent/db/entitlement" + dbgrant "github.com/openmeterio/openmeter/openmeter/ent/db/grant" + "github.com/openmeterio/openmeter/pkg/datetime" + "github.com/openmeterio/openmeter/pkg/models" +) + +// Grant is the model entity for the Grant schema. +type Grant 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"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,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"` + // Metadata holds the value of the "metadata" field. + Metadata map[string]string `json:"metadata,omitempty"` + // OwnerID holds the value of the "owner_id" field. + OwnerID string `json:"owner_id,omitempty"` + // Amount holds the value of the "amount" field. + Amount float64 `json:"amount,omitempty"` + // Priority holds the value of the "priority" field. + Priority uint8 `json:"priority,omitempty"` + // EffectiveAt holds the value of the "effective_at" field. + EffectiveAt time.Time `json:"effective_at,omitempty"` + // Expiration holds the value of the "expiration" field. + Expiration *grant.ExpirationPeriod `json:"expiration,omitempty"` + // ExpiresAt holds the value of the "expires_at" field. + ExpiresAt *time.Time `json:"expires_at,omitempty"` + // VoidedAt holds the value of the "voided_at" field. + VoidedAt *time.Time `json:"voided_at,omitempty"` + // ResetMaxRollover holds the value of the "reset_max_rollover" field. + ResetMaxRollover float64 `json:"reset_max_rollover,omitempty"` + // ResetMinRollover holds the value of the "reset_min_rollover" field. + ResetMinRollover float64 `json:"reset_min_rollover,omitempty"` + // RecurrencePeriod holds the value of the "recurrence_period" field. + RecurrencePeriod *datetime.ISODurationString `json:"recurrence_period,omitempty"` + // RecurrenceAnchor holds the value of the "recurrence_anchor" field. + RecurrenceAnchor *time.Time `json:"recurrence_anchor,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the GrantQuery when eager-loading is set. + Edges GrantEdges `json:"edges"` + selectValues sql.SelectValues +} + +// GrantEdges holds the relations/edges for other nodes in the graph. +type GrantEdges struct { + // Entitlement holds the value of the entitlement edge. + Entitlement *Entitlement `json:"entitlement,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// EntitlementOrErr returns the Entitlement value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e GrantEdges) EntitlementOrErr() (*Entitlement, error) { + if e.Entitlement != nil { + return e.Entitlement, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: entitlement.Label} + } + return nil, &NotLoadedError{edge: "entitlement"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Grant) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case dbgrant.FieldAnnotations, dbgrant.FieldMetadata, dbgrant.FieldExpiration: + values[i] = new([]byte) + case dbgrant.FieldAmount, dbgrant.FieldResetMaxRollover, dbgrant.FieldResetMinRollover: + values[i] = new(sql.NullFloat64) + case dbgrant.FieldPriority: + values[i] = new(sql.NullInt64) + case dbgrant.FieldID, dbgrant.FieldNamespace, dbgrant.FieldOwnerID, dbgrant.FieldRecurrencePeriod: + values[i] = new(sql.NullString) + case dbgrant.FieldCreatedAt, dbgrant.FieldUpdatedAt, dbgrant.FieldDeletedAt, dbgrant.FieldEffectiveAt, dbgrant.FieldExpiresAt, dbgrant.FieldVoidedAt, dbgrant.FieldRecurrenceAnchor: + 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 Grant fields. +func (_m *Grant) 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 dbgrant.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 dbgrant.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 dbgrant.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 dbgrant.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 dbgrant.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 dbgrant.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 dbgrant.FieldMetadata: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field metadata", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Metadata); err != nil { + return fmt.Errorf("unmarshal field metadata: %w", err) + } + } + case dbgrant.FieldOwnerID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field owner_id", values[i]) + } else if value.Valid { + _m.OwnerID = value.String + } + case dbgrant.FieldAmount: + if value, ok := values[i].(*sql.NullFloat64); !ok { + return fmt.Errorf("unexpected type %T for field amount", values[i]) + } else if value.Valid { + _m.Amount = value.Float64 + } + case dbgrant.FieldPriority: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field priority", values[i]) + } else if value.Valid { + _m.Priority = uint8(value.Int64) + } + case dbgrant.FieldEffectiveAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field effective_at", values[i]) + } else if value.Valid { + _m.EffectiveAt = value.Time + } + case dbgrant.FieldExpiration: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field expiration", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Expiration); err != nil { + return fmt.Errorf("unmarshal field expiration: %w", err) + } + } + case dbgrant.FieldExpiresAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field expires_at", values[i]) + } else if value.Valid { + _m.ExpiresAt = new(time.Time) + *_m.ExpiresAt = value.Time + } + case dbgrant.FieldVoidedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field voided_at", values[i]) + } else if value.Valid { + _m.VoidedAt = new(time.Time) + *_m.VoidedAt = value.Time + } + case dbgrant.FieldResetMaxRollover: + if value, ok := values[i].(*sql.NullFloat64); !ok { + return fmt.Errorf("unexpected type %T for field reset_max_rollover", values[i]) + } else if value.Valid { + _m.ResetMaxRollover = value.Float64 + } + case dbgrant.FieldResetMinRollover: + if value, ok := values[i].(*sql.NullFloat64); !ok { + return fmt.Errorf("unexpected type %T for field reset_min_rollover", values[i]) + } else if value.Valid { + _m.ResetMinRollover = value.Float64 + } + case dbgrant.FieldRecurrencePeriod: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field recurrence_period", values[i]) + } else if value.Valid { + _m.RecurrencePeriod = new(datetime.ISODurationString) + *_m.RecurrencePeriod = datetime.ISODurationString(value.String) + } + case dbgrant.FieldRecurrenceAnchor: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field recurrence_anchor", values[i]) + } else if value.Valid { + _m.RecurrenceAnchor = new(time.Time) + *_m.RecurrenceAnchor = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Grant. +// This includes values selected through modifiers, order, etc. +func (_m *Grant) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryEntitlement queries the "entitlement" edge of the Grant entity. +func (_m *Grant) QueryEntitlement() *EntitlementQuery { + return NewGrantClient(_m.config).QueryEntitlement(_m) +} + +// Update returns a builder for updating this Grant. +// Note that you need to call Grant.Unwrap() before calling this method if this Grant +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Grant) Update() *GrantUpdateOne { + return NewGrantClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Grant 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 *Grant) Unwrap() *Grant { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: Grant is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Grant) String() string { + var builder strings.Builder + builder.WriteString("Grant(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + 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("metadata=") + builder.WriteString(fmt.Sprintf("%v", _m.Metadata)) + builder.WriteString(", ") + builder.WriteString("owner_id=") + builder.WriteString(_m.OwnerID) + builder.WriteString(", ") + builder.WriteString("amount=") + builder.WriteString(fmt.Sprintf("%v", _m.Amount)) + builder.WriteString(", ") + builder.WriteString("priority=") + builder.WriteString(fmt.Sprintf("%v", _m.Priority)) + builder.WriteString(", ") + builder.WriteString("effective_at=") + builder.WriteString(_m.EffectiveAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("expiration=") + builder.WriteString(fmt.Sprintf("%v", _m.Expiration)) + builder.WriteString(", ") + if v := _m.ExpiresAt; v != nil { + builder.WriteString("expires_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + if v := _m.VoidedAt; v != nil { + builder.WriteString("voided_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + builder.WriteString("reset_max_rollover=") + builder.WriteString(fmt.Sprintf("%v", _m.ResetMaxRollover)) + builder.WriteString(", ") + builder.WriteString("reset_min_rollover=") + builder.WriteString(fmt.Sprintf("%v", _m.ResetMinRollover)) + builder.WriteString(", ") + if v := _m.RecurrencePeriod; v != nil { + builder.WriteString("recurrence_period=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.RecurrenceAnchor; v != nil { + builder.WriteString("recurrence_anchor=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteByte(')') + return builder.String() +} + +// Grants is a parsable slice of Grant. +type Grants []*Grant diff --git a/ent/db/grant/grant.go b/ent/db/grant/grant.go new file mode 100644 index 0000000000000000000000000000000000000000..7656580ff81d673016023d9395042fc8ab6fb07f --- /dev/null +++ b/ent/db/grant/grant.go @@ -0,0 +1,201 @@ +// Code generated by ent, DO NOT EDIT. + +package dbgrant + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the grant type in the database. + Label = "grant" + // 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" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // 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" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // FieldOwnerID holds the string denoting the owner_id field in the database. + FieldOwnerID = "owner_id" + // FieldAmount holds the string denoting the amount field in the database. + FieldAmount = "amount" + // FieldPriority holds the string denoting the priority field in the database. + FieldPriority = "priority" + // FieldEffectiveAt holds the string denoting the effective_at field in the database. + FieldEffectiveAt = "effective_at" + // FieldExpiration holds the string denoting the expiration field in the database. + FieldExpiration = "expiration" + // FieldExpiresAt holds the string denoting the expires_at field in the database. + FieldExpiresAt = "expires_at" + // FieldVoidedAt holds the string denoting the voided_at field in the database. + FieldVoidedAt = "voided_at" + // FieldResetMaxRollover holds the string denoting the reset_max_rollover field in the database. + FieldResetMaxRollover = "reset_max_rollover" + // FieldResetMinRollover holds the string denoting the reset_min_rollover field in the database. + FieldResetMinRollover = "reset_min_rollover" + // FieldRecurrencePeriod holds the string denoting the recurrence_period field in the database. + FieldRecurrencePeriod = "recurrence_period" + // FieldRecurrenceAnchor holds the string denoting the recurrence_anchor field in the database. + FieldRecurrenceAnchor = "recurrence_anchor" + // EdgeEntitlement holds the string denoting the entitlement edge name in mutations. + EdgeEntitlement = "entitlement" + // Table holds the table name of the grant in the database. + Table = "grants" + // EntitlementTable is the table that holds the entitlement relation/edge. + EntitlementTable = "grants" + // EntitlementInverseTable is the table name for the Entitlement entity. + // It exists in this package in order to avoid circular dependency with the "entitlement" package. + EntitlementInverseTable = "entitlements" + // EntitlementColumn is the table column denoting the entitlement relation/edge. + EntitlementColumn = "owner_id" +) + +// Columns holds all SQL columns for grant fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldAnnotations, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldMetadata, + FieldOwnerID, + FieldAmount, + FieldPriority, + FieldEffectiveAt, + FieldExpiration, + FieldExpiresAt, + FieldVoidedAt, + FieldResetMaxRollover, + FieldResetMinRollover, + FieldRecurrencePeriod, + FieldRecurrenceAnchor, +} + +// 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 + // DefaultPriority holds the default value on creation for the "priority" field. + DefaultPriority uint8 + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// OrderOption defines the ordering options for the Grant 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() +} + +// ByOwnerID orders the results by the owner_id field. +func ByOwnerID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldOwnerID, opts...).ToFunc() +} + +// ByAmount orders the results by the amount field. +func ByAmount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAmount, opts...).ToFunc() +} + +// ByPriority orders the results by the priority field. +func ByPriority(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPriority, opts...).ToFunc() +} + +// ByEffectiveAt orders the results by the effective_at field. +func ByEffectiveAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEffectiveAt, opts...).ToFunc() +} + +// ByExpiresAt orders the results by the expires_at field. +func ByExpiresAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldExpiresAt, opts...).ToFunc() +} + +// ByVoidedAt orders the results by the voided_at field. +func ByVoidedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVoidedAt, opts...).ToFunc() +} + +// ByResetMaxRollover orders the results by the reset_max_rollover field. +func ByResetMaxRollover(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldResetMaxRollover, opts...).ToFunc() +} + +// ByResetMinRollover orders the results by the reset_min_rollover field. +func ByResetMinRollover(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldResetMinRollover, opts...).ToFunc() +} + +// ByRecurrencePeriod orders the results by the recurrence_period field. +func ByRecurrencePeriod(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRecurrencePeriod, opts...).ToFunc() +} + +// ByRecurrenceAnchor orders the results by the recurrence_anchor field. +func ByRecurrenceAnchor(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRecurrenceAnchor, opts...).ToFunc() +} + +// ByEntitlementField orders the results by entitlement field. +func ByEntitlementField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newEntitlementStep(), sql.OrderByField(field, opts...)) + } +} +func newEntitlementStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(EntitlementInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, EntitlementTable, EntitlementColumn), + ) +} diff --git a/ent/db/grant/where.go b/ent/db/grant/where.go new file mode 100644 index 0000000000000000000000000000000000000000..63285365f0ee0ee10e096ab6662609798d2b1b2a --- /dev/null +++ b/ent/db/grant/where.go @@ -0,0 +1,910 @@ +// Code generated by ent, DO NOT EDIT. + +package dbgrant + +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/pkg/datetime" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.Grant { + return predicate.Grant(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.Grant { + return predicate.Grant(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.Grant { + return predicate.Grant(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.Grant { + return predicate.Grant(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.Grant { + return predicate.Grant(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.Grant { + return predicate.Grant(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.Grant { + return predicate.Grant(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.Grant { + return predicate.Grant(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.Grant { + return predicate.Grant(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.Grant { + return predicate.Grant(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.Grant { + return predicate.Grant(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.Grant { + return predicate.Grant(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.Grant { + return predicate.Grant(sql.FieldEQ(FieldDeletedAt, v)) +} + +// OwnerID applies equality check predicate on the "owner_id" field. It's identical to OwnerIDEQ. +func OwnerID(v string) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldOwnerID, v)) +} + +// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ. +func Amount(v float64) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldAmount, v)) +} + +// Priority applies equality check predicate on the "priority" field. It's identical to PriorityEQ. +func Priority(v uint8) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldPriority, v)) +} + +// EffectiveAt applies equality check predicate on the "effective_at" field. It's identical to EffectiveAtEQ. +func EffectiveAt(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldEffectiveAt, v)) +} + +// ExpiresAt applies equality check predicate on the "expires_at" field. It's identical to ExpiresAtEQ. +func ExpiresAt(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldExpiresAt, v)) +} + +// VoidedAt applies equality check predicate on the "voided_at" field. It's identical to VoidedAtEQ. +func VoidedAt(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldVoidedAt, v)) +} + +// ResetMaxRollover applies equality check predicate on the "reset_max_rollover" field. It's identical to ResetMaxRolloverEQ. +func ResetMaxRollover(v float64) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldResetMaxRollover, v)) +} + +// ResetMinRollover applies equality check predicate on the "reset_min_rollover" field. It's identical to ResetMinRolloverEQ. +func ResetMinRollover(v float64) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldResetMinRollover, v)) +} + +// RecurrencePeriod applies equality check predicate on the "recurrence_period" field. It's identical to RecurrencePeriodEQ. +func RecurrencePeriod(v datetime.ISODurationString) predicate.Grant { + vc := string(v) + return predicate.Grant(sql.FieldEQ(FieldRecurrencePeriod, vc)) +} + +// RecurrenceAnchor applies equality check predicate on the "recurrence_anchor" field. It's identical to RecurrenceAnchorEQ. +func RecurrenceAnchor(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldRecurrenceAnchor, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.Grant { + return predicate.Grant(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.Grant { + return predicate.Grant(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.Grant { + return predicate.Grant(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.Grant { + return predicate.Grant(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.Grant { + return predicate.Grant(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.Grant { + return predicate.Grant(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.Grant { + return predicate.Grant(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.Grant { + return predicate.Grant(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.Grant { + return predicate.Grant(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.Grant { + return predicate.Grant(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.Grant { + return predicate.Grant(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.Grant { + return predicate.Grant(sql.FieldContainsFold(FieldNamespace, v)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.Grant { + return predicate.Grant(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.Grant { + return predicate.Grant(sql.FieldNotNull(FieldAnnotations)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Grant { + return predicate.Grant(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Grant { + return predicate.Grant(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.Grant { + return predicate.Grant(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.Grant { + return predicate.Grant(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.Grant { + return predicate.Grant(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.Grant { + return predicate.Grant(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.Grant { + return predicate.Grant(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.Grant { + return predicate.Grant(sql.FieldNotNull(FieldDeletedAt)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.Grant { + return predicate.Grant(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.Grant { + return predicate.Grant(sql.FieldNotNull(FieldMetadata)) +} + +// OwnerIDEQ applies the EQ predicate on the "owner_id" field. +func OwnerIDEQ(v string) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldOwnerID, v)) +} + +// OwnerIDNEQ applies the NEQ predicate on the "owner_id" field. +func OwnerIDNEQ(v string) predicate.Grant { + return predicate.Grant(sql.FieldNEQ(FieldOwnerID, v)) +} + +// OwnerIDIn applies the In predicate on the "owner_id" field. +func OwnerIDIn(vs ...string) predicate.Grant { + return predicate.Grant(sql.FieldIn(FieldOwnerID, vs...)) +} + +// OwnerIDNotIn applies the NotIn predicate on the "owner_id" field. +func OwnerIDNotIn(vs ...string) predicate.Grant { + return predicate.Grant(sql.FieldNotIn(FieldOwnerID, vs...)) +} + +// OwnerIDGT applies the GT predicate on the "owner_id" field. +func OwnerIDGT(v string) predicate.Grant { + return predicate.Grant(sql.FieldGT(FieldOwnerID, v)) +} + +// OwnerIDGTE applies the GTE predicate on the "owner_id" field. +func OwnerIDGTE(v string) predicate.Grant { + return predicate.Grant(sql.FieldGTE(FieldOwnerID, v)) +} + +// OwnerIDLT applies the LT predicate on the "owner_id" field. +func OwnerIDLT(v string) predicate.Grant { + return predicate.Grant(sql.FieldLT(FieldOwnerID, v)) +} + +// OwnerIDLTE applies the LTE predicate on the "owner_id" field. +func OwnerIDLTE(v string) predicate.Grant { + return predicate.Grant(sql.FieldLTE(FieldOwnerID, v)) +} + +// OwnerIDContains applies the Contains predicate on the "owner_id" field. +func OwnerIDContains(v string) predicate.Grant { + return predicate.Grant(sql.FieldContains(FieldOwnerID, v)) +} + +// OwnerIDHasPrefix applies the HasPrefix predicate on the "owner_id" field. +func OwnerIDHasPrefix(v string) predicate.Grant { + return predicate.Grant(sql.FieldHasPrefix(FieldOwnerID, v)) +} + +// OwnerIDHasSuffix applies the HasSuffix predicate on the "owner_id" field. +func OwnerIDHasSuffix(v string) predicate.Grant { + return predicate.Grant(sql.FieldHasSuffix(FieldOwnerID, v)) +} + +// OwnerIDEqualFold applies the EqualFold predicate on the "owner_id" field. +func OwnerIDEqualFold(v string) predicate.Grant { + return predicate.Grant(sql.FieldEqualFold(FieldOwnerID, v)) +} + +// OwnerIDContainsFold applies the ContainsFold predicate on the "owner_id" field. +func OwnerIDContainsFold(v string) predicate.Grant { + return predicate.Grant(sql.FieldContainsFold(FieldOwnerID, v)) +} + +// AmountEQ applies the EQ predicate on the "amount" field. +func AmountEQ(v float64) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldAmount, v)) +} + +// AmountNEQ applies the NEQ predicate on the "amount" field. +func AmountNEQ(v float64) predicate.Grant { + return predicate.Grant(sql.FieldNEQ(FieldAmount, v)) +} + +// AmountIn applies the In predicate on the "amount" field. +func AmountIn(vs ...float64) predicate.Grant { + return predicate.Grant(sql.FieldIn(FieldAmount, vs...)) +} + +// AmountNotIn applies the NotIn predicate on the "amount" field. +func AmountNotIn(vs ...float64) predicate.Grant { + return predicate.Grant(sql.FieldNotIn(FieldAmount, vs...)) +} + +// AmountGT applies the GT predicate on the "amount" field. +func AmountGT(v float64) predicate.Grant { + return predicate.Grant(sql.FieldGT(FieldAmount, v)) +} + +// AmountGTE applies the GTE predicate on the "amount" field. +func AmountGTE(v float64) predicate.Grant { + return predicate.Grant(sql.FieldGTE(FieldAmount, v)) +} + +// AmountLT applies the LT predicate on the "amount" field. +func AmountLT(v float64) predicate.Grant { + return predicate.Grant(sql.FieldLT(FieldAmount, v)) +} + +// AmountLTE applies the LTE predicate on the "amount" field. +func AmountLTE(v float64) predicate.Grant { + return predicate.Grant(sql.FieldLTE(FieldAmount, v)) +} + +// PriorityEQ applies the EQ predicate on the "priority" field. +func PriorityEQ(v uint8) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldPriority, v)) +} + +// PriorityNEQ applies the NEQ predicate on the "priority" field. +func PriorityNEQ(v uint8) predicate.Grant { + return predicate.Grant(sql.FieldNEQ(FieldPriority, v)) +} + +// PriorityIn applies the In predicate on the "priority" field. +func PriorityIn(vs ...uint8) predicate.Grant { + return predicate.Grant(sql.FieldIn(FieldPriority, vs...)) +} + +// PriorityNotIn applies the NotIn predicate on the "priority" field. +func PriorityNotIn(vs ...uint8) predicate.Grant { + return predicate.Grant(sql.FieldNotIn(FieldPriority, vs...)) +} + +// PriorityGT applies the GT predicate on the "priority" field. +func PriorityGT(v uint8) predicate.Grant { + return predicate.Grant(sql.FieldGT(FieldPriority, v)) +} + +// PriorityGTE applies the GTE predicate on the "priority" field. +func PriorityGTE(v uint8) predicate.Grant { + return predicate.Grant(sql.FieldGTE(FieldPriority, v)) +} + +// PriorityLT applies the LT predicate on the "priority" field. +func PriorityLT(v uint8) predicate.Grant { + return predicate.Grant(sql.FieldLT(FieldPriority, v)) +} + +// PriorityLTE applies the LTE predicate on the "priority" field. +func PriorityLTE(v uint8) predicate.Grant { + return predicate.Grant(sql.FieldLTE(FieldPriority, v)) +} + +// EffectiveAtEQ applies the EQ predicate on the "effective_at" field. +func EffectiveAtEQ(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldEffectiveAt, v)) +} + +// EffectiveAtNEQ applies the NEQ predicate on the "effective_at" field. +func EffectiveAtNEQ(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldNEQ(FieldEffectiveAt, v)) +} + +// EffectiveAtIn applies the In predicate on the "effective_at" field. +func EffectiveAtIn(vs ...time.Time) predicate.Grant { + return predicate.Grant(sql.FieldIn(FieldEffectiveAt, vs...)) +} + +// EffectiveAtNotIn applies the NotIn predicate on the "effective_at" field. +func EffectiveAtNotIn(vs ...time.Time) predicate.Grant { + return predicate.Grant(sql.FieldNotIn(FieldEffectiveAt, vs...)) +} + +// EffectiveAtGT applies the GT predicate on the "effective_at" field. +func EffectiveAtGT(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldGT(FieldEffectiveAt, v)) +} + +// EffectiveAtGTE applies the GTE predicate on the "effective_at" field. +func EffectiveAtGTE(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldGTE(FieldEffectiveAt, v)) +} + +// EffectiveAtLT applies the LT predicate on the "effective_at" field. +func EffectiveAtLT(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldLT(FieldEffectiveAt, v)) +} + +// EffectiveAtLTE applies the LTE predicate on the "effective_at" field. +func EffectiveAtLTE(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldLTE(FieldEffectiveAt, v)) +} + +// ExpirationIsNil applies the IsNil predicate on the "expiration" field. +func ExpirationIsNil() predicate.Grant { + return predicate.Grant(sql.FieldIsNull(FieldExpiration)) +} + +// ExpirationNotNil applies the NotNil predicate on the "expiration" field. +func ExpirationNotNil() predicate.Grant { + return predicate.Grant(sql.FieldNotNull(FieldExpiration)) +} + +// ExpiresAtEQ applies the EQ predicate on the "expires_at" field. +func ExpiresAtEQ(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldExpiresAt, v)) +} + +// ExpiresAtNEQ applies the NEQ predicate on the "expires_at" field. +func ExpiresAtNEQ(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldNEQ(FieldExpiresAt, v)) +} + +// ExpiresAtIn applies the In predicate on the "expires_at" field. +func ExpiresAtIn(vs ...time.Time) predicate.Grant { + return predicate.Grant(sql.FieldIn(FieldExpiresAt, vs...)) +} + +// ExpiresAtNotIn applies the NotIn predicate on the "expires_at" field. +func ExpiresAtNotIn(vs ...time.Time) predicate.Grant { + return predicate.Grant(sql.FieldNotIn(FieldExpiresAt, vs...)) +} + +// ExpiresAtGT applies the GT predicate on the "expires_at" field. +func ExpiresAtGT(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldGT(FieldExpiresAt, v)) +} + +// ExpiresAtGTE applies the GTE predicate on the "expires_at" field. +func ExpiresAtGTE(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldGTE(FieldExpiresAt, v)) +} + +// ExpiresAtLT applies the LT predicate on the "expires_at" field. +func ExpiresAtLT(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldLT(FieldExpiresAt, v)) +} + +// ExpiresAtLTE applies the LTE predicate on the "expires_at" field. +func ExpiresAtLTE(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldLTE(FieldExpiresAt, v)) +} + +// ExpiresAtIsNil applies the IsNil predicate on the "expires_at" field. +func ExpiresAtIsNil() predicate.Grant { + return predicate.Grant(sql.FieldIsNull(FieldExpiresAt)) +} + +// ExpiresAtNotNil applies the NotNil predicate on the "expires_at" field. +func ExpiresAtNotNil() predicate.Grant { + return predicate.Grant(sql.FieldNotNull(FieldExpiresAt)) +} + +// VoidedAtEQ applies the EQ predicate on the "voided_at" field. +func VoidedAtEQ(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldVoidedAt, v)) +} + +// VoidedAtNEQ applies the NEQ predicate on the "voided_at" field. +func VoidedAtNEQ(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldNEQ(FieldVoidedAt, v)) +} + +// VoidedAtIn applies the In predicate on the "voided_at" field. +func VoidedAtIn(vs ...time.Time) predicate.Grant { + return predicate.Grant(sql.FieldIn(FieldVoidedAt, vs...)) +} + +// VoidedAtNotIn applies the NotIn predicate on the "voided_at" field. +func VoidedAtNotIn(vs ...time.Time) predicate.Grant { + return predicate.Grant(sql.FieldNotIn(FieldVoidedAt, vs...)) +} + +// VoidedAtGT applies the GT predicate on the "voided_at" field. +func VoidedAtGT(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldGT(FieldVoidedAt, v)) +} + +// VoidedAtGTE applies the GTE predicate on the "voided_at" field. +func VoidedAtGTE(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldGTE(FieldVoidedAt, v)) +} + +// VoidedAtLT applies the LT predicate on the "voided_at" field. +func VoidedAtLT(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldLT(FieldVoidedAt, v)) +} + +// VoidedAtLTE applies the LTE predicate on the "voided_at" field. +func VoidedAtLTE(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldLTE(FieldVoidedAt, v)) +} + +// VoidedAtIsNil applies the IsNil predicate on the "voided_at" field. +func VoidedAtIsNil() predicate.Grant { + return predicate.Grant(sql.FieldIsNull(FieldVoidedAt)) +} + +// VoidedAtNotNil applies the NotNil predicate on the "voided_at" field. +func VoidedAtNotNil() predicate.Grant { + return predicate.Grant(sql.FieldNotNull(FieldVoidedAt)) +} + +// ResetMaxRolloverEQ applies the EQ predicate on the "reset_max_rollover" field. +func ResetMaxRolloverEQ(v float64) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldResetMaxRollover, v)) +} + +// ResetMaxRolloverNEQ applies the NEQ predicate on the "reset_max_rollover" field. +func ResetMaxRolloverNEQ(v float64) predicate.Grant { + return predicate.Grant(sql.FieldNEQ(FieldResetMaxRollover, v)) +} + +// ResetMaxRolloverIn applies the In predicate on the "reset_max_rollover" field. +func ResetMaxRolloverIn(vs ...float64) predicate.Grant { + return predicate.Grant(sql.FieldIn(FieldResetMaxRollover, vs...)) +} + +// ResetMaxRolloverNotIn applies the NotIn predicate on the "reset_max_rollover" field. +func ResetMaxRolloverNotIn(vs ...float64) predicate.Grant { + return predicate.Grant(sql.FieldNotIn(FieldResetMaxRollover, vs...)) +} + +// ResetMaxRolloverGT applies the GT predicate on the "reset_max_rollover" field. +func ResetMaxRolloverGT(v float64) predicate.Grant { + return predicate.Grant(sql.FieldGT(FieldResetMaxRollover, v)) +} + +// ResetMaxRolloverGTE applies the GTE predicate on the "reset_max_rollover" field. +func ResetMaxRolloverGTE(v float64) predicate.Grant { + return predicate.Grant(sql.FieldGTE(FieldResetMaxRollover, v)) +} + +// ResetMaxRolloverLT applies the LT predicate on the "reset_max_rollover" field. +func ResetMaxRolloverLT(v float64) predicate.Grant { + return predicate.Grant(sql.FieldLT(FieldResetMaxRollover, v)) +} + +// ResetMaxRolloverLTE applies the LTE predicate on the "reset_max_rollover" field. +func ResetMaxRolloverLTE(v float64) predicate.Grant { + return predicate.Grant(sql.FieldLTE(FieldResetMaxRollover, v)) +} + +// ResetMinRolloverEQ applies the EQ predicate on the "reset_min_rollover" field. +func ResetMinRolloverEQ(v float64) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldResetMinRollover, v)) +} + +// ResetMinRolloverNEQ applies the NEQ predicate on the "reset_min_rollover" field. +func ResetMinRolloverNEQ(v float64) predicate.Grant { + return predicate.Grant(sql.FieldNEQ(FieldResetMinRollover, v)) +} + +// ResetMinRolloverIn applies the In predicate on the "reset_min_rollover" field. +func ResetMinRolloverIn(vs ...float64) predicate.Grant { + return predicate.Grant(sql.FieldIn(FieldResetMinRollover, vs...)) +} + +// ResetMinRolloverNotIn applies the NotIn predicate on the "reset_min_rollover" field. +func ResetMinRolloverNotIn(vs ...float64) predicate.Grant { + return predicate.Grant(sql.FieldNotIn(FieldResetMinRollover, vs...)) +} + +// ResetMinRolloverGT applies the GT predicate on the "reset_min_rollover" field. +func ResetMinRolloverGT(v float64) predicate.Grant { + return predicate.Grant(sql.FieldGT(FieldResetMinRollover, v)) +} + +// ResetMinRolloverGTE applies the GTE predicate on the "reset_min_rollover" field. +func ResetMinRolloverGTE(v float64) predicate.Grant { + return predicate.Grant(sql.FieldGTE(FieldResetMinRollover, v)) +} + +// ResetMinRolloverLT applies the LT predicate on the "reset_min_rollover" field. +func ResetMinRolloverLT(v float64) predicate.Grant { + return predicate.Grant(sql.FieldLT(FieldResetMinRollover, v)) +} + +// ResetMinRolloverLTE applies the LTE predicate on the "reset_min_rollover" field. +func ResetMinRolloverLTE(v float64) predicate.Grant { + return predicate.Grant(sql.FieldLTE(FieldResetMinRollover, v)) +} + +// RecurrencePeriodEQ applies the EQ predicate on the "recurrence_period" field. +func RecurrencePeriodEQ(v datetime.ISODurationString) predicate.Grant { + vc := string(v) + return predicate.Grant(sql.FieldEQ(FieldRecurrencePeriod, vc)) +} + +// RecurrencePeriodNEQ applies the NEQ predicate on the "recurrence_period" field. +func RecurrencePeriodNEQ(v datetime.ISODurationString) predicate.Grant { + vc := string(v) + return predicate.Grant(sql.FieldNEQ(FieldRecurrencePeriod, vc)) +} + +// RecurrencePeriodIn applies the In predicate on the "recurrence_period" field. +func RecurrencePeriodIn(vs ...datetime.ISODurationString) predicate.Grant { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.Grant(sql.FieldIn(FieldRecurrencePeriod, v...)) +} + +// RecurrencePeriodNotIn applies the NotIn predicate on the "recurrence_period" field. +func RecurrencePeriodNotIn(vs ...datetime.ISODurationString) predicate.Grant { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.Grant(sql.FieldNotIn(FieldRecurrencePeriod, v...)) +} + +// RecurrencePeriodGT applies the GT predicate on the "recurrence_period" field. +func RecurrencePeriodGT(v datetime.ISODurationString) predicate.Grant { + vc := string(v) + return predicate.Grant(sql.FieldGT(FieldRecurrencePeriod, vc)) +} + +// RecurrencePeriodGTE applies the GTE predicate on the "recurrence_period" field. +func RecurrencePeriodGTE(v datetime.ISODurationString) predicate.Grant { + vc := string(v) + return predicate.Grant(sql.FieldGTE(FieldRecurrencePeriod, vc)) +} + +// RecurrencePeriodLT applies the LT predicate on the "recurrence_period" field. +func RecurrencePeriodLT(v datetime.ISODurationString) predicate.Grant { + vc := string(v) + return predicate.Grant(sql.FieldLT(FieldRecurrencePeriod, vc)) +} + +// RecurrencePeriodLTE applies the LTE predicate on the "recurrence_period" field. +func RecurrencePeriodLTE(v datetime.ISODurationString) predicate.Grant { + vc := string(v) + return predicate.Grant(sql.FieldLTE(FieldRecurrencePeriod, vc)) +} + +// RecurrencePeriodContains applies the Contains predicate on the "recurrence_period" field. +func RecurrencePeriodContains(v datetime.ISODurationString) predicate.Grant { + vc := string(v) + return predicate.Grant(sql.FieldContains(FieldRecurrencePeriod, vc)) +} + +// RecurrencePeriodHasPrefix applies the HasPrefix predicate on the "recurrence_period" field. +func RecurrencePeriodHasPrefix(v datetime.ISODurationString) predicate.Grant { + vc := string(v) + return predicate.Grant(sql.FieldHasPrefix(FieldRecurrencePeriod, vc)) +} + +// RecurrencePeriodHasSuffix applies the HasSuffix predicate on the "recurrence_period" field. +func RecurrencePeriodHasSuffix(v datetime.ISODurationString) predicate.Grant { + vc := string(v) + return predicate.Grant(sql.FieldHasSuffix(FieldRecurrencePeriod, vc)) +} + +// RecurrencePeriodIsNil applies the IsNil predicate on the "recurrence_period" field. +func RecurrencePeriodIsNil() predicate.Grant { + return predicate.Grant(sql.FieldIsNull(FieldRecurrencePeriod)) +} + +// RecurrencePeriodNotNil applies the NotNil predicate on the "recurrence_period" field. +func RecurrencePeriodNotNil() predicate.Grant { + return predicate.Grant(sql.FieldNotNull(FieldRecurrencePeriod)) +} + +// RecurrencePeriodEqualFold applies the EqualFold predicate on the "recurrence_period" field. +func RecurrencePeriodEqualFold(v datetime.ISODurationString) predicate.Grant { + vc := string(v) + return predicate.Grant(sql.FieldEqualFold(FieldRecurrencePeriod, vc)) +} + +// RecurrencePeriodContainsFold applies the ContainsFold predicate on the "recurrence_period" field. +func RecurrencePeriodContainsFold(v datetime.ISODurationString) predicate.Grant { + vc := string(v) + return predicate.Grant(sql.FieldContainsFold(FieldRecurrencePeriod, vc)) +} + +// RecurrenceAnchorEQ applies the EQ predicate on the "recurrence_anchor" field. +func RecurrenceAnchorEQ(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldEQ(FieldRecurrenceAnchor, v)) +} + +// RecurrenceAnchorNEQ applies the NEQ predicate on the "recurrence_anchor" field. +func RecurrenceAnchorNEQ(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldNEQ(FieldRecurrenceAnchor, v)) +} + +// RecurrenceAnchorIn applies the In predicate on the "recurrence_anchor" field. +func RecurrenceAnchorIn(vs ...time.Time) predicate.Grant { + return predicate.Grant(sql.FieldIn(FieldRecurrenceAnchor, vs...)) +} + +// RecurrenceAnchorNotIn applies the NotIn predicate on the "recurrence_anchor" field. +func RecurrenceAnchorNotIn(vs ...time.Time) predicate.Grant { + return predicate.Grant(sql.FieldNotIn(FieldRecurrenceAnchor, vs...)) +} + +// RecurrenceAnchorGT applies the GT predicate on the "recurrence_anchor" field. +func RecurrenceAnchorGT(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldGT(FieldRecurrenceAnchor, v)) +} + +// RecurrenceAnchorGTE applies the GTE predicate on the "recurrence_anchor" field. +func RecurrenceAnchorGTE(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldGTE(FieldRecurrenceAnchor, v)) +} + +// RecurrenceAnchorLT applies the LT predicate on the "recurrence_anchor" field. +func RecurrenceAnchorLT(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldLT(FieldRecurrenceAnchor, v)) +} + +// RecurrenceAnchorLTE applies the LTE predicate on the "recurrence_anchor" field. +func RecurrenceAnchorLTE(v time.Time) predicate.Grant { + return predicate.Grant(sql.FieldLTE(FieldRecurrenceAnchor, v)) +} + +// RecurrenceAnchorIsNil applies the IsNil predicate on the "recurrence_anchor" field. +func RecurrenceAnchorIsNil() predicate.Grant { + return predicate.Grant(sql.FieldIsNull(FieldRecurrenceAnchor)) +} + +// RecurrenceAnchorNotNil applies the NotNil predicate on the "recurrence_anchor" field. +func RecurrenceAnchorNotNil() predicate.Grant { + return predicate.Grant(sql.FieldNotNull(FieldRecurrenceAnchor)) +} + +// HasEntitlement applies the HasEdge predicate on the "entitlement" edge. +func HasEntitlement() predicate.Grant { + return predicate.Grant(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, EntitlementTable, EntitlementColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasEntitlementWith applies the HasEdge predicate on the "entitlement" edge with a given conditions (other predicates). +func HasEntitlementWith(preds ...predicate.Entitlement) predicate.Grant { + return predicate.Grant(func(s *sql.Selector) { + step := newEntitlementStep() + 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.Grant) predicate.Grant { + return predicate.Grant(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Grant) predicate.Grant { + return predicate.Grant(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Grant) predicate.Grant { + return predicate.Grant(sql.NotPredicates(p)) +} diff --git a/ent/db/grant_create.go b/ent/db/grant_create.go new file mode 100644 index 0000000000000000000000000000000000000000..35cbf9689cdfc8468e5f0291d99d0c89eeaacc35 --- /dev/null +++ b/ent/db/grant_create.go @@ -0,0 +1,1116 @@ +// 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/credit/grant" + "github.com/openmeterio/openmeter/openmeter/ent/db/entitlement" + dbgrant "github.com/openmeterio/openmeter/openmeter/ent/db/grant" + "github.com/openmeterio/openmeter/pkg/datetime" + "github.com/openmeterio/openmeter/pkg/models" +) + +// GrantCreate is the builder for creating a Grant entity. +type GrantCreate struct { + config + mutation *GrantMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *GrantCreate) SetNamespace(v string) *GrantCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *GrantCreate) SetAnnotations(v models.Annotations) *GrantCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *GrantCreate) SetCreatedAt(v time.Time) *GrantCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *GrantCreate) SetNillableCreatedAt(v *time.Time) *GrantCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *GrantCreate) SetUpdatedAt(v time.Time) *GrantCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *GrantCreate) SetNillableUpdatedAt(v *time.Time) *GrantCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *GrantCreate) SetDeletedAt(v time.Time) *GrantCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *GrantCreate) SetNillableDeletedAt(v *time.Time) *GrantCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetMetadata sets the "metadata" field. +func (_c *GrantCreate) SetMetadata(v map[string]string) *GrantCreate { + _c.mutation.SetMetadata(v) + return _c +} + +// SetOwnerID sets the "owner_id" field. +func (_c *GrantCreate) SetOwnerID(v string) *GrantCreate { + _c.mutation.SetOwnerID(v) + return _c +} + +// SetAmount sets the "amount" field. +func (_c *GrantCreate) SetAmount(v float64) *GrantCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetPriority sets the "priority" field. +func (_c *GrantCreate) SetPriority(v uint8) *GrantCreate { + _c.mutation.SetPriority(v) + return _c +} + +// SetNillablePriority sets the "priority" field if the given value is not nil. +func (_c *GrantCreate) SetNillablePriority(v *uint8) *GrantCreate { + if v != nil { + _c.SetPriority(*v) + } + return _c +} + +// SetEffectiveAt sets the "effective_at" field. +func (_c *GrantCreate) SetEffectiveAt(v time.Time) *GrantCreate { + _c.mutation.SetEffectiveAt(v) + return _c +} + +// SetExpiration sets the "expiration" field. +func (_c *GrantCreate) SetExpiration(v *grant.ExpirationPeriod) *GrantCreate { + _c.mutation.SetExpiration(v) + return _c +} + +// SetExpiresAt sets the "expires_at" field. +func (_c *GrantCreate) SetExpiresAt(v time.Time) *GrantCreate { + _c.mutation.SetExpiresAt(v) + return _c +} + +// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil. +func (_c *GrantCreate) SetNillableExpiresAt(v *time.Time) *GrantCreate { + if v != nil { + _c.SetExpiresAt(*v) + } + return _c +} + +// SetVoidedAt sets the "voided_at" field. +func (_c *GrantCreate) SetVoidedAt(v time.Time) *GrantCreate { + _c.mutation.SetVoidedAt(v) + return _c +} + +// SetNillableVoidedAt sets the "voided_at" field if the given value is not nil. +func (_c *GrantCreate) SetNillableVoidedAt(v *time.Time) *GrantCreate { + if v != nil { + _c.SetVoidedAt(*v) + } + return _c +} + +// SetResetMaxRollover sets the "reset_max_rollover" field. +func (_c *GrantCreate) SetResetMaxRollover(v float64) *GrantCreate { + _c.mutation.SetResetMaxRollover(v) + return _c +} + +// SetResetMinRollover sets the "reset_min_rollover" field. +func (_c *GrantCreate) SetResetMinRollover(v float64) *GrantCreate { + _c.mutation.SetResetMinRollover(v) + return _c +} + +// SetRecurrencePeriod sets the "recurrence_period" field. +func (_c *GrantCreate) SetRecurrencePeriod(v datetime.ISODurationString) *GrantCreate { + _c.mutation.SetRecurrencePeriod(v) + return _c +} + +// SetNillableRecurrencePeriod sets the "recurrence_period" field if the given value is not nil. +func (_c *GrantCreate) SetNillableRecurrencePeriod(v *datetime.ISODurationString) *GrantCreate { + if v != nil { + _c.SetRecurrencePeriod(*v) + } + return _c +} + +// SetRecurrenceAnchor sets the "recurrence_anchor" field. +func (_c *GrantCreate) SetRecurrenceAnchor(v time.Time) *GrantCreate { + _c.mutation.SetRecurrenceAnchor(v) + return _c +} + +// SetNillableRecurrenceAnchor sets the "recurrence_anchor" field if the given value is not nil. +func (_c *GrantCreate) SetNillableRecurrenceAnchor(v *time.Time) *GrantCreate { + if v != nil { + _c.SetRecurrenceAnchor(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *GrantCreate) SetID(v string) *GrantCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *GrantCreate) SetNillableID(v *string) *GrantCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetEntitlementID sets the "entitlement" edge to the Entitlement entity by ID. +func (_c *GrantCreate) SetEntitlementID(id string) *GrantCreate { + _c.mutation.SetEntitlementID(id) + return _c +} + +// SetEntitlement sets the "entitlement" edge to the Entitlement entity. +func (_c *GrantCreate) SetEntitlement(v *Entitlement) *GrantCreate { + return _c.SetEntitlementID(v.ID) +} + +// Mutation returns the GrantMutation object of the builder. +func (_c *GrantCreate) Mutation() *GrantMutation { + return _c.mutation +} + +// Save creates the Grant in the database. +func (_c *GrantCreate) Save(ctx context.Context) (*Grant, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *GrantCreate) SaveX(ctx context.Context) *Grant { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *GrantCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *GrantCreate) 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 *GrantCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := dbgrant.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := dbgrant.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.Priority(); !ok { + v := dbgrant.DefaultPriority + _c.mutation.SetPriority(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := dbgrant.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *GrantCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "Grant.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := dbgrant.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "Grant.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "Grant.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "Grant.updated_at"`)} + } + if _, ok := _c.mutation.OwnerID(); !ok { + return &ValidationError{Name: "owner_id", err: errors.New(`db: missing required field "Grant.owner_id"`)} + } + if _, ok := _c.mutation.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`db: missing required field "Grant.amount"`)} + } + if _, ok := _c.mutation.Priority(); !ok { + return &ValidationError{Name: "priority", err: errors.New(`db: missing required field "Grant.priority"`)} + } + if _, ok := _c.mutation.EffectiveAt(); !ok { + return &ValidationError{Name: "effective_at", err: errors.New(`db: missing required field "Grant.effective_at"`)} + } + if _, ok := _c.mutation.ResetMaxRollover(); !ok { + return &ValidationError{Name: "reset_max_rollover", err: errors.New(`db: missing required field "Grant.reset_max_rollover"`)} + } + if _, ok := _c.mutation.ResetMinRollover(); !ok { + return &ValidationError{Name: "reset_min_rollover", err: errors.New(`db: missing required field "Grant.reset_min_rollover"`)} + } + if len(_c.mutation.EntitlementIDs()) == 0 { + return &ValidationError{Name: "entitlement", err: errors.New(`db: missing required edge "Grant.entitlement"`)} + } + return nil +} + +func (_c *GrantCreate) sqlSave(ctx context.Context) (*Grant, 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 Grant.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *GrantCreate) createSpec() (*Grant, *sqlgraph.CreateSpec) { + var ( + _node = &Grant{config: _c.config} + _spec = sqlgraph.NewCreateSpec(dbgrant.Table, sqlgraph.NewFieldSpec(dbgrant.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(dbgrant.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(dbgrant.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(dbgrant.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(dbgrant.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(dbgrant.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Metadata(); ok { + _spec.SetField(dbgrant.FieldMetadata, field.TypeJSON, value) + _node.Metadata = value + } + if value, ok := _c.mutation.Amount(); ok { + _spec.SetField(dbgrant.FieldAmount, field.TypeFloat64, value) + _node.Amount = value + } + if value, ok := _c.mutation.Priority(); ok { + _spec.SetField(dbgrant.FieldPriority, field.TypeUint8, value) + _node.Priority = value + } + if value, ok := _c.mutation.EffectiveAt(); ok { + _spec.SetField(dbgrant.FieldEffectiveAt, field.TypeTime, value) + _node.EffectiveAt = value + } + if value, ok := _c.mutation.Expiration(); ok { + _spec.SetField(dbgrant.FieldExpiration, field.TypeJSON, value) + _node.Expiration = value + } + if value, ok := _c.mutation.ExpiresAt(); ok { + _spec.SetField(dbgrant.FieldExpiresAt, field.TypeTime, value) + _node.ExpiresAt = &value + } + if value, ok := _c.mutation.VoidedAt(); ok { + _spec.SetField(dbgrant.FieldVoidedAt, field.TypeTime, value) + _node.VoidedAt = &value + } + if value, ok := _c.mutation.ResetMaxRollover(); ok { + _spec.SetField(dbgrant.FieldResetMaxRollover, field.TypeFloat64, value) + _node.ResetMaxRollover = value + } + if value, ok := _c.mutation.ResetMinRollover(); ok { + _spec.SetField(dbgrant.FieldResetMinRollover, field.TypeFloat64, value) + _node.ResetMinRollover = value + } + if value, ok := _c.mutation.RecurrencePeriod(); ok { + _spec.SetField(dbgrant.FieldRecurrencePeriod, field.TypeString, value) + _node.RecurrencePeriod = &value + } + if value, ok := _c.mutation.RecurrenceAnchor(); ok { + _spec.SetField(dbgrant.FieldRecurrenceAnchor, field.TypeTime, value) + _node.RecurrenceAnchor = &value + } + if nodes := _c.mutation.EntitlementIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: dbgrant.EntitlementTable, + Columns: []string{dbgrant.EntitlementColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(entitlement.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.OwnerID = 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.Grant.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.GrantUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *GrantCreate) OnConflict(opts ...sql.ConflictOption) *GrantUpsertOne { + _c.conflict = opts + return &GrantUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Grant.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *GrantCreate) OnConflictColumns(columns ...string) *GrantUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &GrantUpsertOne{ + create: _c, + } +} + +type ( + // GrantUpsertOne is the builder for "upsert"-ing + // one Grant node. + GrantUpsertOne struct { + create *GrantCreate + } + + // GrantUpsert is the "OnConflict" setter. + GrantUpsert struct { + *sql.UpdateSet + } +) + +// SetAnnotations sets the "annotations" field. +func (u *GrantUpsert) SetAnnotations(v models.Annotations) *GrantUpsert { + u.Set(dbgrant.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *GrantUpsert) UpdateAnnotations() *GrantUpsert { + u.SetExcluded(dbgrant.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *GrantUpsert) ClearAnnotations() *GrantUpsert { + u.SetNull(dbgrant.FieldAnnotations) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *GrantUpsert) SetUpdatedAt(v time.Time) *GrantUpsert { + u.Set(dbgrant.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *GrantUpsert) UpdateUpdatedAt() *GrantUpsert { + u.SetExcluded(dbgrant.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *GrantUpsert) SetDeletedAt(v time.Time) *GrantUpsert { + u.Set(dbgrant.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *GrantUpsert) UpdateDeletedAt() *GrantUpsert { + u.SetExcluded(dbgrant.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *GrantUpsert) ClearDeletedAt() *GrantUpsert { + u.SetNull(dbgrant.FieldDeletedAt) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *GrantUpsert) SetMetadata(v map[string]string) *GrantUpsert { + u.Set(dbgrant.FieldMetadata, v) + return u +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *GrantUpsert) UpdateMetadata() *GrantUpsert { + u.SetExcluded(dbgrant.FieldMetadata) + return u +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *GrantUpsert) ClearMetadata() *GrantUpsert { + u.SetNull(dbgrant.FieldMetadata) + return u +} + +// SetVoidedAt sets the "voided_at" field. +func (u *GrantUpsert) SetVoidedAt(v time.Time) *GrantUpsert { + u.Set(dbgrant.FieldVoidedAt, v) + return u +} + +// UpdateVoidedAt sets the "voided_at" field to the value that was provided on create. +func (u *GrantUpsert) UpdateVoidedAt() *GrantUpsert { + u.SetExcluded(dbgrant.FieldVoidedAt) + return u +} + +// ClearVoidedAt clears the value of the "voided_at" field. +func (u *GrantUpsert) ClearVoidedAt() *GrantUpsert { + u.SetNull(dbgrant.FieldVoidedAt) + 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.Grant.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(dbgrant.FieldID) +// }), +// ). +// Exec(ctx) +func (u *GrantUpsertOne) UpdateNewValues() *GrantUpsertOne { + 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(dbgrant.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(dbgrant.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(dbgrant.FieldCreatedAt) + } + if _, exists := u.create.mutation.OwnerID(); exists { + s.SetIgnore(dbgrant.FieldOwnerID) + } + if _, exists := u.create.mutation.Amount(); exists { + s.SetIgnore(dbgrant.FieldAmount) + } + if _, exists := u.create.mutation.Priority(); exists { + s.SetIgnore(dbgrant.FieldPriority) + } + if _, exists := u.create.mutation.EffectiveAt(); exists { + s.SetIgnore(dbgrant.FieldEffectiveAt) + } + if _, exists := u.create.mutation.Expiration(); exists { + s.SetIgnore(dbgrant.FieldExpiration) + } + if _, exists := u.create.mutation.ExpiresAt(); exists { + s.SetIgnore(dbgrant.FieldExpiresAt) + } + if _, exists := u.create.mutation.ResetMaxRollover(); exists { + s.SetIgnore(dbgrant.FieldResetMaxRollover) + } + if _, exists := u.create.mutation.ResetMinRollover(); exists { + s.SetIgnore(dbgrant.FieldResetMinRollover) + } + if _, exists := u.create.mutation.RecurrencePeriod(); exists { + s.SetIgnore(dbgrant.FieldRecurrencePeriod) + } + if _, exists := u.create.mutation.RecurrenceAnchor(); exists { + s.SetIgnore(dbgrant.FieldRecurrenceAnchor) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Grant.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *GrantUpsertOne) Ignore() *GrantUpsertOne { + 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 *GrantUpsertOne) DoNothing() *GrantUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the GrantCreate.OnConflict +// documentation for more info. +func (u *GrantUpsertOne) Update(set func(*GrantUpsert)) *GrantUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&GrantUpsert{UpdateSet: update}) + })) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *GrantUpsertOne) SetAnnotations(v models.Annotations) *GrantUpsertOne { + return u.Update(func(s *GrantUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *GrantUpsertOne) UpdateAnnotations() *GrantUpsertOne { + return u.Update(func(s *GrantUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *GrantUpsertOne) ClearAnnotations() *GrantUpsertOne { + return u.Update(func(s *GrantUpsert) { + s.ClearAnnotations() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *GrantUpsertOne) SetUpdatedAt(v time.Time) *GrantUpsertOne { + return u.Update(func(s *GrantUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *GrantUpsertOne) UpdateUpdatedAt() *GrantUpsertOne { + return u.Update(func(s *GrantUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *GrantUpsertOne) SetDeletedAt(v time.Time) *GrantUpsertOne { + return u.Update(func(s *GrantUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *GrantUpsertOne) UpdateDeletedAt() *GrantUpsertOne { + return u.Update(func(s *GrantUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *GrantUpsertOne) ClearDeletedAt() *GrantUpsertOne { + return u.Update(func(s *GrantUpsert) { + s.ClearDeletedAt() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *GrantUpsertOne) SetMetadata(v map[string]string) *GrantUpsertOne { + return u.Update(func(s *GrantUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *GrantUpsertOne) UpdateMetadata() *GrantUpsertOne { + return u.Update(func(s *GrantUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *GrantUpsertOne) ClearMetadata() *GrantUpsertOne { + return u.Update(func(s *GrantUpsert) { + s.ClearMetadata() + }) +} + +// SetVoidedAt sets the "voided_at" field. +func (u *GrantUpsertOne) SetVoidedAt(v time.Time) *GrantUpsertOne { + return u.Update(func(s *GrantUpsert) { + s.SetVoidedAt(v) + }) +} + +// UpdateVoidedAt sets the "voided_at" field to the value that was provided on create. +func (u *GrantUpsertOne) UpdateVoidedAt() *GrantUpsertOne { + return u.Update(func(s *GrantUpsert) { + s.UpdateVoidedAt() + }) +} + +// ClearVoidedAt clears the value of the "voided_at" field. +func (u *GrantUpsertOne) ClearVoidedAt() *GrantUpsertOne { + return u.Update(func(s *GrantUpsert) { + s.ClearVoidedAt() + }) +} + +// Exec executes the query. +func (u *GrantUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for GrantCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *GrantUpsertOne) 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 *GrantUpsertOne) 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: GrantUpsertOne.ID is not supported by MySQL driver. Use GrantUpsertOne.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 *GrantUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// GrantCreateBulk is the builder for creating many Grant entities in bulk. +type GrantCreateBulk struct { + config + err error + builders []*GrantCreate + conflict []sql.ConflictOption +} + +// Save creates the Grant entities in the database. +func (_c *GrantCreateBulk) Save(ctx context.Context) ([]*Grant, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Grant, 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.(*GrantMutation) + 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 *GrantCreateBulk) SaveX(ctx context.Context) []*Grant { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *GrantCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *GrantCreateBulk) 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.Grant.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.GrantUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *GrantCreateBulk) OnConflict(opts ...sql.ConflictOption) *GrantUpsertBulk { + _c.conflict = opts + return &GrantUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Grant.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *GrantCreateBulk) OnConflictColumns(columns ...string) *GrantUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &GrantUpsertBulk{ + create: _c, + } +} + +// GrantUpsertBulk is the builder for "upsert"-ing +// a bulk of Grant nodes. +type GrantUpsertBulk struct { + create *GrantCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.Grant.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(dbgrant.FieldID) +// }), +// ). +// Exec(ctx) +func (u *GrantUpsertBulk) UpdateNewValues() *GrantUpsertBulk { + 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(dbgrant.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(dbgrant.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(dbgrant.FieldCreatedAt) + } + if _, exists := b.mutation.OwnerID(); exists { + s.SetIgnore(dbgrant.FieldOwnerID) + } + if _, exists := b.mutation.Amount(); exists { + s.SetIgnore(dbgrant.FieldAmount) + } + if _, exists := b.mutation.Priority(); exists { + s.SetIgnore(dbgrant.FieldPriority) + } + if _, exists := b.mutation.EffectiveAt(); exists { + s.SetIgnore(dbgrant.FieldEffectiveAt) + } + if _, exists := b.mutation.Expiration(); exists { + s.SetIgnore(dbgrant.FieldExpiration) + } + if _, exists := b.mutation.ExpiresAt(); exists { + s.SetIgnore(dbgrant.FieldExpiresAt) + } + if _, exists := b.mutation.ResetMaxRollover(); exists { + s.SetIgnore(dbgrant.FieldResetMaxRollover) + } + if _, exists := b.mutation.ResetMinRollover(); exists { + s.SetIgnore(dbgrant.FieldResetMinRollover) + } + if _, exists := b.mutation.RecurrencePeriod(); exists { + s.SetIgnore(dbgrant.FieldRecurrencePeriod) + } + if _, exists := b.mutation.RecurrenceAnchor(); exists { + s.SetIgnore(dbgrant.FieldRecurrenceAnchor) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Grant.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *GrantUpsertBulk) Ignore() *GrantUpsertBulk { + 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 *GrantUpsertBulk) DoNothing() *GrantUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the GrantCreateBulk.OnConflict +// documentation for more info. +func (u *GrantUpsertBulk) Update(set func(*GrantUpsert)) *GrantUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&GrantUpsert{UpdateSet: update}) + })) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *GrantUpsertBulk) SetAnnotations(v models.Annotations) *GrantUpsertBulk { + return u.Update(func(s *GrantUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *GrantUpsertBulk) UpdateAnnotations() *GrantUpsertBulk { + return u.Update(func(s *GrantUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *GrantUpsertBulk) ClearAnnotations() *GrantUpsertBulk { + return u.Update(func(s *GrantUpsert) { + s.ClearAnnotations() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *GrantUpsertBulk) SetUpdatedAt(v time.Time) *GrantUpsertBulk { + return u.Update(func(s *GrantUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *GrantUpsertBulk) UpdateUpdatedAt() *GrantUpsertBulk { + return u.Update(func(s *GrantUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *GrantUpsertBulk) SetDeletedAt(v time.Time) *GrantUpsertBulk { + return u.Update(func(s *GrantUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *GrantUpsertBulk) UpdateDeletedAt() *GrantUpsertBulk { + return u.Update(func(s *GrantUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *GrantUpsertBulk) ClearDeletedAt() *GrantUpsertBulk { + return u.Update(func(s *GrantUpsert) { + s.ClearDeletedAt() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *GrantUpsertBulk) SetMetadata(v map[string]string) *GrantUpsertBulk { + return u.Update(func(s *GrantUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *GrantUpsertBulk) UpdateMetadata() *GrantUpsertBulk { + return u.Update(func(s *GrantUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *GrantUpsertBulk) ClearMetadata() *GrantUpsertBulk { + return u.Update(func(s *GrantUpsert) { + s.ClearMetadata() + }) +} + +// SetVoidedAt sets the "voided_at" field. +func (u *GrantUpsertBulk) SetVoidedAt(v time.Time) *GrantUpsertBulk { + return u.Update(func(s *GrantUpsert) { + s.SetVoidedAt(v) + }) +} + +// UpdateVoidedAt sets the "voided_at" field to the value that was provided on create. +func (u *GrantUpsertBulk) UpdateVoidedAt() *GrantUpsertBulk { + return u.Update(func(s *GrantUpsert) { + s.UpdateVoidedAt() + }) +} + +// ClearVoidedAt clears the value of the "voided_at" field. +func (u *GrantUpsertBulk) ClearVoidedAt() *GrantUpsertBulk { + return u.Update(func(s *GrantUpsert) { + s.ClearVoidedAt() + }) +} + +// Exec executes the query. +func (u *GrantUpsertBulk) 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 GrantCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for GrantCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *GrantUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/grant_delete.go b/ent/db/grant_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..84958a237312dc57b5a1cde1b6c3a649d9c9e10c --- /dev/null +++ b/ent/db/grant_delete.go @@ -0,0 +1,89 @@ +// 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/predicate" + + dbgrant "github.com/openmeterio/openmeter/openmeter/ent/db/grant" +) + +// GrantDelete is the builder for deleting a Grant entity. +type GrantDelete struct { + config + hooks []Hook + mutation *GrantMutation +} + +// Where appends a list predicates to the GrantDelete builder. +func (_d *GrantDelete) Where(ps ...predicate.Grant) *GrantDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *GrantDelete) 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 *GrantDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *GrantDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(dbgrant.Table, sqlgraph.NewFieldSpec(dbgrant.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 +} + +// GrantDeleteOne is the builder for deleting a single Grant entity. +type GrantDeleteOne struct { + _d *GrantDelete +} + +// Where appends a list predicates to the GrantDelete builder. +func (_d *GrantDeleteOne) Where(ps ...predicate.Grant) *GrantDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *GrantDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{dbgrant.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *GrantDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/grant_query.go b/ent/db/grant_query.go new file mode 100644 index 0000000000000000000000000000000000000000..2a24bf0d1f2e24cc08d9fb9febca4027f911dac0 --- /dev/null +++ b/ent/db/grant_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/entitlement" + dbgrant "github.com/openmeterio/openmeter/openmeter/ent/db/grant" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// GrantQuery is the builder for querying Grant entities. +type GrantQuery struct { + config + ctx *QueryContext + order []dbgrant.OrderOption + inters []Interceptor + predicates []predicate.Grant + withEntitlement *EntitlementQuery + 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 GrantQuery builder. +func (_q *GrantQuery) Where(ps ...predicate.Grant) *GrantQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *GrantQuery) Limit(limit int) *GrantQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *GrantQuery) Offset(offset int) *GrantQuery { + _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 *GrantQuery) Unique(unique bool) *GrantQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *GrantQuery) Order(o ...dbgrant.OrderOption) *GrantQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryEntitlement chains the current query on the "entitlement" edge. +func (_q *GrantQuery) QueryEntitlement() *EntitlementQuery { + query := (&EntitlementClient{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(dbgrant.Table, dbgrant.FieldID, selector), + sqlgraph.To(entitlement.Table, entitlement.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, dbgrant.EntitlementTable, dbgrant.EntitlementColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Grant entity from the query. +// Returns a *NotFoundError when no Grant was found. +func (_q *GrantQuery) First(ctx context.Context) (*Grant, 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{dbgrant.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *GrantQuery) FirstX(ctx context.Context) *Grant { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Grant ID from the query. +// Returns a *NotFoundError when no Grant ID was found. +func (_q *GrantQuery) 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{dbgrant.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *GrantQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Grant entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Grant entity is found. +// Returns a *NotFoundError when no Grant entities are found. +func (_q *GrantQuery) Only(ctx context.Context) (*Grant, 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{dbgrant.Label} + default: + return nil, &NotSingularError{dbgrant.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *GrantQuery) OnlyX(ctx context.Context) *Grant { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Grant ID in the query. +// Returns a *NotSingularError when more than one Grant ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *GrantQuery) 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{dbgrant.Label} + default: + err = &NotSingularError{dbgrant.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *GrantQuery) 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 Grants. +func (_q *GrantQuery) All(ctx context.Context) ([]*Grant, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Grant, *GrantQuery]() + return withInterceptors[[]*Grant](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *GrantQuery) AllX(ctx context.Context) []*Grant { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Grant IDs. +func (_q *GrantQuery) 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(dbgrant.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *GrantQuery) 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 *GrantQuery) 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[*GrantQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *GrantQuery) 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 *GrantQuery) 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 *GrantQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the GrantQuery 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 *GrantQuery) Clone() *GrantQuery { + if _q == nil { + return nil + } + return &GrantQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]dbgrant.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Grant{}, _q.predicates...), + withEntitlement: _q.withEntitlement.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithEntitlement tells the query-builder to eager-load the nodes that are connected to +// the "entitlement" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *GrantQuery) WithEntitlement(opts ...func(*EntitlementQuery)) *GrantQuery { + query := (&EntitlementClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withEntitlement = 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.Grant.Query(). +// GroupBy(dbgrant.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *GrantQuery) GroupBy(field string, fields ...string) *GrantGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &GrantGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = dbgrant.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.Grant.Query(). +// Select(dbgrant.FieldNamespace). +// Scan(ctx, &v) +func (_q *GrantQuery) Select(fields ...string) *GrantSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &GrantSelect{GrantQuery: _q} + sbuild.label = dbgrant.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a GrantSelect configured with the given aggregations. +func (_q *GrantQuery) Aggregate(fns ...AggregateFunc) *GrantSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *GrantQuery) 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 !dbgrant.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 *GrantQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Grant, error) { + var ( + nodes = []*Grant{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withEntitlement != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Grant).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Grant{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.withEntitlement; query != nil { + if err := _q.loadEntitlement(ctx, query, nodes, nil, + func(n *Grant, e *Entitlement) { n.Edges.Entitlement = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *GrantQuery) loadEntitlement(ctx context.Context, query *EntitlementQuery, nodes []*Grant, init func(*Grant), assign func(*Grant, *Entitlement)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*Grant) + for i := range nodes { + fk := nodes[i].OwnerID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(entitlement.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 "owner_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *GrantQuery) 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 *GrantQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(dbgrant.Table, dbgrant.Columns, sqlgraph.NewFieldSpec(dbgrant.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, dbgrant.FieldID) + for i := range fields { + if fields[i] != dbgrant.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withEntitlement != nil { + _spec.Node.AddColumnOnce(dbgrant.FieldOwnerID) + } + } + 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 *GrantQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(dbgrant.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = dbgrant.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 *GrantQuery) ForUpdate(opts ...sql.LockOption) *GrantQuery { + 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 *GrantQuery) ForShare(opts ...sql.LockOption) *GrantQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// GrantGroupBy is the group-by builder for Grant entities. +type GrantGroupBy struct { + selector + build *GrantQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *GrantGroupBy) Aggregate(fns ...AggregateFunc) *GrantGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *GrantGroupBy) 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[*GrantQuery, *GrantGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *GrantGroupBy) sqlScan(ctx context.Context, root *GrantQuery, 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) +} + +// GrantSelect is the builder for selecting fields of Grant entities. +type GrantSelect struct { + *GrantQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *GrantSelect) Aggregate(fns ...AggregateFunc) *GrantSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *GrantSelect) 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[*GrantQuery, *GrantSelect](ctx, _s.GrantQuery, _s, _s.inters, v) +} + +func (_s *GrantSelect) sqlScan(ctx context.Context, root *GrantQuery, 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/ent/db/grant_update.go b/ent/db/grant_update.go new file mode 100644 index 0000000000000000000000000000000000000000..b1a2ac6fc6f30da9ae89b3694f8b8a3c122d70a4 --- /dev/null +++ b/ent/db/grant_update.go @@ -0,0 +1,435 @@ +// 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" + dbgrant "github.com/openmeterio/openmeter/openmeter/ent/db/grant" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/models" +) + +// GrantUpdate is the builder for updating Grant entities. +type GrantUpdate struct { + config + hooks []Hook + mutation *GrantMutation +} + +// Where appends a list predicates to the GrantUpdate builder. +func (_u *GrantUpdate) Where(ps ...predicate.Grant) *GrantUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *GrantUpdate) SetAnnotations(v models.Annotations) *GrantUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *GrantUpdate) ClearAnnotations() *GrantUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *GrantUpdate) SetUpdatedAt(v time.Time) *GrantUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *GrantUpdate) SetDeletedAt(v time.Time) *GrantUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *GrantUpdate) SetNillableDeletedAt(v *time.Time) *GrantUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *GrantUpdate) ClearDeletedAt() *GrantUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *GrantUpdate) SetMetadata(v map[string]string) *GrantUpdate { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *GrantUpdate) ClearMetadata() *GrantUpdate { + _u.mutation.ClearMetadata() + return _u +} + +// SetVoidedAt sets the "voided_at" field. +func (_u *GrantUpdate) SetVoidedAt(v time.Time) *GrantUpdate { + _u.mutation.SetVoidedAt(v) + return _u +} + +// SetNillableVoidedAt sets the "voided_at" field if the given value is not nil. +func (_u *GrantUpdate) SetNillableVoidedAt(v *time.Time) *GrantUpdate { + if v != nil { + _u.SetVoidedAt(*v) + } + return _u +} + +// ClearVoidedAt clears the value of the "voided_at" field. +func (_u *GrantUpdate) ClearVoidedAt() *GrantUpdate { + _u.mutation.ClearVoidedAt() + return _u +} + +// Mutation returns the GrantMutation object of the builder. +func (_u *GrantUpdate) Mutation() *GrantMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *GrantUpdate) 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 *GrantUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *GrantUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *GrantUpdate) 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 *GrantUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := dbgrant.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *GrantUpdate) check() error { + if _u.mutation.EntitlementCleared() && len(_u.mutation.EntitlementIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "Grant.entitlement"`) + } + return nil +} + +func (_u *GrantUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(dbgrant.Table, dbgrant.Columns, sqlgraph.NewFieldSpec(dbgrant.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.Annotations(); ok { + _spec.SetField(dbgrant.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(dbgrant.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(dbgrant.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(dbgrant.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(dbgrant.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(dbgrant.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(dbgrant.FieldMetadata, field.TypeJSON) + } + if _u.mutation.ExpirationCleared() { + _spec.ClearField(dbgrant.FieldExpiration, field.TypeJSON) + } + if _u.mutation.ExpiresAtCleared() { + _spec.ClearField(dbgrant.FieldExpiresAt, field.TypeTime) + } + if value, ok := _u.mutation.VoidedAt(); ok { + _spec.SetField(dbgrant.FieldVoidedAt, field.TypeTime, value) + } + if _u.mutation.VoidedAtCleared() { + _spec.ClearField(dbgrant.FieldVoidedAt, field.TypeTime) + } + if _u.mutation.RecurrencePeriodCleared() { + _spec.ClearField(dbgrant.FieldRecurrencePeriod, field.TypeString) + } + if _u.mutation.RecurrenceAnchorCleared() { + _spec.ClearField(dbgrant.FieldRecurrenceAnchor, field.TypeTime) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{dbgrant.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// GrantUpdateOne is the builder for updating a single Grant entity. +type GrantUpdateOne struct { + config + fields []string + hooks []Hook + mutation *GrantMutation +} + +// SetAnnotations sets the "annotations" field. +func (_u *GrantUpdateOne) SetAnnotations(v models.Annotations) *GrantUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *GrantUpdateOne) ClearAnnotations() *GrantUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *GrantUpdateOne) SetUpdatedAt(v time.Time) *GrantUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *GrantUpdateOne) SetDeletedAt(v time.Time) *GrantUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *GrantUpdateOne) SetNillableDeletedAt(v *time.Time) *GrantUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *GrantUpdateOne) ClearDeletedAt() *GrantUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *GrantUpdateOne) SetMetadata(v map[string]string) *GrantUpdateOne { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *GrantUpdateOne) ClearMetadata() *GrantUpdateOne { + _u.mutation.ClearMetadata() + return _u +} + +// SetVoidedAt sets the "voided_at" field. +func (_u *GrantUpdateOne) SetVoidedAt(v time.Time) *GrantUpdateOne { + _u.mutation.SetVoidedAt(v) + return _u +} + +// SetNillableVoidedAt sets the "voided_at" field if the given value is not nil. +func (_u *GrantUpdateOne) SetNillableVoidedAt(v *time.Time) *GrantUpdateOne { + if v != nil { + _u.SetVoidedAt(*v) + } + return _u +} + +// ClearVoidedAt clears the value of the "voided_at" field. +func (_u *GrantUpdateOne) ClearVoidedAt() *GrantUpdateOne { + _u.mutation.ClearVoidedAt() + return _u +} + +// Mutation returns the GrantMutation object of the builder. +func (_u *GrantUpdateOne) Mutation() *GrantMutation { + return _u.mutation +} + +// Where appends a list predicates to the GrantUpdate builder. +func (_u *GrantUpdateOne) Where(ps ...predicate.Grant) *GrantUpdateOne { + _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 *GrantUpdateOne) Select(field string, fields ...string) *GrantUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Grant entity. +func (_u *GrantUpdateOne) Save(ctx context.Context) (*Grant, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *GrantUpdateOne) SaveX(ctx context.Context) *Grant { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *GrantUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *GrantUpdateOne) 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 *GrantUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := dbgrant.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *GrantUpdateOne) check() error { + if _u.mutation.EntitlementCleared() && len(_u.mutation.EntitlementIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "Grant.entitlement"`) + } + return nil +} + +func (_u *GrantUpdateOne) sqlSave(ctx context.Context) (_node *Grant, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(dbgrant.Table, dbgrant.Columns, sqlgraph.NewFieldSpec(dbgrant.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "Grant.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, dbgrant.FieldID) + for _, f := range fields { + if !dbgrant.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != dbgrant.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.Annotations(); ok { + _spec.SetField(dbgrant.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(dbgrant.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(dbgrant.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(dbgrant.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(dbgrant.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(dbgrant.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(dbgrant.FieldMetadata, field.TypeJSON) + } + if _u.mutation.ExpirationCleared() { + _spec.ClearField(dbgrant.FieldExpiration, field.TypeJSON) + } + if _u.mutation.ExpiresAtCleared() { + _spec.ClearField(dbgrant.FieldExpiresAt, field.TypeTime) + } + if value, ok := _u.mutation.VoidedAt(); ok { + _spec.SetField(dbgrant.FieldVoidedAt, field.TypeTime, value) + } + if _u.mutation.VoidedAtCleared() { + _spec.ClearField(dbgrant.FieldVoidedAt, field.TypeTime) + } + if _u.mutation.RecurrencePeriodCleared() { + _spec.ClearField(dbgrant.FieldRecurrencePeriod, field.TypeString) + } + if _u.mutation.RecurrenceAnchorCleared() { + _spec.ClearField(dbgrant.FieldRecurrenceAnchor, field.TypeTime) + } + _node = &Grant{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{dbgrant.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/ent/db/hook/hook.go b/ent/db/hook/hook.go new file mode 100644 index 0000000000000000000000000000000000000000..f93c242cc1d3ce642602e5ff17816b45d01fe6ce --- /dev/null +++ b/ent/db/hook/hook.go @@ -0,0 +1,1171 @@ +// Code generated by ent, DO NOT EDIT. + +package hook + +import ( + "context" + "fmt" + + "github.com/openmeterio/openmeter/openmeter/ent/db" +) + +// The AddonFunc type is an adapter to allow the use of ordinary +// function as Addon mutator. +type AddonFunc func(context.Context, *db.AddonMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f AddonFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.AddonMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AddonMutation", m) +} + +// The AddonRateCardFunc type is an adapter to allow the use of ordinary +// function as AddonRateCard mutator. +type AddonRateCardFunc func(context.Context, *db.AddonRateCardMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f AddonRateCardFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.AddonRateCardMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AddonRateCardMutation", m) +} + +// The AppFunc type is an adapter to allow the use of ordinary +// function as App mutator. +type AppFunc func(context.Context, *db.AppMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f AppFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.AppMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AppMutation", m) +} + +// The AppCustomInvoicingFunc type is an adapter to allow the use of ordinary +// function as AppCustomInvoicing mutator. +type AppCustomInvoicingFunc func(context.Context, *db.AppCustomInvoicingMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f AppCustomInvoicingFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.AppCustomInvoicingMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AppCustomInvoicingMutation", m) +} + +// The AppCustomInvoicingCustomerFunc type is an adapter to allow the use of ordinary +// function as AppCustomInvoicingCustomer mutator. +type AppCustomInvoicingCustomerFunc func(context.Context, *db.AppCustomInvoicingCustomerMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f AppCustomInvoicingCustomerFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.AppCustomInvoicingCustomerMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AppCustomInvoicingCustomerMutation", m) +} + +// The AppCustomerFunc type is an adapter to allow the use of ordinary +// function as AppCustomer mutator. +type AppCustomerFunc func(context.Context, *db.AppCustomerMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f AppCustomerFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.AppCustomerMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AppCustomerMutation", m) +} + +// The AppStripeFunc type is an adapter to allow the use of ordinary +// function as AppStripe mutator. +type AppStripeFunc func(context.Context, *db.AppStripeMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f AppStripeFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.AppStripeMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AppStripeMutation", m) +} + +// The AppStripeCustomerFunc type is an adapter to allow the use of ordinary +// function as AppStripeCustomer mutator. +type AppStripeCustomerFunc func(context.Context, *db.AppStripeCustomerMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f AppStripeCustomerFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.AppStripeCustomerMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AppStripeCustomerMutation", m) +} + +// The BalanceSnapshotFunc type is an adapter to allow the use of ordinary +// function as BalanceSnapshot mutator. +type BalanceSnapshotFunc func(context.Context, *db.BalanceSnapshotMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f BalanceSnapshotFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.BalanceSnapshotMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BalanceSnapshotMutation", m) +} + +// The BillingCustomerLockFunc type is an adapter to allow the use of ordinary +// function as BillingCustomerLock mutator. +type BillingCustomerLockFunc func(context.Context, *db.BillingCustomerLockMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f BillingCustomerLockFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.BillingCustomerLockMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingCustomerLockMutation", m) +} + +// The BillingCustomerOverrideFunc type is an adapter to allow the use of ordinary +// function as BillingCustomerOverride mutator. +type BillingCustomerOverrideFunc func(context.Context, *db.BillingCustomerOverrideMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f BillingCustomerOverrideFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.BillingCustomerOverrideMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingCustomerOverrideMutation", m) +} + +// The BillingInvoiceFunc type is an adapter to allow the use of ordinary +// function as BillingInvoice mutator. +type BillingInvoiceFunc func(context.Context, *db.BillingInvoiceMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f BillingInvoiceFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.BillingInvoiceMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingInvoiceMutation", m) +} + +// The BillingInvoiceFlatFeeLineConfigFunc type is an adapter to allow the use of ordinary +// function as BillingInvoiceFlatFeeLineConfig mutator. +type BillingInvoiceFlatFeeLineConfigFunc func(context.Context, *db.BillingInvoiceFlatFeeLineConfigMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f BillingInvoiceFlatFeeLineConfigFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.BillingInvoiceFlatFeeLineConfigMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingInvoiceFlatFeeLineConfigMutation", m) +} + +// The BillingInvoiceLineFunc type is an adapter to allow the use of ordinary +// function as BillingInvoiceLine mutator. +type BillingInvoiceLineFunc func(context.Context, *db.BillingInvoiceLineMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f BillingInvoiceLineFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.BillingInvoiceLineMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingInvoiceLineMutation", m) +} + +// The BillingInvoiceLineDiscountFunc type is an adapter to allow the use of ordinary +// function as BillingInvoiceLineDiscount mutator. +type BillingInvoiceLineDiscountFunc func(context.Context, *db.BillingInvoiceLineDiscountMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f BillingInvoiceLineDiscountFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.BillingInvoiceLineDiscountMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingInvoiceLineDiscountMutation", m) +} + +// The BillingInvoiceLineUsageDiscountFunc type is an adapter to allow the use of ordinary +// function as BillingInvoiceLineUsageDiscount mutator. +type BillingInvoiceLineUsageDiscountFunc func(context.Context, *db.BillingInvoiceLineUsageDiscountMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f BillingInvoiceLineUsageDiscountFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.BillingInvoiceLineUsageDiscountMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingInvoiceLineUsageDiscountMutation", m) +} + +// The BillingInvoiceSplitLineGroupFunc type is an adapter to allow the use of ordinary +// function as BillingInvoiceSplitLineGroup mutator. +type BillingInvoiceSplitLineGroupFunc func(context.Context, *db.BillingInvoiceSplitLineGroupMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f BillingInvoiceSplitLineGroupFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.BillingInvoiceSplitLineGroupMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingInvoiceSplitLineGroupMutation", m) +} + +// The BillingInvoiceUsageBasedLineConfigFunc type is an adapter to allow the use of ordinary +// function as BillingInvoiceUsageBasedLineConfig mutator. +type BillingInvoiceUsageBasedLineConfigFunc func(context.Context, *db.BillingInvoiceUsageBasedLineConfigMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f BillingInvoiceUsageBasedLineConfigFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.BillingInvoiceUsageBasedLineConfigMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingInvoiceUsageBasedLineConfigMutation", m) +} + +// The BillingInvoiceValidationIssueFunc type is an adapter to allow the use of ordinary +// function as BillingInvoiceValidationIssue mutator. +type BillingInvoiceValidationIssueFunc func(context.Context, *db.BillingInvoiceValidationIssueMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f BillingInvoiceValidationIssueFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.BillingInvoiceValidationIssueMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingInvoiceValidationIssueMutation", m) +} + +// The BillingInvoiceWriteSchemaLevelFunc type is an adapter to allow the use of ordinary +// function as BillingInvoiceWriteSchemaLevel mutator. +type BillingInvoiceWriteSchemaLevelFunc func(context.Context, *db.BillingInvoiceWriteSchemaLevelMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f BillingInvoiceWriteSchemaLevelFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.BillingInvoiceWriteSchemaLevelMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingInvoiceWriteSchemaLevelMutation", m) +} + +// The BillingProfileFunc type is an adapter to allow the use of ordinary +// function as BillingProfile mutator. +type BillingProfileFunc func(context.Context, *db.BillingProfileMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f BillingProfileFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.BillingProfileMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingProfileMutation", m) +} + +// The BillingSequenceNumbersFunc type is an adapter to allow the use of ordinary +// function as BillingSequenceNumbers mutator. +type BillingSequenceNumbersFunc func(context.Context, *db.BillingSequenceNumbersMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f BillingSequenceNumbersFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.BillingSequenceNumbersMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingSequenceNumbersMutation", m) +} + +// The BillingStandardInvoiceDetailedLineFunc type is an adapter to allow the use of ordinary +// function as BillingStandardInvoiceDetailedLine mutator. +type BillingStandardInvoiceDetailedLineFunc func(context.Context, *db.BillingStandardInvoiceDetailedLineMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f BillingStandardInvoiceDetailedLineFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.BillingStandardInvoiceDetailedLineMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingStandardInvoiceDetailedLineMutation", m) +} + +// The BillingStandardInvoiceDetailedLineAmountDiscountFunc type is an adapter to allow the use of ordinary +// function as BillingStandardInvoiceDetailedLineAmountDiscount mutator. +type BillingStandardInvoiceDetailedLineAmountDiscountFunc func(context.Context, *db.BillingStandardInvoiceDetailedLineAmountDiscountMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f BillingStandardInvoiceDetailedLineAmountDiscountFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.BillingStandardInvoiceDetailedLineAmountDiscountMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingStandardInvoiceDetailedLineAmountDiscountMutation", m) +} + +// The BillingWorkflowConfigFunc type is an adapter to allow the use of ordinary +// function as BillingWorkflowConfig mutator. +type BillingWorkflowConfigFunc func(context.Context, *db.BillingWorkflowConfigMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f BillingWorkflowConfigFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.BillingWorkflowConfigMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingWorkflowConfigMutation", m) +} + +// The ChargeFunc type is an adapter to allow the use of ordinary +// function as Charge mutator. +type ChargeFunc func(context.Context, *db.ChargeMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f ChargeFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.ChargeMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ChargeMutation", m) +} + +// The ChargeCreditPurchaseFunc type is an adapter to allow the use of ordinary +// function as ChargeCreditPurchase mutator. +type ChargeCreditPurchaseFunc func(context.Context, *db.ChargeCreditPurchaseMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f ChargeCreditPurchaseFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.ChargeCreditPurchaseMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ChargeCreditPurchaseMutation", m) +} + +// The ChargeCreditPurchaseCreditGrantFunc type is an adapter to allow the use of ordinary +// function as ChargeCreditPurchaseCreditGrant mutator. +type ChargeCreditPurchaseCreditGrantFunc func(context.Context, *db.ChargeCreditPurchaseCreditGrantMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f ChargeCreditPurchaseCreditGrantFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.ChargeCreditPurchaseCreditGrantMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ChargeCreditPurchaseCreditGrantMutation", m) +} + +// The ChargeCreditPurchaseExternalPaymentFunc type is an adapter to allow the use of ordinary +// function as ChargeCreditPurchaseExternalPayment mutator. +type ChargeCreditPurchaseExternalPaymentFunc func(context.Context, *db.ChargeCreditPurchaseExternalPaymentMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f ChargeCreditPurchaseExternalPaymentFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.ChargeCreditPurchaseExternalPaymentMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ChargeCreditPurchaseExternalPaymentMutation", m) +} + +// The ChargeCreditPurchaseInvoicedPaymentFunc type is an adapter to allow the use of ordinary +// function as ChargeCreditPurchaseInvoicedPayment mutator. +type ChargeCreditPurchaseInvoicedPaymentFunc func(context.Context, *db.ChargeCreditPurchaseInvoicedPaymentMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f ChargeCreditPurchaseInvoicedPaymentFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.ChargeCreditPurchaseInvoicedPaymentMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ChargeCreditPurchaseInvoicedPaymentMutation", m) +} + +// The ChargeFlatFeeFunc type is an adapter to allow the use of ordinary +// function as ChargeFlatFee mutator. +type ChargeFlatFeeFunc func(context.Context, *db.ChargeFlatFeeMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f ChargeFlatFeeFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.ChargeFlatFeeMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ChargeFlatFeeMutation", m) +} + +// The ChargeFlatFeeOverrideFunc type is an adapter to allow the use of ordinary +// function as ChargeFlatFeeOverride mutator. +type ChargeFlatFeeOverrideFunc func(context.Context, *db.ChargeFlatFeeOverrideMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f ChargeFlatFeeOverrideFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.ChargeFlatFeeOverrideMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ChargeFlatFeeOverrideMutation", m) +} + +// The ChargeFlatFeeRunFunc type is an adapter to allow the use of ordinary +// function as ChargeFlatFeeRun mutator. +type ChargeFlatFeeRunFunc func(context.Context, *db.ChargeFlatFeeRunMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f ChargeFlatFeeRunFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.ChargeFlatFeeRunMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ChargeFlatFeeRunMutation", m) +} + +// The ChargeFlatFeeRunCreditAllocationsFunc type is an adapter to allow the use of ordinary +// function as ChargeFlatFeeRunCreditAllocations mutator. +type ChargeFlatFeeRunCreditAllocationsFunc func(context.Context, *db.ChargeFlatFeeRunCreditAllocationsMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f ChargeFlatFeeRunCreditAllocationsFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.ChargeFlatFeeRunCreditAllocationsMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ChargeFlatFeeRunCreditAllocationsMutation", m) +} + +// The ChargeFlatFeeRunDetailedLineFunc type is an adapter to allow the use of ordinary +// function as ChargeFlatFeeRunDetailedLine mutator. +type ChargeFlatFeeRunDetailedLineFunc func(context.Context, *db.ChargeFlatFeeRunDetailedLineMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f ChargeFlatFeeRunDetailedLineFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.ChargeFlatFeeRunDetailedLineMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ChargeFlatFeeRunDetailedLineMutation", m) +} + +// The ChargeFlatFeeRunInvoicedUsageFunc type is an adapter to allow the use of ordinary +// function as ChargeFlatFeeRunInvoicedUsage mutator. +type ChargeFlatFeeRunInvoicedUsageFunc func(context.Context, *db.ChargeFlatFeeRunInvoicedUsageMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f ChargeFlatFeeRunInvoicedUsageFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.ChargeFlatFeeRunInvoicedUsageMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ChargeFlatFeeRunInvoicedUsageMutation", m) +} + +// The ChargeFlatFeeRunPaymentFunc type is an adapter to allow the use of ordinary +// function as ChargeFlatFeeRunPayment mutator. +type ChargeFlatFeeRunPaymentFunc func(context.Context, *db.ChargeFlatFeeRunPaymentMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f ChargeFlatFeeRunPaymentFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.ChargeFlatFeeRunPaymentMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ChargeFlatFeeRunPaymentMutation", 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 ChargeUsageBasedOverrideFunc type is an adapter to allow the use of ordinary +// function as ChargeUsageBasedOverride mutator. +type ChargeUsageBasedOverrideFunc func(context.Context, *db.ChargeUsageBasedOverrideMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f ChargeUsageBasedOverrideFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.ChargeUsageBasedOverrideMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ChargeUsageBasedOverrideMutation", 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 ChargeUsageBasedRunDetailedLineFunc type is an adapter to allow the use of ordinary +// function as ChargeUsageBasedRunDetailedLine mutator. +type ChargeUsageBasedRunDetailedLineFunc func(context.Context, *db.ChargeUsageBasedRunDetailedLineMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f ChargeUsageBasedRunDetailedLineFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.ChargeUsageBasedRunDetailedLineMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ChargeUsageBasedRunDetailedLineMutation", 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 CreditRealizationLineageFunc type is an adapter to allow the use of ordinary +// function as CreditRealizationLineage mutator. +type CreditRealizationLineageFunc func(context.Context, *db.CreditRealizationLineageMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f CreditRealizationLineageFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.CreditRealizationLineageMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.CreditRealizationLineageMutation", m) +} + +// The CreditRealizationLineageSegmentFunc type is an adapter to allow the use of ordinary +// function as CreditRealizationLineageSegment mutator. +type CreditRealizationLineageSegmentFunc func(context.Context, *db.CreditRealizationLineageSegmentMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f CreditRealizationLineageSegmentFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.CreditRealizationLineageSegmentMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.CreditRealizationLineageSegmentMutation", 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) + +// Mutate calls f(ctx, m). +func (f CurrencyCostBasisFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.CurrencyCostBasisMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.CurrencyCostBasisMutation", m) +} + +// The CustomCurrencyFunc type is an adapter to allow the use of ordinary +// function as CustomCurrency mutator. +type CustomCurrencyFunc func(context.Context, *db.CustomCurrencyMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f CustomCurrencyFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.CustomCurrencyMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.CustomCurrencyMutation", m) +} + +// The CustomerFunc type is an adapter to allow the use of ordinary +// function as Customer mutator. +type CustomerFunc func(context.Context, *db.CustomerMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f CustomerFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.CustomerMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.CustomerMutation", m) +} + +// The CustomerSubjectsFunc type is an adapter to allow the use of ordinary +// function as CustomerSubjects mutator. +type CustomerSubjectsFunc func(context.Context, *db.CustomerSubjectsMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f CustomerSubjectsFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.CustomerSubjectsMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.CustomerSubjectsMutation", m) +} + +// The EntitlementFunc type is an adapter to allow the use of ordinary +// function as Entitlement mutator. +type EntitlementFunc func(context.Context, *db.EntitlementMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f EntitlementFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.EntitlementMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.EntitlementMutation", m) +} + +// The FeatureFunc type is an adapter to allow the use of ordinary +// function as Feature mutator. +type FeatureFunc func(context.Context, *db.FeatureMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f FeatureFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.FeatureMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.FeatureMutation", m) +} + +// The GrantFunc type is an adapter to allow the use of ordinary +// function as Grant mutator. +type GrantFunc func(context.Context, *db.GrantMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f GrantFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.GrantMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.GrantMutation", m) +} + +// The LLMCostPriceFunc type is an adapter to allow the use of ordinary +// function as LLMCostPrice mutator. +type LLMCostPriceFunc func(context.Context, *db.LLMCostPriceMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f LLMCostPriceFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.LLMCostPriceMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.LLMCostPriceMutation", m) +} + +// The LedgerAccountFunc type is an adapter to allow the use of ordinary +// function as LedgerAccount mutator. +type LedgerAccountFunc func(context.Context, *db.LedgerAccountMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f LedgerAccountFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.LedgerAccountMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.LedgerAccountMutation", m) +} + +// The LedgerBreakageRecordFunc type is an adapter to allow the use of ordinary +// function as LedgerBreakageRecord mutator. +type LedgerBreakageRecordFunc func(context.Context, *db.LedgerBreakageRecordMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f LedgerBreakageRecordFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.LedgerBreakageRecordMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.LedgerBreakageRecordMutation", m) +} + +// The LedgerCreditVoidRecordFunc type is an adapter to allow the use of ordinary +// function as LedgerCreditVoidRecord mutator. +type LedgerCreditVoidRecordFunc func(context.Context, *db.LedgerCreditVoidRecordMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f LedgerCreditVoidRecordFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.LedgerCreditVoidRecordMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.LedgerCreditVoidRecordMutation", m) +} + +// The LedgerCustomerAccountFunc type is an adapter to allow the use of ordinary +// function as LedgerCustomerAccount mutator. +type LedgerCustomerAccountFunc func(context.Context, *db.LedgerCustomerAccountMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f LedgerCustomerAccountFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.LedgerCustomerAccountMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.LedgerCustomerAccountMutation", m) +} + +// The LedgerEntryFunc type is an adapter to allow the use of ordinary +// function as LedgerEntry mutator. +type LedgerEntryFunc func(context.Context, *db.LedgerEntryMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f LedgerEntryFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.LedgerEntryMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.LedgerEntryMutation", m) +} + +// The LedgerSubAccountFunc type is an adapter to allow the use of ordinary +// function as LedgerSubAccount mutator. +type LedgerSubAccountFunc func(context.Context, *db.LedgerSubAccountMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f LedgerSubAccountFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.LedgerSubAccountMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.LedgerSubAccountMutation", m) +} + +// The LedgerSubAccountRouteFunc type is an adapter to allow the use of ordinary +// function as LedgerSubAccountRoute mutator. +type LedgerSubAccountRouteFunc func(context.Context, *db.LedgerSubAccountRouteMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f LedgerSubAccountRouteFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.LedgerSubAccountRouteMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.LedgerSubAccountRouteMutation", m) +} + +// The LedgerTransactionFunc type is an adapter to allow the use of ordinary +// function as LedgerTransaction mutator. +type LedgerTransactionFunc func(context.Context, *db.LedgerTransactionMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f LedgerTransactionFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.LedgerTransactionMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.LedgerTransactionMutation", m) +} + +// The LedgerTransactionGroupFunc type is an adapter to allow the use of ordinary +// function as LedgerTransactionGroup mutator. +type LedgerTransactionGroupFunc func(context.Context, *db.LedgerTransactionGroupMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f LedgerTransactionGroupFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.LedgerTransactionGroupMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.LedgerTransactionGroupMutation", m) +} + +// The MeterFunc type is an adapter to allow the use of ordinary +// function as Meter mutator. +type MeterFunc func(context.Context, *db.MeterMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f MeterFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.MeterMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.MeterMutation", m) +} + +// The NotificationChannelFunc type is an adapter to allow the use of ordinary +// function as NotificationChannel mutator. +type NotificationChannelFunc func(context.Context, *db.NotificationChannelMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f NotificationChannelFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.NotificationChannelMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.NotificationChannelMutation", m) +} + +// The NotificationEventFunc type is an adapter to allow the use of ordinary +// function as NotificationEvent mutator. +type NotificationEventFunc func(context.Context, *db.NotificationEventMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f NotificationEventFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.NotificationEventMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.NotificationEventMutation", m) +} + +// The NotificationEventDeliveryStatusFunc type is an adapter to allow the use of ordinary +// function as NotificationEventDeliveryStatus mutator. +type NotificationEventDeliveryStatusFunc func(context.Context, *db.NotificationEventDeliveryStatusMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f NotificationEventDeliveryStatusFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.NotificationEventDeliveryStatusMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.NotificationEventDeliveryStatusMutation", m) +} + +// The NotificationRuleFunc type is an adapter to allow the use of ordinary +// function as NotificationRule mutator. +type NotificationRuleFunc func(context.Context, *db.NotificationRuleMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f NotificationRuleFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.NotificationRuleMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.NotificationRuleMutation", m) +} + +// The OrganizationDefaultTaxCodesFunc type is an adapter to allow the use of ordinary +// function as OrganizationDefaultTaxCodes mutator. +type OrganizationDefaultTaxCodesFunc func(context.Context, *db.OrganizationDefaultTaxCodesMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f OrganizationDefaultTaxCodesFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.OrganizationDefaultTaxCodesMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.OrganizationDefaultTaxCodesMutation", m) +} + +// The PlanFunc type is an adapter to allow the use of ordinary +// function as Plan mutator. +type PlanFunc func(context.Context, *db.PlanMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f PlanFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.PlanMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.PlanMutation", m) +} + +// The PlanAddonFunc type is an adapter to allow the use of ordinary +// function as PlanAddon mutator. +type PlanAddonFunc func(context.Context, *db.PlanAddonMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f PlanAddonFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.PlanAddonMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.PlanAddonMutation", m) +} + +// The PlanPhaseFunc type is an adapter to allow the use of ordinary +// function as PlanPhase mutator. +type PlanPhaseFunc func(context.Context, *db.PlanPhaseMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f PlanPhaseFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.PlanPhaseMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.PlanPhaseMutation", m) +} + +// The PlanRateCardFunc type is an adapter to allow the use of ordinary +// function as PlanRateCard mutator. +type PlanRateCardFunc func(context.Context, *db.PlanRateCardMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f PlanRateCardFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.PlanRateCardMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.PlanRateCardMutation", m) +} + +// The SubjectFunc type is an adapter to allow the use of ordinary +// function as Subject mutator. +type SubjectFunc func(context.Context, *db.SubjectMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f SubjectFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.SubjectMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.SubjectMutation", m) +} + +// The SubscriptionFunc type is an adapter to allow the use of ordinary +// function as Subscription mutator. +type SubscriptionFunc func(context.Context, *db.SubscriptionMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f SubscriptionFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.SubscriptionMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.SubscriptionMutation", m) +} + +// The SubscriptionAddonFunc type is an adapter to allow the use of ordinary +// function as SubscriptionAddon mutator. +type SubscriptionAddonFunc func(context.Context, *db.SubscriptionAddonMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f SubscriptionAddonFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.SubscriptionAddonMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.SubscriptionAddonMutation", m) +} + +// The SubscriptionAddonQuantityFunc type is an adapter to allow the use of ordinary +// function as SubscriptionAddonQuantity mutator. +type SubscriptionAddonQuantityFunc func(context.Context, *db.SubscriptionAddonQuantityMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f SubscriptionAddonQuantityFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.SubscriptionAddonQuantityMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.SubscriptionAddonQuantityMutation", m) +} + +// The SubscriptionBillingSyncStateFunc type is an adapter to allow the use of ordinary +// function as SubscriptionBillingSyncState mutator. +type SubscriptionBillingSyncStateFunc func(context.Context, *db.SubscriptionBillingSyncStateMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f SubscriptionBillingSyncStateFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.SubscriptionBillingSyncStateMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.SubscriptionBillingSyncStateMutation", m) +} + +// The SubscriptionItemFunc type is an adapter to allow the use of ordinary +// function as SubscriptionItem mutator. +type SubscriptionItemFunc func(context.Context, *db.SubscriptionItemMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f SubscriptionItemFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.SubscriptionItemMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.SubscriptionItemMutation", m) +} + +// The SubscriptionPhaseFunc type is an adapter to allow the use of ordinary +// function as SubscriptionPhase mutator. +type SubscriptionPhaseFunc func(context.Context, *db.SubscriptionPhaseMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f SubscriptionPhaseFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.SubscriptionPhaseMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.SubscriptionPhaseMutation", m) +} + +// The TaxCodeFunc type is an adapter to allow the use of ordinary +// function as TaxCode mutator. +type TaxCodeFunc func(context.Context, *db.TaxCodeMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f TaxCodeFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.TaxCodeMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.TaxCodeMutation", m) +} + +// The UsageResetFunc type is an adapter to allow the use of ordinary +// function as UsageReset mutator. +type UsageResetFunc func(context.Context, *db.UsageResetMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f UsageResetFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.UsageResetMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.UsageResetMutation", m) +} + +// Condition is a hook condition function. +type Condition func(context.Context, db.Mutation) bool + +// And groups conditions with the AND operator. +func And(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m db.Mutation) bool { + if !first(ctx, m) || !second(ctx, m) { + return false + } + for _, cond := range rest { + if !cond(ctx, m) { + return false + } + } + return true + } +} + +// Or groups conditions with the OR operator. +func Or(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m db.Mutation) bool { + if first(ctx, m) || second(ctx, m) { + return true + } + for _, cond := range rest { + if cond(ctx, m) { + return true + } + } + return false + } +} + +// Not negates a given condition. +func Not(cond Condition) Condition { + return func(ctx context.Context, m db.Mutation) bool { + return !cond(ctx, m) + } +} + +// HasOp is a condition testing mutation operation. +func HasOp(op db.Op) Condition { + return func(_ context.Context, m db.Mutation) bool { + return m.Op().Is(op) + } +} + +// HasAddedFields is a condition validating `.AddedField` on fields. +func HasAddedFields(field string, fields ...string) Condition { + return func(_ context.Context, m db.Mutation) bool { + if _, exists := m.AddedField(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.AddedField(field); !exists { + return false + } + } + return true + } +} + +// HasClearedFields is a condition validating `.FieldCleared` on fields. +func HasClearedFields(field string, fields ...string) Condition { + return func(_ context.Context, m db.Mutation) bool { + if exists := m.FieldCleared(field); !exists { + return false + } + for _, field := range fields { + if exists := m.FieldCleared(field); !exists { + return false + } + } + return true + } +} + +// HasFields is a condition validating `.Field` on fields. +func HasFields(field string, fields ...string) Condition { + return func(_ context.Context, m db.Mutation) bool { + if _, exists := m.Field(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.Field(field); !exists { + return false + } + } + return true + } +} + +// If executes the given hook under condition. +// +// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) +func If(hk db.Hook, cond Condition) db.Hook { + return func(next db.Mutator) db.Mutator { + return db.MutateFunc(func(ctx context.Context, m db.Mutation) (db.Value, error) { + if cond(ctx, m) { + return hk(next).Mutate(ctx, m) + } + return next.Mutate(ctx, m) + }) + } +} + +// On executes the given hook only for the given operation. +// +// hook.On(Log, db.Delete|db.Create) +func On(hk db.Hook, op db.Op) db.Hook { + return If(hk, HasOp(op)) +} + +// Unless skips the given hook only for the given operation. +// +// hook.Unless(Log, db.Update|db.UpdateOne) +func Unless(hk db.Hook, op db.Op) db.Hook { + return If(hk, Not(HasOp(op))) +} + +// FixedError is a hook returning a fixed error. +func FixedError(err error) db.Hook { + return func(db.Mutator) db.Mutator { + return db.MutateFunc(func(context.Context, db.Mutation) (db.Value, error) { + return nil, err + }) + } +} + +// Reject returns a hook that rejects all operations that match op. +// +// func (T) Hooks() []db.Hook { +// return []db.Hook{ +// Reject(db.Delete|db.Update), +// } +// } +func Reject(op db.Op) db.Hook { + hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) + return On(hk, op) +} + +// Chain acts as a list of hooks and is effectively immutable. +// Once created, it will always hold the same set of hooks in the same order. +type Chain struct { + hooks []db.Hook +} + +// NewChain creates a new chain of hooks. +func NewChain(hooks ...db.Hook) Chain { + return Chain{append([]db.Hook(nil), hooks...)} +} + +// Hook chains the list of hooks and returns the final hook. +func (c Chain) Hook() db.Hook { + return func(mutator db.Mutator) db.Mutator { + for i := len(c.hooks) - 1; i >= 0; i-- { + mutator = c.hooks[i](mutator) + } + return mutator + } +} + +// Append extends a chain, adding the specified hook +// as the last ones in the mutation flow. +func (c Chain) Append(hooks ...db.Hook) Chain { + newHooks := make([]db.Hook, 0, len(c.hooks)+len(hooks)) + newHooks = append(newHooks, c.hooks...) + newHooks = append(newHooks, hooks...) + return Chain{newHooks} +} + +// Extend extends a chain, adding the specified chain +// as the last ones in the mutation flow. +func (c Chain) Extend(chain Chain) Chain { + return c.Append(chain.hooks...) +} diff --git a/ent/db/ledgeraccount.go b/ent/db/ledgeraccount.go new file mode 100644 index 0000000000000000000000000000000000000000..735e1c96dafd8c1348aaef7d5743500ba206a3e0 --- /dev/null +++ b/ent/db/ledgeraccount.go @@ -0,0 +1,227 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/ledgeraccount" + "github.com/openmeterio/openmeter/openmeter/ledger" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerAccount is the model entity for the LedgerAccount schema. +type LedgerAccount 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"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,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"` + // AccountType holds the value of the "account_type" field. + AccountType ledger.AccountType `json:"account_type,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the LedgerAccountQuery when eager-loading is set. + Edges LedgerAccountEdges `json:"edges"` + selectValues sql.SelectValues +} + +// LedgerAccountEdges holds the relations/edges for other nodes in the graph. +type LedgerAccountEdges struct { + // SubAccounts holds the value of the sub_accounts edge. + SubAccounts []*LedgerSubAccount `json:"sub_accounts,omitempty"` + // SubAccountRoutes holds the value of the sub_account_routes edge. + SubAccountRoutes []*LedgerSubAccountRoute `json:"sub_account_routes,omitempty"` + // CustomerAccounts holds the value of the customer_accounts edge. + CustomerAccounts []*LedgerCustomerAccount `json:"customer_accounts,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [3]bool +} + +// SubAccountsOrErr returns the SubAccounts value or an error if the edge +// was not loaded in eager-loading. +func (e LedgerAccountEdges) SubAccountsOrErr() ([]*LedgerSubAccount, error) { + if e.loadedTypes[0] { + return e.SubAccounts, nil + } + return nil, &NotLoadedError{edge: "sub_accounts"} +} + +// SubAccountRoutesOrErr returns the SubAccountRoutes value or an error if the edge +// was not loaded in eager-loading. +func (e LedgerAccountEdges) SubAccountRoutesOrErr() ([]*LedgerSubAccountRoute, error) { + if e.loadedTypes[1] { + return e.SubAccountRoutes, nil + } + return nil, &NotLoadedError{edge: "sub_account_routes"} +} + +// CustomerAccountsOrErr returns the CustomerAccounts value or an error if the edge +// was not loaded in eager-loading. +func (e LedgerAccountEdges) CustomerAccountsOrErr() ([]*LedgerCustomerAccount, error) { + if e.loadedTypes[2] { + return e.CustomerAccounts, nil + } + return nil, &NotLoadedError{edge: "customer_accounts"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LedgerAccount) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case ledgeraccount.FieldAnnotations: + values[i] = new([]byte) + case ledgeraccount.FieldID, ledgeraccount.FieldNamespace, ledgeraccount.FieldAccountType: + values[i] = new(sql.NullString) + case ledgeraccount.FieldCreatedAt, ledgeraccount.FieldUpdatedAt, ledgeraccount.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 LedgerAccount fields. +func (_m *LedgerAccount) 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 ledgeraccount.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 ledgeraccount.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 ledgeraccount.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 ledgeraccount.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 ledgeraccount.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 ledgeraccount.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 ledgeraccount.FieldAccountType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field account_type", values[i]) + } else if value.Valid { + _m.AccountType = ledger.AccountType(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 LedgerAccount. +// This includes values selected through modifiers, order, etc. +func (_m *LedgerAccount) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QuerySubAccounts queries the "sub_accounts" edge of the LedgerAccount entity. +func (_m *LedgerAccount) QuerySubAccounts() *LedgerSubAccountQuery { + return NewLedgerAccountClient(_m.config).QuerySubAccounts(_m) +} + +// QuerySubAccountRoutes queries the "sub_account_routes" edge of the LedgerAccount entity. +func (_m *LedgerAccount) QuerySubAccountRoutes() *LedgerSubAccountRouteQuery { + return NewLedgerAccountClient(_m.config).QuerySubAccountRoutes(_m) +} + +// QueryCustomerAccounts queries the "customer_accounts" edge of the LedgerAccount entity. +func (_m *LedgerAccount) QueryCustomerAccounts() *LedgerCustomerAccountQuery { + return NewLedgerAccountClient(_m.config).QueryCustomerAccounts(_m) +} + +// Update returns a builder for updating this LedgerAccount. +// Note that you need to call LedgerAccount.Unwrap() before calling this method if this LedgerAccount +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *LedgerAccount) Update() *LedgerAccountUpdateOne { + return NewLedgerAccountClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the LedgerAccount 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 *LedgerAccount) Unwrap() *LedgerAccount { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: LedgerAccount is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *LedgerAccount) String() string { + var builder strings.Builder + builder.WriteString("LedgerAccount(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + 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("account_type=") + builder.WriteString(fmt.Sprintf("%v", _m.AccountType)) + builder.WriteByte(')') + return builder.String() +} + +// LedgerAccounts is a parsable slice of LedgerAccount. +type LedgerAccounts []*LedgerAccount diff --git a/ent/db/ledgeraccount/ledgeraccount.go b/ent/db/ledgeraccount/ledgeraccount.go new file mode 100644 index 0000000000000000000000000000000000000000..936b10823569859e02bd21e633661e6ce62dca58 --- /dev/null +++ b/ent/db/ledgeraccount/ledgeraccount.go @@ -0,0 +1,188 @@ +// Code generated by ent, DO NOT EDIT. + +package ledgeraccount + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the ledgeraccount type in the database. + Label = "ledger_account" + // 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" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // 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" + // FieldAccountType holds the string denoting the account_type field in the database. + FieldAccountType = "account_type" + // EdgeSubAccounts holds the string denoting the sub_accounts edge name in mutations. + EdgeSubAccounts = "sub_accounts" + // EdgeSubAccountRoutes holds the string denoting the sub_account_routes edge name in mutations. + EdgeSubAccountRoutes = "sub_account_routes" + // EdgeCustomerAccounts holds the string denoting the customer_accounts edge name in mutations. + EdgeCustomerAccounts = "customer_accounts" + // Table holds the table name of the ledgeraccount in the database. + Table = "ledger_accounts" + // SubAccountsTable is the table that holds the sub_accounts relation/edge. + SubAccountsTable = "ledger_sub_accounts" + // SubAccountsInverseTable is the table name for the LedgerSubAccount entity. + // It exists in this package in order to avoid circular dependency with the "ledgersubaccount" package. + SubAccountsInverseTable = "ledger_sub_accounts" + // SubAccountsColumn is the table column denoting the sub_accounts relation/edge. + SubAccountsColumn = "account_id" + // SubAccountRoutesTable is the table that holds the sub_account_routes relation/edge. + SubAccountRoutesTable = "ledger_sub_account_routes" + // SubAccountRoutesInverseTable is the table name for the LedgerSubAccountRoute entity. + // It exists in this package in order to avoid circular dependency with the "ledgersubaccountroute" package. + SubAccountRoutesInverseTable = "ledger_sub_account_routes" + // SubAccountRoutesColumn is the table column denoting the sub_account_routes relation/edge. + SubAccountRoutesColumn = "account_id" + // CustomerAccountsTable is the table that holds the customer_accounts relation/edge. + CustomerAccountsTable = "ledger_customer_accounts" + // CustomerAccountsInverseTable is the table name for the LedgerCustomerAccount entity. + // It exists in this package in order to avoid circular dependency with the "ledgercustomeraccount" package. + CustomerAccountsInverseTable = "ledger_customer_accounts" + // CustomerAccountsColumn is the table column denoting the customer_accounts relation/edge. + CustomerAccountsColumn = "account_id" +) + +// Columns holds all SQL columns for ledgeraccount fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldAnnotations, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldAccountType, +} + +// 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 +) + +// OrderOption defines the ordering options for the LedgerAccount 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() +} + +// ByAccountType orders the results by the account_type field. +func ByAccountType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAccountType, opts...).ToFunc() +} + +// BySubAccountsCount orders the results by sub_accounts count. +func BySubAccountsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newSubAccountsStep(), opts...) + } +} + +// BySubAccounts orders the results by sub_accounts terms. +func BySubAccounts(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubAccountsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// BySubAccountRoutesCount orders the results by sub_account_routes count. +func BySubAccountRoutesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newSubAccountRoutesStep(), opts...) + } +} + +// BySubAccountRoutes orders the results by sub_account_routes terms. +func BySubAccountRoutes(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubAccountRoutesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByCustomerAccountsCount orders the results by customer_accounts count. +func ByCustomerAccountsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newCustomerAccountsStep(), opts...) + } +} + +// ByCustomerAccounts orders the results by customer_accounts terms. +func ByCustomerAccounts(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCustomerAccountsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newSubAccountsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SubAccountsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SubAccountsTable, SubAccountsColumn), + ) +} +func newSubAccountRoutesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SubAccountRoutesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SubAccountRoutesTable, SubAccountRoutesColumn), + ) +} +func newCustomerAccountsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CustomerAccountsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, CustomerAccountsTable, CustomerAccountsColumn), + ) +} diff --git a/ent/db/ledgeraccount/where.go b/ent/db/ledgeraccount/where.go new file mode 100644 index 0000000000000000000000000000000000000000..15423ba3ed7cdd73fa55261132797cdf9b64e6ab --- /dev/null +++ b/ent/db/ledgeraccount/where.go @@ -0,0 +1,466 @@ +// Code generated by ent, DO NOT EDIT. + +package ledgeraccount + +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/ledger" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.LedgerAccount { + return predicate.LedgerAccount(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.LedgerAccount { + return predicate.LedgerAccount(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.LedgerAccount { + return predicate.LedgerAccount(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.LedgerAccount { + return predicate.LedgerAccount(sql.FieldEQ(FieldDeletedAt, v)) +} + +// AccountType applies equality check predicate on the "account_type" field. It's identical to AccountTypeEQ. +func AccountType(v ledger.AccountType) predicate.LedgerAccount { + vc := string(v) + return predicate.LedgerAccount(sql.FieldEQ(FieldAccountType, vc)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldContainsFold(FieldNamespace, v)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldNotNull(FieldAnnotations)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.LedgerAccount { + return predicate.LedgerAccount(sql.FieldNotNull(FieldDeletedAt)) +} + +// AccountTypeEQ applies the EQ predicate on the "account_type" field. +func AccountTypeEQ(v ledger.AccountType) predicate.LedgerAccount { + vc := string(v) + return predicate.LedgerAccount(sql.FieldEQ(FieldAccountType, vc)) +} + +// AccountTypeNEQ applies the NEQ predicate on the "account_type" field. +func AccountTypeNEQ(v ledger.AccountType) predicate.LedgerAccount { + vc := string(v) + return predicate.LedgerAccount(sql.FieldNEQ(FieldAccountType, vc)) +} + +// AccountTypeIn applies the In predicate on the "account_type" field. +func AccountTypeIn(vs ...ledger.AccountType) predicate.LedgerAccount { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.LedgerAccount(sql.FieldIn(FieldAccountType, v...)) +} + +// AccountTypeNotIn applies the NotIn predicate on the "account_type" field. +func AccountTypeNotIn(vs ...ledger.AccountType) predicate.LedgerAccount { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.LedgerAccount(sql.FieldNotIn(FieldAccountType, v...)) +} + +// AccountTypeGT applies the GT predicate on the "account_type" field. +func AccountTypeGT(v ledger.AccountType) predicate.LedgerAccount { + vc := string(v) + return predicate.LedgerAccount(sql.FieldGT(FieldAccountType, vc)) +} + +// AccountTypeGTE applies the GTE predicate on the "account_type" field. +func AccountTypeGTE(v ledger.AccountType) predicate.LedgerAccount { + vc := string(v) + return predicate.LedgerAccount(sql.FieldGTE(FieldAccountType, vc)) +} + +// AccountTypeLT applies the LT predicate on the "account_type" field. +func AccountTypeLT(v ledger.AccountType) predicate.LedgerAccount { + vc := string(v) + return predicate.LedgerAccount(sql.FieldLT(FieldAccountType, vc)) +} + +// AccountTypeLTE applies the LTE predicate on the "account_type" field. +func AccountTypeLTE(v ledger.AccountType) predicate.LedgerAccount { + vc := string(v) + return predicate.LedgerAccount(sql.FieldLTE(FieldAccountType, vc)) +} + +// AccountTypeContains applies the Contains predicate on the "account_type" field. +func AccountTypeContains(v ledger.AccountType) predicate.LedgerAccount { + vc := string(v) + return predicate.LedgerAccount(sql.FieldContains(FieldAccountType, vc)) +} + +// AccountTypeHasPrefix applies the HasPrefix predicate on the "account_type" field. +func AccountTypeHasPrefix(v ledger.AccountType) predicate.LedgerAccount { + vc := string(v) + return predicate.LedgerAccount(sql.FieldHasPrefix(FieldAccountType, vc)) +} + +// AccountTypeHasSuffix applies the HasSuffix predicate on the "account_type" field. +func AccountTypeHasSuffix(v ledger.AccountType) predicate.LedgerAccount { + vc := string(v) + return predicate.LedgerAccount(sql.FieldHasSuffix(FieldAccountType, vc)) +} + +// AccountTypeEqualFold applies the EqualFold predicate on the "account_type" field. +func AccountTypeEqualFold(v ledger.AccountType) predicate.LedgerAccount { + vc := string(v) + return predicate.LedgerAccount(sql.FieldEqualFold(FieldAccountType, vc)) +} + +// AccountTypeContainsFold applies the ContainsFold predicate on the "account_type" field. +func AccountTypeContainsFold(v ledger.AccountType) predicate.LedgerAccount { + vc := string(v) + return predicate.LedgerAccount(sql.FieldContainsFold(FieldAccountType, vc)) +} + +// HasSubAccounts applies the HasEdge predicate on the "sub_accounts" edge. +func HasSubAccounts() predicate.LedgerAccount { + return predicate.LedgerAccount(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SubAccountsTable, SubAccountsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubAccountsWith applies the HasEdge predicate on the "sub_accounts" edge with a given conditions (other predicates). +func HasSubAccountsWith(preds ...predicate.LedgerSubAccount) predicate.LedgerAccount { + return predicate.LedgerAccount(func(s *sql.Selector) { + step := newSubAccountsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSubAccountRoutes applies the HasEdge predicate on the "sub_account_routes" edge. +func HasSubAccountRoutes() predicate.LedgerAccount { + return predicate.LedgerAccount(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SubAccountRoutesTable, SubAccountRoutesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubAccountRoutesWith applies the HasEdge predicate on the "sub_account_routes" edge with a given conditions (other predicates). +func HasSubAccountRoutesWith(preds ...predicate.LedgerSubAccountRoute) predicate.LedgerAccount { + return predicate.LedgerAccount(func(s *sql.Selector) { + step := newSubAccountRoutesStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasCustomerAccounts applies the HasEdge predicate on the "customer_accounts" edge. +func HasCustomerAccounts() predicate.LedgerAccount { + return predicate.LedgerAccount(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, CustomerAccountsTable, CustomerAccountsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCustomerAccountsWith applies the HasEdge predicate on the "customer_accounts" edge with a given conditions (other predicates). +func HasCustomerAccountsWith(preds ...predicate.LedgerCustomerAccount) predicate.LedgerAccount { + return predicate.LedgerAccount(func(s *sql.Selector) { + step := newCustomerAccountsStep() + 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.LedgerAccount) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LedgerAccount) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LedgerAccount) predicate.LedgerAccount { + return predicate.LedgerAccount(sql.NotPredicates(p)) +} diff --git a/ent/db/ledgeraccount_create.go b/ent/db/ledgeraccount_create.go new file mode 100644 index 0000000000000000000000000000000000000000..0deaa0cd08d58d83e5f7aa112718eb5f0e41d9cb --- /dev/null +++ b/ent/db/ledgeraccount_create.go @@ -0,0 +1,845 @@ +// 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/ledgeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgercustomeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccountroute" + "github.com/openmeterio/openmeter/openmeter/ledger" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerAccountCreate is the builder for creating a LedgerAccount entity. +type LedgerAccountCreate struct { + config + mutation *LedgerAccountMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *LedgerAccountCreate) SetNamespace(v string) *LedgerAccountCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *LedgerAccountCreate) SetAnnotations(v models.Annotations) *LedgerAccountCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *LedgerAccountCreate) SetCreatedAt(v time.Time) *LedgerAccountCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *LedgerAccountCreate) SetNillableCreatedAt(v *time.Time) *LedgerAccountCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *LedgerAccountCreate) SetUpdatedAt(v time.Time) *LedgerAccountCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *LedgerAccountCreate) SetNillableUpdatedAt(v *time.Time) *LedgerAccountCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *LedgerAccountCreate) SetDeletedAt(v time.Time) *LedgerAccountCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *LedgerAccountCreate) SetNillableDeletedAt(v *time.Time) *LedgerAccountCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetAccountType sets the "account_type" field. +func (_c *LedgerAccountCreate) SetAccountType(v ledger.AccountType) *LedgerAccountCreate { + _c.mutation.SetAccountType(v) + return _c +} + +// SetID sets the "id" field. +func (_c *LedgerAccountCreate) SetID(v string) *LedgerAccountCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *LedgerAccountCreate) SetNillableID(v *string) *LedgerAccountCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// AddSubAccountIDs adds the "sub_accounts" edge to the LedgerSubAccount entity by IDs. +func (_c *LedgerAccountCreate) AddSubAccountIDs(ids ...string) *LedgerAccountCreate { + _c.mutation.AddSubAccountIDs(ids...) + return _c +} + +// AddSubAccounts adds the "sub_accounts" edges to the LedgerSubAccount entity. +func (_c *LedgerAccountCreate) AddSubAccounts(v ...*LedgerSubAccount) *LedgerAccountCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddSubAccountIDs(ids...) +} + +// AddSubAccountRouteIDs adds the "sub_account_routes" edge to the LedgerSubAccountRoute entity by IDs. +func (_c *LedgerAccountCreate) AddSubAccountRouteIDs(ids ...string) *LedgerAccountCreate { + _c.mutation.AddSubAccountRouteIDs(ids...) + return _c +} + +// AddSubAccountRoutes adds the "sub_account_routes" edges to the LedgerSubAccountRoute entity. +func (_c *LedgerAccountCreate) AddSubAccountRoutes(v ...*LedgerSubAccountRoute) *LedgerAccountCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddSubAccountRouteIDs(ids...) +} + +// AddCustomerAccountIDs adds the "customer_accounts" edge to the LedgerCustomerAccount entity by IDs. +func (_c *LedgerAccountCreate) AddCustomerAccountIDs(ids ...string) *LedgerAccountCreate { + _c.mutation.AddCustomerAccountIDs(ids...) + return _c +} + +// AddCustomerAccounts adds the "customer_accounts" edges to the LedgerCustomerAccount entity. +func (_c *LedgerAccountCreate) AddCustomerAccounts(v ...*LedgerCustomerAccount) *LedgerAccountCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddCustomerAccountIDs(ids...) +} + +// Mutation returns the LedgerAccountMutation object of the builder. +func (_c *LedgerAccountCreate) Mutation() *LedgerAccountMutation { + return _c.mutation +} + +// Save creates the LedgerAccount in the database. +func (_c *LedgerAccountCreate) Save(ctx context.Context) (*LedgerAccount, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *LedgerAccountCreate) SaveX(ctx context.Context) *LedgerAccount { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LedgerAccountCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LedgerAccountCreate) 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 *LedgerAccountCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := ledgeraccount.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := ledgeraccount.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := ledgeraccount.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *LedgerAccountCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "LedgerAccount.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := ledgeraccount.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "LedgerAccount.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "LedgerAccount.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "LedgerAccount.updated_at"`)} + } + if _, ok := _c.mutation.AccountType(); !ok { + return &ValidationError{Name: "account_type", err: errors.New(`db: missing required field "LedgerAccount.account_type"`)} + } + if v, ok := _c.mutation.AccountType(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "account_type", err: fmt.Errorf(`db: validator failed for field "LedgerAccount.account_type": %w`, err)} + } + } + return nil +} + +func (_c *LedgerAccountCreate) sqlSave(ctx context.Context) (*LedgerAccount, 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 LedgerAccount.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *LedgerAccountCreate) createSpec() (*LedgerAccount, *sqlgraph.CreateSpec) { + var ( + _node = &LedgerAccount{config: _c.config} + _spec = sqlgraph.NewCreateSpec(ledgeraccount.Table, sqlgraph.NewFieldSpec(ledgeraccount.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(ledgeraccount.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(ledgeraccount.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(ledgeraccount.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(ledgeraccount.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(ledgeraccount.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.AccountType(); ok { + _spec.SetField(ledgeraccount.FieldAccountType, field.TypeString, value) + _node.AccountType = value + } + if nodes := _c.mutation.SubAccountsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.SubAccountsTable, + Columns: []string{ledgeraccount.SubAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccount.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.SubAccountRoutesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.SubAccountRoutesTable, + Columns: []string{ledgeraccount.SubAccountRoutesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccountroute.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.CustomerAccountsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.CustomerAccountsTable, + Columns: []string{ledgeraccount.CustomerAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgercustomeraccount.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.LedgerAccount.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.LedgerAccountUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *LedgerAccountCreate) OnConflict(opts ...sql.ConflictOption) *LedgerAccountUpsertOne { + _c.conflict = opts + return &LedgerAccountUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.LedgerAccount.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *LedgerAccountCreate) OnConflictColumns(columns ...string) *LedgerAccountUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &LedgerAccountUpsertOne{ + create: _c, + } +} + +type ( + // LedgerAccountUpsertOne is the builder for "upsert"-ing + // one LedgerAccount node. + LedgerAccountUpsertOne struct { + create *LedgerAccountCreate + } + + // LedgerAccountUpsert is the "OnConflict" setter. + LedgerAccountUpsert struct { + *sql.UpdateSet + } +) + +// SetAnnotations sets the "annotations" field. +func (u *LedgerAccountUpsert) SetAnnotations(v models.Annotations) *LedgerAccountUpsert { + u.Set(ledgeraccount.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerAccountUpsert) UpdateAnnotations() *LedgerAccountUpsert { + u.SetExcluded(ledgeraccount.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerAccountUpsert) ClearAnnotations() *LedgerAccountUpsert { + u.SetNull(ledgeraccount.FieldAnnotations) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerAccountUpsert) SetUpdatedAt(v time.Time) *LedgerAccountUpsert { + u.Set(ledgeraccount.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerAccountUpsert) UpdateUpdatedAt() *LedgerAccountUpsert { + u.SetExcluded(ledgeraccount.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerAccountUpsert) SetDeletedAt(v time.Time) *LedgerAccountUpsert { + u.Set(ledgeraccount.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerAccountUpsert) UpdateDeletedAt() *LedgerAccountUpsert { + u.SetExcluded(ledgeraccount.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerAccountUpsert) ClearDeletedAt() *LedgerAccountUpsert { + u.SetNull(ledgeraccount.FieldDeletedAt) + 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.LedgerAccount.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(ledgeraccount.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LedgerAccountUpsertOne) UpdateNewValues() *LedgerAccountUpsertOne { + 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(ledgeraccount.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(ledgeraccount.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(ledgeraccount.FieldCreatedAt) + } + if _, exists := u.create.mutation.AccountType(); exists { + s.SetIgnore(ledgeraccount.FieldAccountType) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.LedgerAccount.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LedgerAccountUpsertOne) Ignore() *LedgerAccountUpsertOne { + 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 *LedgerAccountUpsertOne) DoNothing() *LedgerAccountUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LedgerAccountCreate.OnConflict +// documentation for more info. +func (u *LedgerAccountUpsertOne) Update(set func(*LedgerAccountUpsert)) *LedgerAccountUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LedgerAccountUpsert{UpdateSet: update}) + })) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *LedgerAccountUpsertOne) SetAnnotations(v models.Annotations) *LedgerAccountUpsertOne { + return u.Update(func(s *LedgerAccountUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerAccountUpsertOne) UpdateAnnotations() *LedgerAccountUpsertOne { + return u.Update(func(s *LedgerAccountUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerAccountUpsertOne) ClearAnnotations() *LedgerAccountUpsertOne { + return u.Update(func(s *LedgerAccountUpsert) { + s.ClearAnnotations() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerAccountUpsertOne) SetUpdatedAt(v time.Time) *LedgerAccountUpsertOne { + return u.Update(func(s *LedgerAccountUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerAccountUpsertOne) UpdateUpdatedAt() *LedgerAccountUpsertOne { + return u.Update(func(s *LedgerAccountUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerAccountUpsertOne) SetDeletedAt(v time.Time) *LedgerAccountUpsertOne { + return u.Update(func(s *LedgerAccountUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerAccountUpsertOne) UpdateDeletedAt() *LedgerAccountUpsertOne { + return u.Update(func(s *LedgerAccountUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerAccountUpsertOne) ClearDeletedAt() *LedgerAccountUpsertOne { + return u.Update(func(s *LedgerAccountUpsert) { + s.ClearDeletedAt() + }) +} + +// Exec executes the query. +func (u *LedgerAccountUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for LedgerAccountCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LedgerAccountUpsertOne) 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 *LedgerAccountUpsertOne) 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: LedgerAccountUpsertOne.ID is not supported by MySQL driver. Use LedgerAccountUpsertOne.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 *LedgerAccountUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// LedgerAccountCreateBulk is the builder for creating many LedgerAccount entities in bulk. +type LedgerAccountCreateBulk struct { + config + err error + builders []*LedgerAccountCreate + conflict []sql.ConflictOption +} + +// Save creates the LedgerAccount entities in the database. +func (_c *LedgerAccountCreateBulk) Save(ctx context.Context) ([]*LedgerAccount, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*LedgerAccount, 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.(*LedgerAccountMutation) + 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 *LedgerAccountCreateBulk) SaveX(ctx context.Context) []*LedgerAccount { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LedgerAccountCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LedgerAccountCreateBulk) 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.LedgerAccount.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.LedgerAccountUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *LedgerAccountCreateBulk) OnConflict(opts ...sql.ConflictOption) *LedgerAccountUpsertBulk { + _c.conflict = opts + return &LedgerAccountUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.LedgerAccount.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *LedgerAccountCreateBulk) OnConflictColumns(columns ...string) *LedgerAccountUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &LedgerAccountUpsertBulk{ + create: _c, + } +} + +// LedgerAccountUpsertBulk is the builder for "upsert"-ing +// a bulk of LedgerAccount nodes. +type LedgerAccountUpsertBulk struct { + create *LedgerAccountCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.LedgerAccount.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(ledgeraccount.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LedgerAccountUpsertBulk) UpdateNewValues() *LedgerAccountUpsertBulk { + 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(ledgeraccount.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(ledgeraccount.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(ledgeraccount.FieldCreatedAt) + } + if _, exists := b.mutation.AccountType(); exists { + s.SetIgnore(ledgeraccount.FieldAccountType) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.LedgerAccount.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LedgerAccountUpsertBulk) Ignore() *LedgerAccountUpsertBulk { + 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 *LedgerAccountUpsertBulk) DoNothing() *LedgerAccountUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LedgerAccountCreateBulk.OnConflict +// documentation for more info. +func (u *LedgerAccountUpsertBulk) Update(set func(*LedgerAccountUpsert)) *LedgerAccountUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LedgerAccountUpsert{UpdateSet: update}) + })) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *LedgerAccountUpsertBulk) SetAnnotations(v models.Annotations) *LedgerAccountUpsertBulk { + return u.Update(func(s *LedgerAccountUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerAccountUpsertBulk) UpdateAnnotations() *LedgerAccountUpsertBulk { + return u.Update(func(s *LedgerAccountUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerAccountUpsertBulk) ClearAnnotations() *LedgerAccountUpsertBulk { + return u.Update(func(s *LedgerAccountUpsert) { + s.ClearAnnotations() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerAccountUpsertBulk) SetUpdatedAt(v time.Time) *LedgerAccountUpsertBulk { + return u.Update(func(s *LedgerAccountUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerAccountUpsertBulk) UpdateUpdatedAt() *LedgerAccountUpsertBulk { + return u.Update(func(s *LedgerAccountUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerAccountUpsertBulk) SetDeletedAt(v time.Time) *LedgerAccountUpsertBulk { + return u.Update(func(s *LedgerAccountUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerAccountUpsertBulk) UpdateDeletedAt() *LedgerAccountUpsertBulk { + return u.Update(func(s *LedgerAccountUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerAccountUpsertBulk) ClearDeletedAt() *LedgerAccountUpsertBulk { + return u.Update(func(s *LedgerAccountUpsert) { + s.ClearDeletedAt() + }) +} + +// Exec executes the query. +func (u *LedgerAccountUpsertBulk) 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 LedgerAccountCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for LedgerAccountCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LedgerAccountUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/ledgeraccount_delete.go b/ent/db/ledgeraccount_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..bede81293d565d8f151f210cfc033aa15669f368 --- /dev/null +++ b/ent/db/ledgeraccount_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/ledgeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LedgerAccountDelete is the builder for deleting a LedgerAccount entity. +type LedgerAccountDelete struct { + config + hooks []Hook + mutation *LedgerAccountMutation +} + +// Where appends a list predicates to the LedgerAccountDelete builder. +func (_d *LedgerAccountDelete) Where(ps ...predicate.LedgerAccount) *LedgerAccountDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *LedgerAccountDelete) 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 *LedgerAccountDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *LedgerAccountDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(ledgeraccount.Table, sqlgraph.NewFieldSpec(ledgeraccount.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 +} + +// LedgerAccountDeleteOne is the builder for deleting a single LedgerAccount entity. +type LedgerAccountDeleteOne struct { + _d *LedgerAccountDelete +} + +// Where appends a list predicates to the LedgerAccountDelete builder. +func (_d *LedgerAccountDeleteOne) Where(ps ...predicate.LedgerAccount) *LedgerAccountDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *LedgerAccountDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{ledgeraccount.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *LedgerAccountDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/ledgeraccount_query.go b/ent/db/ledgeraccount_query.go new file mode 100644 index 0000000000000000000000000000000000000000..a751976d8504f145515b5a5f4e6702c7f031c867 --- /dev/null +++ b/ent/db/ledgeraccount_query.go @@ -0,0 +1,795 @@ +// 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/ledgeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgercustomeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccountroute" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LedgerAccountQuery is the builder for querying LedgerAccount entities. +type LedgerAccountQuery struct { + config + ctx *QueryContext + order []ledgeraccount.OrderOption + inters []Interceptor + predicates []predicate.LedgerAccount + withSubAccounts *LedgerSubAccountQuery + withSubAccountRoutes *LedgerSubAccountRouteQuery + withCustomerAccounts *LedgerCustomerAccountQuery + 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 LedgerAccountQuery builder. +func (_q *LedgerAccountQuery) Where(ps ...predicate.LedgerAccount) *LedgerAccountQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *LedgerAccountQuery) Limit(limit int) *LedgerAccountQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *LedgerAccountQuery) Offset(offset int) *LedgerAccountQuery { + _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 *LedgerAccountQuery) Unique(unique bool) *LedgerAccountQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *LedgerAccountQuery) Order(o ...ledgeraccount.OrderOption) *LedgerAccountQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QuerySubAccounts chains the current query on the "sub_accounts" edge. +func (_q *LedgerAccountQuery) QuerySubAccounts() *LedgerSubAccountQuery { + query := (&LedgerSubAccountClient{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(ledgeraccount.Table, ledgeraccount.FieldID, selector), + sqlgraph.To(ledgersubaccount.Table, ledgersubaccount.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgeraccount.SubAccountsTable, ledgeraccount.SubAccountsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySubAccountRoutes chains the current query on the "sub_account_routes" edge. +func (_q *LedgerAccountQuery) QuerySubAccountRoutes() *LedgerSubAccountRouteQuery { + query := (&LedgerSubAccountRouteClient{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(ledgeraccount.Table, ledgeraccount.FieldID, selector), + sqlgraph.To(ledgersubaccountroute.Table, ledgersubaccountroute.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgeraccount.SubAccountRoutesTable, ledgeraccount.SubAccountRoutesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCustomerAccounts chains the current query on the "customer_accounts" edge. +func (_q *LedgerAccountQuery) QueryCustomerAccounts() *LedgerCustomerAccountQuery { + query := (&LedgerCustomerAccountClient{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(ledgeraccount.Table, ledgeraccount.FieldID, selector), + sqlgraph.To(ledgercustomeraccount.Table, ledgercustomeraccount.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgeraccount.CustomerAccountsTable, ledgeraccount.CustomerAccountsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first LedgerAccount entity from the query. +// Returns a *NotFoundError when no LedgerAccount was found. +func (_q *LedgerAccountQuery) First(ctx context.Context) (*LedgerAccount, 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{ledgeraccount.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *LedgerAccountQuery) FirstX(ctx context.Context) *LedgerAccount { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LedgerAccount ID from the query. +// Returns a *NotFoundError when no LedgerAccount ID was found. +func (_q *LedgerAccountQuery) 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{ledgeraccount.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *LedgerAccountQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LedgerAccount entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one LedgerAccount entity is found. +// Returns a *NotFoundError when no LedgerAccount entities are found. +func (_q *LedgerAccountQuery) Only(ctx context.Context) (*LedgerAccount, 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{ledgeraccount.Label} + default: + return nil, &NotSingularError{ledgeraccount.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *LedgerAccountQuery) OnlyX(ctx context.Context) *LedgerAccount { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LedgerAccount ID in the query. +// Returns a *NotSingularError when more than one LedgerAccount ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *LedgerAccountQuery) 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{ledgeraccount.Label} + default: + err = &NotSingularError{ledgeraccount.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *LedgerAccountQuery) 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 LedgerAccounts. +func (_q *LedgerAccountQuery) All(ctx context.Context) ([]*LedgerAccount, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*LedgerAccount, *LedgerAccountQuery]() + return withInterceptors[[]*LedgerAccount](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *LedgerAccountQuery) AllX(ctx context.Context) []*LedgerAccount { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LedgerAccount IDs. +func (_q *LedgerAccountQuery) 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(ledgeraccount.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *LedgerAccountQuery) 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 *LedgerAccountQuery) 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[*LedgerAccountQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *LedgerAccountQuery) 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 *LedgerAccountQuery) 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 *LedgerAccountQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LedgerAccountQuery 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 *LedgerAccountQuery) Clone() *LedgerAccountQuery { + if _q == nil { + return nil + } + return &LedgerAccountQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]ledgeraccount.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.LedgerAccount{}, _q.predicates...), + withSubAccounts: _q.withSubAccounts.Clone(), + withSubAccountRoutes: _q.withSubAccountRoutes.Clone(), + withCustomerAccounts: _q.withCustomerAccounts.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithSubAccounts tells the query-builder to eager-load the nodes that are connected to +// the "sub_accounts" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerAccountQuery) WithSubAccounts(opts ...func(*LedgerSubAccountQuery)) *LedgerAccountQuery { + query := (&LedgerSubAccountClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSubAccounts = query + return _q +} + +// WithSubAccountRoutes tells the query-builder to eager-load the nodes that are connected to +// the "sub_account_routes" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerAccountQuery) WithSubAccountRoutes(opts ...func(*LedgerSubAccountRouteQuery)) *LedgerAccountQuery { + query := (&LedgerSubAccountRouteClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSubAccountRoutes = query + return _q +} + +// WithCustomerAccounts tells the query-builder to eager-load the nodes that are connected to +// the "customer_accounts" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerAccountQuery) WithCustomerAccounts(opts ...func(*LedgerCustomerAccountQuery)) *LedgerAccountQuery { + query := (&LedgerCustomerAccountClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCustomerAccounts = 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.LedgerAccount.Query(). +// GroupBy(ledgeraccount.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *LedgerAccountQuery) GroupBy(field string, fields ...string) *LedgerAccountGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &LedgerAccountGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = ledgeraccount.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.LedgerAccount.Query(). +// Select(ledgeraccount.FieldNamespace). +// Scan(ctx, &v) +func (_q *LedgerAccountQuery) Select(fields ...string) *LedgerAccountSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &LedgerAccountSelect{LedgerAccountQuery: _q} + sbuild.label = ledgeraccount.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a LedgerAccountSelect configured with the given aggregations. +func (_q *LedgerAccountQuery) Aggregate(fns ...AggregateFunc) *LedgerAccountSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *LedgerAccountQuery) 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 !ledgeraccount.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 *LedgerAccountQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*LedgerAccount, error) { + var ( + nodes = []*LedgerAccount{} + _spec = _q.querySpec() + loadedTypes = [3]bool{ + _q.withSubAccounts != nil, + _q.withSubAccountRoutes != nil, + _q.withCustomerAccounts != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*LedgerAccount).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &LedgerAccount{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.withSubAccounts; query != nil { + if err := _q.loadSubAccounts(ctx, query, nodes, + func(n *LedgerAccount) { n.Edges.SubAccounts = []*LedgerSubAccount{} }, + func(n *LedgerAccount, e *LedgerSubAccount) { n.Edges.SubAccounts = append(n.Edges.SubAccounts, e) }); err != nil { + return nil, err + } + } + if query := _q.withSubAccountRoutes; query != nil { + if err := _q.loadSubAccountRoutes(ctx, query, nodes, + func(n *LedgerAccount) { n.Edges.SubAccountRoutes = []*LedgerSubAccountRoute{} }, + func(n *LedgerAccount, e *LedgerSubAccountRoute) { + n.Edges.SubAccountRoutes = append(n.Edges.SubAccountRoutes, e) + }); err != nil { + return nil, err + } + } + if query := _q.withCustomerAccounts; query != nil { + if err := _q.loadCustomerAccounts(ctx, query, nodes, + func(n *LedgerAccount) { n.Edges.CustomerAccounts = []*LedgerCustomerAccount{} }, + func(n *LedgerAccount, e *LedgerCustomerAccount) { + n.Edges.CustomerAccounts = append(n.Edges.CustomerAccounts, e) + }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *LedgerAccountQuery) loadSubAccounts(ctx context.Context, query *LedgerSubAccountQuery, nodes []*LedgerAccount, init func(*LedgerAccount), assign func(*LedgerAccount, *LedgerSubAccount)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*LedgerAccount) + 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(ledgersubaccount.FieldAccountID) + } + query.Where(predicate.LedgerSubAccount(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(ledgeraccount.SubAccountsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.AccountID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "account_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *LedgerAccountQuery) loadSubAccountRoutes(ctx context.Context, query *LedgerSubAccountRouteQuery, nodes []*LedgerAccount, init func(*LedgerAccount), assign func(*LedgerAccount, *LedgerSubAccountRoute)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*LedgerAccount) + 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(ledgersubaccountroute.FieldAccountID) + } + query.Where(predicate.LedgerSubAccountRoute(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(ledgeraccount.SubAccountRoutesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.AccountID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "account_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *LedgerAccountQuery) loadCustomerAccounts(ctx context.Context, query *LedgerCustomerAccountQuery, nodes []*LedgerAccount, init func(*LedgerAccount), assign func(*LedgerAccount, *LedgerCustomerAccount)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*LedgerAccount) + 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(ledgercustomeraccount.FieldAccountID) + } + query.Where(predicate.LedgerCustomerAccount(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(ledgeraccount.CustomerAccountsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.AccountID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "account_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *LedgerAccountQuery) 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 *LedgerAccountQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(ledgeraccount.Table, ledgeraccount.Columns, sqlgraph.NewFieldSpec(ledgeraccount.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, ledgeraccount.FieldID) + for i := range fields { + if fields[i] != ledgeraccount.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 *LedgerAccountQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(ledgeraccount.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = ledgeraccount.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 *LedgerAccountQuery) ForUpdate(opts ...sql.LockOption) *LedgerAccountQuery { + 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 *LedgerAccountQuery) ForShare(opts ...sql.LockOption) *LedgerAccountQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// LedgerAccountGroupBy is the group-by builder for LedgerAccount entities. +type LedgerAccountGroupBy struct { + selector + build *LedgerAccountQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *LedgerAccountGroupBy) Aggregate(fns ...AggregateFunc) *LedgerAccountGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *LedgerAccountGroupBy) 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[*LedgerAccountQuery, *LedgerAccountGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *LedgerAccountGroupBy) sqlScan(ctx context.Context, root *LedgerAccountQuery, 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) +} + +// LedgerAccountSelect is the builder for selecting fields of LedgerAccount entities. +type LedgerAccountSelect struct { + *LedgerAccountQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *LedgerAccountSelect) Aggregate(fns ...AggregateFunc) *LedgerAccountSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *LedgerAccountSelect) 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[*LedgerAccountQuery, *LedgerAccountSelect](ctx, _s.LedgerAccountQuery, _s, _s.inters, v) +} + +func (_s *LedgerAccountSelect) sqlScan(ctx context.Context, root *LedgerAccountQuery, 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/ent/db/ledgeraccount_update.go b/ent/db/ledgeraccount_update.go new file mode 100644 index 0000000000000000000000000000000000000000..7f39a2d782138a76b08224fff9fa825932b95a9b --- /dev/null +++ b/ent/db/ledgeraccount_update.go @@ -0,0 +1,790 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/ledgeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgercustomeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccountroute" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerAccountUpdate is the builder for updating LedgerAccount entities. +type LedgerAccountUpdate struct { + config + hooks []Hook + mutation *LedgerAccountMutation +} + +// Where appends a list predicates to the LedgerAccountUpdate builder. +func (_u *LedgerAccountUpdate) Where(ps ...predicate.LedgerAccount) *LedgerAccountUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *LedgerAccountUpdate) SetAnnotations(v models.Annotations) *LedgerAccountUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *LedgerAccountUpdate) ClearAnnotations() *LedgerAccountUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *LedgerAccountUpdate) SetUpdatedAt(v time.Time) *LedgerAccountUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *LedgerAccountUpdate) SetDeletedAt(v time.Time) *LedgerAccountUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *LedgerAccountUpdate) SetNillableDeletedAt(v *time.Time) *LedgerAccountUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *LedgerAccountUpdate) ClearDeletedAt() *LedgerAccountUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// AddSubAccountIDs adds the "sub_accounts" edge to the LedgerSubAccount entity by IDs. +func (_u *LedgerAccountUpdate) AddSubAccountIDs(ids ...string) *LedgerAccountUpdate { + _u.mutation.AddSubAccountIDs(ids...) + return _u +} + +// AddSubAccounts adds the "sub_accounts" edges to the LedgerSubAccount entity. +func (_u *LedgerAccountUpdate) AddSubAccounts(v ...*LedgerSubAccount) *LedgerAccountUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSubAccountIDs(ids...) +} + +// AddSubAccountRouteIDs adds the "sub_account_routes" edge to the LedgerSubAccountRoute entity by IDs. +func (_u *LedgerAccountUpdate) AddSubAccountRouteIDs(ids ...string) *LedgerAccountUpdate { + _u.mutation.AddSubAccountRouteIDs(ids...) + return _u +} + +// AddSubAccountRoutes adds the "sub_account_routes" edges to the LedgerSubAccountRoute entity. +func (_u *LedgerAccountUpdate) AddSubAccountRoutes(v ...*LedgerSubAccountRoute) *LedgerAccountUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSubAccountRouteIDs(ids...) +} + +// AddCustomerAccountIDs adds the "customer_accounts" edge to the LedgerCustomerAccount entity by IDs. +func (_u *LedgerAccountUpdate) AddCustomerAccountIDs(ids ...string) *LedgerAccountUpdate { + _u.mutation.AddCustomerAccountIDs(ids...) + return _u +} + +// AddCustomerAccounts adds the "customer_accounts" edges to the LedgerCustomerAccount entity. +func (_u *LedgerAccountUpdate) AddCustomerAccounts(v ...*LedgerCustomerAccount) *LedgerAccountUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddCustomerAccountIDs(ids...) +} + +// Mutation returns the LedgerAccountMutation object of the builder. +func (_u *LedgerAccountUpdate) Mutation() *LedgerAccountMutation { + return _u.mutation +} + +// ClearSubAccounts clears all "sub_accounts" edges to the LedgerSubAccount entity. +func (_u *LedgerAccountUpdate) ClearSubAccounts() *LedgerAccountUpdate { + _u.mutation.ClearSubAccounts() + return _u +} + +// RemoveSubAccountIDs removes the "sub_accounts" edge to LedgerSubAccount entities by IDs. +func (_u *LedgerAccountUpdate) RemoveSubAccountIDs(ids ...string) *LedgerAccountUpdate { + _u.mutation.RemoveSubAccountIDs(ids...) + return _u +} + +// RemoveSubAccounts removes "sub_accounts" edges to LedgerSubAccount entities. +func (_u *LedgerAccountUpdate) RemoveSubAccounts(v ...*LedgerSubAccount) *LedgerAccountUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSubAccountIDs(ids...) +} + +// ClearSubAccountRoutes clears all "sub_account_routes" edges to the LedgerSubAccountRoute entity. +func (_u *LedgerAccountUpdate) ClearSubAccountRoutes() *LedgerAccountUpdate { + _u.mutation.ClearSubAccountRoutes() + return _u +} + +// RemoveSubAccountRouteIDs removes the "sub_account_routes" edge to LedgerSubAccountRoute entities by IDs. +func (_u *LedgerAccountUpdate) RemoveSubAccountRouteIDs(ids ...string) *LedgerAccountUpdate { + _u.mutation.RemoveSubAccountRouteIDs(ids...) + return _u +} + +// RemoveSubAccountRoutes removes "sub_account_routes" edges to LedgerSubAccountRoute entities. +func (_u *LedgerAccountUpdate) RemoveSubAccountRoutes(v ...*LedgerSubAccountRoute) *LedgerAccountUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSubAccountRouteIDs(ids...) +} + +// ClearCustomerAccounts clears all "customer_accounts" edges to the LedgerCustomerAccount entity. +func (_u *LedgerAccountUpdate) ClearCustomerAccounts() *LedgerAccountUpdate { + _u.mutation.ClearCustomerAccounts() + return _u +} + +// RemoveCustomerAccountIDs removes the "customer_accounts" edge to LedgerCustomerAccount entities by IDs. +func (_u *LedgerAccountUpdate) RemoveCustomerAccountIDs(ids ...string) *LedgerAccountUpdate { + _u.mutation.RemoveCustomerAccountIDs(ids...) + return _u +} + +// RemoveCustomerAccounts removes "customer_accounts" edges to LedgerCustomerAccount entities. +func (_u *LedgerAccountUpdate) RemoveCustomerAccounts(v ...*LedgerCustomerAccount) *LedgerAccountUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveCustomerAccountIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *LedgerAccountUpdate) 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 *LedgerAccountUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *LedgerAccountUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LedgerAccountUpdate) 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 *LedgerAccountUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := ledgeraccount.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +func (_u *LedgerAccountUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(ledgeraccount.Table, ledgeraccount.Columns, sqlgraph.NewFieldSpec(ledgeraccount.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.Annotations(); ok { + _spec.SetField(ledgeraccount.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(ledgeraccount.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(ledgeraccount.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(ledgeraccount.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(ledgeraccount.FieldDeletedAt, field.TypeTime) + } + if _u.mutation.SubAccountsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.SubAccountsTable, + Columns: []string{ledgeraccount.SubAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccount.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSubAccountsIDs(); len(nodes) > 0 && !_u.mutation.SubAccountsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.SubAccountsTable, + Columns: []string{ledgeraccount.SubAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccount.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.SubAccountsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.SubAccountsTable, + Columns: []string{ledgeraccount.SubAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccount.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.SubAccountRoutesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.SubAccountRoutesTable, + Columns: []string{ledgeraccount.SubAccountRoutesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccountroute.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSubAccountRoutesIDs(); len(nodes) > 0 && !_u.mutation.SubAccountRoutesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.SubAccountRoutesTable, + Columns: []string{ledgeraccount.SubAccountRoutesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccountroute.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.SubAccountRoutesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.SubAccountRoutesTable, + Columns: []string{ledgeraccount.SubAccountRoutesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccountroute.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.CustomerAccountsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.CustomerAccountsTable, + Columns: []string{ledgeraccount.CustomerAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgercustomeraccount.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedCustomerAccountsIDs(); len(nodes) > 0 && !_u.mutation.CustomerAccountsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.CustomerAccountsTable, + Columns: []string{ledgeraccount.CustomerAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgercustomeraccount.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.CustomerAccountsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.CustomerAccountsTable, + Columns: []string{ledgeraccount.CustomerAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgercustomeraccount.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{ledgeraccount.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// LedgerAccountUpdateOne is the builder for updating a single LedgerAccount entity. +type LedgerAccountUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LedgerAccountMutation +} + +// SetAnnotations sets the "annotations" field. +func (_u *LedgerAccountUpdateOne) SetAnnotations(v models.Annotations) *LedgerAccountUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *LedgerAccountUpdateOne) ClearAnnotations() *LedgerAccountUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *LedgerAccountUpdateOne) SetUpdatedAt(v time.Time) *LedgerAccountUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *LedgerAccountUpdateOne) SetDeletedAt(v time.Time) *LedgerAccountUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *LedgerAccountUpdateOne) SetNillableDeletedAt(v *time.Time) *LedgerAccountUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *LedgerAccountUpdateOne) ClearDeletedAt() *LedgerAccountUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// AddSubAccountIDs adds the "sub_accounts" edge to the LedgerSubAccount entity by IDs. +func (_u *LedgerAccountUpdateOne) AddSubAccountIDs(ids ...string) *LedgerAccountUpdateOne { + _u.mutation.AddSubAccountIDs(ids...) + return _u +} + +// AddSubAccounts adds the "sub_accounts" edges to the LedgerSubAccount entity. +func (_u *LedgerAccountUpdateOne) AddSubAccounts(v ...*LedgerSubAccount) *LedgerAccountUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSubAccountIDs(ids...) +} + +// AddSubAccountRouteIDs adds the "sub_account_routes" edge to the LedgerSubAccountRoute entity by IDs. +func (_u *LedgerAccountUpdateOne) AddSubAccountRouteIDs(ids ...string) *LedgerAccountUpdateOne { + _u.mutation.AddSubAccountRouteIDs(ids...) + return _u +} + +// AddSubAccountRoutes adds the "sub_account_routes" edges to the LedgerSubAccountRoute entity. +func (_u *LedgerAccountUpdateOne) AddSubAccountRoutes(v ...*LedgerSubAccountRoute) *LedgerAccountUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSubAccountRouteIDs(ids...) +} + +// AddCustomerAccountIDs adds the "customer_accounts" edge to the LedgerCustomerAccount entity by IDs. +func (_u *LedgerAccountUpdateOne) AddCustomerAccountIDs(ids ...string) *LedgerAccountUpdateOne { + _u.mutation.AddCustomerAccountIDs(ids...) + return _u +} + +// AddCustomerAccounts adds the "customer_accounts" edges to the LedgerCustomerAccount entity. +func (_u *LedgerAccountUpdateOne) AddCustomerAccounts(v ...*LedgerCustomerAccount) *LedgerAccountUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddCustomerAccountIDs(ids...) +} + +// Mutation returns the LedgerAccountMutation object of the builder. +func (_u *LedgerAccountUpdateOne) Mutation() *LedgerAccountMutation { + return _u.mutation +} + +// ClearSubAccounts clears all "sub_accounts" edges to the LedgerSubAccount entity. +func (_u *LedgerAccountUpdateOne) ClearSubAccounts() *LedgerAccountUpdateOne { + _u.mutation.ClearSubAccounts() + return _u +} + +// RemoveSubAccountIDs removes the "sub_accounts" edge to LedgerSubAccount entities by IDs. +func (_u *LedgerAccountUpdateOne) RemoveSubAccountIDs(ids ...string) *LedgerAccountUpdateOne { + _u.mutation.RemoveSubAccountIDs(ids...) + return _u +} + +// RemoveSubAccounts removes "sub_accounts" edges to LedgerSubAccount entities. +func (_u *LedgerAccountUpdateOne) RemoveSubAccounts(v ...*LedgerSubAccount) *LedgerAccountUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSubAccountIDs(ids...) +} + +// ClearSubAccountRoutes clears all "sub_account_routes" edges to the LedgerSubAccountRoute entity. +func (_u *LedgerAccountUpdateOne) ClearSubAccountRoutes() *LedgerAccountUpdateOne { + _u.mutation.ClearSubAccountRoutes() + return _u +} + +// RemoveSubAccountRouteIDs removes the "sub_account_routes" edge to LedgerSubAccountRoute entities by IDs. +func (_u *LedgerAccountUpdateOne) RemoveSubAccountRouteIDs(ids ...string) *LedgerAccountUpdateOne { + _u.mutation.RemoveSubAccountRouteIDs(ids...) + return _u +} + +// RemoveSubAccountRoutes removes "sub_account_routes" edges to LedgerSubAccountRoute entities. +func (_u *LedgerAccountUpdateOne) RemoveSubAccountRoutes(v ...*LedgerSubAccountRoute) *LedgerAccountUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSubAccountRouteIDs(ids...) +} + +// ClearCustomerAccounts clears all "customer_accounts" edges to the LedgerCustomerAccount entity. +func (_u *LedgerAccountUpdateOne) ClearCustomerAccounts() *LedgerAccountUpdateOne { + _u.mutation.ClearCustomerAccounts() + return _u +} + +// RemoveCustomerAccountIDs removes the "customer_accounts" edge to LedgerCustomerAccount entities by IDs. +func (_u *LedgerAccountUpdateOne) RemoveCustomerAccountIDs(ids ...string) *LedgerAccountUpdateOne { + _u.mutation.RemoveCustomerAccountIDs(ids...) + return _u +} + +// RemoveCustomerAccounts removes "customer_accounts" edges to LedgerCustomerAccount entities. +func (_u *LedgerAccountUpdateOne) RemoveCustomerAccounts(v ...*LedgerCustomerAccount) *LedgerAccountUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveCustomerAccountIDs(ids...) +} + +// Where appends a list predicates to the LedgerAccountUpdate builder. +func (_u *LedgerAccountUpdateOne) Where(ps ...predicate.LedgerAccount) *LedgerAccountUpdateOne { + _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 *LedgerAccountUpdateOne) Select(field string, fields ...string) *LedgerAccountUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated LedgerAccount entity. +func (_u *LedgerAccountUpdateOne) Save(ctx context.Context) (*LedgerAccount, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *LedgerAccountUpdateOne) SaveX(ctx context.Context) *LedgerAccount { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *LedgerAccountUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LedgerAccountUpdateOne) 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 *LedgerAccountUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := ledgeraccount.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +func (_u *LedgerAccountUpdateOne) sqlSave(ctx context.Context) (_node *LedgerAccount, err error) { + _spec := sqlgraph.NewUpdateSpec(ledgeraccount.Table, ledgeraccount.Columns, sqlgraph.NewFieldSpec(ledgeraccount.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "LedgerAccount.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, ledgeraccount.FieldID) + for _, f := range fields { + if !ledgeraccount.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != ledgeraccount.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.Annotations(); ok { + _spec.SetField(ledgeraccount.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(ledgeraccount.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(ledgeraccount.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(ledgeraccount.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(ledgeraccount.FieldDeletedAt, field.TypeTime) + } + if _u.mutation.SubAccountsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.SubAccountsTable, + Columns: []string{ledgeraccount.SubAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccount.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSubAccountsIDs(); len(nodes) > 0 && !_u.mutation.SubAccountsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.SubAccountsTable, + Columns: []string{ledgeraccount.SubAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccount.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.SubAccountsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.SubAccountsTable, + Columns: []string{ledgeraccount.SubAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccount.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.SubAccountRoutesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.SubAccountRoutesTable, + Columns: []string{ledgeraccount.SubAccountRoutesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccountroute.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSubAccountRoutesIDs(); len(nodes) > 0 && !_u.mutation.SubAccountRoutesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.SubAccountRoutesTable, + Columns: []string{ledgeraccount.SubAccountRoutesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccountroute.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.SubAccountRoutesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.SubAccountRoutesTable, + Columns: []string{ledgeraccount.SubAccountRoutesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccountroute.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.CustomerAccountsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.CustomerAccountsTable, + Columns: []string{ledgeraccount.CustomerAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgercustomeraccount.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedCustomerAccountsIDs(); len(nodes) > 0 && !_u.mutation.CustomerAccountsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.CustomerAccountsTable, + Columns: []string{ledgeraccount.CustomerAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgercustomeraccount.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.CustomerAccountsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgeraccount.CustomerAccountsTable, + Columns: []string{ledgeraccount.CustomerAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgercustomeraccount.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &LedgerAccount{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{ledgeraccount.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/ent/db/ledgerbreakagerecord.go b/ent/db/ledgerbreakagerecord.go new file mode 100644 index 0000000000000000000000000000000000000000..e7706562b8d40de6bab14abf94afdc0949b98edb --- /dev/null +++ b/ent/db/ledgerbreakagerecord.go @@ -0,0 +1,577 @@ +// 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/ledgerbreakagerecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgerentry" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransaction" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransactiongroup" + "github.com/openmeterio/openmeter/openmeter/ledger" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerBreakageRecord is the model entity for the LedgerBreakageRecord schema. +type LedgerBreakageRecord 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"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,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"` + // Kind holds the value of the "kind" field. + Kind ledger.BreakageKind `json:"kind,omitempty"` + // Amount holds the value of the "amount" field. + Amount alpacadecimal.Decimal `json:"amount,omitempty"` + // CustomerID holds the value of the "customer_id" field. + CustomerID string `json:"customer_id,omitempty"` + // Currency holds the value of the "currency" field. + Currency currencyx.Code `json:"currency,omitempty"` + // CreditPriority holds the value of the "credit_priority" field. + CreditPriority int `json:"credit_priority,omitempty"` + // ExpiresAt holds the value of the "expires_at" field. + ExpiresAt time.Time `json:"expires_at,omitempty"` + // SourceKind holds the value of the "source_kind" field. + SourceKind ledger.BreakageSourceKind `json:"source_kind,omitempty"` + // SourceChargeID holds the value of the "source_charge_id" field. + SourceChargeID *string `json:"source_charge_id,omitempty"` + // SourceTransactionGroupID holds the value of the "source_transaction_group_id" field. + SourceTransactionGroupID *string `json:"source_transaction_group_id,omitempty"` + // SourceTransactionID holds the value of the "source_transaction_id" field. + SourceTransactionID *string `json:"source_transaction_id,omitempty"` + // SourceEntryID holds the value of the "source_entry_id" field. + SourceEntryID *string `json:"source_entry_id,omitempty"` + // BreakageTransactionGroupID holds the value of the "breakage_transaction_group_id" field. + BreakageTransactionGroupID string `json:"breakage_transaction_group_id,omitempty"` + // BreakageTransactionID holds the value of the "breakage_transaction_id" field. + BreakageTransactionID string `json:"breakage_transaction_id,omitempty"` + // FboSubAccountID holds the value of the "fbo_sub_account_id" field. + FboSubAccountID string `json:"fbo_sub_account_id,omitempty"` + // BreakageSubAccountID holds the value of the "breakage_sub_account_id" field. + BreakageSubAccountID string `json:"breakage_sub_account_id,omitempty"` + // PlanID holds the value of the "plan_id" field. + PlanID *string `json:"plan_id,omitempty"` + // ReleaseID holds the value of the "release_id" field. + ReleaseID *string `json:"release_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the LedgerBreakageRecordQuery when eager-loading is set. + Edges LedgerBreakageRecordEdges `json:"edges"` + selectValues sql.SelectValues +} + +// LedgerBreakageRecordEdges holds the relations/edges for other nodes in the graph. +type LedgerBreakageRecordEdges struct { + // SourceTransactionGroup holds the value of the source_transaction_group edge. + SourceTransactionGroup *LedgerTransactionGroup `json:"source_transaction_group,omitempty"` + // SourceTransaction holds the value of the source_transaction edge. + SourceTransaction *LedgerTransaction `json:"source_transaction,omitempty"` + // SourceEntry holds the value of the source_entry edge. + SourceEntry *LedgerEntry `json:"source_entry,omitempty"` + // BreakageTransactionGroup holds the value of the breakage_transaction_group edge. + BreakageTransactionGroup *LedgerTransactionGroup `json:"breakage_transaction_group,omitempty"` + // BreakageTransaction holds the value of the breakage_transaction edge. + BreakageTransaction *LedgerTransaction `json:"breakage_transaction,omitempty"` + // FboSubAccount holds the value of the fbo_sub_account edge. + FboSubAccount *LedgerSubAccount `json:"fbo_sub_account,omitempty"` + // BreakageSubAccount holds the value of the breakage_sub_account edge. + BreakageSubAccount *LedgerSubAccount `json:"breakage_sub_account,omitempty"` + // PlannedReleases holds the value of the planned_releases edge. + PlannedReleases []*LedgerBreakageRecord `json:"planned_releases,omitempty"` + // ReleaseReopens holds the value of the release_reopens edge. + ReleaseReopens []*LedgerBreakageRecord `json:"release_reopens,omitempty"` + // Plan holds the value of the plan edge. + Plan *LedgerBreakageRecord `json:"plan,omitempty"` + // Release holds the value of the release edge. + Release *LedgerBreakageRecord `json:"release,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [11]bool +} + +// SourceTransactionGroupOrErr returns the SourceTransactionGroup value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e LedgerBreakageRecordEdges) SourceTransactionGroupOrErr() (*LedgerTransactionGroup, error) { + if e.SourceTransactionGroup != nil { + return e.SourceTransactionGroup, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: ledgertransactiongroup.Label} + } + return nil, &NotLoadedError{edge: "source_transaction_group"} +} + +// SourceTransactionOrErr returns the SourceTransaction value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e LedgerBreakageRecordEdges) SourceTransactionOrErr() (*LedgerTransaction, error) { + if e.SourceTransaction != nil { + return e.SourceTransaction, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: ledgertransaction.Label} + } + return nil, &NotLoadedError{edge: "source_transaction"} +} + +// SourceEntryOrErr returns the SourceEntry value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e LedgerBreakageRecordEdges) SourceEntryOrErr() (*LedgerEntry, error) { + if e.SourceEntry != nil { + return e.SourceEntry, nil + } else if e.loadedTypes[2] { + return nil, &NotFoundError{label: ledgerentry.Label} + } + return nil, &NotLoadedError{edge: "source_entry"} +} + +// BreakageTransactionGroupOrErr returns the BreakageTransactionGroup value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e LedgerBreakageRecordEdges) BreakageTransactionGroupOrErr() (*LedgerTransactionGroup, error) { + if e.BreakageTransactionGroup != nil { + return e.BreakageTransactionGroup, nil + } else if e.loadedTypes[3] { + return nil, &NotFoundError{label: ledgertransactiongroup.Label} + } + return nil, &NotLoadedError{edge: "breakage_transaction_group"} +} + +// BreakageTransactionOrErr returns the BreakageTransaction value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e LedgerBreakageRecordEdges) BreakageTransactionOrErr() (*LedgerTransaction, error) { + if e.BreakageTransaction != nil { + return e.BreakageTransaction, nil + } else if e.loadedTypes[4] { + return nil, &NotFoundError{label: ledgertransaction.Label} + } + return nil, &NotLoadedError{edge: "breakage_transaction"} +} + +// FboSubAccountOrErr returns the FboSubAccount value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e LedgerBreakageRecordEdges) FboSubAccountOrErr() (*LedgerSubAccount, error) { + if e.FboSubAccount != nil { + return e.FboSubAccount, nil + } else if e.loadedTypes[5] { + return nil, &NotFoundError{label: ledgersubaccount.Label} + } + return nil, &NotLoadedError{edge: "fbo_sub_account"} +} + +// BreakageSubAccountOrErr returns the BreakageSubAccount value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e LedgerBreakageRecordEdges) BreakageSubAccountOrErr() (*LedgerSubAccount, error) { + if e.BreakageSubAccount != nil { + return e.BreakageSubAccount, nil + } else if e.loadedTypes[6] { + return nil, &NotFoundError{label: ledgersubaccount.Label} + } + return nil, &NotLoadedError{edge: "breakage_sub_account"} +} + +// PlannedReleasesOrErr returns the PlannedReleases value or an error if the edge +// was not loaded in eager-loading. +func (e LedgerBreakageRecordEdges) PlannedReleasesOrErr() ([]*LedgerBreakageRecord, error) { + if e.loadedTypes[7] { + return e.PlannedReleases, nil + } + return nil, &NotLoadedError{edge: "planned_releases"} +} + +// ReleaseReopensOrErr returns the ReleaseReopens value or an error if the edge +// was not loaded in eager-loading. +func (e LedgerBreakageRecordEdges) ReleaseReopensOrErr() ([]*LedgerBreakageRecord, error) { + if e.loadedTypes[8] { + return e.ReleaseReopens, nil + } + return nil, &NotLoadedError{edge: "release_reopens"} +} + +// PlanOrErr returns the Plan value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e LedgerBreakageRecordEdges) PlanOrErr() (*LedgerBreakageRecord, error) { + if e.Plan != nil { + return e.Plan, nil + } else if e.loadedTypes[9] { + return nil, &NotFoundError{label: ledgerbreakagerecord.Label} + } + return nil, &NotLoadedError{edge: "plan"} +} + +// ReleaseOrErr returns the Release value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e LedgerBreakageRecordEdges) ReleaseOrErr() (*LedgerBreakageRecord, error) { + if e.Release != nil { + return e.Release, nil + } else if e.loadedTypes[10] { + return nil, &NotFoundError{label: ledgerbreakagerecord.Label} + } + return nil, &NotLoadedError{edge: "release"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LedgerBreakageRecord) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case ledgerbreakagerecord.FieldAnnotations: + values[i] = new([]byte) + case ledgerbreakagerecord.FieldAmount: + values[i] = new(alpacadecimal.Decimal) + case ledgerbreakagerecord.FieldCreditPriority: + values[i] = new(sql.NullInt64) + case ledgerbreakagerecord.FieldID, ledgerbreakagerecord.FieldNamespace, ledgerbreakagerecord.FieldKind, ledgerbreakagerecord.FieldCustomerID, ledgerbreakagerecord.FieldCurrency, ledgerbreakagerecord.FieldSourceKind, ledgerbreakagerecord.FieldSourceChargeID, ledgerbreakagerecord.FieldSourceTransactionGroupID, ledgerbreakagerecord.FieldSourceTransactionID, ledgerbreakagerecord.FieldSourceEntryID, ledgerbreakagerecord.FieldBreakageTransactionGroupID, ledgerbreakagerecord.FieldBreakageTransactionID, ledgerbreakagerecord.FieldFboSubAccountID, ledgerbreakagerecord.FieldBreakageSubAccountID, ledgerbreakagerecord.FieldPlanID, ledgerbreakagerecord.FieldReleaseID: + values[i] = new(sql.NullString) + case ledgerbreakagerecord.FieldCreatedAt, ledgerbreakagerecord.FieldUpdatedAt, ledgerbreakagerecord.FieldDeletedAt, ledgerbreakagerecord.FieldExpiresAt: + 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 LedgerBreakageRecord fields. +func (_m *LedgerBreakageRecord) 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 ledgerbreakagerecord.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 ledgerbreakagerecord.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 ledgerbreakagerecord.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 ledgerbreakagerecord.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 ledgerbreakagerecord.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 ledgerbreakagerecord.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 ledgerbreakagerecord.FieldKind: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field kind", values[i]) + } else if value.Valid { + _m.Kind = ledger.BreakageKind(value.String) + } + case ledgerbreakagerecord.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 ledgerbreakagerecord.FieldCustomerID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field customer_id", values[i]) + } else if value.Valid { + _m.CustomerID = value.String + } + case ledgerbreakagerecord.FieldCurrency: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field currency", values[i]) + } else if value.Valid { + _m.Currency = currencyx.Code(value.String) + } + case ledgerbreakagerecord.FieldCreditPriority: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field credit_priority", values[i]) + } else if value.Valid { + _m.CreditPriority = int(value.Int64) + } + case ledgerbreakagerecord.FieldExpiresAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field expires_at", values[i]) + } else if value.Valid { + _m.ExpiresAt = value.Time + } + case ledgerbreakagerecord.FieldSourceKind: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field source_kind", values[i]) + } else if value.Valid { + _m.SourceKind = ledger.BreakageSourceKind(value.String) + } + case ledgerbreakagerecord.FieldSourceChargeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field source_charge_id", values[i]) + } else if value.Valid { + _m.SourceChargeID = new(string) + *_m.SourceChargeID = value.String + } + case ledgerbreakagerecord.FieldSourceTransactionGroupID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field source_transaction_group_id", values[i]) + } else if value.Valid { + _m.SourceTransactionGroupID = new(string) + *_m.SourceTransactionGroupID = value.String + } + case ledgerbreakagerecord.FieldSourceTransactionID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field source_transaction_id", values[i]) + } else if value.Valid { + _m.SourceTransactionID = new(string) + *_m.SourceTransactionID = value.String + } + case ledgerbreakagerecord.FieldSourceEntryID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field source_entry_id", values[i]) + } else if value.Valid { + _m.SourceEntryID = new(string) + *_m.SourceEntryID = value.String + } + case ledgerbreakagerecord.FieldBreakageTransactionGroupID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field breakage_transaction_group_id", values[i]) + } else if value.Valid { + _m.BreakageTransactionGroupID = value.String + } + case ledgerbreakagerecord.FieldBreakageTransactionID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field breakage_transaction_id", values[i]) + } else if value.Valid { + _m.BreakageTransactionID = value.String + } + case ledgerbreakagerecord.FieldFboSubAccountID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field fbo_sub_account_id", values[i]) + } else if value.Valid { + _m.FboSubAccountID = value.String + } + case ledgerbreakagerecord.FieldBreakageSubAccountID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field breakage_sub_account_id", values[i]) + } else if value.Valid { + _m.BreakageSubAccountID = value.String + } + case ledgerbreakagerecord.FieldPlanID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field plan_id", values[i]) + } else if value.Valid { + _m.PlanID = new(string) + *_m.PlanID = value.String + } + case ledgerbreakagerecord.FieldReleaseID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field release_id", values[i]) + } else if value.Valid { + _m.ReleaseID = new(string) + *_m.ReleaseID = 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 LedgerBreakageRecord. +// This includes values selected through modifiers, order, etc. +func (_m *LedgerBreakageRecord) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QuerySourceTransactionGroup queries the "source_transaction_group" edge of the LedgerBreakageRecord entity. +func (_m *LedgerBreakageRecord) QuerySourceTransactionGroup() *LedgerTransactionGroupQuery { + return NewLedgerBreakageRecordClient(_m.config).QuerySourceTransactionGroup(_m) +} + +// QuerySourceTransaction queries the "source_transaction" edge of the LedgerBreakageRecord entity. +func (_m *LedgerBreakageRecord) QuerySourceTransaction() *LedgerTransactionQuery { + return NewLedgerBreakageRecordClient(_m.config).QuerySourceTransaction(_m) +} + +// QuerySourceEntry queries the "source_entry" edge of the LedgerBreakageRecord entity. +func (_m *LedgerBreakageRecord) QuerySourceEntry() *LedgerEntryQuery { + return NewLedgerBreakageRecordClient(_m.config).QuerySourceEntry(_m) +} + +// QueryBreakageTransactionGroup queries the "breakage_transaction_group" edge of the LedgerBreakageRecord entity. +func (_m *LedgerBreakageRecord) QueryBreakageTransactionGroup() *LedgerTransactionGroupQuery { + return NewLedgerBreakageRecordClient(_m.config).QueryBreakageTransactionGroup(_m) +} + +// QueryBreakageTransaction queries the "breakage_transaction" edge of the LedgerBreakageRecord entity. +func (_m *LedgerBreakageRecord) QueryBreakageTransaction() *LedgerTransactionQuery { + return NewLedgerBreakageRecordClient(_m.config).QueryBreakageTransaction(_m) +} + +// QueryFboSubAccount queries the "fbo_sub_account" edge of the LedgerBreakageRecord entity. +func (_m *LedgerBreakageRecord) QueryFboSubAccount() *LedgerSubAccountQuery { + return NewLedgerBreakageRecordClient(_m.config).QueryFboSubAccount(_m) +} + +// QueryBreakageSubAccount queries the "breakage_sub_account" edge of the LedgerBreakageRecord entity. +func (_m *LedgerBreakageRecord) QueryBreakageSubAccount() *LedgerSubAccountQuery { + return NewLedgerBreakageRecordClient(_m.config).QueryBreakageSubAccount(_m) +} + +// QueryPlannedReleases queries the "planned_releases" edge of the LedgerBreakageRecord entity. +func (_m *LedgerBreakageRecord) QueryPlannedReleases() *LedgerBreakageRecordQuery { + return NewLedgerBreakageRecordClient(_m.config).QueryPlannedReleases(_m) +} + +// QueryReleaseReopens queries the "release_reopens" edge of the LedgerBreakageRecord entity. +func (_m *LedgerBreakageRecord) QueryReleaseReopens() *LedgerBreakageRecordQuery { + return NewLedgerBreakageRecordClient(_m.config).QueryReleaseReopens(_m) +} + +// QueryPlan queries the "plan" edge of the LedgerBreakageRecord entity. +func (_m *LedgerBreakageRecord) QueryPlan() *LedgerBreakageRecordQuery { + return NewLedgerBreakageRecordClient(_m.config).QueryPlan(_m) +} + +// QueryRelease queries the "release" edge of the LedgerBreakageRecord entity. +func (_m *LedgerBreakageRecord) QueryRelease() *LedgerBreakageRecordQuery { + return NewLedgerBreakageRecordClient(_m.config).QueryRelease(_m) +} + +// Update returns a builder for updating this LedgerBreakageRecord. +// Note that you need to call LedgerBreakageRecord.Unwrap() before calling this method if this LedgerBreakageRecord +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *LedgerBreakageRecord) Update() *LedgerBreakageRecordUpdateOne { + return NewLedgerBreakageRecordClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the LedgerBreakageRecord 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 *LedgerBreakageRecord) Unwrap() *LedgerBreakageRecord { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: LedgerBreakageRecord is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *LedgerBreakageRecord) String() string { + var builder strings.Builder + builder.WriteString("LedgerBreakageRecord(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + 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("kind=") + builder.WriteString(fmt.Sprintf("%v", _m.Kind)) + builder.WriteString(", ") + builder.WriteString("amount=") + builder.WriteString(fmt.Sprintf("%v", _m.Amount)) + builder.WriteString(", ") + builder.WriteString("customer_id=") + builder.WriteString(_m.CustomerID) + builder.WriteString(", ") + builder.WriteString("currency=") + builder.WriteString(fmt.Sprintf("%v", _m.Currency)) + builder.WriteString(", ") + builder.WriteString("credit_priority=") + builder.WriteString(fmt.Sprintf("%v", _m.CreditPriority)) + builder.WriteString(", ") + builder.WriteString("expires_at=") + builder.WriteString(_m.ExpiresAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("source_kind=") + builder.WriteString(fmt.Sprintf("%v", _m.SourceKind)) + builder.WriteString(", ") + if v := _m.SourceChargeID; v != nil { + builder.WriteString("source_charge_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SourceTransactionGroupID; v != nil { + builder.WriteString("source_transaction_group_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SourceTransactionID; v != nil { + builder.WriteString("source_transaction_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SourceEntryID; v != nil { + builder.WriteString("source_entry_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("breakage_transaction_group_id=") + builder.WriteString(_m.BreakageTransactionGroupID) + builder.WriteString(", ") + builder.WriteString("breakage_transaction_id=") + builder.WriteString(_m.BreakageTransactionID) + builder.WriteString(", ") + builder.WriteString("fbo_sub_account_id=") + builder.WriteString(_m.FboSubAccountID) + builder.WriteString(", ") + builder.WriteString("breakage_sub_account_id=") + builder.WriteString(_m.BreakageSubAccountID) + builder.WriteString(", ") + if v := _m.PlanID; v != nil { + builder.WriteString("plan_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.ReleaseID; v != nil { + builder.WriteString("release_id=") + builder.WriteString(*v) + } + builder.WriteByte(')') + return builder.String() +} + +// LedgerBreakageRecords is a parsable slice of LedgerBreakageRecord. +type LedgerBreakageRecords []*LedgerBreakageRecord diff --git a/ent/db/ledgerbreakagerecord/ledgerbreakagerecord.go b/ent/db/ledgerbreakagerecord/ledgerbreakagerecord.go new file mode 100644 index 0000000000000000000000000000000000000000..9d1cb85721594bb97667868e2fc3948f0a0acc2f --- /dev/null +++ b/ent/db/ledgerbreakagerecord/ledgerbreakagerecord.go @@ -0,0 +1,515 @@ +// Code generated by ent, DO NOT EDIT. + +package ledgerbreakagerecord + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/ledger" +) + +const ( + // Label holds the string label denoting the ledgerbreakagerecord type in the database. + Label = "ledger_breakage_record" + // 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" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // 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" + // FieldKind holds the string denoting the kind field in the database. + FieldKind = "kind" + // FieldAmount holds the string denoting the amount field in the database. + FieldAmount = "amount" + // FieldCustomerID holds the string denoting the customer_id field in the database. + FieldCustomerID = "customer_id" + // FieldCurrency holds the string denoting the currency field in the database. + FieldCurrency = "currency" + // FieldCreditPriority holds the string denoting the credit_priority field in the database. + FieldCreditPriority = "credit_priority" + // FieldExpiresAt holds the string denoting the expires_at field in the database. + FieldExpiresAt = "expires_at" + // FieldSourceKind holds the string denoting the source_kind field in the database. + FieldSourceKind = "source_kind" + // FieldSourceChargeID holds the string denoting the source_charge_id field in the database. + FieldSourceChargeID = "source_charge_id" + // FieldSourceTransactionGroupID holds the string denoting the source_transaction_group_id field in the database. + FieldSourceTransactionGroupID = "source_transaction_group_id" + // FieldSourceTransactionID holds the string denoting the source_transaction_id field in the database. + FieldSourceTransactionID = "source_transaction_id" + // FieldSourceEntryID holds the string denoting the source_entry_id field in the database. + FieldSourceEntryID = "source_entry_id" + // FieldBreakageTransactionGroupID holds the string denoting the breakage_transaction_group_id field in the database. + FieldBreakageTransactionGroupID = "breakage_transaction_group_id" + // FieldBreakageTransactionID holds the string denoting the breakage_transaction_id field in the database. + FieldBreakageTransactionID = "breakage_transaction_id" + // FieldFboSubAccountID holds the string denoting the fbo_sub_account_id field in the database. + FieldFboSubAccountID = "fbo_sub_account_id" + // FieldBreakageSubAccountID holds the string denoting the breakage_sub_account_id field in the database. + FieldBreakageSubAccountID = "breakage_sub_account_id" + // FieldPlanID holds the string denoting the plan_id field in the database. + FieldPlanID = "plan_id" + // FieldReleaseID holds the string denoting the release_id field in the database. + FieldReleaseID = "release_id" + // EdgeSourceTransactionGroup holds the string denoting the source_transaction_group edge name in mutations. + EdgeSourceTransactionGroup = "source_transaction_group" + // EdgeSourceTransaction holds the string denoting the source_transaction edge name in mutations. + EdgeSourceTransaction = "source_transaction" + // EdgeSourceEntry holds the string denoting the source_entry edge name in mutations. + EdgeSourceEntry = "source_entry" + // EdgeBreakageTransactionGroup holds the string denoting the breakage_transaction_group edge name in mutations. + EdgeBreakageTransactionGroup = "breakage_transaction_group" + // EdgeBreakageTransaction holds the string denoting the breakage_transaction edge name in mutations. + EdgeBreakageTransaction = "breakage_transaction" + // EdgeFboSubAccount holds the string denoting the fbo_sub_account edge name in mutations. + EdgeFboSubAccount = "fbo_sub_account" + // EdgeBreakageSubAccount holds the string denoting the breakage_sub_account edge name in mutations. + EdgeBreakageSubAccount = "breakage_sub_account" + // EdgePlannedReleases holds the string denoting the planned_releases edge name in mutations. + EdgePlannedReleases = "planned_releases" + // EdgeReleaseReopens holds the string denoting the release_reopens edge name in mutations. + EdgeReleaseReopens = "release_reopens" + // EdgePlan holds the string denoting the plan edge name in mutations. + EdgePlan = "plan" + // EdgeRelease holds the string denoting the release edge name in mutations. + EdgeRelease = "release" + // Table holds the table name of the ledgerbreakagerecord in the database. + Table = "ledger_breakage_records" + // SourceTransactionGroupTable is the table that holds the source_transaction_group relation/edge. + SourceTransactionGroupTable = "ledger_breakage_records" + // SourceTransactionGroupInverseTable is the table name for the LedgerTransactionGroup entity. + // It exists in this package in order to avoid circular dependency with the "ledgertransactiongroup" package. + SourceTransactionGroupInverseTable = "ledger_transaction_groups" + // SourceTransactionGroupColumn is the table column denoting the source_transaction_group relation/edge. + SourceTransactionGroupColumn = "source_transaction_group_id" + // SourceTransactionTable is the table that holds the source_transaction relation/edge. + SourceTransactionTable = "ledger_breakage_records" + // SourceTransactionInverseTable is the table name for the LedgerTransaction entity. + // It exists in this package in order to avoid circular dependency with the "ledgertransaction" package. + SourceTransactionInverseTable = "ledger_transactions" + // SourceTransactionColumn is the table column denoting the source_transaction relation/edge. + SourceTransactionColumn = "source_transaction_id" + // SourceEntryTable is the table that holds the source_entry relation/edge. + SourceEntryTable = "ledger_breakage_records" + // SourceEntryInverseTable is the table name for the LedgerEntry entity. + // It exists in this package in order to avoid circular dependency with the "ledgerentry" package. + SourceEntryInverseTable = "ledger_entries" + // SourceEntryColumn is the table column denoting the source_entry relation/edge. + SourceEntryColumn = "source_entry_id" + // BreakageTransactionGroupTable is the table that holds the breakage_transaction_group relation/edge. + BreakageTransactionGroupTable = "ledger_breakage_records" + // BreakageTransactionGroupInverseTable is the table name for the LedgerTransactionGroup entity. + // It exists in this package in order to avoid circular dependency with the "ledgertransactiongroup" package. + BreakageTransactionGroupInverseTable = "ledger_transaction_groups" + // BreakageTransactionGroupColumn is the table column denoting the breakage_transaction_group relation/edge. + BreakageTransactionGroupColumn = "breakage_transaction_group_id" + // BreakageTransactionTable is the table that holds the breakage_transaction relation/edge. + BreakageTransactionTable = "ledger_breakage_records" + // BreakageTransactionInverseTable is the table name for the LedgerTransaction entity. + // It exists in this package in order to avoid circular dependency with the "ledgertransaction" package. + BreakageTransactionInverseTable = "ledger_transactions" + // BreakageTransactionColumn is the table column denoting the breakage_transaction relation/edge. + BreakageTransactionColumn = "breakage_transaction_id" + // FboSubAccountTable is the table that holds the fbo_sub_account relation/edge. + FboSubAccountTable = "ledger_breakage_records" + // FboSubAccountInverseTable is the table name for the LedgerSubAccount entity. + // It exists in this package in order to avoid circular dependency with the "ledgersubaccount" package. + FboSubAccountInverseTable = "ledger_sub_accounts" + // FboSubAccountColumn is the table column denoting the fbo_sub_account relation/edge. + FboSubAccountColumn = "fbo_sub_account_id" + // BreakageSubAccountTable is the table that holds the breakage_sub_account relation/edge. + BreakageSubAccountTable = "ledger_breakage_records" + // BreakageSubAccountInverseTable is the table name for the LedgerSubAccount entity. + // It exists in this package in order to avoid circular dependency with the "ledgersubaccount" package. + BreakageSubAccountInverseTable = "ledger_sub_accounts" + // BreakageSubAccountColumn is the table column denoting the breakage_sub_account relation/edge. + BreakageSubAccountColumn = "breakage_sub_account_id" + // PlannedReleasesTable is the table that holds the planned_releases relation/edge. + PlannedReleasesTable = "ledger_breakage_records" + // PlannedReleasesColumn is the table column denoting the planned_releases relation/edge. + PlannedReleasesColumn = "plan_id" + // ReleaseReopensTable is the table that holds the release_reopens relation/edge. + ReleaseReopensTable = "ledger_breakage_records" + // ReleaseReopensColumn is the table column denoting the release_reopens relation/edge. + ReleaseReopensColumn = "release_id" + // PlanTable is the table that holds the plan relation/edge. + PlanTable = "ledger_breakage_records" + // PlanColumn is the table column denoting the plan relation/edge. + PlanColumn = "plan_id" + // ReleaseTable is the table that holds the release relation/edge. + ReleaseTable = "ledger_breakage_records" + // ReleaseColumn is the table column denoting the release relation/edge. + ReleaseColumn = "release_id" +) + +// Columns holds all SQL columns for ledgerbreakagerecord fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldAnnotations, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldKind, + FieldAmount, + FieldCustomerID, + FieldCurrency, + FieldCreditPriority, + FieldExpiresAt, + FieldSourceKind, + FieldSourceChargeID, + FieldSourceTransactionGroupID, + FieldSourceTransactionID, + FieldSourceEntryID, + FieldBreakageTransactionGroupID, + FieldBreakageTransactionID, + FieldFboSubAccountID, + FieldBreakageSubAccountID, + FieldPlanID, + FieldReleaseID, +} + +// 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 + // CustomerIDValidator is a validator for the "customer_id" field. It is called by the builders before save. + CustomerIDValidator func(string) error + // CurrencyValidator is a validator for the "currency" field. It is called by the builders before save. + CurrencyValidator func(string) error + // BreakageTransactionGroupIDValidator is a validator for the "breakage_transaction_group_id" field. It is called by the builders before save. + BreakageTransactionGroupIDValidator func(string) error + // BreakageTransactionIDValidator is a validator for the "breakage_transaction_id" field. It is called by the builders before save. + BreakageTransactionIDValidator func(string) error + // FboSubAccountIDValidator is a validator for the "fbo_sub_account_id" field. It is called by the builders before save. + FboSubAccountIDValidator func(string) error + // BreakageSubAccountIDValidator is a validator for the "breakage_sub_account_id" field. It is called by the builders before save. + BreakageSubAccountIDValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// KindValidator is a validator for the "kind" field enum values. It is called by the builders before save. +func KindValidator(k ledger.BreakageKind) error { + switch k { + case "plan", "release", "reopen": + return nil + default: + return fmt.Errorf("ledgerbreakagerecord: invalid enum value for kind field: %q", k) + } +} + +// SourceKindValidator is a validator for the "source_kind" field enum values. It is called by the builders before save. +func SourceKindValidator(sk ledger.BreakageSourceKind) error { + switch sk { + case "credit_purchase", "usage", "usage_correction", "credit_purchase_correction", "advance_backfill": + return nil + default: + return fmt.Errorf("ledgerbreakagerecord: invalid enum value for source_kind field: %q", sk) + } +} + +// OrderOption defines the ordering options for the LedgerBreakageRecord 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() +} + +// ByKind orders the results by the kind field. +func ByKind(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldKind, opts...).ToFunc() +} + +// ByAmount orders the results by the amount field. +func ByAmount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAmount, opts...).ToFunc() +} + +// ByCustomerID orders the results by the customer_id field. +func ByCustomerID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCustomerID, opts...).ToFunc() +} + +// ByCurrency orders the results by the currency field. +func ByCurrency(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCurrency, opts...).ToFunc() +} + +// ByCreditPriority orders the results by the credit_priority field. +func ByCreditPriority(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreditPriority, opts...).ToFunc() +} + +// ByExpiresAt orders the results by the expires_at field. +func ByExpiresAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldExpiresAt, opts...).ToFunc() +} + +// BySourceKind orders the results by the source_kind field. +func BySourceKind(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSourceKind, opts...).ToFunc() +} + +// BySourceChargeID orders the results by the source_charge_id field. +func BySourceChargeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSourceChargeID, opts...).ToFunc() +} + +// BySourceTransactionGroupID orders the results by the source_transaction_group_id field. +func BySourceTransactionGroupID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSourceTransactionGroupID, opts...).ToFunc() +} + +// BySourceTransactionID orders the results by the source_transaction_id field. +func BySourceTransactionID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSourceTransactionID, opts...).ToFunc() +} + +// BySourceEntryID orders the results by the source_entry_id field. +func BySourceEntryID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSourceEntryID, opts...).ToFunc() +} + +// ByBreakageTransactionGroupID orders the results by the breakage_transaction_group_id field. +func ByBreakageTransactionGroupID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBreakageTransactionGroupID, opts...).ToFunc() +} + +// ByBreakageTransactionID orders the results by the breakage_transaction_id field. +func ByBreakageTransactionID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBreakageTransactionID, opts...).ToFunc() +} + +// ByFboSubAccountID orders the results by the fbo_sub_account_id field. +func ByFboSubAccountID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFboSubAccountID, opts...).ToFunc() +} + +// ByBreakageSubAccountID orders the results by the breakage_sub_account_id field. +func ByBreakageSubAccountID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBreakageSubAccountID, opts...).ToFunc() +} + +// ByPlanID orders the results by the plan_id field. +func ByPlanID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPlanID, opts...).ToFunc() +} + +// ByReleaseID orders the results by the release_id field. +func ByReleaseID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldReleaseID, opts...).ToFunc() +} + +// BySourceTransactionGroupField orders the results by source_transaction_group field. +func BySourceTransactionGroupField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSourceTransactionGroupStep(), sql.OrderByField(field, opts...)) + } +} + +// BySourceTransactionField orders the results by source_transaction field. +func BySourceTransactionField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSourceTransactionStep(), sql.OrderByField(field, opts...)) + } +} + +// BySourceEntryField orders the results by source_entry field. +func BySourceEntryField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSourceEntryStep(), sql.OrderByField(field, opts...)) + } +} + +// ByBreakageTransactionGroupField orders the results by breakage_transaction_group field. +func ByBreakageTransactionGroupField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBreakageTransactionGroupStep(), sql.OrderByField(field, opts...)) + } +} + +// ByBreakageTransactionField orders the results by breakage_transaction field. +func ByBreakageTransactionField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBreakageTransactionStep(), sql.OrderByField(field, opts...)) + } +} + +// ByFboSubAccountField orders the results by fbo_sub_account field. +func ByFboSubAccountField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newFboSubAccountStep(), sql.OrderByField(field, opts...)) + } +} + +// ByBreakageSubAccountField orders the results by breakage_sub_account field. +func ByBreakageSubAccountField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBreakageSubAccountStep(), sql.OrderByField(field, opts...)) + } +} + +// ByPlannedReleasesCount orders the results by planned_releases count. +func ByPlannedReleasesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newPlannedReleasesStep(), opts...) + } +} + +// ByPlannedReleases orders the results by planned_releases terms. +func ByPlannedReleases(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newPlannedReleasesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByReleaseReopensCount orders the results by release_reopens count. +func ByReleaseReopensCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newReleaseReopensStep(), opts...) + } +} + +// ByReleaseReopens orders the results by release_reopens terms. +func ByReleaseReopens(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newReleaseReopensStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByPlanField orders the results by plan field. +func ByPlanField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newPlanStep(), sql.OrderByField(field, opts...)) + } +} + +// ByReleaseField orders the results by release field. +func ByReleaseField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newReleaseStep(), sql.OrderByField(field, opts...)) + } +} +func newSourceTransactionGroupStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SourceTransactionGroupInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SourceTransactionGroupTable, SourceTransactionGroupColumn), + ) +} +func newSourceTransactionStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SourceTransactionInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SourceTransactionTable, SourceTransactionColumn), + ) +} +func newSourceEntryStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SourceEntryInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SourceEntryTable, SourceEntryColumn), + ) +} +func newBreakageTransactionGroupStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BreakageTransactionGroupInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, BreakageTransactionGroupTable, BreakageTransactionGroupColumn), + ) +} +func newBreakageTransactionStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BreakageTransactionInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, BreakageTransactionTable, BreakageTransactionColumn), + ) +} +func newFboSubAccountStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(FboSubAccountInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, FboSubAccountTable, FboSubAccountColumn), + ) +} +func newBreakageSubAccountStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BreakageSubAccountInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, BreakageSubAccountTable, BreakageSubAccountColumn), + ) +} +func newPlannedReleasesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, PlannedReleasesTable, PlannedReleasesColumn), + ) +} +func newReleaseReopensStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ReleaseReopensTable, ReleaseReopensColumn), + ) +} +func newPlanStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, PlanTable, PlanColumn), + ) +} +func newReleaseStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ReleaseTable, ReleaseColumn), + ) +} diff --git a/ent/db/ledgerbreakagerecord/where.go b/ent/db/ledgerbreakagerecord/where.go new file mode 100644 index 0000000000000000000000000000000000000000..9013293bbf9b18c7d65c78957b40108edc9115d7 --- /dev/null +++ b/ent/db/ledgerbreakagerecord/where.go @@ -0,0 +1,1677 @@ +// Code generated by ent, DO NOT EDIT. + +package ledgerbreakagerecord + +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" + "github.com/openmeterio/openmeter/openmeter/ledger" + "github.com/openmeterio/openmeter/pkg/currencyx" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(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.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(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.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(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.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ. +func Amount(v alpacadecimal.Decimal) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldAmount, v)) +} + +// CustomerID applies equality check predicate on the "customer_id" field. It's identical to CustomerIDEQ. +func CustomerID(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldCustomerID, v)) +} + +// Currency applies equality check predicate on the "currency" field. It's identical to CurrencyEQ. +func Currency(v currencyx.Code) predicate.LedgerBreakageRecord { + vc := string(v) + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldCurrency, vc)) +} + +// CreditPriority applies equality check predicate on the "credit_priority" field. It's identical to CreditPriorityEQ. +func CreditPriority(v int) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldCreditPriority, v)) +} + +// ExpiresAt applies equality check predicate on the "expires_at" field. It's identical to ExpiresAtEQ. +func ExpiresAt(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldExpiresAt, v)) +} + +// SourceChargeID applies equality check predicate on the "source_charge_id" field. It's identical to SourceChargeIDEQ. +func SourceChargeID(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldSourceChargeID, v)) +} + +// SourceTransactionGroupID applies equality check predicate on the "source_transaction_group_id" field. It's identical to SourceTransactionGroupIDEQ. +func SourceTransactionGroupID(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldSourceTransactionGroupID, v)) +} + +// SourceTransactionID applies equality check predicate on the "source_transaction_id" field. It's identical to SourceTransactionIDEQ. +func SourceTransactionID(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldSourceTransactionID, v)) +} + +// SourceEntryID applies equality check predicate on the "source_entry_id" field. It's identical to SourceEntryIDEQ. +func SourceEntryID(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldSourceEntryID, v)) +} + +// BreakageTransactionGroupID applies equality check predicate on the "breakage_transaction_group_id" field. It's identical to BreakageTransactionGroupIDEQ. +func BreakageTransactionGroupID(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldBreakageTransactionGroupID, v)) +} + +// BreakageTransactionID applies equality check predicate on the "breakage_transaction_id" field. It's identical to BreakageTransactionIDEQ. +func BreakageTransactionID(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldBreakageTransactionID, v)) +} + +// FboSubAccountID applies equality check predicate on the "fbo_sub_account_id" field. It's identical to FboSubAccountIDEQ. +func FboSubAccountID(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldFboSubAccountID, v)) +} + +// BreakageSubAccountID applies equality check predicate on the "breakage_sub_account_id" field. It's identical to BreakageSubAccountIDEQ. +func BreakageSubAccountID(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldBreakageSubAccountID, v)) +} + +// PlanID applies equality check predicate on the "plan_id" field. It's identical to PlanIDEQ. +func PlanID(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldPlanID, v)) +} + +// ReleaseID applies equality check predicate on the "release_id" field. It's identical to ReleaseIDEQ. +func ReleaseID(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldReleaseID, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContainsFold(FieldNamespace, v)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotNull(FieldAnnotations)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotNull(FieldDeletedAt)) +} + +// KindEQ applies the EQ predicate on the "kind" field. +func KindEQ(v ledger.BreakageKind) predicate.LedgerBreakageRecord { + vc := v + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldKind, vc)) +} + +// KindNEQ applies the NEQ predicate on the "kind" field. +func KindNEQ(v ledger.BreakageKind) predicate.LedgerBreakageRecord { + vc := v + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldKind, vc)) +} + +// KindIn applies the In predicate on the "kind" field. +func KindIn(vs ...ledger.BreakageKind) predicate.LedgerBreakageRecord { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldKind, v...)) +} + +// KindNotIn applies the NotIn predicate on the "kind" field. +func KindNotIn(vs ...ledger.BreakageKind) predicate.LedgerBreakageRecord { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldKind, v...)) +} + +// AmountEQ applies the EQ predicate on the "amount" field. +func AmountEQ(v alpacadecimal.Decimal) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldAmount, v)) +} + +// AmountNEQ applies the NEQ predicate on the "amount" field. +func AmountNEQ(v alpacadecimal.Decimal) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldAmount, v)) +} + +// AmountIn applies the In predicate on the "amount" field. +func AmountIn(vs ...alpacadecimal.Decimal) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldAmount, vs...)) +} + +// AmountNotIn applies the NotIn predicate on the "amount" field. +func AmountNotIn(vs ...alpacadecimal.Decimal) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldAmount, vs...)) +} + +// AmountGT applies the GT predicate on the "amount" field. +func AmountGT(v alpacadecimal.Decimal) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGT(FieldAmount, v)) +} + +// AmountGTE applies the GTE predicate on the "amount" field. +func AmountGTE(v alpacadecimal.Decimal) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGTE(FieldAmount, v)) +} + +// AmountLT applies the LT predicate on the "amount" field. +func AmountLT(v alpacadecimal.Decimal) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLT(FieldAmount, v)) +} + +// AmountLTE applies the LTE predicate on the "amount" field. +func AmountLTE(v alpacadecimal.Decimal) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLTE(FieldAmount, v)) +} + +// CustomerIDEQ applies the EQ predicate on the "customer_id" field. +func CustomerIDEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldCustomerID, v)) +} + +// CustomerIDNEQ applies the NEQ predicate on the "customer_id" field. +func CustomerIDNEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldCustomerID, v)) +} + +// CustomerIDIn applies the In predicate on the "customer_id" field. +func CustomerIDIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldCustomerID, vs...)) +} + +// CustomerIDNotIn applies the NotIn predicate on the "customer_id" field. +func CustomerIDNotIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldCustomerID, vs...)) +} + +// CustomerIDGT applies the GT predicate on the "customer_id" field. +func CustomerIDGT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGT(FieldCustomerID, v)) +} + +// CustomerIDGTE applies the GTE predicate on the "customer_id" field. +func CustomerIDGTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGTE(FieldCustomerID, v)) +} + +// CustomerIDLT applies the LT predicate on the "customer_id" field. +func CustomerIDLT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLT(FieldCustomerID, v)) +} + +// CustomerIDLTE applies the LTE predicate on the "customer_id" field. +func CustomerIDLTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLTE(FieldCustomerID, v)) +} + +// CustomerIDContains applies the Contains predicate on the "customer_id" field. +func CustomerIDContains(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContains(FieldCustomerID, v)) +} + +// CustomerIDHasPrefix applies the HasPrefix predicate on the "customer_id" field. +func CustomerIDHasPrefix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasPrefix(FieldCustomerID, v)) +} + +// CustomerIDHasSuffix applies the HasSuffix predicate on the "customer_id" field. +func CustomerIDHasSuffix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasSuffix(FieldCustomerID, v)) +} + +// CustomerIDEqualFold applies the EqualFold predicate on the "customer_id" field. +func CustomerIDEqualFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEqualFold(FieldCustomerID, v)) +} + +// CustomerIDContainsFold applies the ContainsFold predicate on the "customer_id" field. +func CustomerIDContainsFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContainsFold(FieldCustomerID, v)) +} + +// CurrencyEQ applies the EQ predicate on the "currency" field. +func CurrencyEQ(v currencyx.Code) predicate.LedgerBreakageRecord { + vc := string(v) + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldCurrency, vc)) +} + +// CurrencyNEQ applies the NEQ predicate on the "currency" field. +func CurrencyNEQ(v currencyx.Code) predicate.LedgerBreakageRecord { + vc := string(v) + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldCurrency, vc)) +} + +// CurrencyIn applies the In predicate on the "currency" field. +func CurrencyIn(vs ...currencyx.Code) predicate.LedgerBreakageRecord { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldCurrency, v...)) +} + +// CurrencyNotIn applies the NotIn predicate on the "currency" field. +func CurrencyNotIn(vs ...currencyx.Code) predicate.LedgerBreakageRecord { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldCurrency, v...)) +} + +// CurrencyGT applies the GT predicate on the "currency" field. +func CurrencyGT(v currencyx.Code) predicate.LedgerBreakageRecord { + vc := string(v) + return predicate.LedgerBreakageRecord(sql.FieldGT(FieldCurrency, vc)) +} + +// CurrencyGTE applies the GTE predicate on the "currency" field. +func CurrencyGTE(v currencyx.Code) predicate.LedgerBreakageRecord { + vc := string(v) + return predicate.LedgerBreakageRecord(sql.FieldGTE(FieldCurrency, vc)) +} + +// CurrencyLT applies the LT predicate on the "currency" field. +func CurrencyLT(v currencyx.Code) predicate.LedgerBreakageRecord { + vc := string(v) + return predicate.LedgerBreakageRecord(sql.FieldLT(FieldCurrency, vc)) +} + +// CurrencyLTE applies the LTE predicate on the "currency" field. +func CurrencyLTE(v currencyx.Code) predicate.LedgerBreakageRecord { + vc := string(v) + return predicate.LedgerBreakageRecord(sql.FieldLTE(FieldCurrency, vc)) +} + +// CurrencyContains applies the Contains predicate on the "currency" field. +func CurrencyContains(v currencyx.Code) predicate.LedgerBreakageRecord { + vc := string(v) + return predicate.LedgerBreakageRecord(sql.FieldContains(FieldCurrency, vc)) +} + +// CurrencyHasPrefix applies the HasPrefix predicate on the "currency" field. +func CurrencyHasPrefix(v currencyx.Code) predicate.LedgerBreakageRecord { + vc := string(v) + return predicate.LedgerBreakageRecord(sql.FieldHasPrefix(FieldCurrency, vc)) +} + +// CurrencyHasSuffix applies the HasSuffix predicate on the "currency" field. +func CurrencyHasSuffix(v currencyx.Code) predicate.LedgerBreakageRecord { + vc := string(v) + return predicate.LedgerBreakageRecord(sql.FieldHasSuffix(FieldCurrency, vc)) +} + +// CurrencyEqualFold applies the EqualFold predicate on the "currency" field. +func CurrencyEqualFold(v currencyx.Code) predicate.LedgerBreakageRecord { + vc := string(v) + return predicate.LedgerBreakageRecord(sql.FieldEqualFold(FieldCurrency, vc)) +} + +// CurrencyContainsFold applies the ContainsFold predicate on the "currency" field. +func CurrencyContainsFold(v currencyx.Code) predicate.LedgerBreakageRecord { + vc := string(v) + return predicate.LedgerBreakageRecord(sql.FieldContainsFold(FieldCurrency, vc)) +} + +// CreditPriorityEQ applies the EQ predicate on the "credit_priority" field. +func CreditPriorityEQ(v int) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldCreditPriority, v)) +} + +// CreditPriorityNEQ applies the NEQ predicate on the "credit_priority" field. +func CreditPriorityNEQ(v int) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldCreditPriority, v)) +} + +// CreditPriorityIn applies the In predicate on the "credit_priority" field. +func CreditPriorityIn(vs ...int) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldCreditPriority, vs...)) +} + +// CreditPriorityNotIn applies the NotIn predicate on the "credit_priority" field. +func CreditPriorityNotIn(vs ...int) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldCreditPriority, vs...)) +} + +// CreditPriorityGT applies the GT predicate on the "credit_priority" field. +func CreditPriorityGT(v int) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGT(FieldCreditPriority, v)) +} + +// CreditPriorityGTE applies the GTE predicate on the "credit_priority" field. +func CreditPriorityGTE(v int) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGTE(FieldCreditPriority, v)) +} + +// CreditPriorityLT applies the LT predicate on the "credit_priority" field. +func CreditPriorityLT(v int) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLT(FieldCreditPriority, v)) +} + +// CreditPriorityLTE applies the LTE predicate on the "credit_priority" field. +func CreditPriorityLTE(v int) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLTE(FieldCreditPriority, v)) +} + +// ExpiresAtEQ applies the EQ predicate on the "expires_at" field. +func ExpiresAtEQ(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldExpiresAt, v)) +} + +// ExpiresAtNEQ applies the NEQ predicate on the "expires_at" field. +func ExpiresAtNEQ(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldExpiresAt, v)) +} + +// ExpiresAtIn applies the In predicate on the "expires_at" field. +func ExpiresAtIn(vs ...time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldExpiresAt, vs...)) +} + +// ExpiresAtNotIn applies the NotIn predicate on the "expires_at" field. +func ExpiresAtNotIn(vs ...time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldExpiresAt, vs...)) +} + +// ExpiresAtGT applies the GT predicate on the "expires_at" field. +func ExpiresAtGT(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGT(FieldExpiresAt, v)) +} + +// ExpiresAtGTE applies the GTE predicate on the "expires_at" field. +func ExpiresAtGTE(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGTE(FieldExpiresAt, v)) +} + +// ExpiresAtLT applies the LT predicate on the "expires_at" field. +func ExpiresAtLT(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLT(FieldExpiresAt, v)) +} + +// ExpiresAtLTE applies the LTE predicate on the "expires_at" field. +func ExpiresAtLTE(v time.Time) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLTE(FieldExpiresAt, v)) +} + +// SourceKindEQ applies the EQ predicate on the "source_kind" field. +func SourceKindEQ(v ledger.BreakageSourceKind) predicate.LedgerBreakageRecord { + vc := v + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldSourceKind, vc)) +} + +// SourceKindNEQ applies the NEQ predicate on the "source_kind" field. +func SourceKindNEQ(v ledger.BreakageSourceKind) predicate.LedgerBreakageRecord { + vc := v + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldSourceKind, vc)) +} + +// SourceKindIn applies the In predicate on the "source_kind" field. +func SourceKindIn(vs ...ledger.BreakageSourceKind) predicate.LedgerBreakageRecord { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldSourceKind, v...)) +} + +// SourceKindNotIn applies the NotIn predicate on the "source_kind" field. +func SourceKindNotIn(vs ...ledger.BreakageSourceKind) predicate.LedgerBreakageRecord { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldSourceKind, v...)) +} + +// SourceChargeIDEQ applies the EQ predicate on the "source_charge_id" field. +func SourceChargeIDEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldSourceChargeID, v)) +} + +// SourceChargeIDNEQ applies the NEQ predicate on the "source_charge_id" field. +func SourceChargeIDNEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldSourceChargeID, v)) +} + +// SourceChargeIDIn applies the In predicate on the "source_charge_id" field. +func SourceChargeIDIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldSourceChargeID, vs...)) +} + +// SourceChargeIDNotIn applies the NotIn predicate on the "source_charge_id" field. +func SourceChargeIDNotIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldSourceChargeID, vs...)) +} + +// SourceChargeIDGT applies the GT predicate on the "source_charge_id" field. +func SourceChargeIDGT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGT(FieldSourceChargeID, v)) +} + +// SourceChargeIDGTE applies the GTE predicate on the "source_charge_id" field. +func SourceChargeIDGTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGTE(FieldSourceChargeID, v)) +} + +// SourceChargeIDLT applies the LT predicate on the "source_charge_id" field. +func SourceChargeIDLT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLT(FieldSourceChargeID, v)) +} + +// SourceChargeIDLTE applies the LTE predicate on the "source_charge_id" field. +func SourceChargeIDLTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLTE(FieldSourceChargeID, v)) +} + +// SourceChargeIDContains applies the Contains predicate on the "source_charge_id" field. +func SourceChargeIDContains(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContains(FieldSourceChargeID, v)) +} + +// SourceChargeIDHasPrefix applies the HasPrefix predicate on the "source_charge_id" field. +func SourceChargeIDHasPrefix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasPrefix(FieldSourceChargeID, v)) +} + +// SourceChargeIDHasSuffix applies the HasSuffix predicate on the "source_charge_id" field. +func SourceChargeIDHasSuffix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasSuffix(FieldSourceChargeID, v)) +} + +// SourceChargeIDIsNil applies the IsNil predicate on the "source_charge_id" field. +func SourceChargeIDIsNil() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIsNull(FieldSourceChargeID)) +} + +// SourceChargeIDNotNil applies the NotNil predicate on the "source_charge_id" field. +func SourceChargeIDNotNil() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotNull(FieldSourceChargeID)) +} + +// SourceChargeIDEqualFold applies the EqualFold predicate on the "source_charge_id" field. +func SourceChargeIDEqualFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEqualFold(FieldSourceChargeID, v)) +} + +// SourceChargeIDContainsFold applies the ContainsFold predicate on the "source_charge_id" field. +func SourceChargeIDContainsFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContainsFold(FieldSourceChargeID, v)) +} + +// SourceTransactionGroupIDEQ applies the EQ predicate on the "source_transaction_group_id" field. +func SourceTransactionGroupIDEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldSourceTransactionGroupID, v)) +} + +// SourceTransactionGroupIDNEQ applies the NEQ predicate on the "source_transaction_group_id" field. +func SourceTransactionGroupIDNEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldSourceTransactionGroupID, v)) +} + +// SourceTransactionGroupIDIn applies the In predicate on the "source_transaction_group_id" field. +func SourceTransactionGroupIDIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldSourceTransactionGroupID, vs...)) +} + +// SourceTransactionGroupIDNotIn applies the NotIn predicate on the "source_transaction_group_id" field. +func SourceTransactionGroupIDNotIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldSourceTransactionGroupID, vs...)) +} + +// SourceTransactionGroupIDGT applies the GT predicate on the "source_transaction_group_id" field. +func SourceTransactionGroupIDGT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGT(FieldSourceTransactionGroupID, v)) +} + +// SourceTransactionGroupIDGTE applies the GTE predicate on the "source_transaction_group_id" field. +func SourceTransactionGroupIDGTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGTE(FieldSourceTransactionGroupID, v)) +} + +// SourceTransactionGroupIDLT applies the LT predicate on the "source_transaction_group_id" field. +func SourceTransactionGroupIDLT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLT(FieldSourceTransactionGroupID, v)) +} + +// SourceTransactionGroupIDLTE applies the LTE predicate on the "source_transaction_group_id" field. +func SourceTransactionGroupIDLTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLTE(FieldSourceTransactionGroupID, v)) +} + +// SourceTransactionGroupIDContains applies the Contains predicate on the "source_transaction_group_id" field. +func SourceTransactionGroupIDContains(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContains(FieldSourceTransactionGroupID, v)) +} + +// SourceTransactionGroupIDHasPrefix applies the HasPrefix predicate on the "source_transaction_group_id" field. +func SourceTransactionGroupIDHasPrefix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasPrefix(FieldSourceTransactionGroupID, v)) +} + +// SourceTransactionGroupIDHasSuffix applies the HasSuffix predicate on the "source_transaction_group_id" field. +func SourceTransactionGroupIDHasSuffix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasSuffix(FieldSourceTransactionGroupID, v)) +} + +// SourceTransactionGroupIDIsNil applies the IsNil predicate on the "source_transaction_group_id" field. +func SourceTransactionGroupIDIsNil() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIsNull(FieldSourceTransactionGroupID)) +} + +// SourceTransactionGroupIDNotNil applies the NotNil predicate on the "source_transaction_group_id" field. +func SourceTransactionGroupIDNotNil() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotNull(FieldSourceTransactionGroupID)) +} + +// SourceTransactionGroupIDEqualFold applies the EqualFold predicate on the "source_transaction_group_id" field. +func SourceTransactionGroupIDEqualFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEqualFold(FieldSourceTransactionGroupID, v)) +} + +// SourceTransactionGroupIDContainsFold applies the ContainsFold predicate on the "source_transaction_group_id" field. +func SourceTransactionGroupIDContainsFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContainsFold(FieldSourceTransactionGroupID, v)) +} + +// SourceTransactionIDEQ applies the EQ predicate on the "source_transaction_id" field. +func SourceTransactionIDEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldSourceTransactionID, v)) +} + +// SourceTransactionIDNEQ applies the NEQ predicate on the "source_transaction_id" field. +func SourceTransactionIDNEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldSourceTransactionID, v)) +} + +// SourceTransactionIDIn applies the In predicate on the "source_transaction_id" field. +func SourceTransactionIDIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldSourceTransactionID, vs...)) +} + +// SourceTransactionIDNotIn applies the NotIn predicate on the "source_transaction_id" field. +func SourceTransactionIDNotIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldSourceTransactionID, vs...)) +} + +// SourceTransactionIDGT applies the GT predicate on the "source_transaction_id" field. +func SourceTransactionIDGT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGT(FieldSourceTransactionID, v)) +} + +// SourceTransactionIDGTE applies the GTE predicate on the "source_transaction_id" field. +func SourceTransactionIDGTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGTE(FieldSourceTransactionID, v)) +} + +// SourceTransactionIDLT applies the LT predicate on the "source_transaction_id" field. +func SourceTransactionIDLT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLT(FieldSourceTransactionID, v)) +} + +// SourceTransactionIDLTE applies the LTE predicate on the "source_transaction_id" field. +func SourceTransactionIDLTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLTE(FieldSourceTransactionID, v)) +} + +// SourceTransactionIDContains applies the Contains predicate on the "source_transaction_id" field. +func SourceTransactionIDContains(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContains(FieldSourceTransactionID, v)) +} + +// SourceTransactionIDHasPrefix applies the HasPrefix predicate on the "source_transaction_id" field. +func SourceTransactionIDHasPrefix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasPrefix(FieldSourceTransactionID, v)) +} + +// SourceTransactionIDHasSuffix applies the HasSuffix predicate on the "source_transaction_id" field. +func SourceTransactionIDHasSuffix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasSuffix(FieldSourceTransactionID, v)) +} + +// SourceTransactionIDIsNil applies the IsNil predicate on the "source_transaction_id" field. +func SourceTransactionIDIsNil() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIsNull(FieldSourceTransactionID)) +} + +// SourceTransactionIDNotNil applies the NotNil predicate on the "source_transaction_id" field. +func SourceTransactionIDNotNil() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotNull(FieldSourceTransactionID)) +} + +// SourceTransactionIDEqualFold applies the EqualFold predicate on the "source_transaction_id" field. +func SourceTransactionIDEqualFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEqualFold(FieldSourceTransactionID, v)) +} + +// SourceTransactionIDContainsFold applies the ContainsFold predicate on the "source_transaction_id" field. +func SourceTransactionIDContainsFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContainsFold(FieldSourceTransactionID, v)) +} + +// SourceEntryIDEQ applies the EQ predicate on the "source_entry_id" field. +func SourceEntryIDEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldSourceEntryID, v)) +} + +// SourceEntryIDNEQ applies the NEQ predicate on the "source_entry_id" field. +func SourceEntryIDNEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldSourceEntryID, v)) +} + +// SourceEntryIDIn applies the In predicate on the "source_entry_id" field. +func SourceEntryIDIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldSourceEntryID, vs...)) +} + +// SourceEntryIDNotIn applies the NotIn predicate on the "source_entry_id" field. +func SourceEntryIDNotIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldSourceEntryID, vs...)) +} + +// SourceEntryIDGT applies the GT predicate on the "source_entry_id" field. +func SourceEntryIDGT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGT(FieldSourceEntryID, v)) +} + +// SourceEntryIDGTE applies the GTE predicate on the "source_entry_id" field. +func SourceEntryIDGTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGTE(FieldSourceEntryID, v)) +} + +// SourceEntryIDLT applies the LT predicate on the "source_entry_id" field. +func SourceEntryIDLT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLT(FieldSourceEntryID, v)) +} + +// SourceEntryIDLTE applies the LTE predicate on the "source_entry_id" field. +func SourceEntryIDLTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLTE(FieldSourceEntryID, v)) +} + +// SourceEntryIDContains applies the Contains predicate on the "source_entry_id" field. +func SourceEntryIDContains(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContains(FieldSourceEntryID, v)) +} + +// SourceEntryIDHasPrefix applies the HasPrefix predicate on the "source_entry_id" field. +func SourceEntryIDHasPrefix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasPrefix(FieldSourceEntryID, v)) +} + +// SourceEntryIDHasSuffix applies the HasSuffix predicate on the "source_entry_id" field. +func SourceEntryIDHasSuffix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasSuffix(FieldSourceEntryID, v)) +} + +// SourceEntryIDIsNil applies the IsNil predicate on the "source_entry_id" field. +func SourceEntryIDIsNil() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIsNull(FieldSourceEntryID)) +} + +// SourceEntryIDNotNil applies the NotNil predicate on the "source_entry_id" field. +func SourceEntryIDNotNil() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotNull(FieldSourceEntryID)) +} + +// SourceEntryIDEqualFold applies the EqualFold predicate on the "source_entry_id" field. +func SourceEntryIDEqualFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEqualFold(FieldSourceEntryID, v)) +} + +// SourceEntryIDContainsFold applies the ContainsFold predicate on the "source_entry_id" field. +func SourceEntryIDContainsFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContainsFold(FieldSourceEntryID, v)) +} + +// BreakageTransactionGroupIDEQ applies the EQ predicate on the "breakage_transaction_group_id" field. +func BreakageTransactionGroupIDEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldBreakageTransactionGroupID, v)) +} + +// BreakageTransactionGroupIDNEQ applies the NEQ predicate on the "breakage_transaction_group_id" field. +func BreakageTransactionGroupIDNEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldBreakageTransactionGroupID, v)) +} + +// BreakageTransactionGroupIDIn applies the In predicate on the "breakage_transaction_group_id" field. +func BreakageTransactionGroupIDIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldBreakageTransactionGroupID, vs...)) +} + +// BreakageTransactionGroupIDNotIn applies the NotIn predicate on the "breakage_transaction_group_id" field. +func BreakageTransactionGroupIDNotIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldBreakageTransactionGroupID, vs...)) +} + +// BreakageTransactionGroupIDGT applies the GT predicate on the "breakage_transaction_group_id" field. +func BreakageTransactionGroupIDGT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGT(FieldBreakageTransactionGroupID, v)) +} + +// BreakageTransactionGroupIDGTE applies the GTE predicate on the "breakage_transaction_group_id" field. +func BreakageTransactionGroupIDGTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGTE(FieldBreakageTransactionGroupID, v)) +} + +// BreakageTransactionGroupIDLT applies the LT predicate on the "breakage_transaction_group_id" field. +func BreakageTransactionGroupIDLT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLT(FieldBreakageTransactionGroupID, v)) +} + +// BreakageTransactionGroupIDLTE applies the LTE predicate on the "breakage_transaction_group_id" field. +func BreakageTransactionGroupIDLTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLTE(FieldBreakageTransactionGroupID, v)) +} + +// BreakageTransactionGroupIDContains applies the Contains predicate on the "breakage_transaction_group_id" field. +func BreakageTransactionGroupIDContains(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContains(FieldBreakageTransactionGroupID, v)) +} + +// BreakageTransactionGroupIDHasPrefix applies the HasPrefix predicate on the "breakage_transaction_group_id" field. +func BreakageTransactionGroupIDHasPrefix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasPrefix(FieldBreakageTransactionGroupID, v)) +} + +// BreakageTransactionGroupIDHasSuffix applies the HasSuffix predicate on the "breakage_transaction_group_id" field. +func BreakageTransactionGroupIDHasSuffix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasSuffix(FieldBreakageTransactionGroupID, v)) +} + +// BreakageTransactionGroupIDEqualFold applies the EqualFold predicate on the "breakage_transaction_group_id" field. +func BreakageTransactionGroupIDEqualFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEqualFold(FieldBreakageTransactionGroupID, v)) +} + +// BreakageTransactionGroupIDContainsFold applies the ContainsFold predicate on the "breakage_transaction_group_id" field. +func BreakageTransactionGroupIDContainsFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContainsFold(FieldBreakageTransactionGroupID, v)) +} + +// BreakageTransactionIDEQ applies the EQ predicate on the "breakage_transaction_id" field. +func BreakageTransactionIDEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldBreakageTransactionID, v)) +} + +// BreakageTransactionIDNEQ applies the NEQ predicate on the "breakage_transaction_id" field. +func BreakageTransactionIDNEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldBreakageTransactionID, v)) +} + +// BreakageTransactionIDIn applies the In predicate on the "breakage_transaction_id" field. +func BreakageTransactionIDIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldBreakageTransactionID, vs...)) +} + +// BreakageTransactionIDNotIn applies the NotIn predicate on the "breakage_transaction_id" field. +func BreakageTransactionIDNotIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldBreakageTransactionID, vs...)) +} + +// BreakageTransactionIDGT applies the GT predicate on the "breakage_transaction_id" field. +func BreakageTransactionIDGT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGT(FieldBreakageTransactionID, v)) +} + +// BreakageTransactionIDGTE applies the GTE predicate on the "breakage_transaction_id" field. +func BreakageTransactionIDGTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGTE(FieldBreakageTransactionID, v)) +} + +// BreakageTransactionIDLT applies the LT predicate on the "breakage_transaction_id" field. +func BreakageTransactionIDLT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLT(FieldBreakageTransactionID, v)) +} + +// BreakageTransactionIDLTE applies the LTE predicate on the "breakage_transaction_id" field. +func BreakageTransactionIDLTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLTE(FieldBreakageTransactionID, v)) +} + +// BreakageTransactionIDContains applies the Contains predicate on the "breakage_transaction_id" field. +func BreakageTransactionIDContains(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContains(FieldBreakageTransactionID, v)) +} + +// BreakageTransactionIDHasPrefix applies the HasPrefix predicate on the "breakage_transaction_id" field. +func BreakageTransactionIDHasPrefix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasPrefix(FieldBreakageTransactionID, v)) +} + +// BreakageTransactionIDHasSuffix applies the HasSuffix predicate on the "breakage_transaction_id" field. +func BreakageTransactionIDHasSuffix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasSuffix(FieldBreakageTransactionID, v)) +} + +// BreakageTransactionIDEqualFold applies the EqualFold predicate on the "breakage_transaction_id" field. +func BreakageTransactionIDEqualFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEqualFold(FieldBreakageTransactionID, v)) +} + +// BreakageTransactionIDContainsFold applies the ContainsFold predicate on the "breakage_transaction_id" field. +func BreakageTransactionIDContainsFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContainsFold(FieldBreakageTransactionID, v)) +} + +// FboSubAccountIDEQ applies the EQ predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldFboSubAccountID, v)) +} + +// FboSubAccountIDNEQ applies the NEQ predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDNEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldFboSubAccountID, v)) +} + +// FboSubAccountIDIn applies the In predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldFboSubAccountID, vs...)) +} + +// FboSubAccountIDNotIn applies the NotIn predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDNotIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldFboSubAccountID, vs...)) +} + +// FboSubAccountIDGT applies the GT predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDGT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGT(FieldFboSubAccountID, v)) +} + +// FboSubAccountIDGTE applies the GTE predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDGTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGTE(FieldFboSubAccountID, v)) +} + +// FboSubAccountIDLT applies the LT predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDLT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLT(FieldFboSubAccountID, v)) +} + +// FboSubAccountIDLTE applies the LTE predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDLTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLTE(FieldFboSubAccountID, v)) +} + +// FboSubAccountIDContains applies the Contains predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDContains(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContains(FieldFboSubAccountID, v)) +} + +// FboSubAccountIDHasPrefix applies the HasPrefix predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDHasPrefix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasPrefix(FieldFboSubAccountID, v)) +} + +// FboSubAccountIDHasSuffix applies the HasSuffix predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDHasSuffix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasSuffix(FieldFboSubAccountID, v)) +} + +// FboSubAccountIDEqualFold applies the EqualFold predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDEqualFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEqualFold(FieldFboSubAccountID, v)) +} + +// FboSubAccountIDContainsFold applies the ContainsFold predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDContainsFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContainsFold(FieldFboSubAccountID, v)) +} + +// BreakageSubAccountIDEQ applies the EQ predicate on the "breakage_sub_account_id" field. +func BreakageSubAccountIDEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldBreakageSubAccountID, v)) +} + +// BreakageSubAccountIDNEQ applies the NEQ predicate on the "breakage_sub_account_id" field. +func BreakageSubAccountIDNEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldBreakageSubAccountID, v)) +} + +// BreakageSubAccountIDIn applies the In predicate on the "breakage_sub_account_id" field. +func BreakageSubAccountIDIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldBreakageSubAccountID, vs...)) +} + +// BreakageSubAccountIDNotIn applies the NotIn predicate on the "breakage_sub_account_id" field. +func BreakageSubAccountIDNotIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldBreakageSubAccountID, vs...)) +} + +// BreakageSubAccountIDGT applies the GT predicate on the "breakage_sub_account_id" field. +func BreakageSubAccountIDGT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGT(FieldBreakageSubAccountID, v)) +} + +// BreakageSubAccountIDGTE applies the GTE predicate on the "breakage_sub_account_id" field. +func BreakageSubAccountIDGTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGTE(FieldBreakageSubAccountID, v)) +} + +// BreakageSubAccountIDLT applies the LT predicate on the "breakage_sub_account_id" field. +func BreakageSubAccountIDLT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLT(FieldBreakageSubAccountID, v)) +} + +// BreakageSubAccountIDLTE applies the LTE predicate on the "breakage_sub_account_id" field. +func BreakageSubAccountIDLTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLTE(FieldBreakageSubAccountID, v)) +} + +// BreakageSubAccountIDContains applies the Contains predicate on the "breakage_sub_account_id" field. +func BreakageSubAccountIDContains(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContains(FieldBreakageSubAccountID, v)) +} + +// BreakageSubAccountIDHasPrefix applies the HasPrefix predicate on the "breakage_sub_account_id" field. +func BreakageSubAccountIDHasPrefix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasPrefix(FieldBreakageSubAccountID, v)) +} + +// BreakageSubAccountIDHasSuffix applies the HasSuffix predicate on the "breakage_sub_account_id" field. +func BreakageSubAccountIDHasSuffix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasSuffix(FieldBreakageSubAccountID, v)) +} + +// BreakageSubAccountIDEqualFold applies the EqualFold predicate on the "breakage_sub_account_id" field. +func BreakageSubAccountIDEqualFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEqualFold(FieldBreakageSubAccountID, v)) +} + +// BreakageSubAccountIDContainsFold applies the ContainsFold predicate on the "breakage_sub_account_id" field. +func BreakageSubAccountIDContainsFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContainsFold(FieldBreakageSubAccountID, v)) +} + +// PlanIDEQ applies the EQ predicate on the "plan_id" field. +func PlanIDEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldPlanID, v)) +} + +// PlanIDNEQ applies the NEQ predicate on the "plan_id" field. +func PlanIDNEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldPlanID, v)) +} + +// PlanIDIn applies the In predicate on the "plan_id" field. +func PlanIDIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldPlanID, vs...)) +} + +// PlanIDNotIn applies the NotIn predicate on the "plan_id" field. +func PlanIDNotIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldPlanID, vs...)) +} + +// PlanIDGT applies the GT predicate on the "plan_id" field. +func PlanIDGT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGT(FieldPlanID, v)) +} + +// PlanIDGTE applies the GTE predicate on the "plan_id" field. +func PlanIDGTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGTE(FieldPlanID, v)) +} + +// PlanIDLT applies the LT predicate on the "plan_id" field. +func PlanIDLT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLT(FieldPlanID, v)) +} + +// PlanIDLTE applies the LTE predicate on the "plan_id" field. +func PlanIDLTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLTE(FieldPlanID, v)) +} + +// PlanIDContains applies the Contains predicate on the "plan_id" field. +func PlanIDContains(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContains(FieldPlanID, v)) +} + +// PlanIDHasPrefix applies the HasPrefix predicate on the "plan_id" field. +func PlanIDHasPrefix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasPrefix(FieldPlanID, v)) +} + +// PlanIDHasSuffix applies the HasSuffix predicate on the "plan_id" field. +func PlanIDHasSuffix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasSuffix(FieldPlanID, v)) +} + +// PlanIDIsNil applies the IsNil predicate on the "plan_id" field. +func PlanIDIsNil() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIsNull(FieldPlanID)) +} + +// PlanIDNotNil applies the NotNil predicate on the "plan_id" field. +func PlanIDNotNil() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotNull(FieldPlanID)) +} + +// PlanIDEqualFold applies the EqualFold predicate on the "plan_id" field. +func PlanIDEqualFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEqualFold(FieldPlanID, v)) +} + +// PlanIDContainsFold applies the ContainsFold predicate on the "plan_id" field. +func PlanIDContainsFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContainsFold(FieldPlanID, v)) +} + +// ReleaseIDEQ applies the EQ predicate on the "release_id" field. +func ReleaseIDEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEQ(FieldReleaseID, v)) +} + +// ReleaseIDNEQ applies the NEQ predicate on the "release_id" field. +func ReleaseIDNEQ(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNEQ(FieldReleaseID, v)) +} + +// ReleaseIDIn applies the In predicate on the "release_id" field. +func ReleaseIDIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIn(FieldReleaseID, vs...)) +} + +// ReleaseIDNotIn applies the NotIn predicate on the "release_id" field. +func ReleaseIDNotIn(vs ...string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotIn(FieldReleaseID, vs...)) +} + +// ReleaseIDGT applies the GT predicate on the "release_id" field. +func ReleaseIDGT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGT(FieldReleaseID, v)) +} + +// ReleaseIDGTE applies the GTE predicate on the "release_id" field. +func ReleaseIDGTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldGTE(FieldReleaseID, v)) +} + +// ReleaseIDLT applies the LT predicate on the "release_id" field. +func ReleaseIDLT(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLT(FieldReleaseID, v)) +} + +// ReleaseIDLTE applies the LTE predicate on the "release_id" field. +func ReleaseIDLTE(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldLTE(FieldReleaseID, v)) +} + +// ReleaseIDContains applies the Contains predicate on the "release_id" field. +func ReleaseIDContains(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContains(FieldReleaseID, v)) +} + +// ReleaseIDHasPrefix applies the HasPrefix predicate on the "release_id" field. +func ReleaseIDHasPrefix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasPrefix(FieldReleaseID, v)) +} + +// ReleaseIDHasSuffix applies the HasSuffix predicate on the "release_id" field. +func ReleaseIDHasSuffix(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldHasSuffix(FieldReleaseID, v)) +} + +// ReleaseIDIsNil applies the IsNil predicate on the "release_id" field. +func ReleaseIDIsNil() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldIsNull(FieldReleaseID)) +} + +// ReleaseIDNotNil applies the NotNil predicate on the "release_id" field. +func ReleaseIDNotNil() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldNotNull(FieldReleaseID)) +} + +// ReleaseIDEqualFold applies the EqualFold predicate on the "release_id" field. +func ReleaseIDEqualFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldEqualFold(FieldReleaseID, v)) +} + +// ReleaseIDContainsFold applies the ContainsFold predicate on the "release_id" field. +func ReleaseIDContainsFold(v string) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.FieldContainsFold(FieldReleaseID, v)) +} + +// HasSourceTransactionGroup applies the HasEdge predicate on the "source_transaction_group" edge. +func HasSourceTransactionGroup() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SourceTransactionGroupTable, SourceTransactionGroupColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSourceTransactionGroupWith applies the HasEdge predicate on the "source_transaction_group" edge with a given conditions (other predicates). +func HasSourceTransactionGroupWith(preds ...predicate.LedgerTransactionGroup) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := newSourceTransactionGroupStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSourceTransaction applies the HasEdge predicate on the "source_transaction" edge. +func HasSourceTransaction() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SourceTransactionTable, SourceTransactionColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSourceTransactionWith applies the HasEdge predicate on the "source_transaction" edge with a given conditions (other predicates). +func HasSourceTransactionWith(preds ...predicate.LedgerTransaction) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := newSourceTransactionStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSourceEntry applies the HasEdge predicate on the "source_entry" edge. +func HasSourceEntry() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SourceEntryTable, SourceEntryColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSourceEntryWith applies the HasEdge predicate on the "source_entry" edge with a given conditions (other predicates). +func HasSourceEntryWith(preds ...predicate.LedgerEntry) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := newSourceEntryStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasBreakageTransactionGroup applies the HasEdge predicate on the "breakage_transaction_group" edge. +func HasBreakageTransactionGroup() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, BreakageTransactionGroupTable, BreakageTransactionGroupColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBreakageTransactionGroupWith applies the HasEdge predicate on the "breakage_transaction_group" edge with a given conditions (other predicates). +func HasBreakageTransactionGroupWith(preds ...predicate.LedgerTransactionGroup) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := newBreakageTransactionGroupStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasBreakageTransaction applies the HasEdge predicate on the "breakage_transaction" edge. +func HasBreakageTransaction() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, BreakageTransactionTable, BreakageTransactionColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBreakageTransactionWith applies the HasEdge predicate on the "breakage_transaction" edge with a given conditions (other predicates). +func HasBreakageTransactionWith(preds ...predicate.LedgerTransaction) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := newBreakageTransactionStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasFboSubAccount applies the HasEdge predicate on the "fbo_sub_account" edge. +func HasFboSubAccount() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, FboSubAccountTable, FboSubAccountColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasFboSubAccountWith applies the HasEdge predicate on the "fbo_sub_account" edge with a given conditions (other predicates). +func HasFboSubAccountWith(preds ...predicate.LedgerSubAccount) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := newFboSubAccountStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasBreakageSubAccount applies the HasEdge predicate on the "breakage_sub_account" edge. +func HasBreakageSubAccount() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, BreakageSubAccountTable, BreakageSubAccountColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBreakageSubAccountWith applies the HasEdge predicate on the "breakage_sub_account" edge with a given conditions (other predicates). +func HasBreakageSubAccountWith(preds ...predicate.LedgerSubAccount) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := newBreakageSubAccountStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasPlannedReleases applies the HasEdge predicate on the "planned_releases" edge. +func HasPlannedReleases() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, PlannedReleasesTable, PlannedReleasesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasPlannedReleasesWith applies the HasEdge predicate on the "planned_releases" edge with a given conditions (other predicates). +func HasPlannedReleasesWith(preds ...predicate.LedgerBreakageRecord) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := newPlannedReleasesStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasReleaseReopens applies the HasEdge predicate on the "release_reopens" edge. +func HasReleaseReopens() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ReleaseReopensTable, ReleaseReopensColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasReleaseReopensWith applies the HasEdge predicate on the "release_reopens" edge with a given conditions (other predicates). +func HasReleaseReopensWith(preds ...predicate.LedgerBreakageRecord) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := newReleaseReopensStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasPlan applies the HasEdge predicate on the "plan" edge. +func HasPlan() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, PlanTable, PlanColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasPlanWith applies the HasEdge predicate on the "plan" edge with a given conditions (other predicates). +func HasPlanWith(preds ...predicate.LedgerBreakageRecord) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := newPlanStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasRelease applies the HasEdge predicate on the "release" edge. +func HasRelease() predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ReleaseTable, ReleaseColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasReleaseWith applies the HasEdge predicate on the "release" edge with a given conditions (other predicates). +func HasReleaseWith(preds ...predicate.LedgerBreakageRecord) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(func(s *sql.Selector) { + step := newReleaseStep() + 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.LedgerBreakageRecord) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LedgerBreakageRecord) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LedgerBreakageRecord) predicate.LedgerBreakageRecord { + return predicate.LedgerBreakageRecord(sql.NotPredicates(p)) +} diff --git a/ent/db/ledgerbreakagerecord_create.go b/ent/db/ledgerbreakagerecord_create.go new file mode 100644 index 0000000000000000000000000000000000000000..c4522ae57e8b953c0ce8d8297a8cff9cc403b149 --- /dev/null +++ b/ent/db/ledgerbreakagerecord_create.go @@ -0,0 +1,1394 @@ +// 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/ledgerbreakagerecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgerentry" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransaction" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransactiongroup" + "github.com/openmeterio/openmeter/openmeter/ledger" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerBreakageRecordCreate is the builder for creating a LedgerBreakageRecord entity. +type LedgerBreakageRecordCreate struct { + config + mutation *LedgerBreakageRecordMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *LedgerBreakageRecordCreate) SetNamespace(v string) *LedgerBreakageRecordCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *LedgerBreakageRecordCreate) SetAnnotations(v models.Annotations) *LedgerBreakageRecordCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *LedgerBreakageRecordCreate) SetCreatedAt(v time.Time) *LedgerBreakageRecordCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *LedgerBreakageRecordCreate) SetNillableCreatedAt(v *time.Time) *LedgerBreakageRecordCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *LedgerBreakageRecordCreate) SetUpdatedAt(v time.Time) *LedgerBreakageRecordCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *LedgerBreakageRecordCreate) SetNillableUpdatedAt(v *time.Time) *LedgerBreakageRecordCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *LedgerBreakageRecordCreate) SetDeletedAt(v time.Time) *LedgerBreakageRecordCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *LedgerBreakageRecordCreate) SetNillableDeletedAt(v *time.Time) *LedgerBreakageRecordCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetKind sets the "kind" field. +func (_c *LedgerBreakageRecordCreate) SetKind(v ledger.BreakageKind) *LedgerBreakageRecordCreate { + _c.mutation.SetKind(v) + return _c +} + +// SetAmount sets the "amount" field. +func (_c *LedgerBreakageRecordCreate) SetAmount(v alpacadecimal.Decimal) *LedgerBreakageRecordCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetCustomerID sets the "customer_id" field. +func (_c *LedgerBreakageRecordCreate) SetCustomerID(v string) *LedgerBreakageRecordCreate { + _c.mutation.SetCustomerID(v) + return _c +} + +// SetCurrency sets the "currency" field. +func (_c *LedgerBreakageRecordCreate) SetCurrency(v currencyx.Code) *LedgerBreakageRecordCreate { + _c.mutation.SetCurrency(v) + return _c +} + +// SetCreditPriority sets the "credit_priority" field. +func (_c *LedgerBreakageRecordCreate) SetCreditPriority(v int) *LedgerBreakageRecordCreate { + _c.mutation.SetCreditPriority(v) + return _c +} + +// SetExpiresAt sets the "expires_at" field. +func (_c *LedgerBreakageRecordCreate) SetExpiresAt(v time.Time) *LedgerBreakageRecordCreate { + _c.mutation.SetExpiresAt(v) + return _c +} + +// SetSourceKind sets the "source_kind" field. +func (_c *LedgerBreakageRecordCreate) SetSourceKind(v ledger.BreakageSourceKind) *LedgerBreakageRecordCreate { + _c.mutation.SetSourceKind(v) + return _c +} + +// SetSourceChargeID sets the "source_charge_id" field. +func (_c *LedgerBreakageRecordCreate) SetSourceChargeID(v string) *LedgerBreakageRecordCreate { + _c.mutation.SetSourceChargeID(v) + return _c +} + +// SetNillableSourceChargeID sets the "source_charge_id" field if the given value is not nil. +func (_c *LedgerBreakageRecordCreate) SetNillableSourceChargeID(v *string) *LedgerBreakageRecordCreate { + if v != nil { + _c.SetSourceChargeID(*v) + } + return _c +} + +// SetSourceTransactionGroupID sets the "source_transaction_group_id" field. +func (_c *LedgerBreakageRecordCreate) SetSourceTransactionGroupID(v string) *LedgerBreakageRecordCreate { + _c.mutation.SetSourceTransactionGroupID(v) + return _c +} + +// SetNillableSourceTransactionGroupID sets the "source_transaction_group_id" field if the given value is not nil. +func (_c *LedgerBreakageRecordCreate) SetNillableSourceTransactionGroupID(v *string) *LedgerBreakageRecordCreate { + if v != nil { + _c.SetSourceTransactionGroupID(*v) + } + return _c +} + +// SetSourceTransactionID sets the "source_transaction_id" field. +func (_c *LedgerBreakageRecordCreate) SetSourceTransactionID(v string) *LedgerBreakageRecordCreate { + _c.mutation.SetSourceTransactionID(v) + return _c +} + +// SetNillableSourceTransactionID sets the "source_transaction_id" field if the given value is not nil. +func (_c *LedgerBreakageRecordCreate) SetNillableSourceTransactionID(v *string) *LedgerBreakageRecordCreate { + if v != nil { + _c.SetSourceTransactionID(*v) + } + return _c +} + +// SetSourceEntryID sets the "source_entry_id" field. +func (_c *LedgerBreakageRecordCreate) SetSourceEntryID(v string) *LedgerBreakageRecordCreate { + _c.mutation.SetSourceEntryID(v) + return _c +} + +// SetNillableSourceEntryID sets the "source_entry_id" field if the given value is not nil. +func (_c *LedgerBreakageRecordCreate) SetNillableSourceEntryID(v *string) *LedgerBreakageRecordCreate { + if v != nil { + _c.SetSourceEntryID(*v) + } + return _c +} + +// SetBreakageTransactionGroupID sets the "breakage_transaction_group_id" field. +func (_c *LedgerBreakageRecordCreate) SetBreakageTransactionGroupID(v string) *LedgerBreakageRecordCreate { + _c.mutation.SetBreakageTransactionGroupID(v) + return _c +} + +// SetBreakageTransactionID sets the "breakage_transaction_id" field. +func (_c *LedgerBreakageRecordCreate) SetBreakageTransactionID(v string) *LedgerBreakageRecordCreate { + _c.mutation.SetBreakageTransactionID(v) + return _c +} + +// SetFboSubAccountID sets the "fbo_sub_account_id" field. +func (_c *LedgerBreakageRecordCreate) SetFboSubAccountID(v string) *LedgerBreakageRecordCreate { + _c.mutation.SetFboSubAccountID(v) + return _c +} + +// SetBreakageSubAccountID sets the "breakage_sub_account_id" field. +func (_c *LedgerBreakageRecordCreate) SetBreakageSubAccountID(v string) *LedgerBreakageRecordCreate { + _c.mutation.SetBreakageSubAccountID(v) + return _c +} + +// SetPlanID sets the "plan_id" field. +func (_c *LedgerBreakageRecordCreate) SetPlanID(v string) *LedgerBreakageRecordCreate { + _c.mutation.SetPlanID(v) + return _c +} + +// SetNillablePlanID sets the "plan_id" field if the given value is not nil. +func (_c *LedgerBreakageRecordCreate) SetNillablePlanID(v *string) *LedgerBreakageRecordCreate { + if v != nil { + _c.SetPlanID(*v) + } + return _c +} + +// SetReleaseID sets the "release_id" field. +func (_c *LedgerBreakageRecordCreate) SetReleaseID(v string) *LedgerBreakageRecordCreate { + _c.mutation.SetReleaseID(v) + return _c +} + +// SetNillableReleaseID sets the "release_id" field if the given value is not nil. +func (_c *LedgerBreakageRecordCreate) SetNillableReleaseID(v *string) *LedgerBreakageRecordCreate { + if v != nil { + _c.SetReleaseID(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *LedgerBreakageRecordCreate) SetID(v string) *LedgerBreakageRecordCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *LedgerBreakageRecordCreate) SetNillableID(v *string) *LedgerBreakageRecordCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetSourceTransactionGroup sets the "source_transaction_group" edge to the LedgerTransactionGroup entity. +func (_c *LedgerBreakageRecordCreate) SetSourceTransactionGroup(v *LedgerTransactionGroup) *LedgerBreakageRecordCreate { + return _c.SetSourceTransactionGroupID(v.ID) +} + +// SetSourceTransaction sets the "source_transaction" edge to the LedgerTransaction entity. +func (_c *LedgerBreakageRecordCreate) SetSourceTransaction(v *LedgerTransaction) *LedgerBreakageRecordCreate { + return _c.SetSourceTransactionID(v.ID) +} + +// SetSourceEntry sets the "source_entry" edge to the LedgerEntry entity. +func (_c *LedgerBreakageRecordCreate) SetSourceEntry(v *LedgerEntry) *LedgerBreakageRecordCreate { + return _c.SetSourceEntryID(v.ID) +} + +// SetBreakageTransactionGroup sets the "breakage_transaction_group" edge to the LedgerTransactionGroup entity. +func (_c *LedgerBreakageRecordCreate) SetBreakageTransactionGroup(v *LedgerTransactionGroup) *LedgerBreakageRecordCreate { + return _c.SetBreakageTransactionGroupID(v.ID) +} + +// SetBreakageTransaction sets the "breakage_transaction" edge to the LedgerTransaction entity. +func (_c *LedgerBreakageRecordCreate) SetBreakageTransaction(v *LedgerTransaction) *LedgerBreakageRecordCreate { + return _c.SetBreakageTransactionID(v.ID) +} + +// SetFboSubAccount sets the "fbo_sub_account" edge to the LedgerSubAccount entity. +func (_c *LedgerBreakageRecordCreate) SetFboSubAccount(v *LedgerSubAccount) *LedgerBreakageRecordCreate { + return _c.SetFboSubAccountID(v.ID) +} + +// SetBreakageSubAccount sets the "breakage_sub_account" edge to the LedgerSubAccount entity. +func (_c *LedgerBreakageRecordCreate) SetBreakageSubAccount(v *LedgerSubAccount) *LedgerBreakageRecordCreate { + return _c.SetBreakageSubAccountID(v.ID) +} + +// AddPlannedReleaseIDs adds the "planned_releases" edge to the LedgerBreakageRecord entity by IDs. +func (_c *LedgerBreakageRecordCreate) AddPlannedReleaseIDs(ids ...string) *LedgerBreakageRecordCreate { + _c.mutation.AddPlannedReleaseIDs(ids...) + return _c +} + +// AddPlannedReleases adds the "planned_releases" edges to the LedgerBreakageRecord entity. +func (_c *LedgerBreakageRecordCreate) AddPlannedReleases(v ...*LedgerBreakageRecord) *LedgerBreakageRecordCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddPlannedReleaseIDs(ids...) +} + +// AddReleaseReopenIDs adds the "release_reopens" edge to the LedgerBreakageRecord entity by IDs. +func (_c *LedgerBreakageRecordCreate) AddReleaseReopenIDs(ids ...string) *LedgerBreakageRecordCreate { + _c.mutation.AddReleaseReopenIDs(ids...) + return _c +} + +// AddReleaseReopens adds the "release_reopens" edges to the LedgerBreakageRecord entity. +func (_c *LedgerBreakageRecordCreate) AddReleaseReopens(v ...*LedgerBreakageRecord) *LedgerBreakageRecordCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddReleaseReopenIDs(ids...) +} + +// SetPlan sets the "plan" edge to the LedgerBreakageRecord entity. +func (_c *LedgerBreakageRecordCreate) SetPlan(v *LedgerBreakageRecord) *LedgerBreakageRecordCreate { + return _c.SetPlanID(v.ID) +} + +// SetRelease sets the "release" edge to the LedgerBreakageRecord entity. +func (_c *LedgerBreakageRecordCreate) SetRelease(v *LedgerBreakageRecord) *LedgerBreakageRecordCreate { + return _c.SetReleaseID(v.ID) +} + +// Mutation returns the LedgerBreakageRecordMutation object of the builder. +func (_c *LedgerBreakageRecordCreate) Mutation() *LedgerBreakageRecordMutation { + return _c.mutation +} + +// Save creates the LedgerBreakageRecord in the database. +func (_c *LedgerBreakageRecordCreate) Save(ctx context.Context) (*LedgerBreakageRecord, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *LedgerBreakageRecordCreate) SaveX(ctx context.Context) *LedgerBreakageRecord { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LedgerBreakageRecordCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LedgerBreakageRecordCreate) 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 *LedgerBreakageRecordCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := ledgerbreakagerecord.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := ledgerbreakagerecord.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := ledgerbreakagerecord.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *LedgerBreakageRecordCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "LedgerBreakageRecord.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := ledgerbreakagerecord.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "LedgerBreakageRecord.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "LedgerBreakageRecord.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "LedgerBreakageRecord.updated_at"`)} + } + if _, ok := _c.mutation.Kind(); !ok { + return &ValidationError{Name: "kind", err: errors.New(`db: missing required field "LedgerBreakageRecord.kind"`)} + } + if v, ok := _c.mutation.Kind(); ok { + if err := ledgerbreakagerecord.KindValidator(v); err != nil { + return &ValidationError{Name: "kind", err: fmt.Errorf(`db: validator failed for field "LedgerBreakageRecord.kind": %w`, err)} + } + } + if _, ok := _c.mutation.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`db: missing required field "LedgerBreakageRecord.amount"`)} + } + if _, ok := _c.mutation.CustomerID(); !ok { + return &ValidationError{Name: "customer_id", err: errors.New(`db: missing required field "LedgerBreakageRecord.customer_id"`)} + } + if v, ok := _c.mutation.CustomerID(); ok { + if err := ledgerbreakagerecord.CustomerIDValidator(v); err != nil { + return &ValidationError{Name: "customer_id", err: fmt.Errorf(`db: validator failed for field "LedgerBreakageRecord.customer_id": %w`, err)} + } + } + if _, ok := _c.mutation.Currency(); !ok { + return &ValidationError{Name: "currency", err: errors.New(`db: missing required field "LedgerBreakageRecord.currency"`)} + } + if v, ok := _c.mutation.Currency(); ok { + if err := ledgerbreakagerecord.CurrencyValidator(string(v)); err != nil { + return &ValidationError{Name: "currency", err: fmt.Errorf(`db: validator failed for field "LedgerBreakageRecord.currency": %w`, err)} + } + } + if _, ok := _c.mutation.CreditPriority(); !ok { + return &ValidationError{Name: "credit_priority", err: errors.New(`db: missing required field "LedgerBreakageRecord.credit_priority"`)} + } + if _, ok := _c.mutation.ExpiresAt(); !ok { + return &ValidationError{Name: "expires_at", err: errors.New(`db: missing required field "LedgerBreakageRecord.expires_at"`)} + } + if _, ok := _c.mutation.SourceKind(); !ok { + return &ValidationError{Name: "source_kind", err: errors.New(`db: missing required field "LedgerBreakageRecord.source_kind"`)} + } + if v, ok := _c.mutation.SourceKind(); ok { + if err := ledgerbreakagerecord.SourceKindValidator(v); err != nil { + return &ValidationError{Name: "source_kind", err: fmt.Errorf(`db: validator failed for field "LedgerBreakageRecord.source_kind": %w`, err)} + } + } + if _, ok := _c.mutation.BreakageTransactionGroupID(); !ok { + return &ValidationError{Name: "breakage_transaction_group_id", err: errors.New(`db: missing required field "LedgerBreakageRecord.breakage_transaction_group_id"`)} + } + if v, ok := _c.mutation.BreakageTransactionGroupID(); ok { + if err := ledgerbreakagerecord.BreakageTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "breakage_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "LedgerBreakageRecord.breakage_transaction_group_id": %w`, err)} + } + } + if _, ok := _c.mutation.BreakageTransactionID(); !ok { + return &ValidationError{Name: "breakage_transaction_id", err: errors.New(`db: missing required field "LedgerBreakageRecord.breakage_transaction_id"`)} + } + if v, ok := _c.mutation.BreakageTransactionID(); ok { + if err := ledgerbreakagerecord.BreakageTransactionIDValidator(v); err != nil { + return &ValidationError{Name: "breakage_transaction_id", err: fmt.Errorf(`db: validator failed for field "LedgerBreakageRecord.breakage_transaction_id": %w`, err)} + } + } + if _, ok := _c.mutation.FboSubAccountID(); !ok { + return &ValidationError{Name: "fbo_sub_account_id", err: errors.New(`db: missing required field "LedgerBreakageRecord.fbo_sub_account_id"`)} + } + if v, ok := _c.mutation.FboSubAccountID(); ok { + if err := ledgerbreakagerecord.FboSubAccountIDValidator(v); err != nil { + return &ValidationError{Name: "fbo_sub_account_id", err: fmt.Errorf(`db: validator failed for field "LedgerBreakageRecord.fbo_sub_account_id": %w`, err)} + } + } + if _, ok := _c.mutation.BreakageSubAccountID(); !ok { + return &ValidationError{Name: "breakage_sub_account_id", err: errors.New(`db: missing required field "LedgerBreakageRecord.breakage_sub_account_id"`)} + } + if v, ok := _c.mutation.BreakageSubAccountID(); ok { + if err := ledgerbreakagerecord.BreakageSubAccountIDValidator(v); err != nil { + return &ValidationError{Name: "breakage_sub_account_id", err: fmt.Errorf(`db: validator failed for field "LedgerBreakageRecord.breakage_sub_account_id": %w`, err)} + } + } + if len(_c.mutation.BreakageTransactionGroupIDs()) == 0 { + return &ValidationError{Name: "breakage_transaction_group", err: errors.New(`db: missing required edge "LedgerBreakageRecord.breakage_transaction_group"`)} + } + if len(_c.mutation.BreakageTransactionIDs()) == 0 { + return &ValidationError{Name: "breakage_transaction", err: errors.New(`db: missing required edge "LedgerBreakageRecord.breakage_transaction"`)} + } + if len(_c.mutation.FboSubAccountIDs()) == 0 { + return &ValidationError{Name: "fbo_sub_account", err: errors.New(`db: missing required edge "LedgerBreakageRecord.fbo_sub_account"`)} + } + if len(_c.mutation.BreakageSubAccountIDs()) == 0 { + return &ValidationError{Name: "breakage_sub_account", err: errors.New(`db: missing required edge "LedgerBreakageRecord.breakage_sub_account"`)} + } + return nil +} + +func (_c *LedgerBreakageRecordCreate) sqlSave(ctx context.Context) (*LedgerBreakageRecord, 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 LedgerBreakageRecord.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *LedgerBreakageRecordCreate) createSpec() (*LedgerBreakageRecord, *sqlgraph.CreateSpec) { + var ( + _node = &LedgerBreakageRecord{config: _c.config} + _spec = sqlgraph.NewCreateSpec(ledgerbreakagerecord.Table, sqlgraph.NewFieldSpec(ledgerbreakagerecord.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(ledgerbreakagerecord.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(ledgerbreakagerecord.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(ledgerbreakagerecord.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(ledgerbreakagerecord.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(ledgerbreakagerecord.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Kind(); ok { + _spec.SetField(ledgerbreakagerecord.FieldKind, field.TypeEnum, value) + _node.Kind = value + } + if value, ok := _c.mutation.Amount(); ok { + _spec.SetField(ledgerbreakagerecord.FieldAmount, field.TypeOther, value) + _node.Amount = value + } + if value, ok := _c.mutation.CustomerID(); ok { + _spec.SetField(ledgerbreakagerecord.FieldCustomerID, field.TypeString, value) + _node.CustomerID = value + } + if value, ok := _c.mutation.Currency(); ok { + _spec.SetField(ledgerbreakagerecord.FieldCurrency, field.TypeString, value) + _node.Currency = value + } + if value, ok := _c.mutation.CreditPriority(); ok { + _spec.SetField(ledgerbreakagerecord.FieldCreditPriority, field.TypeInt, value) + _node.CreditPriority = value + } + if value, ok := _c.mutation.ExpiresAt(); ok { + _spec.SetField(ledgerbreakagerecord.FieldExpiresAt, field.TypeTime, value) + _node.ExpiresAt = value + } + if value, ok := _c.mutation.SourceKind(); ok { + _spec.SetField(ledgerbreakagerecord.FieldSourceKind, field.TypeEnum, value) + _node.SourceKind = value + } + if value, ok := _c.mutation.SourceChargeID(); ok { + _spec.SetField(ledgerbreakagerecord.FieldSourceChargeID, field.TypeString, value) + _node.SourceChargeID = &value + } + if nodes := _c.mutation.SourceTransactionGroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: ledgerbreakagerecord.SourceTransactionGroupTable, + Columns: []string{ledgerbreakagerecord.SourceTransactionGroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgertransactiongroup.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.SourceTransactionGroupID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.SourceTransactionIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: ledgerbreakagerecord.SourceTransactionTable, + Columns: []string{ledgerbreakagerecord.SourceTransactionColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgertransaction.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.SourceTransactionID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.SourceEntryIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: ledgerbreakagerecord.SourceEntryTable, + Columns: []string{ledgerbreakagerecord.SourceEntryColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerentry.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.SourceEntryID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.BreakageTransactionGroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: ledgerbreakagerecord.BreakageTransactionGroupTable, + Columns: []string{ledgerbreakagerecord.BreakageTransactionGroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgertransactiongroup.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.BreakageTransactionGroupID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.BreakageTransactionIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: ledgerbreakagerecord.BreakageTransactionTable, + Columns: []string{ledgerbreakagerecord.BreakageTransactionColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgertransaction.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.BreakageTransactionID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.FboSubAccountIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: ledgerbreakagerecord.FboSubAccountTable, + Columns: []string{ledgerbreakagerecord.FboSubAccountColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccount.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.FboSubAccountID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.BreakageSubAccountIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: ledgerbreakagerecord.BreakageSubAccountTable, + Columns: []string{ledgerbreakagerecord.BreakageSubAccountColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccount.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.BreakageSubAccountID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.PlannedReleasesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerbreakagerecord.PlannedReleasesTable, + Columns: []string{ledgerbreakagerecord.PlannedReleasesColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.ReleaseReopensIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerbreakagerecord.ReleaseReopensTable, + Columns: []string{ledgerbreakagerecord.ReleaseReopensColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.PlanIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: ledgerbreakagerecord.PlanTable, + Columns: []string{ledgerbreakagerecord.PlanColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.PlanID = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.ReleaseIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: ledgerbreakagerecord.ReleaseTable, + Columns: []string{ledgerbreakagerecord.ReleaseColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.ReleaseID = &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.LedgerBreakageRecord.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.LedgerBreakageRecordUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *LedgerBreakageRecordCreate) OnConflict(opts ...sql.ConflictOption) *LedgerBreakageRecordUpsertOne { + _c.conflict = opts + return &LedgerBreakageRecordUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.LedgerBreakageRecord.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *LedgerBreakageRecordCreate) OnConflictColumns(columns ...string) *LedgerBreakageRecordUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &LedgerBreakageRecordUpsertOne{ + create: _c, + } +} + +type ( + // LedgerBreakageRecordUpsertOne is the builder for "upsert"-ing + // one LedgerBreakageRecord node. + LedgerBreakageRecordUpsertOne struct { + create *LedgerBreakageRecordCreate + } + + // LedgerBreakageRecordUpsert is the "OnConflict" setter. + LedgerBreakageRecordUpsert struct { + *sql.UpdateSet + } +) + +// SetAnnotations sets the "annotations" field. +func (u *LedgerBreakageRecordUpsert) SetAnnotations(v models.Annotations) *LedgerBreakageRecordUpsert { + u.Set(ledgerbreakagerecord.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerBreakageRecordUpsert) UpdateAnnotations() *LedgerBreakageRecordUpsert { + u.SetExcluded(ledgerbreakagerecord.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerBreakageRecordUpsert) ClearAnnotations() *LedgerBreakageRecordUpsert { + u.SetNull(ledgerbreakagerecord.FieldAnnotations) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerBreakageRecordUpsert) SetUpdatedAt(v time.Time) *LedgerBreakageRecordUpsert { + u.Set(ledgerbreakagerecord.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerBreakageRecordUpsert) UpdateUpdatedAt() *LedgerBreakageRecordUpsert { + u.SetExcluded(ledgerbreakagerecord.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerBreakageRecordUpsert) SetDeletedAt(v time.Time) *LedgerBreakageRecordUpsert { + u.Set(ledgerbreakagerecord.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerBreakageRecordUpsert) UpdateDeletedAt() *LedgerBreakageRecordUpsert { + u.SetExcluded(ledgerbreakagerecord.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerBreakageRecordUpsert) ClearDeletedAt() *LedgerBreakageRecordUpsert { + u.SetNull(ledgerbreakagerecord.FieldDeletedAt) + return u +} + +// SetAmount sets the "amount" field. +func (u *LedgerBreakageRecordUpsert) SetAmount(v alpacadecimal.Decimal) *LedgerBreakageRecordUpsert { + u.Set(ledgerbreakagerecord.FieldAmount, v) + return u +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *LedgerBreakageRecordUpsert) UpdateAmount() *LedgerBreakageRecordUpsert { + u.SetExcluded(ledgerbreakagerecord.FieldAmount) + 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.LedgerBreakageRecord.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(ledgerbreakagerecord.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LedgerBreakageRecordUpsertOne) UpdateNewValues() *LedgerBreakageRecordUpsertOne { + 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(ledgerbreakagerecord.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldCreatedAt) + } + if _, exists := u.create.mutation.Kind(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldKind) + } + if _, exists := u.create.mutation.CustomerID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldCustomerID) + } + if _, exists := u.create.mutation.Currency(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldCurrency) + } + if _, exists := u.create.mutation.CreditPriority(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldCreditPriority) + } + if _, exists := u.create.mutation.ExpiresAt(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldExpiresAt) + } + if _, exists := u.create.mutation.SourceKind(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldSourceKind) + } + if _, exists := u.create.mutation.SourceChargeID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldSourceChargeID) + } + if _, exists := u.create.mutation.SourceTransactionGroupID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldSourceTransactionGroupID) + } + if _, exists := u.create.mutation.SourceTransactionID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldSourceTransactionID) + } + if _, exists := u.create.mutation.SourceEntryID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldSourceEntryID) + } + if _, exists := u.create.mutation.BreakageTransactionGroupID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldBreakageTransactionGroupID) + } + if _, exists := u.create.mutation.BreakageTransactionID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldBreakageTransactionID) + } + if _, exists := u.create.mutation.FboSubAccountID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldFboSubAccountID) + } + if _, exists := u.create.mutation.BreakageSubAccountID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldBreakageSubAccountID) + } + if _, exists := u.create.mutation.PlanID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldPlanID) + } + if _, exists := u.create.mutation.ReleaseID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldReleaseID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.LedgerBreakageRecord.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LedgerBreakageRecordUpsertOne) Ignore() *LedgerBreakageRecordUpsertOne { + 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 *LedgerBreakageRecordUpsertOne) DoNothing() *LedgerBreakageRecordUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LedgerBreakageRecordCreate.OnConflict +// documentation for more info. +func (u *LedgerBreakageRecordUpsertOne) Update(set func(*LedgerBreakageRecordUpsert)) *LedgerBreakageRecordUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LedgerBreakageRecordUpsert{UpdateSet: update}) + })) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *LedgerBreakageRecordUpsertOne) SetAnnotations(v models.Annotations) *LedgerBreakageRecordUpsertOne { + return u.Update(func(s *LedgerBreakageRecordUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerBreakageRecordUpsertOne) UpdateAnnotations() *LedgerBreakageRecordUpsertOne { + return u.Update(func(s *LedgerBreakageRecordUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerBreakageRecordUpsertOne) ClearAnnotations() *LedgerBreakageRecordUpsertOne { + return u.Update(func(s *LedgerBreakageRecordUpsert) { + s.ClearAnnotations() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerBreakageRecordUpsertOne) SetUpdatedAt(v time.Time) *LedgerBreakageRecordUpsertOne { + return u.Update(func(s *LedgerBreakageRecordUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerBreakageRecordUpsertOne) UpdateUpdatedAt() *LedgerBreakageRecordUpsertOne { + return u.Update(func(s *LedgerBreakageRecordUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerBreakageRecordUpsertOne) SetDeletedAt(v time.Time) *LedgerBreakageRecordUpsertOne { + return u.Update(func(s *LedgerBreakageRecordUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerBreakageRecordUpsertOne) UpdateDeletedAt() *LedgerBreakageRecordUpsertOne { + return u.Update(func(s *LedgerBreakageRecordUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerBreakageRecordUpsertOne) ClearDeletedAt() *LedgerBreakageRecordUpsertOne { + return u.Update(func(s *LedgerBreakageRecordUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAmount sets the "amount" field. +func (u *LedgerBreakageRecordUpsertOne) SetAmount(v alpacadecimal.Decimal) *LedgerBreakageRecordUpsertOne { + return u.Update(func(s *LedgerBreakageRecordUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *LedgerBreakageRecordUpsertOne) UpdateAmount() *LedgerBreakageRecordUpsertOne { + return u.Update(func(s *LedgerBreakageRecordUpsert) { + s.UpdateAmount() + }) +} + +// Exec executes the query. +func (u *LedgerBreakageRecordUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for LedgerBreakageRecordCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LedgerBreakageRecordUpsertOne) 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 *LedgerBreakageRecordUpsertOne) 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: LedgerBreakageRecordUpsertOne.ID is not supported by MySQL driver. Use LedgerBreakageRecordUpsertOne.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 *LedgerBreakageRecordUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// LedgerBreakageRecordCreateBulk is the builder for creating many LedgerBreakageRecord entities in bulk. +type LedgerBreakageRecordCreateBulk struct { + config + err error + builders []*LedgerBreakageRecordCreate + conflict []sql.ConflictOption +} + +// Save creates the LedgerBreakageRecord entities in the database. +func (_c *LedgerBreakageRecordCreateBulk) Save(ctx context.Context) ([]*LedgerBreakageRecord, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*LedgerBreakageRecord, 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.(*LedgerBreakageRecordMutation) + 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 *LedgerBreakageRecordCreateBulk) SaveX(ctx context.Context) []*LedgerBreakageRecord { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LedgerBreakageRecordCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LedgerBreakageRecordCreateBulk) 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.LedgerBreakageRecord.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.LedgerBreakageRecordUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *LedgerBreakageRecordCreateBulk) OnConflict(opts ...sql.ConflictOption) *LedgerBreakageRecordUpsertBulk { + _c.conflict = opts + return &LedgerBreakageRecordUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.LedgerBreakageRecord.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *LedgerBreakageRecordCreateBulk) OnConflictColumns(columns ...string) *LedgerBreakageRecordUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &LedgerBreakageRecordUpsertBulk{ + create: _c, + } +} + +// LedgerBreakageRecordUpsertBulk is the builder for "upsert"-ing +// a bulk of LedgerBreakageRecord nodes. +type LedgerBreakageRecordUpsertBulk struct { + create *LedgerBreakageRecordCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.LedgerBreakageRecord.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(ledgerbreakagerecord.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LedgerBreakageRecordUpsertBulk) UpdateNewValues() *LedgerBreakageRecordUpsertBulk { + 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(ledgerbreakagerecord.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldCreatedAt) + } + if _, exists := b.mutation.Kind(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldKind) + } + if _, exists := b.mutation.CustomerID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldCustomerID) + } + if _, exists := b.mutation.Currency(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldCurrency) + } + if _, exists := b.mutation.CreditPriority(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldCreditPriority) + } + if _, exists := b.mutation.ExpiresAt(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldExpiresAt) + } + if _, exists := b.mutation.SourceKind(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldSourceKind) + } + if _, exists := b.mutation.SourceChargeID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldSourceChargeID) + } + if _, exists := b.mutation.SourceTransactionGroupID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldSourceTransactionGroupID) + } + if _, exists := b.mutation.SourceTransactionID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldSourceTransactionID) + } + if _, exists := b.mutation.SourceEntryID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldSourceEntryID) + } + if _, exists := b.mutation.BreakageTransactionGroupID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldBreakageTransactionGroupID) + } + if _, exists := b.mutation.BreakageTransactionID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldBreakageTransactionID) + } + if _, exists := b.mutation.FboSubAccountID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldFboSubAccountID) + } + if _, exists := b.mutation.BreakageSubAccountID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldBreakageSubAccountID) + } + if _, exists := b.mutation.PlanID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldPlanID) + } + if _, exists := b.mutation.ReleaseID(); exists { + s.SetIgnore(ledgerbreakagerecord.FieldReleaseID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.LedgerBreakageRecord.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LedgerBreakageRecordUpsertBulk) Ignore() *LedgerBreakageRecordUpsertBulk { + 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 *LedgerBreakageRecordUpsertBulk) DoNothing() *LedgerBreakageRecordUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LedgerBreakageRecordCreateBulk.OnConflict +// documentation for more info. +func (u *LedgerBreakageRecordUpsertBulk) Update(set func(*LedgerBreakageRecordUpsert)) *LedgerBreakageRecordUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LedgerBreakageRecordUpsert{UpdateSet: update}) + })) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *LedgerBreakageRecordUpsertBulk) SetAnnotations(v models.Annotations) *LedgerBreakageRecordUpsertBulk { + return u.Update(func(s *LedgerBreakageRecordUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerBreakageRecordUpsertBulk) UpdateAnnotations() *LedgerBreakageRecordUpsertBulk { + return u.Update(func(s *LedgerBreakageRecordUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerBreakageRecordUpsertBulk) ClearAnnotations() *LedgerBreakageRecordUpsertBulk { + return u.Update(func(s *LedgerBreakageRecordUpsert) { + s.ClearAnnotations() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerBreakageRecordUpsertBulk) SetUpdatedAt(v time.Time) *LedgerBreakageRecordUpsertBulk { + return u.Update(func(s *LedgerBreakageRecordUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerBreakageRecordUpsertBulk) UpdateUpdatedAt() *LedgerBreakageRecordUpsertBulk { + return u.Update(func(s *LedgerBreakageRecordUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerBreakageRecordUpsertBulk) SetDeletedAt(v time.Time) *LedgerBreakageRecordUpsertBulk { + return u.Update(func(s *LedgerBreakageRecordUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerBreakageRecordUpsertBulk) UpdateDeletedAt() *LedgerBreakageRecordUpsertBulk { + return u.Update(func(s *LedgerBreakageRecordUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerBreakageRecordUpsertBulk) ClearDeletedAt() *LedgerBreakageRecordUpsertBulk { + return u.Update(func(s *LedgerBreakageRecordUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAmount sets the "amount" field. +func (u *LedgerBreakageRecordUpsertBulk) SetAmount(v alpacadecimal.Decimal) *LedgerBreakageRecordUpsertBulk { + return u.Update(func(s *LedgerBreakageRecordUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *LedgerBreakageRecordUpsertBulk) UpdateAmount() *LedgerBreakageRecordUpsertBulk { + return u.Update(func(s *LedgerBreakageRecordUpsert) { + s.UpdateAmount() + }) +} + +// Exec executes the query. +func (u *LedgerBreakageRecordUpsertBulk) 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 LedgerBreakageRecordCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for LedgerBreakageRecordCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LedgerBreakageRecordUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/ledgerbreakagerecord_delete.go b/ent/db/ledgerbreakagerecord_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..33892e4bf43fdb1c5f894041cd3b67eabfbd4504 --- /dev/null +++ b/ent/db/ledgerbreakagerecord_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/ledgerbreakagerecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LedgerBreakageRecordDelete is the builder for deleting a LedgerBreakageRecord entity. +type LedgerBreakageRecordDelete struct { + config + hooks []Hook + mutation *LedgerBreakageRecordMutation +} + +// Where appends a list predicates to the LedgerBreakageRecordDelete builder. +func (_d *LedgerBreakageRecordDelete) Where(ps ...predicate.LedgerBreakageRecord) *LedgerBreakageRecordDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *LedgerBreakageRecordDelete) 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 *LedgerBreakageRecordDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *LedgerBreakageRecordDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(ledgerbreakagerecord.Table, sqlgraph.NewFieldSpec(ledgerbreakagerecord.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 +} + +// LedgerBreakageRecordDeleteOne is the builder for deleting a single LedgerBreakageRecord entity. +type LedgerBreakageRecordDeleteOne struct { + _d *LedgerBreakageRecordDelete +} + +// Where appends a list predicates to the LedgerBreakageRecordDelete builder. +func (_d *LedgerBreakageRecordDeleteOne) Where(ps ...predicate.LedgerBreakageRecord) *LedgerBreakageRecordDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *LedgerBreakageRecordDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{ledgerbreakagerecord.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *LedgerBreakageRecordDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/ledgerbreakagerecord_query.go b/ent/db/ledgerbreakagerecord_query.go new file mode 100644 index 0000000000000000000000000000000000000000..21d7bb3f4015d9e8968ba2a7e6f832b83e04e894 --- /dev/null +++ b/ent/db/ledgerbreakagerecord_query.go @@ -0,0 +1,1410 @@ +// 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/ledgerbreakagerecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgerentry" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransaction" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransactiongroup" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LedgerBreakageRecordQuery is the builder for querying LedgerBreakageRecord entities. +type LedgerBreakageRecordQuery struct { + config + ctx *QueryContext + order []ledgerbreakagerecord.OrderOption + inters []Interceptor + predicates []predicate.LedgerBreakageRecord + withSourceTransactionGroup *LedgerTransactionGroupQuery + withSourceTransaction *LedgerTransactionQuery + withSourceEntry *LedgerEntryQuery + withBreakageTransactionGroup *LedgerTransactionGroupQuery + withBreakageTransaction *LedgerTransactionQuery + withFboSubAccount *LedgerSubAccountQuery + withBreakageSubAccount *LedgerSubAccountQuery + withPlannedReleases *LedgerBreakageRecordQuery + withReleaseReopens *LedgerBreakageRecordQuery + withPlan *LedgerBreakageRecordQuery + withRelease *LedgerBreakageRecordQuery + 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 LedgerBreakageRecordQuery builder. +func (_q *LedgerBreakageRecordQuery) Where(ps ...predicate.LedgerBreakageRecord) *LedgerBreakageRecordQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *LedgerBreakageRecordQuery) Limit(limit int) *LedgerBreakageRecordQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *LedgerBreakageRecordQuery) Offset(offset int) *LedgerBreakageRecordQuery { + _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 *LedgerBreakageRecordQuery) Unique(unique bool) *LedgerBreakageRecordQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *LedgerBreakageRecordQuery) Order(o ...ledgerbreakagerecord.OrderOption) *LedgerBreakageRecordQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QuerySourceTransactionGroup chains the current query on the "source_transaction_group" edge. +func (_q *LedgerBreakageRecordQuery) QuerySourceTransactionGroup() *LedgerTransactionGroupQuery { + query := (&LedgerTransactionGroupClient{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(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, selector), + sqlgraph.To(ledgertransactiongroup.Table, ledgertransactiongroup.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerbreakagerecord.SourceTransactionGroupTable, ledgerbreakagerecord.SourceTransactionGroupColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySourceTransaction chains the current query on the "source_transaction" edge. +func (_q *LedgerBreakageRecordQuery) QuerySourceTransaction() *LedgerTransactionQuery { + query := (&LedgerTransactionClient{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(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, selector), + sqlgraph.To(ledgertransaction.Table, ledgertransaction.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerbreakagerecord.SourceTransactionTable, ledgerbreakagerecord.SourceTransactionColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySourceEntry chains the current query on the "source_entry" edge. +func (_q *LedgerBreakageRecordQuery) QuerySourceEntry() *LedgerEntryQuery { + query := (&LedgerEntryClient{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(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, selector), + sqlgraph.To(ledgerentry.Table, ledgerentry.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerbreakagerecord.SourceEntryTable, ledgerbreakagerecord.SourceEntryColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryBreakageTransactionGroup chains the current query on the "breakage_transaction_group" edge. +func (_q *LedgerBreakageRecordQuery) QueryBreakageTransactionGroup() *LedgerTransactionGroupQuery { + query := (&LedgerTransactionGroupClient{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(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, selector), + sqlgraph.To(ledgertransactiongroup.Table, ledgertransactiongroup.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerbreakagerecord.BreakageTransactionGroupTable, ledgerbreakagerecord.BreakageTransactionGroupColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryBreakageTransaction chains the current query on the "breakage_transaction" edge. +func (_q *LedgerBreakageRecordQuery) QueryBreakageTransaction() *LedgerTransactionQuery { + query := (&LedgerTransactionClient{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(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, selector), + sqlgraph.To(ledgertransaction.Table, ledgertransaction.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerbreakagerecord.BreakageTransactionTable, ledgerbreakagerecord.BreakageTransactionColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryFboSubAccount chains the current query on the "fbo_sub_account" edge. +func (_q *LedgerBreakageRecordQuery) QueryFboSubAccount() *LedgerSubAccountQuery { + query := (&LedgerSubAccountClient{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(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, selector), + sqlgraph.To(ledgersubaccount.Table, ledgersubaccount.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerbreakagerecord.FboSubAccountTable, ledgerbreakagerecord.FboSubAccountColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryBreakageSubAccount chains the current query on the "breakage_sub_account" edge. +func (_q *LedgerBreakageRecordQuery) QueryBreakageSubAccount() *LedgerSubAccountQuery { + query := (&LedgerSubAccountClient{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(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, selector), + sqlgraph.To(ledgersubaccount.Table, ledgersubaccount.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerbreakagerecord.BreakageSubAccountTable, ledgerbreakagerecord.BreakageSubAccountColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryPlannedReleases chains the current query on the "planned_releases" edge. +func (_q *LedgerBreakageRecordQuery) QueryPlannedReleases() *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{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(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, selector), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgerbreakagerecord.PlannedReleasesTable, ledgerbreakagerecord.PlannedReleasesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryReleaseReopens chains the current query on the "release_reopens" edge. +func (_q *LedgerBreakageRecordQuery) QueryReleaseReopens() *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{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(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, selector), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgerbreakagerecord.ReleaseReopensTable, ledgerbreakagerecord.ReleaseReopensColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryPlan chains the current query on the "plan" edge. +func (_q *LedgerBreakageRecordQuery) QueryPlan() *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{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(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, selector), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerbreakagerecord.PlanTable, ledgerbreakagerecord.PlanColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryRelease chains the current query on the "release" edge. +func (_q *LedgerBreakageRecordQuery) QueryRelease() *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{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(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID, selector), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerbreakagerecord.ReleaseTable, ledgerbreakagerecord.ReleaseColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first LedgerBreakageRecord entity from the query. +// Returns a *NotFoundError when no LedgerBreakageRecord was found. +func (_q *LedgerBreakageRecordQuery) First(ctx context.Context) (*LedgerBreakageRecord, 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{ledgerbreakagerecord.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *LedgerBreakageRecordQuery) FirstX(ctx context.Context) *LedgerBreakageRecord { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LedgerBreakageRecord ID from the query. +// Returns a *NotFoundError when no LedgerBreakageRecord ID was found. +func (_q *LedgerBreakageRecordQuery) 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{ledgerbreakagerecord.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *LedgerBreakageRecordQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LedgerBreakageRecord entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one LedgerBreakageRecord entity is found. +// Returns a *NotFoundError when no LedgerBreakageRecord entities are found. +func (_q *LedgerBreakageRecordQuery) Only(ctx context.Context) (*LedgerBreakageRecord, 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{ledgerbreakagerecord.Label} + default: + return nil, &NotSingularError{ledgerbreakagerecord.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *LedgerBreakageRecordQuery) OnlyX(ctx context.Context) *LedgerBreakageRecord { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LedgerBreakageRecord ID in the query. +// Returns a *NotSingularError when more than one LedgerBreakageRecord ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *LedgerBreakageRecordQuery) 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{ledgerbreakagerecord.Label} + default: + err = &NotSingularError{ledgerbreakagerecord.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *LedgerBreakageRecordQuery) 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 LedgerBreakageRecords. +func (_q *LedgerBreakageRecordQuery) All(ctx context.Context) ([]*LedgerBreakageRecord, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*LedgerBreakageRecord, *LedgerBreakageRecordQuery]() + return withInterceptors[[]*LedgerBreakageRecord](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *LedgerBreakageRecordQuery) AllX(ctx context.Context) []*LedgerBreakageRecord { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LedgerBreakageRecord IDs. +func (_q *LedgerBreakageRecordQuery) 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(ledgerbreakagerecord.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *LedgerBreakageRecordQuery) 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 *LedgerBreakageRecordQuery) 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[*LedgerBreakageRecordQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *LedgerBreakageRecordQuery) 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 *LedgerBreakageRecordQuery) 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 *LedgerBreakageRecordQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LedgerBreakageRecordQuery 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 *LedgerBreakageRecordQuery) Clone() *LedgerBreakageRecordQuery { + if _q == nil { + return nil + } + return &LedgerBreakageRecordQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]ledgerbreakagerecord.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.LedgerBreakageRecord{}, _q.predicates...), + withSourceTransactionGroup: _q.withSourceTransactionGroup.Clone(), + withSourceTransaction: _q.withSourceTransaction.Clone(), + withSourceEntry: _q.withSourceEntry.Clone(), + withBreakageTransactionGroup: _q.withBreakageTransactionGroup.Clone(), + withBreakageTransaction: _q.withBreakageTransaction.Clone(), + withFboSubAccount: _q.withFboSubAccount.Clone(), + withBreakageSubAccount: _q.withBreakageSubAccount.Clone(), + withPlannedReleases: _q.withPlannedReleases.Clone(), + withReleaseReopens: _q.withReleaseReopens.Clone(), + withPlan: _q.withPlan.Clone(), + withRelease: _q.withRelease.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithSourceTransactionGroup tells the query-builder to eager-load the nodes that are connected to +// the "source_transaction_group" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerBreakageRecordQuery) WithSourceTransactionGroup(opts ...func(*LedgerTransactionGroupQuery)) *LedgerBreakageRecordQuery { + query := (&LedgerTransactionGroupClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSourceTransactionGroup = query + return _q +} + +// WithSourceTransaction tells the query-builder to eager-load the nodes that are connected to +// the "source_transaction" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerBreakageRecordQuery) WithSourceTransaction(opts ...func(*LedgerTransactionQuery)) *LedgerBreakageRecordQuery { + query := (&LedgerTransactionClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSourceTransaction = query + return _q +} + +// WithSourceEntry tells the query-builder to eager-load the nodes that are connected to +// the "source_entry" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerBreakageRecordQuery) WithSourceEntry(opts ...func(*LedgerEntryQuery)) *LedgerBreakageRecordQuery { + query := (&LedgerEntryClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSourceEntry = query + return _q +} + +// WithBreakageTransactionGroup tells the query-builder to eager-load the nodes that are connected to +// the "breakage_transaction_group" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerBreakageRecordQuery) WithBreakageTransactionGroup(opts ...func(*LedgerTransactionGroupQuery)) *LedgerBreakageRecordQuery { + query := (&LedgerTransactionGroupClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBreakageTransactionGroup = query + return _q +} + +// WithBreakageTransaction tells the query-builder to eager-load the nodes that are connected to +// the "breakage_transaction" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerBreakageRecordQuery) WithBreakageTransaction(opts ...func(*LedgerTransactionQuery)) *LedgerBreakageRecordQuery { + query := (&LedgerTransactionClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBreakageTransaction = query + return _q +} + +// WithFboSubAccount tells the query-builder to eager-load the nodes that are connected to +// the "fbo_sub_account" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerBreakageRecordQuery) WithFboSubAccount(opts ...func(*LedgerSubAccountQuery)) *LedgerBreakageRecordQuery { + query := (&LedgerSubAccountClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withFboSubAccount = query + return _q +} + +// WithBreakageSubAccount tells the query-builder to eager-load the nodes that are connected to +// the "breakage_sub_account" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerBreakageRecordQuery) WithBreakageSubAccount(opts ...func(*LedgerSubAccountQuery)) *LedgerBreakageRecordQuery { + query := (&LedgerSubAccountClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBreakageSubAccount = query + return _q +} + +// WithPlannedReleases tells the query-builder to eager-load the nodes that are connected to +// the "planned_releases" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerBreakageRecordQuery) WithPlannedReleases(opts ...func(*LedgerBreakageRecordQuery)) *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withPlannedReleases = query + return _q +} + +// WithReleaseReopens tells the query-builder to eager-load the nodes that are connected to +// the "release_reopens" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerBreakageRecordQuery) WithReleaseReopens(opts ...func(*LedgerBreakageRecordQuery)) *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withReleaseReopens = query + return _q +} + +// WithPlan tells the query-builder to eager-load the nodes that are connected to +// the "plan" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerBreakageRecordQuery) WithPlan(opts ...func(*LedgerBreakageRecordQuery)) *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withPlan = query + return _q +} + +// WithRelease tells the query-builder to eager-load the nodes that are connected to +// the "release" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerBreakageRecordQuery) WithRelease(opts ...func(*LedgerBreakageRecordQuery)) *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withRelease = 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.LedgerBreakageRecord.Query(). +// GroupBy(ledgerbreakagerecord.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *LedgerBreakageRecordQuery) GroupBy(field string, fields ...string) *LedgerBreakageRecordGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &LedgerBreakageRecordGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = ledgerbreakagerecord.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.LedgerBreakageRecord.Query(). +// Select(ledgerbreakagerecord.FieldNamespace). +// Scan(ctx, &v) +func (_q *LedgerBreakageRecordQuery) Select(fields ...string) *LedgerBreakageRecordSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &LedgerBreakageRecordSelect{LedgerBreakageRecordQuery: _q} + sbuild.label = ledgerbreakagerecord.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a LedgerBreakageRecordSelect configured with the given aggregations. +func (_q *LedgerBreakageRecordQuery) Aggregate(fns ...AggregateFunc) *LedgerBreakageRecordSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *LedgerBreakageRecordQuery) 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 !ledgerbreakagerecord.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 *LedgerBreakageRecordQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*LedgerBreakageRecord, error) { + var ( + nodes = []*LedgerBreakageRecord{} + _spec = _q.querySpec() + loadedTypes = [11]bool{ + _q.withSourceTransactionGroup != nil, + _q.withSourceTransaction != nil, + _q.withSourceEntry != nil, + _q.withBreakageTransactionGroup != nil, + _q.withBreakageTransaction != nil, + _q.withFboSubAccount != nil, + _q.withBreakageSubAccount != nil, + _q.withPlannedReleases != nil, + _q.withReleaseReopens != nil, + _q.withPlan != nil, + _q.withRelease != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*LedgerBreakageRecord).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &LedgerBreakageRecord{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.withSourceTransactionGroup; query != nil { + if err := _q.loadSourceTransactionGroup(ctx, query, nodes, nil, + func(n *LedgerBreakageRecord, e *LedgerTransactionGroup) { n.Edges.SourceTransactionGroup = e }); err != nil { + return nil, err + } + } + if query := _q.withSourceTransaction; query != nil { + if err := _q.loadSourceTransaction(ctx, query, nodes, nil, + func(n *LedgerBreakageRecord, e *LedgerTransaction) { n.Edges.SourceTransaction = e }); err != nil { + return nil, err + } + } + if query := _q.withSourceEntry; query != nil { + if err := _q.loadSourceEntry(ctx, query, nodes, nil, + func(n *LedgerBreakageRecord, e *LedgerEntry) { n.Edges.SourceEntry = e }); err != nil { + return nil, err + } + } + if query := _q.withBreakageTransactionGroup; query != nil { + if err := _q.loadBreakageTransactionGroup(ctx, query, nodes, nil, + func(n *LedgerBreakageRecord, e *LedgerTransactionGroup) { n.Edges.BreakageTransactionGroup = e }); err != nil { + return nil, err + } + } + if query := _q.withBreakageTransaction; query != nil { + if err := _q.loadBreakageTransaction(ctx, query, nodes, nil, + func(n *LedgerBreakageRecord, e *LedgerTransaction) { n.Edges.BreakageTransaction = e }); err != nil { + return nil, err + } + } + if query := _q.withFboSubAccount; query != nil { + if err := _q.loadFboSubAccount(ctx, query, nodes, nil, + func(n *LedgerBreakageRecord, e *LedgerSubAccount) { n.Edges.FboSubAccount = e }); err != nil { + return nil, err + } + } + if query := _q.withBreakageSubAccount; query != nil { + if err := _q.loadBreakageSubAccount(ctx, query, nodes, nil, + func(n *LedgerBreakageRecord, e *LedgerSubAccount) { n.Edges.BreakageSubAccount = e }); err != nil { + return nil, err + } + } + if query := _q.withPlannedReleases; query != nil { + if err := _q.loadPlannedReleases(ctx, query, nodes, + func(n *LedgerBreakageRecord) { n.Edges.PlannedReleases = []*LedgerBreakageRecord{} }, + func(n *LedgerBreakageRecord, e *LedgerBreakageRecord) { + n.Edges.PlannedReleases = append(n.Edges.PlannedReleases, e) + }); err != nil { + return nil, err + } + } + if query := _q.withReleaseReopens; query != nil { + if err := _q.loadReleaseReopens(ctx, query, nodes, + func(n *LedgerBreakageRecord) { n.Edges.ReleaseReopens = []*LedgerBreakageRecord{} }, + func(n *LedgerBreakageRecord, e *LedgerBreakageRecord) { + n.Edges.ReleaseReopens = append(n.Edges.ReleaseReopens, e) + }); err != nil { + return nil, err + } + } + if query := _q.withPlan; query != nil { + if err := _q.loadPlan(ctx, query, nodes, nil, + func(n *LedgerBreakageRecord, e *LedgerBreakageRecord) { n.Edges.Plan = e }); err != nil { + return nil, err + } + } + if query := _q.withRelease; query != nil { + if err := _q.loadRelease(ctx, query, nodes, nil, + func(n *LedgerBreakageRecord, e *LedgerBreakageRecord) { n.Edges.Release = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *LedgerBreakageRecordQuery) loadSourceTransactionGroup(ctx context.Context, query *LedgerTransactionGroupQuery, nodes []*LedgerBreakageRecord, init func(*LedgerBreakageRecord), assign func(*LedgerBreakageRecord, *LedgerTransactionGroup)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*LedgerBreakageRecord) + for i := range nodes { + if nodes[i].SourceTransactionGroupID == nil { + continue + } + fk := *nodes[i].SourceTransactionGroupID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(ledgertransactiongroup.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 "source_transaction_group_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *LedgerBreakageRecordQuery) loadSourceTransaction(ctx context.Context, query *LedgerTransactionQuery, nodes []*LedgerBreakageRecord, init func(*LedgerBreakageRecord), assign func(*LedgerBreakageRecord, *LedgerTransaction)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*LedgerBreakageRecord) + for i := range nodes { + if nodes[i].SourceTransactionID == nil { + continue + } + fk := *nodes[i].SourceTransactionID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(ledgertransaction.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 "source_transaction_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *LedgerBreakageRecordQuery) loadSourceEntry(ctx context.Context, query *LedgerEntryQuery, nodes []*LedgerBreakageRecord, init func(*LedgerBreakageRecord), assign func(*LedgerBreakageRecord, *LedgerEntry)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*LedgerBreakageRecord) + for i := range nodes { + if nodes[i].SourceEntryID == nil { + continue + } + fk := *nodes[i].SourceEntryID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(ledgerentry.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 "source_entry_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *LedgerBreakageRecordQuery) loadBreakageTransactionGroup(ctx context.Context, query *LedgerTransactionGroupQuery, nodes []*LedgerBreakageRecord, init func(*LedgerBreakageRecord), assign func(*LedgerBreakageRecord, *LedgerTransactionGroup)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*LedgerBreakageRecord) + for i := range nodes { + fk := nodes[i].BreakageTransactionGroupID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(ledgertransactiongroup.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 "breakage_transaction_group_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *LedgerBreakageRecordQuery) loadBreakageTransaction(ctx context.Context, query *LedgerTransactionQuery, nodes []*LedgerBreakageRecord, init func(*LedgerBreakageRecord), assign func(*LedgerBreakageRecord, *LedgerTransaction)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*LedgerBreakageRecord) + for i := range nodes { + fk := nodes[i].BreakageTransactionID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(ledgertransaction.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 "breakage_transaction_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *LedgerBreakageRecordQuery) loadFboSubAccount(ctx context.Context, query *LedgerSubAccountQuery, nodes []*LedgerBreakageRecord, init func(*LedgerBreakageRecord), assign func(*LedgerBreakageRecord, *LedgerSubAccount)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*LedgerBreakageRecord) + for i := range nodes { + fk := nodes[i].FboSubAccountID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(ledgersubaccount.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 "fbo_sub_account_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *LedgerBreakageRecordQuery) loadBreakageSubAccount(ctx context.Context, query *LedgerSubAccountQuery, nodes []*LedgerBreakageRecord, init func(*LedgerBreakageRecord), assign func(*LedgerBreakageRecord, *LedgerSubAccount)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*LedgerBreakageRecord) + for i := range nodes { + fk := nodes[i].BreakageSubAccountID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(ledgersubaccount.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 "breakage_sub_account_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *LedgerBreakageRecordQuery) loadPlannedReleases(ctx context.Context, query *LedgerBreakageRecordQuery, nodes []*LedgerBreakageRecord, init func(*LedgerBreakageRecord), assign func(*LedgerBreakageRecord, *LedgerBreakageRecord)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*LedgerBreakageRecord) + 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(ledgerbreakagerecord.FieldPlanID) + } + query.Where(predicate.LedgerBreakageRecord(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(ledgerbreakagerecord.PlannedReleasesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.PlanID + if fk == nil { + return fmt.Errorf(`foreign-key "plan_id" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "plan_id" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *LedgerBreakageRecordQuery) loadReleaseReopens(ctx context.Context, query *LedgerBreakageRecordQuery, nodes []*LedgerBreakageRecord, init func(*LedgerBreakageRecord), assign func(*LedgerBreakageRecord, *LedgerBreakageRecord)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*LedgerBreakageRecord) + 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(ledgerbreakagerecord.FieldReleaseID) + } + query.Where(predicate.LedgerBreakageRecord(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(ledgerbreakagerecord.ReleaseReopensColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.ReleaseID + if fk == nil { + return fmt.Errorf(`foreign-key "release_id" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "release_id" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *LedgerBreakageRecordQuery) loadPlan(ctx context.Context, query *LedgerBreakageRecordQuery, nodes []*LedgerBreakageRecord, init func(*LedgerBreakageRecord), assign func(*LedgerBreakageRecord, *LedgerBreakageRecord)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*LedgerBreakageRecord) + for i := range nodes { + if nodes[i].PlanID == nil { + continue + } + fk := *nodes[i].PlanID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(ledgerbreakagerecord.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 "plan_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *LedgerBreakageRecordQuery) loadRelease(ctx context.Context, query *LedgerBreakageRecordQuery, nodes []*LedgerBreakageRecord, init func(*LedgerBreakageRecord), assign func(*LedgerBreakageRecord, *LedgerBreakageRecord)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*LedgerBreakageRecord) + for i := range nodes { + if nodes[i].ReleaseID == nil { + continue + } + fk := *nodes[i].ReleaseID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(ledgerbreakagerecord.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 "release_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *LedgerBreakageRecordQuery) 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 *LedgerBreakageRecordQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(ledgerbreakagerecord.Table, ledgerbreakagerecord.Columns, sqlgraph.NewFieldSpec(ledgerbreakagerecord.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, ledgerbreakagerecord.FieldID) + for i := range fields { + if fields[i] != ledgerbreakagerecord.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withSourceTransactionGroup != nil { + _spec.Node.AddColumnOnce(ledgerbreakagerecord.FieldSourceTransactionGroupID) + } + if _q.withSourceTransaction != nil { + _spec.Node.AddColumnOnce(ledgerbreakagerecord.FieldSourceTransactionID) + } + if _q.withSourceEntry != nil { + _spec.Node.AddColumnOnce(ledgerbreakagerecord.FieldSourceEntryID) + } + if _q.withBreakageTransactionGroup != nil { + _spec.Node.AddColumnOnce(ledgerbreakagerecord.FieldBreakageTransactionGroupID) + } + if _q.withBreakageTransaction != nil { + _spec.Node.AddColumnOnce(ledgerbreakagerecord.FieldBreakageTransactionID) + } + if _q.withFboSubAccount != nil { + _spec.Node.AddColumnOnce(ledgerbreakagerecord.FieldFboSubAccountID) + } + if _q.withBreakageSubAccount != nil { + _spec.Node.AddColumnOnce(ledgerbreakagerecord.FieldBreakageSubAccountID) + } + if _q.withPlan != nil { + _spec.Node.AddColumnOnce(ledgerbreakagerecord.FieldPlanID) + } + if _q.withRelease != nil { + _spec.Node.AddColumnOnce(ledgerbreakagerecord.FieldReleaseID) + } + } + 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 *LedgerBreakageRecordQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(ledgerbreakagerecord.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = ledgerbreakagerecord.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 *LedgerBreakageRecordQuery) ForUpdate(opts ...sql.LockOption) *LedgerBreakageRecordQuery { + 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 *LedgerBreakageRecordQuery) ForShare(opts ...sql.LockOption) *LedgerBreakageRecordQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// LedgerBreakageRecordGroupBy is the group-by builder for LedgerBreakageRecord entities. +type LedgerBreakageRecordGroupBy struct { + selector + build *LedgerBreakageRecordQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *LedgerBreakageRecordGroupBy) Aggregate(fns ...AggregateFunc) *LedgerBreakageRecordGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *LedgerBreakageRecordGroupBy) 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[*LedgerBreakageRecordQuery, *LedgerBreakageRecordGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *LedgerBreakageRecordGroupBy) sqlScan(ctx context.Context, root *LedgerBreakageRecordQuery, 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) +} + +// LedgerBreakageRecordSelect is the builder for selecting fields of LedgerBreakageRecord entities. +type LedgerBreakageRecordSelect struct { + *LedgerBreakageRecordQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *LedgerBreakageRecordSelect) Aggregate(fns ...AggregateFunc) *LedgerBreakageRecordSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *LedgerBreakageRecordSelect) 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[*LedgerBreakageRecordQuery, *LedgerBreakageRecordSelect](ctx, _s.LedgerBreakageRecordQuery, _s, _s.inters, v) +} + +func (_s *LedgerBreakageRecordSelect) sqlScan(ctx context.Context, root *LedgerBreakageRecordQuery, 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/ent/db/ledgerbreakagerecord_update.go b/ent/db/ledgerbreakagerecord_update.go new file mode 100644 index 0000000000000000000000000000000000000000..630fe5c999b9f60dcc1ef51b8ce9e591a4ec78f0 --- /dev/null +++ b/ent/db/ledgerbreakagerecord_update.go @@ -0,0 +1,706 @@ +// 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/ledgerbreakagerecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerBreakageRecordUpdate is the builder for updating LedgerBreakageRecord entities. +type LedgerBreakageRecordUpdate struct { + config + hooks []Hook + mutation *LedgerBreakageRecordMutation +} + +// Where appends a list predicates to the LedgerBreakageRecordUpdate builder. +func (_u *LedgerBreakageRecordUpdate) Where(ps ...predicate.LedgerBreakageRecord) *LedgerBreakageRecordUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *LedgerBreakageRecordUpdate) SetAnnotations(v models.Annotations) *LedgerBreakageRecordUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *LedgerBreakageRecordUpdate) ClearAnnotations() *LedgerBreakageRecordUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *LedgerBreakageRecordUpdate) SetUpdatedAt(v time.Time) *LedgerBreakageRecordUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *LedgerBreakageRecordUpdate) SetDeletedAt(v time.Time) *LedgerBreakageRecordUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *LedgerBreakageRecordUpdate) SetNillableDeletedAt(v *time.Time) *LedgerBreakageRecordUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *LedgerBreakageRecordUpdate) ClearDeletedAt() *LedgerBreakageRecordUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAmount sets the "amount" field. +func (_u *LedgerBreakageRecordUpdate) SetAmount(v alpacadecimal.Decimal) *LedgerBreakageRecordUpdate { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *LedgerBreakageRecordUpdate) SetNillableAmount(v *alpacadecimal.Decimal) *LedgerBreakageRecordUpdate { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// AddPlannedReleaseIDs adds the "planned_releases" edge to the LedgerBreakageRecord entity by IDs. +func (_u *LedgerBreakageRecordUpdate) AddPlannedReleaseIDs(ids ...string) *LedgerBreakageRecordUpdate { + _u.mutation.AddPlannedReleaseIDs(ids...) + return _u +} + +// AddPlannedReleases adds the "planned_releases" edges to the LedgerBreakageRecord entity. +func (_u *LedgerBreakageRecordUpdate) AddPlannedReleases(v ...*LedgerBreakageRecord) *LedgerBreakageRecordUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddPlannedReleaseIDs(ids...) +} + +// AddReleaseReopenIDs adds the "release_reopens" edge to the LedgerBreakageRecord entity by IDs. +func (_u *LedgerBreakageRecordUpdate) AddReleaseReopenIDs(ids ...string) *LedgerBreakageRecordUpdate { + _u.mutation.AddReleaseReopenIDs(ids...) + return _u +} + +// AddReleaseReopens adds the "release_reopens" edges to the LedgerBreakageRecord entity. +func (_u *LedgerBreakageRecordUpdate) AddReleaseReopens(v ...*LedgerBreakageRecord) *LedgerBreakageRecordUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddReleaseReopenIDs(ids...) +} + +// Mutation returns the LedgerBreakageRecordMutation object of the builder. +func (_u *LedgerBreakageRecordUpdate) Mutation() *LedgerBreakageRecordMutation { + return _u.mutation +} + +// ClearPlannedReleases clears all "planned_releases" edges to the LedgerBreakageRecord entity. +func (_u *LedgerBreakageRecordUpdate) ClearPlannedReleases() *LedgerBreakageRecordUpdate { + _u.mutation.ClearPlannedReleases() + return _u +} + +// RemovePlannedReleaseIDs removes the "planned_releases" edge to LedgerBreakageRecord entities by IDs. +func (_u *LedgerBreakageRecordUpdate) RemovePlannedReleaseIDs(ids ...string) *LedgerBreakageRecordUpdate { + _u.mutation.RemovePlannedReleaseIDs(ids...) + return _u +} + +// RemovePlannedReleases removes "planned_releases" edges to LedgerBreakageRecord entities. +func (_u *LedgerBreakageRecordUpdate) RemovePlannedReleases(v ...*LedgerBreakageRecord) *LedgerBreakageRecordUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemovePlannedReleaseIDs(ids...) +} + +// ClearReleaseReopens clears all "release_reopens" edges to the LedgerBreakageRecord entity. +func (_u *LedgerBreakageRecordUpdate) ClearReleaseReopens() *LedgerBreakageRecordUpdate { + _u.mutation.ClearReleaseReopens() + return _u +} + +// RemoveReleaseReopenIDs removes the "release_reopens" edge to LedgerBreakageRecord entities by IDs. +func (_u *LedgerBreakageRecordUpdate) RemoveReleaseReopenIDs(ids ...string) *LedgerBreakageRecordUpdate { + _u.mutation.RemoveReleaseReopenIDs(ids...) + return _u +} + +// RemoveReleaseReopens removes "release_reopens" edges to LedgerBreakageRecord entities. +func (_u *LedgerBreakageRecordUpdate) RemoveReleaseReopens(v ...*LedgerBreakageRecord) *LedgerBreakageRecordUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveReleaseReopenIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *LedgerBreakageRecordUpdate) 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 *LedgerBreakageRecordUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *LedgerBreakageRecordUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LedgerBreakageRecordUpdate) 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 *LedgerBreakageRecordUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := ledgerbreakagerecord.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *LedgerBreakageRecordUpdate) check() error { + if _u.mutation.BreakageTransactionGroupCleared() && len(_u.mutation.BreakageTransactionGroupIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerBreakageRecord.breakage_transaction_group"`) + } + if _u.mutation.BreakageTransactionCleared() && len(_u.mutation.BreakageTransactionIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerBreakageRecord.breakage_transaction"`) + } + if _u.mutation.FboSubAccountCleared() && len(_u.mutation.FboSubAccountIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerBreakageRecord.fbo_sub_account"`) + } + if _u.mutation.BreakageSubAccountCleared() && len(_u.mutation.BreakageSubAccountIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerBreakageRecord.breakage_sub_account"`) + } + return nil +} + +func (_u *LedgerBreakageRecordUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(ledgerbreakagerecord.Table, ledgerbreakagerecord.Columns, sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.Annotations(); ok { + _spec.SetField(ledgerbreakagerecord.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(ledgerbreakagerecord.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(ledgerbreakagerecord.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(ledgerbreakagerecord.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(ledgerbreakagerecord.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(ledgerbreakagerecord.FieldAmount, field.TypeOther, value) + } + if _u.mutation.SourceChargeIDCleared() { + _spec.ClearField(ledgerbreakagerecord.FieldSourceChargeID, field.TypeString) + } + if _u.mutation.PlannedReleasesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerbreakagerecord.PlannedReleasesTable, + Columns: []string{ledgerbreakagerecord.PlannedReleasesColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedPlannedReleasesIDs(); len(nodes) > 0 && !_u.mutation.PlannedReleasesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerbreakagerecord.PlannedReleasesTable, + Columns: []string{ledgerbreakagerecord.PlannedReleasesColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.PlannedReleasesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerbreakagerecord.PlannedReleasesTable, + Columns: []string{ledgerbreakagerecord.PlannedReleasesColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.ReleaseReopensCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerbreakagerecord.ReleaseReopensTable, + Columns: []string{ledgerbreakagerecord.ReleaseReopensColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedReleaseReopensIDs(); len(nodes) > 0 && !_u.mutation.ReleaseReopensCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerbreakagerecord.ReleaseReopensTable, + Columns: []string{ledgerbreakagerecord.ReleaseReopensColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.ReleaseReopensIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerbreakagerecord.ReleaseReopensTable, + Columns: []string{ledgerbreakagerecord.ReleaseReopensColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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{ledgerbreakagerecord.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// LedgerBreakageRecordUpdateOne is the builder for updating a single LedgerBreakageRecord entity. +type LedgerBreakageRecordUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LedgerBreakageRecordMutation +} + +// SetAnnotations sets the "annotations" field. +func (_u *LedgerBreakageRecordUpdateOne) SetAnnotations(v models.Annotations) *LedgerBreakageRecordUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *LedgerBreakageRecordUpdateOne) ClearAnnotations() *LedgerBreakageRecordUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *LedgerBreakageRecordUpdateOne) SetUpdatedAt(v time.Time) *LedgerBreakageRecordUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *LedgerBreakageRecordUpdateOne) SetDeletedAt(v time.Time) *LedgerBreakageRecordUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *LedgerBreakageRecordUpdateOne) SetNillableDeletedAt(v *time.Time) *LedgerBreakageRecordUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *LedgerBreakageRecordUpdateOne) ClearDeletedAt() *LedgerBreakageRecordUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAmount sets the "amount" field. +func (_u *LedgerBreakageRecordUpdateOne) SetAmount(v alpacadecimal.Decimal) *LedgerBreakageRecordUpdateOne { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *LedgerBreakageRecordUpdateOne) SetNillableAmount(v *alpacadecimal.Decimal) *LedgerBreakageRecordUpdateOne { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// AddPlannedReleaseIDs adds the "planned_releases" edge to the LedgerBreakageRecord entity by IDs. +func (_u *LedgerBreakageRecordUpdateOne) AddPlannedReleaseIDs(ids ...string) *LedgerBreakageRecordUpdateOne { + _u.mutation.AddPlannedReleaseIDs(ids...) + return _u +} + +// AddPlannedReleases adds the "planned_releases" edges to the LedgerBreakageRecord entity. +func (_u *LedgerBreakageRecordUpdateOne) AddPlannedReleases(v ...*LedgerBreakageRecord) *LedgerBreakageRecordUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddPlannedReleaseIDs(ids...) +} + +// AddReleaseReopenIDs adds the "release_reopens" edge to the LedgerBreakageRecord entity by IDs. +func (_u *LedgerBreakageRecordUpdateOne) AddReleaseReopenIDs(ids ...string) *LedgerBreakageRecordUpdateOne { + _u.mutation.AddReleaseReopenIDs(ids...) + return _u +} + +// AddReleaseReopens adds the "release_reopens" edges to the LedgerBreakageRecord entity. +func (_u *LedgerBreakageRecordUpdateOne) AddReleaseReopens(v ...*LedgerBreakageRecord) *LedgerBreakageRecordUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddReleaseReopenIDs(ids...) +} + +// Mutation returns the LedgerBreakageRecordMutation object of the builder. +func (_u *LedgerBreakageRecordUpdateOne) Mutation() *LedgerBreakageRecordMutation { + return _u.mutation +} + +// ClearPlannedReleases clears all "planned_releases" edges to the LedgerBreakageRecord entity. +func (_u *LedgerBreakageRecordUpdateOne) ClearPlannedReleases() *LedgerBreakageRecordUpdateOne { + _u.mutation.ClearPlannedReleases() + return _u +} + +// RemovePlannedReleaseIDs removes the "planned_releases" edge to LedgerBreakageRecord entities by IDs. +func (_u *LedgerBreakageRecordUpdateOne) RemovePlannedReleaseIDs(ids ...string) *LedgerBreakageRecordUpdateOne { + _u.mutation.RemovePlannedReleaseIDs(ids...) + return _u +} + +// RemovePlannedReleases removes "planned_releases" edges to LedgerBreakageRecord entities. +func (_u *LedgerBreakageRecordUpdateOne) RemovePlannedReleases(v ...*LedgerBreakageRecord) *LedgerBreakageRecordUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemovePlannedReleaseIDs(ids...) +} + +// ClearReleaseReopens clears all "release_reopens" edges to the LedgerBreakageRecord entity. +func (_u *LedgerBreakageRecordUpdateOne) ClearReleaseReopens() *LedgerBreakageRecordUpdateOne { + _u.mutation.ClearReleaseReopens() + return _u +} + +// RemoveReleaseReopenIDs removes the "release_reopens" edge to LedgerBreakageRecord entities by IDs. +func (_u *LedgerBreakageRecordUpdateOne) RemoveReleaseReopenIDs(ids ...string) *LedgerBreakageRecordUpdateOne { + _u.mutation.RemoveReleaseReopenIDs(ids...) + return _u +} + +// RemoveReleaseReopens removes "release_reopens" edges to LedgerBreakageRecord entities. +func (_u *LedgerBreakageRecordUpdateOne) RemoveReleaseReopens(v ...*LedgerBreakageRecord) *LedgerBreakageRecordUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveReleaseReopenIDs(ids...) +} + +// Where appends a list predicates to the LedgerBreakageRecordUpdate builder. +func (_u *LedgerBreakageRecordUpdateOne) Where(ps ...predicate.LedgerBreakageRecord) *LedgerBreakageRecordUpdateOne { + _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 *LedgerBreakageRecordUpdateOne) Select(field string, fields ...string) *LedgerBreakageRecordUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated LedgerBreakageRecord entity. +func (_u *LedgerBreakageRecordUpdateOne) Save(ctx context.Context) (*LedgerBreakageRecord, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *LedgerBreakageRecordUpdateOne) SaveX(ctx context.Context) *LedgerBreakageRecord { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *LedgerBreakageRecordUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LedgerBreakageRecordUpdateOne) 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 *LedgerBreakageRecordUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := ledgerbreakagerecord.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *LedgerBreakageRecordUpdateOne) check() error { + if _u.mutation.BreakageTransactionGroupCleared() && len(_u.mutation.BreakageTransactionGroupIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerBreakageRecord.breakage_transaction_group"`) + } + if _u.mutation.BreakageTransactionCleared() && len(_u.mutation.BreakageTransactionIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerBreakageRecord.breakage_transaction"`) + } + if _u.mutation.FboSubAccountCleared() && len(_u.mutation.FboSubAccountIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerBreakageRecord.fbo_sub_account"`) + } + if _u.mutation.BreakageSubAccountCleared() && len(_u.mutation.BreakageSubAccountIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerBreakageRecord.breakage_sub_account"`) + } + return nil +} + +func (_u *LedgerBreakageRecordUpdateOne) sqlSave(ctx context.Context) (_node *LedgerBreakageRecord, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(ledgerbreakagerecord.Table, ledgerbreakagerecord.Columns, sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "LedgerBreakageRecord.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, ledgerbreakagerecord.FieldID) + for _, f := range fields { + if !ledgerbreakagerecord.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != ledgerbreakagerecord.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.Annotations(); ok { + _spec.SetField(ledgerbreakagerecord.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(ledgerbreakagerecord.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(ledgerbreakagerecord.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(ledgerbreakagerecord.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(ledgerbreakagerecord.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(ledgerbreakagerecord.FieldAmount, field.TypeOther, value) + } + if _u.mutation.SourceChargeIDCleared() { + _spec.ClearField(ledgerbreakagerecord.FieldSourceChargeID, field.TypeString) + } + if _u.mutation.PlannedReleasesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerbreakagerecord.PlannedReleasesTable, + Columns: []string{ledgerbreakagerecord.PlannedReleasesColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedPlannedReleasesIDs(); len(nodes) > 0 && !_u.mutation.PlannedReleasesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerbreakagerecord.PlannedReleasesTable, + Columns: []string{ledgerbreakagerecord.PlannedReleasesColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.PlannedReleasesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerbreakagerecord.PlannedReleasesTable, + Columns: []string{ledgerbreakagerecord.PlannedReleasesColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.ReleaseReopensCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerbreakagerecord.ReleaseReopensTable, + Columns: []string{ledgerbreakagerecord.ReleaseReopensColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedReleaseReopensIDs(); len(nodes) > 0 && !_u.mutation.ReleaseReopensCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerbreakagerecord.ReleaseReopensTable, + Columns: []string{ledgerbreakagerecord.ReleaseReopensColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.ReleaseReopensIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerbreakagerecord.ReleaseReopensTable, + Columns: []string{ledgerbreakagerecord.ReleaseReopensColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &LedgerBreakageRecord{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{ledgerbreakagerecord.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/ent/db/ledgercreditvoidrecord.go b/ent/db/ledgercreditvoidrecord.go new file mode 100644 index 0000000000000000000000000000000000000000..e75fbfadf47d5e8840bc827004607fd76a3c85d8 --- /dev/null +++ b/ent/db/ledgercreditvoidrecord.go @@ -0,0 +1,260 @@ +// 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/ledgercreditvoidrecord" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerCreditVoidRecord is the model entity for the LedgerCreditVoidRecord schema. +type LedgerCreditVoidRecord 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"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,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"` + // Amount holds the value of the "amount" field. + Amount alpacadecimal.Decimal `json:"amount,omitempty"` + // CustomerID holds the value of the "customer_id" field. + CustomerID string `json:"customer_id,omitempty"` + // Currency holds the value of the "currency" field. + Currency currencyx.Code `json:"currency,omitempty"` + // VoidedAt holds the value of the "voided_at" field. + VoidedAt time.Time `json:"voided_at,omitempty"` + // SourceChargeID holds the value of the "source_charge_id" field. + SourceChargeID string `json:"source_charge_id,omitempty"` + // VoidTransactionGroupID holds the value of the "void_transaction_group_id" field. + VoidTransactionGroupID string `json:"void_transaction_group_id,omitempty"` + // VoidTransactionID holds the value of the "void_transaction_id" field. + VoidTransactionID string `json:"void_transaction_id,omitempty"` + // FboSubAccountID holds the value of the "fbo_sub_account_id" field. + FboSubAccountID string `json:"fbo_sub_account_id,omitempty"` + // ReceivableSubAccountID holds the value of the "receivable_sub_account_id" field. + ReceivableSubAccountID string `json:"receivable_sub_account_id,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LedgerCreditVoidRecord) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case ledgercreditvoidrecord.FieldAnnotations: + values[i] = new([]byte) + case ledgercreditvoidrecord.FieldAmount: + values[i] = new(alpacadecimal.Decimal) + case ledgercreditvoidrecord.FieldID, ledgercreditvoidrecord.FieldNamespace, ledgercreditvoidrecord.FieldCustomerID, ledgercreditvoidrecord.FieldCurrency, ledgercreditvoidrecord.FieldSourceChargeID, ledgercreditvoidrecord.FieldVoidTransactionGroupID, ledgercreditvoidrecord.FieldVoidTransactionID, ledgercreditvoidrecord.FieldFboSubAccountID, ledgercreditvoidrecord.FieldReceivableSubAccountID: + values[i] = new(sql.NullString) + case ledgercreditvoidrecord.FieldCreatedAt, ledgercreditvoidrecord.FieldUpdatedAt, ledgercreditvoidrecord.FieldDeletedAt, ledgercreditvoidrecord.FieldVoidedAt: + 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 LedgerCreditVoidRecord fields. +func (_m *LedgerCreditVoidRecord) 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 ledgercreditvoidrecord.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 ledgercreditvoidrecord.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 ledgercreditvoidrecord.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 ledgercreditvoidrecord.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 ledgercreditvoidrecord.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 ledgercreditvoidrecord.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 ledgercreditvoidrecord.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 ledgercreditvoidrecord.FieldCustomerID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field customer_id", values[i]) + } else if value.Valid { + _m.CustomerID = value.String + } + case ledgercreditvoidrecord.FieldCurrency: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field currency", values[i]) + } else if value.Valid { + _m.Currency = currencyx.Code(value.String) + } + case ledgercreditvoidrecord.FieldVoidedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field voided_at", values[i]) + } else if value.Valid { + _m.VoidedAt = value.Time + } + case ledgercreditvoidrecord.FieldSourceChargeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field source_charge_id", values[i]) + } else if value.Valid { + _m.SourceChargeID = value.String + } + case ledgercreditvoidrecord.FieldVoidTransactionGroupID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field void_transaction_group_id", values[i]) + } else if value.Valid { + _m.VoidTransactionGroupID = value.String + } + case ledgercreditvoidrecord.FieldVoidTransactionID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field void_transaction_id", values[i]) + } else if value.Valid { + _m.VoidTransactionID = value.String + } + case ledgercreditvoidrecord.FieldFboSubAccountID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field fbo_sub_account_id", values[i]) + } else if value.Valid { + _m.FboSubAccountID = value.String + } + case ledgercreditvoidrecord.FieldReceivableSubAccountID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field receivable_sub_account_id", values[i]) + } else if value.Valid { + _m.ReceivableSubAccountID = 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 LedgerCreditVoidRecord. +// This includes values selected through modifiers, order, etc. +func (_m *LedgerCreditVoidRecord) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this LedgerCreditVoidRecord. +// Note that you need to call LedgerCreditVoidRecord.Unwrap() before calling this method if this LedgerCreditVoidRecord +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *LedgerCreditVoidRecord) Update() *LedgerCreditVoidRecordUpdateOne { + return NewLedgerCreditVoidRecordClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the LedgerCreditVoidRecord 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 *LedgerCreditVoidRecord) Unwrap() *LedgerCreditVoidRecord { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: LedgerCreditVoidRecord is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *LedgerCreditVoidRecord) String() string { + var builder strings.Builder + builder.WriteString("LedgerCreditVoidRecord(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + 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("amount=") + builder.WriteString(fmt.Sprintf("%v", _m.Amount)) + builder.WriteString(", ") + builder.WriteString("customer_id=") + builder.WriteString(_m.CustomerID) + builder.WriteString(", ") + builder.WriteString("currency=") + builder.WriteString(fmt.Sprintf("%v", _m.Currency)) + builder.WriteString(", ") + builder.WriteString("voided_at=") + builder.WriteString(_m.VoidedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("source_charge_id=") + builder.WriteString(_m.SourceChargeID) + builder.WriteString(", ") + builder.WriteString("void_transaction_group_id=") + builder.WriteString(_m.VoidTransactionGroupID) + builder.WriteString(", ") + builder.WriteString("void_transaction_id=") + builder.WriteString(_m.VoidTransactionID) + builder.WriteString(", ") + builder.WriteString("fbo_sub_account_id=") + builder.WriteString(_m.FboSubAccountID) + builder.WriteString(", ") + builder.WriteString("receivable_sub_account_id=") + builder.WriteString(_m.ReceivableSubAccountID) + builder.WriteByte(')') + return builder.String() +} + +// LedgerCreditVoidRecords is a parsable slice of LedgerCreditVoidRecord. +type LedgerCreditVoidRecords []*LedgerCreditVoidRecord diff --git a/ent/db/ledgercreditvoidrecord/ledgercreditvoidrecord.go b/ent/db/ledgercreditvoidrecord/ledgercreditvoidrecord.go new file mode 100644 index 0000000000000000000000000000000000000000..d74bb1e89c715801a698e615d2cebde06fc66bd9 --- /dev/null +++ b/ent/db/ledgercreditvoidrecord/ledgercreditvoidrecord.go @@ -0,0 +1,175 @@ +// Code generated by ent, DO NOT EDIT. + +package ledgercreditvoidrecord + +import ( + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the ledgercreditvoidrecord type in the database. + Label = "ledger_credit_void_record" + // 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" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // 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" + // FieldAmount holds the string denoting the amount field in the database. + FieldAmount = "amount" + // FieldCustomerID holds the string denoting the customer_id field in the database. + FieldCustomerID = "customer_id" + // FieldCurrency holds the string denoting the currency field in the database. + FieldCurrency = "currency" + // FieldVoidedAt holds the string denoting the voided_at field in the database. + FieldVoidedAt = "voided_at" + // FieldSourceChargeID holds the string denoting the source_charge_id field in the database. + FieldSourceChargeID = "source_charge_id" + // FieldVoidTransactionGroupID holds the string denoting the void_transaction_group_id field in the database. + FieldVoidTransactionGroupID = "void_transaction_group_id" + // FieldVoidTransactionID holds the string denoting the void_transaction_id field in the database. + FieldVoidTransactionID = "void_transaction_id" + // FieldFboSubAccountID holds the string denoting the fbo_sub_account_id field in the database. + FieldFboSubAccountID = "fbo_sub_account_id" + // FieldReceivableSubAccountID holds the string denoting the receivable_sub_account_id field in the database. + FieldReceivableSubAccountID = "receivable_sub_account_id" + // Table holds the table name of the ledgercreditvoidrecord in the database. + Table = "ledger_credit_void_records" +) + +// Columns holds all SQL columns for ledgercreditvoidrecord fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldAnnotations, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldAmount, + FieldCustomerID, + FieldCurrency, + FieldVoidedAt, + FieldSourceChargeID, + FieldVoidTransactionGroupID, + FieldVoidTransactionID, + FieldFboSubAccountID, + FieldReceivableSubAccountID, +} + +// 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 + // CustomerIDValidator is a validator for the "customer_id" field. It is called by the builders before save. + CustomerIDValidator func(string) error + // CurrencyValidator is a validator for the "currency" field. It is called by the builders before save. + CurrencyValidator func(string) error + // SourceChargeIDValidator is a validator for the "source_charge_id" field. It is called by the builders before save. + SourceChargeIDValidator func(string) error + // VoidTransactionGroupIDValidator is a validator for the "void_transaction_group_id" field. It is called by the builders before save. + VoidTransactionGroupIDValidator func(string) error + // VoidTransactionIDValidator is a validator for the "void_transaction_id" field. It is called by the builders before save. + VoidTransactionIDValidator func(string) error + // FboSubAccountIDValidator is a validator for the "fbo_sub_account_id" field. It is called by the builders before save. + FboSubAccountIDValidator func(string) error + // ReceivableSubAccountIDValidator is a validator for the "receivable_sub_account_id" field. It is called by the builders before save. + ReceivableSubAccountIDValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// OrderOption defines the ordering options for the LedgerCreditVoidRecord 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() +} + +// ByAmount orders the results by the amount field. +func ByAmount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAmount, opts...).ToFunc() +} + +// ByCustomerID orders the results by the customer_id field. +func ByCustomerID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCustomerID, opts...).ToFunc() +} + +// ByCurrency orders the results by the currency field. +func ByCurrency(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCurrency, opts...).ToFunc() +} + +// ByVoidedAt orders the results by the voided_at field. +func ByVoidedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVoidedAt, opts...).ToFunc() +} + +// BySourceChargeID orders the results by the source_charge_id field. +func BySourceChargeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSourceChargeID, opts...).ToFunc() +} + +// ByVoidTransactionGroupID orders the results by the void_transaction_group_id field. +func ByVoidTransactionGroupID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVoidTransactionGroupID, opts...).ToFunc() +} + +// ByVoidTransactionID orders the results by the void_transaction_id field. +func ByVoidTransactionID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVoidTransactionID, opts...).ToFunc() +} + +// ByFboSubAccountID orders the results by the fbo_sub_account_id field. +func ByFboSubAccountID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFboSubAccountID, opts...).ToFunc() +} + +// ByReceivableSubAccountID orders the results by the receivable_sub_account_id field. +func ByReceivableSubAccountID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldReceivableSubAccountID, opts...).ToFunc() +} diff --git a/ent/db/ledgercreditvoidrecord/where.go b/ent/db/ledgercreditvoidrecord/where.go new file mode 100644 index 0000000000000000000000000000000000000000..a9fc3cd231715f4eb57f10f40138a0a1e05900cf --- /dev/null +++ b/ent/db/ledgercreditvoidrecord/where.go @@ -0,0 +1,907 @@ +// Code generated by ent, DO NOT EDIT. + +package ledgercreditvoidrecord + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/currencyx" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(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.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(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.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(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.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ. +func Amount(v alpacadecimal.Decimal) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldAmount, v)) +} + +// CustomerID applies equality check predicate on the "customer_id" field. It's identical to CustomerIDEQ. +func CustomerID(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldCustomerID, v)) +} + +// Currency applies equality check predicate on the "currency" field. It's identical to CurrencyEQ. +func Currency(v currencyx.Code) predicate.LedgerCreditVoidRecord { + vc := string(v) + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldCurrency, vc)) +} + +// VoidedAt applies equality check predicate on the "voided_at" field. It's identical to VoidedAtEQ. +func VoidedAt(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldVoidedAt, v)) +} + +// SourceChargeID applies equality check predicate on the "source_charge_id" field. It's identical to SourceChargeIDEQ. +func SourceChargeID(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldSourceChargeID, v)) +} + +// VoidTransactionGroupID applies equality check predicate on the "void_transaction_group_id" field. It's identical to VoidTransactionGroupIDEQ. +func VoidTransactionGroupID(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldVoidTransactionGroupID, v)) +} + +// VoidTransactionID applies equality check predicate on the "void_transaction_id" field. It's identical to VoidTransactionIDEQ. +func VoidTransactionID(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldVoidTransactionID, v)) +} + +// FboSubAccountID applies equality check predicate on the "fbo_sub_account_id" field. It's identical to FboSubAccountIDEQ. +func FboSubAccountID(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldFboSubAccountID, v)) +} + +// ReceivableSubAccountID applies equality check predicate on the "receivable_sub_account_id" field. It's identical to ReceivableSubAccountIDEQ. +func ReceivableSubAccountID(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldReceivableSubAccountID, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldContainsFold(FieldNamespace, v)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNotNull(FieldAnnotations)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNotNull(FieldDeletedAt)) +} + +// AmountEQ applies the EQ predicate on the "amount" field. +func AmountEQ(v alpacadecimal.Decimal) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldAmount, v)) +} + +// AmountNEQ applies the NEQ predicate on the "amount" field. +func AmountNEQ(v alpacadecimal.Decimal) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNEQ(FieldAmount, v)) +} + +// AmountIn applies the In predicate on the "amount" field. +func AmountIn(vs ...alpacadecimal.Decimal) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldIn(FieldAmount, vs...)) +} + +// AmountNotIn applies the NotIn predicate on the "amount" field. +func AmountNotIn(vs ...alpacadecimal.Decimal) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNotIn(FieldAmount, vs...)) +} + +// AmountGT applies the GT predicate on the "amount" field. +func AmountGT(v alpacadecimal.Decimal) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGT(FieldAmount, v)) +} + +// AmountGTE applies the GTE predicate on the "amount" field. +func AmountGTE(v alpacadecimal.Decimal) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGTE(FieldAmount, v)) +} + +// AmountLT applies the LT predicate on the "amount" field. +func AmountLT(v alpacadecimal.Decimal) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLT(FieldAmount, v)) +} + +// AmountLTE applies the LTE predicate on the "amount" field. +func AmountLTE(v alpacadecimal.Decimal) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLTE(FieldAmount, v)) +} + +// CustomerIDEQ applies the EQ predicate on the "customer_id" field. +func CustomerIDEQ(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldCustomerID, v)) +} + +// CustomerIDNEQ applies the NEQ predicate on the "customer_id" field. +func CustomerIDNEQ(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNEQ(FieldCustomerID, v)) +} + +// CustomerIDIn applies the In predicate on the "customer_id" field. +func CustomerIDIn(vs ...string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldIn(FieldCustomerID, vs...)) +} + +// CustomerIDNotIn applies the NotIn predicate on the "customer_id" field. +func CustomerIDNotIn(vs ...string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNotIn(FieldCustomerID, vs...)) +} + +// CustomerIDGT applies the GT predicate on the "customer_id" field. +func CustomerIDGT(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGT(FieldCustomerID, v)) +} + +// CustomerIDGTE applies the GTE predicate on the "customer_id" field. +func CustomerIDGTE(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGTE(FieldCustomerID, v)) +} + +// CustomerIDLT applies the LT predicate on the "customer_id" field. +func CustomerIDLT(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLT(FieldCustomerID, v)) +} + +// CustomerIDLTE applies the LTE predicate on the "customer_id" field. +func CustomerIDLTE(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLTE(FieldCustomerID, v)) +} + +// CustomerIDContains applies the Contains predicate on the "customer_id" field. +func CustomerIDContains(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldContains(FieldCustomerID, v)) +} + +// CustomerIDHasPrefix applies the HasPrefix predicate on the "customer_id" field. +func CustomerIDHasPrefix(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldHasPrefix(FieldCustomerID, v)) +} + +// CustomerIDHasSuffix applies the HasSuffix predicate on the "customer_id" field. +func CustomerIDHasSuffix(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldHasSuffix(FieldCustomerID, v)) +} + +// CustomerIDEqualFold applies the EqualFold predicate on the "customer_id" field. +func CustomerIDEqualFold(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEqualFold(FieldCustomerID, v)) +} + +// CustomerIDContainsFold applies the ContainsFold predicate on the "customer_id" field. +func CustomerIDContainsFold(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldContainsFold(FieldCustomerID, v)) +} + +// CurrencyEQ applies the EQ predicate on the "currency" field. +func CurrencyEQ(v currencyx.Code) predicate.LedgerCreditVoidRecord { + vc := string(v) + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldCurrency, vc)) +} + +// CurrencyNEQ applies the NEQ predicate on the "currency" field. +func CurrencyNEQ(v currencyx.Code) predicate.LedgerCreditVoidRecord { + vc := string(v) + return predicate.LedgerCreditVoidRecord(sql.FieldNEQ(FieldCurrency, vc)) +} + +// CurrencyIn applies the In predicate on the "currency" field. +func CurrencyIn(vs ...currencyx.Code) predicate.LedgerCreditVoidRecord { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.LedgerCreditVoidRecord(sql.FieldIn(FieldCurrency, v...)) +} + +// CurrencyNotIn applies the NotIn predicate on the "currency" field. +func CurrencyNotIn(vs ...currencyx.Code) predicate.LedgerCreditVoidRecord { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.LedgerCreditVoidRecord(sql.FieldNotIn(FieldCurrency, v...)) +} + +// CurrencyGT applies the GT predicate on the "currency" field. +func CurrencyGT(v currencyx.Code) predicate.LedgerCreditVoidRecord { + vc := string(v) + return predicate.LedgerCreditVoidRecord(sql.FieldGT(FieldCurrency, vc)) +} + +// CurrencyGTE applies the GTE predicate on the "currency" field. +func CurrencyGTE(v currencyx.Code) predicate.LedgerCreditVoidRecord { + vc := string(v) + return predicate.LedgerCreditVoidRecord(sql.FieldGTE(FieldCurrency, vc)) +} + +// CurrencyLT applies the LT predicate on the "currency" field. +func CurrencyLT(v currencyx.Code) predicate.LedgerCreditVoidRecord { + vc := string(v) + return predicate.LedgerCreditVoidRecord(sql.FieldLT(FieldCurrency, vc)) +} + +// CurrencyLTE applies the LTE predicate on the "currency" field. +func CurrencyLTE(v currencyx.Code) predicate.LedgerCreditVoidRecord { + vc := string(v) + return predicate.LedgerCreditVoidRecord(sql.FieldLTE(FieldCurrency, vc)) +} + +// CurrencyContains applies the Contains predicate on the "currency" field. +func CurrencyContains(v currencyx.Code) predicate.LedgerCreditVoidRecord { + vc := string(v) + return predicate.LedgerCreditVoidRecord(sql.FieldContains(FieldCurrency, vc)) +} + +// CurrencyHasPrefix applies the HasPrefix predicate on the "currency" field. +func CurrencyHasPrefix(v currencyx.Code) predicate.LedgerCreditVoidRecord { + vc := string(v) + return predicate.LedgerCreditVoidRecord(sql.FieldHasPrefix(FieldCurrency, vc)) +} + +// CurrencyHasSuffix applies the HasSuffix predicate on the "currency" field. +func CurrencyHasSuffix(v currencyx.Code) predicate.LedgerCreditVoidRecord { + vc := string(v) + return predicate.LedgerCreditVoidRecord(sql.FieldHasSuffix(FieldCurrency, vc)) +} + +// CurrencyEqualFold applies the EqualFold predicate on the "currency" field. +func CurrencyEqualFold(v currencyx.Code) predicate.LedgerCreditVoidRecord { + vc := string(v) + return predicate.LedgerCreditVoidRecord(sql.FieldEqualFold(FieldCurrency, vc)) +} + +// CurrencyContainsFold applies the ContainsFold predicate on the "currency" field. +func CurrencyContainsFold(v currencyx.Code) predicate.LedgerCreditVoidRecord { + vc := string(v) + return predicate.LedgerCreditVoidRecord(sql.FieldContainsFold(FieldCurrency, vc)) +} + +// VoidedAtEQ applies the EQ predicate on the "voided_at" field. +func VoidedAtEQ(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldVoidedAt, v)) +} + +// VoidedAtNEQ applies the NEQ predicate on the "voided_at" field. +func VoidedAtNEQ(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNEQ(FieldVoidedAt, v)) +} + +// VoidedAtIn applies the In predicate on the "voided_at" field. +func VoidedAtIn(vs ...time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldIn(FieldVoidedAt, vs...)) +} + +// VoidedAtNotIn applies the NotIn predicate on the "voided_at" field. +func VoidedAtNotIn(vs ...time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNotIn(FieldVoidedAt, vs...)) +} + +// VoidedAtGT applies the GT predicate on the "voided_at" field. +func VoidedAtGT(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGT(FieldVoidedAt, v)) +} + +// VoidedAtGTE applies the GTE predicate on the "voided_at" field. +func VoidedAtGTE(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGTE(FieldVoidedAt, v)) +} + +// VoidedAtLT applies the LT predicate on the "voided_at" field. +func VoidedAtLT(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLT(FieldVoidedAt, v)) +} + +// VoidedAtLTE applies the LTE predicate on the "voided_at" field. +func VoidedAtLTE(v time.Time) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLTE(FieldVoidedAt, v)) +} + +// SourceChargeIDEQ applies the EQ predicate on the "source_charge_id" field. +func SourceChargeIDEQ(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldSourceChargeID, v)) +} + +// SourceChargeIDNEQ applies the NEQ predicate on the "source_charge_id" field. +func SourceChargeIDNEQ(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNEQ(FieldSourceChargeID, v)) +} + +// SourceChargeIDIn applies the In predicate on the "source_charge_id" field. +func SourceChargeIDIn(vs ...string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldIn(FieldSourceChargeID, vs...)) +} + +// SourceChargeIDNotIn applies the NotIn predicate on the "source_charge_id" field. +func SourceChargeIDNotIn(vs ...string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNotIn(FieldSourceChargeID, vs...)) +} + +// SourceChargeIDGT applies the GT predicate on the "source_charge_id" field. +func SourceChargeIDGT(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGT(FieldSourceChargeID, v)) +} + +// SourceChargeIDGTE applies the GTE predicate on the "source_charge_id" field. +func SourceChargeIDGTE(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGTE(FieldSourceChargeID, v)) +} + +// SourceChargeIDLT applies the LT predicate on the "source_charge_id" field. +func SourceChargeIDLT(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLT(FieldSourceChargeID, v)) +} + +// SourceChargeIDLTE applies the LTE predicate on the "source_charge_id" field. +func SourceChargeIDLTE(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLTE(FieldSourceChargeID, v)) +} + +// SourceChargeIDContains applies the Contains predicate on the "source_charge_id" field. +func SourceChargeIDContains(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldContains(FieldSourceChargeID, v)) +} + +// SourceChargeIDHasPrefix applies the HasPrefix predicate on the "source_charge_id" field. +func SourceChargeIDHasPrefix(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldHasPrefix(FieldSourceChargeID, v)) +} + +// SourceChargeIDHasSuffix applies the HasSuffix predicate on the "source_charge_id" field. +func SourceChargeIDHasSuffix(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldHasSuffix(FieldSourceChargeID, v)) +} + +// SourceChargeIDEqualFold applies the EqualFold predicate on the "source_charge_id" field. +func SourceChargeIDEqualFold(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEqualFold(FieldSourceChargeID, v)) +} + +// SourceChargeIDContainsFold applies the ContainsFold predicate on the "source_charge_id" field. +func SourceChargeIDContainsFold(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldContainsFold(FieldSourceChargeID, v)) +} + +// VoidTransactionGroupIDEQ applies the EQ predicate on the "void_transaction_group_id" field. +func VoidTransactionGroupIDEQ(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldVoidTransactionGroupID, v)) +} + +// VoidTransactionGroupIDNEQ applies the NEQ predicate on the "void_transaction_group_id" field. +func VoidTransactionGroupIDNEQ(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNEQ(FieldVoidTransactionGroupID, v)) +} + +// VoidTransactionGroupIDIn applies the In predicate on the "void_transaction_group_id" field. +func VoidTransactionGroupIDIn(vs ...string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldIn(FieldVoidTransactionGroupID, vs...)) +} + +// VoidTransactionGroupIDNotIn applies the NotIn predicate on the "void_transaction_group_id" field. +func VoidTransactionGroupIDNotIn(vs ...string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNotIn(FieldVoidTransactionGroupID, vs...)) +} + +// VoidTransactionGroupIDGT applies the GT predicate on the "void_transaction_group_id" field. +func VoidTransactionGroupIDGT(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGT(FieldVoidTransactionGroupID, v)) +} + +// VoidTransactionGroupIDGTE applies the GTE predicate on the "void_transaction_group_id" field. +func VoidTransactionGroupIDGTE(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGTE(FieldVoidTransactionGroupID, v)) +} + +// VoidTransactionGroupIDLT applies the LT predicate on the "void_transaction_group_id" field. +func VoidTransactionGroupIDLT(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLT(FieldVoidTransactionGroupID, v)) +} + +// VoidTransactionGroupIDLTE applies the LTE predicate on the "void_transaction_group_id" field. +func VoidTransactionGroupIDLTE(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLTE(FieldVoidTransactionGroupID, v)) +} + +// VoidTransactionGroupIDContains applies the Contains predicate on the "void_transaction_group_id" field. +func VoidTransactionGroupIDContains(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldContains(FieldVoidTransactionGroupID, v)) +} + +// VoidTransactionGroupIDHasPrefix applies the HasPrefix predicate on the "void_transaction_group_id" field. +func VoidTransactionGroupIDHasPrefix(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldHasPrefix(FieldVoidTransactionGroupID, v)) +} + +// VoidTransactionGroupIDHasSuffix applies the HasSuffix predicate on the "void_transaction_group_id" field. +func VoidTransactionGroupIDHasSuffix(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldHasSuffix(FieldVoidTransactionGroupID, v)) +} + +// VoidTransactionGroupIDEqualFold applies the EqualFold predicate on the "void_transaction_group_id" field. +func VoidTransactionGroupIDEqualFold(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEqualFold(FieldVoidTransactionGroupID, v)) +} + +// VoidTransactionGroupIDContainsFold applies the ContainsFold predicate on the "void_transaction_group_id" field. +func VoidTransactionGroupIDContainsFold(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldContainsFold(FieldVoidTransactionGroupID, v)) +} + +// VoidTransactionIDEQ applies the EQ predicate on the "void_transaction_id" field. +func VoidTransactionIDEQ(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldVoidTransactionID, v)) +} + +// VoidTransactionIDNEQ applies the NEQ predicate on the "void_transaction_id" field. +func VoidTransactionIDNEQ(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNEQ(FieldVoidTransactionID, v)) +} + +// VoidTransactionIDIn applies the In predicate on the "void_transaction_id" field. +func VoidTransactionIDIn(vs ...string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldIn(FieldVoidTransactionID, vs...)) +} + +// VoidTransactionIDNotIn applies the NotIn predicate on the "void_transaction_id" field. +func VoidTransactionIDNotIn(vs ...string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNotIn(FieldVoidTransactionID, vs...)) +} + +// VoidTransactionIDGT applies the GT predicate on the "void_transaction_id" field. +func VoidTransactionIDGT(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGT(FieldVoidTransactionID, v)) +} + +// VoidTransactionIDGTE applies the GTE predicate on the "void_transaction_id" field. +func VoidTransactionIDGTE(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGTE(FieldVoidTransactionID, v)) +} + +// VoidTransactionIDLT applies the LT predicate on the "void_transaction_id" field. +func VoidTransactionIDLT(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLT(FieldVoidTransactionID, v)) +} + +// VoidTransactionIDLTE applies the LTE predicate on the "void_transaction_id" field. +func VoidTransactionIDLTE(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLTE(FieldVoidTransactionID, v)) +} + +// VoidTransactionIDContains applies the Contains predicate on the "void_transaction_id" field. +func VoidTransactionIDContains(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldContains(FieldVoidTransactionID, v)) +} + +// VoidTransactionIDHasPrefix applies the HasPrefix predicate on the "void_transaction_id" field. +func VoidTransactionIDHasPrefix(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldHasPrefix(FieldVoidTransactionID, v)) +} + +// VoidTransactionIDHasSuffix applies the HasSuffix predicate on the "void_transaction_id" field. +func VoidTransactionIDHasSuffix(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldHasSuffix(FieldVoidTransactionID, v)) +} + +// VoidTransactionIDEqualFold applies the EqualFold predicate on the "void_transaction_id" field. +func VoidTransactionIDEqualFold(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEqualFold(FieldVoidTransactionID, v)) +} + +// VoidTransactionIDContainsFold applies the ContainsFold predicate on the "void_transaction_id" field. +func VoidTransactionIDContainsFold(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldContainsFold(FieldVoidTransactionID, v)) +} + +// FboSubAccountIDEQ applies the EQ predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDEQ(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldFboSubAccountID, v)) +} + +// FboSubAccountIDNEQ applies the NEQ predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDNEQ(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNEQ(FieldFboSubAccountID, v)) +} + +// FboSubAccountIDIn applies the In predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDIn(vs ...string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldIn(FieldFboSubAccountID, vs...)) +} + +// FboSubAccountIDNotIn applies the NotIn predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDNotIn(vs ...string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNotIn(FieldFboSubAccountID, vs...)) +} + +// FboSubAccountIDGT applies the GT predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDGT(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGT(FieldFboSubAccountID, v)) +} + +// FboSubAccountIDGTE applies the GTE predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDGTE(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGTE(FieldFboSubAccountID, v)) +} + +// FboSubAccountIDLT applies the LT predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDLT(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLT(FieldFboSubAccountID, v)) +} + +// FboSubAccountIDLTE applies the LTE predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDLTE(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLTE(FieldFboSubAccountID, v)) +} + +// FboSubAccountIDContains applies the Contains predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDContains(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldContains(FieldFboSubAccountID, v)) +} + +// FboSubAccountIDHasPrefix applies the HasPrefix predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDHasPrefix(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldHasPrefix(FieldFboSubAccountID, v)) +} + +// FboSubAccountIDHasSuffix applies the HasSuffix predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDHasSuffix(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldHasSuffix(FieldFboSubAccountID, v)) +} + +// FboSubAccountIDEqualFold applies the EqualFold predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDEqualFold(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEqualFold(FieldFboSubAccountID, v)) +} + +// FboSubAccountIDContainsFold applies the ContainsFold predicate on the "fbo_sub_account_id" field. +func FboSubAccountIDContainsFold(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldContainsFold(FieldFboSubAccountID, v)) +} + +// ReceivableSubAccountIDEQ applies the EQ predicate on the "receivable_sub_account_id" field. +func ReceivableSubAccountIDEQ(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEQ(FieldReceivableSubAccountID, v)) +} + +// ReceivableSubAccountIDNEQ applies the NEQ predicate on the "receivable_sub_account_id" field. +func ReceivableSubAccountIDNEQ(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNEQ(FieldReceivableSubAccountID, v)) +} + +// ReceivableSubAccountIDIn applies the In predicate on the "receivable_sub_account_id" field. +func ReceivableSubAccountIDIn(vs ...string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldIn(FieldReceivableSubAccountID, vs...)) +} + +// ReceivableSubAccountIDNotIn applies the NotIn predicate on the "receivable_sub_account_id" field. +func ReceivableSubAccountIDNotIn(vs ...string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldNotIn(FieldReceivableSubAccountID, vs...)) +} + +// ReceivableSubAccountIDGT applies the GT predicate on the "receivable_sub_account_id" field. +func ReceivableSubAccountIDGT(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGT(FieldReceivableSubAccountID, v)) +} + +// ReceivableSubAccountIDGTE applies the GTE predicate on the "receivable_sub_account_id" field. +func ReceivableSubAccountIDGTE(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldGTE(FieldReceivableSubAccountID, v)) +} + +// ReceivableSubAccountIDLT applies the LT predicate on the "receivable_sub_account_id" field. +func ReceivableSubAccountIDLT(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLT(FieldReceivableSubAccountID, v)) +} + +// ReceivableSubAccountIDLTE applies the LTE predicate on the "receivable_sub_account_id" field. +func ReceivableSubAccountIDLTE(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldLTE(FieldReceivableSubAccountID, v)) +} + +// ReceivableSubAccountIDContains applies the Contains predicate on the "receivable_sub_account_id" field. +func ReceivableSubAccountIDContains(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldContains(FieldReceivableSubAccountID, v)) +} + +// ReceivableSubAccountIDHasPrefix applies the HasPrefix predicate on the "receivable_sub_account_id" field. +func ReceivableSubAccountIDHasPrefix(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldHasPrefix(FieldReceivableSubAccountID, v)) +} + +// ReceivableSubAccountIDHasSuffix applies the HasSuffix predicate on the "receivable_sub_account_id" field. +func ReceivableSubAccountIDHasSuffix(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldHasSuffix(FieldReceivableSubAccountID, v)) +} + +// ReceivableSubAccountIDEqualFold applies the EqualFold predicate on the "receivable_sub_account_id" field. +func ReceivableSubAccountIDEqualFold(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldEqualFold(FieldReceivableSubAccountID, v)) +} + +// ReceivableSubAccountIDContainsFold applies the ContainsFold predicate on the "receivable_sub_account_id" field. +func ReceivableSubAccountIDContainsFold(v string) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.FieldContainsFold(FieldReceivableSubAccountID, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.LedgerCreditVoidRecord) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LedgerCreditVoidRecord) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LedgerCreditVoidRecord) predicate.LedgerCreditVoidRecord { + return predicate.LedgerCreditVoidRecord(sql.NotPredicates(p)) +} diff --git a/ent/db/ledgercreditvoidrecord_create.go b/ent/db/ledgercreditvoidrecord_create.go new file mode 100644 index 0000000000000000000000000000000000000000..bb595c218a0a22ebb587c5d73ee6321192157290 --- /dev/null +++ b/ent/db/ledgercreditvoidrecord_create.go @@ -0,0 +1,966 @@ +// 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/ledgercreditvoidrecord" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerCreditVoidRecordCreate is the builder for creating a LedgerCreditVoidRecord entity. +type LedgerCreditVoidRecordCreate struct { + config + mutation *LedgerCreditVoidRecordMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *LedgerCreditVoidRecordCreate) SetNamespace(v string) *LedgerCreditVoidRecordCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *LedgerCreditVoidRecordCreate) SetAnnotations(v models.Annotations) *LedgerCreditVoidRecordCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *LedgerCreditVoidRecordCreate) SetCreatedAt(v time.Time) *LedgerCreditVoidRecordCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *LedgerCreditVoidRecordCreate) SetNillableCreatedAt(v *time.Time) *LedgerCreditVoidRecordCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *LedgerCreditVoidRecordCreate) SetUpdatedAt(v time.Time) *LedgerCreditVoidRecordCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *LedgerCreditVoidRecordCreate) SetNillableUpdatedAt(v *time.Time) *LedgerCreditVoidRecordCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *LedgerCreditVoidRecordCreate) SetDeletedAt(v time.Time) *LedgerCreditVoidRecordCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *LedgerCreditVoidRecordCreate) SetNillableDeletedAt(v *time.Time) *LedgerCreditVoidRecordCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetAmount sets the "amount" field. +func (_c *LedgerCreditVoidRecordCreate) SetAmount(v alpacadecimal.Decimal) *LedgerCreditVoidRecordCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetCustomerID sets the "customer_id" field. +func (_c *LedgerCreditVoidRecordCreate) SetCustomerID(v string) *LedgerCreditVoidRecordCreate { + _c.mutation.SetCustomerID(v) + return _c +} + +// SetCurrency sets the "currency" field. +func (_c *LedgerCreditVoidRecordCreate) SetCurrency(v currencyx.Code) *LedgerCreditVoidRecordCreate { + _c.mutation.SetCurrency(v) + return _c +} + +// SetVoidedAt sets the "voided_at" field. +func (_c *LedgerCreditVoidRecordCreate) SetVoidedAt(v time.Time) *LedgerCreditVoidRecordCreate { + _c.mutation.SetVoidedAt(v) + return _c +} + +// SetSourceChargeID sets the "source_charge_id" field. +func (_c *LedgerCreditVoidRecordCreate) SetSourceChargeID(v string) *LedgerCreditVoidRecordCreate { + _c.mutation.SetSourceChargeID(v) + return _c +} + +// SetVoidTransactionGroupID sets the "void_transaction_group_id" field. +func (_c *LedgerCreditVoidRecordCreate) SetVoidTransactionGroupID(v string) *LedgerCreditVoidRecordCreate { + _c.mutation.SetVoidTransactionGroupID(v) + return _c +} + +// SetVoidTransactionID sets the "void_transaction_id" field. +func (_c *LedgerCreditVoidRecordCreate) SetVoidTransactionID(v string) *LedgerCreditVoidRecordCreate { + _c.mutation.SetVoidTransactionID(v) + return _c +} + +// SetFboSubAccountID sets the "fbo_sub_account_id" field. +func (_c *LedgerCreditVoidRecordCreate) SetFboSubAccountID(v string) *LedgerCreditVoidRecordCreate { + _c.mutation.SetFboSubAccountID(v) + return _c +} + +// SetReceivableSubAccountID sets the "receivable_sub_account_id" field. +func (_c *LedgerCreditVoidRecordCreate) SetReceivableSubAccountID(v string) *LedgerCreditVoidRecordCreate { + _c.mutation.SetReceivableSubAccountID(v) + return _c +} + +// SetID sets the "id" field. +func (_c *LedgerCreditVoidRecordCreate) SetID(v string) *LedgerCreditVoidRecordCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *LedgerCreditVoidRecordCreate) SetNillableID(v *string) *LedgerCreditVoidRecordCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// Mutation returns the LedgerCreditVoidRecordMutation object of the builder. +func (_c *LedgerCreditVoidRecordCreate) Mutation() *LedgerCreditVoidRecordMutation { + return _c.mutation +} + +// Save creates the LedgerCreditVoidRecord in the database. +func (_c *LedgerCreditVoidRecordCreate) Save(ctx context.Context) (*LedgerCreditVoidRecord, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *LedgerCreditVoidRecordCreate) SaveX(ctx context.Context) *LedgerCreditVoidRecord { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LedgerCreditVoidRecordCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LedgerCreditVoidRecordCreate) 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 *LedgerCreditVoidRecordCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := ledgercreditvoidrecord.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := ledgercreditvoidrecord.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := ledgercreditvoidrecord.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *LedgerCreditVoidRecordCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "LedgerCreditVoidRecord.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := ledgercreditvoidrecord.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "LedgerCreditVoidRecord.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "LedgerCreditVoidRecord.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "LedgerCreditVoidRecord.updated_at"`)} + } + if _, ok := _c.mutation.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`db: missing required field "LedgerCreditVoidRecord.amount"`)} + } + if _, ok := _c.mutation.CustomerID(); !ok { + return &ValidationError{Name: "customer_id", err: errors.New(`db: missing required field "LedgerCreditVoidRecord.customer_id"`)} + } + if v, ok := _c.mutation.CustomerID(); ok { + if err := ledgercreditvoidrecord.CustomerIDValidator(v); err != nil { + return &ValidationError{Name: "customer_id", err: fmt.Errorf(`db: validator failed for field "LedgerCreditVoidRecord.customer_id": %w`, err)} + } + } + if _, ok := _c.mutation.Currency(); !ok { + return &ValidationError{Name: "currency", err: errors.New(`db: missing required field "LedgerCreditVoidRecord.currency"`)} + } + if v, ok := _c.mutation.Currency(); ok { + if err := ledgercreditvoidrecord.CurrencyValidator(string(v)); err != nil { + return &ValidationError{Name: "currency", err: fmt.Errorf(`db: validator failed for field "LedgerCreditVoidRecord.currency": %w`, err)} + } + } + if _, ok := _c.mutation.VoidedAt(); !ok { + return &ValidationError{Name: "voided_at", err: errors.New(`db: missing required field "LedgerCreditVoidRecord.voided_at"`)} + } + if _, ok := _c.mutation.SourceChargeID(); !ok { + return &ValidationError{Name: "source_charge_id", err: errors.New(`db: missing required field "LedgerCreditVoidRecord.source_charge_id"`)} + } + if v, ok := _c.mutation.SourceChargeID(); ok { + if err := ledgercreditvoidrecord.SourceChargeIDValidator(v); err != nil { + return &ValidationError{Name: "source_charge_id", err: fmt.Errorf(`db: validator failed for field "LedgerCreditVoidRecord.source_charge_id": %w`, err)} + } + } + if _, ok := _c.mutation.VoidTransactionGroupID(); !ok { + return &ValidationError{Name: "void_transaction_group_id", err: errors.New(`db: missing required field "LedgerCreditVoidRecord.void_transaction_group_id"`)} + } + if v, ok := _c.mutation.VoidTransactionGroupID(); ok { + if err := ledgercreditvoidrecord.VoidTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "void_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "LedgerCreditVoidRecord.void_transaction_group_id": %w`, err)} + } + } + if _, ok := _c.mutation.VoidTransactionID(); !ok { + return &ValidationError{Name: "void_transaction_id", err: errors.New(`db: missing required field "LedgerCreditVoidRecord.void_transaction_id"`)} + } + if v, ok := _c.mutation.VoidTransactionID(); ok { + if err := ledgercreditvoidrecord.VoidTransactionIDValidator(v); err != nil { + return &ValidationError{Name: "void_transaction_id", err: fmt.Errorf(`db: validator failed for field "LedgerCreditVoidRecord.void_transaction_id": %w`, err)} + } + } + if _, ok := _c.mutation.FboSubAccountID(); !ok { + return &ValidationError{Name: "fbo_sub_account_id", err: errors.New(`db: missing required field "LedgerCreditVoidRecord.fbo_sub_account_id"`)} + } + if v, ok := _c.mutation.FboSubAccountID(); ok { + if err := ledgercreditvoidrecord.FboSubAccountIDValidator(v); err != nil { + return &ValidationError{Name: "fbo_sub_account_id", err: fmt.Errorf(`db: validator failed for field "LedgerCreditVoidRecord.fbo_sub_account_id": %w`, err)} + } + } + if _, ok := _c.mutation.ReceivableSubAccountID(); !ok { + return &ValidationError{Name: "receivable_sub_account_id", err: errors.New(`db: missing required field "LedgerCreditVoidRecord.receivable_sub_account_id"`)} + } + if v, ok := _c.mutation.ReceivableSubAccountID(); ok { + if err := ledgercreditvoidrecord.ReceivableSubAccountIDValidator(v); err != nil { + return &ValidationError{Name: "receivable_sub_account_id", err: fmt.Errorf(`db: validator failed for field "LedgerCreditVoidRecord.receivable_sub_account_id": %w`, err)} + } + } + return nil +} + +func (_c *LedgerCreditVoidRecordCreate) sqlSave(ctx context.Context) (*LedgerCreditVoidRecord, 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 LedgerCreditVoidRecord.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *LedgerCreditVoidRecordCreate) createSpec() (*LedgerCreditVoidRecord, *sqlgraph.CreateSpec) { + var ( + _node = &LedgerCreditVoidRecord{config: _c.config} + _spec = sqlgraph.NewCreateSpec(ledgercreditvoidrecord.Table, sqlgraph.NewFieldSpec(ledgercreditvoidrecord.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(ledgercreditvoidrecord.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Amount(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldAmount, field.TypeOther, value) + _node.Amount = value + } + if value, ok := _c.mutation.CustomerID(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldCustomerID, field.TypeString, value) + _node.CustomerID = value + } + if value, ok := _c.mutation.Currency(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldCurrency, field.TypeString, value) + _node.Currency = value + } + if value, ok := _c.mutation.VoidedAt(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldVoidedAt, field.TypeTime, value) + _node.VoidedAt = value + } + if value, ok := _c.mutation.SourceChargeID(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldSourceChargeID, field.TypeString, value) + _node.SourceChargeID = value + } + if value, ok := _c.mutation.VoidTransactionGroupID(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldVoidTransactionGroupID, field.TypeString, value) + _node.VoidTransactionGroupID = value + } + if value, ok := _c.mutation.VoidTransactionID(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldVoidTransactionID, field.TypeString, value) + _node.VoidTransactionID = value + } + if value, ok := _c.mutation.FboSubAccountID(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldFboSubAccountID, field.TypeString, value) + _node.FboSubAccountID = value + } + if value, ok := _c.mutation.ReceivableSubAccountID(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldReceivableSubAccountID, field.TypeString, value) + _node.ReceivableSubAccountID = value + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.LedgerCreditVoidRecord.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.LedgerCreditVoidRecordUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *LedgerCreditVoidRecordCreate) OnConflict(opts ...sql.ConflictOption) *LedgerCreditVoidRecordUpsertOne { + _c.conflict = opts + return &LedgerCreditVoidRecordUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.LedgerCreditVoidRecord.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *LedgerCreditVoidRecordCreate) OnConflictColumns(columns ...string) *LedgerCreditVoidRecordUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &LedgerCreditVoidRecordUpsertOne{ + create: _c, + } +} + +type ( + // LedgerCreditVoidRecordUpsertOne is the builder for "upsert"-ing + // one LedgerCreditVoidRecord node. + LedgerCreditVoidRecordUpsertOne struct { + create *LedgerCreditVoidRecordCreate + } + + // LedgerCreditVoidRecordUpsert is the "OnConflict" setter. + LedgerCreditVoidRecordUpsert struct { + *sql.UpdateSet + } +) + +// SetAnnotations sets the "annotations" field. +func (u *LedgerCreditVoidRecordUpsert) SetAnnotations(v models.Annotations) *LedgerCreditVoidRecordUpsert { + u.Set(ledgercreditvoidrecord.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerCreditVoidRecordUpsert) UpdateAnnotations() *LedgerCreditVoidRecordUpsert { + u.SetExcluded(ledgercreditvoidrecord.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerCreditVoidRecordUpsert) ClearAnnotations() *LedgerCreditVoidRecordUpsert { + u.SetNull(ledgercreditvoidrecord.FieldAnnotations) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerCreditVoidRecordUpsert) SetUpdatedAt(v time.Time) *LedgerCreditVoidRecordUpsert { + u.Set(ledgercreditvoidrecord.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerCreditVoidRecordUpsert) UpdateUpdatedAt() *LedgerCreditVoidRecordUpsert { + u.SetExcluded(ledgercreditvoidrecord.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerCreditVoidRecordUpsert) SetDeletedAt(v time.Time) *LedgerCreditVoidRecordUpsert { + u.Set(ledgercreditvoidrecord.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerCreditVoidRecordUpsert) UpdateDeletedAt() *LedgerCreditVoidRecordUpsert { + u.SetExcluded(ledgercreditvoidrecord.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerCreditVoidRecordUpsert) ClearDeletedAt() *LedgerCreditVoidRecordUpsert { + u.SetNull(ledgercreditvoidrecord.FieldDeletedAt) + return u +} + +// SetAmount sets the "amount" field. +func (u *LedgerCreditVoidRecordUpsert) SetAmount(v alpacadecimal.Decimal) *LedgerCreditVoidRecordUpsert { + u.Set(ledgercreditvoidrecord.FieldAmount, v) + return u +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *LedgerCreditVoidRecordUpsert) UpdateAmount() *LedgerCreditVoidRecordUpsert { + u.SetExcluded(ledgercreditvoidrecord.FieldAmount) + 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.LedgerCreditVoidRecord.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(ledgercreditvoidrecord.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LedgerCreditVoidRecordUpsertOne) UpdateNewValues() *LedgerCreditVoidRecordUpsertOne { + 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(ledgercreditvoidrecord.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(ledgercreditvoidrecord.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(ledgercreditvoidrecord.FieldCreatedAt) + } + if _, exists := u.create.mutation.CustomerID(); exists { + s.SetIgnore(ledgercreditvoidrecord.FieldCustomerID) + } + if _, exists := u.create.mutation.Currency(); exists { + s.SetIgnore(ledgercreditvoidrecord.FieldCurrency) + } + if _, exists := u.create.mutation.VoidedAt(); exists { + s.SetIgnore(ledgercreditvoidrecord.FieldVoidedAt) + } + if _, exists := u.create.mutation.SourceChargeID(); exists { + s.SetIgnore(ledgercreditvoidrecord.FieldSourceChargeID) + } + if _, exists := u.create.mutation.VoidTransactionGroupID(); exists { + s.SetIgnore(ledgercreditvoidrecord.FieldVoidTransactionGroupID) + } + if _, exists := u.create.mutation.VoidTransactionID(); exists { + s.SetIgnore(ledgercreditvoidrecord.FieldVoidTransactionID) + } + if _, exists := u.create.mutation.FboSubAccountID(); exists { + s.SetIgnore(ledgercreditvoidrecord.FieldFboSubAccountID) + } + if _, exists := u.create.mutation.ReceivableSubAccountID(); exists { + s.SetIgnore(ledgercreditvoidrecord.FieldReceivableSubAccountID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.LedgerCreditVoidRecord.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LedgerCreditVoidRecordUpsertOne) Ignore() *LedgerCreditVoidRecordUpsertOne { + 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 *LedgerCreditVoidRecordUpsertOne) DoNothing() *LedgerCreditVoidRecordUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LedgerCreditVoidRecordCreate.OnConflict +// documentation for more info. +func (u *LedgerCreditVoidRecordUpsertOne) Update(set func(*LedgerCreditVoidRecordUpsert)) *LedgerCreditVoidRecordUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LedgerCreditVoidRecordUpsert{UpdateSet: update}) + })) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *LedgerCreditVoidRecordUpsertOne) SetAnnotations(v models.Annotations) *LedgerCreditVoidRecordUpsertOne { + return u.Update(func(s *LedgerCreditVoidRecordUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerCreditVoidRecordUpsertOne) UpdateAnnotations() *LedgerCreditVoidRecordUpsertOne { + return u.Update(func(s *LedgerCreditVoidRecordUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerCreditVoidRecordUpsertOne) ClearAnnotations() *LedgerCreditVoidRecordUpsertOne { + return u.Update(func(s *LedgerCreditVoidRecordUpsert) { + s.ClearAnnotations() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerCreditVoidRecordUpsertOne) SetUpdatedAt(v time.Time) *LedgerCreditVoidRecordUpsertOne { + return u.Update(func(s *LedgerCreditVoidRecordUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerCreditVoidRecordUpsertOne) UpdateUpdatedAt() *LedgerCreditVoidRecordUpsertOne { + return u.Update(func(s *LedgerCreditVoidRecordUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerCreditVoidRecordUpsertOne) SetDeletedAt(v time.Time) *LedgerCreditVoidRecordUpsertOne { + return u.Update(func(s *LedgerCreditVoidRecordUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerCreditVoidRecordUpsertOne) UpdateDeletedAt() *LedgerCreditVoidRecordUpsertOne { + return u.Update(func(s *LedgerCreditVoidRecordUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerCreditVoidRecordUpsertOne) ClearDeletedAt() *LedgerCreditVoidRecordUpsertOne { + return u.Update(func(s *LedgerCreditVoidRecordUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAmount sets the "amount" field. +func (u *LedgerCreditVoidRecordUpsertOne) SetAmount(v alpacadecimal.Decimal) *LedgerCreditVoidRecordUpsertOne { + return u.Update(func(s *LedgerCreditVoidRecordUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *LedgerCreditVoidRecordUpsertOne) UpdateAmount() *LedgerCreditVoidRecordUpsertOne { + return u.Update(func(s *LedgerCreditVoidRecordUpsert) { + s.UpdateAmount() + }) +} + +// Exec executes the query. +func (u *LedgerCreditVoidRecordUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for LedgerCreditVoidRecordCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LedgerCreditVoidRecordUpsertOne) 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 *LedgerCreditVoidRecordUpsertOne) 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: LedgerCreditVoidRecordUpsertOne.ID is not supported by MySQL driver. Use LedgerCreditVoidRecordUpsertOne.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 *LedgerCreditVoidRecordUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// LedgerCreditVoidRecordCreateBulk is the builder for creating many LedgerCreditVoidRecord entities in bulk. +type LedgerCreditVoidRecordCreateBulk struct { + config + err error + builders []*LedgerCreditVoidRecordCreate + conflict []sql.ConflictOption +} + +// Save creates the LedgerCreditVoidRecord entities in the database. +func (_c *LedgerCreditVoidRecordCreateBulk) Save(ctx context.Context) ([]*LedgerCreditVoidRecord, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*LedgerCreditVoidRecord, 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.(*LedgerCreditVoidRecordMutation) + 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 *LedgerCreditVoidRecordCreateBulk) SaveX(ctx context.Context) []*LedgerCreditVoidRecord { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LedgerCreditVoidRecordCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LedgerCreditVoidRecordCreateBulk) 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.LedgerCreditVoidRecord.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.LedgerCreditVoidRecordUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *LedgerCreditVoidRecordCreateBulk) OnConflict(opts ...sql.ConflictOption) *LedgerCreditVoidRecordUpsertBulk { + _c.conflict = opts + return &LedgerCreditVoidRecordUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.LedgerCreditVoidRecord.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *LedgerCreditVoidRecordCreateBulk) OnConflictColumns(columns ...string) *LedgerCreditVoidRecordUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &LedgerCreditVoidRecordUpsertBulk{ + create: _c, + } +} + +// LedgerCreditVoidRecordUpsertBulk is the builder for "upsert"-ing +// a bulk of LedgerCreditVoidRecord nodes. +type LedgerCreditVoidRecordUpsertBulk struct { + create *LedgerCreditVoidRecordCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.LedgerCreditVoidRecord.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(ledgercreditvoidrecord.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LedgerCreditVoidRecordUpsertBulk) UpdateNewValues() *LedgerCreditVoidRecordUpsertBulk { + 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(ledgercreditvoidrecord.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(ledgercreditvoidrecord.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(ledgercreditvoidrecord.FieldCreatedAt) + } + if _, exists := b.mutation.CustomerID(); exists { + s.SetIgnore(ledgercreditvoidrecord.FieldCustomerID) + } + if _, exists := b.mutation.Currency(); exists { + s.SetIgnore(ledgercreditvoidrecord.FieldCurrency) + } + if _, exists := b.mutation.VoidedAt(); exists { + s.SetIgnore(ledgercreditvoidrecord.FieldVoidedAt) + } + if _, exists := b.mutation.SourceChargeID(); exists { + s.SetIgnore(ledgercreditvoidrecord.FieldSourceChargeID) + } + if _, exists := b.mutation.VoidTransactionGroupID(); exists { + s.SetIgnore(ledgercreditvoidrecord.FieldVoidTransactionGroupID) + } + if _, exists := b.mutation.VoidTransactionID(); exists { + s.SetIgnore(ledgercreditvoidrecord.FieldVoidTransactionID) + } + if _, exists := b.mutation.FboSubAccountID(); exists { + s.SetIgnore(ledgercreditvoidrecord.FieldFboSubAccountID) + } + if _, exists := b.mutation.ReceivableSubAccountID(); exists { + s.SetIgnore(ledgercreditvoidrecord.FieldReceivableSubAccountID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.LedgerCreditVoidRecord.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LedgerCreditVoidRecordUpsertBulk) Ignore() *LedgerCreditVoidRecordUpsertBulk { + 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 *LedgerCreditVoidRecordUpsertBulk) DoNothing() *LedgerCreditVoidRecordUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LedgerCreditVoidRecordCreateBulk.OnConflict +// documentation for more info. +func (u *LedgerCreditVoidRecordUpsertBulk) Update(set func(*LedgerCreditVoidRecordUpsert)) *LedgerCreditVoidRecordUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LedgerCreditVoidRecordUpsert{UpdateSet: update}) + })) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *LedgerCreditVoidRecordUpsertBulk) SetAnnotations(v models.Annotations) *LedgerCreditVoidRecordUpsertBulk { + return u.Update(func(s *LedgerCreditVoidRecordUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerCreditVoidRecordUpsertBulk) UpdateAnnotations() *LedgerCreditVoidRecordUpsertBulk { + return u.Update(func(s *LedgerCreditVoidRecordUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerCreditVoidRecordUpsertBulk) ClearAnnotations() *LedgerCreditVoidRecordUpsertBulk { + return u.Update(func(s *LedgerCreditVoidRecordUpsert) { + s.ClearAnnotations() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerCreditVoidRecordUpsertBulk) SetUpdatedAt(v time.Time) *LedgerCreditVoidRecordUpsertBulk { + return u.Update(func(s *LedgerCreditVoidRecordUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerCreditVoidRecordUpsertBulk) UpdateUpdatedAt() *LedgerCreditVoidRecordUpsertBulk { + return u.Update(func(s *LedgerCreditVoidRecordUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerCreditVoidRecordUpsertBulk) SetDeletedAt(v time.Time) *LedgerCreditVoidRecordUpsertBulk { + return u.Update(func(s *LedgerCreditVoidRecordUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerCreditVoidRecordUpsertBulk) UpdateDeletedAt() *LedgerCreditVoidRecordUpsertBulk { + return u.Update(func(s *LedgerCreditVoidRecordUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerCreditVoidRecordUpsertBulk) ClearDeletedAt() *LedgerCreditVoidRecordUpsertBulk { + return u.Update(func(s *LedgerCreditVoidRecordUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAmount sets the "amount" field. +func (u *LedgerCreditVoidRecordUpsertBulk) SetAmount(v alpacadecimal.Decimal) *LedgerCreditVoidRecordUpsertBulk { + return u.Update(func(s *LedgerCreditVoidRecordUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *LedgerCreditVoidRecordUpsertBulk) UpdateAmount() *LedgerCreditVoidRecordUpsertBulk { + return u.Update(func(s *LedgerCreditVoidRecordUpsert) { + s.UpdateAmount() + }) +} + +// Exec executes the query. +func (u *LedgerCreditVoidRecordUpsertBulk) 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 LedgerCreditVoidRecordCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for LedgerCreditVoidRecordCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LedgerCreditVoidRecordUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/ledgercreditvoidrecord_delete.go b/ent/db/ledgercreditvoidrecord_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..456f2f2afc57471f2d982973a48e468a355a13f6 --- /dev/null +++ b/ent/db/ledgercreditvoidrecord_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/ledgercreditvoidrecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LedgerCreditVoidRecordDelete is the builder for deleting a LedgerCreditVoidRecord entity. +type LedgerCreditVoidRecordDelete struct { + config + hooks []Hook + mutation *LedgerCreditVoidRecordMutation +} + +// Where appends a list predicates to the LedgerCreditVoidRecordDelete builder. +func (_d *LedgerCreditVoidRecordDelete) Where(ps ...predicate.LedgerCreditVoidRecord) *LedgerCreditVoidRecordDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *LedgerCreditVoidRecordDelete) 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 *LedgerCreditVoidRecordDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *LedgerCreditVoidRecordDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(ledgercreditvoidrecord.Table, sqlgraph.NewFieldSpec(ledgercreditvoidrecord.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 +} + +// LedgerCreditVoidRecordDeleteOne is the builder for deleting a single LedgerCreditVoidRecord entity. +type LedgerCreditVoidRecordDeleteOne struct { + _d *LedgerCreditVoidRecordDelete +} + +// Where appends a list predicates to the LedgerCreditVoidRecordDelete builder. +func (_d *LedgerCreditVoidRecordDeleteOne) Where(ps ...predicate.LedgerCreditVoidRecord) *LedgerCreditVoidRecordDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *LedgerCreditVoidRecordDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{ledgercreditvoidrecord.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *LedgerCreditVoidRecordDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/ledgercreditvoidrecord_query.go b/ent/db/ledgercreditvoidrecord_query.go new file mode 100644 index 0000000000000000000000000000000000000000..5d1965e81e861dcd646ce982af0fec444198a154 --- /dev/null +++ b/ent/db/ledgercreditvoidrecord_query.go @@ -0,0 +1,564 @@ +// 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/ledgercreditvoidrecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LedgerCreditVoidRecordQuery is the builder for querying LedgerCreditVoidRecord entities. +type LedgerCreditVoidRecordQuery struct { + config + ctx *QueryContext + order []ledgercreditvoidrecord.OrderOption + inters []Interceptor + predicates []predicate.LedgerCreditVoidRecord + 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 LedgerCreditVoidRecordQuery builder. +func (_q *LedgerCreditVoidRecordQuery) Where(ps ...predicate.LedgerCreditVoidRecord) *LedgerCreditVoidRecordQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *LedgerCreditVoidRecordQuery) Limit(limit int) *LedgerCreditVoidRecordQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *LedgerCreditVoidRecordQuery) Offset(offset int) *LedgerCreditVoidRecordQuery { + _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 *LedgerCreditVoidRecordQuery) Unique(unique bool) *LedgerCreditVoidRecordQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *LedgerCreditVoidRecordQuery) Order(o ...ledgercreditvoidrecord.OrderOption) *LedgerCreditVoidRecordQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first LedgerCreditVoidRecord entity from the query. +// Returns a *NotFoundError when no LedgerCreditVoidRecord was found. +func (_q *LedgerCreditVoidRecordQuery) First(ctx context.Context) (*LedgerCreditVoidRecord, 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{ledgercreditvoidrecord.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *LedgerCreditVoidRecordQuery) FirstX(ctx context.Context) *LedgerCreditVoidRecord { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LedgerCreditVoidRecord ID from the query. +// Returns a *NotFoundError when no LedgerCreditVoidRecord ID was found. +func (_q *LedgerCreditVoidRecordQuery) 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{ledgercreditvoidrecord.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *LedgerCreditVoidRecordQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LedgerCreditVoidRecord entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one LedgerCreditVoidRecord entity is found. +// Returns a *NotFoundError when no LedgerCreditVoidRecord entities are found. +func (_q *LedgerCreditVoidRecordQuery) Only(ctx context.Context) (*LedgerCreditVoidRecord, 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{ledgercreditvoidrecord.Label} + default: + return nil, &NotSingularError{ledgercreditvoidrecord.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *LedgerCreditVoidRecordQuery) OnlyX(ctx context.Context) *LedgerCreditVoidRecord { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LedgerCreditVoidRecord ID in the query. +// Returns a *NotSingularError when more than one LedgerCreditVoidRecord ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *LedgerCreditVoidRecordQuery) 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{ledgercreditvoidrecord.Label} + default: + err = &NotSingularError{ledgercreditvoidrecord.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *LedgerCreditVoidRecordQuery) 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 LedgerCreditVoidRecords. +func (_q *LedgerCreditVoidRecordQuery) All(ctx context.Context) ([]*LedgerCreditVoidRecord, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*LedgerCreditVoidRecord, *LedgerCreditVoidRecordQuery]() + return withInterceptors[[]*LedgerCreditVoidRecord](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *LedgerCreditVoidRecordQuery) AllX(ctx context.Context) []*LedgerCreditVoidRecord { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LedgerCreditVoidRecord IDs. +func (_q *LedgerCreditVoidRecordQuery) 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(ledgercreditvoidrecord.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *LedgerCreditVoidRecordQuery) 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 *LedgerCreditVoidRecordQuery) 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[*LedgerCreditVoidRecordQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *LedgerCreditVoidRecordQuery) 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 *LedgerCreditVoidRecordQuery) 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 *LedgerCreditVoidRecordQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LedgerCreditVoidRecordQuery 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 *LedgerCreditVoidRecordQuery) Clone() *LedgerCreditVoidRecordQuery { + if _q == nil { + return nil + } + return &LedgerCreditVoidRecordQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]ledgercreditvoidrecord.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.LedgerCreditVoidRecord{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// 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.LedgerCreditVoidRecord.Query(). +// GroupBy(ledgercreditvoidrecord.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *LedgerCreditVoidRecordQuery) GroupBy(field string, fields ...string) *LedgerCreditVoidRecordGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &LedgerCreditVoidRecordGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = ledgercreditvoidrecord.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.LedgerCreditVoidRecord.Query(). +// Select(ledgercreditvoidrecord.FieldNamespace). +// Scan(ctx, &v) +func (_q *LedgerCreditVoidRecordQuery) Select(fields ...string) *LedgerCreditVoidRecordSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &LedgerCreditVoidRecordSelect{LedgerCreditVoidRecordQuery: _q} + sbuild.label = ledgercreditvoidrecord.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a LedgerCreditVoidRecordSelect configured with the given aggregations. +func (_q *LedgerCreditVoidRecordQuery) Aggregate(fns ...AggregateFunc) *LedgerCreditVoidRecordSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *LedgerCreditVoidRecordQuery) 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 !ledgercreditvoidrecord.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 *LedgerCreditVoidRecordQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*LedgerCreditVoidRecord, error) { + var ( + nodes = []*LedgerCreditVoidRecord{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*LedgerCreditVoidRecord).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &LedgerCreditVoidRecord{config: _q.config} + nodes = append(nodes, node) + 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 + } + return nodes, nil +} + +func (_q *LedgerCreditVoidRecordQuery) 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 *LedgerCreditVoidRecordQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(ledgercreditvoidrecord.Table, ledgercreditvoidrecord.Columns, sqlgraph.NewFieldSpec(ledgercreditvoidrecord.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, ledgercreditvoidrecord.FieldID) + for i := range fields { + if fields[i] != ledgercreditvoidrecord.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 *LedgerCreditVoidRecordQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(ledgercreditvoidrecord.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = ledgercreditvoidrecord.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 *LedgerCreditVoidRecordQuery) ForUpdate(opts ...sql.LockOption) *LedgerCreditVoidRecordQuery { + 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 *LedgerCreditVoidRecordQuery) ForShare(opts ...sql.LockOption) *LedgerCreditVoidRecordQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// LedgerCreditVoidRecordGroupBy is the group-by builder for LedgerCreditVoidRecord entities. +type LedgerCreditVoidRecordGroupBy struct { + selector + build *LedgerCreditVoidRecordQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *LedgerCreditVoidRecordGroupBy) Aggregate(fns ...AggregateFunc) *LedgerCreditVoidRecordGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *LedgerCreditVoidRecordGroupBy) 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[*LedgerCreditVoidRecordQuery, *LedgerCreditVoidRecordGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *LedgerCreditVoidRecordGroupBy) sqlScan(ctx context.Context, root *LedgerCreditVoidRecordQuery, 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) +} + +// LedgerCreditVoidRecordSelect is the builder for selecting fields of LedgerCreditVoidRecord entities. +type LedgerCreditVoidRecordSelect struct { + *LedgerCreditVoidRecordQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *LedgerCreditVoidRecordSelect) Aggregate(fns ...AggregateFunc) *LedgerCreditVoidRecordSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *LedgerCreditVoidRecordSelect) 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[*LedgerCreditVoidRecordQuery, *LedgerCreditVoidRecordSelect](ctx, _s.LedgerCreditVoidRecordQuery, _s, _s.inters, v) +} + +func (_s *LedgerCreditVoidRecordSelect) sqlScan(ctx context.Context, root *LedgerCreditVoidRecordQuery, 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/ent/db/ledgercreditvoidrecord_update.go b/ent/db/ledgercreditvoidrecord_update.go new file mode 100644 index 0000000000000000000000000000000000000000..bbb4094860b981470066a0ac34ec5249f44a94b3 --- /dev/null +++ b/ent/db/ledgercreditvoidrecord_update.go @@ -0,0 +1,336 @@ +// 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/ledgercreditvoidrecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerCreditVoidRecordUpdate is the builder for updating LedgerCreditVoidRecord entities. +type LedgerCreditVoidRecordUpdate struct { + config + hooks []Hook + mutation *LedgerCreditVoidRecordMutation +} + +// Where appends a list predicates to the LedgerCreditVoidRecordUpdate builder. +func (_u *LedgerCreditVoidRecordUpdate) Where(ps ...predicate.LedgerCreditVoidRecord) *LedgerCreditVoidRecordUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *LedgerCreditVoidRecordUpdate) SetAnnotations(v models.Annotations) *LedgerCreditVoidRecordUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *LedgerCreditVoidRecordUpdate) ClearAnnotations() *LedgerCreditVoidRecordUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *LedgerCreditVoidRecordUpdate) SetUpdatedAt(v time.Time) *LedgerCreditVoidRecordUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *LedgerCreditVoidRecordUpdate) SetDeletedAt(v time.Time) *LedgerCreditVoidRecordUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *LedgerCreditVoidRecordUpdate) SetNillableDeletedAt(v *time.Time) *LedgerCreditVoidRecordUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *LedgerCreditVoidRecordUpdate) ClearDeletedAt() *LedgerCreditVoidRecordUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAmount sets the "amount" field. +func (_u *LedgerCreditVoidRecordUpdate) SetAmount(v alpacadecimal.Decimal) *LedgerCreditVoidRecordUpdate { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *LedgerCreditVoidRecordUpdate) SetNillableAmount(v *alpacadecimal.Decimal) *LedgerCreditVoidRecordUpdate { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// Mutation returns the LedgerCreditVoidRecordMutation object of the builder. +func (_u *LedgerCreditVoidRecordUpdate) Mutation() *LedgerCreditVoidRecordMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *LedgerCreditVoidRecordUpdate) 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 *LedgerCreditVoidRecordUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *LedgerCreditVoidRecordUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LedgerCreditVoidRecordUpdate) 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 *LedgerCreditVoidRecordUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := ledgercreditvoidrecord.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +func (_u *LedgerCreditVoidRecordUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(ledgercreditvoidrecord.Table, ledgercreditvoidrecord.Columns, sqlgraph.NewFieldSpec(ledgercreditvoidrecord.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.Annotations(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(ledgercreditvoidrecord.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(ledgercreditvoidrecord.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldAmount, field.TypeOther, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{ledgercreditvoidrecord.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// LedgerCreditVoidRecordUpdateOne is the builder for updating a single LedgerCreditVoidRecord entity. +type LedgerCreditVoidRecordUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LedgerCreditVoidRecordMutation +} + +// SetAnnotations sets the "annotations" field. +func (_u *LedgerCreditVoidRecordUpdateOne) SetAnnotations(v models.Annotations) *LedgerCreditVoidRecordUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *LedgerCreditVoidRecordUpdateOne) ClearAnnotations() *LedgerCreditVoidRecordUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *LedgerCreditVoidRecordUpdateOne) SetUpdatedAt(v time.Time) *LedgerCreditVoidRecordUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *LedgerCreditVoidRecordUpdateOne) SetDeletedAt(v time.Time) *LedgerCreditVoidRecordUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *LedgerCreditVoidRecordUpdateOne) SetNillableDeletedAt(v *time.Time) *LedgerCreditVoidRecordUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *LedgerCreditVoidRecordUpdateOne) ClearDeletedAt() *LedgerCreditVoidRecordUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAmount sets the "amount" field. +func (_u *LedgerCreditVoidRecordUpdateOne) SetAmount(v alpacadecimal.Decimal) *LedgerCreditVoidRecordUpdateOne { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *LedgerCreditVoidRecordUpdateOne) SetNillableAmount(v *alpacadecimal.Decimal) *LedgerCreditVoidRecordUpdateOne { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// Mutation returns the LedgerCreditVoidRecordMutation object of the builder. +func (_u *LedgerCreditVoidRecordUpdateOne) Mutation() *LedgerCreditVoidRecordMutation { + return _u.mutation +} + +// Where appends a list predicates to the LedgerCreditVoidRecordUpdate builder. +func (_u *LedgerCreditVoidRecordUpdateOne) Where(ps ...predicate.LedgerCreditVoidRecord) *LedgerCreditVoidRecordUpdateOne { + _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 *LedgerCreditVoidRecordUpdateOne) Select(field string, fields ...string) *LedgerCreditVoidRecordUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated LedgerCreditVoidRecord entity. +func (_u *LedgerCreditVoidRecordUpdateOne) Save(ctx context.Context) (*LedgerCreditVoidRecord, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *LedgerCreditVoidRecordUpdateOne) SaveX(ctx context.Context) *LedgerCreditVoidRecord { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *LedgerCreditVoidRecordUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LedgerCreditVoidRecordUpdateOne) 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 *LedgerCreditVoidRecordUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := ledgercreditvoidrecord.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +func (_u *LedgerCreditVoidRecordUpdateOne) sqlSave(ctx context.Context) (_node *LedgerCreditVoidRecord, err error) { + _spec := sqlgraph.NewUpdateSpec(ledgercreditvoidrecord.Table, ledgercreditvoidrecord.Columns, sqlgraph.NewFieldSpec(ledgercreditvoidrecord.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "LedgerCreditVoidRecord.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, ledgercreditvoidrecord.FieldID) + for _, f := range fields { + if !ledgercreditvoidrecord.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != ledgercreditvoidrecord.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.Annotations(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(ledgercreditvoidrecord.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(ledgercreditvoidrecord.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(ledgercreditvoidrecord.FieldAmount, field.TypeOther, value) + } + _node = &LedgerCreditVoidRecord{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{ledgercreditvoidrecord.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/ent/db/ledgercustomeraccount.go b/ent/db/ledgercustomeraccount.go new file mode 100644 index 0000000000000000000000000000000000000000..ccb4b0e477411e1de75dd67dd8ec0e4387511d9d --- /dev/null +++ b/ent/db/ledgercustomeraccount.go @@ -0,0 +1,203 @@ +// 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/ledgeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgercustomeraccount" + "github.com/openmeterio/openmeter/openmeter/ledger" +) + +// LedgerCustomerAccount is the model entity for the LedgerCustomerAccount schema. +type LedgerCustomerAccount 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"` + // CustomerID holds the value of the "customer_id" field. + CustomerID string `json:"customer_id,omitempty"` + // AccountType holds the value of the "account_type" field. + AccountType ledger.AccountType `json:"account_type,omitempty"` + // AccountID holds the value of the "account_id" field. + AccountID string `json:"account_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the LedgerCustomerAccountQuery when eager-loading is set. + Edges LedgerCustomerAccountEdges `json:"edges"` + selectValues sql.SelectValues +} + +// LedgerCustomerAccountEdges holds the relations/edges for other nodes in the graph. +type LedgerCustomerAccountEdges struct { + // Account holds the value of the account edge. + Account *LedgerAccount `json:"account,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// AccountOrErr returns the Account value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e LedgerCustomerAccountEdges) AccountOrErr() (*LedgerAccount, error) { + if e.Account != nil { + return e.Account, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: ledgeraccount.Label} + } + return nil, &NotLoadedError{edge: "account"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LedgerCustomerAccount) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case ledgercustomeraccount.FieldID, ledgercustomeraccount.FieldNamespace, ledgercustomeraccount.FieldCustomerID, ledgercustomeraccount.FieldAccountType, ledgercustomeraccount.FieldAccountID: + values[i] = new(sql.NullString) + case ledgercustomeraccount.FieldCreatedAt, ledgercustomeraccount.FieldUpdatedAt, ledgercustomeraccount.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 LedgerCustomerAccount fields. +func (_m *LedgerCustomerAccount) 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 ledgercustomeraccount.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 ledgercustomeraccount.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 ledgercustomeraccount.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 ledgercustomeraccount.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 ledgercustomeraccount.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 ledgercustomeraccount.FieldCustomerID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field customer_id", values[i]) + } else if value.Valid { + _m.CustomerID = value.String + } + case ledgercustomeraccount.FieldAccountType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field account_type", values[i]) + } else if value.Valid { + _m.AccountType = ledger.AccountType(value.String) + } + case ledgercustomeraccount.FieldAccountID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field account_id", values[i]) + } else if value.Valid { + _m.AccountID = 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 LedgerCustomerAccount. +// This includes values selected through modifiers, order, etc. +func (_m *LedgerCustomerAccount) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryAccount queries the "account" edge of the LedgerCustomerAccount entity. +func (_m *LedgerCustomerAccount) QueryAccount() *LedgerAccountQuery { + return NewLedgerCustomerAccountClient(_m.config).QueryAccount(_m) +} + +// Update returns a builder for updating this LedgerCustomerAccount. +// Note that you need to call LedgerCustomerAccount.Unwrap() before calling this method if this LedgerCustomerAccount +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *LedgerCustomerAccount) Update() *LedgerCustomerAccountUpdateOne { + return NewLedgerCustomerAccountClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the LedgerCustomerAccount 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 *LedgerCustomerAccount) Unwrap() *LedgerCustomerAccount { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: LedgerCustomerAccount is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *LedgerCustomerAccount) String() string { + var builder strings.Builder + builder.WriteString("LedgerCustomerAccount(") + 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("customer_id=") + builder.WriteString(_m.CustomerID) + builder.WriteString(", ") + builder.WriteString("account_type=") + builder.WriteString(fmt.Sprintf("%v", _m.AccountType)) + builder.WriteString(", ") + builder.WriteString("account_id=") + builder.WriteString(_m.AccountID) + builder.WriteByte(')') + return builder.String() +} + +// LedgerCustomerAccounts is a parsable slice of LedgerCustomerAccount. +type LedgerCustomerAccounts []*LedgerCustomerAccount diff --git a/ent/db/ledgercustomeraccount/ledgercustomeraccount.go b/ent/db/ledgercustomeraccount/ledgercustomeraccount.go new file mode 100644 index 0000000000000000000000000000000000000000..2dd7fb0c2b347e8e177c0e42673ee1aa496565d8 --- /dev/null +++ b/ent/db/ledgercustomeraccount/ledgercustomeraccount.go @@ -0,0 +1,134 @@ +// Code generated by ent, DO NOT EDIT. + +package ledgercustomeraccount + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the ledgercustomeraccount type in the database. + Label = "ledger_customer_account" + // 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" + // FieldCustomerID holds the string denoting the customer_id field in the database. + FieldCustomerID = "customer_id" + // FieldAccountType holds the string denoting the account_type field in the database. + FieldAccountType = "account_type" + // FieldAccountID holds the string denoting the account_id field in the database. + FieldAccountID = "account_id" + // EdgeAccount holds the string denoting the account edge name in mutations. + EdgeAccount = "account" + // Table holds the table name of the ledgercustomeraccount in the database. + Table = "ledger_customer_accounts" + // AccountTable is the table that holds the account relation/edge. + AccountTable = "ledger_customer_accounts" + // AccountInverseTable is the table name for the LedgerAccount entity. + // It exists in this package in order to avoid circular dependency with the "ledgeraccount" package. + AccountInverseTable = "ledger_accounts" + // AccountColumn is the table column denoting the account relation/edge. + AccountColumn = "account_id" +) + +// Columns holds all SQL columns for ledgercustomeraccount fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldCustomerID, + FieldAccountType, + FieldAccountID, +} + +// 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 +) + +// OrderOption defines the ordering options for the LedgerCustomerAccount 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() +} + +// ByCustomerID orders the results by the customer_id field. +func ByCustomerID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCustomerID, opts...).ToFunc() +} + +// ByAccountType orders the results by the account_type field. +func ByAccountType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAccountType, opts...).ToFunc() +} + +// ByAccountID orders the results by the account_id field. +func ByAccountID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAccountID, opts...).ToFunc() +} + +// ByAccountField orders the results by account field. +func ByAccountField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newAccountStep(), sql.OrderByField(field, opts...)) + } +} +func newAccountStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(AccountInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, AccountTable, AccountColumn), + ) +} diff --git a/ent/db/ledgercustomeraccount/where.go b/ent/db/ledgercustomeraccount/where.go new file mode 100644 index 0000000000000000000000000000000000000000..b83fbf82cc4f790a074706f055a8225d336e9081 --- /dev/null +++ b/ent/db/ledgercustomeraccount/where.go @@ -0,0 +1,550 @@ +// Code generated by ent, DO NOT EDIT. + +package ledgercustomeraccount + +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/ledger" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(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.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(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.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(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.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldEQ(FieldDeletedAt, v)) +} + +// CustomerID applies equality check predicate on the "customer_id" field. It's identical to CustomerIDEQ. +func CustomerID(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldEQ(FieldCustomerID, v)) +} + +// AccountType applies equality check predicate on the "account_type" field. It's identical to AccountTypeEQ. +func AccountType(v ledger.AccountType) predicate.LedgerCustomerAccount { + vc := string(v) + return predicate.LedgerCustomerAccount(sql.FieldEQ(FieldAccountType, vc)) +} + +// AccountID applies equality check predicate on the "account_id" field. It's identical to AccountIDEQ. +func AccountID(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldEQ(FieldAccountID, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldNotNull(FieldDeletedAt)) +} + +// CustomerIDEQ applies the EQ predicate on the "customer_id" field. +func CustomerIDEQ(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldEQ(FieldCustomerID, v)) +} + +// CustomerIDNEQ applies the NEQ predicate on the "customer_id" field. +func CustomerIDNEQ(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldNEQ(FieldCustomerID, v)) +} + +// CustomerIDIn applies the In predicate on the "customer_id" field. +func CustomerIDIn(vs ...string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldIn(FieldCustomerID, vs...)) +} + +// CustomerIDNotIn applies the NotIn predicate on the "customer_id" field. +func CustomerIDNotIn(vs ...string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldNotIn(FieldCustomerID, vs...)) +} + +// CustomerIDGT applies the GT predicate on the "customer_id" field. +func CustomerIDGT(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldGT(FieldCustomerID, v)) +} + +// CustomerIDGTE applies the GTE predicate on the "customer_id" field. +func CustomerIDGTE(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldGTE(FieldCustomerID, v)) +} + +// CustomerIDLT applies the LT predicate on the "customer_id" field. +func CustomerIDLT(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldLT(FieldCustomerID, v)) +} + +// CustomerIDLTE applies the LTE predicate on the "customer_id" field. +func CustomerIDLTE(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldLTE(FieldCustomerID, v)) +} + +// CustomerIDContains applies the Contains predicate on the "customer_id" field. +func CustomerIDContains(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldContains(FieldCustomerID, v)) +} + +// CustomerIDHasPrefix applies the HasPrefix predicate on the "customer_id" field. +func CustomerIDHasPrefix(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldHasPrefix(FieldCustomerID, v)) +} + +// CustomerIDHasSuffix applies the HasSuffix predicate on the "customer_id" field. +func CustomerIDHasSuffix(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldHasSuffix(FieldCustomerID, v)) +} + +// CustomerIDEqualFold applies the EqualFold predicate on the "customer_id" field. +func CustomerIDEqualFold(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldEqualFold(FieldCustomerID, v)) +} + +// CustomerIDContainsFold applies the ContainsFold predicate on the "customer_id" field. +func CustomerIDContainsFold(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldContainsFold(FieldCustomerID, v)) +} + +// AccountTypeEQ applies the EQ predicate on the "account_type" field. +func AccountTypeEQ(v ledger.AccountType) predicate.LedgerCustomerAccount { + vc := string(v) + return predicate.LedgerCustomerAccount(sql.FieldEQ(FieldAccountType, vc)) +} + +// AccountTypeNEQ applies the NEQ predicate on the "account_type" field. +func AccountTypeNEQ(v ledger.AccountType) predicate.LedgerCustomerAccount { + vc := string(v) + return predicate.LedgerCustomerAccount(sql.FieldNEQ(FieldAccountType, vc)) +} + +// AccountTypeIn applies the In predicate on the "account_type" field. +func AccountTypeIn(vs ...ledger.AccountType) predicate.LedgerCustomerAccount { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.LedgerCustomerAccount(sql.FieldIn(FieldAccountType, v...)) +} + +// AccountTypeNotIn applies the NotIn predicate on the "account_type" field. +func AccountTypeNotIn(vs ...ledger.AccountType) predicate.LedgerCustomerAccount { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.LedgerCustomerAccount(sql.FieldNotIn(FieldAccountType, v...)) +} + +// AccountTypeGT applies the GT predicate on the "account_type" field. +func AccountTypeGT(v ledger.AccountType) predicate.LedgerCustomerAccount { + vc := string(v) + return predicate.LedgerCustomerAccount(sql.FieldGT(FieldAccountType, vc)) +} + +// AccountTypeGTE applies the GTE predicate on the "account_type" field. +func AccountTypeGTE(v ledger.AccountType) predicate.LedgerCustomerAccount { + vc := string(v) + return predicate.LedgerCustomerAccount(sql.FieldGTE(FieldAccountType, vc)) +} + +// AccountTypeLT applies the LT predicate on the "account_type" field. +func AccountTypeLT(v ledger.AccountType) predicate.LedgerCustomerAccount { + vc := string(v) + return predicate.LedgerCustomerAccount(sql.FieldLT(FieldAccountType, vc)) +} + +// AccountTypeLTE applies the LTE predicate on the "account_type" field. +func AccountTypeLTE(v ledger.AccountType) predicate.LedgerCustomerAccount { + vc := string(v) + return predicate.LedgerCustomerAccount(sql.FieldLTE(FieldAccountType, vc)) +} + +// AccountTypeContains applies the Contains predicate on the "account_type" field. +func AccountTypeContains(v ledger.AccountType) predicate.LedgerCustomerAccount { + vc := string(v) + return predicate.LedgerCustomerAccount(sql.FieldContains(FieldAccountType, vc)) +} + +// AccountTypeHasPrefix applies the HasPrefix predicate on the "account_type" field. +func AccountTypeHasPrefix(v ledger.AccountType) predicate.LedgerCustomerAccount { + vc := string(v) + return predicate.LedgerCustomerAccount(sql.FieldHasPrefix(FieldAccountType, vc)) +} + +// AccountTypeHasSuffix applies the HasSuffix predicate on the "account_type" field. +func AccountTypeHasSuffix(v ledger.AccountType) predicate.LedgerCustomerAccount { + vc := string(v) + return predicate.LedgerCustomerAccount(sql.FieldHasSuffix(FieldAccountType, vc)) +} + +// AccountTypeEqualFold applies the EqualFold predicate on the "account_type" field. +func AccountTypeEqualFold(v ledger.AccountType) predicate.LedgerCustomerAccount { + vc := string(v) + return predicate.LedgerCustomerAccount(sql.FieldEqualFold(FieldAccountType, vc)) +} + +// AccountTypeContainsFold applies the ContainsFold predicate on the "account_type" field. +func AccountTypeContainsFold(v ledger.AccountType) predicate.LedgerCustomerAccount { + vc := string(v) + return predicate.LedgerCustomerAccount(sql.FieldContainsFold(FieldAccountType, vc)) +} + +// AccountIDEQ applies the EQ predicate on the "account_id" field. +func AccountIDEQ(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldEQ(FieldAccountID, v)) +} + +// AccountIDNEQ applies the NEQ predicate on the "account_id" field. +func AccountIDNEQ(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldNEQ(FieldAccountID, v)) +} + +// AccountIDIn applies the In predicate on the "account_id" field. +func AccountIDIn(vs ...string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldIn(FieldAccountID, vs...)) +} + +// AccountIDNotIn applies the NotIn predicate on the "account_id" field. +func AccountIDNotIn(vs ...string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldNotIn(FieldAccountID, vs...)) +} + +// AccountIDGT applies the GT predicate on the "account_id" field. +func AccountIDGT(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldGT(FieldAccountID, v)) +} + +// AccountIDGTE applies the GTE predicate on the "account_id" field. +func AccountIDGTE(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldGTE(FieldAccountID, v)) +} + +// AccountIDLT applies the LT predicate on the "account_id" field. +func AccountIDLT(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldLT(FieldAccountID, v)) +} + +// AccountIDLTE applies the LTE predicate on the "account_id" field. +func AccountIDLTE(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldLTE(FieldAccountID, v)) +} + +// AccountIDContains applies the Contains predicate on the "account_id" field. +func AccountIDContains(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldContains(FieldAccountID, v)) +} + +// AccountIDHasPrefix applies the HasPrefix predicate on the "account_id" field. +func AccountIDHasPrefix(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldHasPrefix(FieldAccountID, v)) +} + +// AccountIDHasSuffix applies the HasSuffix predicate on the "account_id" field. +func AccountIDHasSuffix(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldHasSuffix(FieldAccountID, v)) +} + +// AccountIDEqualFold applies the EqualFold predicate on the "account_id" field. +func AccountIDEqualFold(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldEqualFold(FieldAccountID, v)) +} + +// AccountIDContainsFold applies the ContainsFold predicate on the "account_id" field. +func AccountIDContainsFold(v string) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.FieldContainsFold(FieldAccountID, v)) +} + +// HasAccount applies the HasEdge predicate on the "account" edge. +func HasAccount() predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, AccountTable, AccountColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasAccountWith applies the HasEdge predicate on the "account" edge with a given conditions (other predicates). +func HasAccountWith(preds ...predicate.LedgerAccount) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(func(s *sql.Selector) { + step := newAccountStep() + 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.LedgerCustomerAccount) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LedgerCustomerAccount) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LedgerCustomerAccount) predicate.LedgerCustomerAccount { + return predicate.LedgerCustomerAccount(sql.NotPredicates(p)) +} diff --git a/ent/db/ledgercustomeraccount_create.go b/ent/db/ledgercustomeraccount_create.go new file mode 100644 index 0000000000000000000000000000000000000000..9f9e63169cd202e83a41423f1f31c2529318f5e1 --- /dev/null +++ b/ent/db/ledgercustomeraccount_create.go @@ -0,0 +1,738 @@ +// 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/ledgeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgercustomeraccount" + "github.com/openmeterio/openmeter/openmeter/ledger" +) + +// LedgerCustomerAccountCreate is the builder for creating a LedgerCustomerAccount entity. +type LedgerCustomerAccountCreate struct { + config + mutation *LedgerCustomerAccountMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *LedgerCustomerAccountCreate) SetNamespace(v string) *LedgerCustomerAccountCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *LedgerCustomerAccountCreate) SetCreatedAt(v time.Time) *LedgerCustomerAccountCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *LedgerCustomerAccountCreate) SetNillableCreatedAt(v *time.Time) *LedgerCustomerAccountCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *LedgerCustomerAccountCreate) SetUpdatedAt(v time.Time) *LedgerCustomerAccountCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *LedgerCustomerAccountCreate) SetNillableUpdatedAt(v *time.Time) *LedgerCustomerAccountCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *LedgerCustomerAccountCreate) SetDeletedAt(v time.Time) *LedgerCustomerAccountCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *LedgerCustomerAccountCreate) SetNillableDeletedAt(v *time.Time) *LedgerCustomerAccountCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetCustomerID sets the "customer_id" field. +func (_c *LedgerCustomerAccountCreate) SetCustomerID(v string) *LedgerCustomerAccountCreate { + _c.mutation.SetCustomerID(v) + return _c +} + +// SetAccountType sets the "account_type" field. +func (_c *LedgerCustomerAccountCreate) SetAccountType(v ledger.AccountType) *LedgerCustomerAccountCreate { + _c.mutation.SetAccountType(v) + return _c +} + +// SetAccountID sets the "account_id" field. +func (_c *LedgerCustomerAccountCreate) SetAccountID(v string) *LedgerCustomerAccountCreate { + _c.mutation.SetAccountID(v) + return _c +} + +// SetID sets the "id" field. +func (_c *LedgerCustomerAccountCreate) SetID(v string) *LedgerCustomerAccountCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *LedgerCustomerAccountCreate) SetNillableID(v *string) *LedgerCustomerAccountCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetAccount sets the "account" edge to the LedgerAccount entity. +func (_c *LedgerCustomerAccountCreate) SetAccount(v *LedgerAccount) *LedgerCustomerAccountCreate { + return _c.SetAccountID(v.ID) +} + +// Mutation returns the LedgerCustomerAccountMutation object of the builder. +func (_c *LedgerCustomerAccountCreate) Mutation() *LedgerCustomerAccountMutation { + return _c.mutation +} + +// Save creates the LedgerCustomerAccount in the database. +func (_c *LedgerCustomerAccountCreate) Save(ctx context.Context) (*LedgerCustomerAccount, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *LedgerCustomerAccountCreate) SaveX(ctx context.Context) *LedgerCustomerAccount { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LedgerCustomerAccountCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LedgerCustomerAccountCreate) 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 *LedgerCustomerAccountCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := ledgercustomeraccount.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := ledgercustomeraccount.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := ledgercustomeraccount.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *LedgerCustomerAccountCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "LedgerCustomerAccount.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := ledgercustomeraccount.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "LedgerCustomerAccount.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "LedgerCustomerAccount.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "LedgerCustomerAccount.updated_at"`)} + } + if _, ok := _c.mutation.CustomerID(); !ok { + return &ValidationError{Name: "customer_id", err: errors.New(`db: missing required field "LedgerCustomerAccount.customer_id"`)} + } + if _, ok := _c.mutation.AccountType(); !ok { + return &ValidationError{Name: "account_type", err: errors.New(`db: missing required field "LedgerCustomerAccount.account_type"`)} + } + if v, ok := _c.mutation.AccountType(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "account_type", err: fmt.Errorf(`db: validator failed for field "LedgerCustomerAccount.account_type": %w`, err)} + } + } + if _, ok := _c.mutation.AccountID(); !ok { + return &ValidationError{Name: "account_id", err: errors.New(`db: missing required field "LedgerCustomerAccount.account_id"`)} + } + if len(_c.mutation.AccountIDs()) == 0 { + return &ValidationError{Name: "account", err: errors.New(`db: missing required edge "LedgerCustomerAccount.account"`)} + } + return nil +} + +func (_c *LedgerCustomerAccountCreate) sqlSave(ctx context.Context) (*LedgerCustomerAccount, 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 LedgerCustomerAccount.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *LedgerCustomerAccountCreate) createSpec() (*LedgerCustomerAccount, *sqlgraph.CreateSpec) { + var ( + _node = &LedgerCustomerAccount{config: _c.config} + _spec = sqlgraph.NewCreateSpec(ledgercustomeraccount.Table, sqlgraph.NewFieldSpec(ledgercustomeraccount.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(ledgercustomeraccount.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(ledgercustomeraccount.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(ledgercustomeraccount.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(ledgercustomeraccount.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.CustomerID(); ok { + _spec.SetField(ledgercustomeraccount.FieldCustomerID, field.TypeString, value) + _node.CustomerID = value + } + if value, ok := _c.mutation.AccountType(); ok { + _spec.SetField(ledgercustomeraccount.FieldAccountType, field.TypeString, value) + _node.AccountType = value + } + if nodes := _c.mutation.AccountIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: ledgercustomeraccount.AccountTable, + Columns: []string{ledgercustomeraccount.AccountColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgeraccount.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.AccountID = 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.LedgerCustomerAccount.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.LedgerCustomerAccountUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *LedgerCustomerAccountCreate) OnConflict(opts ...sql.ConflictOption) *LedgerCustomerAccountUpsertOne { + _c.conflict = opts + return &LedgerCustomerAccountUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.LedgerCustomerAccount.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *LedgerCustomerAccountCreate) OnConflictColumns(columns ...string) *LedgerCustomerAccountUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &LedgerCustomerAccountUpsertOne{ + create: _c, + } +} + +type ( + // LedgerCustomerAccountUpsertOne is the builder for "upsert"-ing + // one LedgerCustomerAccount node. + LedgerCustomerAccountUpsertOne struct { + create *LedgerCustomerAccountCreate + } + + // LedgerCustomerAccountUpsert is the "OnConflict" setter. + LedgerCustomerAccountUpsert struct { + *sql.UpdateSet + } +) + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerCustomerAccountUpsert) SetUpdatedAt(v time.Time) *LedgerCustomerAccountUpsert { + u.Set(ledgercustomeraccount.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerCustomerAccountUpsert) UpdateUpdatedAt() *LedgerCustomerAccountUpsert { + u.SetExcluded(ledgercustomeraccount.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerCustomerAccountUpsert) SetDeletedAt(v time.Time) *LedgerCustomerAccountUpsert { + u.Set(ledgercustomeraccount.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerCustomerAccountUpsert) UpdateDeletedAt() *LedgerCustomerAccountUpsert { + u.SetExcluded(ledgercustomeraccount.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerCustomerAccountUpsert) ClearDeletedAt() *LedgerCustomerAccountUpsert { + u.SetNull(ledgercustomeraccount.FieldDeletedAt) + 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.LedgerCustomerAccount.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(ledgercustomeraccount.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LedgerCustomerAccountUpsertOne) UpdateNewValues() *LedgerCustomerAccountUpsertOne { + 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(ledgercustomeraccount.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(ledgercustomeraccount.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(ledgercustomeraccount.FieldCreatedAt) + } + if _, exists := u.create.mutation.CustomerID(); exists { + s.SetIgnore(ledgercustomeraccount.FieldCustomerID) + } + if _, exists := u.create.mutation.AccountType(); exists { + s.SetIgnore(ledgercustomeraccount.FieldAccountType) + } + if _, exists := u.create.mutation.AccountID(); exists { + s.SetIgnore(ledgercustomeraccount.FieldAccountID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.LedgerCustomerAccount.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LedgerCustomerAccountUpsertOne) Ignore() *LedgerCustomerAccountUpsertOne { + 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 *LedgerCustomerAccountUpsertOne) DoNothing() *LedgerCustomerAccountUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LedgerCustomerAccountCreate.OnConflict +// documentation for more info. +func (u *LedgerCustomerAccountUpsertOne) Update(set func(*LedgerCustomerAccountUpsert)) *LedgerCustomerAccountUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LedgerCustomerAccountUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerCustomerAccountUpsertOne) SetUpdatedAt(v time.Time) *LedgerCustomerAccountUpsertOne { + return u.Update(func(s *LedgerCustomerAccountUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerCustomerAccountUpsertOne) UpdateUpdatedAt() *LedgerCustomerAccountUpsertOne { + return u.Update(func(s *LedgerCustomerAccountUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerCustomerAccountUpsertOne) SetDeletedAt(v time.Time) *LedgerCustomerAccountUpsertOne { + return u.Update(func(s *LedgerCustomerAccountUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerCustomerAccountUpsertOne) UpdateDeletedAt() *LedgerCustomerAccountUpsertOne { + return u.Update(func(s *LedgerCustomerAccountUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerCustomerAccountUpsertOne) ClearDeletedAt() *LedgerCustomerAccountUpsertOne { + return u.Update(func(s *LedgerCustomerAccountUpsert) { + s.ClearDeletedAt() + }) +} + +// Exec executes the query. +func (u *LedgerCustomerAccountUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for LedgerCustomerAccountCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LedgerCustomerAccountUpsertOne) 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 *LedgerCustomerAccountUpsertOne) 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: LedgerCustomerAccountUpsertOne.ID is not supported by MySQL driver. Use LedgerCustomerAccountUpsertOne.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 *LedgerCustomerAccountUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// LedgerCustomerAccountCreateBulk is the builder for creating many LedgerCustomerAccount entities in bulk. +type LedgerCustomerAccountCreateBulk struct { + config + err error + builders []*LedgerCustomerAccountCreate + conflict []sql.ConflictOption +} + +// Save creates the LedgerCustomerAccount entities in the database. +func (_c *LedgerCustomerAccountCreateBulk) Save(ctx context.Context) ([]*LedgerCustomerAccount, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*LedgerCustomerAccount, 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.(*LedgerCustomerAccountMutation) + 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 *LedgerCustomerAccountCreateBulk) SaveX(ctx context.Context) []*LedgerCustomerAccount { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LedgerCustomerAccountCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LedgerCustomerAccountCreateBulk) 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.LedgerCustomerAccount.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.LedgerCustomerAccountUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *LedgerCustomerAccountCreateBulk) OnConflict(opts ...sql.ConflictOption) *LedgerCustomerAccountUpsertBulk { + _c.conflict = opts + return &LedgerCustomerAccountUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.LedgerCustomerAccount.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *LedgerCustomerAccountCreateBulk) OnConflictColumns(columns ...string) *LedgerCustomerAccountUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &LedgerCustomerAccountUpsertBulk{ + create: _c, + } +} + +// LedgerCustomerAccountUpsertBulk is the builder for "upsert"-ing +// a bulk of LedgerCustomerAccount nodes. +type LedgerCustomerAccountUpsertBulk struct { + create *LedgerCustomerAccountCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.LedgerCustomerAccount.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(ledgercustomeraccount.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LedgerCustomerAccountUpsertBulk) UpdateNewValues() *LedgerCustomerAccountUpsertBulk { + 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(ledgercustomeraccount.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(ledgercustomeraccount.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(ledgercustomeraccount.FieldCreatedAt) + } + if _, exists := b.mutation.CustomerID(); exists { + s.SetIgnore(ledgercustomeraccount.FieldCustomerID) + } + if _, exists := b.mutation.AccountType(); exists { + s.SetIgnore(ledgercustomeraccount.FieldAccountType) + } + if _, exists := b.mutation.AccountID(); exists { + s.SetIgnore(ledgercustomeraccount.FieldAccountID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.LedgerCustomerAccount.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LedgerCustomerAccountUpsertBulk) Ignore() *LedgerCustomerAccountUpsertBulk { + 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 *LedgerCustomerAccountUpsertBulk) DoNothing() *LedgerCustomerAccountUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LedgerCustomerAccountCreateBulk.OnConflict +// documentation for more info. +func (u *LedgerCustomerAccountUpsertBulk) Update(set func(*LedgerCustomerAccountUpsert)) *LedgerCustomerAccountUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LedgerCustomerAccountUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerCustomerAccountUpsertBulk) SetUpdatedAt(v time.Time) *LedgerCustomerAccountUpsertBulk { + return u.Update(func(s *LedgerCustomerAccountUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerCustomerAccountUpsertBulk) UpdateUpdatedAt() *LedgerCustomerAccountUpsertBulk { + return u.Update(func(s *LedgerCustomerAccountUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerCustomerAccountUpsertBulk) SetDeletedAt(v time.Time) *LedgerCustomerAccountUpsertBulk { + return u.Update(func(s *LedgerCustomerAccountUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerCustomerAccountUpsertBulk) UpdateDeletedAt() *LedgerCustomerAccountUpsertBulk { + return u.Update(func(s *LedgerCustomerAccountUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerCustomerAccountUpsertBulk) ClearDeletedAt() *LedgerCustomerAccountUpsertBulk { + return u.Update(func(s *LedgerCustomerAccountUpsert) { + s.ClearDeletedAt() + }) +} + +// Exec executes the query. +func (u *LedgerCustomerAccountUpsertBulk) 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 LedgerCustomerAccountCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for LedgerCustomerAccountCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LedgerCustomerAccountUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/ledgercustomeraccount_delete.go b/ent/db/ledgercustomeraccount_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..8e78b0f233dcf5202ac77713b6448e5ba75b7fbd --- /dev/null +++ b/ent/db/ledgercustomeraccount_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/ledgercustomeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LedgerCustomerAccountDelete is the builder for deleting a LedgerCustomerAccount entity. +type LedgerCustomerAccountDelete struct { + config + hooks []Hook + mutation *LedgerCustomerAccountMutation +} + +// Where appends a list predicates to the LedgerCustomerAccountDelete builder. +func (_d *LedgerCustomerAccountDelete) Where(ps ...predicate.LedgerCustomerAccount) *LedgerCustomerAccountDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *LedgerCustomerAccountDelete) 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 *LedgerCustomerAccountDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *LedgerCustomerAccountDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(ledgercustomeraccount.Table, sqlgraph.NewFieldSpec(ledgercustomeraccount.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 +} + +// LedgerCustomerAccountDeleteOne is the builder for deleting a single LedgerCustomerAccount entity. +type LedgerCustomerAccountDeleteOne struct { + _d *LedgerCustomerAccountDelete +} + +// Where appends a list predicates to the LedgerCustomerAccountDelete builder. +func (_d *LedgerCustomerAccountDeleteOne) Where(ps ...predicate.LedgerCustomerAccount) *LedgerCustomerAccountDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *LedgerCustomerAccountDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{ledgercustomeraccount.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *LedgerCustomerAccountDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/ledgercustomeraccount_query.go b/ent/db/ledgercustomeraccount_query.go new file mode 100644 index 0000000000000000000000000000000000000000..e85fa26d1b7095c0c120ddcf0711d01e303b793e --- /dev/null +++ b/ent/db/ledgercustomeraccount_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/ledgeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgercustomeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LedgerCustomerAccountQuery is the builder for querying LedgerCustomerAccount entities. +type LedgerCustomerAccountQuery struct { + config + ctx *QueryContext + order []ledgercustomeraccount.OrderOption + inters []Interceptor + predicates []predicate.LedgerCustomerAccount + withAccount *LedgerAccountQuery + 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 LedgerCustomerAccountQuery builder. +func (_q *LedgerCustomerAccountQuery) Where(ps ...predicate.LedgerCustomerAccount) *LedgerCustomerAccountQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *LedgerCustomerAccountQuery) Limit(limit int) *LedgerCustomerAccountQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *LedgerCustomerAccountQuery) Offset(offset int) *LedgerCustomerAccountQuery { + _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 *LedgerCustomerAccountQuery) Unique(unique bool) *LedgerCustomerAccountQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *LedgerCustomerAccountQuery) Order(o ...ledgercustomeraccount.OrderOption) *LedgerCustomerAccountQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryAccount chains the current query on the "account" edge. +func (_q *LedgerCustomerAccountQuery) QueryAccount() *LedgerAccountQuery { + query := (&LedgerAccountClient{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(ledgercustomeraccount.Table, ledgercustomeraccount.FieldID, selector), + sqlgraph.To(ledgeraccount.Table, ledgeraccount.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgercustomeraccount.AccountTable, ledgercustomeraccount.AccountColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first LedgerCustomerAccount entity from the query. +// Returns a *NotFoundError when no LedgerCustomerAccount was found. +func (_q *LedgerCustomerAccountQuery) First(ctx context.Context) (*LedgerCustomerAccount, 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{ledgercustomeraccount.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *LedgerCustomerAccountQuery) FirstX(ctx context.Context) *LedgerCustomerAccount { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LedgerCustomerAccount ID from the query. +// Returns a *NotFoundError when no LedgerCustomerAccount ID was found. +func (_q *LedgerCustomerAccountQuery) 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{ledgercustomeraccount.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *LedgerCustomerAccountQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LedgerCustomerAccount entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one LedgerCustomerAccount entity is found. +// Returns a *NotFoundError when no LedgerCustomerAccount entities are found. +func (_q *LedgerCustomerAccountQuery) Only(ctx context.Context) (*LedgerCustomerAccount, 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{ledgercustomeraccount.Label} + default: + return nil, &NotSingularError{ledgercustomeraccount.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *LedgerCustomerAccountQuery) OnlyX(ctx context.Context) *LedgerCustomerAccount { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LedgerCustomerAccount ID in the query. +// Returns a *NotSingularError when more than one LedgerCustomerAccount ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *LedgerCustomerAccountQuery) 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{ledgercustomeraccount.Label} + default: + err = &NotSingularError{ledgercustomeraccount.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *LedgerCustomerAccountQuery) 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 LedgerCustomerAccounts. +func (_q *LedgerCustomerAccountQuery) All(ctx context.Context) ([]*LedgerCustomerAccount, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*LedgerCustomerAccount, *LedgerCustomerAccountQuery]() + return withInterceptors[[]*LedgerCustomerAccount](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *LedgerCustomerAccountQuery) AllX(ctx context.Context) []*LedgerCustomerAccount { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LedgerCustomerAccount IDs. +func (_q *LedgerCustomerAccountQuery) 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(ledgercustomeraccount.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *LedgerCustomerAccountQuery) 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 *LedgerCustomerAccountQuery) 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[*LedgerCustomerAccountQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *LedgerCustomerAccountQuery) 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 *LedgerCustomerAccountQuery) 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 *LedgerCustomerAccountQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LedgerCustomerAccountQuery 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 *LedgerCustomerAccountQuery) Clone() *LedgerCustomerAccountQuery { + if _q == nil { + return nil + } + return &LedgerCustomerAccountQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]ledgercustomeraccount.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.LedgerCustomerAccount{}, _q.predicates...), + withAccount: _q.withAccount.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithAccount tells the query-builder to eager-load the nodes that are connected to +// the "account" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerCustomerAccountQuery) WithAccount(opts ...func(*LedgerAccountQuery)) *LedgerCustomerAccountQuery { + query := (&LedgerAccountClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withAccount = 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.LedgerCustomerAccount.Query(). +// GroupBy(ledgercustomeraccount.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *LedgerCustomerAccountQuery) GroupBy(field string, fields ...string) *LedgerCustomerAccountGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &LedgerCustomerAccountGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = ledgercustomeraccount.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.LedgerCustomerAccount.Query(). +// Select(ledgercustomeraccount.FieldNamespace). +// Scan(ctx, &v) +func (_q *LedgerCustomerAccountQuery) Select(fields ...string) *LedgerCustomerAccountSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &LedgerCustomerAccountSelect{LedgerCustomerAccountQuery: _q} + sbuild.label = ledgercustomeraccount.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a LedgerCustomerAccountSelect configured with the given aggregations. +func (_q *LedgerCustomerAccountQuery) Aggregate(fns ...AggregateFunc) *LedgerCustomerAccountSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *LedgerCustomerAccountQuery) 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 !ledgercustomeraccount.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 *LedgerCustomerAccountQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*LedgerCustomerAccount, error) { + var ( + nodes = []*LedgerCustomerAccount{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withAccount != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*LedgerCustomerAccount).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &LedgerCustomerAccount{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.withAccount; query != nil { + if err := _q.loadAccount(ctx, query, nodes, nil, + func(n *LedgerCustomerAccount, e *LedgerAccount) { n.Edges.Account = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *LedgerCustomerAccountQuery) loadAccount(ctx context.Context, query *LedgerAccountQuery, nodes []*LedgerCustomerAccount, init func(*LedgerCustomerAccount), assign func(*LedgerCustomerAccount, *LedgerAccount)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*LedgerCustomerAccount) + for i := range nodes { + fk := nodes[i].AccountID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(ledgeraccount.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 "account_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *LedgerCustomerAccountQuery) 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 *LedgerCustomerAccountQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(ledgercustomeraccount.Table, ledgercustomeraccount.Columns, sqlgraph.NewFieldSpec(ledgercustomeraccount.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, ledgercustomeraccount.FieldID) + for i := range fields { + if fields[i] != ledgercustomeraccount.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withAccount != nil { + _spec.Node.AddColumnOnce(ledgercustomeraccount.FieldAccountID) + } + } + 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 *LedgerCustomerAccountQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(ledgercustomeraccount.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = ledgercustomeraccount.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 *LedgerCustomerAccountQuery) ForUpdate(opts ...sql.LockOption) *LedgerCustomerAccountQuery { + 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 *LedgerCustomerAccountQuery) ForShare(opts ...sql.LockOption) *LedgerCustomerAccountQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// LedgerCustomerAccountGroupBy is the group-by builder for LedgerCustomerAccount entities. +type LedgerCustomerAccountGroupBy struct { + selector + build *LedgerCustomerAccountQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *LedgerCustomerAccountGroupBy) Aggregate(fns ...AggregateFunc) *LedgerCustomerAccountGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *LedgerCustomerAccountGroupBy) 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[*LedgerCustomerAccountQuery, *LedgerCustomerAccountGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *LedgerCustomerAccountGroupBy) sqlScan(ctx context.Context, root *LedgerCustomerAccountQuery, 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) +} + +// LedgerCustomerAccountSelect is the builder for selecting fields of LedgerCustomerAccount entities. +type LedgerCustomerAccountSelect struct { + *LedgerCustomerAccountQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *LedgerCustomerAccountSelect) Aggregate(fns ...AggregateFunc) *LedgerCustomerAccountSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *LedgerCustomerAccountSelect) 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[*LedgerCustomerAccountQuery, *LedgerCustomerAccountSelect](ctx, _s.LedgerCustomerAccountQuery, _s, _s.inters, v) +} + +func (_s *LedgerCustomerAccountSelect) sqlScan(ctx context.Context, root *LedgerCustomerAccountQuery, 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/ent/db/ledgercustomeraccount_update.go b/ent/db/ledgercustomeraccount_update.go new file mode 100644 index 0000000000000000000000000000000000000000..ab9feb3cb55c9b3c0f6f1969db423eae4a54856f --- /dev/null +++ b/ent/db/ledgercustomeraccount_update.go @@ -0,0 +1,286 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/ledgercustomeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LedgerCustomerAccountUpdate is the builder for updating LedgerCustomerAccount entities. +type LedgerCustomerAccountUpdate struct { + config + hooks []Hook + mutation *LedgerCustomerAccountMutation +} + +// Where appends a list predicates to the LedgerCustomerAccountUpdate builder. +func (_u *LedgerCustomerAccountUpdate) Where(ps ...predicate.LedgerCustomerAccount) *LedgerCustomerAccountUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *LedgerCustomerAccountUpdate) SetUpdatedAt(v time.Time) *LedgerCustomerAccountUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *LedgerCustomerAccountUpdate) SetDeletedAt(v time.Time) *LedgerCustomerAccountUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *LedgerCustomerAccountUpdate) SetNillableDeletedAt(v *time.Time) *LedgerCustomerAccountUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *LedgerCustomerAccountUpdate) ClearDeletedAt() *LedgerCustomerAccountUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// Mutation returns the LedgerCustomerAccountMutation object of the builder. +func (_u *LedgerCustomerAccountUpdate) Mutation() *LedgerCustomerAccountMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *LedgerCustomerAccountUpdate) 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 *LedgerCustomerAccountUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *LedgerCustomerAccountUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LedgerCustomerAccountUpdate) 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 *LedgerCustomerAccountUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := ledgercustomeraccount.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *LedgerCustomerAccountUpdate) check() error { + if _u.mutation.AccountCleared() && len(_u.mutation.AccountIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerCustomerAccount.account"`) + } + return nil +} + +func (_u *LedgerCustomerAccountUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(ledgercustomeraccount.Table, ledgercustomeraccount.Columns, sqlgraph.NewFieldSpec(ledgercustomeraccount.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(ledgercustomeraccount.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(ledgercustomeraccount.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(ledgercustomeraccount.FieldDeletedAt, field.TypeTime) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{ledgercustomeraccount.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// LedgerCustomerAccountUpdateOne is the builder for updating a single LedgerCustomerAccount entity. +type LedgerCustomerAccountUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LedgerCustomerAccountMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *LedgerCustomerAccountUpdateOne) SetUpdatedAt(v time.Time) *LedgerCustomerAccountUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *LedgerCustomerAccountUpdateOne) SetDeletedAt(v time.Time) *LedgerCustomerAccountUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *LedgerCustomerAccountUpdateOne) SetNillableDeletedAt(v *time.Time) *LedgerCustomerAccountUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *LedgerCustomerAccountUpdateOne) ClearDeletedAt() *LedgerCustomerAccountUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// Mutation returns the LedgerCustomerAccountMutation object of the builder. +func (_u *LedgerCustomerAccountUpdateOne) Mutation() *LedgerCustomerAccountMutation { + return _u.mutation +} + +// Where appends a list predicates to the LedgerCustomerAccountUpdate builder. +func (_u *LedgerCustomerAccountUpdateOne) Where(ps ...predicate.LedgerCustomerAccount) *LedgerCustomerAccountUpdateOne { + _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 *LedgerCustomerAccountUpdateOne) Select(field string, fields ...string) *LedgerCustomerAccountUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated LedgerCustomerAccount entity. +func (_u *LedgerCustomerAccountUpdateOne) Save(ctx context.Context) (*LedgerCustomerAccount, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *LedgerCustomerAccountUpdateOne) SaveX(ctx context.Context) *LedgerCustomerAccount { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *LedgerCustomerAccountUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LedgerCustomerAccountUpdateOne) 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 *LedgerCustomerAccountUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := ledgercustomeraccount.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *LedgerCustomerAccountUpdateOne) check() error { + if _u.mutation.AccountCleared() && len(_u.mutation.AccountIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerCustomerAccount.account"`) + } + return nil +} + +func (_u *LedgerCustomerAccountUpdateOne) sqlSave(ctx context.Context) (_node *LedgerCustomerAccount, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(ledgercustomeraccount.Table, ledgercustomeraccount.Columns, sqlgraph.NewFieldSpec(ledgercustomeraccount.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "LedgerCustomerAccount.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, ledgercustomeraccount.FieldID) + for _, f := range fields { + if !ledgercustomeraccount.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != ledgercustomeraccount.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(ledgercustomeraccount.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(ledgercustomeraccount.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(ledgercustomeraccount.FieldDeletedAt, field.TypeTime) + } + _node = &LedgerCustomerAccount{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{ledgercustomeraccount.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/ent/db/ledgerentry.go b/ent/db/ledgerentry.go new file mode 100644 index 0000000000000000000000000000000000000000..f5ff75d7069f4b1c81168f8e15aa168f1d99be10 --- /dev/null +++ b/ent/db/ledgerentry.go @@ -0,0 +1,309 @@ +// 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/ledgerentry" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransaction" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerEntry is the model entity for the LedgerEntry schema. +type LedgerEntry 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"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,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"` + // SubAccountID holds the value of the "sub_account_id" field. + SubAccountID string `json:"sub_account_id,omitempty"` + // IdentityKey holds the value of the "identity_key" field. + IdentityKey string `json:"identity_key,omitempty"` + // SchemaVersion holds the value of the "schema_version" field. + SchemaVersion int `json:"schema_version,omitempty"` + // SourceChargeID holds the value of the "source_charge_id" field. + SourceChargeID *string `json:"source_charge_id,omitempty"` + // SpendChargeID holds the value of the "spend_charge_id" field. + SpendChargeID *string `json:"spend_charge_id,omitempty"` + // Amount holds the value of the "amount" field. + Amount alpacadecimal.Decimal `json:"amount,omitempty"` + // TransactionID holds the value of the "transaction_id" field. + TransactionID string `json:"transaction_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the LedgerEntryQuery when eager-loading is set. + Edges LedgerEntryEdges `json:"edges"` + selectValues sql.SelectValues +} + +// LedgerEntryEdges holds the relations/edges for other nodes in the graph. +type LedgerEntryEdges struct { + // Transaction holds the value of the transaction edge. + Transaction *LedgerTransaction `json:"transaction,omitempty"` + // SubAccount holds the value of the sub_account edge. + SubAccount *LedgerSubAccount `json:"sub_account,omitempty"` + // SourceBreakageRecords holds the value of the source_breakage_records edge. + SourceBreakageRecords []*LedgerBreakageRecord `json:"source_breakage_records,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [3]bool +} + +// TransactionOrErr returns the Transaction value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e LedgerEntryEdges) TransactionOrErr() (*LedgerTransaction, error) { + if e.Transaction != nil { + return e.Transaction, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: ledgertransaction.Label} + } + return nil, &NotLoadedError{edge: "transaction"} +} + +// SubAccountOrErr returns the SubAccount value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e LedgerEntryEdges) SubAccountOrErr() (*LedgerSubAccount, error) { + if e.SubAccount != nil { + return e.SubAccount, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: ledgersubaccount.Label} + } + return nil, &NotLoadedError{edge: "sub_account"} +} + +// SourceBreakageRecordsOrErr returns the SourceBreakageRecords value or an error if the edge +// was not loaded in eager-loading. +func (e LedgerEntryEdges) SourceBreakageRecordsOrErr() ([]*LedgerBreakageRecord, error) { + if e.loadedTypes[2] { + return e.SourceBreakageRecords, nil + } + return nil, &NotLoadedError{edge: "source_breakage_records"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LedgerEntry) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case ledgerentry.FieldAnnotations: + values[i] = new([]byte) + case ledgerentry.FieldAmount: + values[i] = new(alpacadecimal.Decimal) + case ledgerentry.FieldSchemaVersion: + values[i] = new(sql.NullInt64) + case ledgerentry.FieldID, ledgerentry.FieldNamespace, ledgerentry.FieldSubAccountID, ledgerentry.FieldIdentityKey, ledgerentry.FieldSourceChargeID, ledgerentry.FieldSpendChargeID, ledgerentry.FieldTransactionID: + values[i] = new(sql.NullString) + case ledgerentry.FieldCreatedAt, ledgerentry.FieldUpdatedAt, ledgerentry.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 LedgerEntry fields. +func (_m *LedgerEntry) 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 ledgerentry.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 ledgerentry.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 ledgerentry.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 ledgerentry.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 ledgerentry.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 ledgerentry.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 ledgerentry.FieldSubAccountID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field sub_account_id", values[i]) + } else if value.Valid { + _m.SubAccountID = value.String + } + case ledgerentry.FieldIdentityKey: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field identity_key", values[i]) + } else if value.Valid { + _m.IdentityKey = value.String + } + case ledgerentry.FieldSchemaVersion: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field schema_version", values[i]) + } else if value.Valid { + _m.SchemaVersion = int(value.Int64) + } + case ledgerentry.FieldSourceChargeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field source_charge_id", values[i]) + } else if value.Valid { + _m.SourceChargeID = new(string) + *_m.SourceChargeID = value.String + } + case ledgerentry.FieldSpendChargeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field spend_charge_id", values[i]) + } else if value.Valid { + _m.SpendChargeID = new(string) + *_m.SpendChargeID = value.String + } + case ledgerentry.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 ledgerentry.FieldTransactionID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field transaction_id", values[i]) + } else if value.Valid { + _m.TransactionID = 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 LedgerEntry. +// This includes values selected through modifiers, order, etc. +func (_m *LedgerEntry) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryTransaction queries the "transaction" edge of the LedgerEntry entity. +func (_m *LedgerEntry) QueryTransaction() *LedgerTransactionQuery { + return NewLedgerEntryClient(_m.config).QueryTransaction(_m) +} + +// QuerySubAccount queries the "sub_account" edge of the LedgerEntry entity. +func (_m *LedgerEntry) QuerySubAccount() *LedgerSubAccountQuery { + return NewLedgerEntryClient(_m.config).QuerySubAccount(_m) +} + +// QuerySourceBreakageRecords queries the "source_breakage_records" edge of the LedgerEntry entity. +func (_m *LedgerEntry) QuerySourceBreakageRecords() *LedgerBreakageRecordQuery { + return NewLedgerEntryClient(_m.config).QuerySourceBreakageRecords(_m) +} + +// Update returns a builder for updating this LedgerEntry. +// Note that you need to call LedgerEntry.Unwrap() before calling this method if this LedgerEntry +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *LedgerEntry) Update() *LedgerEntryUpdateOne { + return NewLedgerEntryClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the LedgerEntry 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 *LedgerEntry) Unwrap() *LedgerEntry { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: LedgerEntry is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *LedgerEntry) String() string { + var builder strings.Builder + builder.WriteString("LedgerEntry(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + 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("sub_account_id=") + builder.WriteString(_m.SubAccountID) + builder.WriteString(", ") + builder.WriteString("identity_key=") + builder.WriteString(_m.IdentityKey) + builder.WriteString(", ") + builder.WriteString("schema_version=") + builder.WriteString(fmt.Sprintf("%v", _m.SchemaVersion)) + builder.WriteString(", ") + if v := _m.SourceChargeID; v != nil { + builder.WriteString("source_charge_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SpendChargeID; v != nil { + builder.WriteString("spend_charge_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("amount=") + builder.WriteString(fmt.Sprintf("%v", _m.Amount)) + builder.WriteString(", ") + builder.WriteString("transaction_id=") + builder.WriteString(_m.TransactionID) + builder.WriteByte(')') + return builder.String() +} + +// LedgerEntries is a parsable slice of LedgerEntry. +type LedgerEntries []*LedgerEntry diff --git a/ent/db/ledgerentry/ledgerentry.go b/ent/db/ledgerentry/ledgerentry.go new file mode 100644 index 0000000000000000000000000000000000000000..fde66c314841cffcaf9478b503e90c344fc671c5 --- /dev/null +++ b/ent/db/ledgerentry/ledgerentry.go @@ -0,0 +1,230 @@ +// Code generated by ent, DO NOT EDIT. + +package ledgerentry + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the ledgerentry type in the database. + Label = "ledger_entry" + // 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" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // 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" + // FieldSubAccountID holds the string denoting the sub_account_id field in the database. + FieldSubAccountID = "sub_account_id" + // FieldIdentityKey holds the string denoting the identity_key field in the database. + FieldIdentityKey = "identity_key" + // FieldSchemaVersion holds the string denoting the schema_version field in the database. + FieldSchemaVersion = "schema_version" + // FieldSourceChargeID holds the string denoting the source_charge_id field in the database. + FieldSourceChargeID = "source_charge_id" + // FieldSpendChargeID holds the string denoting the spend_charge_id field in the database. + FieldSpendChargeID = "spend_charge_id" + // FieldAmount holds the string denoting the amount field in the database. + FieldAmount = "amount" + // FieldTransactionID holds the string denoting the transaction_id field in the database. + FieldTransactionID = "transaction_id" + // EdgeTransaction holds the string denoting the transaction edge name in mutations. + EdgeTransaction = "transaction" + // EdgeSubAccount holds the string denoting the sub_account edge name in mutations. + EdgeSubAccount = "sub_account" + // EdgeSourceBreakageRecords holds the string denoting the source_breakage_records edge name in mutations. + EdgeSourceBreakageRecords = "source_breakage_records" + // Table holds the table name of the ledgerentry in the database. + Table = "ledger_entries" + // TransactionTable is the table that holds the transaction relation/edge. + TransactionTable = "ledger_entries" + // TransactionInverseTable is the table name for the LedgerTransaction entity. + // It exists in this package in order to avoid circular dependency with the "ledgertransaction" package. + TransactionInverseTable = "ledger_transactions" + // TransactionColumn is the table column denoting the transaction relation/edge. + TransactionColumn = "transaction_id" + // SubAccountTable is the table that holds the sub_account relation/edge. + SubAccountTable = "ledger_entries" + // SubAccountInverseTable is the table name for the LedgerSubAccount entity. + // It exists in this package in order to avoid circular dependency with the "ledgersubaccount" package. + SubAccountInverseTable = "ledger_sub_accounts" + // SubAccountColumn is the table column denoting the sub_account relation/edge. + SubAccountColumn = "sub_account_id" + // SourceBreakageRecordsTable is the table that holds the source_breakage_records relation/edge. + SourceBreakageRecordsTable = "ledger_breakage_records" + // SourceBreakageRecordsInverseTable is the table name for the LedgerBreakageRecord entity. + // It exists in this package in order to avoid circular dependency with the "ledgerbreakagerecord" package. + SourceBreakageRecordsInverseTable = "ledger_breakage_records" + // SourceBreakageRecordsColumn is the table column denoting the source_breakage_records relation/edge. + SourceBreakageRecordsColumn = "source_entry_id" +) + +// Columns holds all SQL columns for ledgerentry fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldAnnotations, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldSubAccountID, + FieldIdentityKey, + FieldSchemaVersion, + FieldSourceChargeID, + FieldSpendChargeID, + FieldAmount, + FieldTransactionID, +} + +// 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 + // DefaultIdentityKey holds the default value on creation for the "identity_key" field. + DefaultIdentityKey string + // DefaultSchemaVersion holds the default value on creation for the "schema_version" field. + DefaultSchemaVersion int + // SourceChargeIDValidator is a validator for the "source_charge_id" field. It is called by the builders before save. + SourceChargeIDValidator func(string) error + // SpendChargeIDValidator is a validator for the "spend_charge_id" field. It is called by the builders before save. + SpendChargeIDValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// OrderOption defines the ordering options for the LedgerEntry 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() +} + +// BySubAccountID orders the results by the sub_account_id field. +func BySubAccountID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSubAccountID, opts...).ToFunc() +} + +// ByIdentityKey orders the results by the identity_key field. +func ByIdentityKey(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIdentityKey, opts...).ToFunc() +} + +// BySchemaVersion orders the results by the schema_version field. +func BySchemaVersion(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSchemaVersion, opts...).ToFunc() +} + +// BySourceChargeID orders the results by the source_charge_id field. +func BySourceChargeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSourceChargeID, opts...).ToFunc() +} + +// BySpendChargeID orders the results by the spend_charge_id field. +func BySpendChargeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSpendChargeID, opts...).ToFunc() +} + +// ByAmount orders the results by the amount field. +func ByAmount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAmount, opts...).ToFunc() +} + +// ByTransactionID orders the results by the transaction_id field. +func ByTransactionID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTransactionID, opts...).ToFunc() +} + +// ByTransactionField orders the results by transaction field. +func ByTransactionField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTransactionStep(), sql.OrderByField(field, opts...)) + } +} + +// BySubAccountField orders the results by sub_account field. +func BySubAccountField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubAccountStep(), sql.OrderByField(field, opts...)) + } +} + +// BySourceBreakageRecordsCount orders the results by source_breakage_records count. +func BySourceBreakageRecordsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newSourceBreakageRecordsStep(), opts...) + } +} + +// BySourceBreakageRecords orders the results by source_breakage_records terms. +func BySourceBreakageRecords(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSourceBreakageRecordsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newTransactionStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TransactionInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, TransactionTable, TransactionColumn), + ) +} +func newSubAccountStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SubAccountInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubAccountTable, SubAccountColumn), + ) +} +func newSourceBreakageRecordsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SourceBreakageRecordsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SourceBreakageRecordsTable, SourceBreakageRecordsColumn), + ) +} diff --git a/ent/db/ledgerentry/where.go b/ent/db/ledgerentry/where.go new file mode 100644 index 0000000000000000000000000000000000000000..b53fdc18ee4f97a7172d25a04e4f93598538bc2f --- /dev/null +++ b/ent/db/ledgerentry/where.go @@ -0,0 +1,836 @@ +// Code generated by ent, DO NOT EDIT. + +package ledgerentry + +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.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(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.LedgerEntry { + return predicate.LedgerEntry(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.LedgerEntry { + return predicate.LedgerEntry(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.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldDeletedAt, v)) +} + +// SubAccountID applies equality check predicate on the "sub_account_id" field. It's identical to SubAccountIDEQ. +func SubAccountID(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldSubAccountID, v)) +} + +// IdentityKey applies equality check predicate on the "identity_key" field. It's identical to IdentityKeyEQ. +func IdentityKey(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldIdentityKey, v)) +} + +// SchemaVersion applies equality check predicate on the "schema_version" field. It's identical to SchemaVersionEQ. +func SchemaVersion(v int) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldSchemaVersion, v)) +} + +// SourceChargeID applies equality check predicate on the "source_charge_id" field. It's identical to SourceChargeIDEQ. +func SourceChargeID(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldSourceChargeID, v)) +} + +// SpendChargeID applies equality check predicate on the "spend_charge_id" field. It's identical to SpendChargeIDEQ. +func SpendChargeID(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldSpendChargeID, v)) +} + +// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ. +func Amount(v alpacadecimal.Decimal) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldAmount, v)) +} + +// TransactionID applies equality check predicate on the "transaction_id" field. It's identical to TransactionIDEQ. +func TransactionID(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldTransactionID, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldContainsFold(FieldNamespace, v)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNotNull(FieldAnnotations)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNotNull(FieldDeletedAt)) +} + +// SubAccountIDEQ applies the EQ predicate on the "sub_account_id" field. +func SubAccountIDEQ(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldSubAccountID, v)) +} + +// SubAccountIDNEQ applies the NEQ predicate on the "sub_account_id" field. +func SubAccountIDNEQ(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNEQ(FieldSubAccountID, v)) +} + +// SubAccountIDIn applies the In predicate on the "sub_account_id" field. +func SubAccountIDIn(vs ...string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldIn(FieldSubAccountID, vs...)) +} + +// SubAccountIDNotIn applies the NotIn predicate on the "sub_account_id" field. +func SubAccountIDNotIn(vs ...string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNotIn(FieldSubAccountID, vs...)) +} + +// SubAccountIDGT applies the GT predicate on the "sub_account_id" field. +func SubAccountIDGT(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGT(FieldSubAccountID, v)) +} + +// SubAccountIDGTE applies the GTE predicate on the "sub_account_id" field. +func SubAccountIDGTE(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGTE(FieldSubAccountID, v)) +} + +// SubAccountIDLT applies the LT predicate on the "sub_account_id" field. +func SubAccountIDLT(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLT(FieldSubAccountID, v)) +} + +// SubAccountIDLTE applies the LTE predicate on the "sub_account_id" field. +func SubAccountIDLTE(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLTE(FieldSubAccountID, v)) +} + +// SubAccountIDContains applies the Contains predicate on the "sub_account_id" field. +func SubAccountIDContains(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldContains(FieldSubAccountID, v)) +} + +// SubAccountIDHasPrefix applies the HasPrefix predicate on the "sub_account_id" field. +func SubAccountIDHasPrefix(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldHasPrefix(FieldSubAccountID, v)) +} + +// SubAccountIDHasSuffix applies the HasSuffix predicate on the "sub_account_id" field. +func SubAccountIDHasSuffix(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldHasSuffix(FieldSubAccountID, v)) +} + +// SubAccountIDEqualFold applies the EqualFold predicate on the "sub_account_id" field. +func SubAccountIDEqualFold(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEqualFold(FieldSubAccountID, v)) +} + +// SubAccountIDContainsFold applies the ContainsFold predicate on the "sub_account_id" field. +func SubAccountIDContainsFold(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldContainsFold(FieldSubAccountID, v)) +} + +// IdentityKeyEQ applies the EQ predicate on the "identity_key" field. +func IdentityKeyEQ(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldIdentityKey, v)) +} + +// IdentityKeyNEQ applies the NEQ predicate on the "identity_key" field. +func IdentityKeyNEQ(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNEQ(FieldIdentityKey, v)) +} + +// IdentityKeyIn applies the In predicate on the "identity_key" field. +func IdentityKeyIn(vs ...string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldIn(FieldIdentityKey, vs...)) +} + +// IdentityKeyNotIn applies the NotIn predicate on the "identity_key" field. +func IdentityKeyNotIn(vs ...string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNotIn(FieldIdentityKey, vs...)) +} + +// IdentityKeyGT applies the GT predicate on the "identity_key" field. +func IdentityKeyGT(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGT(FieldIdentityKey, v)) +} + +// IdentityKeyGTE applies the GTE predicate on the "identity_key" field. +func IdentityKeyGTE(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGTE(FieldIdentityKey, v)) +} + +// IdentityKeyLT applies the LT predicate on the "identity_key" field. +func IdentityKeyLT(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLT(FieldIdentityKey, v)) +} + +// IdentityKeyLTE applies the LTE predicate on the "identity_key" field. +func IdentityKeyLTE(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLTE(FieldIdentityKey, v)) +} + +// IdentityKeyContains applies the Contains predicate on the "identity_key" field. +func IdentityKeyContains(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldContains(FieldIdentityKey, v)) +} + +// IdentityKeyHasPrefix applies the HasPrefix predicate on the "identity_key" field. +func IdentityKeyHasPrefix(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldHasPrefix(FieldIdentityKey, v)) +} + +// IdentityKeyHasSuffix applies the HasSuffix predicate on the "identity_key" field. +func IdentityKeyHasSuffix(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldHasSuffix(FieldIdentityKey, v)) +} + +// IdentityKeyEqualFold applies the EqualFold predicate on the "identity_key" field. +func IdentityKeyEqualFold(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEqualFold(FieldIdentityKey, v)) +} + +// IdentityKeyContainsFold applies the ContainsFold predicate on the "identity_key" field. +func IdentityKeyContainsFold(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldContainsFold(FieldIdentityKey, v)) +} + +// SchemaVersionEQ applies the EQ predicate on the "schema_version" field. +func SchemaVersionEQ(v int) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldSchemaVersion, v)) +} + +// SchemaVersionNEQ applies the NEQ predicate on the "schema_version" field. +func SchemaVersionNEQ(v int) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNEQ(FieldSchemaVersion, v)) +} + +// SchemaVersionIn applies the In predicate on the "schema_version" field. +func SchemaVersionIn(vs ...int) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldIn(FieldSchemaVersion, vs...)) +} + +// SchemaVersionNotIn applies the NotIn predicate on the "schema_version" field. +func SchemaVersionNotIn(vs ...int) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNotIn(FieldSchemaVersion, vs...)) +} + +// SchemaVersionGT applies the GT predicate on the "schema_version" field. +func SchemaVersionGT(v int) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGT(FieldSchemaVersion, v)) +} + +// SchemaVersionGTE applies the GTE predicate on the "schema_version" field. +func SchemaVersionGTE(v int) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGTE(FieldSchemaVersion, v)) +} + +// SchemaVersionLT applies the LT predicate on the "schema_version" field. +func SchemaVersionLT(v int) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLT(FieldSchemaVersion, v)) +} + +// SchemaVersionLTE applies the LTE predicate on the "schema_version" field. +func SchemaVersionLTE(v int) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLTE(FieldSchemaVersion, v)) +} + +// SourceChargeIDEQ applies the EQ predicate on the "source_charge_id" field. +func SourceChargeIDEQ(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldSourceChargeID, v)) +} + +// SourceChargeIDNEQ applies the NEQ predicate on the "source_charge_id" field. +func SourceChargeIDNEQ(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNEQ(FieldSourceChargeID, v)) +} + +// SourceChargeIDIn applies the In predicate on the "source_charge_id" field. +func SourceChargeIDIn(vs ...string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldIn(FieldSourceChargeID, vs...)) +} + +// SourceChargeIDNotIn applies the NotIn predicate on the "source_charge_id" field. +func SourceChargeIDNotIn(vs ...string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNotIn(FieldSourceChargeID, vs...)) +} + +// SourceChargeIDGT applies the GT predicate on the "source_charge_id" field. +func SourceChargeIDGT(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGT(FieldSourceChargeID, v)) +} + +// SourceChargeIDGTE applies the GTE predicate on the "source_charge_id" field. +func SourceChargeIDGTE(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGTE(FieldSourceChargeID, v)) +} + +// SourceChargeIDLT applies the LT predicate on the "source_charge_id" field. +func SourceChargeIDLT(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLT(FieldSourceChargeID, v)) +} + +// SourceChargeIDLTE applies the LTE predicate on the "source_charge_id" field. +func SourceChargeIDLTE(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLTE(FieldSourceChargeID, v)) +} + +// SourceChargeIDContains applies the Contains predicate on the "source_charge_id" field. +func SourceChargeIDContains(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldContains(FieldSourceChargeID, v)) +} + +// SourceChargeIDHasPrefix applies the HasPrefix predicate on the "source_charge_id" field. +func SourceChargeIDHasPrefix(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldHasPrefix(FieldSourceChargeID, v)) +} + +// SourceChargeIDHasSuffix applies the HasSuffix predicate on the "source_charge_id" field. +func SourceChargeIDHasSuffix(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldHasSuffix(FieldSourceChargeID, v)) +} + +// SourceChargeIDIsNil applies the IsNil predicate on the "source_charge_id" field. +func SourceChargeIDIsNil() predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldIsNull(FieldSourceChargeID)) +} + +// SourceChargeIDNotNil applies the NotNil predicate on the "source_charge_id" field. +func SourceChargeIDNotNil() predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNotNull(FieldSourceChargeID)) +} + +// SourceChargeIDEqualFold applies the EqualFold predicate on the "source_charge_id" field. +func SourceChargeIDEqualFold(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEqualFold(FieldSourceChargeID, v)) +} + +// SourceChargeIDContainsFold applies the ContainsFold predicate on the "source_charge_id" field. +func SourceChargeIDContainsFold(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldContainsFold(FieldSourceChargeID, v)) +} + +// SpendChargeIDEQ applies the EQ predicate on the "spend_charge_id" field. +func SpendChargeIDEQ(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldSpendChargeID, v)) +} + +// SpendChargeIDNEQ applies the NEQ predicate on the "spend_charge_id" field. +func SpendChargeIDNEQ(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNEQ(FieldSpendChargeID, v)) +} + +// SpendChargeIDIn applies the In predicate on the "spend_charge_id" field. +func SpendChargeIDIn(vs ...string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldIn(FieldSpendChargeID, vs...)) +} + +// SpendChargeIDNotIn applies the NotIn predicate on the "spend_charge_id" field. +func SpendChargeIDNotIn(vs ...string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNotIn(FieldSpendChargeID, vs...)) +} + +// SpendChargeIDGT applies the GT predicate on the "spend_charge_id" field. +func SpendChargeIDGT(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGT(FieldSpendChargeID, v)) +} + +// SpendChargeIDGTE applies the GTE predicate on the "spend_charge_id" field. +func SpendChargeIDGTE(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGTE(FieldSpendChargeID, v)) +} + +// SpendChargeIDLT applies the LT predicate on the "spend_charge_id" field. +func SpendChargeIDLT(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLT(FieldSpendChargeID, v)) +} + +// SpendChargeIDLTE applies the LTE predicate on the "spend_charge_id" field. +func SpendChargeIDLTE(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLTE(FieldSpendChargeID, v)) +} + +// SpendChargeIDContains applies the Contains predicate on the "spend_charge_id" field. +func SpendChargeIDContains(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldContains(FieldSpendChargeID, v)) +} + +// SpendChargeIDHasPrefix applies the HasPrefix predicate on the "spend_charge_id" field. +func SpendChargeIDHasPrefix(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldHasPrefix(FieldSpendChargeID, v)) +} + +// SpendChargeIDHasSuffix applies the HasSuffix predicate on the "spend_charge_id" field. +func SpendChargeIDHasSuffix(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldHasSuffix(FieldSpendChargeID, v)) +} + +// SpendChargeIDIsNil applies the IsNil predicate on the "spend_charge_id" field. +func SpendChargeIDIsNil() predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldIsNull(FieldSpendChargeID)) +} + +// SpendChargeIDNotNil applies the NotNil predicate on the "spend_charge_id" field. +func SpendChargeIDNotNil() predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNotNull(FieldSpendChargeID)) +} + +// SpendChargeIDEqualFold applies the EqualFold predicate on the "spend_charge_id" field. +func SpendChargeIDEqualFold(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEqualFold(FieldSpendChargeID, v)) +} + +// SpendChargeIDContainsFold applies the ContainsFold predicate on the "spend_charge_id" field. +func SpendChargeIDContainsFold(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldContainsFold(FieldSpendChargeID, v)) +} + +// AmountEQ applies the EQ predicate on the "amount" field. +func AmountEQ(v alpacadecimal.Decimal) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldAmount, v)) +} + +// AmountNEQ applies the NEQ predicate on the "amount" field. +func AmountNEQ(v alpacadecimal.Decimal) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNEQ(FieldAmount, v)) +} + +// AmountIn applies the In predicate on the "amount" field. +func AmountIn(vs ...alpacadecimal.Decimal) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldIn(FieldAmount, vs...)) +} + +// AmountNotIn applies the NotIn predicate on the "amount" field. +func AmountNotIn(vs ...alpacadecimal.Decimal) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNotIn(FieldAmount, vs...)) +} + +// AmountGT applies the GT predicate on the "amount" field. +func AmountGT(v alpacadecimal.Decimal) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGT(FieldAmount, v)) +} + +// AmountGTE applies the GTE predicate on the "amount" field. +func AmountGTE(v alpacadecimal.Decimal) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGTE(FieldAmount, v)) +} + +// AmountLT applies the LT predicate on the "amount" field. +func AmountLT(v alpacadecimal.Decimal) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLT(FieldAmount, v)) +} + +// AmountLTE applies the LTE predicate on the "amount" field. +func AmountLTE(v alpacadecimal.Decimal) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLTE(FieldAmount, v)) +} + +// TransactionIDEQ applies the EQ predicate on the "transaction_id" field. +func TransactionIDEQ(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEQ(FieldTransactionID, v)) +} + +// TransactionIDNEQ applies the NEQ predicate on the "transaction_id" field. +func TransactionIDNEQ(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNEQ(FieldTransactionID, v)) +} + +// TransactionIDIn applies the In predicate on the "transaction_id" field. +func TransactionIDIn(vs ...string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldIn(FieldTransactionID, vs...)) +} + +// TransactionIDNotIn applies the NotIn predicate on the "transaction_id" field. +func TransactionIDNotIn(vs ...string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldNotIn(FieldTransactionID, vs...)) +} + +// TransactionIDGT applies the GT predicate on the "transaction_id" field. +func TransactionIDGT(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGT(FieldTransactionID, v)) +} + +// TransactionIDGTE applies the GTE predicate on the "transaction_id" field. +func TransactionIDGTE(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldGTE(FieldTransactionID, v)) +} + +// TransactionIDLT applies the LT predicate on the "transaction_id" field. +func TransactionIDLT(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLT(FieldTransactionID, v)) +} + +// TransactionIDLTE applies the LTE predicate on the "transaction_id" field. +func TransactionIDLTE(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldLTE(FieldTransactionID, v)) +} + +// TransactionIDContains applies the Contains predicate on the "transaction_id" field. +func TransactionIDContains(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldContains(FieldTransactionID, v)) +} + +// TransactionIDHasPrefix applies the HasPrefix predicate on the "transaction_id" field. +func TransactionIDHasPrefix(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldHasPrefix(FieldTransactionID, v)) +} + +// TransactionIDHasSuffix applies the HasSuffix predicate on the "transaction_id" field. +func TransactionIDHasSuffix(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldHasSuffix(FieldTransactionID, v)) +} + +// TransactionIDEqualFold applies the EqualFold predicate on the "transaction_id" field. +func TransactionIDEqualFold(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldEqualFold(FieldTransactionID, v)) +} + +// TransactionIDContainsFold applies the ContainsFold predicate on the "transaction_id" field. +func TransactionIDContainsFold(v string) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.FieldContainsFold(FieldTransactionID, v)) +} + +// HasTransaction applies the HasEdge predicate on the "transaction" edge. +func HasTransaction() predicate.LedgerEntry { + return predicate.LedgerEntry(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, TransactionTable, TransactionColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTransactionWith applies the HasEdge predicate on the "transaction" edge with a given conditions (other predicates). +func HasTransactionWith(preds ...predicate.LedgerTransaction) predicate.LedgerEntry { + return predicate.LedgerEntry(func(s *sql.Selector) { + step := newTransactionStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSubAccount applies the HasEdge predicate on the "sub_account" edge. +func HasSubAccount() predicate.LedgerEntry { + return predicate.LedgerEntry(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SubAccountTable, SubAccountColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubAccountWith applies the HasEdge predicate on the "sub_account" edge with a given conditions (other predicates). +func HasSubAccountWith(preds ...predicate.LedgerSubAccount) predicate.LedgerEntry { + return predicate.LedgerEntry(func(s *sql.Selector) { + step := newSubAccountStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSourceBreakageRecords applies the HasEdge predicate on the "source_breakage_records" edge. +func HasSourceBreakageRecords() predicate.LedgerEntry { + return predicate.LedgerEntry(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SourceBreakageRecordsTable, SourceBreakageRecordsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSourceBreakageRecordsWith applies the HasEdge predicate on the "source_breakage_records" edge with a given conditions (other predicates). +func HasSourceBreakageRecordsWith(preds ...predicate.LedgerBreakageRecord) predicate.LedgerEntry { + return predicate.LedgerEntry(func(s *sql.Selector) { + step := newSourceBreakageRecordsStep() + 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.LedgerEntry) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LedgerEntry) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LedgerEntry) predicate.LedgerEntry { + return predicate.LedgerEntry(sql.NotPredicates(p)) +} diff --git a/ent/db/ledgerentry_create.go b/ent/db/ledgerentry_create.go new file mode 100644 index 0000000000000000000000000000000000000000..2573d18725d2b33b67a662e1af343b9f971a7ada --- /dev/null +++ b/ent/db/ledgerentry_create.go @@ -0,0 +1,978 @@ +// 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/ledgerbreakagerecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgerentry" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransaction" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerEntryCreate is the builder for creating a LedgerEntry entity. +type LedgerEntryCreate struct { + config + mutation *LedgerEntryMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *LedgerEntryCreate) SetNamespace(v string) *LedgerEntryCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *LedgerEntryCreate) SetAnnotations(v models.Annotations) *LedgerEntryCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *LedgerEntryCreate) SetCreatedAt(v time.Time) *LedgerEntryCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *LedgerEntryCreate) SetNillableCreatedAt(v *time.Time) *LedgerEntryCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *LedgerEntryCreate) SetUpdatedAt(v time.Time) *LedgerEntryCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *LedgerEntryCreate) SetNillableUpdatedAt(v *time.Time) *LedgerEntryCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *LedgerEntryCreate) SetDeletedAt(v time.Time) *LedgerEntryCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *LedgerEntryCreate) SetNillableDeletedAt(v *time.Time) *LedgerEntryCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetSubAccountID sets the "sub_account_id" field. +func (_c *LedgerEntryCreate) SetSubAccountID(v string) *LedgerEntryCreate { + _c.mutation.SetSubAccountID(v) + return _c +} + +// SetIdentityKey sets the "identity_key" field. +func (_c *LedgerEntryCreate) SetIdentityKey(v string) *LedgerEntryCreate { + _c.mutation.SetIdentityKey(v) + return _c +} + +// SetNillableIdentityKey sets the "identity_key" field if the given value is not nil. +func (_c *LedgerEntryCreate) SetNillableIdentityKey(v *string) *LedgerEntryCreate { + if v != nil { + _c.SetIdentityKey(*v) + } + return _c +} + +// SetSchemaVersion sets the "schema_version" field. +func (_c *LedgerEntryCreate) SetSchemaVersion(v int) *LedgerEntryCreate { + _c.mutation.SetSchemaVersion(v) + return _c +} + +// SetNillableSchemaVersion sets the "schema_version" field if the given value is not nil. +func (_c *LedgerEntryCreate) SetNillableSchemaVersion(v *int) *LedgerEntryCreate { + if v != nil { + _c.SetSchemaVersion(*v) + } + return _c +} + +// SetSourceChargeID sets the "source_charge_id" field. +func (_c *LedgerEntryCreate) SetSourceChargeID(v string) *LedgerEntryCreate { + _c.mutation.SetSourceChargeID(v) + return _c +} + +// SetNillableSourceChargeID sets the "source_charge_id" field if the given value is not nil. +func (_c *LedgerEntryCreate) SetNillableSourceChargeID(v *string) *LedgerEntryCreate { + if v != nil { + _c.SetSourceChargeID(*v) + } + return _c +} + +// SetSpendChargeID sets the "spend_charge_id" field. +func (_c *LedgerEntryCreate) SetSpendChargeID(v string) *LedgerEntryCreate { + _c.mutation.SetSpendChargeID(v) + return _c +} + +// SetNillableSpendChargeID sets the "spend_charge_id" field if the given value is not nil. +func (_c *LedgerEntryCreate) SetNillableSpendChargeID(v *string) *LedgerEntryCreate { + if v != nil { + _c.SetSpendChargeID(*v) + } + return _c +} + +// SetAmount sets the "amount" field. +func (_c *LedgerEntryCreate) SetAmount(v alpacadecimal.Decimal) *LedgerEntryCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetTransactionID sets the "transaction_id" field. +func (_c *LedgerEntryCreate) SetTransactionID(v string) *LedgerEntryCreate { + _c.mutation.SetTransactionID(v) + return _c +} + +// SetID sets the "id" field. +func (_c *LedgerEntryCreate) SetID(v string) *LedgerEntryCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *LedgerEntryCreate) SetNillableID(v *string) *LedgerEntryCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetTransaction sets the "transaction" edge to the LedgerTransaction entity. +func (_c *LedgerEntryCreate) SetTransaction(v *LedgerTransaction) *LedgerEntryCreate { + return _c.SetTransactionID(v.ID) +} + +// SetSubAccount sets the "sub_account" edge to the LedgerSubAccount entity. +func (_c *LedgerEntryCreate) SetSubAccount(v *LedgerSubAccount) *LedgerEntryCreate { + return _c.SetSubAccountID(v.ID) +} + +// AddSourceBreakageRecordIDs adds the "source_breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_c *LedgerEntryCreate) AddSourceBreakageRecordIDs(ids ...string) *LedgerEntryCreate { + _c.mutation.AddSourceBreakageRecordIDs(ids...) + return _c +} + +// AddSourceBreakageRecords adds the "source_breakage_records" edges to the LedgerBreakageRecord entity. +func (_c *LedgerEntryCreate) AddSourceBreakageRecords(v ...*LedgerBreakageRecord) *LedgerEntryCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddSourceBreakageRecordIDs(ids...) +} + +// Mutation returns the LedgerEntryMutation object of the builder. +func (_c *LedgerEntryCreate) Mutation() *LedgerEntryMutation { + return _c.mutation +} + +// Save creates the LedgerEntry in the database. +func (_c *LedgerEntryCreate) Save(ctx context.Context) (*LedgerEntry, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *LedgerEntryCreate) SaveX(ctx context.Context) *LedgerEntry { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LedgerEntryCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LedgerEntryCreate) 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 *LedgerEntryCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := ledgerentry.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := ledgerentry.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.IdentityKey(); !ok { + v := ledgerentry.DefaultIdentityKey + _c.mutation.SetIdentityKey(v) + } + if _, ok := _c.mutation.SchemaVersion(); !ok { + v := ledgerentry.DefaultSchemaVersion + _c.mutation.SetSchemaVersion(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := ledgerentry.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *LedgerEntryCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "LedgerEntry.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := ledgerentry.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "LedgerEntry.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "LedgerEntry.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "LedgerEntry.updated_at"`)} + } + if _, ok := _c.mutation.SubAccountID(); !ok { + return &ValidationError{Name: "sub_account_id", err: errors.New(`db: missing required field "LedgerEntry.sub_account_id"`)} + } + if _, ok := _c.mutation.IdentityKey(); !ok { + return &ValidationError{Name: "identity_key", err: errors.New(`db: missing required field "LedgerEntry.identity_key"`)} + } + if _, ok := _c.mutation.SchemaVersion(); !ok { + return &ValidationError{Name: "schema_version", err: errors.New(`db: missing required field "LedgerEntry.schema_version"`)} + } + if v, ok := _c.mutation.SourceChargeID(); ok { + if err := ledgerentry.SourceChargeIDValidator(v); err != nil { + return &ValidationError{Name: "source_charge_id", err: fmt.Errorf(`db: validator failed for field "LedgerEntry.source_charge_id": %w`, err)} + } + } + if v, ok := _c.mutation.SpendChargeID(); ok { + if err := ledgerentry.SpendChargeIDValidator(v); err != nil { + return &ValidationError{Name: "spend_charge_id", err: fmt.Errorf(`db: validator failed for field "LedgerEntry.spend_charge_id": %w`, err)} + } + } + if _, ok := _c.mutation.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`db: missing required field "LedgerEntry.amount"`)} + } + if _, ok := _c.mutation.TransactionID(); !ok { + return &ValidationError{Name: "transaction_id", err: errors.New(`db: missing required field "LedgerEntry.transaction_id"`)} + } + if len(_c.mutation.TransactionIDs()) == 0 { + return &ValidationError{Name: "transaction", err: errors.New(`db: missing required edge "LedgerEntry.transaction"`)} + } + if len(_c.mutation.SubAccountIDs()) == 0 { + return &ValidationError{Name: "sub_account", err: errors.New(`db: missing required edge "LedgerEntry.sub_account"`)} + } + return nil +} + +func (_c *LedgerEntryCreate) sqlSave(ctx context.Context) (*LedgerEntry, 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 LedgerEntry.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *LedgerEntryCreate) createSpec() (*LedgerEntry, *sqlgraph.CreateSpec) { + var ( + _node = &LedgerEntry{config: _c.config} + _spec = sqlgraph.NewCreateSpec(ledgerentry.Table, sqlgraph.NewFieldSpec(ledgerentry.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(ledgerentry.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(ledgerentry.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(ledgerentry.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(ledgerentry.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(ledgerentry.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.IdentityKey(); ok { + _spec.SetField(ledgerentry.FieldIdentityKey, field.TypeString, value) + _node.IdentityKey = value + } + if value, ok := _c.mutation.SchemaVersion(); ok { + _spec.SetField(ledgerentry.FieldSchemaVersion, field.TypeInt, value) + _node.SchemaVersion = value + } + if value, ok := _c.mutation.SourceChargeID(); ok { + _spec.SetField(ledgerentry.FieldSourceChargeID, field.TypeString, value) + _node.SourceChargeID = &value + } + if value, ok := _c.mutation.SpendChargeID(); ok { + _spec.SetField(ledgerentry.FieldSpendChargeID, field.TypeString, value) + _node.SpendChargeID = &value + } + if value, ok := _c.mutation.Amount(); ok { + _spec.SetField(ledgerentry.FieldAmount, field.TypeOther, value) + _node.Amount = value + } + if nodes := _c.mutation.TransactionIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: ledgerentry.TransactionTable, + Columns: []string{ledgerentry.TransactionColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgertransaction.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.TransactionID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.SubAccountIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: ledgerentry.SubAccountTable, + Columns: []string{ledgerentry.SubAccountColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccount.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.SubAccountID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.SourceBreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerentry.SourceBreakageRecordsTable, + Columns: []string{ledgerentry.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.LedgerEntry.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.LedgerEntryUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *LedgerEntryCreate) OnConflict(opts ...sql.ConflictOption) *LedgerEntryUpsertOne { + _c.conflict = opts + return &LedgerEntryUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.LedgerEntry.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *LedgerEntryCreate) OnConflictColumns(columns ...string) *LedgerEntryUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &LedgerEntryUpsertOne{ + create: _c, + } +} + +type ( + // LedgerEntryUpsertOne is the builder for "upsert"-ing + // one LedgerEntry node. + LedgerEntryUpsertOne struct { + create *LedgerEntryCreate + } + + // LedgerEntryUpsert is the "OnConflict" setter. + LedgerEntryUpsert struct { + *sql.UpdateSet + } +) + +// SetAnnotations sets the "annotations" field. +func (u *LedgerEntryUpsert) SetAnnotations(v models.Annotations) *LedgerEntryUpsert { + u.Set(ledgerentry.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerEntryUpsert) UpdateAnnotations() *LedgerEntryUpsert { + u.SetExcluded(ledgerentry.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerEntryUpsert) ClearAnnotations() *LedgerEntryUpsert { + u.SetNull(ledgerentry.FieldAnnotations) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerEntryUpsert) SetUpdatedAt(v time.Time) *LedgerEntryUpsert { + u.Set(ledgerentry.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerEntryUpsert) UpdateUpdatedAt() *LedgerEntryUpsert { + u.SetExcluded(ledgerentry.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerEntryUpsert) SetDeletedAt(v time.Time) *LedgerEntryUpsert { + u.Set(ledgerentry.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerEntryUpsert) UpdateDeletedAt() *LedgerEntryUpsert { + u.SetExcluded(ledgerentry.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerEntryUpsert) ClearDeletedAt() *LedgerEntryUpsert { + u.SetNull(ledgerentry.FieldDeletedAt) + 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.LedgerEntry.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(ledgerentry.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LedgerEntryUpsertOne) UpdateNewValues() *LedgerEntryUpsertOne { + 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(ledgerentry.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(ledgerentry.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(ledgerentry.FieldCreatedAt) + } + if _, exists := u.create.mutation.SubAccountID(); exists { + s.SetIgnore(ledgerentry.FieldSubAccountID) + } + if _, exists := u.create.mutation.IdentityKey(); exists { + s.SetIgnore(ledgerentry.FieldIdentityKey) + } + if _, exists := u.create.mutation.SchemaVersion(); exists { + s.SetIgnore(ledgerentry.FieldSchemaVersion) + } + if _, exists := u.create.mutation.SourceChargeID(); exists { + s.SetIgnore(ledgerentry.FieldSourceChargeID) + } + if _, exists := u.create.mutation.SpendChargeID(); exists { + s.SetIgnore(ledgerentry.FieldSpendChargeID) + } + if _, exists := u.create.mutation.Amount(); exists { + s.SetIgnore(ledgerentry.FieldAmount) + } + if _, exists := u.create.mutation.TransactionID(); exists { + s.SetIgnore(ledgerentry.FieldTransactionID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.LedgerEntry.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LedgerEntryUpsertOne) Ignore() *LedgerEntryUpsertOne { + 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 *LedgerEntryUpsertOne) DoNothing() *LedgerEntryUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LedgerEntryCreate.OnConflict +// documentation for more info. +func (u *LedgerEntryUpsertOne) Update(set func(*LedgerEntryUpsert)) *LedgerEntryUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LedgerEntryUpsert{UpdateSet: update}) + })) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *LedgerEntryUpsertOne) SetAnnotations(v models.Annotations) *LedgerEntryUpsertOne { + return u.Update(func(s *LedgerEntryUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerEntryUpsertOne) UpdateAnnotations() *LedgerEntryUpsertOne { + return u.Update(func(s *LedgerEntryUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerEntryUpsertOne) ClearAnnotations() *LedgerEntryUpsertOne { + return u.Update(func(s *LedgerEntryUpsert) { + s.ClearAnnotations() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerEntryUpsertOne) SetUpdatedAt(v time.Time) *LedgerEntryUpsertOne { + return u.Update(func(s *LedgerEntryUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerEntryUpsertOne) UpdateUpdatedAt() *LedgerEntryUpsertOne { + return u.Update(func(s *LedgerEntryUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerEntryUpsertOne) SetDeletedAt(v time.Time) *LedgerEntryUpsertOne { + return u.Update(func(s *LedgerEntryUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerEntryUpsertOne) UpdateDeletedAt() *LedgerEntryUpsertOne { + return u.Update(func(s *LedgerEntryUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerEntryUpsertOne) ClearDeletedAt() *LedgerEntryUpsertOne { + return u.Update(func(s *LedgerEntryUpsert) { + s.ClearDeletedAt() + }) +} + +// Exec executes the query. +func (u *LedgerEntryUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for LedgerEntryCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LedgerEntryUpsertOne) 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 *LedgerEntryUpsertOne) 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: LedgerEntryUpsertOne.ID is not supported by MySQL driver. Use LedgerEntryUpsertOne.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 *LedgerEntryUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// LedgerEntryCreateBulk is the builder for creating many LedgerEntry entities in bulk. +type LedgerEntryCreateBulk struct { + config + err error + builders []*LedgerEntryCreate + conflict []sql.ConflictOption +} + +// Save creates the LedgerEntry entities in the database. +func (_c *LedgerEntryCreateBulk) Save(ctx context.Context) ([]*LedgerEntry, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*LedgerEntry, 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.(*LedgerEntryMutation) + 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 *LedgerEntryCreateBulk) SaveX(ctx context.Context) []*LedgerEntry { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LedgerEntryCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LedgerEntryCreateBulk) 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.LedgerEntry.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.LedgerEntryUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *LedgerEntryCreateBulk) OnConflict(opts ...sql.ConflictOption) *LedgerEntryUpsertBulk { + _c.conflict = opts + return &LedgerEntryUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.LedgerEntry.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *LedgerEntryCreateBulk) OnConflictColumns(columns ...string) *LedgerEntryUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &LedgerEntryUpsertBulk{ + create: _c, + } +} + +// LedgerEntryUpsertBulk is the builder for "upsert"-ing +// a bulk of LedgerEntry nodes. +type LedgerEntryUpsertBulk struct { + create *LedgerEntryCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.LedgerEntry.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(ledgerentry.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LedgerEntryUpsertBulk) UpdateNewValues() *LedgerEntryUpsertBulk { + 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(ledgerentry.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(ledgerentry.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(ledgerentry.FieldCreatedAt) + } + if _, exists := b.mutation.SubAccountID(); exists { + s.SetIgnore(ledgerentry.FieldSubAccountID) + } + if _, exists := b.mutation.IdentityKey(); exists { + s.SetIgnore(ledgerentry.FieldIdentityKey) + } + if _, exists := b.mutation.SchemaVersion(); exists { + s.SetIgnore(ledgerentry.FieldSchemaVersion) + } + if _, exists := b.mutation.SourceChargeID(); exists { + s.SetIgnore(ledgerentry.FieldSourceChargeID) + } + if _, exists := b.mutation.SpendChargeID(); exists { + s.SetIgnore(ledgerentry.FieldSpendChargeID) + } + if _, exists := b.mutation.Amount(); exists { + s.SetIgnore(ledgerentry.FieldAmount) + } + if _, exists := b.mutation.TransactionID(); exists { + s.SetIgnore(ledgerentry.FieldTransactionID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.LedgerEntry.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LedgerEntryUpsertBulk) Ignore() *LedgerEntryUpsertBulk { + 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 *LedgerEntryUpsertBulk) DoNothing() *LedgerEntryUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LedgerEntryCreateBulk.OnConflict +// documentation for more info. +func (u *LedgerEntryUpsertBulk) Update(set func(*LedgerEntryUpsert)) *LedgerEntryUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LedgerEntryUpsert{UpdateSet: update}) + })) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *LedgerEntryUpsertBulk) SetAnnotations(v models.Annotations) *LedgerEntryUpsertBulk { + return u.Update(func(s *LedgerEntryUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerEntryUpsertBulk) UpdateAnnotations() *LedgerEntryUpsertBulk { + return u.Update(func(s *LedgerEntryUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerEntryUpsertBulk) ClearAnnotations() *LedgerEntryUpsertBulk { + return u.Update(func(s *LedgerEntryUpsert) { + s.ClearAnnotations() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerEntryUpsertBulk) SetUpdatedAt(v time.Time) *LedgerEntryUpsertBulk { + return u.Update(func(s *LedgerEntryUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerEntryUpsertBulk) UpdateUpdatedAt() *LedgerEntryUpsertBulk { + return u.Update(func(s *LedgerEntryUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerEntryUpsertBulk) SetDeletedAt(v time.Time) *LedgerEntryUpsertBulk { + return u.Update(func(s *LedgerEntryUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerEntryUpsertBulk) UpdateDeletedAt() *LedgerEntryUpsertBulk { + return u.Update(func(s *LedgerEntryUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerEntryUpsertBulk) ClearDeletedAt() *LedgerEntryUpsertBulk { + return u.Update(func(s *LedgerEntryUpsert) { + s.ClearDeletedAt() + }) +} + +// Exec executes the query. +func (u *LedgerEntryUpsertBulk) 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 LedgerEntryCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for LedgerEntryCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LedgerEntryUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/ledgerentry_delete.go b/ent/db/ledgerentry_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..1f9ac0958bf8908c596aac487bbd5a942248913d --- /dev/null +++ b/ent/db/ledgerentry_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/ledgerentry" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LedgerEntryDelete is the builder for deleting a LedgerEntry entity. +type LedgerEntryDelete struct { + config + hooks []Hook + mutation *LedgerEntryMutation +} + +// Where appends a list predicates to the LedgerEntryDelete builder. +func (_d *LedgerEntryDelete) Where(ps ...predicate.LedgerEntry) *LedgerEntryDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *LedgerEntryDelete) 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 *LedgerEntryDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *LedgerEntryDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(ledgerentry.Table, sqlgraph.NewFieldSpec(ledgerentry.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 +} + +// LedgerEntryDeleteOne is the builder for deleting a single LedgerEntry entity. +type LedgerEntryDeleteOne struct { + _d *LedgerEntryDelete +} + +// Where appends a list predicates to the LedgerEntryDelete builder. +func (_d *LedgerEntryDeleteOne) Where(ps ...predicate.LedgerEntry) *LedgerEntryDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *LedgerEntryDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{ledgerentry.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *LedgerEntryDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/ledgerentry_query.go b/ent/db/ledgerentry_query.go new file mode 100644 index 0000000000000000000000000000000000000000..8046709353f1a62f18497247f156b469a0df6fc4 --- /dev/null +++ b/ent/db/ledgerentry_query.go @@ -0,0 +1,798 @@ +// 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/ledgerbreakagerecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgerentry" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransaction" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LedgerEntryQuery is the builder for querying LedgerEntry entities. +type LedgerEntryQuery struct { + config + ctx *QueryContext + order []ledgerentry.OrderOption + inters []Interceptor + predicates []predicate.LedgerEntry + withTransaction *LedgerTransactionQuery + withSubAccount *LedgerSubAccountQuery + withSourceBreakageRecords *LedgerBreakageRecordQuery + 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 LedgerEntryQuery builder. +func (_q *LedgerEntryQuery) Where(ps ...predicate.LedgerEntry) *LedgerEntryQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *LedgerEntryQuery) Limit(limit int) *LedgerEntryQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *LedgerEntryQuery) Offset(offset int) *LedgerEntryQuery { + _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 *LedgerEntryQuery) Unique(unique bool) *LedgerEntryQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *LedgerEntryQuery) Order(o ...ledgerentry.OrderOption) *LedgerEntryQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryTransaction chains the current query on the "transaction" edge. +func (_q *LedgerEntryQuery) QueryTransaction() *LedgerTransactionQuery { + query := (&LedgerTransactionClient{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(ledgerentry.Table, ledgerentry.FieldID, selector), + sqlgraph.To(ledgertransaction.Table, ledgertransaction.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerentry.TransactionTable, ledgerentry.TransactionColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySubAccount chains the current query on the "sub_account" edge. +func (_q *LedgerEntryQuery) QuerySubAccount() *LedgerSubAccountQuery { + query := (&LedgerSubAccountClient{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(ledgerentry.Table, ledgerentry.FieldID, selector), + sqlgraph.To(ledgersubaccount.Table, ledgersubaccount.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgerentry.SubAccountTable, ledgerentry.SubAccountColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySourceBreakageRecords chains the current query on the "source_breakage_records" edge. +func (_q *LedgerEntryQuery) QuerySourceBreakageRecords() *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{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(ledgerentry.Table, ledgerentry.FieldID, selector), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgerentry.SourceBreakageRecordsTable, ledgerentry.SourceBreakageRecordsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first LedgerEntry entity from the query. +// Returns a *NotFoundError when no LedgerEntry was found. +func (_q *LedgerEntryQuery) First(ctx context.Context) (*LedgerEntry, 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{ledgerentry.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *LedgerEntryQuery) FirstX(ctx context.Context) *LedgerEntry { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LedgerEntry ID from the query. +// Returns a *NotFoundError when no LedgerEntry ID was found. +func (_q *LedgerEntryQuery) 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{ledgerentry.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *LedgerEntryQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LedgerEntry entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one LedgerEntry entity is found. +// Returns a *NotFoundError when no LedgerEntry entities are found. +func (_q *LedgerEntryQuery) Only(ctx context.Context) (*LedgerEntry, 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{ledgerentry.Label} + default: + return nil, &NotSingularError{ledgerentry.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *LedgerEntryQuery) OnlyX(ctx context.Context) *LedgerEntry { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LedgerEntry ID in the query. +// Returns a *NotSingularError when more than one LedgerEntry ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *LedgerEntryQuery) 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{ledgerentry.Label} + default: + err = &NotSingularError{ledgerentry.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *LedgerEntryQuery) 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 LedgerEntries. +func (_q *LedgerEntryQuery) All(ctx context.Context) ([]*LedgerEntry, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*LedgerEntry, *LedgerEntryQuery]() + return withInterceptors[[]*LedgerEntry](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *LedgerEntryQuery) AllX(ctx context.Context) []*LedgerEntry { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LedgerEntry IDs. +func (_q *LedgerEntryQuery) 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(ledgerentry.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *LedgerEntryQuery) 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 *LedgerEntryQuery) 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[*LedgerEntryQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *LedgerEntryQuery) 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 *LedgerEntryQuery) 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 *LedgerEntryQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LedgerEntryQuery 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 *LedgerEntryQuery) Clone() *LedgerEntryQuery { + if _q == nil { + return nil + } + return &LedgerEntryQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]ledgerentry.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.LedgerEntry{}, _q.predicates...), + withTransaction: _q.withTransaction.Clone(), + withSubAccount: _q.withSubAccount.Clone(), + withSourceBreakageRecords: _q.withSourceBreakageRecords.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithTransaction tells the query-builder to eager-load the nodes that are connected to +// the "transaction" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerEntryQuery) WithTransaction(opts ...func(*LedgerTransactionQuery)) *LedgerEntryQuery { + query := (&LedgerTransactionClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withTransaction = query + return _q +} + +// WithSubAccount tells the query-builder to eager-load the nodes that are connected to +// the "sub_account" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerEntryQuery) WithSubAccount(opts ...func(*LedgerSubAccountQuery)) *LedgerEntryQuery { + query := (&LedgerSubAccountClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSubAccount = query + return _q +} + +// WithSourceBreakageRecords tells the query-builder to eager-load the nodes that are connected to +// the "source_breakage_records" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerEntryQuery) WithSourceBreakageRecords(opts ...func(*LedgerBreakageRecordQuery)) *LedgerEntryQuery { + query := (&LedgerBreakageRecordClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSourceBreakageRecords = 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.LedgerEntry.Query(). +// GroupBy(ledgerentry.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *LedgerEntryQuery) GroupBy(field string, fields ...string) *LedgerEntryGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &LedgerEntryGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = ledgerentry.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.LedgerEntry.Query(). +// Select(ledgerentry.FieldNamespace). +// Scan(ctx, &v) +func (_q *LedgerEntryQuery) Select(fields ...string) *LedgerEntrySelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &LedgerEntrySelect{LedgerEntryQuery: _q} + sbuild.label = ledgerentry.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a LedgerEntrySelect configured with the given aggregations. +func (_q *LedgerEntryQuery) Aggregate(fns ...AggregateFunc) *LedgerEntrySelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *LedgerEntryQuery) 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 !ledgerentry.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 *LedgerEntryQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*LedgerEntry, error) { + var ( + nodes = []*LedgerEntry{} + _spec = _q.querySpec() + loadedTypes = [3]bool{ + _q.withTransaction != nil, + _q.withSubAccount != nil, + _q.withSourceBreakageRecords != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*LedgerEntry).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &LedgerEntry{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.withTransaction; query != nil { + if err := _q.loadTransaction(ctx, query, nodes, nil, + func(n *LedgerEntry, e *LedgerTransaction) { n.Edges.Transaction = e }); err != nil { + return nil, err + } + } + if query := _q.withSubAccount; query != nil { + if err := _q.loadSubAccount(ctx, query, nodes, nil, + func(n *LedgerEntry, e *LedgerSubAccount) { n.Edges.SubAccount = e }); err != nil { + return nil, err + } + } + if query := _q.withSourceBreakageRecords; query != nil { + if err := _q.loadSourceBreakageRecords(ctx, query, nodes, + func(n *LedgerEntry) { n.Edges.SourceBreakageRecords = []*LedgerBreakageRecord{} }, + func(n *LedgerEntry, e *LedgerBreakageRecord) { + n.Edges.SourceBreakageRecords = append(n.Edges.SourceBreakageRecords, e) + }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *LedgerEntryQuery) loadTransaction(ctx context.Context, query *LedgerTransactionQuery, nodes []*LedgerEntry, init func(*LedgerEntry), assign func(*LedgerEntry, *LedgerTransaction)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*LedgerEntry) + for i := range nodes { + fk := nodes[i].TransactionID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(ledgertransaction.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 "transaction_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *LedgerEntryQuery) loadSubAccount(ctx context.Context, query *LedgerSubAccountQuery, nodes []*LedgerEntry, init func(*LedgerEntry), assign func(*LedgerEntry, *LedgerSubAccount)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*LedgerEntry) + for i := range nodes { + fk := nodes[i].SubAccountID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(ledgersubaccount.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 "sub_account_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *LedgerEntryQuery) loadSourceBreakageRecords(ctx context.Context, query *LedgerBreakageRecordQuery, nodes []*LedgerEntry, init func(*LedgerEntry), assign func(*LedgerEntry, *LedgerBreakageRecord)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*LedgerEntry) + 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(ledgerbreakagerecord.FieldSourceEntryID) + } + query.Where(predicate.LedgerBreakageRecord(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(ledgerentry.SourceBreakageRecordsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.SourceEntryID + if fk == nil { + return fmt.Errorf(`foreign-key "source_entry_id" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "source_entry_id" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *LedgerEntryQuery) 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 *LedgerEntryQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(ledgerentry.Table, ledgerentry.Columns, sqlgraph.NewFieldSpec(ledgerentry.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, ledgerentry.FieldID) + for i := range fields { + if fields[i] != ledgerentry.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withTransaction != nil { + _spec.Node.AddColumnOnce(ledgerentry.FieldTransactionID) + } + if _q.withSubAccount != nil { + _spec.Node.AddColumnOnce(ledgerentry.FieldSubAccountID) + } + } + 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 *LedgerEntryQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(ledgerentry.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = ledgerentry.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 *LedgerEntryQuery) ForUpdate(opts ...sql.LockOption) *LedgerEntryQuery { + 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 *LedgerEntryQuery) ForShare(opts ...sql.LockOption) *LedgerEntryQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// LedgerEntryGroupBy is the group-by builder for LedgerEntry entities. +type LedgerEntryGroupBy struct { + selector + build *LedgerEntryQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *LedgerEntryGroupBy) Aggregate(fns ...AggregateFunc) *LedgerEntryGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *LedgerEntryGroupBy) 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[*LedgerEntryQuery, *LedgerEntryGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *LedgerEntryGroupBy) sqlScan(ctx context.Context, root *LedgerEntryQuery, 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) +} + +// LedgerEntrySelect is the builder for selecting fields of LedgerEntry entities. +type LedgerEntrySelect struct { + *LedgerEntryQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *LedgerEntrySelect) Aggregate(fns ...AggregateFunc) *LedgerEntrySelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *LedgerEntrySelect) 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[*LedgerEntryQuery, *LedgerEntrySelect](ctx, _s.LedgerEntryQuery, _s, _s.inters, v) +} + +func (_s *LedgerEntrySelect) sqlScan(ctx context.Context, root *LedgerEntryQuery, 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/ent/db/ledgerentry_update.go b/ent/db/ledgerentry_update.go new file mode 100644 index 0000000000000000000000000000000000000000..ccf638ff6bea718c1303ae6eb52daffc63e39840 --- /dev/null +++ b/ent/db/ledgerentry_update.go @@ -0,0 +1,504 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/ledgerbreakagerecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgerentry" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerEntryUpdate is the builder for updating LedgerEntry entities. +type LedgerEntryUpdate struct { + config + hooks []Hook + mutation *LedgerEntryMutation +} + +// Where appends a list predicates to the LedgerEntryUpdate builder. +func (_u *LedgerEntryUpdate) Where(ps ...predicate.LedgerEntry) *LedgerEntryUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *LedgerEntryUpdate) SetAnnotations(v models.Annotations) *LedgerEntryUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *LedgerEntryUpdate) ClearAnnotations() *LedgerEntryUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *LedgerEntryUpdate) SetUpdatedAt(v time.Time) *LedgerEntryUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *LedgerEntryUpdate) SetDeletedAt(v time.Time) *LedgerEntryUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *LedgerEntryUpdate) SetNillableDeletedAt(v *time.Time) *LedgerEntryUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *LedgerEntryUpdate) ClearDeletedAt() *LedgerEntryUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// AddSourceBreakageRecordIDs adds the "source_breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_u *LedgerEntryUpdate) AddSourceBreakageRecordIDs(ids ...string) *LedgerEntryUpdate { + _u.mutation.AddSourceBreakageRecordIDs(ids...) + return _u +} + +// AddSourceBreakageRecords adds the "source_breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerEntryUpdate) AddSourceBreakageRecords(v ...*LedgerBreakageRecord) *LedgerEntryUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSourceBreakageRecordIDs(ids...) +} + +// Mutation returns the LedgerEntryMutation object of the builder. +func (_u *LedgerEntryUpdate) Mutation() *LedgerEntryMutation { + return _u.mutation +} + +// ClearSourceBreakageRecords clears all "source_breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerEntryUpdate) ClearSourceBreakageRecords() *LedgerEntryUpdate { + _u.mutation.ClearSourceBreakageRecords() + return _u +} + +// RemoveSourceBreakageRecordIDs removes the "source_breakage_records" edge to LedgerBreakageRecord entities by IDs. +func (_u *LedgerEntryUpdate) RemoveSourceBreakageRecordIDs(ids ...string) *LedgerEntryUpdate { + _u.mutation.RemoveSourceBreakageRecordIDs(ids...) + return _u +} + +// RemoveSourceBreakageRecords removes "source_breakage_records" edges to LedgerBreakageRecord entities. +func (_u *LedgerEntryUpdate) RemoveSourceBreakageRecords(v ...*LedgerBreakageRecord) *LedgerEntryUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSourceBreakageRecordIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *LedgerEntryUpdate) 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 *LedgerEntryUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *LedgerEntryUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LedgerEntryUpdate) 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 *LedgerEntryUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := ledgerentry.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *LedgerEntryUpdate) check() error { + if _u.mutation.TransactionCleared() && len(_u.mutation.TransactionIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerEntry.transaction"`) + } + if _u.mutation.SubAccountCleared() && len(_u.mutation.SubAccountIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerEntry.sub_account"`) + } + return nil +} + +func (_u *LedgerEntryUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(ledgerentry.Table, ledgerentry.Columns, sqlgraph.NewFieldSpec(ledgerentry.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.Annotations(); ok { + _spec.SetField(ledgerentry.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(ledgerentry.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(ledgerentry.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(ledgerentry.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(ledgerentry.FieldDeletedAt, field.TypeTime) + } + if _u.mutation.SourceChargeIDCleared() { + _spec.ClearField(ledgerentry.FieldSourceChargeID, field.TypeString) + } + if _u.mutation.SpendChargeIDCleared() { + _spec.ClearField(ledgerentry.FieldSpendChargeID, field.TypeString) + } + if _u.mutation.SourceBreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerentry.SourceBreakageRecordsTable, + Columns: []string{ledgerentry.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSourceBreakageRecordsIDs(); len(nodes) > 0 && !_u.mutation.SourceBreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerentry.SourceBreakageRecordsTable, + Columns: []string{ledgerentry.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.SourceBreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerentry.SourceBreakageRecordsTable, + Columns: []string{ledgerentry.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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{ledgerentry.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// LedgerEntryUpdateOne is the builder for updating a single LedgerEntry entity. +type LedgerEntryUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LedgerEntryMutation +} + +// SetAnnotations sets the "annotations" field. +func (_u *LedgerEntryUpdateOne) SetAnnotations(v models.Annotations) *LedgerEntryUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *LedgerEntryUpdateOne) ClearAnnotations() *LedgerEntryUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *LedgerEntryUpdateOne) SetUpdatedAt(v time.Time) *LedgerEntryUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *LedgerEntryUpdateOne) SetDeletedAt(v time.Time) *LedgerEntryUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *LedgerEntryUpdateOne) SetNillableDeletedAt(v *time.Time) *LedgerEntryUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *LedgerEntryUpdateOne) ClearDeletedAt() *LedgerEntryUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// AddSourceBreakageRecordIDs adds the "source_breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_u *LedgerEntryUpdateOne) AddSourceBreakageRecordIDs(ids ...string) *LedgerEntryUpdateOne { + _u.mutation.AddSourceBreakageRecordIDs(ids...) + return _u +} + +// AddSourceBreakageRecords adds the "source_breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerEntryUpdateOne) AddSourceBreakageRecords(v ...*LedgerBreakageRecord) *LedgerEntryUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSourceBreakageRecordIDs(ids...) +} + +// Mutation returns the LedgerEntryMutation object of the builder. +func (_u *LedgerEntryUpdateOne) Mutation() *LedgerEntryMutation { + return _u.mutation +} + +// ClearSourceBreakageRecords clears all "source_breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerEntryUpdateOne) ClearSourceBreakageRecords() *LedgerEntryUpdateOne { + _u.mutation.ClearSourceBreakageRecords() + return _u +} + +// RemoveSourceBreakageRecordIDs removes the "source_breakage_records" edge to LedgerBreakageRecord entities by IDs. +func (_u *LedgerEntryUpdateOne) RemoveSourceBreakageRecordIDs(ids ...string) *LedgerEntryUpdateOne { + _u.mutation.RemoveSourceBreakageRecordIDs(ids...) + return _u +} + +// RemoveSourceBreakageRecords removes "source_breakage_records" edges to LedgerBreakageRecord entities. +func (_u *LedgerEntryUpdateOne) RemoveSourceBreakageRecords(v ...*LedgerBreakageRecord) *LedgerEntryUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSourceBreakageRecordIDs(ids...) +} + +// Where appends a list predicates to the LedgerEntryUpdate builder. +func (_u *LedgerEntryUpdateOne) Where(ps ...predicate.LedgerEntry) *LedgerEntryUpdateOne { + _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 *LedgerEntryUpdateOne) Select(field string, fields ...string) *LedgerEntryUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated LedgerEntry entity. +func (_u *LedgerEntryUpdateOne) Save(ctx context.Context) (*LedgerEntry, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *LedgerEntryUpdateOne) SaveX(ctx context.Context) *LedgerEntry { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *LedgerEntryUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LedgerEntryUpdateOne) 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 *LedgerEntryUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := ledgerentry.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *LedgerEntryUpdateOne) check() error { + if _u.mutation.TransactionCleared() && len(_u.mutation.TransactionIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerEntry.transaction"`) + } + if _u.mutation.SubAccountCleared() && len(_u.mutation.SubAccountIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerEntry.sub_account"`) + } + return nil +} + +func (_u *LedgerEntryUpdateOne) sqlSave(ctx context.Context) (_node *LedgerEntry, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(ledgerentry.Table, ledgerentry.Columns, sqlgraph.NewFieldSpec(ledgerentry.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "LedgerEntry.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, ledgerentry.FieldID) + for _, f := range fields { + if !ledgerentry.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != ledgerentry.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.Annotations(); ok { + _spec.SetField(ledgerentry.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(ledgerentry.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(ledgerentry.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(ledgerentry.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(ledgerentry.FieldDeletedAt, field.TypeTime) + } + if _u.mutation.SourceChargeIDCleared() { + _spec.ClearField(ledgerentry.FieldSourceChargeID, field.TypeString) + } + if _u.mutation.SpendChargeIDCleared() { + _spec.ClearField(ledgerentry.FieldSpendChargeID, field.TypeString) + } + if _u.mutation.SourceBreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerentry.SourceBreakageRecordsTable, + Columns: []string{ledgerentry.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSourceBreakageRecordsIDs(); len(nodes) > 0 && !_u.mutation.SourceBreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerentry.SourceBreakageRecordsTable, + Columns: []string{ledgerentry.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.SourceBreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgerentry.SourceBreakageRecordsTable, + Columns: []string{ledgerentry.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &LedgerEntry{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{ledgerentry.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/ent/db/ledgersubaccount.go b/ent/db/ledgersubaccount.go new file mode 100644 index 0000000000000000000000000000000000000000..c35485b918c9df957d7904312722753875f3355f --- /dev/null +++ b/ent/db/ledgersubaccount.go @@ -0,0 +1,275 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/ledgeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccountroute" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerSubAccount is the model entity for the LedgerSubAccount schema. +type LedgerSubAccount 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"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,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"` + // AccountID holds the value of the "account_id" field. + AccountID string `json:"account_id,omitempty"` + // RouteID holds the value of the "route_id" field. + RouteID string `json:"route_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the LedgerSubAccountQuery when eager-loading is set. + Edges LedgerSubAccountEdges `json:"edges"` + selectValues sql.SelectValues +} + +// LedgerSubAccountEdges holds the relations/edges for other nodes in the graph. +type LedgerSubAccountEdges struct { + // Account holds the value of the account edge. + Account *LedgerAccount `json:"account,omitempty"` + // Route holds the value of the route edge. + Route *LedgerSubAccountRoute `json:"route,omitempty"` + // Entries holds the value of the entries edge. + Entries []*LedgerEntry `json:"entries,omitempty"` + // FboBreakageRecords holds the value of the fbo_breakage_records edge. + FboBreakageRecords []*LedgerBreakageRecord `json:"fbo_breakage_records,omitempty"` + // BreakageRecords holds the value of the breakage_records edge. + BreakageRecords []*LedgerBreakageRecord `json:"breakage_records,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [5]bool +} + +// AccountOrErr returns the Account value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e LedgerSubAccountEdges) AccountOrErr() (*LedgerAccount, error) { + if e.Account != nil { + return e.Account, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: ledgeraccount.Label} + } + return nil, &NotLoadedError{edge: "account"} +} + +// RouteOrErr returns the Route value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e LedgerSubAccountEdges) RouteOrErr() (*LedgerSubAccountRoute, error) { + if e.Route != nil { + return e.Route, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: ledgersubaccountroute.Label} + } + return nil, &NotLoadedError{edge: "route"} +} + +// EntriesOrErr returns the Entries value or an error if the edge +// was not loaded in eager-loading. +func (e LedgerSubAccountEdges) EntriesOrErr() ([]*LedgerEntry, error) { + if e.loadedTypes[2] { + return e.Entries, nil + } + return nil, &NotLoadedError{edge: "entries"} +} + +// FboBreakageRecordsOrErr returns the FboBreakageRecords value or an error if the edge +// was not loaded in eager-loading. +func (e LedgerSubAccountEdges) FboBreakageRecordsOrErr() ([]*LedgerBreakageRecord, error) { + if e.loadedTypes[3] { + return e.FboBreakageRecords, nil + } + return nil, &NotLoadedError{edge: "fbo_breakage_records"} +} + +// BreakageRecordsOrErr returns the BreakageRecords value or an error if the edge +// was not loaded in eager-loading. +func (e LedgerSubAccountEdges) BreakageRecordsOrErr() ([]*LedgerBreakageRecord, error) { + if e.loadedTypes[4] { + return e.BreakageRecords, nil + } + return nil, &NotLoadedError{edge: "breakage_records"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LedgerSubAccount) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case ledgersubaccount.FieldAnnotations: + values[i] = new([]byte) + case ledgersubaccount.FieldID, ledgersubaccount.FieldNamespace, ledgersubaccount.FieldAccountID, ledgersubaccount.FieldRouteID: + values[i] = new(sql.NullString) + case ledgersubaccount.FieldCreatedAt, ledgersubaccount.FieldUpdatedAt, ledgersubaccount.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 LedgerSubAccount fields. +func (_m *LedgerSubAccount) 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 ledgersubaccount.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 ledgersubaccount.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 ledgersubaccount.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 ledgersubaccount.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 ledgersubaccount.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 ledgersubaccount.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 ledgersubaccount.FieldAccountID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field account_id", values[i]) + } else if value.Valid { + _m.AccountID = value.String + } + case ledgersubaccount.FieldRouteID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field route_id", values[i]) + } else if value.Valid { + _m.RouteID = 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 LedgerSubAccount. +// This includes values selected through modifiers, order, etc. +func (_m *LedgerSubAccount) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryAccount queries the "account" edge of the LedgerSubAccount entity. +func (_m *LedgerSubAccount) QueryAccount() *LedgerAccountQuery { + return NewLedgerSubAccountClient(_m.config).QueryAccount(_m) +} + +// QueryRoute queries the "route" edge of the LedgerSubAccount entity. +func (_m *LedgerSubAccount) QueryRoute() *LedgerSubAccountRouteQuery { + return NewLedgerSubAccountClient(_m.config).QueryRoute(_m) +} + +// QueryEntries queries the "entries" edge of the LedgerSubAccount entity. +func (_m *LedgerSubAccount) QueryEntries() *LedgerEntryQuery { + return NewLedgerSubAccountClient(_m.config).QueryEntries(_m) +} + +// QueryFboBreakageRecords queries the "fbo_breakage_records" edge of the LedgerSubAccount entity. +func (_m *LedgerSubAccount) QueryFboBreakageRecords() *LedgerBreakageRecordQuery { + return NewLedgerSubAccountClient(_m.config).QueryFboBreakageRecords(_m) +} + +// QueryBreakageRecords queries the "breakage_records" edge of the LedgerSubAccount entity. +func (_m *LedgerSubAccount) QueryBreakageRecords() *LedgerBreakageRecordQuery { + return NewLedgerSubAccountClient(_m.config).QueryBreakageRecords(_m) +} + +// Update returns a builder for updating this LedgerSubAccount. +// Note that you need to call LedgerSubAccount.Unwrap() before calling this method if this LedgerSubAccount +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *LedgerSubAccount) Update() *LedgerSubAccountUpdateOne { + return NewLedgerSubAccountClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the LedgerSubAccount 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 *LedgerSubAccount) Unwrap() *LedgerSubAccount { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: LedgerSubAccount is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *LedgerSubAccount) String() string { + var builder strings.Builder + builder.WriteString("LedgerSubAccount(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + 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("account_id=") + builder.WriteString(_m.AccountID) + builder.WriteString(", ") + builder.WriteString("route_id=") + builder.WriteString(_m.RouteID) + builder.WriteByte(')') + return builder.String() +} + +// LedgerSubAccounts is a parsable slice of LedgerSubAccount. +type LedgerSubAccounts []*LedgerSubAccount diff --git a/ent/db/ledgersubaccount/ledgersubaccount.go b/ent/db/ledgersubaccount/ledgersubaccount.go new file mode 100644 index 0000000000000000000000000000000000000000..40a694eb697d8c3d7438c2d2825dbe22b11c0717 --- /dev/null +++ b/ent/db/ledgersubaccount/ledgersubaccount.go @@ -0,0 +1,242 @@ +// Code generated by ent, DO NOT EDIT. + +package ledgersubaccount + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the ledgersubaccount type in the database. + Label = "ledger_sub_account" + // 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" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // 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" + // FieldAccountID holds the string denoting the account_id field in the database. + FieldAccountID = "account_id" + // FieldRouteID holds the string denoting the route_id field in the database. + FieldRouteID = "route_id" + // EdgeAccount holds the string denoting the account edge name in mutations. + EdgeAccount = "account" + // EdgeRoute holds the string denoting the route edge name in mutations. + EdgeRoute = "route" + // EdgeEntries holds the string denoting the entries edge name in mutations. + EdgeEntries = "entries" + // EdgeFboBreakageRecords holds the string denoting the fbo_breakage_records edge name in mutations. + EdgeFboBreakageRecords = "fbo_breakage_records" + // EdgeBreakageRecords holds the string denoting the breakage_records edge name in mutations. + EdgeBreakageRecords = "breakage_records" + // Table holds the table name of the ledgersubaccount in the database. + Table = "ledger_sub_accounts" + // AccountTable is the table that holds the account relation/edge. + AccountTable = "ledger_sub_accounts" + // AccountInverseTable is the table name for the LedgerAccount entity. + // It exists in this package in order to avoid circular dependency with the "ledgeraccount" package. + AccountInverseTable = "ledger_accounts" + // AccountColumn is the table column denoting the account relation/edge. + AccountColumn = "account_id" + // RouteTable is the table that holds the route relation/edge. + RouteTable = "ledger_sub_accounts" + // RouteInverseTable is the table name for the LedgerSubAccountRoute entity. + // It exists in this package in order to avoid circular dependency with the "ledgersubaccountroute" package. + RouteInverseTable = "ledger_sub_account_routes" + // RouteColumn is the table column denoting the route relation/edge. + RouteColumn = "route_id" + // EntriesTable is the table that holds the entries relation/edge. + EntriesTable = "ledger_entries" + // EntriesInverseTable is the table name for the LedgerEntry entity. + // It exists in this package in order to avoid circular dependency with the "ledgerentry" package. + EntriesInverseTable = "ledger_entries" + // EntriesColumn is the table column denoting the entries relation/edge. + EntriesColumn = "sub_account_id" + // FboBreakageRecordsTable is the table that holds the fbo_breakage_records relation/edge. + FboBreakageRecordsTable = "ledger_breakage_records" + // FboBreakageRecordsInverseTable is the table name for the LedgerBreakageRecord entity. + // It exists in this package in order to avoid circular dependency with the "ledgerbreakagerecord" package. + FboBreakageRecordsInverseTable = "ledger_breakage_records" + // FboBreakageRecordsColumn is the table column denoting the fbo_breakage_records relation/edge. + FboBreakageRecordsColumn = "fbo_sub_account_id" + // BreakageRecordsTable is the table that holds the breakage_records relation/edge. + BreakageRecordsTable = "ledger_breakage_records" + // BreakageRecordsInverseTable is the table name for the LedgerBreakageRecord entity. + // It exists in this package in order to avoid circular dependency with the "ledgerbreakagerecord" package. + BreakageRecordsInverseTable = "ledger_breakage_records" + // BreakageRecordsColumn is the table column denoting the breakage_records relation/edge. + BreakageRecordsColumn = "breakage_sub_account_id" +) + +// Columns holds all SQL columns for ledgersubaccount fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldAnnotations, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldAccountID, + FieldRouteID, +} + +// 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 +) + +// OrderOption defines the ordering options for the LedgerSubAccount 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() +} + +// ByAccountID orders the results by the account_id field. +func ByAccountID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAccountID, opts...).ToFunc() +} + +// ByRouteID orders the results by the route_id field. +func ByRouteID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRouteID, opts...).ToFunc() +} + +// ByAccountField orders the results by account field. +func ByAccountField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newAccountStep(), sql.OrderByField(field, opts...)) + } +} + +// ByRouteField orders the results by route field. +func ByRouteField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newRouteStep(), sql.OrderByField(field, opts...)) + } +} + +// ByEntriesCount orders the results by entries count. +func ByEntriesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newEntriesStep(), opts...) + } +} + +// ByEntries orders the results by entries terms. +func ByEntries(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newEntriesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByFboBreakageRecordsCount orders the results by fbo_breakage_records count. +func ByFboBreakageRecordsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newFboBreakageRecordsStep(), opts...) + } +} + +// ByFboBreakageRecords orders the results by fbo_breakage_records terms. +func ByFboBreakageRecords(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newFboBreakageRecordsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByBreakageRecordsCount orders the results by breakage_records count. +func ByBreakageRecordsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newBreakageRecordsStep(), opts...) + } +} + +// ByBreakageRecords orders the results by breakage_records terms. +func ByBreakageRecords(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBreakageRecordsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newAccountStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(AccountInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, AccountTable, AccountColumn), + ) +} +func newRouteStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RouteInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, RouteTable, RouteColumn), + ) +} +func newEntriesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(EntriesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, EntriesTable, EntriesColumn), + ) +} +func newFboBreakageRecordsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(FboBreakageRecordsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, FboBreakageRecordsTable, FboBreakageRecordsColumn), + ) +} +func newBreakageRecordsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BreakageRecordsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, BreakageRecordsTable, BreakageRecordsColumn), + ) +} diff --git a/ent/db/ledgersubaccount/where.go b/ent/db/ledgersubaccount/where.go new file mode 100644 index 0000000000000000000000000000000000000000..c7b743d2d5c1dff4181d135a6531e99a29ea315c --- /dev/null +++ b/ent/db/ledgersubaccount/where.go @@ -0,0 +1,561 @@ +// Code generated by ent, DO NOT EDIT. + +package ledgersubaccount + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(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.LedgerSubAccount { + return predicate.LedgerSubAccount(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.LedgerSubAccount { + return predicate.LedgerSubAccount(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.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldEQ(FieldDeletedAt, v)) +} + +// AccountID applies equality check predicate on the "account_id" field. It's identical to AccountIDEQ. +func AccountID(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldEQ(FieldAccountID, v)) +} + +// RouteID applies equality check predicate on the "route_id" field. It's identical to RouteIDEQ. +func RouteID(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldEQ(FieldRouteID, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldContainsFold(FieldNamespace, v)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldNotNull(FieldAnnotations)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldNotNull(FieldDeletedAt)) +} + +// AccountIDEQ applies the EQ predicate on the "account_id" field. +func AccountIDEQ(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldEQ(FieldAccountID, v)) +} + +// AccountIDNEQ applies the NEQ predicate on the "account_id" field. +func AccountIDNEQ(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldNEQ(FieldAccountID, v)) +} + +// AccountIDIn applies the In predicate on the "account_id" field. +func AccountIDIn(vs ...string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldIn(FieldAccountID, vs...)) +} + +// AccountIDNotIn applies the NotIn predicate on the "account_id" field. +func AccountIDNotIn(vs ...string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldNotIn(FieldAccountID, vs...)) +} + +// AccountIDGT applies the GT predicate on the "account_id" field. +func AccountIDGT(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldGT(FieldAccountID, v)) +} + +// AccountIDGTE applies the GTE predicate on the "account_id" field. +func AccountIDGTE(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldGTE(FieldAccountID, v)) +} + +// AccountIDLT applies the LT predicate on the "account_id" field. +func AccountIDLT(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldLT(FieldAccountID, v)) +} + +// AccountIDLTE applies the LTE predicate on the "account_id" field. +func AccountIDLTE(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldLTE(FieldAccountID, v)) +} + +// AccountIDContains applies the Contains predicate on the "account_id" field. +func AccountIDContains(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldContains(FieldAccountID, v)) +} + +// AccountIDHasPrefix applies the HasPrefix predicate on the "account_id" field. +func AccountIDHasPrefix(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldHasPrefix(FieldAccountID, v)) +} + +// AccountIDHasSuffix applies the HasSuffix predicate on the "account_id" field. +func AccountIDHasSuffix(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldHasSuffix(FieldAccountID, v)) +} + +// AccountIDEqualFold applies the EqualFold predicate on the "account_id" field. +func AccountIDEqualFold(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldEqualFold(FieldAccountID, v)) +} + +// AccountIDContainsFold applies the ContainsFold predicate on the "account_id" field. +func AccountIDContainsFold(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldContainsFold(FieldAccountID, v)) +} + +// RouteIDEQ applies the EQ predicate on the "route_id" field. +func RouteIDEQ(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldEQ(FieldRouteID, v)) +} + +// RouteIDNEQ applies the NEQ predicate on the "route_id" field. +func RouteIDNEQ(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldNEQ(FieldRouteID, v)) +} + +// RouteIDIn applies the In predicate on the "route_id" field. +func RouteIDIn(vs ...string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldIn(FieldRouteID, vs...)) +} + +// RouteIDNotIn applies the NotIn predicate on the "route_id" field. +func RouteIDNotIn(vs ...string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldNotIn(FieldRouteID, vs...)) +} + +// RouteIDGT applies the GT predicate on the "route_id" field. +func RouteIDGT(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldGT(FieldRouteID, v)) +} + +// RouteIDGTE applies the GTE predicate on the "route_id" field. +func RouteIDGTE(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldGTE(FieldRouteID, v)) +} + +// RouteIDLT applies the LT predicate on the "route_id" field. +func RouteIDLT(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldLT(FieldRouteID, v)) +} + +// RouteIDLTE applies the LTE predicate on the "route_id" field. +func RouteIDLTE(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldLTE(FieldRouteID, v)) +} + +// RouteIDContains applies the Contains predicate on the "route_id" field. +func RouteIDContains(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldContains(FieldRouteID, v)) +} + +// RouteIDHasPrefix applies the HasPrefix predicate on the "route_id" field. +func RouteIDHasPrefix(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldHasPrefix(FieldRouteID, v)) +} + +// RouteIDHasSuffix applies the HasSuffix predicate on the "route_id" field. +func RouteIDHasSuffix(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldHasSuffix(FieldRouteID, v)) +} + +// RouteIDEqualFold applies the EqualFold predicate on the "route_id" field. +func RouteIDEqualFold(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldEqualFold(FieldRouteID, v)) +} + +// RouteIDContainsFold applies the ContainsFold predicate on the "route_id" field. +func RouteIDContainsFold(v string) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.FieldContainsFold(FieldRouteID, v)) +} + +// HasAccount applies the HasEdge predicate on the "account" edge. +func HasAccount() predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, AccountTable, AccountColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasAccountWith applies the HasEdge predicate on the "account" edge with a given conditions (other predicates). +func HasAccountWith(preds ...predicate.LedgerAccount) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(func(s *sql.Selector) { + step := newAccountStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasRoute applies the HasEdge predicate on the "route" edge. +func HasRoute() predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, RouteTable, RouteColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasRouteWith applies the HasEdge predicate on the "route" edge with a given conditions (other predicates). +func HasRouteWith(preds ...predicate.LedgerSubAccountRoute) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(func(s *sql.Selector) { + step := newRouteStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasEntries applies the HasEdge predicate on the "entries" edge. +func HasEntries() predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, EntriesTable, EntriesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasEntriesWith applies the HasEdge predicate on the "entries" edge with a given conditions (other predicates). +func HasEntriesWith(preds ...predicate.LedgerEntry) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(func(s *sql.Selector) { + step := newEntriesStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasFboBreakageRecords applies the HasEdge predicate on the "fbo_breakage_records" edge. +func HasFboBreakageRecords() predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, FboBreakageRecordsTable, FboBreakageRecordsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasFboBreakageRecordsWith applies the HasEdge predicate on the "fbo_breakage_records" edge with a given conditions (other predicates). +func HasFboBreakageRecordsWith(preds ...predicate.LedgerBreakageRecord) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(func(s *sql.Selector) { + step := newFboBreakageRecordsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasBreakageRecords applies the HasEdge predicate on the "breakage_records" edge. +func HasBreakageRecords() predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, BreakageRecordsTable, BreakageRecordsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBreakageRecordsWith applies the HasEdge predicate on the "breakage_records" edge with a given conditions (other predicates). +func HasBreakageRecordsWith(preds ...predicate.LedgerBreakageRecord) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(func(s *sql.Selector) { + step := newBreakageRecordsStep() + 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.LedgerSubAccount) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LedgerSubAccount) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LedgerSubAccount) predicate.LedgerSubAccount { + return predicate.LedgerSubAccount(sql.NotPredicates(p)) +} diff --git a/ent/db/ledgersubaccount_create.go b/ent/db/ledgersubaccount_create.go new file mode 100644 index 0000000000000000000000000000000000000000..90fd2b69cf591d1307850aa9cb17f11883168b95 --- /dev/null +++ b/ent/db/ledgersubaccount_create.go @@ -0,0 +1,901 @@ +// 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/ledgeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgerbreakagerecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgerentry" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccountroute" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerSubAccountCreate is the builder for creating a LedgerSubAccount entity. +type LedgerSubAccountCreate struct { + config + mutation *LedgerSubAccountMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *LedgerSubAccountCreate) SetNamespace(v string) *LedgerSubAccountCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *LedgerSubAccountCreate) SetAnnotations(v models.Annotations) *LedgerSubAccountCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *LedgerSubAccountCreate) SetCreatedAt(v time.Time) *LedgerSubAccountCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *LedgerSubAccountCreate) SetNillableCreatedAt(v *time.Time) *LedgerSubAccountCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *LedgerSubAccountCreate) SetUpdatedAt(v time.Time) *LedgerSubAccountCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *LedgerSubAccountCreate) SetNillableUpdatedAt(v *time.Time) *LedgerSubAccountCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *LedgerSubAccountCreate) SetDeletedAt(v time.Time) *LedgerSubAccountCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *LedgerSubAccountCreate) SetNillableDeletedAt(v *time.Time) *LedgerSubAccountCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetAccountID sets the "account_id" field. +func (_c *LedgerSubAccountCreate) SetAccountID(v string) *LedgerSubAccountCreate { + _c.mutation.SetAccountID(v) + return _c +} + +// SetRouteID sets the "route_id" field. +func (_c *LedgerSubAccountCreate) SetRouteID(v string) *LedgerSubAccountCreate { + _c.mutation.SetRouteID(v) + return _c +} + +// SetID sets the "id" field. +func (_c *LedgerSubAccountCreate) SetID(v string) *LedgerSubAccountCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *LedgerSubAccountCreate) SetNillableID(v *string) *LedgerSubAccountCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetAccount sets the "account" edge to the LedgerAccount entity. +func (_c *LedgerSubAccountCreate) SetAccount(v *LedgerAccount) *LedgerSubAccountCreate { + return _c.SetAccountID(v.ID) +} + +// SetRoute sets the "route" edge to the LedgerSubAccountRoute entity. +func (_c *LedgerSubAccountCreate) SetRoute(v *LedgerSubAccountRoute) *LedgerSubAccountCreate { + return _c.SetRouteID(v.ID) +} + +// AddEntryIDs adds the "entries" edge to the LedgerEntry entity by IDs. +func (_c *LedgerSubAccountCreate) AddEntryIDs(ids ...string) *LedgerSubAccountCreate { + _c.mutation.AddEntryIDs(ids...) + return _c +} + +// AddEntries adds the "entries" edges to the LedgerEntry entity. +func (_c *LedgerSubAccountCreate) AddEntries(v ...*LedgerEntry) *LedgerSubAccountCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddEntryIDs(ids...) +} + +// AddFboBreakageRecordIDs adds the "fbo_breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_c *LedgerSubAccountCreate) AddFboBreakageRecordIDs(ids ...string) *LedgerSubAccountCreate { + _c.mutation.AddFboBreakageRecordIDs(ids...) + return _c +} + +// AddFboBreakageRecords adds the "fbo_breakage_records" edges to the LedgerBreakageRecord entity. +func (_c *LedgerSubAccountCreate) AddFboBreakageRecords(v ...*LedgerBreakageRecord) *LedgerSubAccountCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddFboBreakageRecordIDs(ids...) +} + +// AddBreakageRecordIDs adds the "breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_c *LedgerSubAccountCreate) AddBreakageRecordIDs(ids ...string) *LedgerSubAccountCreate { + _c.mutation.AddBreakageRecordIDs(ids...) + return _c +} + +// AddBreakageRecords adds the "breakage_records" edges to the LedgerBreakageRecord entity. +func (_c *LedgerSubAccountCreate) AddBreakageRecords(v ...*LedgerBreakageRecord) *LedgerSubAccountCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddBreakageRecordIDs(ids...) +} + +// Mutation returns the LedgerSubAccountMutation object of the builder. +func (_c *LedgerSubAccountCreate) Mutation() *LedgerSubAccountMutation { + return _c.mutation +} + +// Save creates the LedgerSubAccount in the database. +func (_c *LedgerSubAccountCreate) Save(ctx context.Context) (*LedgerSubAccount, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *LedgerSubAccountCreate) SaveX(ctx context.Context) *LedgerSubAccount { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LedgerSubAccountCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LedgerSubAccountCreate) 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 *LedgerSubAccountCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := ledgersubaccount.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := ledgersubaccount.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := ledgersubaccount.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *LedgerSubAccountCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "LedgerSubAccount.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := ledgersubaccount.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "LedgerSubAccount.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "LedgerSubAccount.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "LedgerSubAccount.updated_at"`)} + } + if _, ok := _c.mutation.AccountID(); !ok { + return &ValidationError{Name: "account_id", err: errors.New(`db: missing required field "LedgerSubAccount.account_id"`)} + } + if _, ok := _c.mutation.RouteID(); !ok { + return &ValidationError{Name: "route_id", err: errors.New(`db: missing required field "LedgerSubAccount.route_id"`)} + } + if len(_c.mutation.AccountIDs()) == 0 { + return &ValidationError{Name: "account", err: errors.New(`db: missing required edge "LedgerSubAccount.account"`)} + } + if len(_c.mutation.RouteIDs()) == 0 { + return &ValidationError{Name: "route", err: errors.New(`db: missing required edge "LedgerSubAccount.route"`)} + } + return nil +} + +func (_c *LedgerSubAccountCreate) sqlSave(ctx context.Context) (*LedgerSubAccount, 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 LedgerSubAccount.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *LedgerSubAccountCreate) createSpec() (*LedgerSubAccount, *sqlgraph.CreateSpec) { + var ( + _node = &LedgerSubAccount{config: _c.config} + _spec = sqlgraph.NewCreateSpec(ledgersubaccount.Table, sqlgraph.NewFieldSpec(ledgersubaccount.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(ledgersubaccount.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(ledgersubaccount.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(ledgersubaccount.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(ledgersubaccount.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(ledgersubaccount.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if nodes := _c.mutation.AccountIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: ledgersubaccount.AccountTable, + Columns: []string{ledgersubaccount.AccountColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgeraccount.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.AccountID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.RouteIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: ledgersubaccount.RouteTable, + Columns: []string{ledgersubaccount.RouteColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccountroute.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.RouteID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.EntriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.EntriesTable, + Columns: []string{ledgersubaccount.EntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerentry.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.FboBreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.FboBreakageRecordsTable, + Columns: []string{ledgersubaccount.FboBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.BreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.BreakageRecordsTable, + Columns: []string{ledgersubaccount.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.LedgerSubAccount.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.LedgerSubAccountUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *LedgerSubAccountCreate) OnConflict(opts ...sql.ConflictOption) *LedgerSubAccountUpsertOne { + _c.conflict = opts + return &LedgerSubAccountUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.LedgerSubAccount.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *LedgerSubAccountCreate) OnConflictColumns(columns ...string) *LedgerSubAccountUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &LedgerSubAccountUpsertOne{ + create: _c, + } +} + +type ( + // LedgerSubAccountUpsertOne is the builder for "upsert"-ing + // one LedgerSubAccount node. + LedgerSubAccountUpsertOne struct { + create *LedgerSubAccountCreate + } + + // LedgerSubAccountUpsert is the "OnConflict" setter. + LedgerSubAccountUpsert struct { + *sql.UpdateSet + } +) + +// SetAnnotations sets the "annotations" field. +func (u *LedgerSubAccountUpsert) SetAnnotations(v models.Annotations) *LedgerSubAccountUpsert { + u.Set(ledgersubaccount.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerSubAccountUpsert) UpdateAnnotations() *LedgerSubAccountUpsert { + u.SetExcluded(ledgersubaccount.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerSubAccountUpsert) ClearAnnotations() *LedgerSubAccountUpsert { + u.SetNull(ledgersubaccount.FieldAnnotations) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerSubAccountUpsert) SetUpdatedAt(v time.Time) *LedgerSubAccountUpsert { + u.Set(ledgersubaccount.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerSubAccountUpsert) UpdateUpdatedAt() *LedgerSubAccountUpsert { + u.SetExcluded(ledgersubaccount.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerSubAccountUpsert) SetDeletedAt(v time.Time) *LedgerSubAccountUpsert { + u.Set(ledgersubaccount.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerSubAccountUpsert) UpdateDeletedAt() *LedgerSubAccountUpsert { + u.SetExcluded(ledgersubaccount.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerSubAccountUpsert) ClearDeletedAt() *LedgerSubAccountUpsert { + u.SetNull(ledgersubaccount.FieldDeletedAt) + 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.LedgerSubAccount.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(ledgersubaccount.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LedgerSubAccountUpsertOne) UpdateNewValues() *LedgerSubAccountUpsertOne { + 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(ledgersubaccount.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(ledgersubaccount.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(ledgersubaccount.FieldCreatedAt) + } + if _, exists := u.create.mutation.AccountID(); exists { + s.SetIgnore(ledgersubaccount.FieldAccountID) + } + if _, exists := u.create.mutation.RouteID(); exists { + s.SetIgnore(ledgersubaccount.FieldRouteID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.LedgerSubAccount.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LedgerSubAccountUpsertOne) Ignore() *LedgerSubAccountUpsertOne { + 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 *LedgerSubAccountUpsertOne) DoNothing() *LedgerSubAccountUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LedgerSubAccountCreate.OnConflict +// documentation for more info. +func (u *LedgerSubAccountUpsertOne) Update(set func(*LedgerSubAccountUpsert)) *LedgerSubAccountUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LedgerSubAccountUpsert{UpdateSet: update}) + })) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *LedgerSubAccountUpsertOne) SetAnnotations(v models.Annotations) *LedgerSubAccountUpsertOne { + return u.Update(func(s *LedgerSubAccountUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerSubAccountUpsertOne) UpdateAnnotations() *LedgerSubAccountUpsertOne { + return u.Update(func(s *LedgerSubAccountUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerSubAccountUpsertOne) ClearAnnotations() *LedgerSubAccountUpsertOne { + return u.Update(func(s *LedgerSubAccountUpsert) { + s.ClearAnnotations() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerSubAccountUpsertOne) SetUpdatedAt(v time.Time) *LedgerSubAccountUpsertOne { + return u.Update(func(s *LedgerSubAccountUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerSubAccountUpsertOne) UpdateUpdatedAt() *LedgerSubAccountUpsertOne { + return u.Update(func(s *LedgerSubAccountUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerSubAccountUpsertOne) SetDeletedAt(v time.Time) *LedgerSubAccountUpsertOne { + return u.Update(func(s *LedgerSubAccountUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerSubAccountUpsertOne) UpdateDeletedAt() *LedgerSubAccountUpsertOne { + return u.Update(func(s *LedgerSubAccountUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerSubAccountUpsertOne) ClearDeletedAt() *LedgerSubAccountUpsertOne { + return u.Update(func(s *LedgerSubAccountUpsert) { + s.ClearDeletedAt() + }) +} + +// Exec executes the query. +func (u *LedgerSubAccountUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for LedgerSubAccountCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LedgerSubAccountUpsertOne) 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 *LedgerSubAccountUpsertOne) 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: LedgerSubAccountUpsertOne.ID is not supported by MySQL driver. Use LedgerSubAccountUpsertOne.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 *LedgerSubAccountUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// LedgerSubAccountCreateBulk is the builder for creating many LedgerSubAccount entities in bulk. +type LedgerSubAccountCreateBulk struct { + config + err error + builders []*LedgerSubAccountCreate + conflict []sql.ConflictOption +} + +// Save creates the LedgerSubAccount entities in the database. +func (_c *LedgerSubAccountCreateBulk) Save(ctx context.Context) ([]*LedgerSubAccount, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*LedgerSubAccount, 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.(*LedgerSubAccountMutation) + 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 *LedgerSubAccountCreateBulk) SaveX(ctx context.Context) []*LedgerSubAccount { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LedgerSubAccountCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LedgerSubAccountCreateBulk) 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.LedgerSubAccount.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.LedgerSubAccountUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *LedgerSubAccountCreateBulk) OnConflict(opts ...sql.ConflictOption) *LedgerSubAccountUpsertBulk { + _c.conflict = opts + return &LedgerSubAccountUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.LedgerSubAccount.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *LedgerSubAccountCreateBulk) OnConflictColumns(columns ...string) *LedgerSubAccountUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &LedgerSubAccountUpsertBulk{ + create: _c, + } +} + +// LedgerSubAccountUpsertBulk is the builder for "upsert"-ing +// a bulk of LedgerSubAccount nodes. +type LedgerSubAccountUpsertBulk struct { + create *LedgerSubAccountCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.LedgerSubAccount.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(ledgersubaccount.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LedgerSubAccountUpsertBulk) UpdateNewValues() *LedgerSubAccountUpsertBulk { + 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(ledgersubaccount.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(ledgersubaccount.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(ledgersubaccount.FieldCreatedAt) + } + if _, exists := b.mutation.AccountID(); exists { + s.SetIgnore(ledgersubaccount.FieldAccountID) + } + if _, exists := b.mutation.RouteID(); exists { + s.SetIgnore(ledgersubaccount.FieldRouteID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.LedgerSubAccount.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LedgerSubAccountUpsertBulk) Ignore() *LedgerSubAccountUpsertBulk { + 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 *LedgerSubAccountUpsertBulk) DoNothing() *LedgerSubAccountUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LedgerSubAccountCreateBulk.OnConflict +// documentation for more info. +func (u *LedgerSubAccountUpsertBulk) Update(set func(*LedgerSubAccountUpsert)) *LedgerSubAccountUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LedgerSubAccountUpsert{UpdateSet: update}) + })) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *LedgerSubAccountUpsertBulk) SetAnnotations(v models.Annotations) *LedgerSubAccountUpsertBulk { + return u.Update(func(s *LedgerSubAccountUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerSubAccountUpsertBulk) UpdateAnnotations() *LedgerSubAccountUpsertBulk { + return u.Update(func(s *LedgerSubAccountUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerSubAccountUpsertBulk) ClearAnnotations() *LedgerSubAccountUpsertBulk { + return u.Update(func(s *LedgerSubAccountUpsert) { + s.ClearAnnotations() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerSubAccountUpsertBulk) SetUpdatedAt(v time.Time) *LedgerSubAccountUpsertBulk { + return u.Update(func(s *LedgerSubAccountUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerSubAccountUpsertBulk) UpdateUpdatedAt() *LedgerSubAccountUpsertBulk { + return u.Update(func(s *LedgerSubAccountUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerSubAccountUpsertBulk) SetDeletedAt(v time.Time) *LedgerSubAccountUpsertBulk { + return u.Update(func(s *LedgerSubAccountUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerSubAccountUpsertBulk) UpdateDeletedAt() *LedgerSubAccountUpsertBulk { + return u.Update(func(s *LedgerSubAccountUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerSubAccountUpsertBulk) ClearDeletedAt() *LedgerSubAccountUpsertBulk { + return u.Update(func(s *LedgerSubAccountUpsert) { + s.ClearDeletedAt() + }) +} + +// Exec executes the query. +func (u *LedgerSubAccountUpsertBulk) 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 LedgerSubAccountCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for LedgerSubAccountCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LedgerSubAccountUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/ledgersubaccount_delete.go b/ent/db/ledgersubaccount_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..93960a20ff9d8e3470f8ffbb34df15a5dcc5746d --- /dev/null +++ b/ent/db/ledgersubaccount_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/ledgersubaccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LedgerSubAccountDelete is the builder for deleting a LedgerSubAccount entity. +type LedgerSubAccountDelete struct { + config + hooks []Hook + mutation *LedgerSubAccountMutation +} + +// Where appends a list predicates to the LedgerSubAccountDelete builder. +func (_d *LedgerSubAccountDelete) Where(ps ...predicate.LedgerSubAccount) *LedgerSubAccountDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *LedgerSubAccountDelete) 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 *LedgerSubAccountDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *LedgerSubAccountDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(ledgersubaccount.Table, sqlgraph.NewFieldSpec(ledgersubaccount.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 +} + +// LedgerSubAccountDeleteOne is the builder for deleting a single LedgerSubAccount entity. +type LedgerSubAccountDeleteOne struct { + _d *LedgerSubAccountDelete +} + +// Where appends a list predicates to the LedgerSubAccountDelete builder. +func (_d *LedgerSubAccountDeleteOne) Where(ps ...predicate.LedgerSubAccount) *LedgerSubAccountDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *LedgerSubAccountDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{ledgersubaccount.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *LedgerSubAccountDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/ledgersubaccount_query.go b/ent/db/ledgersubaccount_query.go new file mode 100644 index 0000000000000000000000000000000000000000..bee60d17141a2fd33b16314ffe4841449b087427 --- /dev/null +++ b/ent/db/ledgersubaccount_query.go @@ -0,0 +1,944 @@ +// 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/ledgeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgerbreakagerecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgerentry" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccountroute" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LedgerSubAccountQuery is the builder for querying LedgerSubAccount entities. +type LedgerSubAccountQuery struct { + config + ctx *QueryContext + order []ledgersubaccount.OrderOption + inters []Interceptor + predicates []predicate.LedgerSubAccount + withAccount *LedgerAccountQuery + withRoute *LedgerSubAccountRouteQuery + withEntries *LedgerEntryQuery + withFboBreakageRecords *LedgerBreakageRecordQuery + withBreakageRecords *LedgerBreakageRecordQuery + 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 LedgerSubAccountQuery builder. +func (_q *LedgerSubAccountQuery) Where(ps ...predicate.LedgerSubAccount) *LedgerSubAccountQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *LedgerSubAccountQuery) Limit(limit int) *LedgerSubAccountQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *LedgerSubAccountQuery) Offset(offset int) *LedgerSubAccountQuery { + _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 *LedgerSubAccountQuery) Unique(unique bool) *LedgerSubAccountQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *LedgerSubAccountQuery) Order(o ...ledgersubaccount.OrderOption) *LedgerSubAccountQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryAccount chains the current query on the "account" edge. +func (_q *LedgerSubAccountQuery) QueryAccount() *LedgerAccountQuery { + query := (&LedgerAccountClient{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(ledgersubaccount.Table, ledgersubaccount.FieldID, selector), + sqlgraph.To(ledgeraccount.Table, ledgeraccount.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgersubaccount.AccountTable, ledgersubaccount.AccountColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryRoute chains the current query on the "route" edge. +func (_q *LedgerSubAccountQuery) QueryRoute() *LedgerSubAccountRouteQuery { + query := (&LedgerSubAccountRouteClient{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(ledgersubaccount.Table, ledgersubaccount.FieldID, selector), + sqlgraph.To(ledgersubaccountroute.Table, ledgersubaccountroute.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgersubaccount.RouteTable, ledgersubaccount.RouteColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryEntries chains the current query on the "entries" edge. +func (_q *LedgerSubAccountQuery) QueryEntries() *LedgerEntryQuery { + query := (&LedgerEntryClient{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(ledgersubaccount.Table, ledgersubaccount.FieldID, selector), + sqlgraph.To(ledgerentry.Table, ledgerentry.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgersubaccount.EntriesTable, ledgersubaccount.EntriesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryFboBreakageRecords chains the current query on the "fbo_breakage_records" edge. +func (_q *LedgerSubAccountQuery) QueryFboBreakageRecords() *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{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(ledgersubaccount.Table, ledgersubaccount.FieldID, selector), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgersubaccount.FboBreakageRecordsTable, ledgersubaccount.FboBreakageRecordsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryBreakageRecords chains the current query on the "breakage_records" edge. +func (_q *LedgerSubAccountQuery) QueryBreakageRecords() *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{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(ledgersubaccount.Table, ledgersubaccount.FieldID, selector), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgersubaccount.BreakageRecordsTable, ledgersubaccount.BreakageRecordsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first LedgerSubAccount entity from the query. +// Returns a *NotFoundError when no LedgerSubAccount was found. +func (_q *LedgerSubAccountQuery) First(ctx context.Context) (*LedgerSubAccount, 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{ledgersubaccount.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *LedgerSubAccountQuery) FirstX(ctx context.Context) *LedgerSubAccount { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LedgerSubAccount ID from the query. +// Returns a *NotFoundError when no LedgerSubAccount ID was found. +func (_q *LedgerSubAccountQuery) 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{ledgersubaccount.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *LedgerSubAccountQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LedgerSubAccount entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one LedgerSubAccount entity is found. +// Returns a *NotFoundError when no LedgerSubAccount entities are found. +func (_q *LedgerSubAccountQuery) Only(ctx context.Context) (*LedgerSubAccount, 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{ledgersubaccount.Label} + default: + return nil, &NotSingularError{ledgersubaccount.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *LedgerSubAccountQuery) OnlyX(ctx context.Context) *LedgerSubAccount { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LedgerSubAccount ID in the query. +// Returns a *NotSingularError when more than one LedgerSubAccount ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *LedgerSubAccountQuery) 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{ledgersubaccount.Label} + default: + err = &NotSingularError{ledgersubaccount.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *LedgerSubAccountQuery) 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 LedgerSubAccounts. +func (_q *LedgerSubAccountQuery) All(ctx context.Context) ([]*LedgerSubAccount, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*LedgerSubAccount, *LedgerSubAccountQuery]() + return withInterceptors[[]*LedgerSubAccount](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *LedgerSubAccountQuery) AllX(ctx context.Context) []*LedgerSubAccount { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LedgerSubAccount IDs. +func (_q *LedgerSubAccountQuery) 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(ledgersubaccount.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *LedgerSubAccountQuery) 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 *LedgerSubAccountQuery) 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[*LedgerSubAccountQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *LedgerSubAccountQuery) 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 *LedgerSubAccountQuery) 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 *LedgerSubAccountQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LedgerSubAccountQuery 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 *LedgerSubAccountQuery) Clone() *LedgerSubAccountQuery { + if _q == nil { + return nil + } + return &LedgerSubAccountQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]ledgersubaccount.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.LedgerSubAccount{}, _q.predicates...), + withAccount: _q.withAccount.Clone(), + withRoute: _q.withRoute.Clone(), + withEntries: _q.withEntries.Clone(), + withFboBreakageRecords: _q.withFboBreakageRecords.Clone(), + withBreakageRecords: _q.withBreakageRecords.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithAccount tells the query-builder to eager-load the nodes that are connected to +// the "account" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerSubAccountQuery) WithAccount(opts ...func(*LedgerAccountQuery)) *LedgerSubAccountQuery { + query := (&LedgerAccountClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withAccount = query + return _q +} + +// WithRoute tells the query-builder to eager-load the nodes that are connected to +// the "route" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerSubAccountQuery) WithRoute(opts ...func(*LedgerSubAccountRouteQuery)) *LedgerSubAccountQuery { + query := (&LedgerSubAccountRouteClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withRoute = query + return _q +} + +// WithEntries tells the query-builder to eager-load the nodes that are connected to +// the "entries" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerSubAccountQuery) WithEntries(opts ...func(*LedgerEntryQuery)) *LedgerSubAccountQuery { + query := (&LedgerEntryClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withEntries = query + return _q +} + +// WithFboBreakageRecords tells the query-builder to eager-load the nodes that are connected to +// the "fbo_breakage_records" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerSubAccountQuery) WithFboBreakageRecords(opts ...func(*LedgerBreakageRecordQuery)) *LedgerSubAccountQuery { + query := (&LedgerBreakageRecordClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withFboBreakageRecords = query + return _q +} + +// WithBreakageRecords tells the query-builder to eager-load the nodes that are connected to +// the "breakage_records" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerSubAccountQuery) WithBreakageRecords(opts ...func(*LedgerBreakageRecordQuery)) *LedgerSubAccountQuery { + query := (&LedgerBreakageRecordClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBreakageRecords = 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.LedgerSubAccount.Query(). +// GroupBy(ledgersubaccount.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *LedgerSubAccountQuery) GroupBy(field string, fields ...string) *LedgerSubAccountGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &LedgerSubAccountGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = ledgersubaccount.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.LedgerSubAccount.Query(). +// Select(ledgersubaccount.FieldNamespace). +// Scan(ctx, &v) +func (_q *LedgerSubAccountQuery) Select(fields ...string) *LedgerSubAccountSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &LedgerSubAccountSelect{LedgerSubAccountQuery: _q} + sbuild.label = ledgersubaccount.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a LedgerSubAccountSelect configured with the given aggregations. +func (_q *LedgerSubAccountQuery) Aggregate(fns ...AggregateFunc) *LedgerSubAccountSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *LedgerSubAccountQuery) 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 !ledgersubaccount.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 *LedgerSubAccountQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*LedgerSubAccount, error) { + var ( + nodes = []*LedgerSubAccount{} + _spec = _q.querySpec() + loadedTypes = [5]bool{ + _q.withAccount != nil, + _q.withRoute != nil, + _q.withEntries != nil, + _q.withFboBreakageRecords != nil, + _q.withBreakageRecords != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*LedgerSubAccount).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &LedgerSubAccount{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.withAccount; query != nil { + if err := _q.loadAccount(ctx, query, nodes, nil, + func(n *LedgerSubAccount, e *LedgerAccount) { n.Edges.Account = e }); err != nil { + return nil, err + } + } + if query := _q.withRoute; query != nil { + if err := _q.loadRoute(ctx, query, nodes, nil, + func(n *LedgerSubAccount, e *LedgerSubAccountRoute) { n.Edges.Route = e }); err != nil { + return nil, err + } + } + if query := _q.withEntries; query != nil { + if err := _q.loadEntries(ctx, query, nodes, + func(n *LedgerSubAccount) { n.Edges.Entries = []*LedgerEntry{} }, + func(n *LedgerSubAccount, e *LedgerEntry) { n.Edges.Entries = append(n.Edges.Entries, e) }); err != nil { + return nil, err + } + } + if query := _q.withFboBreakageRecords; query != nil { + if err := _q.loadFboBreakageRecords(ctx, query, nodes, + func(n *LedgerSubAccount) { n.Edges.FboBreakageRecords = []*LedgerBreakageRecord{} }, + func(n *LedgerSubAccount, e *LedgerBreakageRecord) { + n.Edges.FboBreakageRecords = append(n.Edges.FboBreakageRecords, e) + }); err != nil { + return nil, err + } + } + if query := _q.withBreakageRecords; query != nil { + if err := _q.loadBreakageRecords(ctx, query, nodes, + func(n *LedgerSubAccount) { n.Edges.BreakageRecords = []*LedgerBreakageRecord{} }, + func(n *LedgerSubAccount, e *LedgerBreakageRecord) { + n.Edges.BreakageRecords = append(n.Edges.BreakageRecords, e) + }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *LedgerSubAccountQuery) loadAccount(ctx context.Context, query *LedgerAccountQuery, nodes []*LedgerSubAccount, init func(*LedgerSubAccount), assign func(*LedgerSubAccount, *LedgerAccount)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*LedgerSubAccount) + for i := range nodes { + fk := nodes[i].AccountID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(ledgeraccount.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 "account_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *LedgerSubAccountQuery) loadRoute(ctx context.Context, query *LedgerSubAccountRouteQuery, nodes []*LedgerSubAccount, init func(*LedgerSubAccount), assign func(*LedgerSubAccount, *LedgerSubAccountRoute)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*LedgerSubAccount) + for i := range nodes { + fk := nodes[i].RouteID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(ledgersubaccountroute.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 "route_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *LedgerSubAccountQuery) loadEntries(ctx context.Context, query *LedgerEntryQuery, nodes []*LedgerSubAccount, init func(*LedgerSubAccount), assign func(*LedgerSubAccount, *LedgerEntry)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*LedgerSubAccount) + 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(ledgerentry.FieldSubAccountID) + } + query.Where(predicate.LedgerEntry(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(ledgersubaccount.EntriesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.SubAccountID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "sub_account_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *LedgerSubAccountQuery) loadFboBreakageRecords(ctx context.Context, query *LedgerBreakageRecordQuery, nodes []*LedgerSubAccount, init func(*LedgerSubAccount), assign func(*LedgerSubAccount, *LedgerBreakageRecord)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*LedgerSubAccount) + 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(ledgerbreakagerecord.FieldFboSubAccountID) + } + query.Where(predicate.LedgerBreakageRecord(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(ledgersubaccount.FboBreakageRecordsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.FboSubAccountID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "fbo_sub_account_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *LedgerSubAccountQuery) loadBreakageRecords(ctx context.Context, query *LedgerBreakageRecordQuery, nodes []*LedgerSubAccount, init func(*LedgerSubAccount), assign func(*LedgerSubAccount, *LedgerBreakageRecord)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*LedgerSubAccount) + 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(ledgerbreakagerecord.FieldBreakageSubAccountID) + } + query.Where(predicate.LedgerBreakageRecord(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(ledgersubaccount.BreakageRecordsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.BreakageSubAccountID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "breakage_sub_account_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *LedgerSubAccountQuery) 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 *LedgerSubAccountQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(ledgersubaccount.Table, ledgersubaccount.Columns, sqlgraph.NewFieldSpec(ledgersubaccount.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, ledgersubaccount.FieldID) + for i := range fields { + if fields[i] != ledgersubaccount.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withAccount != nil { + _spec.Node.AddColumnOnce(ledgersubaccount.FieldAccountID) + } + if _q.withRoute != nil { + _spec.Node.AddColumnOnce(ledgersubaccount.FieldRouteID) + } + } + 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 *LedgerSubAccountQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(ledgersubaccount.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = ledgersubaccount.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 *LedgerSubAccountQuery) ForUpdate(opts ...sql.LockOption) *LedgerSubAccountQuery { + 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 *LedgerSubAccountQuery) ForShare(opts ...sql.LockOption) *LedgerSubAccountQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// LedgerSubAccountGroupBy is the group-by builder for LedgerSubAccount entities. +type LedgerSubAccountGroupBy struct { + selector + build *LedgerSubAccountQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *LedgerSubAccountGroupBy) Aggregate(fns ...AggregateFunc) *LedgerSubAccountGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *LedgerSubAccountGroupBy) 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[*LedgerSubAccountQuery, *LedgerSubAccountGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *LedgerSubAccountGroupBy) sqlScan(ctx context.Context, root *LedgerSubAccountQuery, 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) +} + +// LedgerSubAccountSelect is the builder for selecting fields of LedgerSubAccount entities. +type LedgerSubAccountSelect struct { + *LedgerSubAccountQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *LedgerSubAccountSelect) Aggregate(fns ...AggregateFunc) *LedgerSubAccountSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *LedgerSubAccountSelect) 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[*LedgerSubAccountQuery, *LedgerSubAccountSelect](ctx, _s.LedgerSubAccountQuery, _s, _s.inters, v) +} + +func (_s *LedgerSubAccountSelect) sqlScan(ctx context.Context, root *LedgerSubAccountQuery, 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/ent/db/ledgersubaccount_update.go b/ent/db/ledgersubaccount_update.go new file mode 100644 index 0000000000000000000000000000000000000000..ca9a82240a569b392d52fc0adf617bd44f836e88 --- /dev/null +++ b/ent/db/ledgersubaccount_update.go @@ -0,0 +1,817 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/ledgerbreakagerecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgerentry" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerSubAccountUpdate is the builder for updating LedgerSubAccount entities. +type LedgerSubAccountUpdate struct { + config + hooks []Hook + mutation *LedgerSubAccountMutation +} + +// Where appends a list predicates to the LedgerSubAccountUpdate builder. +func (_u *LedgerSubAccountUpdate) Where(ps ...predicate.LedgerSubAccount) *LedgerSubAccountUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *LedgerSubAccountUpdate) SetAnnotations(v models.Annotations) *LedgerSubAccountUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *LedgerSubAccountUpdate) ClearAnnotations() *LedgerSubAccountUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *LedgerSubAccountUpdate) SetUpdatedAt(v time.Time) *LedgerSubAccountUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *LedgerSubAccountUpdate) SetDeletedAt(v time.Time) *LedgerSubAccountUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *LedgerSubAccountUpdate) SetNillableDeletedAt(v *time.Time) *LedgerSubAccountUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *LedgerSubAccountUpdate) ClearDeletedAt() *LedgerSubAccountUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// AddEntryIDs adds the "entries" edge to the LedgerEntry entity by IDs. +func (_u *LedgerSubAccountUpdate) AddEntryIDs(ids ...string) *LedgerSubAccountUpdate { + _u.mutation.AddEntryIDs(ids...) + return _u +} + +// AddEntries adds the "entries" edges to the LedgerEntry entity. +func (_u *LedgerSubAccountUpdate) AddEntries(v ...*LedgerEntry) *LedgerSubAccountUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddEntryIDs(ids...) +} + +// AddFboBreakageRecordIDs adds the "fbo_breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_u *LedgerSubAccountUpdate) AddFboBreakageRecordIDs(ids ...string) *LedgerSubAccountUpdate { + _u.mutation.AddFboBreakageRecordIDs(ids...) + return _u +} + +// AddFboBreakageRecords adds the "fbo_breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerSubAccountUpdate) AddFboBreakageRecords(v ...*LedgerBreakageRecord) *LedgerSubAccountUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddFboBreakageRecordIDs(ids...) +} + +// AddBreakageRecordIDs adds the "breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_u *LedgerSubAccountUpdate) AddBreakageRecordIDs(ids ...string) *LedgerSubAccountUpdate { + _u.mutation.AddBreakageRecordIDs(ids...) + return _u +} + +// AddBreakageRecords adds the "breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerSubAccountUpdate) AddBreakageRecords(v ...*LedgerBreakageRecord) *LedgerSubAccountUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddBreakageRecordIDs(ids...) +} + +// Mutation returns the LedgerSubAccountMutation object of the builder. +func (_u *LedgerSubAccountUpdate) Mutation() *LedgerSubAccountMutation { + return _u.mutation +} + +// ClearEntries clears all "entries" edges to the LedgerEntry entity. +func (_u *LedgerSubAccountUpdate) ClearEntries() *LedgerSubAccountUpdate { + _u.mutation.ClearEntries() + return _u +} + +// RemoveEntryIDs removes the "entries" edge to LedgerEntry entities by IDs. +func (_u *LedgerSubAccountUpdate) RemoveEntryIDs(ids ...string) *LedgerSubAccountUpdate { + _u.mutation.RemoveEntryIDs(ids...) + return _u +} + +// RemoveEntries removes "entries" edges to LedgerEntry entities. +func (_u *LedgerSubAccountUpdate) RemoveEntries(v ...*LedgerEntry) *LedgerSubAccountUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveEntryIDs(ids...) +} + +// ClearFboBreakageRecords clears all "fbo_breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerSubAccountUpdate) ClearFboBreakageRecords() *LedgerSubAccountUpdate { + _u.mutation.ClearFboBreakageRecords() + return _u +} + +// RemoveFboBreakageRecordIDs removes the "fbo_breakage_records" edge to LedgerBreakageRecord entities by IDs. +func (_u *LedgerSubAccountUpdate) RemoveFboBreakageRecordIDs(ids ...string) *LedgerSubAccountUpdate { + _u.mutation.RemoveFboBreakageRecordIDs(ids...) + return _u +} + +// RemoveFboBreakageRecords removes "fbo_breakage_records" edges to LedgerBreakageRecord entities. +func (_u *LedgerSubAccountUpdate) RemoveFboBreakageRecords(v ...*LedgerBreakageRecord) *LedgerSubAccountUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveFboBreakageRecordIDs(ids...) +} + +// ClearBreakageRecords clears all "breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerSubAccountUpdate) ClearBreakageRecords() *LedgerSubAccountUpdate { + _u.mutation.ClearBreakageRecords() + return _u +} + +// RemoveBreakageRecordIDs removes the "breakage_records" edge to LedgerBreakageRecord entities by IDs. +func (_u *LedgerSubAccountUpdate) RemoveBreakageRecordIDs(ids ...string) *LedgerSubAccountUpdate { + _u.mutation.RemoveBreakageRecordIDs(ids...) + return _u +} + +// RemoveBreakageRecords removes "breakage_records" edges to LedgerBreakageRecord entities. +func (_u *LedgerSubAccountUpdate) RemoveBreakageRecords(v ...*LedgerBreakageRecord) *LedgerSubAccountUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveBreakageRecordIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *LedgerSubAccountUpdate) 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 *LedgerSubAccountUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *LedgerSubAccountUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LedgerSubAccountUpdate) 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 *LedgerSubAccountUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := ledgersubaccount.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *LedgerSubAccountUpdate) check() error { + if _u.mutation.AccountCleared() && len(_u.mutation.AccountIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerSubAccount.account"`) + } + if _u.mutation.RouteCleared() && len(_u.mutation.RouteIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerSubAccount.route"`) + } + return nil +} + +func (_u *LedgerSubAccountUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(ledgersubaccount.Table, ledgersubaccount.Columns, sqlgraph.NewFieldSpec(ledgersubaccount.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.Annotations(); ok { + _spec.SetField(ledgersubaccount.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(ledgersubaccount.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(ledgersubaccount.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(ledgersubaccount.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(ledgersubaccount.FieldDeletedAt, field.TypeTime) + } + if _u.mutation.EntriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.EntriesTable, + Columns: []string{ledgersubaccount.EntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerentry.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedEntriesIDs(); len(nodes) > 0 && !_u.mutation.EntriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.EntriesTable, + Columns: []string{ledgersubaccount.EntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerentry.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.EntriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.EntriesTable, + Columns: []string{ledgersubaccount.EntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerentry.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.FboBreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.FboBreakageRecordsTable, + Columns: []string{ledgersubaccount.FboBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedFboBreakageRecordsIDs(); len(nodes) > 0 && !_u.mutation.FboBreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.FboBreakageRecordsTable, + Columns: []string{ledgersubaccount.FboBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.FboBreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.FboBreakageRecordsTable, + Columns: []string{ledgersubaccount.FboBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.BreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.BreakageRecordsTable, + Columns: []string{ledgersubaccount.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedBreakageRecordsIDs(); len(nodes) > 0 && !_u.mutation.BreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.BreakageRecordsTable, + Columns: []string{ledgersubaccount.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.BreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.BreakageRecordsTable, + Columns: []string{ledgersubaccount.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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{ledgersubaccount.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// LedgerSubAccountUpdateOne is the builder for updating a single LedgerSubAccount entity. +type LedgerSubAccountUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LedgerSubAccountMutation +} + +// SetAnnotations sets the "annotations" field. +func (_u *LedgerSubAccountUpdateOne) SetAnnotations(v models.Annotations) *LedgerSubAccountUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *LedgerSubAccountUpdateOne) ClearAnnotations() *LedgerSubAccountUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *LedgerSubAccountUpdateOne) SetUpdatedAt(v time.Time) *LedgerSubAccountUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *LedgerSubAccountUpdateOne) SetDeletedAt(v time.Time) *LedgerSubAccountUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *LedgerSubAccountUpdateOne) SetNillableDeletedAt(v *time.Time) *LedgerSubAccountUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *LedgerSubAccountUpdateOne) ClearDeletedAt() *LedgerSubAccountUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// AddEntryIDs adds the "entries" edge to the LedgerEntry entity by IDs. +func (_u *LedgerSubAccountUpdateOne) AddEntryIDs(ids ...string) *LedgerSubAccountUpdateOne { + _u.mutation.AddEntryIDs(ids...) + return _u +} + +// AddEntries adds the "entries" edges to the LedgerEntry entity. +func (_u *LedgerSubAccountUpdateOne) AddEntries(v ...*LedgerEntry) *LedgerSubAccountUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddEntryIDs(ids...) +} + +// AddFboBreakageRecordIDs adds the "fbo_breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_u *LedgerSubAccountUpdateOne) AddFboBreakageRecordIDs(ids ...string) *LedgerSubAccountUpdateOne { + _u.mutation.AddFboBreakageRecordIDs(ids...) + return _u +} + +// AddFboBreakageRecords adds the "fbo_breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerSubAccountUpdateOne) AddFboBreakageRecords(v ...*LedgerBreakageRecord) *LedgerSubAccountUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddFboBreakageRecordIDs(ids...) +} + +// AddBreakageRecordIDs adds the "breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_u *LedgerSubAccountUpdateOne) AddBreakageRecordIDs(ids ...string) *LedgerSubAccountUpdateOne { + _u.mutation.AddBreakageRecordIDs(ids...) + return _u +} + +// AddBreakageRecords adds the "breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerSubAccountUpdateOne) AddBreakageRecords(v ...*LedgerBreakageRecord) *LedgerSubAccountUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddBreakageRecordIDs(ids...) +} + +// Mutation returns the LedgerSubAccountMutation object of the builder. +func (_u *LedgerSubAccountUpdateOne) Mutation() *LedgerSubAccountMutation { + return _u.mutation +} + +// ClearEntries clears all "entries" edges to the LedgerEntry entity. +func (_u *LedgerSubAccountUpdateOne) ClearEntries() *LedgerSubAccountUpdateOne { + _u.mutation.ClearEntries() + return _u +} + +// RemoveEntryIDs removes the "entries" edge to LedgerEntry entities by IDs. +func (_u *LedgerSubAccountUpdateOne) RemoveEntryIDs(ids ...string) *LedgerSubAccountUpdateOne { + _u.mutation.RemoveEntryIDs(ids...) + return _u +} + +// RemoveEntries removes "entries" edges to LedgerEntry entities. +func (_u *LedgerSubAccountUpdateOne) RemoveEntries(v ...*LedgerEntry) *LedgerSubAccountUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveEntryIDs(ids...) +} + +// ClearFboBreakageRecords clears all "fbo_breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerSubAccountUpdateOne) ClearFboBreakageRecords() *LedgerSubAccountUpdateOne { + _u.mutation.ClearFboBreakageRecords() + return _u +} + +// RemoveFboBreakageRecordIDs removes the "fbo_breakage_records" edge to LedgerBreakageRecord entities by IDs. +func (_u *LedgerSubAccountUpdateOne) RemoveFboBreakageRecordIDs(ids ...string) *LedgerSubAccountUpdateOne { + _u.mutation.RemoveFboBreakageRecordIDs(ids...) + return _u +} + +// RemoveFboBreakageRecords removes "fbo_breakage_records" edges to LedgerBreakageRecord entities. +func (_u *LedgerSubAccountUpdateOne) RemoveFboBreakageRecords(v ...*LedgerBreakageRecord) *LedgerSubAccountUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveFboBreakageRecordIDs(ids...) +} + +// ClearBreakageRecords clears all "breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerSubAccountUpdateOne) ClearBreakageRecords() *LedgerSubAccountUpdateOne { + _u.mutation.ClearBreakageRecords() + return _u +} + +// RemoveBreakageRecordIDs removes the "breakage_records" edge to LedgerBreakageRecord entities by IDs. +func (_u *LedgerSubAccountUpdateOne) RemoveBreakageRecordIDs(ids ...string) *LedgerSubAccountUpdateOne { + _u.mutation.RemoveBreakageRecordIDs(ids...) + return _u +} + +// RemoveBreakageRecords removes "breakage_records" edges to LedgerBreakageRecord entities. +func (_u *LedgerSubAccountUpdateOne) RemoveBreakageRecords(v ...*LedgerBreakageRecord) *LedgerSubAccountUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveBreakageRecordIDs(ids...) +} + +// Where appends a list predicates to the LedgerSubAccountUpdate builder. +func (_u *LedgerSubAccountUpdateOne) Where(ps ...predicate.LedgerSubAccount) *LedgerSubAccountUpdateOne { + _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 *LedgerSubAccountUpdateOne) Select(field string, fields ...string) *LedgerSubAccountUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated LedgerSubAccount entity. +func (_u *LedgerSubAccountUpdateOne) Save(ctx context.Context) (*LedgerSubAccount, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *LedgerSubAccountUpdateOne) SaveX(ctx context.Context) *LedgerSubAccount { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *LedgerSubAccountUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LedgerSubAccountUpdateOne) 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 *LedgerSubAccountUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := ledgersubaccount.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *LedgerSubAccountUpdateOne) check() error { + if _u.mutation.AccountCleared() && len(_u.mutation.AccountIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerSubAccount.account"`) + } + if _u.mutation.RouteCleared() && len(_u.mutation.RouteIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerSubAccount.route"`) + } + return nil +} + +func (_u *LedgerSubAccountUpdateOne) sqlSave(ctx context.Context) (_node *LedgerSubAccount, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(ledgersubaccount.Table, ledgersubaccount.Columns, sqlgraph.NewFieldSpec(ledgersubaccount.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "LedgerSubAccount.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, ledgersubaccount.FieldID) + for _, f := range fields { + if !ledgersubaccount.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != ledgersubaccount.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.Annotations(); ok { + _spec.SetField(ledgersubaccount.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(ledgersubaccount.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(ledgersubaccount.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(ledgersubaccount.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(ledgersubaccount.FieldDeletedAt, field.TypeTime) + } + if _u.mutation.EntriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.EntriesTable, + Columns: []string{ledgersubaccount.EntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerentry.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedEntriesIDs(); len(nodes) > 0 && !_u.mutation.EntriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.EntriesTable, + Columns: []string{ledgersubaccount.EntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerentry.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.EntriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.EntriesTable, + Columns: []string{ledgersubaccount.EntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerentry.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.FboBreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.FboBreakageRecordsTable, + Columns: []string{ledgersubaccount.FboBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedFboBreakageRecordsIDs(); len(nodes) > 0 && !_u.mutation.FboBreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.FboBreakageRecordsTable, + Columns: []string{ledgersubaccount.FboBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.FboBreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.FboBreakageRecordsTable, + Columns: []string{ledgersubaccount.FboBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.BreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.BreakageRecordsTable, + Columns: []string{ledgersubaccount.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedBreakageRecordsIDs(); len(nodes) > 0 && !_u.mutation.BreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.BreakageRecordsTable, + Columns: []string{ledgersubaccount.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.BreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccount.BreakageRecordsTable, + Columns: []string{ledgersubaccount.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &LedgerSubAccount{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{ledgersubaccount.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/ent/db/ledgersubaccountroute.go b/ent/db/ledgersubaccountroute.go new file mode 100644 index 0000000000000000000000000000000000000000..399fe2f08c21a26d4a8e1e97f68b391d0985dacd --- /dev/null +++ b/ent/db/ledgersubaccountroute.go @@ -0,0 +1,319 @@ +// 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/lib/pq" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccountroute" + "github.com/openmeterio/openmeter/openmeter/ledger" +) + +// LedgerSubAccountRoute is the model entity for the LedgerSubAccountRoute schema. +type LedgerSubAccountRoute 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"` + // AccountID holds the value of the "account_id" field. + AccountID string `json:"account_id,omitempty"` + // RoutingKeyVersion holds the value of the "routing_key_version" field. + RoutingKeyVersion ledger.RoutingKeyVersion `json:"routing_key_version,omitempty"` + // RoutingKey holds the value of the "routing_key" field. + RoutingKey string `json:"routing_key,omitempty"` + // Currency holds the value of the "currency" field. + Currency string `json:"currency,omitempty"` + // TaxCode holds the value of the "tax_code" field. + TaxCode *string `json:"tax_code,omitempty"` + // TaxBehavior holds the value of the "tax_behavior" field. + TaxBehavior *ledger.TaxBehavior `json:"tax_behavior,omitempty"` + // Features holds the value of the "features" field. + Features pq.StringArray `json:"features,omitempty"` + // CostBasis holds the value of the "cost_basis" field. + CostBasis *alpacadecimal.Decimal `json:"cost_basis,omitempty"` + // CreditPriority holds the value of the "credit_priority" field. + CreditPriority *int `json:"credit_priority,omitempty"` + // TransactionAuthorizationStatus holds the value of the "transaction_authorization_status" field. + TransactionAuthorizationStatus *ledger.TransactionAuthorizationStatus `json:"transaction_authorization_status,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the LedgerSubAccountRouteQuery when eager-loading is set. + Edges LedgerSubAccountRouteEdges `json:"edges"` + selectValues sql.SelectValues +} + +// LedgerSubAccountRouteEdges holds the relations/edges for other nodes in the graph. +type LedgerSubAccountRouteEdges struct { + // Account holds the value of the account edge. + Account *LedgerAccount `json:"account,omitempty"` + // SubAccounts holds the value of the sub_accounts edge. + SubAccounts []*LedgerSubAccount `json:"sub_accounts,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// AccountOrErr returns the Account value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e LedgerSubAccountRouteEdges) AccountOrErr() (*LedgerAccount, error) { + if e.Account != nil { + return e.Account, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: ledgeraccount.Label} + } + return nil, &NotLoadedError{edge: "account"} +} + +// SubAccountsOrErr returns the SubAccounts value or an error if the edge +// was not loaded in eager-loading. +func (e LedgerSubAccountRouteEdges) SubAccountsOrErr() ([]*LedgerSubAccount, error) { + if e.loadedTypes[1] { + return e.SubAccounts, nil + } + return nil, &NotLoadedError{edge: "sub_accounts"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LedgerSubAccountRoute) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case ledgersubaccountroute.FieldCostBasis: + values[i] = &sql.NullScanner{S: new(alpacadecimal.Decimal)} + case ledgersubaccountroute.FieldFeatures: + values[i] = new(pq.StringArray) + case ledgersubaccountroute.FieldCreditPriority: + values[i] = new(sql.NullInt64) + case ledgersubaccountroute.FieldID, ledgersubaccountroute.FieldNamespace, ledgersubaccountroute.FieldAccountID, ledgersubaccountroute.FieldRoutingKeyVersion, ledgersubaccountroute.FieldRoutingKey, ledgersubaccountroute.FieldCurrency, ledgersubaccountroute.FieldTaxCode, ledgersubaccountroute.FieldTaxBehavior, ledgersubaccountroute.FieldTransactionAuthorizationStatus: + values[i] = new(sql.NullString) + case ledgersubaccountroute.FieldCreatedAt, ledgersubaccountroute.FieldUpdatedAt, ledgersubaccountroute.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 LedgerSubAccountRoute fields. +func (_m *LedgerSubAccountRoute) 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 ledgersubaccountroute.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 ledgersubaccountroute.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 ledgersubaccountroute.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 ledgersubaccountroute.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 ledgersubaccountroute.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 ledgersubaccountroute.FieldAccountID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field account_id", values[i]) + } else if value.Valid { + _m.AccountID = value.String + } + case ledgersubaccountroute.FieldRoutingKeyVersion: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field routing_key_version", values[i]) + } else if value.Valid { + _m.RoutingKeyVersion = ledger.RoutingKeyVersion(value.String) + } + case ledgersubaccountroute.FieldRoutingKey: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field routing_key", values[i]) + } else if value.Valid { + _m.RoutingKey = value.String + } + case ledgersubaccountroute.FieldCurrency: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field currency", values[i]) + } else if value.Valid { + _m.Currency = value.String + } + case ledgersubaccountroute.FieldTaxCode: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field tax_code", values[i]) + } else if value.Valid { + _m.TaxCode = new(string) + *_m.TaxCode = value.String + } + case ledgersubaccountroute.FieldTaxBehavior: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field tax_behavior", values[i]) + } else if value.Valid { + _m.TaxBehavior = new(ledger.TaxBehavior) + *_m.TaxBehavior = ledger.TaxBehavior(value.String) + } + case ledgersubaccountroute.FieldFeatures: + if value, ok := values[i].(*pq.StringArray); !ok { + return fmt.Errorf("unexpected type %T for field features", values[i]) + } else if value != nil { + _m.Features = *value + } + case ledgersubaccountroute.FieldCostBasis: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field cost_basis", values[i]) + } else if value.Valid { + _m.CostBasis = new(alpacadecimal.Decimal) + *_m.CostBasis = *value.S.(*alpacadecimal.Decimal) + } + case ledgersubaccountroute.FieldCreditPriority: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field credit_priority", values[i]) + } else if value.Valid { + _m.CreditPriority = new(int) + *_m.CreditPriority = int(value.Int64) + } + case ledgersubaccountroute.FieldTransactionAuthorizationStatus: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field transaction_authorization_status", values[i]) + } else if value.Valid { + _m.TransactionAuthorizationStatus = new(ledger.TransactionAuthorizationStatus) + *_m.TransactionAuthorizationStatus = ledger.TransactionAuthorizationStatus(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 LedgerSubAccountRoute. +// This includes values selected through modifiers, order, etc. +func (_m *LedgerSubAccountRoute) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryAccount queries the "account" edge of the LedgerSubAccountRoute entity. +func (_m *LedgerSubAccountRoute) QueryAccount() *LedgerAccountQuery { + return NewLedgerSubAccountRouteClient(_m.config).QueryAccount(_m) +} + +// QuerySubAccounts queries the "sub_accounts" edge of the LedgerSubAccountRoute entity. +func (_m *LedgerSubAccountRoute) QuerySubAccounts() *LedgerSubAccountQuery { + return NewLedgerSubAccountRouteClient(_m.config).QuerySubAccounts(_m) +} + +// Update returns a builder for updating this LedgerSubAccountRoute. +// Note that you need to call LedgerSubAccountRoute.Unwrap() before calling this method if this LedgerSubAccountRoute +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *LedgerSubAccountRoute) Update() *LedgerSubAccountRouteUpdateOne { + return NewLedgerSubAccountRouteClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the LedgerSubAccountRoute 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 *LedgerSubAccountRoute) Unwrap() *LedgerSubAccountRoute { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: LedgerSubAccountRoute is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *LedgerSubAccountRoute) String() string { + var builder strings.Builder + builder.WriteString("LedgerSubAccountRoute(") + 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("account_id=") + builder.WriteString(_m.AccountID) + builder.WriteString(", ") + builder.WriteString("routing_key_version=") + builder.WriteString(fmt.Sprintf("%v", _m.RoutingKeyVersion)) + builder.WriteString(", ") + builder.WriteString("routing_key=") + builder.WriteString(_m.RoutingKey) + builder.WriteString(", ") + builder.WriteString("currency=") + builder.WriteString(_m.Currency) + builder.WriteString(", ") + if v := _m.TaxCode; v != nil { + builder.WriteString("tax_code=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.TaxBehavior; v != nil { + builder.WriteString("tax_behavior=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + builder.WriteString("features=") + builder.WriteString(fmt.Sprintf("%v", _m.Features)) + builder.WriteString(", ") + if v := _m.CostBasis; v != nil { + builder.WriteString("cost_basis=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.CreditPriority; v != nil { + builder.WriteString("credit_priority=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.TransactionAuthorizationStatus; v != nil { + builder.WriteString("transaction_authorization_status=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteByte(')') + return builder.String() +} + +// LedgerSubAccountRoutes is a parsable slice of LedgerSubAccountRoute. +type LedgerSubAccountRoutes []*LedgerSubAccountRoute diff --git a/ent/db/ledgersubaccountroute/ledgersubaccountroute.go b/ent/db/ledgersubaccountroute/ledgersubaccountroute.go new file mode 100644 index 0000000000000000000000000000000000000000..d92cd6881bada11c92016774cec6ced36b62e03d --- /dev/null +++ b/ent/db/ledgersubaccountroute/ledgersubaccountroute.go @@ -0,0 +1,220 @@ +// Code generated by ent, DO NOT EDIT. + +package ledgersubaccountroute + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the ledgersubaccountroute type in the database. + Label = "ledger_sub_account_route" + // 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" + // FieldAccountID holds the string denoting the account_id field in the database. + FieldAccountID = "account_id" + // FieldRoutingKeyVersion holds the string denoting the routing_key_version field in the database. + FieldRoutingKeyVersion = "routing_key_version" + // FieldRoutingKey holds the string denoting the routing_key field in the database. + FieldRoutingKey = "routing_key" + // FieldCurrency holds the string denoting the currency field in the database. + FieldCurrency = "currency" + // FieldTaxCode holds the string denoting the tax_code field in the database. + FieldTaxCode = "tax_code" + // FieldTaxBehavior holds the string denoting the tax_behavior field in the database. + FieldTaxBehavior = "tax_behavior" + // FieldFeatures holds the string denoting the features field in the database. + FieldFeatures = "features" + // FieldCostBasis holds the string denoting the cost_basis field in the database. + FieldCostBasis = "cost_basis" + // FieldCreditPriority holds the string denoting the credit_priority field in the database. + FieldCreditPriority = "credit_priority" + // FieldTransactionAuthorizationStatus holds the string denoting the transaction_authorization_status field in the database. + FieldTransactionAuthorizationStatus = "transaction_authorization_status" + // EdgeAccount holds the string denoting the account edge name in mutations. + EdgeAccount = "account" + // EdgeSubAccounts holds the string denoting the sub_accounts edge name in mutations. + EdgeSubAccounts = "sub_accounts" + // Table holds the table name of the ledgersubaccountroute in the database. + Table = "ledger_sub_account_routes" + // AccountTable is the table that holds the account relation/edge. + AccountTable = "ledger_sub_account_routes" + // AccountInverseTable is the table name for the LedgerAccount entity. + // It exists in this package in order to avoid circular dependency with the "ledgeraccount" package. + AccountInverseTable = "ledger_accounts" + // AccountColumn is the table column denoting the account relation/edge. + AccountColumn = "account_id" + // SubAccountsTable is the table that holds the sub_accounts relation/edge. + SubAccountsTable = "ledger_sub_accounts" + // SubAccountsInverseTable is the table name for the LedgerSubAccount entity. + // It exists in this package in order to avoid circular dependency with the "ledgersubaccount" package. + SubAccountsInverseTable = "ledger_sub_accounts" + // SubAccountsColumn is the table column denoting the sub_accounts relation/edge. + SubAccountsColumn = "route_id" +) + +// Columns holds all SQL columns for ledgersubaccountroute fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldAccountID, + FieldRoutingKeyVersion, + FieldRoutingKey, + FieldCurrency, + FieldTaxCode, + FieldTaxBehavior, + FieldFeatures, + FieldCostBasis, + FieldCreditPriority, + FieldTransactionAuthorizationStatus, +} + +// 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 +) + +// OrderOption defines the ordering options for the LedgerSubAccountRoute 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() +} + +// ByAccountID orders the results by the account_id field. +func ByAccountID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAccountID, opts...).ToFunc() +} + +// ByRoutingKeyVersion orders the results by the routing_key_version field. +func ByRoutingKeyVersion(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRoutingKeyVersion, opts...).ToFunc() +} + +// ByRoutingKey orders the results by the routing_key field. +func ByRoutingKey(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRoutingKey, opts...).ToFunc() +} + +// ByCurrency orders the results by the currency field. +func ByCurrency(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCurrency, opts...).ToFunc() +} + +// ByTaxCode orders the results by the tax_code field. +func ByTaxCode(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxCode, opts...).ToFunc() +} + +// ByTaxBehavior orders the results by the tax_behavior field. +func ByTaxBehavior(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxBehavior, opts...).ToFunc() +} + +// ByFeatures orders the results by the features field. +func ByFeatures(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFeatures, opts...).ToFunc() +} + +// ByCostBasis orders the results by the cost_basis field. +func ByCostBasis(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCostBasis, opts...).ToFunc() +} + +// ByCreditPriority orders the results by the credit_priority field. +func ByCreditPriority(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreditPriority, opts...).ToFunc() +} + +// ByTransactionAuthorizationStatus orders the results by the transaction_authorization_status field. +func ByTransactionAuthorizationStatus(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTransactionAuthorizationStatus, opts...).ToFunc() +} + +// ByAccountField orders the results by account field. +func ByAccountField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newAccountStep(), sql.OrderByField(field, opts...)) + } +} + +// BySubAccountsCount orders the results by sub_accounts count. +func BySubAccountsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newSubAccountsStep(), opts...) + } +} + +// BySubAccounts orders the results by sub_accounts terms. +func BySubAccounts(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubAccountsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newAccountStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(AccountInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, AccountTable, AccountColumn), + ) +} +func newSubAccountsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SubAccountsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SubAccountsTable, SubAccountsColumn), + ) +} diff --git a/ent/db/ledgersubaccountroute/where.go b/ent/db/ledgersubaccountroute/where.go new file mode 100644 index 0000000000000000000000000000000000000000..30bc3b436277f584f884deda72ffdf8fa63ff87d --- /dev/null +++ b/ent/db/ledgersubaccountroute/where.go @@ -0,0 +1,1090 @@ +// Code generated by ent, DO NOT EDIT. + +package ledgersubaccountroute + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/alpacahq/alpacadecimal" + "github.com/lib/pq" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/ledger" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(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.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(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.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(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.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldDeletedAt, v)) +} + +// AccountID applies equality check predicate on the "account_id" field. It's identical to AccountIDEQ. +func AccountID(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldAccountID, v)) +} + +// RoutingKeyVersion applies equality check predicate on the "routing_key_version" field. It's identical to RoutingKeyVersionEQ. +func RoutingKeyVersion(v ledger.RoutingKeyVersion) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldRoutingKeyVersion, vc)) +} + +// RoutingKey applies equality check predicate on the "routing_key" field. It's identical to RoutingKeyEQ. +func RoutingKey(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldRoutingKey, v)) +} + +// Currency applies equality check predicate on the "currency" field. It's identical to CurrencyEQ. +func Currency(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldCurrency, v)) +} + +// TaxCode applies equality check predicate on the "tax_code" field. It's identical to TaxCodeEQ. +func TaxCode(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldTaxCode, v)) +} + +// TaxBehavior applies equality check predicate on the "tax_behavior" field. It's identical to TaxBehaviorEQ. +func TaxBehavior(v ledger.TaxBehavior) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldTaxBehavior, vc)) +} + +// Features applies equality check predicate on the "features" field. It's identical to FeaturesEQ. +func Features(v pq.StringArray) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldFeatures, v)) +} + +// CostBasis applies equality check predicate on the "cost_basis" field. It's identical to CostBasisEQ. +func CostBasis(v alpacadecimal.Decimal) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldCostBasis, v)) +} + +// CreditPriority applies equality check predicate on the "credit_priority" field. It's identical to CreditPriorityEQ. +func CreditPriority(v int) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldCreditPriority, v)) +} + +// TransactionAuthorizationStatus applies equality check predicate on the "transaction_authorization_status" field. It's identical to TransactionAuthorizationStatusEQ. +func TransactionAuthorizationStatus(v ledger.TransactionAuthorizationStatus) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldTransactionAuthorizationStatus, vc)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNotNull(FieldDeletedAt)) +} + +// AccountIDEQ applies the EQ predicate on the "account_id" field. +func AccountIDEQ(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldAccountID, v)) +} + +// AccountIDNEQ applies the NEQ predicate on the "account_id" field. +func AccountIDNEQ(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNEQ(FieldAccountID, v)) +} + +// AccountIDIn applies the In predicate on the "account_id" field. +func AccountIDIn(vs ...string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldIn(FieldAccountID, vs...)) +} + +// AccountIDNotIn applies the NotIn predicate on the "account_id" field. +func AccountIDNotIn(vs ...string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNotIn(FieldAccountID, vs...)) +} + +// AccountIDGT applies the GT predicate on the "account_id" field. +func AccountIDGT(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGT(FieldAccountID, v)) +} + +// AccountIDGTE applies the GTE predicate on the "account_id" field. +func AccountIDGTE(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGTE(FieldAccountID, v)) +} + +// AccountIDLT applies the LT predicate on the "account_id" field. +func AccountIDLT(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLT(FieldAccountID, v)) +} + +// AccountIDLTE applies the LTE predicate on the "account_id" field. +func AccountIDLTE(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLTE(FieldAccountID, v)) +} + +// AccountIDContains applies the Contains predicate on the "account_id" field. +func AccountIDContains(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldContains(FieldAccountID, v)) +} + +// AccountIDHasPrefix applies the HasPrefix predicate on the "account_id" field. +func AccountIDHasPrefix(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldHasPrefix(FieldAccountID, v)) +} + +// AccountIDHasSuffix applies the HasSuffix predicate on the "account_id" field. +func AccountIDHasSuffix(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldHasSuffix(FieldAccountID, v)) +} + +// AccountIDEqualFold applies the EqualFold predicate on the "account_id" field. +func AccountIDEqualFold(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEqualFold(FieldAccountID, v)) +} + +// AccountIDContainsFold applies the ContainsFold predicate on the "account_id" field. +func AccountIDContainsFold(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldContainsFold(FieldAccountID, v)) +} + +// RoutingKeyVersionEQ applies the EQ predicate on the "routing_key_version" field. +func RoutingKeyVersionEQ(v ledger.RoutingKeyVersion) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldRoutingKeyVersion, vc)) +} + +// RoutingKeyVersionNEQ applies the NEQ predicate on the "routing_key_version" field. +func RoutingKeyVersionNEQ(v ledger.RoutingKeyVersion) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldNEQ(FieldRoutingKeyVersion, vc)) +} + +// RoutingKeyVersionIn applies the In predicate on the "routing_key_version" field. +func RoutingKeyVersionIn(vs ...ledger.RoutingKeyVersion) predicate.LedgerSubAccountRoute { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.LedgerSubAccountRoute(sql.FieldIn(FieldRoutingKeyVersion, v...)) +} + +// RoutingKeyVersionNotIn applies the NotIn predicate on the "routing_key_version" field. +func RoutingKeyVersionNotIn(vs ...ledger.RoutingKeyVersion) predicate.LedgerSubAccountRoute { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.LedgerSubAccountRoute(sql.FieldNotIn(FieldRoutingKeyVersion, v...)) +} + +// RoutingKeyVersionGT applies the GT predicate on the "routing_key_version" field. +func RoutingKeyVersionGT(v ledger.RoutingKeyVersion) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldGT(FieldRoutingKeyVersion, vc)) +} + +// RoutingKeyVersionGTE applies the GTE predicate on the "routing_key_version" field. +func RoutingKeyVersionGTE(v ledger.RoutingKeyVersion) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldGTE(FieldRoutingKeyVersion, vc)) +} + +// RoutingKeyVersionLT applies the LT predicate on the "routing_key_version" field. +func RoutingKeyVersionLT(v ledger.RoutingKeyVersion) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldLT(FieldRoutingKeyVersion, vc)) +} + +// RoutingKeyVersionLTE applies the LTE predicate on the "routing_key_version" field. +func RoutingKeyVersionLTE(v ledger.RoutingKeyVersion) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldLTE(FieldRoutingKeyVersion, vc)) +} + +// RoutingKeyVersionContains applies the Contains predicate on the "routing_key_version" field. +func RoutingKeyVersionContains(v ledger.RoutingKeyVersion) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldContains(FieldRoutingKeyVersion, vc)) +} + +// RoutingKeyVersionHasPrefix applies the HasPrefix predicate on the "routing_key_version" field. +func RoutingKeyVersionHasPrefix(v ledger.RoutingKeyVersion) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldHasPrefix(FieldRoutingKeyVersion, vc)) +} + +// RoutingKeyVersionHasSuffix applies the HasSuffix predicate on the "routing_key_version" field. +func RoutingKeyVersionHasSuffix(v ledger.RoutingKeyVersion) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldHasSuffix(FieldRoutingKeyVersion, vc)) +} + +// RoutingKeyVersionEqualFold applies the EqualFold predicate on the "routing_key_version" field. +func RoutingKeyVersionEqualFold(v ledger.RoutingKeyVersion) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldEqualFold(FieldRoutingKeyVersion, vc)) +} + +// RoutingKeyVersionContainsFold applies the ContainsFold predicate on the "routing_key_version" field. +func RoutingKeyVersionContainsFold(v ledger.RoutingKeyVersion) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldContainsFold(FieldRoutingKeyVersion, vc)) +} + +// RoutingKeyEQ applies the EQ predicate on the "routing_key" field. +func RoutingKeyEQ(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldRoutingKey, v)) +} + +// RoutingKeyNEQ applies the NEQ predicate on the "routing_key" field. +func RoutingKeyNEQ(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNEQ(FieldRoutingKey, v)) +} + +// RoutingKeyIn applies the In predicate on the "routing_key" field. +func RoutingKeyIn(vs ...string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldIn(FieldRoutingKey, vs...)) +} + +// RoutingKeyNotIn applies the NotIn predicate on the "routing_key" field. +func RoutingKeyNotIn(vs ...string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNotIn(FieldRoutingKey, vs...)) +} + +// RoutingKeyGT applies the GT predicate on the "routing_key" field. +func RoutingKeyGT(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGT(FieldRoutingKey, v)) +} + +// RoutingKeyGTE applies the GTE predicate on the "routing_key" field. +func RoutingKeyGTE(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGTE(FieldRoutingKey, v)) +} + +// RoutingKeyLT applies the LT predicate on the "routing_key" field. +func RoutingKeyLT(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLT(FieldRoutingKey, v)) +} + +// RoutingKeyLTE applies the LTE predicate on the "routing_key" field. +func RoutingKeyLTE(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLTE(FieldRoutingKey, v)) +} + +// RoutingKeyContains applies the Contains predicate on the "routing_key" field. +func RoutingKeyContains(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldContains(FieldRoutingKey, v)) +} + +// RoutingKeyHasPrefix applies the HasPrefix predicate on the "routing_key" field. +func RoutingKeyHasPrefix(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldHasPrefix(FieldRoutingKey, v)) +} + +// RoutingKeyHasSuffix applies the HasSuffix predicate on the "routing_key" field. +func RoutingKeyHasSuffix(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldHasSuffix(FieldRoutingKey, v)) +} + +// RoutingKeyEqualFold applies the EqualFold predicate on the "routing_key" field. +func RoutingKeyEqualFold(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEqualFold(FieldRoutingKey, v)) +} + +// RoutingKeyContainsFold applies the ContainsFold predicate on the "routing_key" field. +func RoutingKeyContainsFold(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldContainsFold(FieldRoutingKey, v)) +} + +// CurrencyEQ applies the EQ predicate on the "currency" field. +func CurrencyEQ(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldCurrency, v)) +} + +// CurrencyNEQ applies the NEQ predicate on the "currency" field. +func CurrencyNEQ(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNEQ(FieldCurrency, v)) +} + +// CurrencyIn applies the In predicate on the "currency" field. +func CurrencyIn(vs ...string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldIn(FieldCurrency, vs...)) +} + +// CurrencyNotIn applies the NotIn predicate on the "currency" field. +func CurrencyNotIn(vs ...string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNotIn(FieldCurrency, vs...)) +} + +// CurrencyGT applies the GT predicate on the "currency" field. +func CurrencyGT(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGT(FieldCurrency, v)) +} + +// CurrencyGTE applies the GTE predicate on the "currency" field. +func CurrencyGTE(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGTE(FieldCurrency, v)) +} + +// CurrencyLT applies the LT predicate on the "currency" field. +func CurrencyLT(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLT(FieldCurrency, v)) +} + +// CurrencyLTE applies the LTE predicate on the "currency" field. +func CurrencyLTE(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLTE(FieldCurrency, v)) +} + +// CurrencyContains applies the Contains predicate on the "currency" field. +func CurrencyContains(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldContains(FieldCurrency, v)) +} + +// CurrencyHasPrefix applies the HasPrefix predicate on the "currency" field. +func CurrencyHasPrefix(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldHasPrefix(FieldCurrency, v)) +} + +// CurrencyHasSuffix applies the HasSuffix predicate on the "currency" field. +func CurrencyHasSuffix(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldHasSuffix(FieldCurrency, v)) +} + +// CurrencyEqualFold applies the EqualFold predicate on the "currency" field. +func CurrencyEqualFold(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEqualFold(FieldCurrency, v)) +} + +// CurrencyContainsFold applies the ContainsFold predicate on the "currency" field. +func CurrencyContainsFold(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldContainsFold(FieldCurrency, v)) +} + +// TaxCodeEQ applies the EQ predicate on the "tax_code" field. +func TaxCodeEQ(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldTaxCode, v)) +} + +// TaxCodeNEQ applies the NEQ predicate on the "tax_code" field. +func TaxCodeNEQ(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNEQ(FieldTaxCode, v)) +} + +// TaxCodeIn applies the In predicate on the "tax_code" field. +func TaxCodeIn(vs ...string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldIn(FieldTaxCode, vs...)) +} + +// TaxCodeNotIn applies the NotIn predicate on the "tax_code" field. +func TaxCodeNotIn(vs ...string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNotIn(FieldTaxCode, vs...)) +} + +// TaxCodeGT applies the GT predicate on the "tax_code" field. +func TaxCodeGT(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGT(FieldTaxCode, v)) +} + +// TaxCodeGTE applies the GTE predicate on the "tax_code" field. +func TaxCodeGTE(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGTE(FieldTaxCode, v)) +} + +// TaxCodeLT applies the LT predicate on the "tax_code" field. +func TaxCodeLT(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLT(FieldTaxCode, v)) +} + +// TaxCodeLTE applies the LTE predicate on the "tax_code" field. +func TaxCodeLTE(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLTE(FieldTaxCode, v)) +} + +// TaxCodeContains applies the Contains predicate on the "tax_code" field. +func TaxCodeContains(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldContains(FieldTaxCode, v)) +} + +// TaxCodeHasPrefix applies the HasPrefix predicate on the "tax_code" field. +func TaxCodeHasPrefix(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldHasPrefix(FieldTaxCode, v)) +} + +// TaxCodeHasSuffix applies the HasSuffix predicate on the "tax_code" field. +func TaxCodeHasSuffix(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldHasSuffix(FieldTaxCode, v)) +} + +// TaxCodeIsNil applies the IsNil predicate on the "tax_code" field. +func TaxCodeIsNil() predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldIsNull(FieldTaxCode)) +} + +// TaxCodeNotNil applies the NotNil predicate on the "tax_code" field. +func TaxCodeNotNil() predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNotNull(FieldTaxCode)) +} + +// TaxCodeEqualFold applies the EqualFold predicate on the "tax_code" field. +func TaxCodeEqualFold(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEqualFold(FieldTaxCode, v)) +} + +// TaxCodeContainsFold applies the ContainsFold predicate on the "tax_code" field. +func TaxCodeContainsFold(v string) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldContainsFold(FieldTaxCode, v)) +} + +// TaxBehaviorEQ applies the EQ predicate on the "tax_behavior" field. +func TaxBehaviorEQ(v ledger.TaxBehavior) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldTaxBehavior, vc)) +} + +// TaxBehaviorNEQ applies the NEQ predicate on the "tax_behavior" field. +func TaxBehaviorNEQ(v ledger.TaxBehavior) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldNEQ(FieldTaxBehavior, vc)) +} + +// TaxBehaviorIn applies the In predicate on the "tax_behavior" field. +func TaxBehaviorIn(vs ...ledger.TaxBehavior) predicate.LedgerSubAccountRoute { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.LedgerSubAccountRoute(sql.FieldIn(FieldTaxBehavior, v...)) +} + +// TaxBehaviorNotIn applies the NotIn predicate on the "tax_behavior" field. +func TaxBehaviorNotIn(vs ...ledger.TaxBehavior) predicate.LedgerSubAccountRoute { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.LedgerSubAccountRoute(sql.FieldNotIn(FieldTaxBehavior, v...)) +} + +// TaxBehaviorGT applies the GT predicate on the "tax_behavior" field. +func TaxBehaviorGT(v ledger.TaxBehavior) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldGT(FieldTaxBehavior, vc)) +} + +// TaxBehaviorGTE applies the GTE predicate on the "tax_behavior" field. +func TaxBehaviorGTE(v ledger.TaxBehavior) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldGTE(FieldTaxBehavior, vc)) +} + +// TaxBehaviorLT applies the LT predicate on the "tax_behavior" field. +func TaxBehaviorLT(v ledger.TaxBehavior) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldLT(FieldTaxBehavior, vc)) +} + +// TaxBehaviorLTE applies the LTE predicate on the "tax_behavior" field. +func TaxBehaviorLTE(v ledger.TaxBehavior) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldLTE(FieldTaxBehavior, vc)) +} + +// TaxBehaviorContains applies the Contains predicate on the "tax_behavior" field. +func TaxBehaviorContains(v ledger.TaxBehavior) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldContains(FieldTaxBehavior, vc)) +} + +// TaxBehaviorHasPrefix applies the HasPrefix predicate on the "tax_behavior" field. +func TaxBehaviorHasPrefix(v ledger.TaxBehavior) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldHasPrefix(FieldTaxBehavior, vc)) +} + +// TaxBehaviorHasSuffix applies the HasSuffix predicate on the "tax_behavior" field. +func TaxBehaviorHasSuffix(v ledger.TaxBehavior) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldHasSuffix(FieldTaxBehavior, vc)) +} + +// TaxBehaviorIsNil applies the IsNil predicate on the "tax_behavior" field. +func TaxBehaviorIsNil() predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldIsNull(FieldTaxBehavior)) +} + +// TaxBehaviorNotNil applies the NotNil predicate on the "tax_behavior" field. +func TaxBehaviorNotNil() predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNotNull(FieldTaxBehavior)) +} + +// TaxBehaviorEqualFold applies the EqualFold predicate on the "tax_behavior" field. +func TaxBehaviorEqualFold(v ledger.TaxBehavior) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldEqualFold(FieldTaxBehavior, vc)) +} + +// TaxBehaviorContainsFold applies the ContainsFold predicate on the "tax_behavior" field. +func TaxBehaviorContainsFold(v ledger.TaxBehavior) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldContainsFold(FieldTaxBehavior, vc)) +} + +// FeaturesEQ applies the EQ predicate on the "features" field. +func FeaturesEQ(v pq.StringArray) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldFeatures, v)) +} + +// FeaturesNEQ applies the NEQ predicate on the "features" field. +func FeaturesNEQ(v pq.StringArray) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNEQ(FieldFeatures, v)) +} + +// FeaturesIn applies the In predicate on the "features" field. +func FeaturesIn(vs ...pq.StringArray) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldIn(FieldFeatures, vs...)) +} + +// FeaturesNotIn applies the NotIn predicate on the "features" field. +func FeaturesNotIn(vs ...pq.StringArray) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNotIn(FieldFeatures, vs...)) +} + +// FeaturesGT applies the GT predicate on the "features" field. +func FeaturesGT(v pq.StringArray) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGT(FieldFeatures, v)) +} + +// FeaturesGTE applies the GTE predicate on the "features" field. +func FeaturesGTE(v pq.StringArray) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGTE(FieldFeatures, v)) +} + +// FeaturesLT applies the LT predicate on the "features" field. +func FeaturesLT(v pq.StringArray) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLT(FieldFeatures, v)) +} + +// FeaturesLTE applies the LTE predicate on the "features" field. +func FeaturesLTE(v pq.StringArray) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLTE(FieldFeatures, v)) +} + +// FeaturesIsNil applies the IsNil predicate on the "features" field. +func FeaturesIsNil() predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldIsNull(FieldFeatures)) +} + +// FeaturesNotNil applies the NotNil predicate on the "features" field. +func FeaturesNotNil() predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNotNull(FieldFeatures)) +} + +// CostBasisEQ applies the EQ predicate on the "cost_basis" field. +func CostBasisEQ(v alpacadecimal.Decimal) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldCostBasis, v)) +} + +// CostBasisNEQ applies the NEQ predicate on the "cost_basis" field. +func CostBasisNEQ(v alpacadecimal.Decimal) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNEQ(FieldCostBasis, v)) +} + +// CostBasisIn applies the In predicate on the "cost_basis" field. +func CostBasisIn(vs ...alpacadecimal.Decimal) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldIn(FieldCostBasis, vs...)) +} + +// CostBasisNotIn applies the NotIn predicate on the "cost_basis" field. +func CostBasisNotIn(vs ...alpacadecimal.Decimal) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNotIn(FieldCostBasis, vs...)) +} + +// CostBasisGT applies the GT predicate on the "cost_basis" field. +func CostBasisGT(v alpacadecimal.Decimal) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGT(FieldCostBasis, v)) +} + +// CostBasisGTE applies the GTE predicate on the "cost_basis" field. +func CostBasisGTE(v alpacadecimal.Decimal) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGTE(FieldCostBasis, v)) +} + +// CostBasisLT applies the LT predicate on the "cost_basis" field. +func CostBasisLT(v alpacadecimal.Decimal) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLT(FieldCostBasis, v)) +} + +// CostBasisLTE applies the LTE predicate on the "cost_basis" field. +func CostBasisLTE(v alpacadecimal.Decimal) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLTE(FieldCostBasis, v)) +} + +// CostBasisIsNil applies the IsNil predicate on the "cost_basis" field. +func CostBasisIsNil() predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldIsNull(FieldCostBasis)) +} + +// CostBasisNotNil applies the NotNil predicate on the "cost_basis" field. +func CostBasisNotNil() predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNotNull(FieldCostBasis)) +} + +// CreditPriorityEQ applies the EQ predicate on the "credit_priority" field. +func CreditPriorityEQ(v int) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldCreditPriority, v)) +} + +// CreditPriorityNEQ applies the NEQ predicate on the "credit_priority" field. +func CreditPriorityNEQ(v int) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNEQ(FieldCreditPriority, v)) +} + +// CreditPriorityIn applies the In predicate on the "credit_priority" field. +func CreditPriorityIn(vs ...int) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldIn(FieldCreditPriority, vs...)) +} + +// CreditPriorityNotIn applies the NotIn predicate on the "credit_priority" field. +func CreditPriorityNotIn(vs ...int) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNotIn(FieldCreditPriority, vs...)) +} + +// CreditPriorityGT applies the GT predicate on the "credit_priority" field. +func CreditPriorityGT(v int) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGT(FieldCreditPriority, v)) +} + +// CreditPriorityGTE applies the GTE predicate on the "credit_priority" field. +func CreditPriorityGTE(v int) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldGTE(FieldCreditPriority, v)) +} + +// CreditPriorityLT applies the LT predicate on the "credit_priority" field. +func CreditPriorityLT(v int) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLT(FieldCreditPriority, v)) +} + +// CreditPriorityLTE applies the LTE predicate on the "credit_priority" field. +func CreditPriorityLTE(v int) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldLTE(FieldCreditPriority, v)) +} + +// CreditPriorityIsNil applies the IsNil predicate on the "credit_priority" field. +func CreditPriorityIsNil() predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldIsNull(FieldCreditPriority)) +} + +// CreditPriorityNotNil applies the NotNil predicate on the "credit_priority" field. +func CreditPriorityNotNil() predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNotNull(FieldCreditPriority)) +} + +// TransactionAuthorizationStatusEQ applies the EQ predicate on the "transaction_authorization_status" field. +func TransactionAuthorizationStatusEQ(v ledger.TransactionAuthorizationStatus) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldEQ(FieldTransactionAuthorizationStatus, vc)) +} + +// TransactionAuthorizationStatusNEQ applies the NEQ predicate on the "transaction_authorization_status" field. +func TransactionAuthorizationStatusNEQ(v ledger.TransactionAuthorizationStatus) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldNEQ(FieldTransactionAuthorizationStatus, vc)) +} + +// TransactionAuthorizationStatusIn applies the In predicate on the "transaction_authorization_status" field. +func TransactionAuthorizationStatusIn(vs ...ledger.TransactionAuthorizationStatus) predicate.LedgerSubAccountRoute { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.LedgerSubAccountRoute(sql.FieldIn(FieldTransactionAuthorizationStatus, v...)) +} + +// TransactionAuthorizationStatusNotIn applies the NotIn predicate on the "transaction_authorization_status" field. +func TransactionAuthorizationStatusNotIn(vs ...ledger.TransactionAuthorizationStatus) predicate.LedgerSubAccountRoute { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.LedgerSubAccountRoute(sql.FieldNotIn(FieldTransactionAuthorizationStatus, v...)) +} + +// TransactionAuthorizationStatusGT applies the GT predicate on the "transaction_authorization_status" field. +func TransactionAuthorizationStatusGT(v ledger.TransactionAuthorizationStatus) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldGT(FieldTransactionAuthorizationStatus, vc)) +} + +// TransactionAuthorizationStatusGTE applies the GTE predicate on the "transaction_authorization_status" field. +func TransactionAuthorizationStatusGTE(v ledger.TransactionAuthorizationStatus) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldGTE(FieldTransactionAuthorizationStatus, vc)) +} + +// TransactionAuthorizationStatusLT applies the LT predicate on the "transaction_authorization_status" field. +func TransactionAuthorizationStatusLT(v ledger.TransactionAuthorizationStatus) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldLT(FieldTransactionAuthorizationStatus, vc)) +} + +// TransactionAuthorizationStatusLTE applies the LTE predicate on the "transaction_authorization_status" field. +func TransactionAuthorizationStatusLTE(v ledger.TransactionAuthorizationStatus) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldLTE(FieldTransactionAuthorizationStatus, vc)) +} + +// TransactionAuthorizationStatusContains applies the Contains predicate on the "transaction_authorization_status" field. +func TransactionAuthorizationStatusContains(v ledger.TransactionAuthorizationStatus) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldContains(FieldTransactionAuthorizationStatus, vc)) +} + +// TransactionAuthorizationStatusHasPrefix applies the HasPrefix predicate on the "transaction_authorization_status" field. +func TransactionAuthorizationStatusHasPrefix(v ledger.TransactionAuthorizationStatus) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldHasPrefix(FieldTransactionAuthorizationStatus, vc)) +} + +// TransactionAuthorizationStatusHasSuffix applies the HasSuffix predicate on the "transaction_authorization_status" field. +func TransactionAuthorizationStatusHasSuffix(v ledger.TransactionAuthorizationStatus) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldHasSuffix(FieldTransactionAuthorizationStatus, vc)) +} + +// TransactionAuthorizationStatusIsNil applies the IsNil predicate on the "transaction_authorization_status" field. +func TransactionAuthorizationStatusIsNil() predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldIsNull(FieldTransactionAuthorizationStatus)) +} + +// TransactionAuthorizationStatusNotNil applies the NotNil predicate on the "transaction_authorization_status" field. +func TransactionAuthorizationStatusNotNil() predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.FieldNotNull(FieldTransactionAuthorizationStatus)) +} + +// TransactionAuthorizationStatusEqualFold applies the EqualFold predicate on the "transaction_authorization_status" field. +func TransactionAuthorizationStatusEqualFold(v ledger.TransactionAuthorizationStatus) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldEqualFold(FieldTransactionAuthorizationStatus, vc)) +} + +// TransactionAuthorizationStatusContainsFold applies the ContainsFold predicate on the "transaction_authorization_status" field. +func TransactionAuthorizationStatusContainsFold(v ledger.TransactionAuthorizationStatus) predicate.LedgerSubAccountRoute { + vc := string(v) + return predicate.LedgerSubAccountRoute(sql.FieldContainsFold(FieldTransactionAuthorizationStatus, vc)) +} + +// HasAccount applies the HasEdge predicate on the "account" edge. +func HasAccount() predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, AccountTable, AccountColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasAccountWith applies the HasEdge predicate on the "account" edge with a given conditions (other predicates). +func HasAccountWith(preds ...predicate.LedgerAccount) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(func(s *sql.Selector) { + step := newAccountStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSubAccounts applies the HasEdge predicate on the "sub_accounts" edge. +func HasSubAccounts() predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SubAccountsTable, SubAccountsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubAccountsWith applies the HasEdge predicate on the "sub_accounts" edge with a given conditions (other predicates). +func HasSubAccountsWith(preds ...predicate.LedgerSubAccount) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(func(s *sql.Selector) { + step := newSubAccountsStep() + 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.LedgerSubAccountRoute) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LedgerSubAccountRoute) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LedgerSubAccountRoute) predicate.LedgerSubAccountRoute { + return predicate.LedgerSubAccountRoute(sql.NotPredicates(p)) +} diff --git a/ent/db/ledgersubaccountroute_create.go b/ent/db/ledgersubaccountroute_create.go new file mode 100644 index 0000000000000000000000000000000000000000..4ebc10b0c3cd94074061ed42f4323c94481f5646 --- /dev/null +++ b/ent/db/ledgersubaccountroute_create.go @@ -0,0 +1,937 @@ +// 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/lib/pq" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccountroute" + "github.com/openmeterio/openmeter/openmeter/ledger" +) + +// LedgerSubAccountRouteCreate is the builder for creating a LedgerSubAccountRoute entity. +type LedgerSubAccountRouteCreate struct { + config + mutation *LedgerSubAccountRouteMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *LedgerSubAccountRouteCreate) SetNamespace(v string) *LedgerSubAccountRouteCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *LedgerSubAccountRouteCreate) SetCreatedAt(v time.Time) *LedgerSubAccountRouteCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *LedgerSubAccountRouteCreate) SetNillableCreatedAt(v *time.Time) *LedgerSubAccountRouteCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *LedgerSubAccountRouteCreate) SetUpdatedAt(v time.Time) *LedgerSubAccountRouteCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *LedgerSubAccountRouteCreate) SetNillableUpdatedAt(v *time.Time) *LedgerSubAccountRouteCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *LedgerSubAccountRouteCreate) SetDeletedAt(v time.Time) *LedgerSubAccountRouteCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *LedgerSubAccountRouteCreate) SetNillableDeletedAt(v *time.Time) *LedgerSubAccountRouteCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetAccountID sets the "account_id" field. +func (_c *LedgerSubAccountRouteCreate) SetAccountID(v string) *LedgerSubAccountRouteCreate { + _c.mutation.SetAccountID(v) + return _c +} + +// SetRoutingKeyVersion sets the "routing_key_version" field. +func (_c *LedgerSubAccountRouteCreate) SetRoutingKeyVersion(v ledger.RoutingKeyVersion) *LedgerSubAccountRouteCreate { + _c.mutation.SetRoutingKeyVersion(v) + return _c +} + +// SetRoutingKey sets the "routing_key" field. +func (_c *LedgerSubAccountRouteCreate) SetRoutingKey(v string) *LedgerSubAccountRouteCreate { + _c.mutation.SetRoutingKey(v) + return _c +} + +// SetCurrency sets the "currency" field. +func (_c *LedgerSubAccountRouteCreate) SetCurrency(v string) *LedgerSubAccountRouteCreate { + _c.mutation.SetCurrency(v) + return _c +} + +// SetTaxCode sets the "tax_code" field. +func (_c *LedgerSubAccountRouteCreate) SetTaxCode(v string) *LedgerSubAccountRouteCreate { + _c.mutation.SetTaxCode(v) + return _c +} + +// SetNillableTaxCode sets the "tax_code" field if the given value is not nil. +func (_c *LedgerSubAccountRouteCreate) SetNillableTaxCode(v *string) *LedgerSubAccountRouteCreate { + if v != nil { + _c.SetTaxCode(*v) + } + return _c +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (_c *LedgerSubAccountRouteCreate) SetTaxBehavior(v ledger.TaxBehavior) *LedgerSubAccountRouteCreate { + _c.mutation.SetTaxBehavior(v) + return _c +} + +// SetNillableTaxBehavior sets the "tax_behavior" field if the given value is not nil. +func (_c *LedgerSubAccountRouteCreate) SetNillableTaxBehavior(v *ledger.TaxBehavior) *LedgerSubAccountRouteCreate { + if v != nil { + _c.SetTaxBehavior(*v) + } + return _c +} + +// SetFeatures sets the "features" field. +func (_c *LedgerSubAccountRouteCreate) SetFeatures(v pq.StringArray) *LedgerSubAccountRouteCreate { + _c.mutation.SetFeatures(v) + return _c +} + +// SetCostBasis sets the "cost_basis" field. +func (_c *LedgerSubAccountRouteCreate) SetCostBasis(v alpacadecimal.Decimal) *LedgerSubAccountRouteCreate { + _c.mutation.SetCostBasis(v) + return _c +} + +// SetNillableCostBasis sets the "cost_basis" field if the given value is not nil. +func (_c *LedgerSubAccountRouteCreate) SetNillableCostBasis(v *alpacadecimal.Decimal) *LedgerSubAccountRouteCreate { + if v != nil { + _c.SetCostBasis(*v) + } + return _c +} + +// SetCreditPriority sets the "credit_priority" field. +func (_c *LedgerSubAccountRouteCreate) SetCreditPriority(v int) *LedgerSubAccountRouteCreate { + _c.mutation.SetCreditPriority(v) + return _c +} + +// SetNillableCreditPriority sets the "credit_priority" field if the given value is not nil. +func (_c *LedgerSubAccountRouteCreate) SetNillableCreditPriority(v *int) *LedgerSubAccountRouteCreate { + if v != nil { + _c.SetCreditPriority(*v) + } + return _c +} + +// SetTransactionAuthorizationStatus sets the "transaction_authorization_status" field. +func (_c *LedgerSubAccountRouteCreate) SetTransactionAuthorizationStatus(v ledger.TransactionAuthorizationStatus) *LedgerSubAccountRouteCreate { + _c.mutation.SetTransactionAuthorizationStatus(v) + return _c +} + +// SetNillableTransactionAuthorizationStatus sets the "transaction_authorization_status" field if the given value is not nil. +func (_c *LedgerSubAccountRouteCreate) SetNillableTransactionAuthorizationStatus(v *ledger.TransactionAuthorizationStatus) *LedgerSubAccountRouteCreate { + if v != nil { + _c.SetTransactionAuthorizationStatus(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *LedgerSubAccountRouteCreate) SetID(v string) *LedgerSubAccountRouteCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *LedgerSubAccountRouteCreate) SetNillableID(v *string) *LedgerSubAccountRouteCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetAccount sets the "account" edge to the LedgerAccount entity. +func (_c *LedgerSubAccountRouteCreate) SetAccount(v *LedgerAccount) *LedgerSubAccountRouteCreate { + return _c.SetAccountID(v.ID) +} + +// AddSubAccountIDs adds the "sub_accounts" edge to the LedgerSubAccount entity by IDs. +func (_c *LedgerSubAccountRouteCreate) AddSubAccountIDs(ids ...string) *LedgerSubAccountRouteCreate { + _c.mutation.AddSubAccountIDs(ids...) + return _c +} + +// AddSubAccounts adds the "sub_accounts" edges to the LedgerSubAccount entity. +func (_c *LedgerSubAccountRouteCreate) AddSubAccounts(v ...*LedgerSubAccount) *LedgerSubAccountRouteCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddSubAccountIDs(ids...) +} + +// Mutation returns the LedgerSubAccountRouteMutation object of the builder. +func (_c *LedgerSubAccountRouteCreate) Mutation() *LedgerSubAccountRouteMutation { + return _c.mutation +} + +// Save creates the LedgerSubAccountRoute in the database. +func (_c *LedgerSubAccountRouteCreate) Save(ctx context.Context) (*LedgerSubAccountRoute, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *LedgerSubAccountRouteCreate) SaveX(ctx context.Context) *LedgerSubAccountRoute { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LedgerSubAccountRouteCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LedgerSubAccountRouteCreate) 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 *LedgerSubAccountRouteCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := ledgersubaccountroute.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := ledgersubaccountroute.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := ledgersubaccountroute.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *LedgerSubAccountRouteCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "LedgerSubAccountRoute.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := ledgersubaccountroute.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "LedgerSubAccountRoute.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "LedgerSubAccountRoute.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "LedgerSubAccountRoute.updated_at"`)} + } + if _, ok := _c.mutation.AccountID(); !ok { + return &ValidationError{Name: "account_id", err: errors.New(`db: missing required field "LedgerSubAccountRoute.account_id"`)} + } + if _, ok := _c.mutation.RoutingKeyVersion(); !ok { + return &ValidationError{Name: "routing_key_version", err: errors.New(`db: missing required field "LedgerSubAccountRoute.routing_key_version"`)} + } + if v, ok := _c.mutation.RoutingKeyVersion(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "routing_key_version", err: fmt.Errorf(`db: validator failed for field "LedgerSubAccountRoute.routing_key_version": %w`, err)} + } + } + if _, ok := _c.mutation.RoutingKey(); !ok { + return &ValidationError{Name: "routing_key", err: errors.New(`db: missing required field "LedgerSubAccountRoute.routing_key"`)} + } + if _, ok := _c.mutation.Currency(); !ok { + return &ValidationError{Name: "currency", err: errors.New(`db: missing required field "LedgerSubAccountRoute.currency"`)} + } + if v, ok := _c.mutation.TaxBehavior(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "tax_behavior", err: fmt.Errorf(`db: validator failed for field "LedgerSubAccountRoute.tax_behavior": %w`, err)} + } + } + if v, ok := _c.mutation.TransactionAuthorizationStatus(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "transaction_authorization_status", err: fmt.Errorf(`db: validator failed for field "LedgerSubAccountRoute.transaction_authorization_status": %w`, err)} + } + } + if len(_c.mutation.AccountIDs()) == 0 { + return &ValidationError{Name: "account", err: errors.New(`db: missing required edge "LedgerSubAccountRoute.account"`)} + } + return nil +} + +func (_c *LedgerSubAccountRouteCreate) sqlSave(ctx context.Context) (*LedgerSubAccountRoute, 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 LedgerSubAccountRoute.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *LedgerSubAccountRouteCreate) createSpec() (*LedgerSubAccountRoute, *sqlgraph.CreateSpec) { + var ( + _node = &LedgerSubAccountRoute{config: _c.config} + _spec = sqlgraph.NewCreateSpec(ledgersubaccountroute.Table, sqlgraph.NewFieldSpec(ledgersubaccountroute.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(ledgersubaccountroute.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(ledgersubaccountroute.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(ledgersubaccountroute.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(ledgersubaccountroute.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.RoutingKeyVersion(); ok { + _spec.SetField(ledgersubaccountroute.FieldRoutingKeyVersion, field.TypeString, value) + _node.RoutingKeyVersion = value + } + if value, ok := _c.mutation.RoutingKey(); ok { + _spec.SetField(ledgersubaccountroute.FieldRoutingKey, field.TypeString, value) + _node.RoutingKey = value + } + if value, ok := _c.mutation.Currency(); ok { + _spec.SetField(ledgersubaccountroute.FieldCurrency, field.TypeString, value) + _node.Currency = value + } + if value, ok := _c.mutation.TaxCode(); ok { + _spec.SetField(ledgersubaccountroute.FieldTaxCode, field.TypeString, value) + _node.TaxCode = &value + } + if value, ok := _c.mutation.TaxBehavior(); ok { + _spec.SetField(ledgersubaccountroute.FieldTaxBehavior, field.TypeString, value) + _node.TaxBehavior = &value + } + if value, ok := _c.mutation.Features(); ok { + _spec.SetField(ledgersubaccountroute.FieldFeatures, field.TypeOther, value) + _node.Features = value + } + if value, ok := _c.mutation.CostBasis(); ok { + _spec.SetField(ledgersubaccountroute.FieldCostBasis, field.TypeOther, value) + _node.CostBasis = &value + } + if value, ok := _c.mutation.CreditPriority(); ok { + _spec.SetField(ledgersubaccountroute.FieldCreditPriority, field.TypeInt, value) + _node.CreditPriority = &value + } + if value, ok := _c.mutation.TransactionAuthorizationStatus(); ok { + _spec.SetField(ledgersubaccountroute.FieldTransactionAuthorizationStatus, field.TypeString, value) + _node.TransactionAuthorizationStatus = &value + } + if nodes := _c.mutation.AccountIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: ledgersubaccountroute.AccountTable, + Columns: []string{ledgersubaccountroute.AccountColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgeraccount.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.AccountID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.SubAccountsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccountroute.SubAccountsTable, + Columns: []string{ledgersubaccountroute.SubAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccount.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.LedgerSubAccountRoute.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.LedgerSubAccountRouteUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *LedgerSubAccountRouteCreate) OnConflict(opts ...sql.ConflictOption) *LedgerSubAccountRouteUpsertOne { + _c.conflict = opts + return &LedgerSubAccountRouteUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.LedgerSubAccountRoute.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *LedgerSubAccountRouteCreate) OnConflictColumns(columns ...string) *LedgerSubAccountRouteUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &LedgerSubAccountRouteUpsertOne{ + create: _c, + } +} + +type ( + // LedgerSubAccountRouteUpsertOne is the builder for "upsert"-ing + // one LedgerSubAccountRoute node. + LedgerSubAccountRouteUpsertOne struct { + create *LedgerSubAccountRouteCreate + } + + // LedgerSubAccountRouteUpsert is the "OnConflict" setter. + LedgerSubAccountRouteUpsert struct { + *sql.UpdateSet + } +) + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerSubAccountRouteUpsert) SetUpdatedAt(v time.Time) *LedgerSubAccountRouteUpsert { + u.Set(ledgersubaccountroute.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerSubAccountRouteUpsert) UpdateUpdatedAt() *LedgerSubAccountRouteUpsert { + u.SetExcluded(ledgersubaccountroute.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerSubAccountRouteUpsert) SetDeletedAt(v time.Time) *LedgerSubAccountRouteUpsert { + u.Set(ledgersubaccountroute.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerSubAccountRouteUpsert) UpdateDeletedAt() *LedgerSubAccountRouteUpsert { + u.SetExcluded(ledgersubaccountroute.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerSubAccountRouteUpsert) ClearDeletedAt() *LedgerSubAccountRouteUpsert { + u.SetNull(ledgersubaccountroute.FieldDeletedAt) + 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.LedgerSubAccountRoute.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(ledgersubaccountroute.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LedgerSubAccountRouteUpsertOne) UpdateNewValues() *LedgerSubAccountRouteUpsertOne { + 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(ledgersubaccountroute.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(ledgersubaccountroute.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(ledgersubaccountroute.FieldCreatedAt) + } + if _, exists := u.create.mutation.AccountID(); exists { + s.SetIgnore(ledgersubaccountroute.FieldAccountID) + } + if _, exists := u.create.mutation.RoutingKeyVersion(); exists { + s.SetIgnore(ledgersubaccountroute.FieldRoutingKeyVersion) + } + if _, exists := u.create.mutation.RoutingKey(); exists { + s.SetIgnore(ledgersubaccountroute.FieldRoutingKey) + } + if _, exists := u.create.mutation.Currency(); exists { + s.SetIgnore(ledgersubaccountroute.FieldCurrency) + } + if _, exists := u.create.mutation.TaxCode(); exists { + s.SetIgnore(ledgersubaccountroute.FieldTaxCode) + } + if _, exists := u.create.mutation.TaxBehavior(); exists { + s.SetIgnore(ledgersubaccountroute.FieldTaxBehavior) + } + if _, exists := u.create.mutation.Features(); exists { + s.SetIgnore(ledgersubaccountroute.FieldFeatures) + } + if _, exists := u.create.mutation.CostBasis(); exists { + s.SetIgnore(ledgersubaccountroute.FieldCostBasis) + } + if _, exists := u.create.mutation.CreditPriority(); exists { + s.SetIgnore(ledgersubaccountroute.FieldCreditPriority) + } + if _, exists := u.create.mutation.TransactionAuthorizationStatus(); exists { + s.SetIgnore(ledgersubaccountroute.FieldTransactionAuthorizationStatus) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.LedgerSubAccountRoute.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LedgerSubAccountRouteUpsertOne) Ignore() *LedgerSubAccountRouteUpsertOne { + 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 *LedgerSubAccountRouteUpsertOne) DoNothing() *LedgerSubAccountRouteUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LedgerSubAccountRouteCreate.OnConflict +// documentation for more info. +func (u *LedgerSubAccountRouteUpsertOne) Update(set func(*LedgerSubAccountRouteUpsert)) *LedgerSubAccountRouteUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LedgerSubAccountRouteUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerSubAccountRouteUpsertOne) SetUpdatedAt(v time.Time) *LedgerSubAccountRouteUpsertOne { + return u.Update(func(s *LedgerSubAccountRouteUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerSubAccountRouteUpsertOne) UpdateUpdatedAt() *LedgerSubAccountRouteUpsertOne { + return u.Update(func(s *LedgerSubAccountRouteUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerSubAccountRouteUpsertOne) SetDeletedAt(v time.Time) *LedgerSubAccountRouteUpsertOne { + return u.Update(func(s *LedgerSubAccountRouteUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerSubAccountRouteUpsertOne) UpdateDeletedAt() *LedgerSubAccountRouteUpsertOne { + return u.Update(func(s *LedgerSubAccountRouteUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerSubAccountRouteUpsertOne) ClearDeletedAt() *LedgerSubAccountRouteUpsertOne { + return u.Update(func(s *LedgerSubAccountRouteUpsert) { + s.ClearDeletedAt() + }) +} + +// Exec executes the query. +func (u *LedgerSubAccountRouteUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for LedgerSubAccountRouteCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LedgerSubAccountRouteUpsertOne) 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 *LedgerSubAccountRouteUpsertOne) 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: LedgerSubAccountRouteUpsertOne.ID is not supported by MySQL driver. Use LedgerSubAccountRouteUpsertOne.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 *LedgerSubAccountRouteUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// LedgerSubAccountRouteCreateBulk is the builder for creating many LedgerSubAccountRoute entities in bulk. +type LedgerSubAccountRouteCreateBulk struct { + config + err error + builders []*LedgerSubAccountRouteCreate + conflict []sql.ConflictOption +} + +// Save creates the LedgerSubAccountRoute entities in the database. +func (_c *LedgerSubAccountRouteCreateBulk) Save(ctx context.Context) ([]*LedgerSubAccountRoute, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*LedgerSubAccountRoute, 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.(*LedgerSubAccountRouteMutation) + 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 *LedgerSubAccountRouteCreateBulk) SaveX(ctx context.Context) []*LedgerSubAccountRoute { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LedgerSubAccountRouteCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LedgerSubAccountRouteCreateBulk) 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.LedgerSubAccountRoute.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.LedgerSubAccountRouteUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *LedgerSubAccountRouteCreateBulk) OnConflict(opts ...sql.ConflictOption) *LedgerSubAccountRouteUpsertBulk { + _c.conflict = opts + return &LedgerSubAccountRouteUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.LedgerSubAccountRoute.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *LedgerSubAccountRouteCreateBulk) OnConflictColumns(columns ...string) *LedgerSubAccountRouteUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &LedgerSubAccountRouteUpsertBulk{ + create: _c, + } +} + +// LedgerSubAccountRouteUpsertBulk is the builder for "upsert"-ing +// a bulk of LedgerSubAccountRoute nodes. +type LedgerSubAccountRouteUpsertBulk struct { + create *LedgerSubAccountRouteCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.LedgerSubAccountRoute.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(ledgersubaccountroute.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LedgerSubAccountRouteUpsertBulk) UpdateNewValues() *LedgerSubAccountRouteUpsertBulk { + 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(ledgersubaccountroute.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(ledgersubaccountroute.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(ledgersubaccountroute.FieldCreatedAt) + } + if _, exists := b.mutation.AccountID(); exists { + s.SetIgnore(ledgersubaccountroute.FieldAccountID) + } + if _, exists := b.mutation.RoutingKeyVersion(); exists { + s.SetIgnore(ledgersubaccountroute.FieldRoutingKeyVersion) + } + if _, exists := b.mutation.RoutingKey(); exists { + s.SetIgnore(ledgersubaccountroute.FieldRoutingKey) + } + if _, exists := b.mutation.Currency(); exists { + s.SetIgnore(ledgersubaccountroute.FieldCurrency) + } + if _, exists := b.mutation.TaxCode(); exists { + s.SetIgnore(ledgersubaccountroute.FieldTaxCode) + } + if _, exists := b.mutation.TaxBehavior(); exists { + s.SetIgnore(ledgersubaccountroute.FieldTaxBehavior) + } + if _, exists := b.mutation.Features(); exists { + s.SetIgnore(ledgersubaccountroute.FieldFeatures) + } + if _, exists := b.mutation.CostBasis(); exists { + s.SetIgnore(ledgersubaccountroute.FieldCostBasis) + } + if _, exists := b.mutation.CreditPriority(); exists { + s.SetIgnore(ledgersubaccountroute.FieldCreditPriority) + } + if _, exists := b.mutation.TransactionAuthorizationStatus(); exists { + s.SetIgnore(ledgersubaccountroute.FieldTransactionAuthorizationStatus) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.LedgerSubAccountRoute.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LedgerSubAccountRouteUpsertBulk) Ignore() *LedgerSubAccountRouteUpsertBulk { + 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 *LedgerSubAccountRouteUpsertBulk) DoNothing() *LedgerSubAccountRouteUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LedgerSubAccountRouteCreateBulk.OnConflict +// documentation for more info. +func (u *LedgerSubAccountRouteUpsertBulk) Update(set func(*LedgerSubAccountRouteUpsert)) *LedgerSubAccountRouteUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LedgerSubAccountRouteUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerSubAccountRouteUpsertBulk) SetUpdatedAt(v time.Time) *LedgerSubAccountRouteUpsertBulk { + return u.Update(func(s *LedgerSubAccountRouteUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerSubAccountRouteUpsertBulk) UpdateUpdatedAt() *LedgerSubAccountRouteUpsertBulk { + return u.Update(func(s *LedgerSubAccountRouteUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerSubAccountRouteUpsertBulk) SetDeletedAt(v time.Time) *LedgerSubAccountRouteUpsertBulk { + return u.Update(func(s *LedgerSubAccountRouteUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerSubAccountRouteUpsertBulk) UpdateDeletedAt() *LedgerSubAccountRouteUpsertBulk { + return u.Update(func(s *LedgerSubAccountRouteUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerSubAccountRouteUpsertBulk) ClearDeletedAt() *LedgerSubAccountRouteUpsertBulk { + return u.Update(func(s *LedgerSubAccountRouteUpsert) { + s.ClearDeletedAt() + }) +} + +// Exec executes the query. +func (u *LedgerSubAccountRouteUpsertBulk) 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 LedgerSubAccountRouteCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for LedgerSubAccountRouteCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LedgerSubAccountRouteUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/ledgersubaccountroute_delete.go b/ent/db/ledgersubaccountroute_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..71dfc7e2f68a434f83595e859ce5b1ccc9595579 --- /dev/null +++ b/ent/db/ledgersubaccountroute_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/ledgersubaccountroute" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LedgerSubAccountRouteDelete is the builder for deleting a LedgerSubAccountRoute entity. +type LedgerSubAccountRouteDelete struct { + config + hooks []Hook + mutation *LedgerSubAccountRouteMutation +} + +// Where appends a list predicates to the LedgerSubAccountRouteDelete builder. +func (_d *LedgerSubAccountRouteDelete) Where(ps ...predicate.LedgerSubAccountRoute) *LedgerSubAccountRouteDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *LedgerSubAccountRouteDelete) 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 *LedgerSubAccountRouteDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *LedgerSubAccountRouteDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(ledgersubaccountroute.Table, sqlgraph.NewFieldSpec(ledgersubaccountroute.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 +} + +// LedgerSubAccountRouteDeleteOne is the builder for deleting a single LedgerSubAccountRoute entity. +type LedgerSubAccountRouteDeleteOne struct { + _d *LedgerSubAccountRouteDelete +} + +// Where appends a list predicates to the LedgerSubAccountRouteDelete builder. +func (_d *LedgerSubAccountRouteDeleteOne) Where(ps ...predicate.LedgerSubAccountRoute) *LedgerSubAccountRouteDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *LedgerSubAccountRouteDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{ledgersubaccountroute.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *LedgerSubAccountRouteDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/ledgersubaccountroute_query.go b/ent/db/ledgersubaccountroute_query.go new file mode 100644 index 0000000000000000000000000000000000000000..3a9fbd9705fbeb926be3d66ffe6cf1fcf1fa39da --- /dev/null +++ b/ent/db/ledgersubaccountroute_query.go @@ -0,0 +1,720 @@ +// 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/ledgeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccountroute" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LedgerSubAccountRouteQuery is the builder for querying LedgerSubAccountRoute entities. +type LedgerSubAccountRouteQuery struct { + config + ctx *QueryContext + order []ledgersubaccountroute.OrderOption + inters []Interceptor + predicates []predicate.LedgerSubAccountRoute + withAccount *LedgerAccountQuery + withSubAccounts *LedgerSubAccountQuery + 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 LedgerSubAccountRouteQuery builder. +func (_q *LedgerSubAccountRouteQuery) Where(ps ...predicate.LedgerSubAccountRoute) *LedgerSubAccountRouteQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *LedgerSubAccountRouteQuery) Limit(limit int) *LedgerSubAccountRouteQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *LedgerSubAccountRouteQuery) Offset(offset int) *LedgerSubAccountRouteQuery { + _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 *LedgerSubAccountRouteQuery) Unique(unique bool) *LedgerSubAccountRouteQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *LedgerSubAccountRouteQuery) Order(o ...ledgersubaccountroute.OrderOption) *LedgerSubAccountRouteQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryAccount chains the current query on the "account" edge. +func (_q *LedgerSubAccountRouteQuery) QueryAccount() *LedgerAccountQuery { + query := (&LedgerAccountClient{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(ledgersubaccountroute.Table, ledgersubaccountroute.FieldID, selector), + sqlgraph.To(ledgeraccount.Table, ledgeraccount.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgersubaccountroute.AccountTable, ledgersubaccountroute.AccountColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySubAccounts chains the current query on the "sub_accounts" edge. +func (_q *LedgerSubAccountRouteQuery) QuerySubAccounts() *LedgerSubAccountQuery { + query := (&LedgerSubAccountClient{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(ledgersubaccountroute.Table, ledgersubaccountroute.FieldID, selector), + sqlgraph.To(ledgersubaccount.Table, ledgersubaccount.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgersubaccountroute.SubAccountsTable, ledgersubaccountroute.SubAccountsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first LedgerSubAccountRoute entity from the query. +// Returns a *NotFoundError when no LedgerSubAccountRoute was found. +func (_q *LedgerSubAccountRouteQuery) First(ctx context.Context) (*LedgerSubAccountRoute, 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{ledgersubaccountroute.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *LedgerSubAccountRouteQuery) FirstX(ctx context.Context) *LedgerSubAccountRoute { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LedgerSubAccountRoute ID from the query. +// Returns a *NotFoundError when no LedgerSubAccountRoute ID was found. +func (_q *LedgerSubAccountRouteQuery) 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{ledgersubaccountroute.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *LedgerSubAccountRouteQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LedgerSubAccountRoute entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one LedgerSubAccountRoute entity is found. +// Returns a *NotFoundError when no LedgerSubAccountRoute entities are found. +func (_q *LedgerSubAccountRouteQuery) Only(ctx context.Context) (*LedgerSubAccountRoute, 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{ledgersubaccountroute.Label} + default: + return nil, &NotSingularError{ledgersubaccountroute.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *LedgerSubAccountRouteQuery) OnlyX(ctx context.Context) *LedgerSubAccountRoute { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LedgerSubAccountRoute ID in the query. +// Returns a *NotSingularError when more than one LedgerSubAccountRoute ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *LedgerSubAccountRouteQuery) 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{ledgersubaccountroute.Label} + default: + err = &NotSingularError{ledgersubaccountroute.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *LedgerSubAccountRouteQuery) 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 LedgerSubAccountRoutes. +func (_q *LedgerSubAccountRouteQuery) All(ctx context.Context) ([]*LedgerSubAccountRoute, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*LedgerSubAccountRoute, *LedgerSubAccountRouteQuery]() + return withInterceptors[[]*LedgerSubAccountRoute](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *LedgerSubAccountRouteQuery) AllX(ctx context.Context) []*LedgerSubAccountRoute { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LedgerSubAccountRoute IDs. +func (_q *LedgerSubAccountRouteQuery) 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(ledgersubaccountroute.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *LedgerSubAccountRouteQuery) 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 *LedgerSubAccountRouteQuery) 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[*LedgerSubAccountRouteQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *LedgerSubAccountRouteQuery) 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 *LedgerSubAccountRouteQuery) 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 *LedgerSubAccountRouteQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LedgerSubAccountRouteQuery 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 *LedgerSubAccountRouteQuery) Clone() *LedgerSubAccountRouteQuery { + if _q == nil { + return nil + } + return &LedgerSubAccountRouteQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]ledgersubaccountroute.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.LedgerSubAccountRoute{}, _q.predicates...), + withAccount: _q.withAccount.Clone(), + withSubAccounts: _q.withSubAccounts.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithAccount tells the query-builder to eager-load the nodes that are connected to +// the "account" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerSubAccountRouteQuery) WithAccount(opts ...func(*LedgerAccountQuery)) *LedgerSubAccountRouteQuery { + query := (&LedgerAccountClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withAccount = query + return _q +} + +// WithSubAccounts tells the query-builder to eager-load the nodes that are connected to +// the "sub_accounts" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerSubAccountRouteQuery) WithSubAccounts(opts ...func(*LedgerSubAccountQuery)) *LedgerSubAccountRouteQuery { + query := (&LedgerSubAccountClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSubAccounts = 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.LedgerSubAccountRoute.Query(). +// GroupBy(ledgersubaccountroute.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *LedgerSubAccountRouteQuery) GroupBy(field string, fields ...string) *LedgerSubAccountRouteGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &LedgerSubAccountRouteGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = ledgersubaccountroute.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.LedgerSubAccountRoute.Query(). +// Select(ledgersubaccountroute.FieldNamespace). +// Scan(ctx, &v) +func (_q *LedgerSubAccountRouteQuery) Select(fields ...string) *LedgerSubAccountRouteSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &LedgerSubAccountRouteSelect{LedgerSubAccountRouteQuery: _q} + sbuild.label = ledgersubaccountroute.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a LedgerSubAccountRouteSelect configured with the given aggregations. +func (_q *LedgerSubAccountRouteQuery) Aggregate(fns ...AggregateFunc) *LedgerSubAccountRouteSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *LedgerSubAccountRouteQuery) 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 !ledgersubaccountroute.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 *LedgerSubAccountRouteQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*LedgerSubAccountRoute, error) { + var ( + nodes = []*LedgerSubAccountRoute{} + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withAccount != nil, + _q.withSubAccounts != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*LedgerSubAccountRoute).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &LedgerSubAccountRoute{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.withAccount; query != nil { + if err := _q.loadAccount(ctx, query, nodes, nil, + func(n *LedgerSubAccountRoute, e *LedgerAccount) { n.Edges.Account = e }); err != nil { + return nil, err + } + } + if query := _q.withSubAccounts; query != nil { + if err := _q.loadSubAccounts(ctx, query, nodes, + func(n *LedgerSubAccountRoute) { n.Edges.SubAccounts = []*LedgerSubAccount{} }, + func(n *LedgerSubAccountRoute, e *LedgerSubAccount) { + n.Edges.SubAccounts = append(n.Edges.SubAccounts, e) + }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *LedgerSubAccountRouteQuery) loadAccount(ctx context.Context, query *LedgerAccountQuery, nodes []*LedgerSubAccountRoute, init func(*LedgerSubAccountRoute), assign func(*LedgerSubAccountRoute, *LedgerAccount)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*LedgerSubAccountRoute) + for i := range nodes { + fk := nodes[i].AccountID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(ledgeraccount.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 "account_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *LedgerSubAccountRouteQuery) loadSubAccounts(ctx context.Context, query *LedgerSubAccountQuery, nodes []*LedgerSubAccountRoute, init func(*LedgerSubAccountRoute), assign func(*LedgerSubAccountRoute, *LedgerSubAccount)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*LedgerSubAccountRoute) + 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(ledgersubaccount.FieldRouteID) + } + query.Where(predicate.LedgerSubAccount(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(ledgersubaccountroute.SubAccountsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.RouteID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "route_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *LedgerSubAccountRouteQuery) 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 *LedgerSubAccountRouteQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(ledgersubaccountroute.Table, ledgersubaccountroute.Columns, sqlgraph.NewFieldSpec(ledgersubaccountroute.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, ledgersubaccountroute.FieldID) + for i := range fields { + if fields[i] != ledgersubaccountroute.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withAccount != nil { + _spec.Node.AddColumnOnce(ledgersubaccountroute.FieldAccountID) + } + } + 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 *LedgerSubAccountRouteQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(ledgersubaccountroute.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = ledgersubaccountroute.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 *LedgerSubAccountRouteQuery) ForUpdate(opts ...sql.LockOption) *LedgerSubAccountRouteQuery { + 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 *LedgerSubAccountRouteQuery) ForShare(opts ...sql.LockOption) *LedgerSubAccountRouteQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// LedgerSubAccountRouteGroupBy is the group-by builder for LedgerSubAccountRoute entities. +type LedgerSubAccountRouteGroupBy struct { + selector + build *LedgerSubAccountRouteQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *LedgerSubAccountRouteGroupBy) Aggregate(fns ...AggregateFunc) *LedgerSubAccountRouteGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *LedgerSubAccountRouteGroupBy) 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[*LedgerSubAccountRouteQuery, *LedgerSubAccountRouteGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *LedgerSubAccountRouteGroupBy) sqlScan(ctx context.Context, root *LedgerSubAccountRouteQuery, 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) +} + +// LedgerSubAccountRouteSelect is the builder for selecting fields of LedgerSubAccountRoute entities. +type LedgerSubAccountRouteSelect struct { + *LedgerSubAccountRouteQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *LedgerSubAccountRouteSelect) Aggregate(fns ...AggregateFunc) *LedgerSubAccountRouteSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *LedgerSubAccountRouteSelect) 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[*LedgerSubAccountRouteQuery, *LedgerSubAccountRouteSelect](ctx, _s.LedgerSubAccountRouteQuery, _s, _s.inters, v) +} + +func (_s *LedgerSubAccountRouteSelect) sqlScan(ctx context.Context, root *LedgerSubAccountRouteQuery, 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/ent/db/ledgersubaccountroute_update.go b/ent/db/ledgersubaccountroute_update.go new file mode 100644 index 0000000000000000000000000000000000000000..b99d73d6bf77e813547639974a90d1ef9355d235 --- /dev/null +++ b/ent/db/ledgersubaccountroute_update.go @@ -0,0 +1,485 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/ledgersubaccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccountroute" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LedgerSubAccountRouteUpdate is the builder for updating LedgerSubAccountRoute entities. +type LedgerSubAccountRouteUpdate struct { + config + hooks []Hook + mutation *LedgerSubAccountRouteMutation +} + +// Where appends a list predicates to the LedgerSubAccountRouteUpdate builder. +func (_u *LedgerSubAccountRouteUpdate) Where(ps ...predicate.LedgerSubAccountRoute) *LedgerSubAccountRouteUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *LedgerSubAccountRouteUpdate) SetUpdatedAt(v time.Time) *LedgerSubAccountRouteUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *LedgerSubAccountRouteUpdate) SetDeletedAt(v time.Time) *LedgerSubAccountRouteUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *LedgerSubAccountRouteUpdate) SetNillableDeletedAt(v *time.Time) *LedgerSubAccountRouteUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *LedgerSubAccountRouteUpdate) ClearDeletedAt() *LedgerSubAccountRouteUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// AddSubAccountIDs adds the "sub_accounts" edge to the LedgerSubAccount entity by IDs. +func (_u *LedgerSubAccountRouteUpdate) AddSubAccountIDs(ids ...string) *LedgerSubAccountRouteUpdate { + _u.mutation.AddSubAccountIDs(ids...) + return _u +} + +// AddSubAccounts adds the "sub_accounts" edges to the LedgerSubAccount entity. +func (_u *LedgerSubAccountRouteUpdate) AddSubAccounts(v ...*LedgerSubAccount) *LedgerSubAccountRouteUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSubAccountIDs(ids...) +} + +// Mutation returns the LedgerSubAccountRouteMutation object of the builder. +func (_u *LedgerSubAccountRouteUpdate) Mutation() *LedgerSubAccountRouteMutation { + return _u.mutation +} + +// ClearSubAccounts clears all "sub_accounts" edges to the LedgerSubAccount entity. +func (_u *LedgerSubAccountRouteUpdate) ClearSubAccounts() *LedgerSubAccountRouteUpdate { + _u.mutation.ClearSubAccounts() + return _u +} + +// RemoveSubAccountIDs removes the "sub_accounts" edge to LedgerSubAccount entities by IDs. +func (_u *LedgerSubAccountRouteUpdate) RemoveSubAccountIDs(ids ...string) *LedgerSubAccountRouteUpdate { + _u.mutation.RemoveSubAccountIDs(ids...) + return _u +} + +// RemoveSubAccounts removes "sub_accounts" edges to LedgerSubAccount entities. +func (_u *LedgerSubAccountRouteUpdate) RemoveSubAccounts(v ...*LedgerSubAccount) *LedgerSubAccountRouteUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSubAccountIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *LedgerSubAccountRouteUpdate) 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 *LedgerSubAccountRouteUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *LedgerSubAccountRouteUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LedgerSubAccountRouteUpdate) 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 *LedgerSubAccountRouteUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := ledgersubaccountroute.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *LedgerSubAccountRouteUpdate) check() error { + if _u.mutation.AccountCleared() && len(_u.mutation.AccountIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerSubAccountRoute.account"`) + } + return nil +} + +func (_u *LedgerSubAccountRouteUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(ledgersubaccountroute.Table, ledgersubaccountroute.Columns, sqlgraph.NewFieldSpec(ledgersubaccountroute.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(ledgersubaccountroute.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(ledgersubaccountroute.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(ledgersubaccountroute.FieldDeletedAt, field.TypeTime) + } + if _u.mutation.TaxCodeCleared() { + _spec.ClearField(ledgersubaccountroute.FieldTaxCode, field.TypeString) + } + if _u.mutation.TaxBehaviorCleared() { + _spec.ClearField(ledgersubaccountroute.FieldTaxBehavior, field.TypeString) + } + if _u.mutation.FeaturesCleared() { + _spec.ClearField(ledgersubaccountroute.FieldFeatures, field.TypeOther) + } + if _u.mutation.CostBasisCleared() { + _spec.ClearField(ledgersubaccountroute.FieldCostBasis, field.TypeOther) + } + if _u.mutation.CreditPriorityCleared() { + _spec.ClearField(ledgersubaccountroute.FieldCreditPriority, field.TypeInt) + } + if _u.mutation.TransactionAuthorizationStatusCleared() { + _spec.ClearField(ledgersubaccountroute.FieldTransactionAuthorizationStatus, field.TypeString) + } + if _u.mutation.SubAccountsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccountroute.SubAccountsTable, + Columns: []string{ledgersubaccountroute.SubAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccount.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSubAccountsIDs(); len(nodes) > 0 && !_u.mutation.SubAccountsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccountroute.SubAccountsTable, + Columns: []string{ledgersubaccountroute.SubAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccount.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.SubAccountsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccountroute.SubAccountsTable, + Columns: []string{ledgersubaccountroute.SubAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccount.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{ledgersubaccountroute.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// LedgerSubAccountRouteUpdateOne is the builder for updating a single LedgerSubAccountRoute entity. +type LedgerSubAccountRouteUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LedgerSubAccountRouteMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *LedgerSubAccountRouteUpdateOne) SetUpdatedAt(v time.Time) *LedgerSubAccountRouteUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *LedgerSubAccountRouteUpdateOne) SetDeletedAt(v time.Time) *LedgerSubAccountRouteUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *LedgerSubAccountRouteUpdateOne) SetNillableDeletedAt(v *time.Time) *LedgerSubAccountRouteUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *LedgerSubAccountRouteUpdateOne) ClearDeletedAt() *LedgerSubAccountRouteUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// AddSubAccountIDs adds the "sub_accounts" edge to the LedgerSubAccount entity by IDs. +func (_u *LedgerSubAccountRouteUpdateOne) AddSubAccountIDs(ids ...string) *LedgerSubAccountRouteUpdateOne { + _u.mutation.AddSubAccountIDs(ids...) + return _u +} + +// AddSubAccounts adds the "sub_accounts" edges to the LedgerSubAccount entity. +func (_u *LedgerSubAccountRouteUpdateOne) AddSubAccounts(v ...*LedgerSubAccount) *LedgerSubAccountRouteUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSubAccountIDs(ids...) +} + +// Mutation returns the LedgerSubAccountRouteMutation object of the builder. +func (_u *LedgerSubAccountRouteUpdateOne) Mutation() *LedgerSubAccountRouteMutation { + return _u.mutation +} + +// ClearSubAccounts clears all "sub_accounts" edges to the LedgerSubAccount entity. +func (_u *LedgerSubAccountRouteUpdateOne) ClearSubAccounts() *LedgerSubAccountRouteUpdateOne { + _u.mutation.ClearSubAccounts() + return _u +} + +// RemoveSubAccountIDs removes the "sub_accounts" edge to LedgerSubAccount entities by IDs. +func (_u *LedgerSubAccountRouteUpdateOne) RemoveSubAccountIDs(ids ...string) *LedgerSubAccountRouteUpdateOne { + _u.mutation.RemoveSubAccountIDs(ids...) + return _u +} + +// RemoveSubAccounts removes "sub_accounts" edges to LedgerSubAccount entities. +func (_u *LedgerSubAccountRouteUpdateOne) RemoveSubAccounts(v ...*LedgerSubAccount) *LedgerSubAccountRouteUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSubAccountIDs(ids...) +} + +// Where appends a list predicates to the LedgerSubAccountRouteUpdate builder. +func (_u *LedgerSubAccountRouteUpdateOne) Where(ps ...predicate.LedgerSubAccountRoute) *LedgerSubAccountRouteUpdateOne { + _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 *LedgerSubAccountRouteUpdateOne) Select(field string, fields ...string) *LedgerSubAccountRouteUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated LedgerSubAccountRoute entity. +func (_u *LedgerSubAccountRouteUpdateOne) Save(ctx context.Context) (*LedgerSubAccountRoute, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *LedgerSubAccountRouteUpdateOne) SaveX(ctx context.Context) *LedgerSubAccountRoute { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *LedgerSubAccountRouteUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LedgerSubAccountRouteUpdateOne) 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 *LedgerSubAccountRouteUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := ledgersubaccountroute.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *LedgerSubAccountRouteUpdateOne) check() error { + if _u.mutation.AccountCleared() && len(_u.mutation.AccountIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerSubAccountRoute.account"`) + } + return nil +} + +func (_u *LedgerSubAccountRouteUpdateOne) sqlSave(ctx context.Context) (_node *LedgerSubAccountRoute, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(ledgersubaccountroute.Table, ledgersubaccountroute.Columns, sqlgraph.NewFieldSpec(ledgersubaccountroute.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "LedgerSubAccountRoute.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, ledgersubaccountroute.FieldID) + for _, f := range fields { + if !ledgersubaccountroute.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != ledgersubaccountroute.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(ledgersubaccountroute.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(ledgersubaccountroute.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(ledgersubaccountroute.FieldDeletedAt, field.TypeTime) + } + if _u.mutation.TaxCodeCleared() { + _spec.ClearField(ledgersubaccountroute.FieldTaxCode, field.TypeString) + } + if _u.mutation.TaxBehaviorCleared() { + _spec.ClearField(ledgersubaccountroute.FieldTaxBehavior, field.TypeString) + } + if _u.mutation.FeaturesCleared() { + _spec.ClearField(ledgersubaccountroute.FieldFeatures, field.TypeOther) + } + if _u.mutation.CostBasisCleared() { + _spec.ClearField(ledgersubaccountroute.FieldCostBasis, field.TypeOther) + } + if _u.mutation.CreditPriorityCleared() { + _spec.ClearField(ledgersubaccountroute.FieldCreditPriority, field.TypeInt) + } + if _u.mutation.TransactionAuthorizationStatusCleared() { + _spec.ClearField(ledgersubaccountroute.FieldTransactionAuthorizationStatus, field.TypeString) + } + if _u.mutation.SubAccountsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccountroute.SubAccountsTable, + Columns: []string{ledgersubaccountroute.SubAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccount.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSubAccountsIDs(); len(nodes) > 0 && !_u.mutation.SubAccountsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccountroute.SubAccountsTable, + Columns: []string{ledgersubaccountroute.SubAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccount.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.SubAccountsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgersubaccountroute.SubAccountsTable, + Columns: []string{ledgersubaccountroute.SubAccountsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgersubaccount.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &LedgerSubAccountRoute{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{ledgersubaccountroute.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/ent/db/ledgertransaction.go b/ent/db/ledgertransaction.go new file mode 100644 index 0000000000000000000000000000000000000000..11b21a046a0e6fab622d1a076bc3a7abb9c110e1 --- /dev/null +++ b/ent/db/ledgertransaction.go @@ -0,0 +1,256 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/ledgertransaction" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransactiongroup" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerTransaction is the model entity for the LedgerTransaction schema. +type LedgerTransaction 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"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,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"` + // GroupID holds the value of the "group_id" field. + GroupID string `json:"group_id,omitempty"` + // BookedAt holds the value of the "booked_at" field. + BookedAt time.Time `json:"booked_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the LedgerTransactionQuery when eager-loading is set. + Edges LedgerTransactionEdges `json:"edges"` + selectValues sql.SelectValues +} + +// LedgerTransactionEdges holds the relations/edges for other nodes in the graph. +type LedgerTransactionEdges struct { + // Group holds the value of the group edge. + Group *LedgerTransactionGroup `json:"group,omitempty"` + // Entries holds the value of the entries edge. + Entries []*LedgerEntry `json:"entries,omitempty"` + // SourceBreakageRecords holds the value of the source_breakage_records edge. + SourceBreakageRecords []*LedgerBreakageRecord `json:"source_breakage_records,omitempty"` + // BreakageRecords holds the value of the breakage_records edge. + BreakageRecords []*LedgerBreakageRecord `json:"breakage_records,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [4]bool +} + +// GroupOrErr returns the Group value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e LedgerTransactionEdges) GroupOrErr() (*LedgerTransactionGroup, error) { + if e.Group != nil { + return e.Group, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: ledgertransactiongroup.Label} + } + return nil, &NotLoadedError{edge: "group"} +} + +// EntriesOrErr returns the Entries value or an error if the edge +// was not loaded in eager-loading. +func (e LedgerTransactionEdges) EntriesOrErr() ([]*LedgerEntry, error) { + if e.loadedTypes[1] { + return e.Entries, nil + } + return nil, &NotLoadedError{edge: "entries"} +} + +// SourceBreakageRecordsOrErr returns the SourceBreakageRecords value or an error if the edge +// was not loaded in eager-loading. +func (e LedgerTransactionEdges) SourceBreakageRecordsOrErr() ([]*LedgerBreakageRecord, error) { + if e.loadedTypes[2] { + return e.SourceBreakageRecords, nil + } + return nil, &NotLoadedError{edge: "source_breakage_records"} +} + +// BreakageRecordsOrErr returns the BreakageRecords value or an error if the edge +// was not loaded in eager-loading. +func (e LedgerTransactionEdges) BreakageRecordsOrErr() ([]*LedgerBreakageRecord, error) { + if e.loadedTypes[3] { + return e.BreakageRecords, nil + } + return nil, &NotLoadedError{edge: "breakage_records"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LedgerTransaction) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case ledgertransaction.FieldAnnotations: + values[i] = new([]byte) + case ledgertransaction.FieldID, ledgertransaction.FieldNamespace, ledgertransaction.FieldGroupID: + values[i] = new(sql.NullString) + case ledgertransaction.FieldCreatedAt, ledgertransaction.FieldUpdatedAt, ledgertransaction.FieldDeletedAt, ledgertransaction.FieldBookedAt: + 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 LedgerTransaction fields. +func (_m *LedgerTransaction) 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 ledgertransaction.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 ledgertransaction.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 ledgertransaction.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 ledgertransaction.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 ledgertransaction.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 ledgertransaction.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 ledgertransaction.FieldGroupID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field group_id", values[i]) + } else if value.Valid { + _m.GroupID = value.String + } + case ledgertransaction.FieldBookedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field booked_at", values[i]) + } else if value.Valid { + _m.BookedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the LedgerTransaction. +// This includes values selected through modifiers, order, etc. +func (_m *LedgerTransaction) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryGroup queries the "group" edge of the LedgerTransaction entity. +func (_m *LedgerTransaction) QueryGroup() *LedgerTransactionGroupQuery { + return NewLedgerTransactionClient(_m.config).QueryGroup(_m) +} + +// QueryEntries queries the "entries" edge of the LedgerTransaction entity. +func (_m *LedgerTransaction) QueryEntries() *LedgerEntryQuery { + return NewLedgerTransactionClient(_m.config).QueryEntries(_m) +} + +// QuerySourceBreakageRecords queries the "source_breakage_records" edge of the LedgerTransaction entity. +func (_m *LedgerTransaction) QuerySourceBreakageRecords() *LedgerBreakageRecordQuery { + return NewLedgerTransactionClient(_m.config).QuerySourceBreakageRecords(_m) +} + +// QueryBreakageRecords queries the "breakage_records" edge of the LedgerTransaction entity. +func (_m *LedgerTransaction) QueryBreakageRecords() *LedgerBreakageRecordQuery { + return NewLedgerTransactionClient(_m.config).QueryBreakageRecords(_m) +} + +// Update returns a builder for updating this LedgerTransaction. +// Note that you need to call LedgerTransaction.Unwrap() before calling this method if this LedgerTransaction +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *LedgerTransaction) Update() *LedgerTransactionUpdateOne { + return NewLedgerTransactionClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the LedgerTransaction 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 *LedgerTransaction) Unwrap() *LedgerTransaction { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: LedgerTransaction is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *LedgerTransaction) String() string { + var builder strings.Builder + builder.WriteString("LedgerTransaction(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + 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("group_id=") + builder.WriteString(_m.GroupID) + builder.WriteString(", ") + builder.WriteString("booked_at=") + builder.WriteString(_m.BookedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// LedgerTransactions is a parsable slice of LedgerTransaction. +type LedgerTransactions []*LedgerTransaction diff --git a/ent/db/ledgertransaction/ledgertransaction.go b/ent/db/ledgertransaction/ledgertransaction.go new file mode 100644 index 0000000000000000000000000000000000000000..ea4840e0d4236f7be8dbeee3d5be770f98c26505 --- /dev/null +++ b/ent/db/ledgertransaction/ledgertransaction.go @@ -0,0 +1,219 @@ +// Code generated by ent, DO NOT EDIT. + +package ledgertransaction + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the ledgertransaction type in the database. + Label = "ledger_transaction" + // 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" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // 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" + // FieldGroupID holds the string denoting the group_id field in the database. + FieldGroupID = "group_id" + // FieldBookedAt holds the string denoting the booked_at field in the database. + FieldBookedAt = "booked_at" + // EdgeGroup holds the string denoting the group edge name in mutations. + EdgeGroup = "group" + // EdgeEntries holds the string denoting the entries edge name in mutations. + EdgeEntries = "entries" + // EdgeSourceBreakageRecords holds the string denoting the source_breakage_records edge name in mutations. + EdgeSourceBreakageRecords = "source_breakage_records" + // EdgeBreakageRecords holds the string denoting the breakage_records edge name in mutations. + EdgeBreakageRecords = "breakage_records" + // Table holds the table name of the ledgertransaction in the database. + Table = "ledger_transactions" + // GroupTable is the table that holds the group relation/edge. + GroupTable = "ledger_transactions" + // GroupInverseTable is the table name for the LedgerTransactionGroup entity. + // It exists in this package in order to avoid circular dependency with the "ledgertransactiongroup" package. + GroupInverseTable = "ledger_transaction_groups" + // GroupColumn is the table column denoting the group relation/edge. + GroupColumn = "group_id" + // EntriesTable is the table that holds the entries relation/edge. + EntriesTable = "ledger_entries" + // EntriesInverseTable is the table name for the LedgerEntry entity. + // It exists in this package in order to avoid circular dependency with the "ledgerentry" package. + EntriesInverseTable = "ledger_entries" + // EntriesColumn is the table column denoting the entries relation/edge. + EntriesColumn = "transaction_id" + // SourceBreakageRecordsTable is the table that holds the source_breakage_records relation/edge. + SourceBreakageRecordsTable = "ledger_breakage_records" + // SourceBreakageRecordsInverseTable is the table name for the LedgerBreakageRecord entity. + // It exists in this package in order to avoid circular dependency with the "ledgerbreakagerecord" package. + SourceBreakageRecordsInverseTable = "ledger_breakage_records" + // SourceBreakageRecordsColumn is the table column denoting the source_breakage_records relation/edge. + SourceBreakageRecordsColumn = "source_transaction_id" + // BreakageRecordsTable is the table that holds the breakage_records relation/edge. + BreakageRecordsTable = "ledger_breakage_records" + // BreakageRecordsInverseTable is the table name for the LedgerBreakageRecord entity. + // It exists in this package in order to avoid circular dependency with the "ledgerbreakagerecord" package. + BreakageRecordsInverseTable = "ledger_breakage_records" + // BreakageRecordsColumn is the table column denoting the breakage_records relation/edge. + BreakageRecordsColumn = "breakage_transaction_id" +) + +// Columns holds all SQL columns for ledgertransaction fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldAnnotations, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldGroupID, + FieldBookedAt, +} + +// 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 +) + +// OrderOption defines the ordering options for the LedgerTransaction 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() +} + +// ByGroupID orders the results by the group_id field. +func ByGroupID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldGroupID, opts...).ToFunc() +} + +// ByBookedAt orders the results by the booked_at field. +func ByBookedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBookedAt, opts...).ToFunc() +} + +// ByGroupField orders the results by group field. +func ByGroupField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newGroupStep(), sql.OrderByField(field, opts...)) + } +} + +// ByEntriesCount orders the results by entries count. +func ByEntriesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newEntriesStep(), opts...) + } +} + +// ByEntries orders the results by entries terms. +func ByEntries(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newEntriesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// BySourceBreakageRecordsCount orders the results by source_breakage_records count. +func BySourceBreakageRecordsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newSourceBreakageRecordsStep(), opts...) + } +} + +// BySourceBreakageRecords orders the results by source_breakage_records terms. +func BySourceBreakageRecords(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSourceBreakageRecordsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByBreakageRecordsCount orders the results by breakage_records count. +func ByBreakageRecordsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newBreakageRecordsStep(), opts...) + } +} + +// ByBreakageRecords orders the results by breakage_records terms. +func ByBreakageRecords(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBreakageRecordsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newGroupStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(GroupInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn), + ) +} +func newEntriesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(EntriesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, EntriesTable, EntriesColumn), + ) +} +func newSourceBreakageRecordsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SourceBreakageRecordsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SourceBreakageRecordsTable, SourceBreakageRecordsColumn), + ) +} +func newBreakageRecordsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BreakageRecordsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, BreakageRecordsTable, BreakageRecordsColumn), + ) +} diff --git a/ent/db/ledgertransaction/where.go b/ent/db/ledgertransaction/where.go new file mode 100644 index 0000000000000000000000000000000000000000..c13c6e4b9570188f38c0720718683b314257af56 --- /dev/null +++ b/ent/db/ledgertransaction/where.go @@ -0,0 +1,513 @@ +// Code generated by ent, DO NOT EDIT. + +package ledgertransaction + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(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.LedgerTransaction { + return predicate.LedgerTransaction(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.LedgerTransaction { + return predicate.LedgerTransaction(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.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldEQ(FieldDeletedAt, v)) +} + +// GroupID applies equality check predicate on the "group_id" field. It's identical to GroupIDEQ. +func GroupID(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldEQ(FieldGroupID, v)) +} + +// BookedAt applies equality check predicate on the "booked_at" field. It's identical to BookedAtEQ. +func BookedAt(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldEQ(FieldBookedAt, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldContainsFold(FieldNamespace, v)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldNotNull(FieldAnnotations)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldNotNull(FieldDeletedAt)) +} + +// GroupIDEQ applies the EQ predicate on the "group_id" field. +func GroupIDEQ(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldEQ(FieldGroupID, v)) +} + +// GroupIDNEQ applies the NEQ predicate on the "group_id" field. +func GroupIDNEQ(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldNEQ(FieldGroupID, v)) +} + +// GroupIDIn applies the In predicate on the "group_id" field. +func GroupIDIn(vs ...string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldIn(FieldGroupID, vs...)) +} + +// GroupIDNotIn applies the NotIn predicate on the "group_id" field. +func GroupIDNotIn(vs ...string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldNotIn(FieldGroupID, vs...)) +} + +// GroupIDGT applies the GT predicate on the "group_id" field. +func GroupIDGT(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldGT(FieldGroupID, v)) +} + +// GroupIDGTE applies the GTE predicate on the "group_id" field. +func GroupIDGTE(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldGTE(FieldGroupID, v)) +} + +// GroupIDLT applies the LT predicate on the "group_id" field. +func GroupIDLT(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldLT(FieldGroupID, v)) +} + +// GroupIDLTE applies the LTE predicate on the "group_id" field. +func GroupIDLTE(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldLTE(FieldGroupID, v)) +} + +// GroupIDContains applies the Contains predicate on the "group_id" field. +func GroupIDContains(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldContains(FieldGroupID, v)) +} + +// GroupIDHasPrefix applies the HasPrefix predicate on the "group_id" field. +func GroupIDHasPrefix(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldHasPrefix(FieldGroupID, v)) +} + +// GroupIDHasSuffix applies the HasSuffix predicate on the "group_id" field. +func GroupIDHasSuffix(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldHasSuffix(FieldGroupID, v)) +} + +// GroupIDEqualFold applies the EqualFold predicate on the "group_id" field. +func GroupIDEqualFold(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldEqualFold(FieldGroupID, v)) +} + +// GroupIDContainsFold applies the ContainsFold predicate on the "group_id" field. +func GroupIDContainsFold(v string) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldContainsFold(FieldGroupID, v)) +} + +// BookedAtEQ applies the EQ predicate on the "booked_at" field. +func BookedAtEQ(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldEQ(FieldBookedAt, v)) +} + +// BookedAtNEQ applies the NEQ predicate on the "booked_at" field. +func BookedAtNEQ(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldNEQ(FieldBookedAt, v)) +} + +// BookedAtIn applies the In predicate on the "booked_at" field. +func BookedAtIn(vs ...time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldIn(FieldBookedAt, vs...)) +} + +// BookedAtNotIn applies the NotIn predicate on the "booked_at" field. +func BookedAtNotIn(vs ...time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldNotIn(FieldBookedAt, vs...)) +} + +// BookedAtGT applies the GT predicate on the "booked_at" field. +func BookedAtGT(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldGT(FieldBookedAt, v)) +} + +// BookedAtGTE applies the GTE predicate on the "booked_at" field. +func BookedAtGTE(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldGTE(FieldBookedAt, v)) +} + +// BookedAtLT applies the LT predicate on the "booked_at" field. +func BookedAtLT(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldLT(FieldBookedAt, v)) +} + +// BookedAtLTE applies the LTE predicate on the "booked_at" field. +func BookedAtLTE(v time.Time) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.FieldLTE(FieldBookedAt, v)) +} + +// HasGroup applies the HasEdge predicate on the "group" edge. +func HasGroup() predicate.LedgerTransaction { + return predicate.LedgerTransaction(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasGroupWith applies the HasEdge predicate on the "group" edge with a given conditions (other predicates). +func HasGroupWith(preds ...predicate.LedgerTransactionGroup) predicate.LedgerTransaction { + return predicate.LedgerTransaction(func(s *sql.Selector) { + step := newGroupStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasEntries applies the HasEdge predicate on the "entries" edge. +func HasEntries() predicate.LedgerTransaction { + return predicate.LedgerTransaction(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, EntriesTable, EntriesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasEntriesWith applies the HasEdge predicate on the "entries" edge with a given conditions (other predicates). +func HasEntriesWith(preds ...predicate.LedgerEntry) predicate.LedgerTransaction { + return predicate.LedgerTransaction(func(s *sql.Selector) { + step := newEntriesStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSourceBreakageRecords applies the HasEdge predicate on the "source_breakage_records" edge. +func HasSourceBreakageRecords() predicate.LedgerTransaction { + return predicate.LedgerTransaction(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SourceBreakageRecordsTable, SourceBreakageRecordsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSourceBreakageRecordsWith applies the HasEdge predicate on the "source_breakage_records" edge with a given conditions (other predicates). +func HasSourceBreakageRecordsWith(preds ...predicate.LedgerBreakageRecord) predicate.LedgerTransaction { + return predicate.LedgerTransaction(func(s *sql.Selector) { + step := newSourceBreakageRecordsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasBreakageRecords applies the HasEdge predicate on the "breakage_records" edge. +func HasBreakageRecords() predicate.LedgerTransaction { + return predicate.LedgerTransaction(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, BreakageRecordsTable, BreakageRecordsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBreakageRecordsWith applies the HasEdge predicate on the "breakage_records" edge with a given conditions (other predicates). +func HasBreakageRecordsWith(preds ...predicate.LedgerBreakageRecord) predicate.LedgerTransaction { + return predicate.LedgerTransaction(func(s *sql.Selector) { + step := newBreakageRecordsStep() + 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.LedgerTransaction) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LedgerTransaction) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LedgerTransaction) predicate.LedgerTransaction { + return predicate.LedgerTransaction(sql.NotPredicates(p)) +} diff --git a/ent/db/ledgertransaction_create.go b/ent/db/ledgertransaction_create.go new file mode 100644 index 0000000000000000000000000000000000000000..590c575aeb5d199cdbc95a041bb71ef61c50a176 --- /dev/null +++ b/ent/db/ledgertransaction_create.go @@ -0,0 +1,879 @@ +// 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/ledgerbreakagerecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgerentry" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransaction" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransactiongroup" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerTransactionCreate is the builder for creating a LedgerTransaction entity. +type LedgerTransactionCreate struct { + config + mutation *LedgerTransactionMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *LedgerTransactionCreate) SetNamespace(v string) *LedgerTransactionCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *LedgerTransactionCreate) SetAnnotations(v models.Annotations) *LedgerTransactionCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *LedgerTransactionCreate) SetCreatedAt(v time.Time) *LedgerTransactionCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *LedgerTransactionCreate) SetNillableCreatedAt(v *time.Time) *LedgerTransactionCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *LedgerTransactionCreate) SetUpdatedAt(v time.Time) *LedgerTransactionCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *LedgerTransactionCreate) SetNillableUpdatedAt(v *time.Time) *LedgerTransactionCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *LedgerTransactionCreate) SetDeletedAt(v time.Time) *LedgerTransactionCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *LedgerTransactionCreate) SetNillableDeletedAt(v *time.Time) *LedgerTransactionCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetGroupID sets the "group_id" field. +func (_c *LedgerTransactionCreate) SetGroupID(v string) *LedgerTransactionCreate { + _c.mutation.SetGroupID(v) + return _c +} + +// SetBookedAt sets the "booked_at" field. +func (_c *LedgerTransactionCreate) SetBookedAt(v time.Time) *LedgerTransactionCreate { + _c.mutation.SetBookedAt(v) + return _c +} + +// SetID sets the "id" field. +func (_c *LedgerTransactionCreate) SetID(v string) *LedgerTransactionCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *LedgerTransactionCreate) SetNillableID(v *string) *LedgerTransactionCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetGroup sets the "group" edge to the LedgerTransactionGroup entity. +func (_c *LedgerTransactionCreate) SetGroup(v *LedgerTransactionGroup) *LedgerTransactionCreate { + return _c.SetGroupID(v.ID) +} + +// AddEntryIDs adds the "entries" edge to the LedgerEntry entity by IDs. +func (_c *LedgerTransactionCreate) AddEntryIDs(ids ...string) *LedgerTransactionCreate { + _c.mutation.AddEntryIDs(ids...) + return _c +} + +// AddEntries adds the "entries" edges to the LedgerEntry entity. +func (_c *LedgerTransactionCreate) AddEntries(v ...*LedgerEntry) *LedgerTransactionCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddEntryIDs(ids...) +} + +// AddSourceBreakageRecordIDs adds the "source_breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_c *LedgerTransactionCreate) AddSourceBreakageRecordIDs(ids ...string) *LedgerTransactionCreate { + _c.mutation.AddSourceBreakageRecordIDs(ids...) + return _c +} + +// AddSourceBreakageRecords adds the "source_breakage_records" edges to the LedgerBreakageRecord entity. +func (_c *LedgerTransactionCreate) AddSourceBreakageRecords(v ...*LedgerBreakageRecord) *LedgerTransactionCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddSourceBreakageRecordIDs(ids...) +} + +// AddBreakageRecordIDs adds the "breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_c *LedgerTransactionCreate) AddBreakageRecordIDs(ids ...string) *LedgerTransactionCreate { + _c.mutation.AddBreakageRecordIDs(ids...) + return _c +} + +// AddBreakageRecords adds the "breakage_records" edges to the LedgerBreakageRecord entity. +func (_c *LedgerTransactionCreate) AddBreakageRecords(v ...*LedgerBreakageRecord) *LedgerTransactionCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddBreakageRecordIDs(ids...) +} + +// Mutation returns the LedgerTransactionMutation object of the builder. +func (_c *LedgerTransactionCreate) Mutation() *LedgerTransactionMutation { + return _c.mutation +} + +// Save creates the LedgerTransaction in the database. +func (_c *LedgerTransactionCreate) Save(ctx context.Context) (*LedgerTransaction, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *LedgerTransactionCreate) SaveX(ctx context.Context) *LedgerTransaction { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LedgerTransactionCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LedgerTransactionCreate) 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 *LedgerTransactionCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := ledgertransaction.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := ledgertransaction.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := ledgertransaction.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *LedgerTransactionCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "LedgerTransaction.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := ledgertransaction.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "LedgerTransaction.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "LedgerTransaction.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "LedgerTransaction.updated_at"`)} + } + if _, ok := _c.mutation.GroupID(); !ok { + return &ValidationError{Name: "group_id", err: errors.New(`db: missing required field "LedgerTransaction.group_id"`)} + } + if _, ok := _c.mutation.BookedAt(); !ok { + return &ValidationError{Name: "booked_at", err: errors.New(`db: missing required field "LedgerTransaction.booked_at"`)} + } + if len(_c.mutation.GroupIDs()) == 0 { + return &ValidationError{Name: "group", err: errors.New(`db: missing required edge "LedgerTransaction.group"`)} + } + return nil +} + +func (_c *LedgerTransactionCreate) sqlSave(ctx context.Context) (*LedgerTransaction, 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 LedgerTransaction.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *LedgerTransactionCreate) createSpec() (*LedgerTransaction, *sqlgraph.CreateSpec) { + var ( + _node = &LedgerTransaction{config: _c.config} + _spec = sqlgraph.NewCreateSpec(ledgertransaction.Table, sqlgraph.NewFieldSpec(ledgertransaction.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(ledgertransaction.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(ledgertransaction.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(ledgertransaction.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(ledgertransaction.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(ledgertransaction.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.BookedAt(); ok { + _spec.SetField(ledgertransaction.FieldBookedAt, field.TypeTime, value) + _node.BookedAt = value + } + if nodes := _c.mutation.GroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: ledgertransaction.GroupTable, + Columns: []string{ledgertransaction.GroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgertransactiongroup.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.GroupID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.EntriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.EntriesTable, + Columns: []string{ledgertransaction.EntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerentry.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.SourceBreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.SourceBreakageRecordsTable, + Columns: []string{ledgertransaction.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.BreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.BreakageRecordsTable, + Columns: []string{ledgertransaction.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.LedgerTransaction.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.LedgerTransactionUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *LedgerTransactionCreate) OnConflict(opts ...sql.ConflictOption) *LedgerTransactionUpsertOne { + _c.conflict = opts + return &LedgerTransactionUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.LedgerTransaction.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *LedgerTransactionCreate) OnConflictColumns(columns ...string) *LedgerTransactionUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &LedgerTransactionUpsertOne{ + create: _c, + } +} + +type ( + // LedgerTransactionUpsertOne is the builder for "upsert"-ing + // one LedgerTransaction node. + LedgerTransactionUpsertOne struct { + create *LedgerTransactionCreate + } + + // LedgerTransactionUpsert is the "OnConflict" setter. + LedgerTransactionUpsert struct { + *sql.UpdateSet + } +) + +// SetAnnotations sets the "annotations" field. +func (u *LedgerTransactionUpsert) SetAnnotations(v models.Annotations) *LedgerTransactionUpsert { + u.Set(ledgertransaction.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerTransactionUpsert) UpdateAnnotations() *LedgerTransactionUpsert { + u.SetExcluded(ledgertransaction.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerTransactionUpsert) ClearAnnotations() *LedgerTransactionUpsert { + u.SetNull(ledgertransaction.FieldAnnotations) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerTransactionUpsert) SetUpdatedAt(v time.Time) *LedgerTransactionUpsert { + u.Set(ledgertransaction.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerTransactionUpsert) UpdateUpdatedAt() *LedgerTransactionUpsert { + u.SetExcluded(ledgertransaction.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerTransactionUpsert) SetDeletedAt(v time.Time) *LedgerTransactionUpsert { + u.Set(ledgertransaction.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerTransactionUpsert) UpdateDeletedAt() *LedgerTransactionUpsert { + u.SetExcluded(ledgertransaction.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerTransactionUpsert) ClearDeletedAt() *LedgerTransactionUpsert { + u.SetNull(ledgertransaction.FieldDeletedAt) + 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.LedgerTransaction.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(ledgertransaction.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LedgerTransactionUpsertOne) UpdateNewValues() *LedgerTransactionUpsertOne { + 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(ledgertransaction.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(ledgertransaction.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(ledgertransaction.FieldCreatedAt) + } + if _, exists := u.create.mutation.GroupID(); exists { + s.SetIgnore(ledgertransaction.FieldGroupID) + } + if _, exists := u.create.mutation.BookedAt(); exists { + s.SetIgnore(ledgertransaction.FieldBookedAt) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.LedgerTransaction.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LedgerTransactionUpsertOne) Ignore() *LedgerTransactionUpsertOne { + 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 *LedgerTransactionUpsertOne) DoNothing() *LedgerTransactionUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LedgerTransactionCreate.OnConflict +// documentation for more info. +func (u *LedgerTransactionUpsertOne) Update(set func(*LedgerTransactionUpsert)) *LedgerTransactionUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LedgerTransactionUpsert{UpdateSet: update}) + })) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *LedgerTransactionUpsertOne) SetAnnotations(v models.Annotations) *LedgerTransactionUpsertOne { + return u.Update(func(s *LedgerTransactionUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerTransactionUpsertOne) UpdateAnnotations() *LedgerTransactionUpsertOne { + return u.Update(func(s *LedgerTransactionUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerTransactionUpsertOne) ClearAnnotations() *LedgerTransactionUpsertOne { + return u.Update(func(s *LedgerTransactionUpsert) { + s.ClearAnnotations() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerTransactionUpsertOne) SetUpdatedAt(v time.Time) *LedgerTransactionUpsertOne { + return u.Update(func(s *LedgerTransactionUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerTransactionUpsertOne) UpdateUpdatedAt() *LedgerTransactionUpsertOne { + return u.Update(func(s *LedgerTransactionUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerTransactionUpsertOne) SetDeletedAt(v time.Time) *LedgerTransactionUpsertOne { + return u.Update(func(s *LedgerTransactionUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerTransactionUpsertOne) UpdateDeletedAt() *LedgerTransactionUpsertOne { + return u.Update(func(s *LedgerTransactionUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerTransactionUpsertOne) ClearDeletedAt() *LedgerTransactionUpsertOne { + return u.Update(func(s *LedgerTransactionUpsert) { + s.ClearDeletedAt() + }) +} + +// Exec executes the query. +func (u *LedgerTransactionUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for LedgerTransactionCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LedgerTransactionUpsertOne) 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 *LedgerTransactionUpsertOne) 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: LedgerTransactionUpsertOne.ID is not supported by MySQL driver. Use LedgerTransactionUpsertOne.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 *LedgerTransactionUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// LedgerTransactionCreateBulk is the builder for creating many LedgerTransaction entities in bulk. +type LedgerTransactionCreateBulk struct { + config + err error + builders []*LedgerTransactionCreate + conflict []sql.ConflictOption +} + +// Save creates the LedgerTransaction entities in the database. +func (_c *LedgerTransactionCreateBulk) Save(ctx context.Context) ([]*LedgerTransaction, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*LedgerTransaction, 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.(*LedgerTransactionMutation) + 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 *LedgerTransactionCreateBulk) SaveX(ctx context.Context) []*LedgerTransaction { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LedgerTransactionCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LedgerTransactionCreateBulk) 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.LedgerTransaction.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.LedgerTransactionUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *LedgerTransactionCreateBulk) OnConflict(opts ...sql.ConflictOption) *LedgerTransactionUpsertBulk { + _c.conflict = opts + return &LedgerTransactionUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.LedgerTransaction.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *LedgerTransactionCreateBulk) OnConflictColumns(columns ...string) *LedgerTransactionUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &LedgerTransactionUpsertBulk{ + create: _c, + } +} + +// LedgerTransactionUpsertBulk is the builder for "upsert"-ing +// a bulk of LedgerTransaction nodes. +type LedgerTransactionUpsertBulk struct { + create *LedgerTransactionCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.LedgerTransaction.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(ledgertransaction.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LedgerTransactionUpsertBulk) UpdateNewValues() *LedgerTransactionUpsertBulk { + 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(ledgertransaction.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(ledgertransaction.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(ledgertransaction.FieldCreatedAt) + } + if _, exists := b.mutation.GroupID(); exists { + s.SetIgnore(ledgertransaction.FieldGroupID) + } + if _, exists := b.mutation.BookedAt(); exists { + s.SetIgnore(ledgertransaction.FieldBookedAt) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.LedgerTransaction.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LedgerTransactionUpsertBulk) Ignore() *LedgerTransactionUpsertBulk { + 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 *LedgerTransactionUpsertBulk) DoNothing() *LedgerTransactionUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LedgerTransactionCreateBulk.OnConflict +// documentation for more info. +func (u *LedgerTransactionUpsertBulk) Update(set func(*LedgerTransactionUpsert)) *LedgerTransactionUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LedgerTransactionUpsert{UpdateSet: update}) + })) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *LedgerTransactionUpsertBulk) SetAnnotations(v models.Annotations) *LedgerTransactionUpsertBulk { + return u.Update(func(s *LedgerTransactionUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerTransactionUpsertBulk) UpdateAnnotations() *LedgerTransactionUpsertBulk { + return u.Update(func(s *LedgerTransactionUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerTransactionUpsertBulk) ClearAnnotations() *LedgerTransactionUpsertBulk { + return u.Update(func(s *LedgerTransactionUpsert) { + s.ClearAnnotations() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerTransactionUpsertBulk) SetUpdatedAt(v time.Time) *LedgerTransactionUpsertBulk { + return u.Update(func(s *LedgerTransactionUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerTransactionUpsertBulk) UpdateUpdatedAt() *LedgerTransactionUpsertBulk { + return u.Update(func(s *LedgerTransactionUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerTransactionUpsertBulk) SetDeletedAt(v time.Time) *LedgerTransactionUpsertBulk { + return u.Update(func(s *LedgerTransactionUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerTransactionUpsertBulk) UpdateDeletedAt() *LedgerTransactionUpsertBulk { + return u.Update(func(s *LedgerTransactionUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerTransactionUpsertBulk) ClearDeletedAt() *LedgerTransactionUpsertBulk { + return u.Update(func(s *LedgerTransactionUpsert) { + s.ClearDeletedAt() + }) +} + +// Exec executes the query. +func (u *LedgerTransactionUpsertBulk) 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 LedgerTransactionCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for LedgerTransactionCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LedgerTransactionUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/ledgertransaction_delete.go b/ent/db/ledgertransaction_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..6d655f349c7e68c7d58e43b511f1114a223de98e --- /dev/null +++ b/ent/db/ledgertransaction_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/ledgertransaction" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LedgerTransactionDelete is the builder for deleting a LedgerTransaction entity. +type LedgerTransactionDelete struct { + config + hooks []Hook + mutation *LedgerTransactionMutation +} + +// Where appends a list predicates to the LedgerTransactionDelete builder. +func (_d *LedgerTransactionDelete) Where(ps ...predicate.LedgerTransaction) *LedgerTransactionDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *LedgerTransactionDelete) 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 *LedgerTransactionDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *LedgerTransactionDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(ledgertransaction.Table, sqlgraph.NewFieldSpec(ledgertransaction.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 +} + +// LedgerTransactionDeleteOne is the builder for deleting a single LedgerTransaction entity. +type LedgerTransactionDeleteOne struct { + _d *LedgerTransactionDelete +} + +// Where appends a list predicates to the LedgerTransactionDelete builder. +func (_d *LedgerTransactionDeleteOne) Where(ps ...predicate.LedgerTransaction) *LedgerTransactionDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *LedgerTransactionDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{ledgertransaction.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *LedgerTransactionDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/ledgertransaction_query.go b/ent/db/ledgertransaction_query.go new file mode 100644 index 0000000000000000000000000000000000000000..ff0c5c3ccd5792e61481f3a98ddd6b0e6730120d --- /dev/null +++ b/ent/db/ledgertransaction_query.go @@ -0,0 +1,872 @@ +// 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/ledgerbreakagerecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgerentry" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransaction" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransactiongroup" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LedgerTransactionQuery is the builder for querying LedgerTransaction entities. +type LedgerTransactionQuery struct { + config + ctx *QueryContext + order []ledgertransaction.OrderOption + inters []Interceptor + predicates []predicate.LedgerTransaction + withGroup *LedgerTransactionGroupQuery + withEntries *LedgerEntryQuery + withSourceBreakageRecords *LedgerBreakageRecordQuery + withBreakageRecords *LedgerBreakageRecordQuery + 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 LedgerTransactionQuery builder. +func (_q *LedgerTransactionQuery) Where(ps ...predicate.LedgerTransaction) *LedgerTransactionQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *LedgerTransactionQuery) Limit(limit int) *LedgerTransactionQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *LedgerTransactionQuery) Offset(offset int) *LedgerTransactionQuery { + _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 *LedgerTransactionQuery) Unique(unique bool) *LedgerTransactionQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *LedgerTransactionQuery) Order(o ...ledgertransaction.OrderOption) *LedgerTransactionQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryGroup chains the current query on the "group" edge. +func (_q *LedgerTransactionQuery) QueryGroup() *LedgerTransactionGroupQuery { + query := (&LedgerTransactionGroupClient{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(ledgertransaction.Table, ledgertransaction.FieldID, selector), + sqlgraph.To(ledgertransactiongroup.Table, ledgertransactiongroup.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ledgertransaction.GroupTable, ledgertransaction.GroupColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryEntries chains the current query on the "entries" edge. +func (_q *LedgerTransactionQuery) QueryEntries() *LedgerEntryQuery { + query := (&LedgerEntryClient{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(ledgertransaction.Table, ledgertransaction.FieldID, selector), + sqlgraph.To(ledgerentry.Table, ledgerentry.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgertransaction.EntriesTable, ledgertransaction.EntriesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySourceBreakageRecords chains the current query on the "source_breakage_records" edge. +func (_q *LedgerTransactionQuery) QuerySourceBreakageRecords() *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{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(ledgertransaction.Table, ledgertransaction.FieldID, selector), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgertransaction.SourceBreakageRecordsTable, ledgertransaction.SourceBreakageRecordsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryBreakageRecords chains the current query on the "breakage_records" edge. +func (_q *LedgerTransactionQuery) QueryBreakageRecords() *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{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(ledgertransaction.Table, ledgertransaction.FieldID, selector), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgertransaction.BreakageRecordsTable, ledgertransaction.BreakageRecordsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first LedgerTransaction entity from the query. +// Returns a *NotFoundError when no LedgerTransaction was found. +func (_q *LedgerTransactionQuery) First(ctx context.Context) (*LedgerTransaction, 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{ledgertransaction.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *LedgerTransactionQuery) FirstX(ctx context.Context) *LedgerTransaction { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LedgerTransaction ID from the query. +// Returns a *NotFoundError when no LedgerTransaction ID was found. +func (_q *LedgerTransactionQuery) 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{ledgertransaction.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *LedgerTransactionQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LedgerTransaction entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one LedgerTransaction entity is found. +// Returns a *NotFoundError when no LedgerTransaction entities are found. +func (_q *LedgerTransactionQuery) Only(ctx context.Context) (*LedgerTransaction, 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{ledgertransaction.Label} + default: + return nil, &NotSingularError{ledgertransaction.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *LedgerTransactionQuery) OnlyX(ctx context.Context) *LedgerTransaction { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LedgerTransaction ID in the query. +// Returns a *NotSingularError when more than one LedgerTransaction ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *LedgerTransactionQuery) 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{ledgertransaction.Label} + default: + err = &NotSingularError{ledgertransaction.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *LedgerTransactionQuery) 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 LedgerTransactions. +func (_q *LedgerTransactionQuery) All(ctx context.Context) ([]*LedgerTransaction, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*LedgerTransaction, *LedgerTransactionQuery]() + return withInterceptors[[]*LedgerTransaction](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *LedgerTransactionQuery) AllX(ctx context.Context) []*LedgerTransaction { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LedgerTransaction IDs. +func (_q *LedgerTransactionQuery) 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(ledgertransaction.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *LedgerTransactionQuery) 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 *LedgerTransactionQuery) 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[*LedgerTransactionQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *LedgerTransactionQuery) 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 *LedgerTransactionQuery) 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 *LedgerTransactionQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LedgerTransactionQuery 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 *LedgerTransactionQuery) Clone() *LedgerTransactionQuery { + if _q == nil { + return nil + } + return &LedgerTransactionQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]ledgertransaction.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.LedgerTransaction{}, _q.predicates...), + withGroup: _q.withGroup.Clone(), + withEntries: _q.withEntries.Clone(), + withSourceBreakageRecords: _q.withSourceBreakageRecords.Clone(), + withBreakageRecords: _q.withBreakageRecords.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithGroup tells the query-builder to eager-load the nodes that are connected to +// the "group" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerTransactionQuery) WithGroup(opts ...func(*LedgerTransactionGroupQuery)) *LedgerTransactionQuery { + query := (&LedgerTransactionGroupClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withGroup = query + return _q +} + +// WithEntries tells the query-builder to eager-load the nodes that are connected to +// the "entries" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerTransactionQuery) WithEntries(opts ...func(*LedgerEntryQuery)) *LedgerTransactionQuery { + query := (&LedgerEntryClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withEntries = query + return _q +} + +// WithSourceBreakageRecords tells the query-builder to eager-load the nodes that are connected to +// the "source_breakage_records" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerTransactionQuery) WithSourceBreakageRecords(opts ...func(*LedgerBreakageRecordQuery)) *LedgerTransactionQuery { + query := (&LedgerBreakageRecordClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSourceBreakageRecords = query + return _q +} + +// WithBreakageRecords tells the query-builder to eager-load the nodes that are connected to +// the "breakage_records" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerTransactionQuery) WithBreakageRecords(opts ...func(*LedgerBreakageRecordQuery)) *LedgerTransactionQuery { + query := (&LedgerBreakageRecordClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBreakageRecords = 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.LedgerTransaction.Query(). +// GroupBy(ledgertransaction.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *LedgerTransactionQuery) GroupBy(field string, fields ...string) *LedgerTransactionGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &LedgerTransactionGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = ledgertransaction.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.LedgerTransaction.Query(). +// Select(ledgertransaction.FieldNamespace). +// Scan(ctx, &v) +func (_q *LedgerTransactionQuery) Select(fields ...string) *LedgerTransactionSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &LedgerTransactionSelect{LedgerTransactionQuery: _q} + sbuild.label = ledgertransaction.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a LedgerTransactionSelect configured with the given aggregations. +func (_q *LedgerTransactionQuery) Aggregate(fns ...AggregateFunc) *LedgerTransactionSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *LedgerTransactionQuery) 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 !ledgertransaction.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 *LedgerTransactionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*LedgerTransaction, error) { + var ( + nodes = []*LedgerTransaction{} + _spec = _q.querySpec() + loadedTypes = [4]bool{ + _q.withGroup != nil, + _q.withEntries != nil, + _q.withSourceBreakageRecords != nil, + _q.withBreakageRecords != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*LedgerTransaction).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &LedgerTransaction{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.withGroup; query != nil { + if err := _q.loadGroup(ctx, query, nodes, nil, + func(n *LedgerTransaction, e *LedgerTransactionGroup) { n.Edges.Group = e }); err != nil { + return nil, err + } + } + if query := _q.withEntries; query != nil { + if err := _q.loadEntries(ctx, query, nodes, + func(n *LedgerTransaction) { n.Edges.Entries = []*LedgerEntry{} }, + func(n *LedgerTransaction, e *LedgerEntry) { n.Edges.Entries = append(n.Edges.Entries, e) }); err != nil { + return nil, err + } + } + if query := _q.withSourceBreakageRecords; query != nil { + if err := _q.loadSourceBreakageRecords(ctx, query, nodes, + func(n *LedgerTransaction) { n.Edges.SourceBreakageRecords = []*LedgerBreakageRecord{} }, + func(n *LedgerTransaction, e *LedgerBreakageRecord) { + n.Edges.SourceBreakageRecords = append(n.Edges.SourceBreakageRecords, e) + }); err != nil { + return nil, err + } + } + if query := _q.withBreakageRecords; query != nil { + if err := _q.loadBreakageRecords(ctx, query, nodes, + func(n *LedgerTransaction) { n.Edges.BreakageRecords = []*LedgerBreakageRecord{} }, + func(n *LedgerTransaction, e *LedgerBreakageRecord) { + n.Edges.BreakageRecords = append(n.Edges.BreakageRecords, e) + }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *LedgerTransactionQuery) loadGroup(ctx context.Context, query *LedgerTransactionGroupQuery, nodes []*LedgerTransaction, init func(*LedgerTransaction), assign func(*LedgerTransaction, *LedgerTransactionGroup)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*LedgerTransaction) + for i := range nodes { + fk := nodes[i].GroupID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(ledgertransactiongroup.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 "group_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *LedgerTransactionQuery) loadEntries(ctx context.Context, query *LedgerEntryQuery, nodes []*LedgerTransaction, init func(*LedgerTransaction), assign func(*LedgerTransaction, *LedgerEntry)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*LedgerTransaction) + 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(ledgerentry.FieldTransactionID) + } + query.Where(predicate.LedgerEntry(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(ledgertransaction.EntriesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.TransactionID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "transaction_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *LedgerTransactionQuery) loadSourceBreakageRecords(ctx context.Context, query *LedgerBreakageRecordQuery, nodes []*LedgerTransaction, init func(*LedgerTransaction), assign func(*LedgerTransaction, *LedgerBreakageRecord)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*LedgerTransaction) + 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(ledgerbreakagerecord.FieldSourceTransactionID) + } + query.Where(predicate.LedgerBreakageRecord(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(ledgertransaction.SourceBreakageRecordsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.SourceTransactionID + if fk == nil { + return fmt.Errorf(`foreign-key "source_transaction_id" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "source_transaction_id" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *LedgerTransactionQuery) loadBreakageRecords(ctx context.Context, query *LedgerBreakageRecordQuery, nodes []*LedgerTransaction, init func(*LedgerTransaction), assign func(*LedgerTransaction, *LedgerBreakageRecord)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*LedgerTransaction) + 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(ledgerbreakagerecord.FieldBreakageTransactionID) + } + query.Where(predicate.LedgerBreakageRecord(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(ledgertransaction.BreakageRecordsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.BreakageTransactionID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "breakage_transaction_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *LedgerTransactionQuery) 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 *LedgerTransactionQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(ledgertransaction.Table, ledgertransaction.Columns, sqlgraph.NewFieldSpec(ledgertransaction.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, ledgertransaction.FieldID) + for i := range fields { + if fields[i] != ledgertransaction.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withGroup != nil { + _spec.Node.AddColumnOnce(ledgertransaction.FieldGroupID) + } + } + 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 *LedgerTransactionQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(ledgertransaction.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = ledgertransaction.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 *LedgerTransactionQuery) ForUpdate(opts ...sql.LockOption) *LedgerTransactionQuery { + 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 *LedgerTransactionQuery) ForShare(opts ...sql.LockOption) *LedgerTransactionQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// LedgerTransactionGroupBy is the group-by builder for LedgerTransaction entities. +type LedgerTransactionGroupBy struct { + selector + build *LedgerTransactionQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *LedgerTransactionGroupBy) Aggregate(fns ...AggregateFunc) *LedgerTransactionGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *LedgerTransactionGroupBy) 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[*LedgerTransactionQuery, *LedgerTransactionGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *LedgerTransactionGroupBy) sqlScan(ctx context.Context, root *LedgerTransactionQuery, 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) +} + +// LedgerTransactionSelect is the builder for selecting fields of LedgerTransaction entities. +type LedgerTransactionSelect struct { + *LedgerTransactionQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *LedgerTransactionSelect) Aggregate(fns ...AggregateFunc) *LedgerTransactionSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *LedgerTransactionSelect) 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[*LedgerTransactionQuery, *LedgerTransactionSelect](ctx, _s.LedgerTransactionQuery, _s, _s.inters, v) +} + +func (_s *LedgerTransactionSelect) sqlScan(ctx context.Context, root *LedgerTransactionQuery, 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/ent/db/ledgertransaction_update.go b/ent/db/ledgertransaction_update.go new file mode 100644 index 0000000000000000000000000000000000000000..0654cd9e0b37ed74ec23e49584cc7c39913bd5f8 --- /dev/null +++ b/ent/db/ledgertransaction_update.go @@ -0,0 +1,811 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/ledgerbreakagerecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgerentry" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransaction" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerTransactionUpdate is the builder for updating LedgerTransaction entities. +type LedgerTransactionUpdate struct { + config + hooks []Hook + mutation *LedgerTransactionMutation +} + +// Where appends a list predicates to the LedgerTransactionUpdate builder. +func (_u *LedgerTransactionUpdate) Where(ps ...predicate.LedgerTransaction) *LedgerTransactionUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *LedgerTransactionUpdate) SetAnnotations(v models.Annotations) *LedgerTransactionUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *LedgerTransactionUpdate) ClearAnnotations() *LedgerTransactionUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *LedgerTransactionUpdate) SetUpdatedAt(v time.Time) *LedgerTransactionUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *LedgerTransactionUpdate) SetDeletedAt(v time.Time) *LedgerTransactionUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *LedgerTransactionUpdate) SetNillableDeletedAt(v *time.Time) *LedgerTransactionUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *LedgerTransactionUpdate) ClearDeletedAt() *LedgerTransactionUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// AddEntryIDs adds the "entries" edge to the LedgerEntry entity by IDs. +func (_u *LedgerTransactionUpdate) AddEntryIDs(ids ...string) *LedgerTransactionUpdate { + _u.mutation.AddEntryIDs(ids...) + return _u +} + +// AddEntries adds the "entries" edges to the LedgerEntry entity. +func (_u *LedgerTransactionUpdate) AddEntries(v ...*LedgerEntry) *LedgerTransactionUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddEntryIDs(ids...) +} + +// AddSourceBreakageRecordIDs adds the "source_breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_u *LedgerTransactionUpdate) AddSourceBreakageRecordIDs(ids ...string) *LedgerTransactionUpdate { + _u.mutation.AddSourceBreakageRecordIDs(ids...) + return _u +} + +// AddSourceBreakageRecords adds the "source_breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerTransactionUpdate) AddSourceBreakageRecords(v ...*LedgerBreakageRecord) *LedgerTransactionUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSourceBreakageRecordIDs(ids...) +} + +// AddBreakageRecordIDs adds the "breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_u *LedgerTransactionUpdate) AddBreakageRecordIDs(ids ...string) *LedgerTransactionUpdate { + _u.mutation.AddBreakageRecordIDs(ids...) + return _u +} + +// AddBreakageRecords adds the "breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerTransactionUpdate) AddBreakageRecords(v ...*LedgerBreakageRecord) *LedgerTransactionUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddBreakageRecordIDs(ids...) +} + +// Mutation returns the LedgerTransactionMutation object of the builder. +func (_u *LedgerTransactionUpdate) Mutation() *LedgerTransactionMutation { + return _u.mutation +} + +// ClearEntries clears all "entries" edges to the LedgerEntry entity. +func (_u *LedgerTransactionUpdate) ClearEntries() *LedgerTransactionUpdate { + _u.mutation.ClearEntries() + return _u +} + +// RemoveEntryIDs removes the "entries" edge to LedgerEntry entities by IDs. +func (_u *LedgerTransactionUpdate) RemoveEntryIDs(ids ...string) *LedgerTransactionUpdate { + _u.mutation.RemoveEntryIDs(ids...) + return _u +} + +// RemoveEntries removes "entries" edges to LedgerEntry entities. +func (_u *LedgerTransactionUpdate) RemoveEntries(v ...*LedgerEntry) *LedgerTransactionUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveEntryIDs(ids...) +} + +// ClearSourceBreakageRecords clears all "source_breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerTransactionUpdate) ClearSourceBreakageRecords() *LedgerTransactionUpdate { + _u.mutation.ClearSourceBreakageRecords() + return _u +} + +// RemoveSourceBreakageRecordIDs removes the "source_breakage_records" edge to LedgerBreakageRecord entities by IDs. +func (_u *LedgerTransactionUpdate) RemoveSourceBreakageRecordIDs(ids ...string) *LedgerTransactionUpdate { + _u.mutation.RemoveSourceBreakageRecordIDs(ids...) + return _u +} + +// RemoveSourceBreakageRecords removes "source_breakage_records" edges to LedgerBreakageRecord entities. +func (_u *LedgerTransactionUpdate) RemoveSourceBreakageRecords(v ...*LedgerBreakageRecord) *LedgerTransactionUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSourceBreakageRecordIDs(ids...) +} + +// ClearBreakageRecords clears all "breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerTransactionUpdate) ClearBreakageRecords() *LedgerTransactionUpdate { + _u.mutation.ClearBreakageRecords() + return _u +} + +// RemoveBreakageRecordIDs removes the "breakage_records" edge to LedgerBreakageRecord entities by IDs. +func (_u *LedgerTransactionUpdate) RemoveBreakageRecordIDs(ids ...string) *LedgerTransactionUpdate { + _u.mutation.RemoveBreakageRecordIDs(ids...) + return _u +} + +// RemoveBreakageRecords removes "breakage_records" edges to LedgerBreakageRecord entities. +func (_u *LedgerTransactionUpdate) RemoveBreakageRecords(v ...*LedgerBreakageRecord) *LedgerTransactionUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveBreakageRecordIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *LedgerTransactionUpdate) 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 *LedgerTransactionUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *LedgerTransactionUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LedgerTransactionUpdate) 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 *LedgerTransactionUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := ledgertransaction.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *LedgerTransactionUpdate) check() error { + if _u.mutation.GroupCleared() && len(_u.mutation.GroupIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerTransaction.group"`) + } + return nil +} + +func (_u *LedgerTransactionUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(ledgertransaction.Table, ledgertransaction.Columns, sqlgraph.NewFieldSpec(ledgertransaction.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.Annotations(); ok { + _spec.SetField(ledgertransaction.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(ledgertransaction.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(ledgertransaction.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(ledgertransaction.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(ledgertransaction.FieldDeletedAt, field.TypeTime) + } + if _u.mutation.EntriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.EntriesTable, + Columns: []string{ledgertransaction.EntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerentry.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedEntriesIDs(); len(nodes) > 0 && !_u.mutation.EntriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.EntriesTable, + Columns: []string{ledgertransaction.EntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerentry.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.EntriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.EntriesTable, + Columns: []string{ledgertransaction.EntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerentry.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.SourceBreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.SourceBreakageRecordsTable, + Columns: []string{ledgertransaction.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSourceBreakageRecordsIDs(); len(nodes) > 0 && !_u.mutation.SourceBreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.SourceBreakageRecordsTable, + Columns: []string{ledgertransaction.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.SourceBreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.SourceBreakageRecordsTable, + Columns: []string{ledgertransaction.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.BreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.BreakageRecordsTable, + Columns: []string{ledgertransaction.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedBreakageRecordsIDs(); len(nodes) > 0 && !_u.mutation.BreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.BreakageRecordsTable, + Columns: []string{ledgertransaction.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.BreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.BreakageRecordsTable, + Columns: []string{ledgertransaction.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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{ledgertransaction.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// LedgerTransactionUpdateOne is the builder for updating a single LedgerTransaction entity. +type LedgerTransactionUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LedgerTransactionMutation +} + +// SetAnnotations sets the "annotations" field. +func (_u *LedgerTransactionUpdateOne) SetAnnotations(v models.Annotations) *LedgerTransactionUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *LedgerTransactionUpdateOne) ClearAnnotations() *LedgerTransactionUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *LedgerTransactionUpdateOne) SetUpdatedAt(v time.Time) *LedgerTransactionUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *LedgerTransactionUpdateOne) SetDeletedAt(v time.Time) *LedgerTransactionUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *LedgerTransactionUpdateOne) SetNillableDeletedAt(v *time.Time) *LedgerTransactionUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *LedgerTransactionUpdateOne) ClearDeletedAt() *LedgerTransactionUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// AddEntryIDs adds the "entries" edge to the LedgerEntry entity by IDs. +func (_u *LedgerTransactionUpdateOne) AddEntryIDs(ids ...string) *LedgerTransactionUpdateOne { + _u.mutation.AddEntryIDs(ids...) + return _u +} + +// AddEntries adds the "entries" edges to the LedgerEntry entity. +func (_u *LedgerTransactionUpdateOne) AddEntries(v ...*LedgerEntry) *LedgerTransactionUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddEntryIDs(ids...) +} + +// AddSourceBreakageRecordIDs adds the "source_breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_u *LedgerTransactionUpdateOne) AddSourceBreakageRecordIDs(ids ...string) *LedgerTransactionUpdateOne { + _u.mutation.AddSourceBreakageRecordIDs(ids...) + return _u +} + +// AddSourceBreakageRecords adds the "source_breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerTransactionUpdateOne) AddSourceBreakageRecords(v ...*LedgerBreakageRecord) *LedgerTransactionUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSourceBreakageRecordIDs(ids...) +} + +// AddBreakageRecordIDs adds the "breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_u *LedgerTransactionUpdateOne) AddBreakageRecordIDs(ids ...string) *LedgerTransactionUpdateOne { + _u.mutation.AddBreakageRecordIDs(ids...) + return _u +} + +// AddBreakageRecords adds the "breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerTransactionUpdateOne) AddBreakageRecords(v ...*LedgerBreakageRecord) *LedgerTransactionUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddBreakageRecordIDs(ids...) +} + +// Mutation returns the LedgerTransactionMutation object of the builder. +func (_u *LedgerTransactionUpdateOne) Mutation() *LedgerTransactionMutation { + return _u.mutation +} + +// ClearEntries clears all "entries" edges to the LedgerEntry entity. +func (_u *LedgerTransactionUpdateOne) ClearEntries() *LedgerTransactionUpdateOne { + _u.mutation.ClearEntries() + return _u +} + +// RemoveEntryIDs removes the "entries" edge to LedgerEntry entities by IDs. +func (_u *LedgerTransactionUpdateOne) RemoveEntryIDs(ids ...string) *LedgerTransactionUpdateOne { + _u.mutation.RemoveEntryIDs(ids...) + return _u +} + +// RemoveEntries removes "entries" edges to LedgerEntry entities. +func (_u *LedgerTransactionUpdateOne) RemoveEntries(v ...*LedgerEntry) *LedgerTransactionUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveEntryIDs(ids...) +} + +// ClearSourceBreakageRecords clears all "source_breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerTransactionUpdateOne) ClearSourceBreakageRecords() *LedgerTransactionUpdateOne { + _u.mutation.ClearSourceBreakageRecords() + return _u +} + +// RemoveSourceBreakageRecordIDs removes the "source_breakage_records" edge to LedgerBreakageRecord entities by IDs. +func (_u *LedgerTransactionUpdateOne) RemoveSourceBreakageRecordIDs(ids ...string) *LedgerTransactionUpdateOne { + _u.mutation.RemoveSourceBreakageRecordIDs(ids...) + return _u +} + +// RemoveSourceBreakageRecords removes "source_breakage_records" edges to LedgerBreakageRecord entities. +func (_u *LedgerTransactionUpdateOne) RemoveSourceBreakageRecords(v ...*LedgerBreakageRecord) *LedgerTransactionUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSourceBreakageRecordIDs(ids...) +} + +// ClearBreakageRecords clears all "breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerTransactionUpdateOne) ClearBreakageRecords() *LedgerTransactionUpdateOne { + _u.mutation.ClearBreakageRecords() + return _u +} + +// RemoveBreakageRecordIDs removes the "breakage_records" edge to LedgerBreakageRecord entities by IDs. +func (_u *LedgerTransactionUpdateOne) RemoveBreakageRecordIDs(ids ...string) *LedgerTransactionUpdateOne { + _u.mutation.RemoveBreakageRecordIDs(ids...) + return _u +} + +// RemoveBreakageRecords removes "breakage_records" edges to LedgerBreakageRecord entities. +func (_u *LedgerTransactionUpdateOne) RemoveBreakageRecords(v ...*LedgerBreakageRecord) *LedgerTransactionUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveBreakageRecordIDs(ids...) +} + +// Where appends a list predicates to the LedgerTransactionUpdate builder. +func (_u *LedgerTransactionUpdateOne) Where(ps ...predicate.LedgerTransaction) *LedgerTransactionUpdateOne { + _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 *LedgerTransactionUpdateOne) Select(field string, fields ...string) *LedgerTransactionUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated LedgerTransaction entity. +func (_u *LedgerTransactionUpdateOne) Save(ctx context.Context) (*LedgerTransaction, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *LedgerTransactionUpdateOne) SaveX(ctx context.Context) *LedgerTransaction { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *LedgerTransactionUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LedgerTransactionUpdateOne) 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 *LedgerTransactionUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := ledgertransaction.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *LedgerTransactionUpdateOne) check() error { + if _u.mutation.GroupCleared() && len(_u.mutation.GroupIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "LedgerTransaction.group"`) + } + return nil +} + +func (_u *LedgerTransactionUpdateOne) sqlSave(ctx context.Context) (_node *LedgerTransaction, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(ledgertransaction.Table, ledgertransaction.Columns, sqlgraph.NewFieldSpec(ledgertransaction.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "LedgerTransaction.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, ledgertransaction.FieldID) + for _, f := range fields { + if !ledgertransaction.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != ledgertransaction.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.Annotations(); ok { + _spec.SetField(ledgertransaction.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(ledgertransaction.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(ledgertransaction.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(ledgertransaction.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(ledgertransaction.FieldDeletedAt, field.TypeTime) + } + if _u.mutation.EntriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.EntriesTable, + Columns: []string{ledgertransaction.EntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerentry.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedEntriesIDs(); len(nodes) > 0 && !_u.mutation.EntriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.EntriesTable, + Columns: []string{ledgertransaction.EntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerentry.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.EntriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.EntriesTable, + Columns: []string{ledgertransaction.EntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerentry.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.SourceBreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.SourceBreakageRecordsTable, + Columns: []string{ledgertransaction.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSourceBreakageRecordsIDs(); len(nodes) > 0 && !_u.mutation.SourceBreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.SourceBreakageRecordsTable, + Columns: []string{ledgertransaction.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.SourceBreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.SourceBreakageRecordsTable, + Columns: []string{ledgertransaction.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.BreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.BreakageRecordsTable, + Columns: []string{ledgertransaction.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedBreakageRecordsIDs(); len(nodes) > 0 && !_u.mutation.BreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.BreakageRecordsTable, + Columns: []string{ledgertransaction.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.BreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransaction.BreakageRecordsTable, + Columns: []string{ledgertransaction.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &LedgerTransaction{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{ledgertransaction.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/ent/db/ledgertransactiongroup.go b/ent/db/ledgertransactiongroup.go new file mode 100644 index 0000000000000000000000000000000000000000..3eee4e3ddab6c8b1bf74a2aefc7ebe9dfecc9de4 --- /dev/null +++ b/ent/db/ledgertransactiongroup.go @@ -0,0 +1,215 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/ledgertransactiongroup" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerTransactionGroup is the model entity for the LedgerTransactionGroup schema. +type LedgerTransactionGroup 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"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,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"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the LedgerTransactionGroupQuery when eager-loading is set. + Edges LedgerTransactionGroupEdges `json:"edges"` + selectValues sql.SelectValues +} + +// LedgerTransactionGroupEdges holds the relations/edges for other nodes in the graph. +type LedgerTransactionGroupEdges struct { + // Transactions holds the value of the transactions edge. + Transactions []*LedgerTransaction `json:"transactions,omitempty"` + // SourceBreakageRecords holds the value of the source_breakage_records edge. + SourceBreakageRecords []*LedgerBreakageRecord `json:"source_breakage_records,omitempty"` + // BreakageRecords holds the value of the breakage_records edge. + BreakageRecords []*LedgerBreakageRecord `json:"breakage_records,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [3]bool +} + +// TransactionsOrErr returns the Transactions value or an error if the edge +// was not loaded in eager-loading. +func (e LedgerTransactionGroupEdges) TransactionsOrErr() ([]*LedgerTransaction, error) { + if e.loadedTypes[0] { + return e.Transactions, nil + } + return nil, &NotLoadedError{edge: "transactions"} +} + +// SourceBreakageRecordsOrErr returns the SourceBreakageRecords value or an error if the edge +// was not loaded in eager-loading. +func (e LedgerTransactionGroupEdges) SourceBreakageRecordsOrErr() ([]*LedgerBreakageRecord, error) { + if e.loadedTypes[1] { + return e.SourceBreakageRecords, nil + } + return nil, &NotLoadedError{edge: "source_breakage_records"} +} + +// BreakageRecordsOrErr returns the BreakageRecords value or an error if the edge +// was not loaded in eager-loading. +func (e LedgerTransactionGroupEdges) BreakageRecordsOrErr() ([]*LedgerBreakageRecord, error) { + if e.loadedTypes[2] { + return e.BreakageRecords, nil + } + return nil, &NotLoadedError{edge: "breakage_records"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LedgerTransactionGroup) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case ledgertransactiongroup.FieldAnnotations: + values[i] = new([]byte) + case ledgertransactiongroup.FieldID, ledgertransactiongroup.FieldNamespace: + values[i] = new(sql.NullString) + case ledgertransactiongroup.FieldCreatedAt, ledgertransactiongroup.FieldUpdatedAt, ledgertransactiongroup.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 LedgerTransactionGroup fields. +func (_m *LedgerTransactionGroup) 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 ledgertransactiongroup.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 ledgertransactiongroup.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 ledgertransactiongroup.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 ledgertransactiongroup.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 ledgertransactiongroup.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 ledgertransactiongroup.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 + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the LedgerTransactionGroup. +// This includes values selected through modifiers, order, etc. +func (_m *LedgerTransactionGroup) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryTransactions queries the "transactions" edge of the LedgerTransactionGroup entity. +func (_m *LedgerTransactionGroup) QueryTransactions() *LedgerTransactionQuery { + return NewLedgerTransactionGroupClient(_m.config).QueryTransactions(_m) +} + +// QuerySourceBreakageRecords queries the "source_breakage_records" edge of the LedgerTransactionGroup entity. +func (_m *LedgerTransactionGroup) QuerySourceBreakageRecords() *LedgerBreakageRecordQuery { + return NewLedgerTransactionGroupClient(_m.config).QuerySourceBreakageRecords(_m) +} + +// QueryBreakageRecords queries the "breakage_records" edge of the LedgerTransactionGroup entity. +func (_m *LedgerTransactionGroup) QueryBreakageRecords() *LedgerBreakageRecordQuery { + return NewLedgerTransactionGroupClient(_m.config).QueryBreakageRecords(_m) +} + +// Update returns a builder for updating this LedgerTransactionGroup. +// Note that you need to call LedgerTransactionGroup.Unwrap() before calling this method if this LedgerTransactionGroup +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *LedgerTransactionGroup) Update() *LedgerTransactionGroupUpdateOne { + return NewLedgerTransactionGroupClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the LedgerTransactionGroup 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 *LedgerTransactionGroup) Unwrap() *LedgerTransactionGroup { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: LedgerTransactionGroup is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *LedgerTransactionGroup) String() string { + var builder strings.Builder + builder.WriteString("LedgerTransactionGroup(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + 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.WriteByte(')') + return builder.String() +} + +// LedgerTransactionGroups is a parsable slice of LedgerTransactionGroup. +type LedgerTransactionGroups []*LedgerTransactionGroup diff --git a/ent/db/ledgertransactiongroup/ledgertransactiongroup.go b/ent/db/ledgertransactiongroup/ledgertransactiongroup.go new file mode 100644 index 0000000000000000000000000000000000000000..40aaa6fdec556c319424c9fd884dc43e5210b927 --- /dev/null +++ b/ent/db/ledgertransactiongroup/ledgertransactiongroup.go @@ -0,0 +1,180 @@ +// Code generated by ent, DO NOT EDIT. + +package ledgertransactiongroup + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the ledgertransactiongroup type in the database. + Label = "ledger_transaction_group" + // 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" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // 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" + // EdgeTransactions holds the string denoting the transactions edge name in mutations. + EdgeTransactions = "transactions" + // EdgeSourceBreakageRecords holds the string denoting the source_breakage_records edge name in mutations. + EdgeSourceBreakageRecords = "source_breakage_records" + // EdgeBreakageRecords holds the string denoting the breakage_records edge name in mutations. + EdgeBreakageRecords = "breakage_records" + // Table holds the table name of the ledgertransactiongroup in the database. + Table = "ledger_transaction_groups" + // TransactionsTable is the table that holds the transactions relation/edge. + TransactionsTable = "ledger_transactions" + // TransactionsInverseTable is the table name for the LedgerTransaction entity. + // It exists in this package in order to avoid circular dependency with the "ledgertransaction" package. + TransactionsInverseTable = "ledger_transactions" + // TransactionsColumn is the table column denoting the transactions relation/edge. + TransactionsColumn = "group_id" + // SourceBreakageRecordsTable is the table that holds the source_breakage_records relation/edge. + SourceBreakageRecordsTable = "ledger_breakage_records" + // SourceBreakageRecordsInverseTable is the table name for the LedgerBreakageRecord entity. + // It exists in this package in order to avoid circular dependency with the "ledgerbreakagerecord" package. + SourceBreakageRecordsInverseTable = "ledger_breakage_records" + // SourceBreakageRecordsColumn is the table column denoting the source_breakage_records relation/edge. + SourceBreakageRecordsColumn = "source_transaction_group_id" + // BreakageRecordsTable is the table that holds the breakage_records relation/edge. + BreakageRecordsTable = "ledger_breakage_records" + // BreakageRecordsInverseTable is the table name for the LedgerBreakageRecord entity. + // It exists in this package in order to avoid circular dependency with the "ledgerbreakagerecord" package. + BreakageRecordsInverseTable = "ledger_breakage_records" + // BreakageRecordsColumn is the table column denoting the breakage_records relation/edge. + BreakageRecordsColumn = "breakage_transaction_group_id" +) + +// Columns holds all SQL columns for ledgertransactiongroup fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldAnnotations, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, +} + +// 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 +) + +// OrderOption defines the ordering options for the LedgerTransactionGroup 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() +} + +// ByTransactionsCount orders the results by transactions count. +func ByTransactionsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newTransactionsStep(), opts...) + } +} + +// ByTransactions orders the results by transactions terms. +func ByTransactions(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTransactionsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// BySourceBreakageRecordsCount orders the results by source_breakage_records count. +func BySourceBreakageRecordsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newSourceBreakageRecordsStep(), opts...) + } +} + +// BySourceBreakageRecords orders the results by source_breakage_records terms. +func BySourceBreakageRecords(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSourceBreakageRecordsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByBreakageRecordsCount orders the results by breakage_records count. +func ByBreakageRecordsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newBreakageRecordsStep(), opts...) + } +} + +// ByBreakageRecords orders the results by breakage_records terms. +func ByBreakageRecords(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newBreakageRecordsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newTransactionsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TransactionsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, TransactionsTable, TransactionsColumn), + ) +} +func newSourceBreakageRecordsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SourceBreakageRecordsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SourceBreakageRecordsTable, SourceBreakageRecordsColumn), + ) +} +func newBreakageRecordsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(BreakageRecordsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, BreakageRecordsTable, BreakageRecordsColumn), + ) +} diff --git a/ent/db/ledgertransactiongroup/where.go b/ent/db/ledgertransactiongroup/where.go new file mode 100644 index 0000000000000000000000000000000000000000..8d7c60515c6d3a1a78343d0e10a39c2a333cceeb --- /dev/null +++ b/ent/db/ledgertransactiongroup/where.go @@ -0,0 +1,375 @@ +// Code generated by ent, DO NOT EDIT. + +package ledgertransactiongroup + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(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.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(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.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(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.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldEQ(FieldDeletedAt, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldContainsFold(FieldNamespace, v)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldNotNull(FieldAnnotations)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.FieldNotNull(FieldDeletedAt)) +} + +// HasTransactions applies the HasEdge predicate on the "transactions" edge. +func HasTransactions() predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, TransactionsTable, TransactionsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTransactionsWith applies the HasEdge predicate on the "transactions" edge with a given conditions (other predicates). +func HasTransactionsWith(preds ...predicate.LedgerTransaction) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(func(s *sql.Selector) { + step := newTransactionsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSourceBreakageRecords applies the HasEdge predicate on the "source_breakage_records" edge. +func HasSourceBreakageRecords() predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SourceBreakageRecordsTable, SourceBreakageRecordsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSourceBreakageRecordsWith applies the HasEdge predicate on the "source_breakage_records" edge with a given conditions (other predicates). +func HasSourceBreakageRecordsWith(preds ...predicate.LedgerBreakageRecord) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(func(s *sql.Selector) { + step := newSourceBreakageRecordsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasBreakageRecords applies the HasEdge predicate on the "breakage_records" edge. +func HasBreakageRecords() predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, BreakageRecordsTable, BreakageRecordsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasBreakageRecordsWith applies the HasEdge predicate on the "breakage_records" edge with a given conditions (other predicates). +func HasBreakageRecordsWith(preds ...predicate.LedgerBreakageRecord) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(func(s *sql.Selector) { + step := newBreakageRecordsStep() + 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.LedgerTransactionGroup) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LedgerTransactionGroup) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LedgerTransactionGroup) predicate.LedgerTransactionGroup { + return predicate.LedgerTransactionGroup(sql.NotPredicates(p)) +} diff --git a/ent/db/ledgertransactiongroup_create.go b/ent/db/ledgertransactiongroup_create.go new file mode 100644 index 0000000000000000000000000000000000000000..246402cf745995bc05ea3c98b445cf6138455e01 --- /dev/null +++ b/ent/db/ledgertransactiongroup_create.go @@ -0,0 +1,819 @@ +// 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/ledgerbreakagerecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransaction" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransactiongroup" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerTransactionGroupCreate is the builder for creating a LedgerTransactionGroup entity. +type LedgerTransactionGroupCreate struct { + config + mutation *LedgerTransactionGroupMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *LedgerTransactionGroupCreate) SetNamespace(v string) *LedgerTransactionGroupCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *LedgerTransactionGroupCreate) SetAnnotations(v models.Annotations) *LedgerTransactionGroupCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *LedgerTransactionGroupCreate) SetCreatedAt(v time.Time) *LedgerTransactionGroupCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *LedgerTransactionGroupCreate) SetNillableCreatedAt(v *time.Time) *LedgerTransactionGroupCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *LedgerTransactionGroupCreate) SetUpdatedAt(v time.Time) *LedgerTransactionGroupCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *LedgerTransactionGroupCreate) SetNillableUpdatedAt(v *time.Time) *LedgerTransactionGroupCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *LedgerTransactionGroupCreate) SetDeletedAt(v time.Time) *LedgerTransactionGroupCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *LedgerTransactionGroupCreate) SetNillableDeletedAt(v *time.Time) *LedgerTransactionGroupCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *LedgerTransactionGroupCreate) SetID(v string) *LedgerTransactionGroupCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *LedgerTransactionGroupCreate) SetNillableID(v *string) *LedgerTransactionGroupCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// AddTransactionIDs adds the "transactions" edge to the LedgerTransaction entity by IDs. +func (_c *LedgerTransactionGroupCreate) AddTransactionIDs(ids ...string) *LedgerTransactionGroupCreate { + _c.mutation.AddTransactionIDs(ids...) + return _c +} + +// AddTransactions adds the "transactions" edges to the LedgerTransaction entity. +func (_c *LedgerTransactionGroupCreate) AddTransactions(v ...*LedgerTransaction) *LedgerTransactionGroupCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddTransactionIDs(ids...) +} + +// AddSourceBreakageRecordIDs adds the "source_breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_c *LedgerTransactionGroupCreate) AddSourceBreakageRecordIDs(ids ...string) *LedgerTransactionGroupCreate { + _c.mutation.AddSourceBreakageRecordIDs(ids...) + return _c +} + +// AddSourceBreakageRecords adds the "source_breakage_records" edges to the LedgerBreakageRecord entity. +func (_c *LedgerTransactionGroupCreate) AddSourceBreakageRecords(v ...*LedgerBreakageRecord) *LedgerTransactionGroupCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddSourceBreakageRecordIDs(ids...) +} + +// AddBreakageRecordIDs adds the "breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_c *LedgerTransactionGroupCreate) AddBreakageRecordIDs(ids ...string) *LedgerTransactionGroupCreate { + _c.mutation.AddBreakageRecordIDs(ids...) + return _c +} + +// AddBreakageRecords adds the "breakage_records" edges to the LedgerBreakageRecord entity. +func (_c *LedgerTransactionGroupCreate) AddBreakageRecords(v ...*LedgerBreakageRecord) *LedgerTransactionGroupCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddBreakageRecordIDs(ids...) +} + +// Mutation returns the LedgerTransactionGroupMutation object of the builder. +func (_c *LedgerTransactionGroupCreate) Mutation() *LedgerTransactionGroupMutation { + return _c.mutation +} + +// Save creates the LedgerTransactionGroup in the database. +func (_c *LedgerTransactionGroupCreate) Save(ctx context.Context) (*LedgerTransactionGroup, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *LedgerTransactionGroupCreate) SaveX(ctx context.Context) *LedgerTransactionGroup { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LedgerTransactionGroupCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LedgerTransactionGroupCreate) 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 *LedgerTransactionGroupCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := ledgertransactiongroup.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := ledgertransactiongroup.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := ledgertransactiongroup.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *LedgerTransactionGroupCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "LedgerTransactionGroup.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := ledgertransactiongroup.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "LedgerTransactionGroup.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "LedgerTransactionGroup.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "LedgerTransactionGroup.updated_at"`)} + } + return nil +} + +func (_c *LedgerTransactionGroupCreate) sqlSave(ctx context.Context) (*LedgerTransactionGroup, 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 LedgerTransactionGroup.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *LedgerTransactionGroupCreate) createSpec() (*LedgerTransactionGroup, *sqlgraph.CreateSpec) { + var ( + _node = &LedgerTransactionGroup{config: _c.config} + _spec = sqlgraph.NewCreateSpec(ledgertransactiongroup.Table, sqlgraph.NewFieldSpec(ledgertransactiongroup.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(ledgertransactiongroup.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(ledgertransactiongroup.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(ledgertransactiongroup.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(ledgertransactiongroup.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(ledgertransactiongroup.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if nodes := _c.mutation.TransactionsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.TransactionsTable, + Columns: []string{ledgertransactiongroup.TransactionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgertransaction.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.SourceBreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.SourceBreakageRecordsTable, + Columns: []string{ledgertransactiongroup.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.BreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.BreakageRecordsTable, + Columns: []string{ledgertransactiongroup.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.LedgerTransactionGroup.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.LedgerTransactionGroupUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *LedgerTransactionGroupCreate) OnConflict(opts ...sql.ConflictOption) *LedgerTransactionGroupUpsertOne { + _c.conflict = opts + return &LedgerTransactionGroupUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.LedgerTransactionGroup.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *LedgerTransactionGroupCreate) OnConflictColumns(columns ...string) *LedgerTransactionGroupUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &LedgerTransactionGroupUpsertOne{ + create: _c, + } +} + +type ( + // LedgerTransactionGroupUpsertOne is the builder for "upsert"-ing + // one LedgerTransactionGroup node. + LedgerTransactionGroupUpsertOne struct { + create *LedgerTransactionGroupCreate + } + + // LedgerTransactionGroupUpsert is the "OnConflict" setter. + LedgerTransactionGroupUpsert struct { + *sql.UpdateSet + } +) + +// SetAnnotations sets the "annotations" field. +func (u *LedgerTransactionGroupUpsert) SetAnnotations(v models.Annotations) *LedgerTransactionGroupUpsert { + u.Set(ledgertransactiongroup.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerTransactionGroupUpsert) UpdateAnnotations() *LedgerTransactionGroupUpsert { + u.SetExcluded(ledgertransactiongroup.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerTransactionGroupUpsert) ClearAnnotations() *LedgerTransactionGroupUpsert { + u.SetNull(ledgertransactiongroup.FieldAnnotations) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerTransactionGroupUpsert) SetUpdatedAt(v time.Time) *LedgerTransactionGroupUpsert { + u.Set(ledgertransactiongroup.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerTransactionGroupUpsert) UpdateUpdatedAt() *LedgerTransactionGroupUpsert { + u.SetExcluded(ledgertransactiongroup.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerTransactionGroupUpsert) SetDeletedAt(v time.Time) *LedgerTransactionGroupUpsert { + u.Set(ledgertransactiongroup.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerTransactionGroupUpsert) UpdateDeletedAt() *LedgerTransactionGroupUpsert { + u.SetExcluded(ledgertransactiongroup.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerTransactionGroupUpsert) ClearDeletedAt() *LedgerTransactionGroupUpsert { + u.SetNull(ledgertransactiongroup.FieldDeletedAt) + 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.LedgerTransactionGroup.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(ledgertransactiongroup.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LedgerTransactionGroupUpsertOne) UpdateNewValues() *LedgerTransactionGroupUpsertOne { + 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(ledgertransactiongroup.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(ledgertransactiongroup.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(ledgertransactiongroup.FieldCreatedAt) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.LedgerTransactionGroup.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LedgerTransactionGroupUpsertOne) Ignore() *LedgerTransactionGroupUpsertOne { + 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 *LedgerTransactionGroupUpsertOne) DoNothing() *LedgerTransactionGroupUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LedgerTransactionGroupCreate.OnConflict +// documentation for more info. +func (u *LedgerTransactionGroupUpsertOne) Update(set func(*LedgerTransactionGroupUpsert)) *LedgerTransactionGroupUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LedgerTransactionGroupUpsert{UpdateSet: update}) + })) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *LedgerTransactionGroupUpsertOne) SetAnnotations(v models.Annotations) *LedgerTransactionGroupUpsertOne { + return u.Update(func(s *LedgerTransactionGroupUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerTransactionGroupUpsertOne) UpdateAnnotations() *LedgerTransactionGroupUpsertOne { + return u.Update(func(s *LedgerTransactionGroupUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerTransactionGroupUpsertOne) ClearAnnotations() *LedgerTransactionGroupUpsertOne { + return u.Update(func(s *LedgerTransactionGroupUpsert) { + s.ClearAnnotations() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerTransactionGroupUpsertOne) SetUpdatedAt(v time.Time) *LedgerTransactionGroupUpsertOne { + return u.Update(func(s *LedgerTransactionGroupUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerTransactionGroupUpsertOne) UpdateUpdatedAt() *LedgerTransactionGroupUpsertOne { + return u.Update(func(s *LedgerTransactionGroupUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerTransactionGroupUpsertOne) SetDeletedAt(v time.Time) *LedgerTransactionGroupUpsertOne { + return u.Update(func(s *LedgerTransactionGroupUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerTransactionGroupUpsertOne) UpdateDeletedAt() *LedgerTransactionGroupUpsertOne { + return u.Update(func(s *LedgerTransactionGroupUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerTransactionGroupUpsertOne) ClearDeletedAt() *LedgerTransactionGroupUpsertOne { + return u.Update(func(s *LedgerTransactionGroupUpsert) { + s.ClearDeletedAt() + }) +} + +// Exec executes the query. +func (u *LedgerTransactionGroupUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for LedgerTransactionGroupCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LedgerTransactionGroupUpsertOne) 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 *LedgerTransactionGroupUpsertOne) 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: LedgerTransactionGroupUpsertOne.ID is not supported by MySQL driver. Use LedgerTransactionGroupUpsertOne.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 *LedgerTransactionGroupUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// LedgerTransactionGroupCreateBulk is the builder for creating many LedgerTransactionGroup entities in bulk. +type LedgerTransactionGroupCreateBulk struct { + config + err error + builders []*LedgerTransactionGroupCreate + conflict []sql.ConflictOption +} + +// Save creates the LedgerTransactionGroup entities in the database. +func (_c *LedgerTransactionGroupCreateBulk) Save(ctx context.Context) ([]*LedgerTransactionGroup, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*LedgerTransactionGroup, 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.(*LedgerTransactionGroupMutation) + 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 *LedgerTransactionGroupCreateBulk) SaveX(ctx context.Context) []*LedgerTransactionGroup { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LedgerTransactionGroupCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LedgerTransactionGroupCreateBulk) 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.LedgerTransactionGroup.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.LedgerTransactionGroupUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *LedgerTransactionGroupCreateBulk) OnConflict(opts ...sql.ConflictOption) *LedgerTransactionGroupUpsertBulk { + _c.conflict = opts + return &LedgerTransactionGroupUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.LedgerTransactionGroup.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *LedgerTransactionGroupCreateBulk) OnConflictColumns(columns ...string) *LedgerTransactionGroupUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &LedgerTransactionGroupUpsertBulk{ + create: _c, + } +} + +// LedgerTransactionGroupUpsertBulk is the builder for "upsert"-ing +// a bulk of LedgerTransactionGroup nodes. +type LedgerTransactionGroupUpsertBulk struct { + create *LedgerTransactionGroupCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.LedgerTransactionGroup.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(ledgertransactiongroup.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LedgerTransactionGroupUpsertBulk) UpdateNewValues() *LedgerTransactionGroupUpsertBulk { + 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(ledgertransactiongroup.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(ledgertransactiongroup.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(ledgertransactiongroup.FieldCreatedAt) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.LedgerTransactionGroup.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LedgerTransactionGroupUpsertBulk) Ignore() *LedgerTransactionGroupUpsertBulk { + 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 *LedgerTransactionGroupUpsertBulk) DoNothing() *LedgerTransactionGroupUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LedgerTransactionGroupCreateBulk.OnConflict +// documentation for more info. +func (u *LedgerTransactionGroupUpsertBulk) Update(set func(*LedgerTransactionGroupUpsert)) *LedgerTransactionGroupUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LedgerTransactionGroupUpsert{UpdateSet: update}) + })) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *LedgerTransactionGroupUpsertBulk) SetAnnotations(v models.Annotations) *LedgerTransactionGroupUpsertBulk { + return u.Update(func(s *LedgerTransactionGroupUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *LedgerTransactionGroupUpsertBulk) UpdateAnnotations() *LedgerTransactionGroupUpsertBulk { + return u.Update(func(s *LedgerTransactionGroupUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *LedgerTransactionGroupUpsertBulk) ClearAnnotations() *LedgerTransactionGroupUpsertBulk { + return u.Update(func(s *LedgerTransactionGroupUpsert) { + s.ClearAnnotations() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LedgerTransactionGroupUpsertBulk) SetUpdatedAt(v time.Time) *LedgerTransactionGroupUpsertBulk { + return u.Update(func(s *LedgerTransactionGroupUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LedgerTransactionGroupUpsertBulk) UpdateUpdatedAt() *LedgerTransactionGroupUpsertBulk { + return u.Update(func(s *LedgerTransactionGroupUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LedgerTransactionGroupUpsertBulk) SetDeletedAt(v time.Time) *LedgerTransactionGroupUpsertBulk { + return u.Update(func(s *LedgerTransactionGroupUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LedgerTransactionGroupUpsertBulk) UpdateDeletedAt() *LedgerTransactionGroupUpsertBulk { + return u.Update(func(s *LedgerTransactionGroupUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LedgerTransactionGroupUpsertBulk) ClearDeletedAt() *LedgerTransactionGroupUpsertBulk { + return u.Update(func(s *LedgerTransactionGroupUpsert) { + s.ClearDeletedAt() + }) +} + +// Exec executes the query. +func (u *LedgerTransactionGroupUpsertBulk) 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 LedgerTransactionGroupCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for LedgerTransactionGroupCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LedgerTransactionGroupUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/ledgertransactiongroup_delete.go b/ent/db/ledgertransactiongroup_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..78a5b8af925f817790e6dad20faab4bbb15d1753 --- /dev/null +++ b/ent/db/ledgertransactiongroup_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/ledgertransactiongroup" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LedgerTransactionGroupDelete is the builder for deleting a LedgerTransactionGroup entity. +type LedgerTransactionGroupDelete struct { + config + hooks []Hook + mutation *LedgerTransactionGroupMutation +} + +// Where appends a list predicates to the LedgerTransactionGroupDelete builder. +func (_d *LedgerTransactionGroupDelete) Where(ps ...predicate.LedgerTransactionGroup) *LedgerTransactionGroupDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *LedgerTransactionGroupDelete) 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 *LedgerTransactionGroupDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *LedgerTransactionGroupDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(ledgertransactiongroup.Table, sqlgraph.NewFieldSpec(ledgertransactiongroup.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 +} + +// LedgerTransactionGroupDeleteOne is the builder for deleting a single LedgerTransactionGroup entity. +type LedgerTransactionGroupDeleteOne struct { + _d *LedgerTransactionGroupDelete +} + +// Where appends a list predicates to the LedgerTransactionGroupDelete builder. +func (_d *LedgerTransactionGroupDeleteOne) Where(ps ...predicate.LedgerTransactionGroup) *LedgerTransactionGroupDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *LedgerTransactionGroupDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{ledgertransactiongroup.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *LedgerTransactionGroupDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/ledgertransactiongroup_query.go b/ent/db/ledgertransactiongroup_query.go new file mode 100644 index 0000000000000000000000000000000000000000..0db13cf29eb4566f1e4f1e401c8a988dca2ae4f4 --- /dev/null +++ b/ent/db/ledgertransactiongroup_query.go @@ -0,0 +1,799 @@ +// 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/ledgerbreakagerecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransaction" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransactiongroup" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LedgerTransactionGroupQuery is the builder for querying LedgerTransactionGroup entities. +type LedgerTransactionGroupQuery struct { + config + ctx *QueryContext + order []ledgertransactiongroup.OrderOption + inters []Interceptor + predicates []predicate.LedgerTransactionGroup + withTransactions *LedgerTransactionQuery + withSourceBreakageRecords *LedgerBreakageRecordQuery + withBreakageRecords *LedgerBreakageRecordQuery + 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 LedgerTransactionGroupQuery builder. +func (_q *LedgerTransactionGroupQuery) Where(ps ...predicate.LedgerTransactionGroup) *LedgerTransactionGroupQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *LedgerTransactionGroupQuery) Limit(limit int) *LedgerTransactionGroupQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *LedgerTransactionGroupQuery) Offset(offset int) *LedgerTransactionGroupQuery { + _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 *LedgerTransactionGroupQuery) Unique(unique bool) *LedgerTransactionGroupQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *LedgerTransactionGroupQuery) Order(o ...ledgertransactiongroup.OrderOption) *LedgerTransactionGroupQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryTransactions chains the current query on the "transactions" edge. +func (_q *LedgerTransactionGroupQuery) QueryTransactions() *LedgerTransactionQuery { + query := (&LedgerTransactionClient{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(ledgertransactiongroup.Table, ledgertransactiongroup.FieldID, selector), + sqlgraph.To(ledgertransaction.Table, ledgertransaction.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgertransactiongroup.TransactionsTable, ledgertransactiongroup.TransactionsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySourceBreakageRecords chains the current query on the "source_breakage_records" edge. +func (_q *LedgerTransactionGroupQuery) QuerySourceBreakageRecords() *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{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(ledgertransactiongroup.Table, ledgertransactiongroup.FieldID, selector), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgertransactiongroup.SourceBreakageRecordsTable, ledgertransactiongroup.SourceBreakageRecordsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryBreakageRecords chains the current query on the "breakage_records" edge. +func (_q *LedgerTransactionGroupQuery) QueryBreakageRecords() *LedgerBreakageRecordQuery { + query := (&LedgerBreakageRecordClient{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(ledgertransactiongroup.Table, ledgertransactiongroup.FieldID, selector), + sqlgraph.To(ledgerbreakagerecord.Table, ledgerbreakagerecord.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ledgertransactiongroup.BreakageRecordsTable, ledgertransactiongroup.BreakageRecordsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first LedgerTransactionGroup entity from the query. +// Returns a *NotFoundError when no LedgerTransactionGroup was found. +func (_q *LedgerTransactionGroupQuery) First(ctx context.Context) (*LedgerTransactionGroup, 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{ledgertransactiongroup.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *LedgerTransactionGroupQuery) FirstX(ctx context.Context) *LedgerTransactionGroup { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LedgerTransactionGroup ID from the query. +// Returns a *NotFoundError when no LedgerTransactionGroup ID was found. +func (_q *LedgerTransactionGroupQuery) 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{ledgertransactiongroup.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *LedgerTransactionGroupQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LedgerTransactionGroup entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one LedgerTransactionGroup entity is found. +// Returns a *NotFoundError when no LedgerTransactionGroup entities are found. +func (_q *LedgerTransactionGroupQuery) Only(ctx context.Context) (*LedgerTransactionGroup, 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{ledgertransactiongroup.Label} + default: + return nil, &NotSingularError{ledgertransactiongroup.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *LedgerTransactionGroupQuery) OnlyX(ctx context.Context) *LedgerTransactionGroup { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LedgerTransactionGroup ID in the query. +// Returns a *NotSingularError when more than one LedgerTransactionGroup ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *LedgerTransactionGroupQuery) 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{ledgertransactiongroup.Label} + default: + err = &NotSingularError{ledgertransactiongroup.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *LedgerTransactionGroupQuery) 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 LedgerTransactionGroups. +func (_q *LedgerTransactionGroupQuery) All(ctx context.Context) ([]*LedgerTransactionGroup, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*LedgerTransactionGroup, *LedgerTransactionGroupQuery]() + return withInterceptors[[]*LedgerTransactionGroup](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *LedgerTransactionGroupQuery) AllX(ctx context.Context) []*LedgerTransactionGroup { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LedgerTransactionGroup IDs. +func (_q *LedgerTransactionGroupQuery) 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(ledgertransactiongroup.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *LedgerTransactionGroupQuery) 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 *LedgerTransactionGroupQuery) 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[*LedgerTransactionGroupQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *LedgerTransactionGroupQuery) 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 *LedgerTransactionGroupQuery) 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 *LedgerTransactionGroupQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LedgerTransactionGroupQuery 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 *LedgerTransactionGroupQuery) Clone() *LedgerTransactionGroupQuery { + if _q == nil { + return nil + } + return &LedgerTransactionGroupQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]ledgertransactiongroup.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.LedgerTransactionGroup{}, _q.predicates...), + withTransactions: _q.withTransactions.Clone(), + withSourceBreakageRecords: _q.withSourceBreakageRecords.Clone(), + withBreakageRecords: _q.withBreakageRecords.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithTransactions tells the query-builder to eager-load the nodes that are connected to +// the "transactions" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerTransactionGroupQuery) WithTransactions(opts ...func(*LedgerTransactionQuery)) *LedgerTransactionGroupQuery { + query := (&LedgerTransactionClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withTransactions = query + return _q +} + +// WithSourceBreakageRecords tells the query-builder to eager-load the nodes that are connected to +// the "source_breakage_records" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerTransactionGroupQuery) WithSourceBreakageRecords(opts ...func(*LedgerBreakageRecordQuery)) *LedgerTransactionGroupQuery { + query := (&LedgerBreakageRecordClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSourceBreakageRecords = query + return _q +} + +// WithBreakageRecords tells the query-builder to eager-load the nodes that are connected to +// the "breakage_records" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *LedgerTransactionGroupQuery) WithBreakageRecords(opts ...func(*LedgerBreakageRecordQuery)) *LedgerTransactionGroupQuery { + query := (&LedgerBreakageRecordClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withBreakageRecords = 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.LedgerTransactionGroup.Query(). +// GroupBy(ledgertransactiongroup.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *LedgerTransactionGroupQuery) GroupBy(field string, fields ...string) *LedgerTransactionGroupGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &LedgerTransactionGroupGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = ledgertransactiongroup.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.LedgerTransactionGroup.Query(). +// Select(ledgertransactiongroup.FieldNamespace). +// Scan(ctx, &v) +func (_q *LedgerTransactionGroupQuery) Select(fields ...string) *LedgerTransactionGroupSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &LedgerTransactionGroupSelect{LedgerTransactionGroupQuery: _q} + sbuild.label = ledgertransactiongroup.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a LedgerTransactionGroupSelect configured with the given aggregations. +func (_q *LedgerTransactionGroupQuery) Aggregate(fns ...AggregateFunc) *LedgerTransactionGroupSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *LedgerTransactionGroupQuery) 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 !ledgertransactiongroup.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 *LedgerTransactionGroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*LedgerTransactionGroup, error) { + var ( + nodes = []*LedgerTransactionGroup{} + _spec = _q.querySpec() + loadedTypes = [3]bool{ + _q.withTransactions != nil, + _q.withSourceBreakageRecords != nil, + _q.withBreakageRecords != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*LedgerTransactionGroup).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &LedgerTransactionGroup{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.withTransactions; query != nil { + if err := _q.loadTransactions(ctx, query, nodes, + func(n *LedgerTransactionGroup) { n.Edges.Transactions = []*LedgerTransaction{} }, + func(n *LedgerTransactionGroup, e *LedgerTransaction) { + n.Edges.Transactions = append(n.Edges.Transactions, e) + }); err != nil { + return nil, err + } + } + if query := _q.withSourceBreakageRecords; query != nil { + if err := _q.loadSourceBreakageRecords(ctx, query, nodes, + func(n *LedgerTransactionGroup) { n.Edges.SourceBreakageRecords = []*LedgerBreakageRecord{} }, + func(n *LedgerTransactionGroup, e *LedgerBreakageRecord) { + n.Edges.SourceBreakageRecords = append(n.Edges.SourceBreakageRecords, e) + }); err != nil { + return nil, err + } + } + if query := _q.withBreakageRecords; query != nil { + if err := _q.loadBreakageRecords(ctx, query, nodes, + func(n *LedgerTransactionGroup) { n.Edges.BreakageRecords = []*LedgerBreakageRecord{} }, + func(n *LedgerTransactionGroup, e *LedgerBreakageRecord) { + n.Edges.BreakageRecords = append(n.Edges.BreakageRecords, e) + }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *LedgerTransactionGroupQuery) loadTransactions(ctx context.Context, query *LedgerTransactionQuery, nodes []*LedgerTransactionGroup, init func(*LedgerTransactionGroup), assign func(*LedgerTransactionGroup, *LedgerTransaction)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*LedgerTransactionGroup) + 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(ledgertransaction.FieldGroupID) + } + query.Where(predicate.LedgerTransaction(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(ledgertransactiongroup.TransactionsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.GroupID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "group_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *LedgerTransactionGroupQuery) loadSourceBreakageRecords(ctx context.Context, query *LedgerBreakageRecordQuery, nodes []*LedgerTransactionGroup, init func(*LedgerTransactionGroup), assign func(*LedgerTransactionGroup, *LedgerBreakageRecord)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*LedgerTransactionGroup) + 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(ledgerbreakagerecord.FieldSourceTransactionGroupID) + } + query.Where(predicate.LedgerBreakageRecord(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(ledgertransactiongroup.SourceBreakageRecordsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.SourceTransactionGroupID + if fk == nil { + return fmt.Errorf(`foreign-key "source_transaction_group_id" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "source_transaction_group_id" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *LedgerTransactionGroupQuery) loadBreakageRecords(ctx context.Context, query *LedgerBreakageRecordQuery, nodes []*LedgerTransactionGroup, init func(*LedgerTransactionGroup), assign func(*LedgerTransactionGroup, *LedgerBreakageRecord)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*LedgerTransactionGroup) + 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(ledgerbreakagerecord.FieldBreakageTransactionGroupID) + } + query.Where(predicate.LedgerBreakageRecord(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(ledgertransactiongroup.BreakageRecordsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.BreakageTransactionGroupID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "breakage_transaction_group_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *LedgerTransactionGroupQuery) 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 *LedgerTransactionGroupQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(ledgertransactiongroup.Table, ledgertransactiongroup.Columns, sqlgraph.NewFieldSpec(ledgertransactiongroup.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, ledgertransactiongroup.FieldID) + for i := range fields { + if fields[i] != ledgertransactiongroup.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 *LedgerTransactionGroupQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(ledgertransactiongroup.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = ledgertransactiongroup.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 *LedgerTransactionGroupQuery) ForUpdate(opts ...sql.LockOption) *LedgerTransactionGroupQuery { + 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 *LedgerTransactionGroupQuery) ForShare(opts ...sql.LockOption) *LedgerTransactionGroupQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// LedgerTransactionGroupGroupBy is the group-by builder for LedgerTransactionGroup entities. +type LedgerTransactionGroupGroupBy struct { + selector + build *LedgerTransactionGroupQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *LedgerTransactionGroupGroupBy) Aggregate(fns ...AggregateFunc) *LedgerTransactionGroupGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *LedgerTransactionGroupGroupBy) 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[*LedgerTransactionGroupQuery, *LedgerTransactionGroupGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *LedgerTransactionGroupGroupBy) sqlScan(ctx context.Context, root *LedgerTransactionGroupQuery, 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) +} + +// LedgerTransactionGroupSelect is the builder for selecting fields of LedgerTransactionGroup entities. +type LedgerTransactionGroupSelect struct { + *LedgerTransactionGroupQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *LedgerTransactionGroupSelect) Aggregate(fns ...AggregateFunc) *LedgerTransactionGroupSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *LedgerTransactionGroupSelect) 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[*LedgerTransactionGroupQuery, *LedgerTransactionGroupSelect](ctx, _s.LedgerTransactionGroupQuery, _s, _s.inters, v) +} + +func (_s *LedgerTransactionGroupSelect) sqlScan(ctx context.Context, root *LedgerTransactionGroupQuery, 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/ent/db/ledgertransactiongroup_update.go b/ent/db/ledgertransactiongroup_update.go new file mode 100644 index 0000000000000000000000000000000000000000..8d26f5cd41499138ef629131c1e1edfe7a30e70b --- /dev/null +++ b/ent/db/ledgertransactiongroup_update.go @@ -0,0 +1,789 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/ledgerbreakagerecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransaction" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransactiongroup" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/models" +) + +// LedgerTransactionGroupUpdate is the builder for updating LedgerTransactionGroup entities. +type LedgerTransactionGroupUpdate struct { + config + hooks []Hook + mutation *LedgerTransactionGroupMutation +} + +// Where appends a list predicates to the LedgerTransactionGroupUpdate builder. +func (_u *LedgerTransactionGroupUpdate) Where(ps ...predicate.LedgerTransactionGroup) *LedgerTransactionGroupUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *LedgerTransactionGroupUpdate) SetAnnotations(v models.Annotations) *LedgerTransactionGroupUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *LedgerTransactionGroupUpdate) ClearAnnotations() *LedgerTransactionGroupUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *LedgerTransactionGroupUpdate) SetUpdatedAt(v time.Time) *LedgerTransactionGroupUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *LedgerTransactionGroupUpdate) SetDeletedAt(v time.Time) *LedgerTransactionGroupUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *LedgerTransactionGroupUpdate) SetNillableDeletedAt(v *time.Time) *LedgerTransactionGroupUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *LedgerTransactionGroupUpdate) ClearDeletedAt() *LedgerTransactionGroupUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// AddTransactionIDs adds the "transactions" edge to the LedgerTransaction entity by IDs. +func (_u *LedgerTransactionGroupUpdate) AddTransactionIDs(ids ...string) *LedgerTransactionGroupUpdate { + _u.mutation.AddTransactionIDs(ids...) + return _u +} + +// AddTransactions adds the "transactions" edges to the LedgerTransaction entity. +func (_u *LedgerTransactionGroupUpdate) AddTransactions(v ...*LedgerTransaction) *LedgerTransactionGroupUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddTransactionIDs(ids...) +} + +// AddSourceBreakageRecordIDs adds the "source_breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_u *LedgerTransactionGroupUpdate) AddSourceBreakageRecordIDs(ids ...string) *LedgerTransactionGroupUpdate { + _u.mutation.AddSourceBreakageRecordIDs(ids...) + return _u +} + +// AddSourceBreakageRecords adds the "source_breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerTransactionGroupUpdate) AddSourceBreakageRecords(v ...*LedgerBreakageRecord) *LedgerTransactionGroupUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSourceBreakageRecordIDs(ids...) +} + +// AddBreakageRecordIDs adds the "breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_u *LedgerTransactionGroupUpdate) AddBreakageRecordIDs(ids ...string) *LedgerTransactionGroupUpdate { + _u.mutation.AddBreakageRecordIDs(ids...) + return _u +} + +// AddBreakageRecords adds the "breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerTransactionGroupUpdate) AddBreakageRecords(v ...*LedgerBreakageRecord) *LedgerTransactionGroupUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddBreakageRecordIDs(ids...) +} + +// Mutation returns the LedgerTransactionGroupMutation object of the builder. +func (_u *LedgerTransactionGroupUpdate) Mutation() *LedgerTransactionGroupMutation { + return _u.mutation +} + +// ClearTransactions clears all "transactions" edges to the LedgerTransaction entity. +func (_u *LedgerTransactionGroupUpdate) ClearTransactions() *LedgerTransactionGroupUpdate { + _u.mutation.ClearTransactions() + return _u +} + +// RemoveTransactionIDs removes the "transactions" edge to LedgerTransaction entities by IDs. +func (_u *LedgerTransactionGroupUpdate) RemoveTransactionIDs(ids ...string) *LedgerTransactionGroupUpdate { + _u.mutation.RemoveTransactionIDs(ids...) + return _u +} + +// RemoveTransactions removes "transactions" edges to LedgerTransaction entities. +func (_u *LedgerTransactionGroupUpdate) RemoveTransactions(v ...*LedgerTransaction) *LedgerTransactionGroupUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveTransactionIDs(ids...) +} + +// ClearSourceBreakageRecords clears all "source_breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerTransactionGroupUpdate) ClearSourceBreakageRecords() *LedgerTransactionGroupUpdate { + _u.mutation.ClearSourceBreakageRecords() + return _u +} + +// RemoveSourceBreakageRecordIDs removes the "source_breakage_records" edge to LedgerBreakageRecord entities by IDs. +func (_u *LedgerTransactionGroupUpdate) RemoveSourceBreakageRecordIDs(ids ...string) *LedgerTransactionGroupUpdate { + _u.mutation.RemoveSourceBreakageRecordIDs(ids...) + return _u +} + +// RemoveSourceBreakageRecords removes "source_breakage_records" edges to LedgerBreakageRecord entities. +func (_u *LedgerTransactionGroupUpdate) RemoveSourceBreakageRecords(v ...*LedgerBreakageRecord) *LedgerTransactionGroupUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSourceBreakageRecordIDs(ids...) +} + +// ClearBreakageRecords clears all "breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerTransactionGroupUpdate) ClearBreakageRecords() *LedgerTransactionGroupUpdate { + _u.mutation.ClearBreakageRecords() + return _u +} + +// RemoveBreakageRecordIDs removes the "breakage_records" edge to LedgerBreakageRecord entities by IDs. +func (_u *LedgerTransactionGroupUpdate) RemoveBreakageRecordIDs(ids ...string) *LedgerTransactionGroupUpdate { + _u.mutation.RemoveBreakageRecordIDs(ids...) + return _u +} + +// RemoveBreakageRecords removes "breakage_records" edges to LedgerBreakageRecord entities. +func (_u *LedgerTransactionGroupUpdate) RemoveBreakageRecords(v ...*LedgerBreakageRecord) *LedgerTransactionGroupUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveBreakageRecordIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *LedgerTransactionGroupUpdate) 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 *LedgerTransactionGroupUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *LedgerTransactionGroupUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LedgerTransactionGroupUpdate) 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 *LedgerTransactionGroupUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := ledgertransactiongroup.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +func (_u *LedgerTransactionGroupUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(ledgertransactiongroup.Table, ledgertransactiongroup.Columns, sqlgraph.NewFieldSpec(ledgertransactiongroup.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.Annotations(); ok { + _spec.SetField(ledgertransactiongroup.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(ledgertransactiongroup.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(ledgertransactiongroup.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(ledgertransactiongroup.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(ledgertransactiongroup.FieldDeletedAt, field.TypeTime) + } + if _u.mutation.TransactionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.TransactionsTable, + Columns: []string{ledgertransactiongroup.TransactionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgertransaction.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedTransactionsIDs(); len(nodes) > 0 && !_u.mutation.TransactionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.TransactionsTable, + Columns: []string{ledgertransactiongroup.TransactionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgertransaction.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.TransactionsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.TransactionsTable, + Columns: []string{ledgertransactiongroup.TransactionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgertransaction.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.SourceBreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.SourceBreakageRecordsTable, + Columns: []string{ledgertransactiongroup.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSourceBreakageRecordsIDs(); len(nodes) > 0 && !_u.mutation.SourceBreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.SourceBreakageRecordsTable, + Columns: []string{ledgertransactiongroup.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.SourceBreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.SourceBreakageRecordsTable, + Columns: []string{ledgertransactiongroup.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.BreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.BreakageRecordsTable, + Columns: []string{ledgertransactiongroup.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedBreakageRecordsIDs(); len(nodes) > 0 && !_u.mutation.BreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.BreakageRecordsTable, + Columns: []string{ledgertransactiongroup.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.BreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.BreakageRecordsTable, + Columns: []string{ledgertransactiongroup.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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{ledgertransactiongroup.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// LedgerTransactionGroupUpdateOne is the builder for updating a single LedgerTransactionGroup entity. +type LedgerTransactionGroupUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LedgerTransactionGroupMutation +} + +// SetAnnotations sets the "annotations" field. +func (_u *LedgerTransactionGroupUpdateOne) SetAnnotations(v models.Annotations) *LedgerTransactionGroupUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *LedgerTransactionGroupUpdateOne) ClearAnnotations() *LedgerTransactionGroupUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *LedgerTransactionGroupUpdateOne) SetUpdatedAt(v time.Time) *LedgerTransactionGroupUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *LedgerTransactionGroupUpdateOne) SetDeletedAt(v time.Time) *LedgerTransactionGroupUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *LedgerTransactionGroupUpdateOne) SetNillableDeletedAt(v *time.Time) *LedgerTransactionGroupUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *LedgerTransactionGroupUpdateOne) ClearDeletedAt() *LedgerTransactionGroupUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// AddTransactionIDs adds the "transactions" edge to the LedgerTransaction entity by IDs. +func (_u *LedgerTransactionGroupUpdateOne) AddTransactionIDs(ids ...string) *LedgerTransactionGroupUpdateOne { + _u.mutation.AddTransactionIDs(ids...) + return _u +} + +// AddTransactions adds the "transactions" edges to the LedgerTransaction entity. +func (_u *LedgerTransactionGroupUpdateOne) AddTransactions(v ...*LedgerTransaction) *LedgerTransactionGroupUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddTransactionIDs(ids...) +} + +// AddSourceBreakageRecordIDs adds the "source_breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_u *LedgerTransactionGroupUpdateOne) AddSourceBreakageRecordIDs(ids ...string) *LedgerTransactionGroupUpdateOne { + _u.mutation.AddSourceBreakageRecordIDs(ids...) + return _u +} + +// AddSourceBreakageRecords adds the "source_breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerTransactionGroupUpdateOne) AddSourceBreakageRecords(v ...*LedgerBreakageRecord) *LedgerTransactionGroupUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSourceBreakageRecordIDs(ids...) +} + +// AddBreakageRecordIDs adds the "breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (_u *LedgerTransactionGroupUpdateOne) AddBreakageRecordIDs(ids ...string) *LedgerTransactionGroupUpdateOne { + _u.mutation.AddBreakageRecordIDs(ids...) + return _u +} + +// AddBreakageRecords adds the "breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerTransactionGroupUpdateOne) AddBreakageRecords(v ...*LedgerBreakageRecord) *LedgerTransactionGroupUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddBreakageRecordIDs(ids...) +} + +// Mutation returns the LedgerTransactionGroupMutation object of the builder. +func (_u *LedgerTransactionGroupUpdateOne) Mutation() *LedgerTransactionGroupMutation { + return _u.mutation +} + +// ClearTransactions clears all "transactions" edges to the LedgerTransaction entity. +func (_u *LedgerTransactionGroupUpdateOne) ClearTransactions() *LedgerTransactionGroupUpdateOne { + _u.mutation.ClearTransactions() + return _u +} + +// RemoveTransactionIDs removes the "transactions" edge to LedgerTransaction entities by IDs. +func (_u *LedgerTransactionGroupUpdateOne) RemoveTransactionIDs(ids ...string) *LedgerTransactionGroupUpdateOne { + _u.mutation.RemoveTransactionIDs(ids...) + return _u +} + +// RemoveTransactions removes "transactions" edges to LedgerTransaction entities. +func (_u *LedgerTransactionGroupUpdateOne) RemoveTransactions(v ...*LedgerTransaction) *LedgerTransactionGroupUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveTransactionIDs(ids...) +} + +// ClearSourceBreakageRecords clears all "source_breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerTransactionGroupUpdateOne) ClearSourceBreakageRecords() *LedgerTransactionGroupUpdateOne { + _u.mutation.ClearSourceBreakageRecords() + return _u +} + +// RemoveSourceBreakageRecordIDs removes the "source_breakage_records" edge to LedgerBreakageRecord entities by IDs. +func (_u *LedgerTransactionGroupUpdateOne) RemoveSourceBreakageRecordIDs(ids ...string) *LedgerTransactionGroupUpdateOne { + _u.mutation.RemoveSourceBreakageRecordIDs(ids...) + return _u +} + +// RemoveSourceBreakageRecords removes "source_breakage_records" edges to LedgerBreakageRecord entities. +func (_u *LedgerTransactionGroupUpdateOne) RemoveSourceBreakageRecords(v ...*LedgerBreakageRecord) *LedgerTransactionGroupUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSourceBreakageRecordIDs(ids...) +} + +// ClearBreakageRecords clears all "breakage_records" edges to the LedgerBreakageRecord entity. +func (_u *LedgerTransactionGroupUpdateOne) ClearBreakageRecords() *LedgerTransactionGroupUpdateOne { + _u.mutation.ClearBreakageRecords() + return _u +} + +// RemoveBreakageRecordIDs removes the "breakage_records" edge to LedgerBreakageRecord entities by IDs. +func (_u *LedgerTransactionGroupUpdateOne) RemoveBreakageRecordIDs(ids ...string) *LedgerTransactionGroupUpdateOne { + _u.mutation.RemoveBreakageRecordIDs(ids...) + return _u +} + +// RemoveBreakageRecords removes "breakage_records" edges to LedgerBreakageRecord entities. +func (_u *LedgerTransactionGroupUpdateOne) RemoveBreakageRecords(v ...*LedgerBreakageRecord) *LedgerTransactionGroupUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveBreakageRecordIDs(ids...) +} + +// Where appends a list predicates to the LedgerTransactionGroupUpdate builder. +func (_u *LedgerTransactionGroupUpdateOne) Where(ps ...predicate.LedgerTransactionGroup) *LedgerTransactionGroupUpdateOne { + _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 *LedgerTransactionGroupUpdateOne) Select(field string, fields ...string) *LedgerTransactionGroupUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated LedgerTransactionGroup entity. +func (_u *LedgerTransactionGroupUpdateOne) Save(ctx context.Context) (*LedgerTransactionGroup, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *LedgerTransactionGroupUpdateOne) SaveX(ctx context.Context) *LedgerTransactionGroup { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *LedgerTransactionGroupUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LedgerTransactionGroupUpdateOne) 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 *LedgerTransactionGroupUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := ledgertransactiongroup.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +func (_u *LedgerTransactionGroupUpdateOne) sqlSave(ctx context.Context) (_node *LedgerTransactionGroup, err error) { + _spec := sqlgraph.NewUpdateSpec(ledgertransactiongroup.Table, ledgertransactiongroup.Columns, sqlgraph.NewFieldSpec(ledgertransactiongroup.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "LedgerTransactionGroup.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, ledgertransactiongroup.FieldID) + for _, f := range fields { + if !ledgertransactiongroup.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != ledgertransactiongroup.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.Annotations(); ok { + _spec.SetField(ledgertransactiongroup.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(ledgertransactiongroup.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(ledgertransactiongroup.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(ledgertransactiongroup.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(ledgertransactiongroup.FieldDeletedAt, field.TypeTime) + } + if _u.mutation.TransactionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.TransactionsTable, + Columns: []string{ledgertransactiongroup.TransactionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgertransaction.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedTransactionsIDs(); len(nodes) > 0 && !_u.mutation.TransactionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.TransactionsTable, + Columns: []string{ledgertransactiongroup.TransactionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgertransaction.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.TransactionsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.TransactionsTable, + Columns: []string{ledgertransactiongroup.TransactionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgertransaction.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.SourceBreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.SourceBreakageRecordsTable, + Columns: []string{ledgertransactiongroup.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSourceBreakageRecordsIDs(); len(nodes) > 0 && !_u.mutation.SourceBreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.SourceBreakageRecordsTable, + Columns: []string{ledgertransactiongroup.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.SourceBreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.SourceBreakageRecordsTable, + Columns: []string{ledgertransactiongroup.SourceBreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.BreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.BreakageRecordsTable, + Columns: []string{ledgertransactiongroup.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedBreakageRecordsIDs(); len(nodes) > 0 && !_u.mutation.BreakageRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.BreakageRecordsTable, + Columns: []string{ledgertransactiongroup.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.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.BreakageRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: ledgertransactiongroup.BreakageRecordsTable, + Columns: []string{ledgertransactiongroup.BreakageRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(ledgerbreakagerecord.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &LedgerTransactionGroup{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{ledgertransactiongroup.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/ent/db/llmcostprice.go b/ent/db/llmcostprice.go new file mode 100644 index 0000000000000000000000000000000000000000..688a26dd27b0a66370e99214379726f6fad6fa2a --- /dev/null +++ b/ent/db/llmcostprice.go @@ -0,0 +1,311 @@ +// 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/llmcostprice" + "github.com/openmeterio/openmeter/openmeter/llmcost" +) + +// LLMCostPrice is the model entity for the LLMCostPrice schema. +type LLMCostPrice struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // Metadata holds the value of the "metadata" field. + Metadata map[string]string `json:"metadata,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"` + // Nil for global prices, set for namespace overrides + Namespace *string `json:"namespace,omitempty"` + // Provider holds the value of the "provider" field. + Provider string `json:"provider,omitempty"` + // ModelID holds the value of the "model_id" field. + ModelID string `json:"model_id,omitempty"` + // ModelName holds the value of the "model_name" field. + ModelName string `json:"model_name,omitempty"` + // InputPerToken holds the value of the "input_per_token" field. + InputPerToken alpacadecimal.Decimal `json:"input_per_token,omitempty"` + // OutputPerToken holds the value of the "output_per_token" field. + OutputPerToken alpacadecimal.Decimal `json:"output_per_token,omitempty"` + // CacheReadPerToken holds the value of the "cache_read_per_token" field. + CacheReadPerToken alpacadecimal.Decimal `json:"cache_read_per_token,omitempty"` + // ReasoningPerToken holds the value of the "reasoning_per_token" field. + ReasoningPerToken alpacadecimal.Decimal `json:"reasoning_per_token,omitempty"` + // CacheWritePerToken holds the value of the "cache_write_per_token" field. + CacheWritePerToken alpacadecimal.Decimal `json:"cache_write_per_token,omitempty"` + // Currency holds the value of the "currency" field. + Currency string `json:"currency,omitempty"` + // Source holds the value of the "source" field. + Source string `json:"source,omitempty"` + // SourcePrices holds the value of the "source_prices" field. + SourcePrices llmcost.SourcePricesMap `json:"source_prices,omitempty"` + // EffectiveFrom holds the value of the "effective_from" field. + EffectiveFrom time.Time `json:"effective_from,omitempty"` + // EffectiveTo holds the value of the "effective_to" field. + EffectiveTo *time.Time `json:"effective_to,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LLMCostPrice) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case llmcostprice.FieldMetadata: + values[i] = new([]byte) + case llmcostprice.FieldInputPerToken, llmcostprice.FieldOutputPerToken, llmcostprice.FieldCacheReadPerToken, llmcostprice.FieldReasoningPerToken, llmcostprice.FieldCacheWritePerToken: + values[i] = new(alpacadecimal.Decimal) + case llmcostprice.FieldID, llmcostprice.FieldNamespace, llmcostprice.FieldProvider, llmcostprice.FieldModelID, llmcostprice.FieldModelName, llmcostprice.FieldCurrency, llmcostprice.FieldSource: + values[i] = new(sql.NullString) + case llmcostprice.FieldCreatedAt, llmcostprice.FieldUpdatedAt, llmcostprice.FieldDeletedAt, llmcostprice.FieldEffectiveFrom, llmcostprice.FieldEffectiveTo: + values[i] = new(sql.NullTime) + case llmcostprice.FieldSourcePrices: + values[i] = llmcostprice.ValueScanner.SourcePrices.ScanValue() + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the LLMCostPrice fields. +func (_m *LLMCostPrice) 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 llmcostprice.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 llmcostprice.FieldMetadata: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field metadata", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Metadata); err != nil { + return fmt.Errorf("unmarshal field metadata: %w", err) + } + } + case llmcostprice.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 llmcostprice.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 llmcostprice.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 llmcostprice.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 = new(string) + *_m.Namespace = value.String + } + case llmcostprice.FieldProvider: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field provider", values[i]) + } else if value.Valid { + _m.Provider = value.String + } + case llmcostprice.FieldModelID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field model_id", values[i]) + } else if value.Valid { + _m.ModelID = value.String + } + case llmcostprice.FieldModelName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field model_name", values[i]) + } else if value.Valid { + _m.ModelName = value.String + } + case llmcostprice.FieldInputPerToken: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field input_per_token", values[i]) + } else if value != nil { + _m.InputPerToken = *value + } + case llmcostprice.FieldOutputPerToken: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field output_per_token", values[i]) + } else if value != nil { + _m.OutputPerToken = *value + } + case llmcostprice.FieldCacheReadPerToken: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field cache_read_per_token", values[i]) + } else if value != nil { + _m.CacheReadPerToken = *value + } + case llmcostprice.FieldReasoningPerToken: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field reasoning_per_token", values[i]) + } else if value != nil { + _m.ReasoningPerToken = *value + } + case llmcostprice.FieldCacheWritePerToken: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field cache_write_per_token", values[i]) + } else if value != nil { + _m.CacheWritePerToken = *value + } + case llmcostprice.FieldCurrency: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field currency", values[i]) + } else if value.Valid { + _m.Currency = value.String + } + case llmcostprice.FieldSource: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field source", values[i]) + } else if value.Valid { + _m.Source = value.String + } + case llmcostprice.FieldSourcePrices: + if value, err := llmcostprice.ValueScanner.SourcePrices.FromValue(values[i]); err != nil { + return err + } else { + _m.SourcePrices = value + } + case llmcostprice.FieldEffectiveFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field effective_from", values[i]) + } else if value.Valid { + _m.EffectiveFrom = value.Time + } + case llmcostprice.FieldEffectiveTo: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field effective_to", values[i]) + } else if value.Valid { + _m.EffectiveTo = new(time.Time) + *_m.EffectiveTo = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the LLMCostPrice. +// This includes values selected through modifiers, order, etc. +func (_m *LLMCostPrice) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this LLMCostPrice. +// Note that you need to call LLMCostPrice.Unwrap() before calling this method if this LLMCostPrice +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *LLMCostPrice) Update() *LLMCostPriceUpdateOne { + return NewLLMCostPriceClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the LLMCostPrice 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 *LLMCostPrice) Unwrap() *LLMCostPrice { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: LLMCostPrice is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *LLMCostPrice) String() string { + var builder strings.Builder + builder.WriteString("LLMCostPrice(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("metadata=") + builder.WriteString(fmt.Sprintf("%v", _m.Metadata)) + 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(", ") + if v := _m.Namespace; v != nil { + builder.WriteString("namespace=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("provider=") + builder.WriteString(_m.Provider) + builder.WriteString(", ") + builder.WriteString("model_id=") + builder.WriteString(_m.ModelID) + builder.WriteString(", ") + builder.WriteString("model_name=") + builder.WriteString(_m.ModelName) + builder.WriteString(", ") + builder.WriteString("input_per_token=") + builder.WriteString(fmt.Sprintf("%v", _m.InputPerToken)) + builder.WriteString(", ") + builder.WriteString("output_per_token=") + builder.WriteString(fmt.Sprintf("%v", _m.OutputPerToken)) + builder.WriteString(", ") + builder.WriteString("cache_read_per_token=") + builder.WriteString(fmt.Sprintf("%v", _m.CacheReadPerToken)) + builder.WriteString(", ") + builder.WriteString("reasoning_per_token=") + builder.WriteString(fmt.Sprintf("%v", _m.ReasoningPerToken)) + builder.WriteString(", ") + builder.WriteString("cache_write_per_token=") + builder.WriteString(fmt.Sprintf("%v", _m.CacheWritePerToken)) + builder.WriteString(", ") + builder.WriteString("currency=") + builder.WriteString(_m.Currency) + builder.WriteString(", ") + builder.WriteString("source=") + builder.WriteString(_m.Source) + builder.WriteString(", ") + builder.WriteString("source_prices=") + builder.WriteString(fmt.Sprintf("%v", _m.SourcePrices)) + builder.WriteString(", ") + builder.WriteString("effective_from=") + builder.WriteString(_m.EffectiveFrom.Format(time.ANSIC)) + builder.WriteString(", ") + if v := _m.EffectiveTo; v != nil { + builder.WriteString("effective_to=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteByte(')') + return builder.String() +} + +// LLMCostPrices is a parsable slice of LLMCostPrice. +type LLMCostPrices []*LLMCostPrice diff --git a/ent/db/llmcostprice/llmcostprice.go b/ent/db/llmcostprice/llmcostprice.go new file mode 100644 index 0000000000000000000000000000000000000000..50585c62fb1288c5a326fae00129bcf7d76dc3f1 --- /dev/null +++ b/ent/db/llmcostprice/llmcostprice.go @@ -0,0 +1,216 @@ +// Code generated by ent, DO NOT EDIT. + +package llmcostprice + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/schema/field" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/llmcost" +) + +const ( + // Label holds the string label denoting the llmcostprice type in the database. + Label = "llm_cost_price" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // 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" + // FieldNamespace holds the string denoting the namespace field in the database. + FieldNamespace = "namespace" + // FieldProvider holds the string denoting the provider field in the database. + FieldProvider = "provider" + // FieldModelID holds the string denoting the model_id field in the database. + FieldModelID = "model_id" + // FieldModelName holds the string denoting the model_name field in the database. + FieldModelName = "model_name" + // FieldInputPerToken holds the string denoting the input_per_token field in the database. + FieldInputPerToken = "input_per_token" + // FieldOutputPerToken holds the string denoting the output_per_token field in the database. + FieldOutputPerToken = "output_per_token" + // FieldCacheReadPerToken holds the string denoting the cache_read_per_token field in the database. + FieldCacheReadPerToken = "cache_read_per_token" + // FieldReasoningPerToken holds the string denoting the reasoning_per_token field in the database. + FieldReasoningPerToken = "reasoning_per_token" + // FieldCacheWritePerToken holds the string denoting the cache_write_per_token field in the database. + FieldCacheWritePerToken = "cache_write_per_token" + // FieldCurrency holds the string denoting the currency field in the database. + FieldCurrency = "currency" + // FieldSource holds the string denoting the source field in the database. + FieldSource = "source" + // FieldSourcePrices holds the string denoting the source_prices field in the database. + FieldSourcePrices = "source_prices" + // FieldEffectiveFrom holds the string denoting the effective_from field in the database. + FieldEffectiveFrom = "effective_from" + // FieldEffectiveTo holds the string denoting the effective_to field in the database. + FieldEffectiveTo = "effective_to" + // Table holds the table name of the llmcostprice in the database. + Table = "llm_cost_prices" +) + +// Columns holds all SQL columns for llmcostprice fields. +var Columns = []string{ + FieldID, + FieldMetadata, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldNamespace, + FieldProvider, + FieldModelID, + FieldModelName, + FieldInputPerToken, + FieldOutputPerToken, + FieldCacheReadPerToken, + FieldReasoningPerToken, + FieldCacheWritePerToken, + FieldCurrency, + FieldSource, + FieldSourcePrices, + FieldEffectiveFrom, + FieldEffectiveTo, +} + +// 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 ( + // 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 + // ProviderValidator is a validator for the "provider" field. It is called by the builders before save. + ProviderValidator func(string) error + // ModelIDValidator is a validator for the "model_id" field. It is called by the builders before save. + ModelIDValidator func(string) error + // DefaultModelName holds the default value on creation for the "model_name" field. + DefaultModelName string + // DefaultCacheReadPerToken holds the default value on creation for the "cache_read_per_token" field. + DefaultCacheReadPerToken alpacadecimal.Decimal + // DefaultReasoningPerToken holds the default value on creation for the "reasoning_per_token" field. + DefaultReasoningPerToken alpacadecimal.Decimal + // DefaultCacheWritePerToken holds the default value on creation for the "cache_write_per_token" field. + DefaultCacheWritePerToken alpacadecimal.Decimal + // DefaultCurrency holds the default value on creation for the "currency" field. + DefaultCurrency string + // CurrencyValidator is a validator for the "currency" field. It is called by the builders before save. + CurrencyValidator func(string) error + // SourceValidator is a validator for the "source" field. It is called by the builders before save. + SourceValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string + // ValueScanner of all LLMCostPrice fields. + ValueScanner struct { + SourcePrices field.TypeValueScanner[llmcost.SourcePricesMap] + } +) + +// OrderOption defines the ordering options for the LLMCostPrice 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() +} + +// 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() +} + +// ByNamespace orders the results by the namespace field. +func ByNamespace(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldNamespace, opts...).ToFunc() +} + +// ByProvider orders the results by the provider field. +func ByProvider(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldProvider, opts...).ToFunc() +} + +// ByModelID orders the results by the model_id field. +func ByModelID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldModelID, opts...).ToFunc() +} + +// ByModelName orders the results by the model_name field. +func ByModelName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldModelName, opts...).ToFunc() +} + +// ByInputPerToken orders the results by the input_per_token field. +func ByInputPerToken(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInputPerToken, opts...).ToFunc() +} + +// ByOutputPerToken orders the results by the output_per_token field. +func ByOutputPerToken(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldOutputPerToken, opts...).ToFunc() +} + +// ByCacheReadPerToken orders the results by the cache_read_per_token field. +func ByCacheReadPerToken(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCacheReadPerToken, opts...).ToFunc() +} + +// ByReasoningPerToken orders the results by the reasoning_per_token field. +func ByReasoningPerToken(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldReasoningPerToken, opts...).ToFunc() +} + +// ByCacheWritePerToken orders the results by the cache_write_per_token field. +func ByCacheWritePerToken(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCacheWritePerToken, opts...).ToFunc() +} + +// ByCurrency orders the results by the currency field. +func ByCurrency(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCurrency, opts...).ToFunc() +} + +// BySource orders the results by the source field. +func BySource(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSource, opts...).ToFunc() +} + +// BySourcePrices orders the results by the source_prices field. +func BySourcePrices(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSourcePrices, opts...).ToFunc() +} + +// ByEffectiveFrom orders the results by the effective_from field. +func ByEffectiveFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEffectiveFrom, opts...).ToFunc() +} + +// ByEffectiveTo orders the results by the effective_to field. +func ByEffectiveTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEffectiveTo, opts...).ToFunc() +} diff --git a/ent/db/llmcostprice/where.go b/ent/db/llmcostprice/where.go new file mode 100644 index 0000000000000000000000000000000000000000..da5154a8ad92dbdfb735864ea883a41fe9ef7b00 --- /dev/null +++ b/ent/db/llmcostprice/where.go @@ -0,0 +1,1001 @@ +// Code generated by ent, DO NOT EDIT. + +package llmcostprice + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "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.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldContainsFold(FieldID, id)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(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.LLMCostPrice { + return predicate.LLMCostPrice(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.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldNamespace, v)) +} + +// Provider applies equality check predicate on the "provider" field. It's identical to ProviderEQ. +func Provider(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldProvider, v)) +} + +// ModelID applies equality check predicate on the "model_id" field. It's identical to ModelIDEQ. +func ModelID(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldModelID, v)) +} + +// ModelName applies equality check predicate on the "model_name" field. It's identical to ModelNameEQ. +func ModelName(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldModelName, v)) +} + +// InputPerToken applies equality check predicate on the "input_per_token" field. It's identical to InputPerTokenEQ. +func InputPerToken(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldInputPerToken, v)) +} + +// OutputPerToken applies equality check predicate on the "output_per_token" field. It's identical to OutputPerTokenEQ. +func OutputPerToken(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldOutputPerToken, v)) +} + +// CacheReadPerToken applies equality check predicate on the "cache_read_per_token" field. It's identical to CacheReadPerTokenEQ. +func CacheReadPerToken(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldCacheReadPerToken, v)) +} + +// ReasoningPerToken applies equality check predicate on the "reasoning_per_token" field. It's identical to ReasoningPerTokenEQ. +func ReasoningPerToken(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldReasoningPerToken, v)) +} + +// CacheWritePerToken applies equality check predicate on the "cache_write_per_token" field. It's identical to CacheWritePerTokenEQ. +func CacheWritePerToken(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldCacheWritePerToken, v)) +} + +// Currency applies equality check predicate on the "currency" field. It's identical to CurrencyEQ. +func Currency(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldCurrency, v)) +} + +// Source applies equality check predicate on the "source" field. It's identical to SourceEQ. +func Source(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldSource, v)) +} + +// EffectiveFrom applies equality check predicate on the "effective_from" field. It's identical to EffectiveFromEQ. +func EffectiveFrom(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldEffectiveFrom, v)) +} + +// EffectiveTo applies equality check predicate on the "effective_to" field. It's identical to EffectiveToEQ. +func EffectiveTo(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldEffectiveTo, v)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotNull(FieldMetadata)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotNull(FieldDeletedAt)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceIsNil applies the IsNil predicate on the "namespace" field. +func NamespaceIsNil() predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIsNull(FieldNamespace)) +} + +// NamespaceNotNil applies the NotNil predicate on the "namespace" field. +func NamespaceNotNil() predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotNull(FieldNamespace)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldContainsFold(FieldNamespace, v)) +} + +// ProviderEQ applies the EQ predicate on the "provider" field. +func ProviderEQ(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldProvider, v)) +} + +// ProviderNEQ applies the NEQ predicate on the "provider" field. +func ProviderNEQ(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNEQ(FieldProvider, v)) +} + +// ProviderIn applies the In predicate on the "provider" field. +func ProviderIn(vs ...string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIn(FieldProvider, vs...)) +} + +// ProviderNotIn applies the NotIn predicate on the "provider" field. +func ProviderNotIn(vs ...string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotIn(FieldProvider, vs...)) +} + +// ProviderGT applies the GT predicate on the "provider" field. +func ProviderGT(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGT(FieldProvider, v)) +} + +// ProviderGTE applies the GTE predicate on the "provider" field. +func ProviderGTE(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGTE(FieldProvider, v)) +} + +// ProviderLT applies the LT predicate on the "provider" field. +func ProviderLT(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLT(FieldProvider, v)) +} + +// ProviderLTE applies the LTE predicate on the "provider" field. +func ProviderLTE(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLTE(FieldProvider, v)) +} + +// ProviderContains applies the Contains predicate on the "provider" field. +func ProviderContains(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldContains(FieldProvider, v)) +} + +// ProviderHasPrefix applies the HasPrefix predicate on the "provider" field. +func ProviderHasPrefix(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldHasPrefix(FieldProvider, v)) +} + +// ProviderHasSuffix applies the HasSuffix predicate on the "provider" field. +func ProviderHasSuffix(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldHasSuffix(FieldProvider, v)) +} + +// ProviderEqualFold applies the EqualFold predicate on the "provider" field. +func ProviderEqualFold(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEqualFold(FieldProvider, v)) +} + +// ProviderContainsFold applies the ContainsFold predicate on the "provider" field. +func ProviderContainsFold(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldContainsFold(FieldProvider, v)) +} + +// ModelIDEQ applies the EQ predicate on the "model_id" field. +func ModelIDEQ(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldModelID, v)) +} + +// ModelIDNEQ applies the NEQ predicate on the "model_id" field. +func ModelIDNEQ(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNEQ(FieldModelID, v)) +} + +// ModelIDIn applies the In predicate on the "model_id" field. +func ModelIDIn(vs ...string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIn(FieldModelID, vs...)) +} + +// ModelIDNotIn applies the NotIn predicate on the "model_id" field. +func ModelIDNotIn(vs ...string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotIn(FieldModelID, vs...)) +} + +// ModelIDGT applies the GT predicate on the "model_id" field. +func ModelIDGT(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGT(FieldModelID, v)) +} + +// ModelIDGTE applies the GTE predicate on the "model_id" field. +func ModelIDGTE(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGTE(FieldModelID, v)) +} + +// ModelIDLT applies the LT predicate on the "model_id" field. +func ModelIDLT(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLT(FieldModelID, v)) +} + +// ModelIDLTE applies the LTE predicate on the "model_id" field. +func ModelIDLTE(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLTE(FieldModelID, v)) +} + +// ModelIDContains applies the Contains predicate on the "model_id" field. +func ModelIDContains(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldContains(FieldModelID, v)) +} + +// ModelIDHasPrefix applies the HasPrefix predicate on the "model_id" field. +func ModelIDHasPrefix(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldHasPrefix(FieldModelID, v)) +} + +// ModelIDHasSuffix applies the HasSuffix predicate on the "model_id" field. +func ModelIDHasSuffix(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldHasSuffix(FieldModelID, v)) +} + +// ModelIDEqualFold applies the EqualFold predicate on the "model_id" field. +func ModelIDEqualFold(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEqualFold(FieldModelID, v)) +} + +// ModelIDContainsFold applies the ContainsFold predicate on the "model_id" field. +func ModelIDContainsFold(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldContainsFold(FieldModelID, v)) +} + +// ModelNameEQ applies the EQ predicate on the "model_name" field. +func ModelNameEQ(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldModelName, v)) +} + +// ModelNameNEQ applies the NEQ predicate on the "model_name" field. +func ModelNameNEQ(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNEQ(FieldModelName, v)) +} + +// ModelNameIn applies the In predicate on the "model_name" field. +func ModelNameIn(vs ...string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIn(FieldModelName, vs...)) +} + +// ModelNameNotIn applies the NotIn predicate on the "model_name" field. +func ModelNameNotIn(vs ...string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotIn(FieldModelName, vs...)) +} + +// ModelNameGT applies the GT predicate on the "model_name" field. +func ModelNameGT(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGT(FieldModelName, v)) +} + +// ModelNameGTE applies the GTE predicate on the "model_name" field. +func ModelNameGTE(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGTE(FieldModelName, v)) +} + +// ModelNameLT applies the LT predicate on the "model_name" field. +func ModelNameLT(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLT(FieldModelName, v)) +} + +// ModelNameLTE applies the LTE predicate on the "model_name" field. +func ModelNameLTE(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLTE(FieldModelName, v)) +} + +// ModelNameContains applies the Contains predicate on the "model_name" field. +func ModelNameContains(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldContains(FieldModelName, v)) +} + +// ModelNameHasPrefix applies the HasPrefix predicate on the "model_name" field. +func ModelNameHasPrefix(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldHasPrefix(FieldModelName, v)) +} + +// ModelNameHasSuffix applies the HasSuffix predicate on the "model_name" field. +func ModelNameHasSuffix(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldHasSuffix(FieldModelName, v)) +} + +// ModelNameEqualFold applies the EqualFold predicate on the "model_name" field. +func ModelNameEqualFold(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEqualFold(FieldModelName, v)) +} + +// ModelNameContainsFold applies the ContainsFold predicate on the "model_name" field. +func ModelNameContainsFold(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldContainsFold(FieldModelName, v)) +} + +// InputPerTokenEQ applies the EQ predicate on the "input_per_token" field. +func InputPerTokenEQ(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldInputPerToken, v)) +} + +// InputPerTokenNEQ applies the NEQ predicate on the "input_per_token" field. +func InputPerTokenNEQ(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNEQ(FieldInputPerToken, v)) +} + +// InputPerTokenIn applies the In predicate on the "input_per_token" field. +func InputPerTokenIn(vs ...alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIn(FieldInputPerToken, vs...)) +} + +// InputPerTokenNotIn applies the NotIn predicate on the "input_per_token" field. +func InputPerTokenNotIn(vs ...alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotIn(FieldInputPerToken, vs...)) +} + +// InputPerTokenGT applies the GT predicate on the "input_per_token" field. +func InputPerTokenGT(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGT(FieldInputPerToken, v)) +} + +// InputPerTokenGTE applies the GTE predicate on the "input_per_token" field. +func InputPerTokenGTE(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGTE(FieldInputPerToken, v)) +} + +// InputPerTokenLT applies the LT predicate on the "input_per_token" field. +func InputPerTokenLT(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLT(FieldInputPerToken, v)) +} + +// InputPerTokenLTE applies the LTE predicate on the "input_per_token" field. +func InputPerTokenLTE(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLTE(FieldInputPerToken, v)) +} + +// OutputPerTokenEQ applies the EQ predicate on the "output_per_token" field. +func OutputPerTokenEQ(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldOutputPerToken, v)) +} + +// OutputPerTokenNEQ applies the NEQ predicate on the "output_per_token" field. +func OutputPerTokenNEQ(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNEQ(FieldOutputPerToken, v)) +} + +// OutputPerTokenIn applies the In predicate on the "output_per_token" field. +func OutputPerTokenIn(vs ...alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIn(FieldOutputPerToken, vs...)) +} + +// OutputPerTokenNotIn applies the NotIn predicate on the "output_per_token" field. +func OutputPerTokenNotIn(vs ...alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotIn(FieldOutputPerToken, vs...)) +} + +// OutputPerTokenGT applies the GT predicate on the "output_per_token" field. +func OutputPerTokenGT(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGT(FieldOutputPerToken, v)) +} + +// OutputPerTokenGTE applies the GTE predicate on the "output_per_token" field. +func OutputPerTokenGTE(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGTE(FieldOutputPerToken, v)) +} + +// OutputPerTokenLT applies the LT predicate on the "output_per_token" field. +func OutputPerTokenLT(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLT(FieldOutputPerToken, v)) +} + +// OutputPerTokenLTE applies the LTE predicate on the "output_per_token" field. +func OutputPerTokenLTE(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLTE(FieldOutputPerToken, v)) +} + +// CacheReadPerTokenEQ applies the EQ predicate on the "cache_read_per_token" field. +func CacheReadPerTokenEQ(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldCacheReadPerToken, v)) +} + +// CacheReadPerTokenNEQ applies the NEQ predicate on the "cache_read_per_token" field. +func CacheReadPerTokenNEQ(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNEQ(FieldCacheReadPerToken, v)) +} + +// CacheReadPerTokenIn applies the In predicate on the "cache_read_per_token" field. +func CacheReadPerTokenIn(vs ...alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIn(FieldCacheReadPerToken, vs...)) +} + +// CacheReadPerTokenNotIn applies the NotIn predicate on the "cache_read_per_token" field. +func CacheReadPerTokenNotIn(vs ...alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotIn(FieldCacheReadPerToken, vs...)) +} + +// CacheReadPerTokenGT applies the GT predicate on the "cache_read_per_token" field. +func CacheReadPerTokenGT(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGT(FieldCacheReadPerToken, v)) +} + +// CacheReadPerTokenGTE applies the GTE predicate on the "cache_read_per_token" field. +func CacheReadPerTokenGTE(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGTE(FieldCacheReadPerToken, v)) +} + +// CacheReadPerTokenLT applies the LT predicate on the "cache_read_per_token" field. +func CacheReadPerTokenLT(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLT(FieldCacheReadPerToken, v)) +} + +// CacheReadPerTokenLTE applies the LTE predicate on the "cache_read_per_token" field. +func CacheReadPerTokenLTE(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLTE(FieldCacheReadPerToken, v)) +} + +// ReasoningPerTokenEQ applies the EQ predicate on the "reasoning_per_token" field. +func ReasoningPerTokenEQ(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldReasoningPerToken, v)) +} + +// ReasoningPerTokenNEQ applies the NEQ predicate on the "reasoning_per_token" field. +func ReasoningPerTokenNEQ(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNEQ(FieldReasoningPerToken, v)) +} + +// ReasoningPerTokenIn applies the In predicate on the "reasoning_per_token" field. +func ReasoningPerTokenIn(vs ...alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIn(FieldReasoningPerToken, vs...)) +} + +// ReasoningPerTokenNotIn applies the NotIn predicate on the "reasoning_per_token" field. +func ReasoningPerTokenNotIn(vs ...alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotIn(FieldReasoningPerToken, vs...)) +} + +// ReasoningPerTokenGT applies the GT predicate on the "reasoning_per_token" field. +func ReasoningPerTokenGT(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGT(FieldReasoningPerToken, v)) +} + +// ReasoningPerTokenGTE applies the GTE predicate on the "reasoning_per_token" field. +func ReasoningPerTokenGTE(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGTE(FieldReasoningPerToken, v)) +} + +// ReasoningPerTokenLT applies the LT predicate on the "reasoning_per_token" field. +func ReasoningPerTokenLT(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLT(FieldReasoningPerToken, v)) +} + +// ReasoningPerTokenLTE applies the LTE predicate on the "reasoning_per_token" field. +func ReasoningPerTokenLTE(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLTE(FieldReasoningPerToken, v)) +} + +// CacheWritePerTokenEQ applies the EQ predicate on the "cache_write_per_token" field. +func CacheWritePerTokenEQ(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldCacheWritePerToken, v)) +} + +// CacheWritePerTokenNEQ applies the NEQ predicate on the "cache_write_per_token" field. +func CacheWritePerTokenNEQ(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNEQ(FieldCacheWritePerToken, v)) +} + +// CacheWritePerTokenIn applies the In predicate on the "cache_write_per_token" field. +func CacheWritePerTokenIn(vs ...alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIn(FieldCacheWritePerToken, vs...)) +} + +// CacheWritePerTokenNotIn applies the NotIn predicate on the "cache_write_per_token" field. +func CacheWritePerTokenNotIn(vs ...alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotIn(FieldCacheWritePerToken, vs...)) +} + +// CacheWritePerTokenGT applies the GT predicate on the "cache_write_per_token" field. +func CacheWritePerTokenGT(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGT(FieldCacheWritePerToken, v)) +} + +// CacheWritePerTokenGTE applies the GTE predicate on the "cache_write_per_token" field. +func CacheWritePerTokenGTE(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGTE(FieldCacheWritePerToken, v)) +} + +// CacheWritePerTokenLT applies the LT predicate on the "cache_write_per_token" field. +func CacheWritePerTokenLT(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLT(FieldCacheWritePerToken, v)) +} + +// CacheWritePerTokenLTE applies the LTE predicate on the "cache_write_per_token" field. +func CacheWritePerTokenLTE(v alpacadecimal.Decimal) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLTE(FieldCacheWritePerToken, v)) +} + +// CurrencyEQ applies the EQ predicate on the "currency" field. +func CurrencyEQ(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldCurrency, v)) +} + +// CurrencyNEQ applies the NEQ predicate on the "currency" field. +func CurrencyNEQ(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNEQ(FieldCurrency, v)) +} + +// CurrencyIn applies the In predicate on the "currency" field. +func CurrencyIn(vs ...string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIn(FieldCurrency, vs...)) +} + +// CurrencyNotIn applies the NotIn predicate on the "currency" field. +func CurrencyNotIn(vs ...string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotIn(FieldCurrency, vs...)) +} + +// CurrencyGT applies the GT predicate on the "currency" field. +func CurrencyGT(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGT(FieldCurrency, v)) +} + +// CurrencyGTE applies the GTE predicate on the "currency" field. +func CurrencyGTE(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGTE(FieldCurrency, v)) +} + +// CurrencyLT applies the LT predicate on the "currency" field. +func CurrencyLT(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLT(FieldCurrency, v)) +} + +// CurrencyLTE applies the LTE predicate on the "currency" field. +func CurrencyLTE(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLTE(FieldCurrency, v)) +} + +// CurrencyContains applies the Contains predicate on the "currency" field. +func CurrencyContains(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldContains(FieldCurrency, v)) +} + +// CurrencyHasPrefix applies the HasPrefix predicate on the "currency" field. +func CurrencyHasPrefix(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldHasPrefix(FieldCurrency, v)) +} + +// CurrencyHasSuffix applies the HasSuffix predicate on the "currency" field. +func CurrencyHasSuffix(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldHasSuffix(FieldCurrency, v)) +} + +// CurrencyEqualFold applies the EqualFold predicate on the "currency" field. +func CurrencyEqualFold(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEqualFold(FieldCurrency, v)) +} + +// CurrencyContainsFold applies the ContainsFold predicate on the "currency" field. +func CurrencyContainsFold(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldContainsFold(FieldCurrency, v)) +} + +// SourceEQ applies the EQ predicate on the "source" field. +func SourceEQ(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldSource, v)) +} + +// SourceNEQ applies the NEQ predicate on the "source" field. +func SourceNEQ(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNEQ(FieldSource, v)) +} + +// SourceIn applies the In predicate on the "source" field. +func SourceIn(vs ...string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIn(FieldSource, vs...)) +} + +// SourceNotIn applies the NotIn predicate on the "source" field. +func SourceNotIn(vs ...string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotIn(FieldSource, vs...)) +} + +// SourceGT applies the GT predicate on the "source" field. +func SourceGT(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGT(FieldSource, v)) +} + +// SourceGTE applies the GTE predicate on the "source" field. +func SourceGTE(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGTE(FieldSource, v)) +} + +// SourceLT applies the LT predicate on the "source" field. +func SourceLT(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLT(FieldSource, v)) +} + +// SourceLTE applies the LTE predicate on the "source" field. +func SourceLTE(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLTE(FieldSource, v)) +} + +// SourceContains applies the Contains predicate on the "source" field. +func SourceContains(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldContains(FieldSource, v)) +} + +// SourceHasPrefix applies the HasPrefix predicate on the "source" field. +func SourceHasPrefix(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldHasPrefix(FieldSource, v)) +} + +// SourceHasSuffix applies the HasSuffix predicate on the "source" field. +func SourceHasSuffix(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldHasSuffix(FieldSource, v)) +} + +// SourceEqualFold applies the EqualFold predicate on the "source" field. +func SourceEqualFold(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEqualFold(FieldSource, v)) +} + +// SourceContainsFold applies the ContainsFold predicate on the "source" field. +func SourceContainsFold(v string) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldContainsFold(FieldSource, v)) +} + +// SourcePricesIsNil applies the IsNil predicate on the "source_prices" field. +func SourcePricesIsNil() predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIsNull(FieldSourcePrices)) +} + +// SourcePricesNotNil applies the NotNil predicate on the "source_prices" field. +func SourcePricesNotNil() predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotNull(FieldSourcePrices)) +} + +// EffectiveFromEQ applies the EQ predicate on the "effective_from" field. +func EffectiveFromEQ(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldEffectiveFrom, v)) +} + +// EffectiveFromNEQ applies the NEQ predicate on the "effective_from" field. +func EffectiveFromNEQ(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNEQ(FieldEffectiveFrom, v)) +} + +// EffectiveFromIn applies the In predicate on the "effective_from" field. +func EffectiveFromIn(vs ...time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIn(FieldEffectiveFrom, vs...)) +} + +// EffectiveFromNotIn applies the NotIn predicate on the "effective_from" field. +func EffectiveFromNotIn(vs ...time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotIn(FieldEffectiveFrom, vs...)) +} + +// EffectiveFromGT applies the GT predicate on the "effective_from" field. +func EffectiveFromGT(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGT(FieldEffectiveFrom, v)) +} + +// EffectiveFromGTE applies the GTE predicate on the "effective_from" field. +func EffectiveFromGTE(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGTE(FieldEffectiveFrom, v)) +} + +// EffectiveFromLT applies the LT predicate on the "effective_from" field. +func EffectiveFromLT(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLT(FieldEffectiveFrom, v)) +} + +// EffectiveFromLTE applies the LTE predicate on the "effective_from" field. +func EffectiveFromLTE(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLTE(FieldEffectiveFrom, v)) +} + +// EffectiveToEQ applies the EQ predicate on the "effective_to" field. +func EffectiveToEQ(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldEQ(FieldEffectiveTo, v)) +} + +// EffectiveToNEQ applies the NEQ predicate on the "effective_to" field. +func EffectiveToNEQ(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNEQ(FieldEffectiveTo, v)) +} + +// EffectiveToIn applies the In predicate on the "effective_to" field. +func EffectiveToIn(vs ...time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIn(FieldEffectiveTo, vs...)) +} + +// EffectiveToNotIn applies the NotIn predicate on the "effective_to" field. +func EffectiveToNotIn(vs ...time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotIn(FieldEffectiveTo, vs...)) +} + +// EffectiveToGT applies the GT predicate on the "effective_to" field. +func EffectiveToGT(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGT(FieldEffectiveTo, v)) +} + +// EffectiveToGTE applies the GTE predicate on the "effective_to" field. +func EffectiveToGTE(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldGTE(FieldEffectiveTo, v)) +} + +// EffectiveToLT applies the LT predicate on the "effective_to" field. +func EffectiveToLT(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLT(FieldEffectiveTo, v)) +} + +// EffectiveToLTE applies the LTE predicate on the "effective_to" field. +func EffectiveToLTE(v time.Time) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldLTE(FieldEffectiveTo, v)) +} + +// EffectiveToIsNil applies the IsNil predicate on the "effective_to" field. +func EffectiveToIsNil() predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldIsNull(FieldEffectiveTo)) +} + +// EffectiveToNotNil applies the NotNil predicate on the "effective_to" field. +func EffectiveToNotNil() predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.FieldNotNull(FieldEffectiveTo)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.LLMCostPrice) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LLMCostPrice) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LLMCostPrice) predicate.LLMCostPrice { + return predicate.LLMCostPrice(sql.NotPredicates(p)) +} diff --git a/ent/db/llmcostprice_create.go b/ent/db/llmcostprice_create.go new file mode 100644 index 0000000000000000000000000000000000000000..bc83a46c063ef6f587d126c8b21ed08f925cd8e2 --- /dev/null +++ b/ent/db/llmcostprice_create.go @@ -0,0 +1,1600 @@ +// 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/llmcostprice" + "github.com/openmeterio/openmeter/openmeter/llmcost" +) + +// LLMCostPriceCreate is the builder for creating a LLMCostPrice entity. +type LLMCostPriceCreate struct { + config + mutation *LLMCostPriceMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetMetadata sets the "metadata" field. +func (_c *LLMCostPriceCreate) SetMetadata(v map[string]string) *LLMCostPriceCreate { + _c.mutation.SetMetadata(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *LLMCostPriceCreate) SetCreatedAt(v time.Time) *LLMCostPriceCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *LLMCostPriceCreate) SetNillableCreatedAt(v *time.Time) *LLMCostPriceCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *LLMCostPriceCreate) SetUpdatedAt(v time.Time) *LLMCostPriceCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *LLMCostPriceCreate) SetNillableUpdatedAt(v *time.Time) *LLMCostPriceCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *LLMCostPriceCreate) SetDeletedAt(v time.Time) *LLMCostPriceCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *LLMCostPriceCreate) SetNillableDeletedAt(v *time.Time) *LLMCostPriceCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetNamespace sets the "namespace" field. +func (_c *LLMCostPriceCreate) SetNamespace(v string) *LLMCostPriceCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetNillableNamespace sets the "namespace" field if the given value is not nil. +func (_c *LLMCostPriceCreate) SetNillableNamespace(v *string) *LLMCostPriceCreate { + if v != nil { + _c.SetNamespace(*v) + } + return _c +} + +// SetProvider sets the "provider" field. +func (_c *LLMCostPriceCreate) SetProvider(v string) *LLMCostPriceCreate { + _c.mutation.SetProvider(v) + return _c +} + +// SetModelID sets the "model_id" field. +func (_c *LLMCostPriceCreate) SetModelID(v string) *LLMCostPriceCreate { + _c.mutation.SetModelID(v) + return _c +} + +// SetModelName sets the "model_name" field. +func (_c *LLMCostPriceCreate) SetModelName(v string) *LLMCostPriceCreate { + _c.mutation.SetModelName(v) + return _c +} + +// SetNillableModelName sets the "model_name" field if the given value is not nil. +func (_c *LLMCostPriceCreate) SetNillableModelName(v *string) *LLMCostPriceCreate { + if v != nil { + _c.SetModelName(*v) + } + return _c +} + +// SetInputPerToken sets the "input_per_token" field. +func (_c *LLMCostPriceCreate) SetInputPerToken(v alpacadecimal.Decimal) *LLMCostPriceCreate { + _c.mutation.SetInputPerToken(v) + return _c +} + +// SetOutputPerToken sets the "output_per_token" field. +func (_c *LLMCostPriceCreate) SetOutputPerToken(v alpacadecimal.Decimal) *LLMCostPriceCreate { + _c.mutation.SetOutputPerToken(v) + return _c +} + +// SetCacheReadPerToken sets the "cache_read_per_token" field. +func (_c *LLMCostPriceCreate) SetCacheReadPerToken(v alpacadecimal.Decimal) *LLMCostPriceCreate { + _c.mutation.SetCacheReadPerToken(v) + return _c +} + +// SetNillableCacheReadPerToken sets the "cache_read_per_token" field if the given value is not nil. +func (_c *LLMCostPriceCreate) SetNillableCacheReadPerToken(v *alpacadecimal.Decimal) *LLMCostPriceCreate { + if v != nil { + _c.SetCacheReadPerToken(*v) + } + return _c +} + +// SetReasoningPerToken sets the "reasoning_per_token" field. +func (_c *LLMCostPriceCreate) SetReasoningPerToken(v alpacadecimal.Decimal) *LLMCostPriceCreate { + _c.mutation.SetReasoningPerToken(v) + return _c +} + +// SetNillableReasoningPerToken sets the "reasoning_per_token" field if the given value is not nil. +func (_c *LLMCostPriceCreate) SetNillableReasoningPerToken(v *alpacadecimal.Decimal) *LLMCostPriceCreate { + if v != nil { + _c.SetReasoningPerToken(*v) + } + return _c +} + +// SetCacheWritePerToken sets the "cache_write_per_token" field. +func (_c *LLMCostPriceCreate) SetCacheWritePerToken(v alpacadecimal.Decimal) *LLMCostPriceCreate { + _c.mutation.SetCacheWritePerToken(v) + return _c +} + +// SetNillableCacheWritePerToken sets the "cache_write_per_token" field if the given value is not nil. +func (_c *LLMCostPriceCreate) SetNillableCacheWritePerToken(v *alpacadecimal.Decimal) *LLMCostPriceCreate { + if v != nil { + _c.SetCacheWritePerToken(*v) + } + return _c +} + +// SetCurrency sets the "currency" field. +func (_c *LLMCostPriceCreate) SetCurrency(v string) *LLMCostPriceCreate { + _c.mutation.SetCurrency(v) + return _c +} + +// SetNillableCurrency sets the "currency" field if the given value is not nil. +func (_c *LLMCostPriceCreate) SetNillableCurrency(v *string) *LLMCostPriceCreate { + if v != nil { + _c.SetCurrency(*v) + } + return _c +} + +// SetSource sets the "source" field. +func (_c *LLMCostPriceCreate) SetSource(v string) *LLMCostPriceCreate { + _c.mutation.SetSource(v) + return _c +} + +// SetSourcePrices sets the "source_prices" field. +func (_c *LLMCostPriceCreate) SetSourcePrices(v llmcost.SourcePricesMap) *LLMCostPriceCreate { + _c.mutation.SetSourcePrices(v) + return _c +} + +// SetEffectiveFrom sets the "effective_from" field. +func (_c *LLMCostPriceCreate) SetEffectiveFrom(v time.Time) *LLMCostPriceCreate { + _c.mutation.SetEffectiveFrom(v) + return _c +} + +// SetEffectiveTo sets the "effective_to" field. +func (_c *LLMCostPriceCreate) SetEffectiveTo(v time.Time) *LLMCostPriceCreate { + _c.mutation.SetEffectiveTo(v) + return _c +} + +// SetNillableEffectiveTo sets the "effective_to" field if the given value is not nil. +func (_c *LLMCostPriceCreate) SetNillableEffectiveTo(v *time.Time) *LLMCostPriceCreate { + if v != nil { + _c.SetEffectiveTo(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *LLMCostPriceCreate) SetID(v string) *LLMCostPriceCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *LLMCostPriceCreate) SetNillableID(v *string) *LLMCostPriceCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// Mutation returns the LLMCostPriceMutation object of the builder. +func (_c *LLMCostPriceCreate) Mutation() *LLMCostPriceMutation { + return _c.mutation +} + +// Save creates the LLMCostPrice in the database. +func (_c *LLMCostPriceCreate) Save(ctx context.Context) (*LLMCostPrice, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *LLMCostPriceCreate) SaveX(ctx context.Context) *LLMCostPrice { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LLMCostPriceCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LLMCostPriceCreate) 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 *LLMCostPriceCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := llmcostprice.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := llmcostprice.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ModelName(); !ok { + v := llmcostprice.DefaultModelName + _c.mutation.SetModelName(v) + } + if _, ok := _c.mutation.CacheReadPerToken(); !ok { + v := llmcostprice.DefaultCacheReadPerToken + _c.mutation.SetCacheReadPerToken(v) + } + if _, ok := _c.mutation.ReasoningPerToken(); !ok { + v := llmcostprice.DefaultReasoningPerToken + _c.mutation.SetReasoningPerToken(v) + } + if _, ok := _c.mutation.CacheWritePerToken(); !ok { + v := llmcostprice.DefaultCacheWritePerToken + _c.mutation.SetCacheWritePerToken(v) + } + if _, ok := _c.mutation.Currency(); !ok { + v := llmcostprice.DefaultCurrency + _c.mutation.SetCurrency(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := llmcostprice.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *LLMCostPriceCreate) check() error { + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "LLMCostPrice.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "LLMCostPrice.updated_at"`)} + } + if _, ok := _c.mutation.Provider(); !ok { + return &ValidationError{Name: "provider", err: errors.New(`db: missing required field "LLMCostPrice.provider"`)} + } + if v, ok := _c.mutation.Provider(); ok { + if err := llmcostprice.ProviderValidator(v); err != nil { + return &ValidationError{Name: "provider", err: fmt.Errorf(`db: validator failed for field "LLMCostPrice.provider": %w`, err)} + } + } + if _, ok := _c.mutation.ModelID(); !ok { + return &ValidationError{Name: "model_id", err: errors.New(`db: missing required field "LLMCostPrice.model_id"`)} + } + if v, ok := _c.mutation.ModelID(); ok { + if err := llmcostprice.ModelIDValidator(v); err != nil { + return &ValidationError{Name: "model_id", err: fmt.Errorf(`db: validator failed for field "LLMCostPrice.model_id": %w`, err)} + } + } + if _, ok := _c.mutation.ModelName(); !ok { + return &ValidationError{Name: "model_name", err: errors.New(`db: missing required field "LLMCostPrice.model_name"`)} + } + if _, ok := _c.mutation.InputPerToken(); !ok { + return &ValidationError{Name: "input_per_token", err: errors.New(`db: missing required field "LLMCostPrice.input_per_token"`)} + } + if _, ok := _c.mutation.OutputPerToken(); !ok { + return &ValidationError{Name: "output_per_token", err: errors.New(`db: missing required field "LLMCostPrice.output_per_token"`)} + } + if _, ok := _c.mutation.CacheReadPerToken(); !ok { + return &ValidationError{Name: "cache_read_per_token", err: errors.New(`db: missing required field "LLMCostPrice.cache_read_per_token"`)} + } + if _, ok := _c.mutation.ReasoningPerToken(); !ok { + return &ValidationError{Name: "reasoning_per_token", err: errors.New(`db: missing required field "LLMCostPrice.reasoning_per_token"`)} + } + if _, ok := _c.mutation.CacheWritePerToken(); !ok { + return &ValidationError{Name: "cache_write_per_token", err: errors.New(`db: missing required field "LLMCostPrice.cache_write_per_token"`)} + } + if _, ok := _c.mutation.Currency(); !ok { + return &ValidationError{Name: "currency", err: errors.New(`db: missing required field "LLMCostPrice.currency"`)} + } + if v, ok := _c.mutation.Currency(); ok { + if err := llmcostprice.CurrencyValidator(v); err != nil { + return &ValidationError{Name: "currency", err: fmt.Errorf(`db: validator failed for field "LLMCostPrice.currency": %w`, err)} + } + } + if _, ok := _c.mutation.Source(); !ok { + return &ValidationError{Name: "source", err: errors.New(`db: missing required field "LLMCostPrice.source"`)} + } + if v, ok := _c.mutation.Source(); ok { + if err := llmcostprice.SourceValidator(v); err != nil { + return &ValidationError{Name: "source", err: fmt.Errorf(`db: validator failed for field "LLMCostPrice.source": %w`, err)} + } + } + if _, ok := _c.mutation.EffectiveFrom(); !ok { + return &ValidationError{Name: "effective_from", err: errors.New(`db: missing required field "LLMCostPrice.effective_from"`)} + } + return nil +} + +func (_c *LLMCostPriceCreate) sqlSave(ctx context.Context) (*LLMCostPrice, 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 LLMCostPrice.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *LLMCostPriceCreate) createSpec() (*LLMCostPrice, *sqlgraph.CreateSpec, error) { + var ( + _node = &LLMCostPrice{config: _c.config} + _spec = sqlgraph.NewCreateSpec(llmcostprice.Table, sqlgraph.NewFieldSpec(llmcostprice.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.Metadata(); ok { + _spec.SetField(llmcostprice.FieldMetadata, field.TypeJSON, value) + _node.Metadata = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(llmcostprice.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(llmcostprice.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(llmcostprice.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(llmcostprice.FieldNamespace, field.TypeString, value) + _node.Namespace = &value + } + if value, ok := _c.mutation.Provider(); ok { + _spec.SetField(llmcostprice.FieldProvider, field.TypeString, value) + _node.Provider = value + } + if value, ok := _c.mutation.ModelID(); ok { + _spec.SetField(llmcostprice.FieldModelID, field.TypeString, value) + _node.ModelID = value + } + if value, ok := _c.mutation.ModelName(); ok { + _spec.SetField(llmcostprice.FieldModelName, field.TypeString, value) + _node.ModelName = value + } + if value, ok := _c.mutation.InputPerToken(); ok { + _spec.SetField(llmcostprice.FieldInputPerToken, field.TypeOther, value) + _node.InputPerToken = value + } + if value, ok := _c.mutation.OutputPerToken(); ok { + _spec.SetField(llmcostprice.FieldOutputPerToken, field.TypeOther, value) + _node.OutputPerToken = value + } + if value, ok := _c.mutation.CacheReadPerToken(); ok { + _spec.SetField(llmcostprice.FieldCacheReadPerToken, field.TypeOther, value) + _node.CacheReadPerToken = value + } + if value, ok := _c.mutation.ReasoningPerToken(); ok { + _spec.SetField(llmcostprice.FieldReasoningPerToken, field.TypeOther, value) + _node.ReasoningPerToken = value + } + if value, ok := _c.mutation.CacheWritePerToken(); ok { + _spec.SetField(llmcostprice.FieldCacheWritePerToken, field.TypeOther, value) + _node.CacheWritePerToken = value + } + if value, ok := _c.mutation.Currency(); ok { + _spec.SetField(llmcostprice.FieldCurrency, field.TypeString, value) + _node.Currency = value + } + if value, ok := _c.mutation.Source(); ok { + _spec.SetField(llmcostprice.FieldSource, field.TypeString, value) + _node.Source = value + } + if value, ok := _c.mutation.SourcePrices(); ok { + vv, err := llmcostprice.ValueScanner.SourcePrices.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(llmcostprice.FieldSourcePrices, field.TypeString, vv) + _node.SourcePrices = value + } + if value, ok := _c.mutation.EffectiveFrom(); ok { + _spec.SetField(llmcostprice.FieldEffectiveFrom, field.TypeTime, value) + _node.EffectiveFrom = value + } + if value, ok := _c.mutation.EffectiveTo(); ok { + _spec.SetField(llmcostprice.FieldEffectiveTo, field.TypeTime, value) + _node.EffectiveTo = &value + } + return _node, _spec, nil +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.LLMCostPrice.Create(). +// SetMetadata(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.LLMCostPriceUpsert) { +// SetMetadata(v+v). +// }). +// Exec(ctx) +func (_c *LLMCostPriceCreate) OnConflict(opts ...sql.ConflictOption) *LLMCostPriceUpsertOne { + _c.conflict = opts + return &LLMCostPriceUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.LLMCostPrice.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *LLMCostPriceCreate) OnConflictColumns(columns ...string) *LLMCostPriceUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &LLMCostPriceUpsertOne{ + create: _c, + } +} + +type ( + // LLMCostPriceUpsertOne is the builder for "upsert"-ing + // one LLMCostPrice node. + LLMCostPriceUpsertOne struct { + create *LLMCostPriceCreate + } + + // LLMCostPriceUpsert is the "OnConflict" setter. + LLMCostPriceUpsert struct { + *sql.UpdateSet + } +) + +// SetMetadata sets the "metadata" field. +func (u *LLMCostPriceUpsert) SetMetadata(v map[string]string) *LLMCostPriceUpsert { + u.Set(llmcostprice.FieldMetadata, v) + return u +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *LLMCostPriceUpsert) UpdateMetadata() *LLMCostPriceUpsert { + u.SetExcluded(llmcostprice.FieldMetadata) + return u +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *LLMCostPriceUpsert) ClearMetadata() *LLMCostPriceUpsert { + u.SetNull(llmcostprice.FieldMetadata) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LLMCostPriceUpsert) SetUpdatedAt(v time.Time) *LLMCostPriceUpsert { + u.Set(llmcostprice.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LLMCostPriceUpsert) UpdateUpdatedAt() *LLMCostPriceUpsert { + u.SetExcluded(llmcostprice.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LLMCostPriceUpsert) SetDeletedAt(v time.Time) *LLMCostPriceUpsert { + u.Set(llmcostprice.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LLMCostPriceUpsert) UpdateDeletedAt() *LLMCostPriceUpsert { + u.SetExcluded(llmcostprice.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LLMCostPriceUpsert) ClearDeletedAt() *LLMCostPriceUpsert { + u.SetNull(llmcostprice.FieldDeletedAt) + return u +} + +// SetNamespace sets the "namespace" field. +func (u *LLMCostPriceUpsert) SetNamespace(v string) *LLMCostPriceUpsert { + u.Set(llmcostprice.FieldNamespace, v) + return u +} + +// UpdateNamespace sets the "namespace" field to the value that was provided on create. +func (u *LLMCostPriceUpsert) UpdateNamespace() *LLMCostPriceUpsert { + u.SetExcluded(llmcostprice.FieldNamespace) + return u +} + +// ClearNamespace clears the value of the "namespace" field. +func (u *LLMCostPriceUpsert) ClearNamespace() *LLMCostPriceUpsert { + u.SetNull(llmcostprice.FieldNamespace) + return u +} + +// SetProvider sets the "provider" field. +func (u *LLMCostPriceUpsert) SetProvider(v string) *LLMCostPriceUpsert { + u.Set(llmcostprice.FieldProvider, v) + return u +} + +// UpdateProvider sets the "provider" field to the value that was provided on create. +func (u *LLMCostPriceUpsert) UpdateProvider() *LLMCostPriceUpsert { + u.SetExcluded(llmcostprice.FieldProvider) + return u +} + +// SetModelID sets the "model_id" field. +func (u *LLMCostPriceUpsert) SetModelID(v string) *LLMCostPriceUpsert { + u.Set(llmcostprice.FieldModelID, v) + return u +} + +// UpdateModelID sets the "model_id" field to the value that was provided on create. +func (u *LLMCostPriceUpsert) UpdateModelID() *LLMCostPriceUpsert { + u.SetExcluded(llmcostprice.FieldModelID) + return u +} + +// SetModelName sets the "model_name" field. +func (u *LLMCostPriceUpsert) SetModelName(v string) *LLMCostPriceUpsert { + u.Set(llmcostprice.FieldModelName, v) + return u +} + +// UpdateModelName sets the "model_name" field to the value that was provided on create. +func (u *LLMCostPriceUpsert) UpdateModelName() *LLMCostPriceUpsert { + u.SetExcluded(llmcostprice.FieldModelName) + return u +} + +// SetInputPerToken sets the "input_per_token" field. +func (u *LLMCostPriceUpsert) SetInputPerToken(v alpacadecimal.Decimal) *LLMCostPriceUpsert { + u.Set(llmcostprice.FieldInputPerToken, v) + return u +} + +// UpdateInputPerToken sets the "input_per_token" field to the value that was provided on create. +func (u *LLMCostPriceUpsert) UpdateInputPerToken() *LLMCostPriceUpsert { + u.SetExcluded(llmcostprice.FieldInputPerToken) + return u +} + +// SetOutputPerToken sets the "output_per_token" field. +func (u *LLMCostPriceUpsert) SetOutputPerToken(v alpacadecimal.Decimal) *LLMCostPriceUpsert { + u.Set(llmcostprice.FieldOutputPerToken, v) + return u +} + +// UpdateOutputPerToken sets the "output_per_token" field to the value that was provided on create. +func (u *LLMCostPriceUpsert) UpdateOutputPerToken() *LLMCostPriceUpsert { + u.SetExcluded(llmcostprice.FieldOutputPerToken) + return u +} + +// SetCacheReadPerToken sets the "cache_read_per_token" field. +func (u *LLMCostPriceUpsert) SetCacheReadPerToken(v alpacadecimal.Decimal) *LLMCostPriceUpsert { + u.Set(llmcostprice.FieldCacheReadPerToken, v) + return u +} + +// UpdateCacheReadPerToken sets the "cache_read_per_token" field to the value that was provided on create. +func (u *LLMCostPriceUpsert) UpdateCacheReadPerToken() *LLMCostPriceUpsert { + u.SetExcluded(llmcostprice.FieldCacheReadPerToken) + return u +} + +// SetReasoningPerToken sets the "reasoning_per_token" field. +func (u *LLMCostPriceUpsert) SetReasoningPerToken(v alpacadecimal.Decimal) *LLMCostPriceUpsert { + u.Set(llmcostprice.FieldReasoningPerToken, v) + return u +} + +// UpdateReasoningPerToken sets the "reasoning_per_token" field to the value that was provided on create. +func (u *LLMCostPriceUpsert) UpdateReasoningPerToken() *LLMCostPriceUpsert { + u.SetExcluded(llmcostprice.FieldReasoningPerToken) + return u +} + +// SetCacheWritePerToken sets the "cache_write_per_token" field. +func (u *LLMCostPriceUpsert) SetCacheWritePerToken(v alpacadecimal.Decimal) *LLMCostPriceUpsert { + u.Set(llmcostprice.FieldCacheWritePerToken, v) + return u +} + +// UpdateCacheWritePerToken sets the "cache_write_per_token" field to the value that was provided on create. +func (u *LLMCostPriceUpsert) UpdateCacheWritePerToken() *LLMCostPriceUpsert { + u.SetExcluded(llmcostprice.FieldCacheWritePerToken) + return u +} + +// SetCurrency sets the "currency" field. +func (u *LLMCostPriceUpsert) SetCurrency(v string) *LLMCostPriceUpsert { + u.Set(llmcostprice.FieldCurrency, v) + return u +} + +// UpdateCurrency sets the "currency" field to the value that was provided on create. +func (u *LLMCostPriceUpsert) UpdateCurrency() *LLMCostPriceUpsert { + u.SetExcluded(llmcostprice.FieldCurrency) + return u +} + +// SetSource sets the "source" field. +func (u *LLMCostPriceUpsert) SetSource(v string) *LLMCostPriceUpsert { + u.Set(llmcostprice.FieldSource, v) + return u +} + +// UpdateSource sets the "source" field to the value that was provided on create. +func (u *LLMCostPriceUpsert) UpdateSource() *LLMCostPriceUpsert { + u.SetExcluded(llmcostprice.FieldSource) + return u +} + +// SetSourcePrices sets the "source_prices" field. +func (u *LLMCostPriceUpsert) SetSourcePrices(v llmcost.SourcePricesMap) *LLMCostPriceUpsert { + u.Set(llmcostprice.FieldSourcePrices, v) + return u +} + +// UpdateSourcePrices sets the "source_prices" field to the value that was provided on create. +func (u *LLMCostPriceUpsert) UpdateSourcePrices() *LLMCostPriceUpsert { + u.SetExcluded(llmcostprice.FieldSourcePrices) + return u +} + +// ClearSourcePrices clears the value of the "source_prices" field. +func (u *LLMCostPriceUpsert) ClearSourcePrices() *LLMCostPriceUpsert { + u.SetNull(llmcostprice.FieldSourcePrices) + return u +} + +// SetEffectiveFrom sets the "effective_from" field. +func (u *LLMCostPriceUpsert) SetEffectiveFrom(v time.Time) *LLMCostPriceUpsert { + u.Set(llmcostprice.FieldEffectiveFrom, v) + return u +} + +// UpdateEffectiveFrom sets the "effective_from" field to the value that was provided on create. +func (u *LLMCostPriceUpsert) UpdateEffectiveFrom() *LLMCostPriceUpsert { + u.SetExcluded(llmcostprice.FieldEffectiveFrom) + return u +} + +// SetEffectiveTo sets the "effective_to" field. +func (u *LLMCostPriceUpsert) SetEffectiveTo(v time.Time) *LLMCostPriceUpsert { + u.Set(llmcostprice.FieldEffectiveTo, v) + return u +} + +// UpdateEffectiveTo sets the "effective_to" field to the value that was provided on create. +func (u *LLMCostPriceUpsert) UpdateEffectiveTo() *LLMCostPriceUpsert { + u.SetExcluded(llmcostprice.FieldEffectiveTo) + return u +} + +// ClearEffectiveTo clears the value of the "effective_to" field. +func (u *LLMCostPriceUpsert) ClearEffectiveTo() *LLMCostPriceUpsert { + u.SetNull(llmcostprice.FieldEffectiveTo) + 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.LLMCostPrice.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(llmcostprice.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LLMCostPriceUpsertOne) UpdateNewValues() *LLMCostPriceUpsertOne { + 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(llmcostprice.FieldID) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(llmcostprice.FieldCreatedAt) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.LLMCostPrice.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LLMCostPriceUpsertOne) Ignore() *LLMCostPriceUpsertOne { + 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 *LLMCostPriceUpsertOne) DoNothing() *LLMCostPriceUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LLMCostPriceCreate.OnConflict +// documentation for more info. +func (u *LLMCostPriceUpsertOne) Update(set func(*LLMCostPriceUpsert)) *LLMCostPriceUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LLMCostPriceUpsert{UpdateSet: update}) + })) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *LLMCostPriceUpsertOne) SetMetadata(v map[string]string) *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *LLMCostPriceUpsertOne) UpdateMetadata() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *LLMCostPriceUpsertOne) ClearMetadata() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LLMCostPriceUpsertOne) SetUpdatedAt(v time.Time) *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LLMCostPriceUpsertOne) UpdateUpdatedAt() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LLMCostPriceUpsertOne) SetDeletedAt(v time.Time) *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LLMCostPriceUpsertOne) UpdateDeletedAt() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LLMCostPriceUpsertOne) ClearDeletedAt() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.ClearDeletedAt() + }) +} + +// SetNamespace sets the "namespace" field. +func (u *LLMCostPriceUpsertOne) SetNamespace(v string) *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetNamespace(v) + }) +} + +// UpdateNamespace sets the "namespace" field to the value that was provided on create. +func (u *LLMCostPriceUpsertOne) UpdateNamespace() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateNamespace() + }) +} + +// ClearNamespace clears the value of the "namespace" field. +func (u *LLMCostPriceUpsertOne) ClearNamespace() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.ClearNamespace() + }) +} + +// SetProvider sets the "provider" field. +func (u *LLMCostPriceUpsertOne) SetProvider(v string) *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetProvider(v) + }) +} + +// UpdateProvider sets the "provider" field to the value that was provided on create. +func (u *LLMCostPriceUpsertOne) UpdateProvider() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateProvider() + }) +} + +// SetModelID sets the "model_id" field. +func (u *LLMCostPriceUpsertOne) SetModelID(v string) *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetModelID(v) + }) +} + +// UpdateModelID sets the "model_id" field to the value that was provided on create. +func (u *LLMCostPriceUpsertOne) UpdateModelID() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateModelID() + }) +} + +// SetModelName sets the "model_name" field. +func (u *LLMCostPriceUpsertOne) SetModelName(v string) *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetModelName(v) + }) +} + +// UpdateModelName sets the "model_name" field to the value that was provided on create. +func (u *LLMCostPriceUpsertOne) UpdateModelName() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateModelName() + }) +} + +// SetInputPerToken sets the "input_per_token" field. +func (u *LLMCostPriceUpsertOne) SetInputPerToken(v alpacadecimal.Decimal) *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetInputPerToken(v) + }) +} + +// UpdateInputPerToken sets the "input_per_token" field to the value that was provided on create. +func (u *LLMCostPriceUpsertOne) UpdateInputPerToken() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateInputPerToken() + }) +} + +// SetOutputPerToken sets the "output_per_token" field. +func (u *LLMCostPriceUpsertOne) SetOutputPerToken(v alpacadecimal.Decimal) *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetOutputPerToken(v) + }) +} + +// UpdateOutputPerToken sets the "output_per_token" field to the value that was provided on create. +func (u *LLMCostPriceUpsertOne) UpdateOutputPerToken() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateOutputPerToken() + }) +} + +// SetCacheReadPerToken sets the "cache_read_per_token" field. +func (u *LLMCostPriceUpsertOne) SetCacheReadPerToken(v alpacadecimal.Decimal) *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetCacheReadPerToken(v) + }) +} + +// UpdateCacheReadPerToken sets the "cache_read_per_token" field to the value that was provided on create. +func (u *LLMCostPriceUpsertOne) UpdateCacheReadPerToken() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateCacheReadPerToken() + }) +} + +// SetReasoningPerToken sets the "reasoning_per_token" field. +func (u *LLMCostPriceUpsertOne) SetReasoningPerToken(v alpacadecimal.Decimal) *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetReasoningPerToken(v) + }) +} + +// UpdateReasoningPerToken sets the "reasoning_per_token" field to the value that was provided on create. +func (u *LLMCostPriceUpsertOne) UpdateReasoningPerToken() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateReasoningPerToken() + }) +} + +// SetCacheWritePerToken sets the "cache_write_per_token" field. +func (u *LLMCostPriceUpsertOne) SetCacheWritePerToken(v alpacadecimal.Decimal) *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetCacheWritePerToken(v) + }) +} + +// UpdateCacheWritePerToken sets the "cache_write_per_token" field to the value that was provided on create. +func (u *LLMCostPriceUpsertOne) UpdateCacheWritePerToken() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateCacheWritePerToken() + }) +} + +// SetCurrency sets the "currency" field. +func (u *LLMCostPriceUpsertOne) SetCurrency(v string) *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetCurrency(v) + }) +} + +// UpdateCurrency sets the "currency" field to the value that was provided on create. +func (u *LLMCostPriceUpsertOne) UpdateCurrency() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateCurrency() + }) +} + +// SetSource sets the "source" field. +func (u *LLMCostPriceUpsertOne) SetSource(v string) *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetSource(v) + }) +} + +// UpdateSource sets the "source" field to the value that was provided on create. +func (u *LLMCostPriceUpsertOne) UpdateSource() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateSource() + }) +} + +// SetSourcePrices sets the "source_prices" field. +func (u *LLMCostPriceUpsertOne) SetSourcePrices(v llmcost.SourcePricesMap) *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetSourcePrices(v) + }) +} + +// UpdateSourcePrices sets the "source_prices" field to the value that was provided on create. +func (u *LLMCostPriceUpsertOne) UpdateSourcePrices() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateSourcePrices() + }) +} + +// ClearSourcePrices clears the value of the "source_prices" field. +func (u *LLMCostPriceUpsertOne) ClearSourcePrices() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.ClearSourcePrices() + }) +} + +// SetEffectiveFrom sets the "effective_from" field. +func (u *LLMCostPriceUpsertOne) SetEffectiveFrom(v time.Time) *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetEffectiveFrom(v) + }) +} + +// UpdateEffectiveFrom sets the "effective_from" field to the value that was provided on create. +func (u *LLMCostPriceUpsertOne) UpdateEffectiveFrom() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateEffectiveFrom() + }) +} + +// SetEffectiveTo sets the "effective_to" field. +func (u *LLMCostPriceUpsertOne) SetEffectiveTo(v time.Time) *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetEffectiveTo(v) + }) +} + +// UpdateEffectiveTo sets the "effective_to" field to the value that was provided on create. +func (u *LLMCostPriceUpsertOne) UpdateEffectiveTo() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateEffectiveTo() + }) +} + +// ClearEffectiveTo clears the value of the "effective_to" field. +func (u *LLMCostPriceUpsertOne) ClearEffectiveTo() *LLMCostPriceUpsertOne { + return u.Update(func(s *LLMCostPriceUpsert) { + s.ClearEffectiveTo() + }) +} + +// Exec executes the query. +func (u *LLMCostPriceUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for LLMCostPriceCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LLMCostPriceUpsertOne) 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 *LLMCostPriceUpsertOne) 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: LLMCostPriceUpsertOne.ID is not supported by MySQL driver. Use LLMCostPriceUpsertOne.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 *LLMCostPriceUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// LLMCostPriceCreateBulk is the builder for creating many LLMCostPrice entities in bulk. +type LLMCostPriceCreateBulk struct { + config + err error + builders []*LLMCostPriceCreate + conflict []sql.ConflictOption +} + +// Save creates the LLMCostPrice entities in the database. +func (_c *LLMCostPriceCreateBulk) Save(ctx context.Context) ([]*LLMCostPrice, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*LLMCostPrice, 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.(*LLMCostPriceMutation) + 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 *LLMCostPriceCreateBulk) SaveX(ctx context.Context) []*LLMCostPrice { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LLMCostPriceCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LLMCostPriceCreateBulk) 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.LLMCostPrice.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.LLMCostPriceUpsert) { +// SetMetadata(v+v). +// }). +// Exec(ctx) +func (_c *LLMCostPriceCreateBulk) OnConflict(opts ...sql.ConflictOption) *LLMCostPriceUpsertBulk { + _c.conflict = opts + return &LLMCostPriceUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.LLMCostPrice.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *LLMCostPriceCreateBulk) OnConflictColumns(columns ...string) *LLMCostPriceUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &LLMCostPriceUpsertBulk{ + create: _c, + } +} + +// LLMCostPriceUpsertBulk is the builder for "upsert"-ing +// a bulk of LLMCostPrice nodes. +type LLMCostPriceUpsertBulk struct { + create *LLMCostPriceCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.LLMCostPrice.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(llmcostprice.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LLMCostPriceUpsertBulk) UpdateNewValues() *LLMCostPriceUpsertBulk { + 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(llmcostprice.FieldID) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(llmcostprice.FieldCreatedAt) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.LLMCostPrice.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LLMCostPriceUpsertBulk) Ignore() *LLMCostPriceUpsertBulk { + 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 *LLMCostPriceUpsertBulk) DoNothing() *LLMCostPriceUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LLMCostPriceCreateBulk.OnConflict +// documentation for more info. +func (u *LLMCostPriceUpsertBulk) Update(set func(*LLMCostPriceUpsert)) *LLMCostPriceUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LLMCostPriceUpsert{UpdateSet: update}) + })) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *LLMCostPriceUpsertBulk) SetMetadata(v map[string]string) *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *LLMCostPriceUpsertBulk) UpdateMetadata() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *LLMCostPriceUpsertBulk) ClearMetadata() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *LLMCostPriceUpsertBulk) SetUpdatedAt(v time.Time) *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *LLMCostPriceUpsertBulk) UpdateUpdatedAt() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *LLMCostPriceUpsertBulk) SetDeletedAt(v time.Time) *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *LLMCostPriceUpsertBulk) UpdateDeletedAt() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *LLMCostPriceUpsertBulk) ClearDeletedAt() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.ClearDeletedAt() + }) +} + +// SetNamespace sets the "namespace" field. +func (u *LLMCostPriceUpsertBulk) SetNamespace(v string) *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetNamespace(v) + }) +} + +// UpdateNamespace sets the "namespace" field to the value that was provided on create. +func (u *LLMCostPriceUpsertBulk) UpdateNamespace() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateNamespace() + }) +} + +// ClearNamespace clears the value of the "namespace" field. +func (u *LLMCostPriceUpsertBulk) ClearNamespace() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.ClearNamespace() + }) +} + +// SetProvider sets the "provider" field. +func (u *LLMCostPriceUpsertBulk) SetProvider(v string) *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetProvider(v) + }) +} + +// UpdateProvider sets the "provider" field to the value that was provided on create. +func (u *LLMCostPriceUpsertBulk) UpdateProvider() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateProvider() + }) +} + +// SetModelID sets the "model_id" field. +func (u *LLMCostPriceUpsertBulk) SetModelID(v string) *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetModelID(v) + }) +} + +// UpdateModelID sets the "model_id" field to the value that was provided on create. +func (u *LLMCostPriceUpsertBulk) UpdateModelID() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateModelID() + }) +} + +// SetModelName sets the "model_name" field. +func (u *LLMCostPriceUpsertBulk) SetModelName(v string) *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetModelName(v) + }) +} + +// UpdateModelName sets the "model_name" field to the value that was provided on create. +func (u *LLMCostPriceUpsertBulk) UpdateModelName() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateModelName() + }) +} + +// SetInputPerToken sets the "input_per_token" field. +func (u *LLMCostPriceUpsertBulk) SetInputPerToken(v alpacadecimal.Decimal) *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetInputPerToken(v) + }) +} + +// UpdateInputPerToken sets the "input_per_token" field to the value that was provided on create. +func (u *LLMCostPriceUpsertBulk) UpdateInputPerToken() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateInputPerToken() + }) +} + +// SetOutputPerToken sets the "output_per_token" field. +func (u *LLMCostPriceUpsertBulk) SetOutputPerToken(v alpacadecimal.Decimal) *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetOutputPerToken(v) + }) +} + +// UpdateOutputPerToken sets the "output_per_token" field to the value that was provided on create. +func (u *LLMCostPriceUpsertBulk) UpdateOutputPerToken() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateOutputPerToken() + }) +} + +// SetCacheReadPerToken sets the "cache_read_per_token" field. +func (u *LLMCostPriceUpsertBulk) SetCacheReadPerToken(v alpacadecimal.Decimal) *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetCacheReadPerToken(v) + }) +} + +// UpdateCacheReadPerToken sets the "cache_read_per_token" field to the value that was provided on create. +func (u *LLMCostPriceUpsertBulk) UpdateCacheReadPerToken() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateCacheReadPerToken() + }) +} + +// SetReasoningPerToken sets the "reasoning_per_token" field. +func (u *LLMCostPriceUpsertBulk) SetReasoningPerToken(v alpacadecimal.Decimal) *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetReasoningPerToken(v) + }) +} + +// UpdateReasoningPerToken sets the "reasoning_per_token" field to the value that was provided on create. +func (u *LLMCostPriceUpsertBulk) UpdateReasoningPerToken() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateReasoningPerToken() + }) +} + +// SetCacheWritePerToken sets the "cache_write_per_token" field. +func (u *LLMCostPriceUpsertBulk) SetCacheWritePerToken(v alpacadecimal.Decimal) *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetCacheWritePerToken(v) + }) +} + +// UpdateCacheWritePerToken sets the "cache_write_per_token" field to the value that was provided on create. +func (u *LLMCostPriceUpsertBulk) UpdateCacheWritePerToken() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateCacheWritePerToken() + }) +} + +// SetCurrency sets the "currency" field. +func (u *LLMCostPriceUpsertBulk) SetCurrency(v string) *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetCurrency(v) + }) +} + +// UpdateCurrency sets the "currency" field to the value that was provided on create. +func (u *LLMCostPriceUpsertBulk) UpdateCurrency() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateCurrency() + }) +} + +// SetSource sets the "source" field. +func (u *LLMCostPriceUpsertBulk) SetSource(v string) *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetSource(v) + }) +} + +// UpdateSource sets the "source" field to the value that was provided on create. +func (u *LLMCostPriceUpsertBulk) UpdateSource() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateSource() + }) +} + +// SetSourcePrices sets the "source_prices" field. +func (u *LLMCostPriceUpsertBulk) SetSourcePrices(v llmcost.SourcePricesMap) *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetSourcePrices(v) + }) +} + +// UpdateSourcePrices sets the "source_prices" field to the value that was provided on create. +func (u *LLMCostPriceUpsertBulk) UpdateSourcePrices() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateSourcePrices() + }) +} + +// ClearSourcePrices clears the value of the "source_prices" field. +func (u *LLMCostPriceUpsertBulk) ClearSourcePrices() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.ClearSourcePrices() + }) +} + +// SetEffectiveFrom sets the "effective_from" field. +func (u *LLMCostPriceUpsertBulk) SetEffectiveFrom(v time.Time) *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetEffectiveFrom(v) + }) +} + +// UpdateEffectiveFrom sets the "effective_from" field to the value that was provided on create. +func (u *LLMCostPriceUpsertBulk) UpdateEffectiveFrom() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateEffectiveFrom() + }) +} + +// SetEffectiveTo sets the "effective_to" field. +func (u *LLMCostPriceUpsertBulk) SetEffectiveTo(v time.Time) *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.SetEffectiveTo(v) + }) +} + +// UpdateEffectiveTo sets the "effective_to" field to the value that was provided on create. +func (u *LLMCostPriceUpsertBulk) UpdateEffectiveTo() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.UpdateEffectiveTo() + }) +} + +// ClearEffectiveTo clears the value of the "effective_to" field. +func (u *LLMCostPriceUpsertBulk) ClearEffectiveTo() *LLMCostPriceUpsertBulk { + return u.Update(func(s *LLMCostPriceUpsert) { + s.ClearEffectiveTo() + }) +} + +// Exec executes the query. +func (u *LLMCostPriceUpsertBulk) 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 LLMCostPriceCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for LLMCostPriceCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LLMCostPriceUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/llmcostprice_delete.go b/ent/db/llmcostprice_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..11c3274699f5ea26c1c3c3686086e56d4e27fa01 --- /dev/null +++ b/ent/db/llmcostprice_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/llmcostprice" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LLMCostPriceDelete is the builder for deleting a LLMCostPrice entity. +type LLMCostPriceDelete struct { + config + hooks []Hook + mutation *LLMCostPriceMutation +} + +// Where appends a list predicates to the LLMCostPriceDelete builder. +func (_d *LLMCostPriceDelete) Where(ps ...predicate.LLMCostPrice) *LLMCostPriceDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *LLMCostPriceDelete) 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 *LLMCostPriceDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *LLMCostPriceDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(llmcostprice.Table, sqlgraph.NewFieldSpec(llmcostprice.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 +} + +// LLMCostPriceDeleteOne is the builder for deleting a single LLMCostPrice entity. +type LLMCostPriceDeleteOne struct { + _d *LLMCostPriceDelete +} + +// Where appends a list predicates to the LLMCostPriceDelete builder. +func (_d *LLMCostPriceDeleteOne) Where(ps ...predicate.LLMCostPrice) *LLMCostPriceDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *LLMCostPriceDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{llmcostprice.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *LLMCostPriceDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/llmcostprice_query.go b/ent/db/llmcostprice_query.go new file mode 100644 index 0000000000000000000000000000000000000000..bae9f5acf1a7268aaaaa85a954eb828effcff81c --- /dev/null +++ b/ent/db/llmcostprice_query.go @@ -0,0 +1,564 @@ +// 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/llmcostprice" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// LLMCostPriceQuery is the builder for querying LLMCostPrice entities. +type LLMCostPriceQuery struct { + config + ctx *QueryContext + order []llmcostprice.OrderOption + inters []Interceptor + predicates []predicate.LLMCostPrice + 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 LLMCostPriceQuery builder. +func (_q *LLMCostPriceQuery) Where(ps ...predicate.LLMCostPrice) *LLMCostPriceQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *LLMCostPriceQuery) Limit(limit int) *LLMCostPriceQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *LLMCostPriceQuery) Offset(offset int) *LLMCostPriceQuery { + _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 *LLMCostPriceQuery) Unique(unique bool) *LLMCostPriceQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *LLMCostPriceQuery) Order(o ...llmcostprice.OrderOption) *LLMCostPriceQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first LLMCostPrice entity from the query. +// Returns a *NotFoundError when no LLMCostPrice was found. +func (_q *LLMCostPriceQuery) First(ctx context.Context) (*LLMCostPrice, 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{llmcostprice.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *LLMCostPriceQuery) FirstX(ctx context.Context) *LLMCostPrice { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LLMCostPrice ID from the query. +// Returns a *NotFoundError when no LLMCostPrice ID was found. +func (_q *LLMCostPriceQuery) 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{llmcostprice.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *LLMCostPriceQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LLMCostPrice entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one LLMCostPrice entity is found. +// Returns a *NotFoundError when no LLMCostPrice entities are found. +func (_q *LLMCostPriceQuery) Only(ctx context.Context) (*LLMCostPrice, 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{llmcostprice.Label} + default: + return nil, &NotSingularError{llmcostprice.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *LLMCostPriceQuery) OnlyX(ctx context.Context) *LLMCostPrice { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LLMCostPrice ID in the query. +// Returns a *NotSingularError when more than one LLMCostPrice ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *LLMCostPriceQuery) 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{llmcostprice.Label} + default: + err = &NotSingularError{llmcostprice.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *LLMCostPriceQuery) 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 LLMCostPrices. +func (_q *LLMCostPriceQuery) All(ctx context.Context) ([]*LLMCostPrice, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*LLMCostPrice, *LLMCostPriceQuery]() + return withInterceptors[[]*LLMCostPrice](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *LLMCostPriceQuery) AllX(ctx context.Context) []*LLMCostPrice { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LLMCostPrice IDs. +func (_q *LLMCostPriceQuery) 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(llmcostprice.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *LLMCostPriceQuery) 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 *LLMCostPriceQuery) 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[*LLMCostPriceQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *LLMCostPriceQuery) 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 *LLMCostPriceQuery) 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 *LLMCostPriceQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LLMCostPriceQuery 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 *LLMCostPriceQuery) Clone() *LLMCostPriceQuery { + if _q == nil { + return nil + } + return &LLMCostPriceQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]llmcostprice.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.LLMCostPrice{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// 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 { +// Metadata map[string]string `json:"metadata,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.LLMCostPrice.Query(). +// GroupBy(llmcostprice.FieldMetadata). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *LLMCostPriceQuery) GroupBy(field string, fields ...string) *LLMCostPriceGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &LLMCostPriceGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = llmcostprice.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 { +// Metadata map[string]string `json:"metadata,omitempty"` +// } +// +// client.LLMCostPrice.Query(). +// Select(llmcostprice.FieldMetadata). +// Scan(ctx, &v) +func (_q *LLMCostPriceQuery) Select(fields ...string) *LLMCostPriceSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &LLMCostPriceSelect{LLMCostPriceQuery: _q} + sbuild.label = llmcostprice.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a LLMCostPriceSelect configured with the given aggregations. +func (_q *LLMCostPriceQuery) Aggregate(fns ...AggregateFunc) *LLMCostPriceSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *LLMCostPriceQuery) 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 !llmcostprice.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 *LLMCostPriceQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*LLMCostPrice, error) { + var ( + nodes = []*LLMCostPrice{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*LLMCostPrice).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &LLMCostPrice{config: _q.config} + nodes = append(nodes, node) + 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 + } + return nodes, nil +} + +func (_q *LLMCostPriceQuery) 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 *LLMCostPriceQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(llmcostprice.Table, llmcostprice.Columns, sqlgraph.NewFieldSpec(llmcostprice.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, llmcostprice.FieldID) + for i := range fields { + if fields[i] != llmcostprice.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 *LLMCostPriceQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(llmcostprice.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = llmcostprice.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 *LLMCostPriceQuery) ForUpdate(opts ...sql.LockOption) *LLMCostPriceQuery { + 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 *LLMCostPriceQuery) ForShare(opts ...sql.LockOption) *LLMCostPriceQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// LLMCostPriceGroupBy is the group-by builder for LLMCostPrice entities. +type LLMCostPriceGroupBy struct { + selector + build *LLMCostPriceQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *LLMCostPriceGroupBy) Aggregate(fns ...AggregateFunc) *LLMCostPriceGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *LLMCostPriceGroupBy) 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[*LLMCostPriceQuery, *LLMCostPriceGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *LLMCostPriceGroupBy) sqlScan(ctx context.Context, root *LLMCostPriceQuery, 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) +} + +// LLMCostPriceSelect is the builder for selecting fields of LLMCostPrice entities. +type LLMCostPriceSelect struct { + *LLMCostPriceQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *LLMCostPriceSelect) Aggregate(fns ...AggregateFunc) *LLMCostPriceSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *LLMCostPriceSelect) 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[*LLMCostPriceQuery, *LLMCostPriceSelect](ctx, _s.LLMCostPriceQuery, _s, _s.inters, v) +} + +func (_s *LLMCostPriceSelect) sqlScan(ctx context.Context, root *LLMCostPriceQuery, 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/ent/db/llmcostprice_update.go b/ent/db/llmcostprice_update.go new file mode 100644 index 0000000000000000000000000000000000000000..d177e4147b3b63ef6dca1943025fc9dd2094f8fe --- /dev/null +++ b/ent/db/llmcostprice_update.go @@ -0,0 +1,880 @@ +// 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/llmcostprice" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/llmcost" +) + +// LLMCostPriceUpdate is the builder for updating LLMCostPrice entities. +type LLMCostPriceUpdate struct { + config + hooks []Hook + mutation *LLMCostPriceMutation +} + +// Where appends a list predicates to the LLMCostPriceUpdate builder. +func (_u *LLMCostPriceUpdate) Where(ps ...predicate.LLMCostPrice) *LLMCostPriceUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *LLMCostPriceUpdate) SetMetadata(v map[string]string) *LLMCostPriceUpdate { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *LLMCostPriceUpdate) ClearMetadata() *LLMCostPriceUpdate { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *LLMCostPriceUpdate) SetUpdatedAt(v time.Time) *LLMCostPriceUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *LLMCostPriceUpdate) SetDeletedAt(v time.Time) *LLMCostPriceUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *LLMCostPriceUpdate) SetNillableDeletedAt(v *time.Time) *LLMCostPriceUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *LLMCostPriceUpdate) ClearDeletedAt() *LLMCostPriceUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetNamespace sets the "namespace" field. +func (_u *LLMCostPriceUpdate) SetNamespace(v string) *LLMCostPriceUpdate { + _u.mutation.SetNamespace(v) + return _u +} + +// SetNillableNamespace sets the "namespace" field if the given value is not nil. +func (_u *LLMCostPriceUpdate) SetNillableNamespace(v *string) *LLMCostPriceUpdate { + if v != nil { + _u.SetNamespace(*v) + } + return _u +} + +// ClearNamespace clears the value of the "namespace" field. +func (_u *LLMCostPriceUpdate) ClearNamespace() *LLMCostPriceUpdate { + _u.mutation.ClearNamespace() + return _u +} + +// SetProvider sets the "provider" field. +func (_u *LLMCostPriceUpdate) SetProvider(v string) *LLMCostPriceUpdate { + _u.mutation.SetProvider(v) + return _u +} + +// SetNillableProvider sets the "provider" field if the given value is not nil. +func (_u *LLMCostPriceUpdate) SetNillableProvider(v *string) *LLMCostPriceUpdate { + if v != nil { + _u.SetProvider(*v) + } + return _u +} + +// SetModelID sets the "model_id" field. +func (_u *LLMCostPriceUpdate) SetModelID(v string) *LLMCostPriceUpdate { + _u.mutation.SetModelID(v) + return _u +} + +// SetNillableModelID sets the "model_id" field if the given value is not nil. +func (_u *LLMCostPriceUpdate) SetNillableModelID(v *string) *LLMCostPriceUpdate { + if v != nil { + _u.SetModelID(*v) + } + return _u +} + +// SetModelName sets the "model_name" field. +func (_u *LLMCostPriceUpdate) SetModelName(v string) *LLMCostPriceUpdate { + _u.mutation.SetModelName(v) + return _u +} + +// SetNillableModelName sets the "model_name" field if the given value is not nil. +func (_u *LLMCostPriceUpdate) SetNillableModelName(v *string) *LLMCostPriceUpdate { + if v != nil { + _u.SetModelName(*v) + } + return _u +} + +// SetInputPerToken sets the "input_per_token" field. +func (_u *LLMCostPriceUpdate) SetInputPerToken(v alpacadecimal.Decimal) *LLMCostPriceUpdate { + _u.mutation.SetInputPerToken(v) + return _u +} + +// SetNillableInputPerToken sets the "input_per_token" field if the given value is not nil. +func (_u *LLMCostPriceUpdate) SetNillableInputPerToken(v *alpacadecimal.Decimal) *LLMCostPriceUpdate { + if v != nil { + _u.SetInputPerToken(*v) + } + return _u +} + +// SetOutputPerToken sets the "output_per_token" field. +func (_u *LLMCostPriceUpdate) SetOutputPerToken(v alpacadecimal.Decimal) *LLMCostPriceUpdate { + _u.mutation.SetOutputPerToken(v) + return _u +} + +// SetNillableOutputPerToken sets the "output_per_token" field if the given value is not nil. +func (_u *LLMCostPriceUpdate) SetNillableOutputPerToken(v *alpacadecimal.Decimal) *LLMCostPriceUpdate { + if v != nil { + _u.SetOutputPerToken(*v) + } + return _u +} + +// SetCacheReadPerToken sets the "cache_read_per_token" field. +func (_u *LLMCostPriceUpdate) SetCacheReadPerToken(v alpacadecimal.Decimal) *LLMCostPriceUpdate { + _u.mutation.SetCacheReadPerToken(v) + return _u +} + +// SetNillableCacheReadPerToken sets the "cache_read_per_token" field if the given value is not nil. +func (_u *LLMCostPriceUpdate) SetNillableCacheReadPerToken(v *alpacadecimal.Decimal) *LLMCostPriceUpdate { + if v != nil { + _u.SetCacheReadPerToken(*v) + } + return _u +} + +// SetReasoningPerToken sets the "reasoning_per_token" field. +func (_u *LLMCostPriceUpdate) SetReasoningPerToken(v alpacadecimal.Decimal) *LLMCostPriceUpdate { + _u.mutation.SetReasoningPerToken(v) + return _u +} + +// SetNillableReasoningPerToken sets the "reasoning_per_token" field if the given value is not nil. +func (_u *LLMCostPriceUpdate) SetNillableReasoningPerToken(v *alpacadecimal.Decimal) *LLMCostPriceUpdate { + if v != nil { + _u.SetReasoningPerToken(*v) + } + return _u +} + +// SetCacheWritePerToken sets the "cache_write_per_token" field. +func (_u *LLMCostPriceUpdate) SetCacheWritePerToken(v alpacadecimal.Decimal) *LLMCostPriceUpdate { + _u.mutation.SetCacheWritePerToken(v) + return _u +} + +// SetNillableCacheWritePerToken sets the "cache_write_per_token" field if the given value is not nil. +func (_u *LLMCostPriceUpdate) SetNillableCacheWritePerToken(v *alpacadecimal.Decimal) *LLMCostPriceUpdate { + if v != nil { + _u.SetCacheWritePerToken(*v) + } + return _u +} + +// SetCurrency sets the "currency" field. +func (_u *LLMCostPriceUpdate) SetCurrency(v string) *LLMCostPriceUpdate { + _u.mutation.SetCurrency(v) + return _u +} + +// SetNillableCurrency sets the "currency" field if the given value is not nil. +func (_u *LLMCostPriceUpdate) SetNillableCurrency(v *string) *LLMCostPriceUpdate { + if v != nil { + _u.SetCurrency(*v) + } + return _u +} + +// SetSource sets the "source" field. +func (_u *LLMCostPriceUpdate) SetSource(v string) *LLMCostPriceUpdate { + _u.mutation.SetSource(v) + return _u +} + +// SetNillableSource sets the "source" field if the given value is not nil. +func (_u *LLMCostPriceUpdate) SetNillableSource(v *string) *LLMCostPriceUpdate { + if v != nil { + _u.SetSource(*v) + } + return _u +} + +// SetSourcePrices sets the "source_prices" field. +func (_u *LLMCostPriceUpdate) SetSourcePrices(v llmcost.SourcePricesMap) *LLMCostPriceUpdate { + _u.mutation.SetSourcePrices(v) + return _u +} + +// ClearSourcePrices clears the value of the "source_prices" field. +func (_u *LLMCostPriceUpdate) ClearSourcePrices() *LLMCostPriceUpdate { + _u.mutation.ClearSourcePrices() + return _u +} + +// SetEffectiveFrom sets the "effective_from" field. +func (_u *LLMCostPriceUpdate) SetEffectiveFrom(v time.Time) *LLMCostPriceUpdate { + _u.mutation.SetEffectiveFrom(v) + return _u +} + +// SetNillableEffectiveFrom sets the "effective_from" field if the given value is not nil. +func (_u *LLMCostPriceUpdate) SetNillableEffectiveFrom(v *time.Time) *LLMCostPriceUpdate { + if v != nil { + _u.SetEffectiveFrom(*v) + } + return _u +} + +// SetEffectiveTo sets the "effective_to" field. +func (_u *LLMCostPriceUpdate) SetEffectiveTo(v time.Time) *LLMCostPriceUpdate { + _u.mutation.SetEffectiveTo(v) + return _u +} + +// SetNillableEffectiveTo sets the "effective_to" field if the given value is not nil. +func (_u *LLMCostPriceUpdate) SetNillableEffectiveTo(v *time.Time) *LLMCostPriceUpdate { + if v != nil { + _u.SetEffectiveTo(*v) + } + return _u +} + +// ClearEffectiveTo clears the value of the "effective_to" field. +func (_u *LLMCostPriceUpdate) ClearEffectiveTo() *LLMCostPriceUpdate { + _u.mutation.ClearEffectiveTo() + return _u +} + +// Mutation returns the LLMCostPriceMutation object of the builder. +func (_u *LLMCostPriceUpdate) Mutation() *LLMCostPriceMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *LLMCostPriceUpdate) 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 *LLMCostPriceUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *LLMCostPriceUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LLMCostPriceUpdate) 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 *LLMCostPriceUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := llmcostprice.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *LLMCostPriceUpdate) check() error { + if v, ok := _u.mutation.Provider(); ok { + if err := llmcostprice.ProviderValidator(v); err != nil { + return &ValidationError{Name: "provider", err: fmt.Errorf(`db: validator failed for field "LLMCostPrice.provider": %w`, err)} + } + } + if v, ok := _u.mutation.ModelID(); ok { + if err := llmcostprice.ModelIDValidator(v); err != nil { + return &ValidationError{Name: "model_id", err: fmt.Errorf(`db: validator failed for field "LLMCostPrice.model_id": %w`, err)} + } + } + if v, ok := _u.mutation.Currency(); ok { + if err := llmcostprice.CurrencyValidator(v); err != nil { + return &ValidationError{Name: "currency", err: fmt.Errorf(`db: validator failed for field "LLMCostPrice.currency": %w`, err)} + } + } + if v, ok := _u.mutation.Source(); ok { + if err := llmcostprice.SourceValidator(v); err != nil { + return &ValidationError{Name: "source", err: fmt.Errorf(`db: validator failed for field "LLMCostPrice.source": %w`, err)} + } + } + return nil +} + +func (_u *LLMCostPriceUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(llmcostprice.Table, llmcostprice.Columns, sqlgraph.NewFieldSpec(llmcostprice.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.Metadata(); ok { + _spec.SetField(llmcostprice.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(llmcostprice.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(llmcostprice.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(llmcostprice.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(llmcostprice.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Namespace(); ok { + _spec.SetField(llmcostprice.FieldNamespace, field.TypeString, value) + } + if _u.mutation.NamespaceCleared() { + _spec.ClearField(llmcostprice.FieldNamespace, field.TypeString) + } + if value, ok := _u.mutation.Provider(); ok { + _spec.SetField(llmcostprice.FieldProvider, field.TypeString, value) + } + if value, ok := _u.mutation.ModelID(); ok { + _spec.SetField(llmcostprice.FieldModelID, field.TypeString, value) + } + if value, ok := _u.mutation.ModelName(); ok { + _spec.SetField(llmcostprice.FieldModelName, field.TypeString, value) + } + if value, ok := _u.mutation.InputPerToken(); ok { + _spec.SetField(llmcostprice.FieldInputPerToken, field.TypeOther, value) + } + if value, ok := _u.mutation.OutputPerToken(); ok { + _spec.SetField(llmcostprice.FieldOutputPerToken, field.TypeOther, value) + } + if value, ok := _u.mutation.CacheReadPerToken(); ok { + _spec.SetField(llmcostprice.FieldCacheReadPerToken, field.TypeOther, value) + } + if value, ok := _u.mutation.ReasoningPerToken(); ok { + _spec.SetField(llmcostprice.FieldReasoningPerToken, field.TypeOther, value) + } + if value, ok := _u.mutation.CacheWritePerToken(); ok { + _spec.SetField(llmcostprice.FieldCacheWritePerToken, field.TypeOther, value) + } + if value, ok := _u.mutation.Currency(); ok { + _spec.SetField(llmcostprice.FieldCurrency, field.TypeString, value) + } + if value, ok := _u.mutation.Source(); ok { + _spec.SetField(llmcostprice.FieldSource, field.TypeString, value) + } + if value, ok := _u.mutation.SourcePrices(); ok { + vv, err := llmcostprice.ValueScanner.SourcePrices.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(llmcostprice.FieldSourcePrices, field.TypeString, vv) + } + if _u.mutation.SourcePricesCleared() { + _spec.ClearField(llmcostprice.FieldSourcePrices, field.TypeString) + } + if value, ok := _u.mutation.EffectiveFrom(); ok { + _spec.SetField(llmcostprice.FieldEffectiveFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.EffectiveTo(); ok { + _spec.SetField(llmcostprice.FieldEffectiveTo, field.TypeTime, value) + } + if _u.mutation.EffectiveToCleared() { + _spec.ClearField(llmcostprice.FieldEffectiveTo, field.TypeTime) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{llmcostprice.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// LLMCostPriceUpdateOne is the builder for updating a single LLMCostPrice entity. +type LLMCostPriceUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LLMCostPriceMutation +} + +// SetMetadata sets the "metadata" field. +func (_u *LLMCostPriceUpdateOne) SetMetadata(v map[string]string) *LLMCostPriceUpdateOne { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *LLMCostPriceUpdateOne) ClearMetadata() *LLMCostPriceUpdateOne { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *LLMCostPriceUpdateOne) SetUpdatedAt(v time.Time) *LLMCostPriceUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *LLMCostPriceUpdateOne) SetDeletedAt(v time.Time) *LLMCostPriceUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *LLMCostPriceUpdateOne) SetNillableDeletedAt(v *time.Time) *LLMCostPriceUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *LLMCostPriceUpdateOne) ClearDeletedAt() *LLMCostPriceUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetNamespace sets the "namespace" field. +func (_u *LLMCostPriceUpdateOne) SetNamespace(v string) *LLMCostPriceUpdateOne { + _u.mutation.SetNamespace(v) + return _u +} + +// SetNillableNamespace sets the "namespace" field if the given value is not nil. +func (_u *LLMCostPriceUpdateOne) SetNillableNamespace(v *string) *LLMCostPriceUpdateOne { + if v != nil { + _u.SetNamespace(*v) + } + return _u +} + +// ClearNamespace clears the value of the "namespace" field. +func (_u *LLMCostPriceUpdateOne) ClearNamespace() *LLMCostPriceUpdateOne { + _u.mutation.ClearNamespace() + return _u +} + +// SetProvider sets the "provider" field. +func (_u *LLMCostPriceUpdateOne) SetProvider(v string) *LLMCostPriceUpdateOne { + _u.mutation.SetProvider(v) + return _u +} + +// SetNillableProvider sets the "provider" field if the given value is not nil. +func (_u *LLMCostPriceUpdateOne) SetNillableProvider(v *string) *LLMCostPriceUpdateOne { + if v != nil { + _u.SetProvider(*v) + } + return _u +} + +// SetModelID sets the "model_id" field. +func (_u *LLMCostPriceUpdateOne) SetModelID(v string) *LLMCostPriceUpdateOne { + _u.mutation.SetModelID(v) + return _u +} + +// SetNillableModelID sets the "model_id" field if the given value is not nil. +func (_u *LLMCostPriceUpdateOne) SetNillableModelID(v *string) *LLMCostPriceUpdateOne { + if v != nil { + _u.SetModelID(*v) + } + return _u +} + +// SetModelName sets the "model_name" field. +func (_u *LLMCostPriceUpdateOne) SetModelName(v string) *LLMCostPriceUpdateOne { + _u.mutation.SetModelName(v) + return _u +} + +// SetNillableModelName sets the "model_name" field if the given value is not nil. +func (_u *LLMCostPriceUpdateOne) SetNillableModelName(v *string) *LLMCostPriceUpdateOne { + if v != nil { + _u.SetModelName(*v) + } + return _u +} + +// SetInputPerToken sets the "input_per_token" field. +func (_u *LLMCostPriceUpdateOne) SetInputPerToken(v alpacadecimal.Decimal) *LLMCostPriceUpdateOne { + _u.mutation.SetInputPerToken(v) + return _u +} + +// SetNillableInputPerToken sets the "input_per_token" field if the given value is not nil. +func (_u *LLMCostPriceUpdateOne) SetNillableInputPerToken(v *alpacadecimal.Decimal) *LLMCostPriceUpdateOne { + if v != nil { + _u.SetInputPerToken(*v) + } + return _u +} + +// SetOutputPerToken sets the "output_per_token" field. +func (_u *LLMCostPriceUpdateOne) SetOutputPerToken(v alpacadecimal.Decimal) *LLMCostPriceUpdateOne { + _u.mutation.SetOutputPerToken(v) + return _u +} + +// SetNillableOutputPerToken sets the "output_per_token" field if the given value is not nil. +func (_u *LLMCostPriceUpdateOne) SetNillableOutputPerToken(v *alpacadecimal.Decimal) *LLMCostPriceUpdateOne { + if v != nil { + _u.SetOutputPerToken(*v) + } + return _u +} + +// SetCacheReadPerToken sets the "cache_read_per_token" field. +func (_u *LLMCostPriceUpdateOne) SetCacheReadPerToken(v alpacadecimal.Decimal) *LLMCostPriceUpdateOne { + _u.mutation.SetCacheReadPerToken(v) + return _u +} + +// SetNillableCacheReadPerToken sets the "cache_read_per_token" field if the given value is not nil. +func (_u *LLMCostPriceUpdateOne) SetNillableCacheReadPerToken(v *alpacadecimal.Decimal) *LLMCostPriceUpdateOne { + if v != nil { + _u.SetCacheReadPerToken(*v) + } + return _u +} + +// SetReasoningPerToken sets the "reasoning_per_token" field. +func (_u *LLMCostPriceUpdateOne) SetReasoningPerToken(v alpacadecimal.Decimal) *LLMCostPriceUpdateOne { + _u.mutation.SetReasoningPerToken(v) + return _u +} + +// SetNillableReasoningPerToken sets the "reasoning_per_token" field if the given value is not nil. +func (_u *LLMCostPriceUpdateOne) SetNillableReasoningPerToken(v *alpacadecimal.Decimal) *LLMCostPriceUpdateOne { + if v != nil { + _u.SetReasoningPerToken(*v) + } + return _u +} + +// SetCacheWritePerToken sets the "cache_write_per_token" field. +func (_u *LLMCostPriceUpdateOne) SetCacheWritePerToken(v alpacadecimal.Decimal) *LLMCostPriceUpdateOne { + _u.mutation.SetCacheWritePerToken(v) + return _u +} + +// SetNillableCacheWritePerToken sets the "cache_write_per_token" field if the given value is not nil. +func (_u *LLMCostPriceUpdateOne) SetNillableCacheWritePerToken(v *alpacadecimal.Decimal) *LLMCostPriceUpdateOne { + if v != nil { + _u.SetCacheWritePerToken(*v) + } + return _u +} + +// SetCurrency sets the "currency" field. +func (_u *LLMCostPriceUpdateOne) SetCurrency(v string) *LLMCostPriceUpdateOne { + _u.mutation.SetCurrency(v) + return _u +} + +// SetNillableCurrency sets the "currency" field if the given value is not nil. +func (_u *LLMCostPriceUpdateOne) SetNillableCurrency(v *string) *LLMCostPriceUpdateOne { + if v != nil { + _u.SetCurrency(*v) + } + return _u +} + +// SetSource sets the "source" field. +func (_u *LLMCostPriceUpdateOne) SetSource(v string) *LLMCostPriceUpdateOne { + _u.mutation.SetSource(v) + return _u +} + +// SetNillableSource sets the "source" field if the given value is not nil. +func (_u *LLMCostPriceUpdateOne) SetNillableSource(v *string) *LLMCostPriceUpdateOne { + if v != nil { + _u.SetSource(*v) + } + return _u +} + +// SetSourcePrices sets the "source_prices" field. +func (_u *LLMCostPriceUpdateOne) SetSourcePrices(v llmcost.SourcePricesMap) *LLMCostPriceUpdateOne { + _u.mutation.SetSourcePrices(v) + return _u +} + +// ClearSourcePrices clears the value of the "source_prices" field. +func (_u *LLMCostPriceUpdateOne) ClearSourcePrices() *LLMCostPriceUpdateOne { + _u.mutation.ClearSourcePrices() + return _u +} + +// SetEffectiveFrom sets the "effective_from" field. +func (_u *LLMCostPriceUpdateOne) SetEffectiveFrom(v time.Time) *LLMCostPriceUpdateOne { + _u.mutation.SetEffectiveFrom(v) + return _u +} + +// SetNillableEffectiveFrom sets the "effective_from" field if the given value is not nil. +func (_u *LLMCostPriceUpdateOne) SetNillableEffectiveFrom(v *time.Time) *LLMCostPriceUpdateOne { + if v != nil { + _u.SetEffectiveFrom(*v) + } + return _u +} + +// SetEffectiveTo sets the "effective_to" field. +func (_u *LLMCostPriceUpdateOne) SetEffectiveTo(v time.Time) *LLMCostPriceUpdateOne { + _u.mutation.SetEffectiveTo(v) + return _u +} + +// SetNillableEffectiveTo sets the "effective_to" field if the given value is not nil. +func (_u *LLMCostPriceUpdateOne) SetNillableEffectiveTo(v *time.Time) *LLMCostPriceUpdateOne { + if v != nil { + _u.SetEffectiveTo(*v) + } + return _u +} + +// ClearEffectiveTo clears the value of the "effective_to" field. +func (_u *LLMCostPriceUpdateOne) ClearEffectiveTo() *LLMCostPriceUpdateOne { + _u.mutation.ClearEffectiveTo() + return _u +} + +// Mutation returns the LLMCostPriceMutation object of the builder. +func (_u *LLMCostPriceUpdateOne) Mutation() *LLMCostPriceMutation { + return _u.mutation +} + +// Where appends a list predicates to the LLMCostPriceUpdate builder. +func (_u *LLMCostPriceUpdateOne) Where(ps ...predicate.LLMCostPrice) *LLMCostPriceUpdateOne { + _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 *LLMCostPriceUpdateOne) Select(field string, fields ...string) *LLMCostPriceUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated LLMCostPrice entity. +func (_u *LLMCostPriceUpdateOne) Save(ctx context.Context) (*LLMCostPrice, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *LLMCostPriceUpdateOne) SaveX(ctx context.Context) *LLMCostPrice { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *LLMCostPriceUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LLMCostPriceUpdateOne) 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 *LLMCostPriceUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := llmcostprice.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *LLMCostPriceUpdateOne) check() error { + if v, ok := _u.mutation.Provider(); ok { + if err := llmcostprice.ProviderValidator(v); err != nil { + return &ValidationError{Name: "provider", err: fmt.Errorf(`db: validator failed for field "LLMCostPrice.provider": %w`, err)} + } + } + if v, ok := _u.mutation.ModelID(); ok { + if err := llmcostprice.ModelIDValidator(v); err != nil { + return &ValidationError{Name: "model_id", err: fmt.Errorf(`db: validator failed for field "LLMCostPrice.model_id": %w`, err)} + } + } + if v, ok := _u.mutation.Currency(); ok { + if err := llmcostprice.CurrencyValidator(v); err != nil { + return &ValidationError{Name: "currency", err: fmt.Errorf(`db: validator failed for field "LLMCostPrice.currency": %w`, err)} + } + } + if v, ok := _u.mutation.Source(); ok { + if err := llmcostprice.SourceValidator(v); err != nil { + return &ValidationError{Name: "source", err: fmt.Errorf(`db: validator failed for field "LLMCostPrice.source": %w`, err)} + } + } + return nil +} + +func (_u *LLMCostPriceUpdateOne) sqlSave(ctx context.Context) (_node *LLMCostPrice, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(llmcostprice.Table, llmcostprice.Columns, sqlgraph.NewFieldSpec(llmcostprice.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "LLMCostPrice.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, llmcostprice.FieldID) + for _, f := range fields { + if !llmcostprice.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != llmcostprice.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.Metadata(); ok { + _spec.SetField(llmcostprice.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(llmcostprice.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(llmcostprice.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(llmcostprice.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(llmcostprice.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Namespace(); ok { + _spec.SetField(llmcostprice.FieldNamespace, field.TypeString, value) + } + if _u.mutation.NamespaceCleared() { + _spec.ClearField(llmcostprice.FieldNamespace, field.TypeString) + } + if value, ok := _u.mutation.Provider(); ok { + _spec.SetField(llmcostprice.FieldProvider, field.TypeString, value) + } + if value, ok := _u.mutation.ModelID(); ok { + _spec.SetField(llmcostprice.FieldModelID, field.TypeString, value) + } + if value, ok := _u.mutation.ModelName(); ok { + _spec.SetField(llmcostprice.FieldModelName, field.TypeString, value) + } + if value, ok := _u.mutation.InputPerToken(); ok { + _spec.SetField(llmcostprice.FieldInputPerToken, field.TypeOther, value) + } + if value, ok := _u.mutation.OutputPerToken(); ok { + _spec.SetField(llmcostprice.FieldOutputPerToken, field.TypeOther, value) + } + if value, ok := _u.mutation.CacheReadPerToken(); ok { + _spec.SetField(llmcostprice.FieldCacheReadPerToken, field.TypeOther, value) + } + if value, ok := _u.mutation.ReasoningPerToken(); ok { + _spec.SetField(llmcostprice.FieldReasoningPerToken, field.TypeOther, value) + } + if value, ok := _u.mutation.CacheWritePerToken(); ok { + _spec.SetField(llmcostprice.FieldCacheWritePerToken, field.TypeOther, value) + } + if value, ok := _u.mutation.Currency(); ok { + _spec.SetField(llmcostprice.FieldCurrency, field.TypeString, value) + } + if value, ok := _u.mutation.Source(); ok { + _spec.SetField(llmcostprice.FieldSource, field.TypeString, value) + } + if value, ok := _u.mutation.SourcePrices(); ok { + vv, err := llmcostprice.ValueScanner.SourcePrices.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(llmcostprice.FieldSourcePrices, field.TypeString, vv) + } + if _u.mutation.SourcePricesCleared() { + _spec.ClearField(llmcostprice.FieldSourcePrices, field.TypeString) + } + if value, ok := _u.mutation.EffectiveFrom(); ok { + _spec.SetField(llmcostprice.FieldEffectiveFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.EffectiveTo(); ok { + _spec.SetField(llmcostprice.FieldEffectiveTo, field.TypeTime, value) + } + if _u.mutation.EffectiveToCleared() { + _spec.ClearField(llmcostprice.FieldEffectiveTo, field.TypeTime) + } + _node = &LLMCostPrice{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{llmcostprice.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/ent/db/meter.go b/ent/db/meter.go new file mode 100644 index 0000000000000000000000000000000000000000..4a131ad3b0377710f89dd9b5e082782d485bc087 --- /dev/null +++ b/ent/db/meter.go @@ -0,0 +1,296 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + dbmeter "github.com/openmeterio/openmeter/openmeter/ent/db/meter" + "github.com/openmeterio/openmeter/openmeter/meter" + "github.com/openmeterio/openmeter/pkg/models" +) + +// Meter is the model entity for the Meter schema. +type Meter 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"` + // Metadata holds the value of the "metadata" field. + Metadata map[string]string `json:"metadata,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"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Description holds the value of the "description" field. + Description *string `json:"description,omitempty"` + // Key holds the value of the "key" field. + Key string `json:"key,omitempty"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,omitempty"` + // EventType holds the value of the "event_type" field. + EventType string `json:"event_type,omitempty"` + // ValueProperty holds the value of the "value_property" field. + ValueProperty *string `json:"value_property,omitempty"` + // GroupBy holds the value of the "group_by" field. + GroupBy map[string]string `json:"group_by,omitempty"` + // Aggregation holds the value of the "aggregation" field. + Aggregation meter.MeterAggregation `json:"aggregation,omitempty"` + // EventFrom holds the value of the "event_from" field. + EventFrom *time.Time `json:"event_from,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the MeterQuery when eager-loading is set. + Edges MeterEdges `json:"edges"` + selectValues sql.SelectValues +} + +// MeterEdges holds the relations/edges for other nodes in the graph. +type MeterEdges struct { + // Feature holds the value of the feature edge. + Feature []*Feature `json:"feature,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// FeatureOrErr returns the Feature value or an error if the edge +// was not loaded in eager-loading. +func (e MeterEdges) FeatureOrErr() ([]*Feature, error) { + if e.loadedTypes[0] { + return e.Feature, nil + } + return nil, &NotLoadedError{edge: "feature"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Meter) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case dbmeter.FieldMetadata, dbmeter.FieldAnnotations, dbmeter.FieldGroupBy: + values[i] = new([]byte) + case dbmeter.FieldID, dbmeter.FieldNamespace, dbmeter.FieldName, dbmeter.FieldDescription, dbmeter.FieldKey, dbmeter.FieldEventType, dbmeter.FieldValueProperty, dbmeter.FieldAggregation: + values[i] = new(sql.NullString) + case dbmeter.FieldCreatedAt, dbmeter.FieldUpdatedAt, dbmeter.FieldDeletedAt, dbmeter.FieldEventFrom: + 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 Meter fields. +func (_m *Meter) 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 dbmeter.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 dbmeter.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 dbmeter.FieldMetadata: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field metadata", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Metadata); err != nil { + return fmt.Errorf("unmarshal field metadata: %w", err) + } + } + case dbmeter.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 dbmeter.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 dbmeter.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 dbmeter.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case dbmeter.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + _m.Description = new(string) + *_m.Description = value.String + } + case dbmeter.FieldKey: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field key", values[i]) + } else if value.Valid { + _m.Key = value.String + } + case dbmeter.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 dbmeter.FieldEventType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field event_type", values[i]) + } else if value.Valid { + _m.EventType = value.String + } + case dbmeter.FieldValueProperty: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field value_property", values[i]) + } else if value.Valid { + _m.ValueProperty = new(string) + *_m.ValueProperty = value.String + } + case dbmeter.FieldGroupBy: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field group_by", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.GroupBy); err != nil { + return fmt.Errorf("unmarshal field group_by: %w", err) + } + } + case dbmeter.FieldAggregation: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field aggregation", values[i]) + } else if value.Valid { + _m.Aggregation = meter.MeterAggregation(value.String) + } + case dbmeter.FieldEventFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field event_from", values[i]) + } else if value.Valid { + _m.EventFrom = new(time.Time) + *_m.EventFrom = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Meter. +// This includes values selected through modifiers, order, etc. +func (_m *Meter) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryFeature queries the "feature" edge of the Meter entity. +func (_m *Meter) QueryFeature() *FeatureQuery { + return NewMeterClient(_m.config).QueryFeature(_m) +} + +// Update returns a builder for updating this Meter. +// Note that you need to call Meter.Unwrap() before calling this method if this Meter +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Meter) Update() *MeterUpdateOne { + return NewMeterClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Meter 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 *Meter) Unwrap() *Meter { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: Meter is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Meter) String() string { + var builder strings.Builder + builder.WriteString("Meter(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("metadata=") + builder.WriteString(fmt.Sprintf("%v", _m.Metadata)) + 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("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + if v := _m.Description; v != nil { + builder.WriteString("description=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("key=") + builder.WriteString(_m.Key) + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + builder.WriteString(", ") + builder.WriteString("event_type=") + builder.WriteString(_m.EventType) + builder.WriteString(", ") + if v := _m.ValueProperty; v != nil { + builder.WriteString("value_property=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("group_by=") + builder.WriteString(fmt.Sprintf("%v", _m.GroupBy)) + builder.WriteString(", ") + builder.WriteString("aggregation=") + builder.WriteString(fmt.Sprintf("%v", _m.Aggregation)) + builder.WriteString(", ") + if v := _m.EventFrom; v != nil { + builder.WriteString("event_from=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteByte(')') + return builder.String() +} + +// Meters is a parsable slice of Meter. +type Meters []*Meter diff --git a/ent/db/meter/meter.go b/ent/db/meter/meter.go new file mode 100644 index 0000000000000000000000000000000000000000..630be2d93b0f1a7db18ae3ab4d93ef1c68f26813 --- /dev/null +++ b/ent/db/meter/meter.go @@ -0,0 +1,198 @@ +// Code generated by ent, DO NOT EDIT. + +package dbmeter + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/meter" +) + +const ( + // Label holds the string label denoting the meter type in the database. + Label = "meter" + // 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" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // 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" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // FieldKey holds the string denoting the key field in the database. + FieldKey = "key" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // FieldEventType holds the string denoting the event_type field in the database. + FieldEventType = "event_type" + // FieldValueProperty holds the string denoting the value_property field in the database. + FieldValueProperty = "value_property" + // FieldGroupBy holds the string denoting the group_by field in the database. + FieldGroupBy = "group_by" + // FieldAggregation holds the string denoting the aggregation field in the database. + FieldAggregation = "aggregation" + // FieldEventFrom holds the string denoting the event_from field in the database. + FieldEventFrom = "event_from" + // EdgeFeature holds the string denoting the feature edge name in mutations. + EdgeFeature = "feature" + // Table holds the table name of the meter in the database. + Table = "meters" + // FeatureTable is the table that holds the feature relation/edge. + FeatureTable = "features" + // FeatureInverseTable is the table name for the Feature entity. + // It exists in this package in order to avoid circular dependency with the "dbfeature" package. + FeatureInverseTable = "features" + // FeatureColumn is the table column denoting the feature relation/edge. + FeatureColumn = "meter_id" +) + +// Columns holds all SQL columns for meter fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldMetadata, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldName, + FieldDescription, + FieldKey, + FieldAnnotations, + FieldEventType, + FieldValueProperty, + FieldGroupBy, + FieldAggregation, + FieldEventFrom, +} + +// 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 + // KeyValidator is a validator for the "key" field. It is called by the builders before save. + KeyValidator func(string) error + // EventTypeValidator is a validator for the "event_type" field. It is called by the builders before save. + EventTypeValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// AggregationValidator is a validator for the "aggregation" field enum values. It is called by the builders before save. +func AggregationValidator(a meter.MeterAggregation) error { + switch a { + case "SUM", "COUNT", "AVG", "MIN", "MAX", "UNIQUE_COUNT", "LATEST": + return nil + default: + return fmt.Errorf("dbmeter: invalid enum value for aggregation field: %q", a) + } +} + +// OrderOption defines the ordering options for the Meter 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() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, opts...).ToFunc() +} + +// ByKey orders the results by the key field. +func ByKey(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldKey, opts...).ToFunc() +} + +// ByEventType orders the results by the event_type field. +func ByEventType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEventType, opts...).ToFunc() +} + +// ByValueProperty orders the results by the value_property field. +func ByValueProperty(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldValueProperty, opts...).ToFunc() +} + +// ByAggregation orders the results by the aggregation field. +func ByAggregation(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAggregation, opts...).ToFunc() +} + +// ByEventFrom orders the results by the event_from field. +func ByEventFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEventFrom, opts...).ToFunc() +} + +// ByFeatureCount orders the results by feature count. +func ByFeatureCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newFeatureStep(), opts...) + } +} + +// ByFeature orders the results by feature terms. +func ByFeature(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newFeatureStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newFeatureStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(FeatureInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, FeatureTable, FeatureColumn), + ) +} diff --git a/ent/db/meter/where.go b/ent/db/meter/where.go new file mode 100644 index 0000000000000000000000000000000000000000..59674b5b8889044d99799c8b54467ccfe686e5b9 --- /dev/null +++ b/ent/db/meter/where.go @@ -0,0 +1,805 @@ +// Code generated by ent, DO NOT EDIT. + +package dbmeter + +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/meter" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.Meter { + return predicate.Meter(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.Meter { + return predicate.Meter(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.Meter { + return predicate.Meter(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.Meter { + return predicate.Meter(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.Meter { + return predicate.Meter(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.Meter { + return predicate.Meter(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.Meter { + return predicate.Meter(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.Meter { + return predicate.Meter(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.Meter { + return predicate.Meter(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.Meter { + return predicate.Meter(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.Meter { + return predicate.Meter(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.Meter { + return predicate.Meter(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.Meter { + return predicate.Meter(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.Meter { + return predicate.Meter(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.Meter { + return predicate.Meter(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.Meter { + return predicate.Meter(sql.FieldEQ(FieldName, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.Meter { + return predicate.Meter(sql.FieldEQ(FieldDescription, v)) +} + +// Key applies equality check predicate on the "key" field. It's identical to KeyEQ. +func Key(v string) predicate.Meter { + return predicate.Meter(sql.FieldEQ(FieldKey, v)) +} + +// EventType applies equality check predicate on the "event_type" field. It's identical to EventTypeEQ. +func EventType(v string) predicate.Meter { + return predicate.Meter(sql.FieldEQ(FieldEventType, v)) +} + +// ValueProperty applies equality check predicate on the "value_property" field. It's identical to ValuePropertyEQ. +func ValueProperty(v string) predicate.Meter { + return predicate.Meter(sql.FieldEQ(FieldValueProperty, v)) +} + +// EventFrom applies equality check predicate on the "event_from" field. It's identical to EventFromEQ. +func EventFrom(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldEQ(FieldEventFrom, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.Meter { + return predicate.Meter(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.Meter { + return predicate.Meter(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.Meter { + return predicate.Meter(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.Meter { + return predicate.Meter(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.Meter { + return predicate.Meter(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.Meter { + return predicate.Meter(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.Meter { + return predicate.Meter(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.Meter { + return predicate.Meter(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.Meter { + return predicate.Meter(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.Meter { + return predicate.Meter(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.Meter { + return predicate.Meter(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.Meter { + return predicate.Meter(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.Meter { + return predicate.Meter(sql.FieldContainsFold(FieldNamespace, v)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.Meter { + return predicate.Meter(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.Meter { + return predicate.Meter(sql.FieldNotNull(FieldMetadata)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Meter { + return predicate.Meter(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Meter { + return predicate.Meter(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.Meter { + return predicate.Meter(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.Meter { + return predicate.Meter(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.Meter { + return predicate.Meter(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.Meter { + return predicate.Meter(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.Meter { + return predicate.Meter(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.Meter { + return predicate.Meter(sql.FieldNotNull(FieldDeletedAt)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.Meter { + return predicate.Meter(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.Meter { + return predicate.Meter(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.Meter { + return predicate.Meter(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.Meter { + return predicate.Meter(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.Meter { + return predicate.Meter(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.Meter { + return predicate.Meter(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.Meter { + return predicate.Meter(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.Meter { + return predicate.Meter(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.Meter { + return predicate.Meter(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.Meter { + return predicate.Meter(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.Meter { + return predicate.Meter(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.Meter { + return predicate.Meter(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.Meter { + return predicate.Meter(sql.FieldContainsFold(FieldName, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.Meter { + return predicate.Meter(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.Meter { + return predicate.Meter(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.Meter { + return predicate.Meter(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.Meter { + return predicate.Meter(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.Meter { + return predicate.Meter(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.Meter { + return predicate.Meter(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.Meter { + return predicate.Meter(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.Meter { + return predicate.Meter(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.Meter { + return predicate.Meter(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.Meter { + return predicate.Meter(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.Meter { + return predicate.Meter(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.Meter { + return predicate.Meter(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.Meter { + return predicate.Meter(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.Meter { + return predicate.Meter(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.Meter { + return predicate.Meter(sql.FieldContainsFold(FieldDescription, v)) +} + +// KeyEQ applies the EQ predicate on the "key" field. +func KeyEQ(v string) predicate.Meter { + return predicate.Meter(sql.FieldEQ(FieldKey, v)) +} + +// KeyNEQ applies the NEQ predicate on the "key" field. +func KeyNEQ(v string) predicate.Meter { + return predicate.Meter(sql.FieldNEQ(FieldKey, v)) +} + +// KeyIn applies the In predicate on the "key" field. +func KeyIn(vs ...string) predicate.Meter { + return predicate.Meter(sql.FieldIn(FieldKey, vs...)) +} + +// KeyNotIn applies the NotIn predicate on the "key" field. +func KeyNotIn(vs ...string) predicate.Meter { + return predicate.Meter(sql.FieldNotIn(FieldKey, vs...)) +} + +// KeyGT applies the GT predicate on the "key" field. +func KeyGT(v string) predicate.Meter { + return predicate.Meter(sql.FieldGT(FieldKey, v)) +} + +// KeyGTE applies the GTE predicate on the "key" field. +func KeyGTE(v string) predicate.Meter { + return predicate.Meter(sql.FieldGTE(FieldKey, v)) +} + +// KeyLT applies the LT predicate on the "key" field. +func KeyLT(v string) predicate.Meter { + return predicate.Meter(sql.FieldLT(FieldKey, v)) +} + +// KeyLTE applies the LTE predicate on the "key" field. +func KeyLTE(v string) predicate.Meter { + return predicate.Meter(sql.FieldLTE(FieldKey, v)) +} + +// KeyContains applies the Contains predicate on the "key" field. +func KeyContains(v string) predicate.Meter { + return predicate.Meter(sql.FieldContains(FieldKey, v)) +} + +// KeyHasPrefix applies the HasPrefix predicate on the "key" field. +func KeyHasPrefix(v string) predicate.Meter { + return predicate.Meter(sql.FieldHasPrefix(FieldKey, v)) +} + +// KeyHasSuffix applies the HasSuffix predicate on the "key" field. +func KeyHasSuffix(v string) predicate.Meter { + return predicate.Meter(sql.FieldHasSuffix(FieldKey, v)) +} + +// KeyEqualFold applies the EqualFold predicate on the "key" field. +func KeyEqualFold(v string) predicate.Meter { + return predicate.Meter(sql.FieldEqualFold(FieldKey, v)) +} + +// KeyContainsFold applies the ContainsFold predicate on the "key" field. +func KeyContainsFold(v string) predicate.Meter { + return predicate.Meter(sql.FieldContainsFold(FieldKey, v)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.Meter { + return predicate.Meter(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.Meter { + return predicate.Meter(sql.FieldNotNull(FieldAnnotations)) +} + +// EventTypeEQ applies the EQ predicate on the "event_type" field. +func EventTypeEQ(v string) predicate.Meter { + return predicate.Meter(sql.FieldEQ(FieldEventType, v)) +} + +// EventTypeNEQ applies the NEQ predicate on the "event_type" field. +func EventTypeNEQ(v string) predicate.Meter { + return predicate.Meter(sql.FieldNEQ(FieldEventType, v)) +} + +// EventTypeIn applies the In predicate on the "event_type" field. +func EventTypeIn(vs ...string) predicate.Meter { + return predicate.Meter(sql.FieldIn(FieldEventType, vs...)) +} + +// EventTypeNotIn applies the NotIn predicate on the "event_type" field. +func EventTypeNotIn(vs ...string) predicate.Meter { + return predicate.Meter(sql.FieldNotIn(FieldEventType, vs...)) +} + +// EventTypeGT applies the GT predicate on the "event_type" field. +func EventTypeGT(v string) predicate.Meter { + return predicate.Meter(sql.FieldGT(FieldEventType, v)) +} + +// EventTypeGTE applies the GTE predicate on the "event_type" field. +func EventTypeGTE(v string) predicate.Meter { + return predicate.Meter(sql.FieldGTE(FieldEventType, v)) +} + +// EventTypeLT applies the LT predicate on the "event_type" field. +func EventTypeLT(v string) predicate.Meter { + return predicate.Meter(sql.FieldLT(FieldEventType, v)) +} + +// EventTypeLTE applies the LTE predicate on the "event_type" field. +func EventTypeLTE(v string) predicate.Meter { + return predicate.Meter(sql.FieldLTE(FieldEventType, v)) +} + +// EventTypeContains applies the Contains predicate on the "event_type" field. +func EventTypeContains(v string) predicate.Meter { + return predicate.Meter(sql.FieldContains(FieldEventType, v)) +} + +// EventTypeHasPrefix applies the HasPrefix predicate on the "event_type" field. +func EventTypeHasPrefix(v string) predicate.Meter { + return predicate.Meter(sql.FieldHasPrefix(FieldEventType, v)) +} + +// EventTypeHasSuffix applies the HasSuffix predicate on the "event_type" field. +func EventTypeHasSuffix(v string) predicate.Meter { + return predicate.Meter(sql.FieldHasSuffix(FieldEventType, v)) +} + +// EventTypeEqualFold applies the EqualFold predicate on the "event_type" field. +func EventTypeEqualFold(v string) predicate.Meter { + return predicate.Meter(sql.FieldEqualFold(FieldEventType, v)) +} + +// EventTypeContainsFold applies the ContainsFold predicate on the "event_type" field. +func EventTypeContainsFold(v string) predicate.Meter { + return predicate.Meter(sql.FieldContainsFold(FieldEventType, v)) +} + +// ValuePropertyEQ applies the EQ predicate on the "value_property" field. +func ValuePropertyEQ(v string) predicate.Meter { + return predicate.Meter(sql.FieldEQ(FieldValueProperty, v)) +} + +// ValuePropertyNEQ applies the NEQ predicate on the "value_property" field. +func ValuePropertyNEQ(v string) predicate.Meter { + return predicate.Meter(sql.FieldNEQ(FieldValueProperty, v)) +} + +// ValuePropertyIn applies the In predicate on the "value_property" field. +func ValuePropertyIn(vs ...string) predicate.Meter { + return predicate.Meter(sql.FieldIn(FieldValueProperty, vs...)) +} + +// ValuePropertyNotIn applies the NotIn predicate on the "value_property" field. +func ValuePropertyNotIn(vs ...string) predicate.Meter { + return predicate.Meter(sql.FieldNotIn(FieldValueProperty, vs...)) +} + +// ValuePropertyGT applies the GT predicate on the "value_property" field. +func ValuePropertyGT(v string) predicate.Meter { + return predicate.Meter(sql.FieldGT(FieldValueProperty, v)) +} + +// ValuePropertyGTE applies the GTE predicate on the "value_property" field. +func ValuePropertyGTE(v string) predicate.Meter { + return predicate.Meter(sql.FieldGTE(FieldValueProperty, v)) +} + +// ValuePropertyLT applies the LT predicate on the "value_property" field. +func ValuePropertyLT(v string) predicate.Meter { + return predicate.Meter(sql.FieldLT(FieldValueProperty, v)) +} + +// ValuePropertyLTE applies the LTE predicate on the "value_property" field. +func ValuePropertyLTE(v string) predicate.Meter { + return predicate.Meter(sql.FieldLTE(FieldValueProperty, v)) +} + +// ValuePropertyContains applies the Contains predicate on the "value_property" field. +func ValuePropertyContains(v string) predicate.Meter { + return predicate.Meter(sql.FieldContains(FieldValueProperty, v)) +} + +// ValuePropertyHasPrefix applies the HasPrefix predicate on the "value_property" field. +func ValuePropertyHasPrefix(v string) predicate.Meter { + return predicate.Meter(sql.FieldHasPrefix(FieldValueProperty, v)) +} + +// ValuePropertyHasSuffix applies the HasSuffix predicate on the "value_property" field. +func ValuePropertyHasSuffix(v string) predicate.Meter { + return predicate.Meter(sql.FieldHasSuffix(FieldValueProperty, v)) +} + +// ValuePropertyIsNil applies the IsNil predicate on the "value_property" field. +func ValuePropertyIsNil() predicate.Meter { + return predicate.Meter(sql.FieldIsNull(FieldValueProperty)) +} + +// ValuePropertyNotNil applies the NotNil predicate on the "value_property" field. +func ValuePropertyNotNil() predicate.Meter { + return predicate.Meter(sql.FieldNotNull(FieldValueProperty)) +} + +// ValuePropertyEqualFold applies the EqualFold predicate on the "value_property" field. +func ValuePropertyEqualFold(v string) predicate.Meter { + return predicate.Meter(sql.FieldEqualFold(FieldValueProperty, v)) +} + +// ValuePropertyContainsFold applies the ContainsFold predicate on the "value_property" field. +func ValuePropertyContainsFold(v string) predicate.Meter { + return predicate.Meter(sql.FieldContainsFold(FieldValueProperty, v)) +} + +// GroupByIsNil applies the IsNil predicate on the "group_by" field. +func GroupByIsNil() predicate.Meter { + return predicate.Meter(sql.FieldIsNull(FieldGroupBy)) +} + +// GroupByNotNil applies the NotNil predicate on the "group_by" field. +func GroupByNotNil() predicate.Meter { + return predicate.Meter(sql.FieldNotNull(FieldGroupBy)) +} + +// AggregationEQ applies the EQ predicate on the "aggregation" field. +func AggregationEQ(v meter.MeterAggregation) predicate.Meter { + vc := v + return predicate.Meter(sql.FieldEQ(FieldAggregation, vc)) +} + +// AggregationNEQ applies the NEQ predicate on the "aggregation" field. +func AggregationNEQ(v meter.MeterAggregation) predicate.Meter { + vc := v + return predicate.Meter(sql.FieldNEQ(FieldAggregation, vc)) +} + +// AggregationIn applies the In predicate on the "aggregation" field. +func AggregationIn(vs ...meter.MeterAggregation) predicate.Meter { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Meter(sql.FieldIn(FieldAggregation, v...)) +} + +// AggregationNotIn applies the NotIn predicate on the "aggregation" field. +func AggregationNotIn(vs ...meter.MeterAggregation) predicate.Meter { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Meter(sql.FieldNotIn(FieldAggregation, v...)) +} + +// EventFromEQ applies the EQ predicate on the "event_from" field. +func EventFromEQ(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldEQ(FieldEventFrom, v)) +} + +// EventFromNEQ applies the NEQ predicate on the "event_from" field. +func EventFromNEQ(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldNEQ(FieldEventFrom, v)) +} + +// EventFromIn applies the In predicate on the "event_from" field. +func EventFromIn(vs ...time.Time) predicate.Meter { + return predicate.Meter(sql.FieldIn(FieldEventFrom, vs...)) +} + +// EventFromNotIn applies the NotIn predicate on the "event_from" field. +func EventFromNotIn(vs ...time.Time) predicate.Meter { + return predicate.Meter(sql.FieldNotIn(FieldEventFrom, vs...)) +} + +// EventFromGT applies the GT predicate on the "event_from" field. +func EventFromGT(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldGT(FieldEventFrom, v)) +} + +// EventFromGTE applies the GTE predicate on the "event_from" field. +func EventFromGTE(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldGTE(FieldEventFrom, v)) +} + +// EventFromLT applies the LT predicate on the "event_from" field. +func EventFromLT(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldLT(FieldEventFrom, v)) +} + +// EventFromLTE applies the LTE predicate on the "event_from" field. +func EventFromLTE(v time.Time) predicate.Meter { + return predicate.Meter(sql.FieldLTE(FieldEventFrom, v)) +} + +// EventFromIsNil applies the IsNil predicate on the "event_from" field. +func EventFromIsNil() predicate.Meter { + return predicate.Meter(sql.FieldIsNull(FieldEventFrom)) +} + +// EventFromNotNil applies the NotNil predicate on the "event_from" field. +func EventFromNotNil() predicate.Meter { + return predicate.Meter(sql.FieldNotNull(FieldEventFrom)) +} + +// HasFeature applies the HasEdge predicate on the "feature" edge. +func HasFeature() predicate.Meter { + return predicate.Meter(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, FeatureTable, FeatureColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasFeatureWith applies the HasEdge predicate on the "feature" edge with a given conditions (other predicates). +func HasFeatureWith(preds ...predicate.Feature) predicate.Meter { + return predicate.Meter(func(s *sql.Selector) { + step := newFeatureStep() + 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.Meter) predicate.Meter { + return predicate.Meter(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Meter) predicate.Meter { + return predicate.Meter(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Meter) predicate.Meter { + return predicate.Meter(sql.NotPredicates(p)) +} diff --git a/ent/db/meter_create.go b/ent/db/meter_create.go new file mode 100644 index 0000000000000000000000000000000000000000..289a54c160f6497ef0007f264d639f4a6c952f20 --- /dev/null +++ b/ent/db/meter_create.go @@ -0,0 +1,1256 @@ +// 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" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + dbmeter "github.com/openmeterio/openmeter/openmeter/ent/db/meter" + "github.com/openmeterio/openmeter/openmeter/meter" + "github.com/openmeterio/openmeter/pkg/models" +) + +// MeterCreate is the builder for creating a Meter entity. +type MeterCreate struct { + config + mutation *MeterMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *MeterCreate) SetNamespace(v string) *MeterCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetMetadata sets the "metadata" field. +func (_c *MeterCreate) SetMetadata(v map[string]string) *MeterCreate { + _c.mutation.SetMetadata(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *MeterCreate) SetCreatedAt(v time.Time) *MeterCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *MeterCreate) SetNillableCreatedAt(v *time.Time) *MeterCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *MeterCreate) SetUpdatedAt(v time.Time) *MeterCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *MeterCreate) SetNillableUpdatedAt(v *time.Time) *MeterCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *MeterCreate) SetDeletedAt(v time.Time) *MeterCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *MeterCreate) SetNillableDeletedAt(v *time.Time) *MeterCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetName sets the "name" field. +func (_c *MeterCreate) SetName(v string) *MeterCreate { + _c.mutation.SetName(v) + return _c +} + +// SetDescription sets the "description" field. +func (_c *MeterCreate) SetDescription(v string) *MeterCreate { + _c.mutation.SetDescription(v) + return _c +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_c *MeterCreate) SetNillableDescription(v *string) *MeterCreate { + if v != nil { + _c.SetDescription(*v) + } + return _c +} + +// SetKey sets the "key" field. +func (_c *MeterCreate) SetKey(v string) *MeterCreate { + _c.mutation.SetKey(v) + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *MeterCreate) SetAnnotations(v models.Annotations) *MeterCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetEventType sets the "event_type" field. +func (_c *MeterCreate) SetEventType(v string) *MeterCreate { + _c.mutation.SetEventType(v) + return _c +} + +// SetValueProperty sets the "value_property" field. +func (_c *MeterCreate) SetValueProperty(v string) *MeterCreate { + _c.mutation.SetValueProperty(v) + return _c +} + +// SetNillableValueProperty sets the "value_property" field if the given value is not nil. +func (_c *MeterCreate) SetNillableValueProperty(v *string) *MeterCreate { + if v != nil { + _c.SetValueProperty(*v) + } + return _c +} + +// SetGroupBy sets the "group_by" field. +func (_c *MeterCreate) SetGroupBy(v map[string]string) *MeterCreate { + _c.mutation.SetGroupBy(v) + return _c +} + +// SetAggregation sets the "aggregation" field. +func (_c *MeterCreate) SetAggregation(v meter.MeterAggregation) *MeterCreate { + _c.mutation.SetAggregation(v) + return _c +} + +// SetEventFrom sets the "event_from" field. +func (_c *MeterCreate) SetEventFrom(v time.Time) *MeterCreate { + _c.mutation.SetEventFrom(v) + return _c +} + +// SetNillableEventFrom sets the "event_from" field if the given value is not nil. +func (_c *MeterCreate) SetNillableEventFrom(v *time.Time) *MeterCreate { + if v != nil { + _c.SetEventFrom(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *MeterCreate) SetID(v string) *MeterCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *MeterCreate) SetNillableID(v *string) *MeterCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// AddFeatureIDs adds the "feature" edge to the Feature entity by IDs. +func (_c *MeterCreate) AddFeatureIDs(ids ...string) *MeterCreate { + _c.mutation.AddFeatureIDs(ids...) + return _c +} + +// AddFeature adds the "feature" edges to the Feature entity. +func (_c *MeterCreate) AddFeature(v ...*Feature) *MeterCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddFeatureIDs(ids...) +} + +// Mutation returns the MeterMutation object of the builder. +func (_c *MeterCreate) Mutation() *MeterMutation { + return _c.mutation +} + +// Save creates the Meter in the database. +func (_c *MeterCreate) Save(ctx context.Context) (*Meter, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *MeterCreate) SaveX(ctx context.Context) *Meter { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *MeterCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *MeterCreate) 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 *MeterCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := dbmeter.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := dbmeter.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := dbmeter.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *MeterCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "Meter.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := dbmeter.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "Meter.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "Meter.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "Meter.updated_at"`)} + } + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "Meter.name"`)} + } + if _, ok := _c.mutation.Key(); !ok { + return &ValidationError{Name: "key", err: errors.New(`db: missing required field "Meter.key"`)} + } + if v, ok := _c.mutation.Key(); ok { + if err := dbmeter.KeyValidator(v); err != nil { + return &ValidationError{Name: "key", err: fmt.Errorf(`db: validator failed for field "Meter.key": %w`, err)} + } + } + if _, ok := _c.mutation.EventType(); !ok { + return &ValidationError{Name: "event_type", err: errors.New(`db: missing required field "Meter.event_type"`)} + } + if v, ok := _c.mutation.EventType(); ok { + if err := dbmeter.EventTypeValidator(v); err != nil { + return &ValidationError{Name: "event_type", err: fmt.Errorf(`db: validator failed for field "Meter.event_type": %w`, err)} + } + } + if _, ok := _c.mutation.Aggregation(); !ok { + return &ValidationError{Name: "aggregation", err: errors.New(`db: missing required field "Meter.aggregation"`)} + } + if v, ok := _c.mutation.Aggregation(); ok { + if err := dbmeter.AggregationValidator(v); err != nil { + return &ValidationError{Name: "aggregation", err: fmt.Errorf(`db: validator failed for field "Meter.aggregation": %w`, err)} + } + } + return nil +} + +func (_c *MeterCreate) sqlSave(ctx context.Context) (*Meter, 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 Meter.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *MeterCreate) createSpec() (*Meter, *sqlgraph.CreateSpec) { + var ( + _node = &Meter{config: _c.config} + _spec = sqlgraph.NewCreateSpec(dbmeter.Table, sqlgraph.NewFieldSpec(dbmeter.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(dbmeter.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Metadata(); ok { + _spec.SetField(dbmeter.FieldMetadata, field.TypeJSON, value) + _node.Metadata = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(dbmeter.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(dbmeter.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(dbmeter.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(dbmeter.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Description(); ok { + _spec.SetField(dbmeter.FieldDescription, field.TypeString, value) + _node.Description = &value + } + if value, ok := _c.mutation.Key(); ok { + _spec.SetField(dbmeter.FieldKey, field.TypeString, value) + _node.Key = value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(dbmeter.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.EventType(); ok { + _spec.SetField(dbmeter.FieldEventType, field.TypeString, value) + _node.EventType = value + } + if value, ok := _c.mutation.ValueProperty(); ok { + _spec.SetField(dbmeter.FieldValueProperty, field.TypeString, value) + _node.ValueProperty = &value + } + if value, ok := _c.mutation.GroupBy(); ok { + _spec.SetField(dbmeter.FieldGroupBy, field.TypeJSON, value) + _node.GroupBy = value + } + if value, ok := _c.mutation.Aggregation(); ok { + _spec.SetField(dbmeter.FieldAggregation, field.TypeEnum, value) + _node.Aggregation = value + } + if value, ok := _c.mutation.EventFrom(); ok { + _spec.SetField(dbmeter.FieldEventFrom, field.TypeTime, value) + _node.EventFrom = &value + } + if nodes := _c.mutation.FeatureIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbmeter.FeatureTable, + Columns: []string{dbmeter.FeatureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbfeature.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.Meter.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.MeterUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *MeterCreate) OnConflict(opts ...sql.ConflictOption) *MeterUpsertOne { + _c.conflict = opts + return &MeterUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Meter.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *MeterCreate) OnConflictColumns(columns ...string) *MeterUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &MeterUpsertOne{ + create: _c, + } +} + +type ( + // MeterUpsertOne is the builder for "upsert"-ing + // one Meter node. + MeterUpsertOne struct { + create *MeterCreate + } + + // MeterUpsert is the "OnConflict" setter. + MeterUpsert struct { + *sql.UpdateSet + } +) + +// SetMetadata sets the "metadata" field. +func (u *MeterUpsert) SetMetadata(v map[string]string) *MeterUpsert { + u.Set(dbmeter.FieldMetadata, v) + return u +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *MeterUpsert) UpdateMetadata() *MeterUpsert { + u.SetExcluded(dbmeter.FieldMetadata) + return u +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *MeterUpsert) ClearMetadata() *MeterUpsert { + u.SetNull(dbmeter.FieldMetadata) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *MeterUpsert) SetUpdatedAt(v time.Time) *MeterUpsert { + u.Set(dbmeter.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *MeterUpsert) UpdateUpdatedAt() *MeterUpsert { + u.SetExcluded(dbmeter.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *MeterUpsert) SetDeletedAt(v time.Time) *MeterUpsert { + u.Set(dbmeter.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *MeterUpsert) UpdateDeletedAt() *MeterUpsert { + u.SetExcluded(dbmeter.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *MeterUpsert) ClearDeletedAt() *MeterUpsert { + u.SetNull(dbmeter.FieldDeletedAt) + return u +} + +// SetName sets the "name" field. +func (u *MeterUpsert) SetName(v string) *MeterUpsert { + u.Set(dbmeter.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *MeterUpsert) UpdateName() *MeterUpsert { + u.SetExcluded(dbmeter.FieldName) + return u +} + +// SetDescription sets the "description" field. +func (u *MeterUpsert) SetDescription(v string) *MeterUpsert { + u.Set(dbmeter.FieldDescription, v) + return u +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *MeterUpsert) UpdateDescription() *MeterUpsert { + u.SetExcluded(dbmeter.FieldDescription) + return u +} + +// ClearDescription clears the value of the "description" field. +func (u *MeterUpsert) ClearDescription() *MeterUpsert { + u.SetNull(dbmeter.FieldDescription) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *MeterUpsert) SetAnnotations(v models.Annotations) *MeterUpsert { + u.Set(dbmeter.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *MeterUpsert) UpdateAnnotations() *MeterUpsert { + u.SetExcluded(dbmeter.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *MeterUpsert) ClearAnnotations() *MeterUpsert { + u.SetNull(dbmeter.FieldAnnotations) + return u +} + +// SetValueProperty sets the "value_property" field. +func (u *MeterUpsert) SetValueProperty(v string) *MeterUpsert { + u.Set(dbmeter.FieldValueProperty, v) + return u +} + +// UpdateValueProperty sets the "value_property" field to the value that was provided on create. +func (u *MeterUpsert) UpdateValueProperty() *MeterUpsert { + u.SetExcluded(dbmeter.FieldValueProperty) + return u +} + +// ClearValueProperty clears the value of the "value_property" field. +func (u *MeterUpsert) ClearValueProperty() *MeterUpsert { + u.SetNull(dbmeter.FieldValueProperty) + return u +} + +// SetGroupBy sets the "group_by" field. +func (u *MeterUpsert) SetGroupBy(v map[string]string) *MeterUpsert { + u.Set(dbmeter.FieldGroupBy, v) + return u +} + +// UpdateGroupBy sets the "group_by" field to the value that was provided on create. +func (u *MeterUpsert) UpdateGroupBy() *MeterUpsert { + u.SetExcluded(dbmeter.FieldGroupBy) + return u +} + +// ClearGroupBy clears the value of the "group_by" field. +func (u *MeterUpsert) ClearGroupBy() *MeterUpsert { + u.SetNull(dbmeter.FieldGroupBy) + return u +} + +// SetEventFrom sets the "event_from" field. +func (u *MeterUpsert) SetEventFrom(v time.Time) *MeterUpsert { + u.Set(dbmeter.FieldEventFrom, v) + return u +} + +// UpdateEventFrom sets the "event_from" field to the value that was provided on create. +func (u *MeterUpsert) UpdateEventFrom() *MeterUpsert { + u.SetExcluded(dbmeter.FieldEventFrom) + return u +} + +// ClearEventFrom clears the value of the "event_from" field. +func (u *MeterUpsert) ClearEventFrom() *MeterUpsert { + u.SetNull(dbmeter.FieldEventFrom) + 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.Meter.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(dbmeter.FieldID) +// }), +// ). +// Exec(ctx) +func (u *MeterUpsertOne) UpdateNewValues() *MeterUpsertOne { + 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(dbmeter.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(dbmeter.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(dbmeter.FieldCreatedAt) + } + if _, exists := u.create.mutation.Key(); exists { + s.SetIgnore(dbmeter.FieldKey) + } + if _, exists := u.create.mutation.EventType(); exists { + s.SetIgnore(dbmeter.FieldEventType) + } + if _, exists := u.create.mutation.Aggregation(); exists { + s.SetIgnore(dbmeter.FieldAggregation) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Meter.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *MeterUpsertOne) Ignore() *MeterUpsertOne { + 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 *MeterUpsertOne) DoNothing() *MeterUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the MeterCreate.OnConflict +// documentation for more info. +func (u *MeterUpsertOne) Update(set func(*MeterUpsert)) *MeterUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&MeterUpsert{UpdateSet: update}) + })) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *MeterUpsertOne) SetMetadata(v map[string]string) *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *MeterUpsertOne) UpdateMetadata() *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *MeterUpsertOne) ClearMetadata() *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *MeterUpsertOne) SetUpdatedAt(v time.Time) *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *MeterUpsertOne) UpdateUpdatedAt() *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *MeterUpsertOne) SetDeletedAt(v time.Time) *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *MeterUpsertOne) UpdateDeletedAt() *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *MeterUpsertOne) ClearDeletedAt() *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *MeterUpsertOne) SetName(v string) *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *MeterUpsertOne) UpdateName() *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *MeterUpsertOne) SetDescription(v string) *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *MeterUpsertOne) UpdateDescription() *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *MeterUpsertOne) ClearDescription() *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.ClearDescription() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *MeterUpsertOne) SetAnnotations(v models.Annotations) *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *MeterUpsertOne) UpdateAnnotations() *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *MeterUpsertOne) ClearAnnotations() *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.ClearAnnotations() + }) +} + +// SetValueProperty sets the "value_property" field. +func (u *MeterUpsertOne) SetValueProperty(v string) *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.SetValueProperty(v) + }) +} + +// UpdateValueProperty sets the "value_property" field to the value that was provided on create. +func (u *MeterUpsertOne) UpdateValueProperty() *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.UpdateValueProperty() + }) +} + +// ClearValueProperty clears the value of the "value_property" field. +func (u *MeterUpsertOne) ClearValueProperty() *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.ClearValueProperty() + }) +} + +// SetGroupBy sets the "group_by" field. +func (u *MeterUpsertOne) SetGroupBy(v map[string]string) *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.SetGroupBy(v) + }) +} + +// UpdateGroupBy sets the "group_by" field to the value that was provided on create. +func (u *MeterUpsertOne) UpdateGroupBy() *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.UpdateGroupBy() + }) +} + +// ClearGroupBy clears the value of the "group_by" field. +func (u *MeterUpsertOne) ClearGroupBy() *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.ClearGroupBy() + }) +} + +// SetEventFrom sets the "event_from" field. +func (u *MeterUpsertOne) SetEventFrom(v time.Time) *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.SetEventFrom(v) + }) +} + +// UpdateEventFrom sets the "event_from" field to the value that was provided on create. +func (u *MeterUpsertOne) UpdateEventFrom() *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.UpdateEventFrom() + }) +} + +// ClearEventFrom clears the value of the "event_from" field. +func (u *MeterUpsertOne) ClearEventFrom() *MeterUpsertOne { + return u.Update(func(s *MeterUpsert) { + s.ClearEventFrom() + }) +} + +// Exec executes the query. +func (u *MeterUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for MeterCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *MeterUpsertOne) 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 *MeterUpsertOne) 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: MeterUpsertOne.ID is not supported by MySQL driver. Use MeterUpsertOne.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 *MeterUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// MeterCreateBulk is the builder for creating many Meter entities in bulk. +type MeterCreateBulk struct { + config + err error + builders []*MeterCreate + conflict []sql.ConflictOption +} + +// Save creates the Meter entities in the database. +func (_c *MeterCreateBulk) Save(ctx context.Context) ([]*Meter, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Meter, 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.(*MeterMutation) + 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 *MeterCreateBulk) SaveX(ctx context.Context) []*Meter { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *MeterCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *MeterCreateBulk) 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.Meter.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.MeterUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *MeterCreateBulk) OnConflict(opts ...sql.ConflictOption) *MeterUpsertBulk { + _c.conflict = opts + return &MeterUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Meter.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *MeterCreateBulk) OnConflictColumns(columns ...string) *MeterUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &MeterUpsertBulk{ + create: _c, + } +} + +// MeterUpsertBulk is the builder for "upsert"-ing +// a bulk of Meter nodes. +type MeterUpsertBulk struct { + create *MeterCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.Meter.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(dbmeter.FieldID) +// }), +// ). +// Exec(ctx) +func (u *MeterUpsertBulk) UpdateNewValues() *MeterUpsertBulk { + 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(dbmeter.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(dbmeter.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(dbmeter.FieldCreatedAt) + } + if _, exists := b.mutation.Key(); exists { + s.SetIgnore(dbmeter.FieldKey) + } + if _, exists := b.mutation.EventType(); exists { + s.SetIgnore(dbmeter.FieldEventType) + } + if _, exists := b.mutation.Aggregation(); exists { + s.SetIgnore(dbmeter.FieldAggregation) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Meter.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *MeterUpsertBulk) Ignore() *MeterUpsertBulk { + 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 *MeterUpsertBulk) DoNothing() *MeterUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the MeterCreateBulk.OnConflict +// documentation for more info. +func (u *MeterUpsertBulk) Update(set func(*MeterUpsert)) *MeterUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&MeterUpsert{UpdateSet: update}) + })) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *MeterUpsertBulk) SetMetadata(v map[string]string) *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *MeterUpsertBulk) UpdateMetadata() *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *MeterUpsertBulk) ClearMetadata() *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.ClearMetadata() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *MeterUpsertBulk) SetUpdatedAt(v time.Time) *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *MeterUpsertBulk) UpdateUpdatedAt() *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *MeterUpsertBulk) SetDeletedAt(v time.Time) *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *MeterUpsertBulk) UpdateDeletedAt() *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *MeterUpsertBulk) ClearDeletedAt() *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.ClearDeletedAt() + }) +} + +// SetName sets the "name" field. +func (u *MeterUpsertBulk) SetName(v string) *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *MeterUpsertBulk) UpdateName() *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *MeterUpsertBulk) SetDescription(v string) *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *MeterUpsertBulk) UpdateDescription() *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *MeterUpsertBulk) ClearDescription() *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.ClearDescription() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *MeterUpsertBulk) SetAnnotations(v models.Annotations) *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *MeterUpsertBulk) UpdateAnnotations() *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *MeterUpsertBulk) ClearAnnotations() *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.ClearAnnotations() + }) +} + +// SetValueProperty sets the "value_property" field. +func (u *MeterUpsertBulk) SetValueProperty(v string) *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.SetValueProperty(v) + }) +} + +// UpdateValueProperty sets the "value_property" field to the value that was provided on create. +func (u *MeterUpsertBulk) UpdateValueProperty() *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.UpdateValueProperty() + }) +} + +// ClearValueProperty clears the value of the "value_property" field. +func (u *MeterUpsertBulk) ClearValueProperty() *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.ClearValueProperty() + }) +} + +// SetGroupBy sets the "group_by" field. +func (u *MeterUpsertBulk) SetGroupBy(v map[string]string) *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.SetGroupBy(v) + }) +} + +// UpdateGroupBy sets the "group_by" field to the value that was provided on create. +func (u *MeterUpsertBulk) UpdateGroupBy() *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.UpdateGroupBy() + }) +} + +// ClearGroupBy clears the value of the "group_by" field. +func (u *MeterUpsertBulk) ClearGroupBy() *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.ClearGroupBy() + }) +} + +// SetEventFrom sets the "event_from" field. +func (u *MeterUpsertBulk) SetEventFrom(v time.Time) *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.SetEventFrom(v) + }) +} + +// UpdateEventFrom sets the "event_from" field to the value that was provided on create. +func (u *MeterUpsertBulk) UpdateEventFrom() *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.UpdateEventFrom() + }) +} + +// ClearEventFrom clears the value of the "event_from" field. +func (u *MeterUpsertBulk) ClearEventFrom() *MeterUpsertBulk { + return u.Update(func(s *MeterUpsert) { + s.ClearEventFrom() + }) +} + +// Exec executes the query. +func (u *MeterUpsertBulk) 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 MeterCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for MeterCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *MeterUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/meter_delete.go b/ent/db/meter_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..62967972cb738f51489f9658df7996ccf1a02e6d --- /dev/null +++ b/ent/db/meter_delete.go @@ -0,0 +1,89 @@ +// 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/predicate" + + dbmeter "github.com/openmeterio/openmeter/openmeter/ent/db/meter" +) + +// MeterDelete is the builder for deleting a Meter entity. +type MeterDelete struct { + config + hooks []Hook + mutation *MeterMutation +} + +// Where appends a list predicates to the MeterDelete builder. +func (_d *MeterDelete) Where(ps ...predicate.Meter) *MeterDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *MeterDelete) 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 *MeterDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *MeterDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(dbmeter.Table, sqlgraph.NewFieldSpec(dbmeter.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 +} + +// MeterDeleteOne is the builder for deleting a single Meter entity. +type MeterDeleteOne struct { + _d *MeterDelete +} + +// Where appends a list predicates to the MeterDelete builder. +func (_d *MeterDeleteOne) Where(ps ...predicate.Meter) *MeterDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *MeterDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{dbmeter.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *MeterDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/meter_query.go b/ent/db/meter_query.go new file mode 100644 index 0000000000000000000000000000000000000000..9e43f441f9570c250a73cbcab16bc1f2871683e7 --- /dev/null +++ b/ent/db/meter_query.go @@ -0,0 +1,646 @@ +// 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" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + dbmeter "github.com/openmeterio/openmeter/openmeter/ent/db/meter" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// MeterQuery is the builder for querying Meter entities. +type MeterQuery struct { + config + ctx *QueryContext + order []dbmeter.OrderOption + inters []Interceptor + predicates []predicate.Meter + withFeature *FeatureQuery + 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 MeterQuery builder. +func (_q *MeterQuery) Where(ps ...predicate.Meter) *MeterQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *MeterQuery) Limit(limit int) *MeterQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *MeterQuery) Offset(offset int) *MeterQuery { + _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 *MeterQuery) Unique(unique bool) *MeterQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *MeterQuery) Order(o ...dbmeter.OrderOption) *MeterQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryFeature chains the current query on the "feature" edge. +func (_q *MeterQuery) QueryFeature() *FeatureQuery { + query := (&FeatureClient{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(dbmeter.Table, dbmeter.FieldID, selector), + sqlgraph.To(dbfeature.Table, dbfeature.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, dbmeter.FeatureTable, dbmeter.FeatureColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Meter entity from the query. +// Returns a *NotFoundError when no Meter was found. +func (_q *MeterQuery) First(ctx context.Context) (*Meter, 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{dbmeter.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *MeterQuery) FirstX(ctx context.Context) *Meter { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Meter ID from the query. +// Returns a *NotFoundError when no Meter ID was found. +func (_q *MeterQuery) 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{dbmeter.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *MeterQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Meter entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Meter entity is found. +// Returns a *NotFoundError when no Meter entities are found. +func (_q *MeterQuery) Only(ctx context.Context) (*Meter, 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{dbmeter.Label} + default: + return nil, &NotSingularError{dbmeter.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *MeterQuery) OnlyX(ctx context.Context) *Meter { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Meter ID in the query. +// Returns a *NotSingularError when more than one Meter ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *MeterQuery) 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{dbmeter.Label} + default: + err = &NotSingularError{dbmeter.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *MeterQuery) 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 Meters. +func (_q *MeterQuery) All(ctx context.Context) ([]*Meter, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Meter, *MeterQuery]() + return withInterceptors[[]*Meter](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *MeterQuery) AllX(ctx context.Context) []*Meter { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Meter IDs. +func (_q *MeterQuery) 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(dbmeter.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *MeterQuery) 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 *MeterQuery) 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[*MeterQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *MeterQuery) 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 *MeterQuery) 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 *MeterQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the MeterQuery 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 *MeterQuery) Clone() *MeterQuery { + if _q == nil { + return nil + } + return &MeterQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]dbmeter.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Meter{}, _q.predicates...), + withFeature: _q.withFeature.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithFeature tells the query-builder to eager-load the nodes that are connected to +// the "feature" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *MeterQuery) WithFeature(opts ...func(*FeatureQuery)) *MeterQuery { + query := (&FeatureClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withFeature = 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.Meter.Query(). +// GroupBy(dbmeter.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *MeterQuery) GroupBy(field string, fields ...string) *MeterGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &MeterGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = dbmeter.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.Meter.Query(). +// Select(dbmeter.FieldNamespace). +// Scan(ctx, &v) +func (_q *MeterQuery) Select(fields ...string) *MeterSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &MeterSelect{MeterQuery: _q} + sbuild.label = dbmeter.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a MeterSelect configured with the given aggregations. +func (_q *MeterQuery) Aggregate(fns ...AggregateFunc) *MeterSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *MeterQuery) 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 !dbmeter.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 *MeterQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Meter, error) { + var ( + nodes = []*Meter{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withFeature != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Meter).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Meter{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.withFeature; query != nil { + if err := _q.loadFeature(ctx, query, nodes, + func(n *Meter) { n.Edges.Feature = []*Feature{} }, + func(n *Meter, e *Feature) { n.Edges.Feature = append(n.Edges.Feature, e) }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *MeterQuery) loadFeature(ctx context.Context, query *FeatureQuery, nodes []*Meter, init func(*Meter), assign func(*Meter, *Feature)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Meter) + 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(dbfeature.FieldMeterID) + } + query.Where(predicate.Feature(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(dbmeter.FeatureColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.MeterID + if fk == nil { + return fmt.Errorf(`foreign-key "meter_id" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "meter_id" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *MeterQuery) 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 *MeterQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(dbmeter.Table, dbmeter.Columns, sqlgraph.NewFieldSpec(dbmeter.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, dbmeter.FieldID) + for i := range fields { + if fields[i] != dbmeter.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 *MeterQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(dbmeter.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = dbmeter.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 *MeterQuery) ForUpdate(opts ...sql.LockOption) *MeterQuery { + 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 *MeterQuery) ForShare(opts ...sql.LockOption) *MeterQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// MeterGroupBy is the group-by builder for Meter entities. +type MeterGroupBy struct { + selector + build *MeterQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *MeterGroupBy) Aggregate(fns ...AggregateFunc) *MeterGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *MeterGroupBy) 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[*MeterQuery, *MeterGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *MeterGroupBy) sqlScan(ctx context.Context, root *MeterQuery, 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) +} + +// MeterSelect is the builder for selecting fields of Meter entities. +type MeterSelect struct { + *MeterQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *MeterSelect) Aggregate(fns ...AggregateFunc) *MeterSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *MeterSelect) 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[*MeterQuery, *MeterSelect](ctx, _s.MeterQuery, _s, _s.inters, v) +} + +func (_s *MeterSelect) sqlScan(ctx context.Context, root *MeterQuery, 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/ent/db/meter_update.go b/ent/db/meter_update.go new file mode 100644 index 0000000000000000000000000000000000000000..4d57dd51c7bf89fefffd8178f146fb10f48e8496 --- /dev/null +++ b/ent/db/meter_update.go @@ -0,0 +1,726 @@ +// 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" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + dbmeter "github.com/openmeterio/openmeter/openmeter/ent/db/meter" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/models" +) + +// MeterUpdate is the builder for updating Meter entities. +type MeterUpdate struct { + config + hooks []Hook + mutation *MeterMutation +} + +// Where appends a list predicates to the MeterUpdate builder. +func (_u *MeterUpdate) Where(ps ...predicate.Meter) *MeterUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *MeterUpdate) SetMetadata(v map[string]string) *MeterUpdate { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *MeterUpdate) ClearMetadata() *MeterUpdate { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *MeterUpdate) SetUpdatedAt(v time.Time) *MeterUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *MeterUpdate) SetDeletedAt(v time.Time) *MeterUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *MeterUpdate) SetNillableDeletedAt(v *time.Time) *MeterUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *MeterUpdate) ClearDeletedAt() *MeterUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *MeterUpdate) SetName(v string) *MeterUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *MeterUpdate) SetNillableName(v *string) *MeterUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *MeterUpdate) SetDescription(v string) *MeterUpdate { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *MeterUpdate) SetNillableDescription(v *string) *MeterUpdate { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *MeterUpdate) ClearDescription() *MeterUpdate { + _u.mutation.ClearDescription() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *MeterUpdate) SetAnnotations(v models.Annotations) *MeterUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *MeterUpdate) ClearAnnotations() *MeterUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetValueProperty sets the "value_property" field. +func (_u *MeterUpdate) SetValueProperty(v string) *MeterUpdate { + _u.mutation.SetValueProperty(v) + return _u +} + +// SetNillableValueProperty sets the "value_property" field if the given value is not nil. +func (_u *MeterUpdate) SetNillableValueProperty(v *string) *MeterUpdate { + if v != nil { + _u.SetValueProperty(*v) + } + return _u +} + +// ClearValueProperty clears the value of the "value_property" field. +func (_u *MeterUpdate) ClearValueProperty() *MeterUpdate { + _u.mutation.ClearValueProperty() + return _u +} + +// SetGroupBy sets the "group_by" field. +func (_u *MeterUpdate) SetGroupBy(v map[string]string) *MeterUpdate { + _u.mutation.SetGroupBy(v) + return _u +} + +// ClearGroupBy clears the value of the "group_by" field. +func (_u *MeterUpdate) ClearGroupBy() *MeterUpdate { + _u.mutation.ClearGroupBy() + return _u +} + +// SetEventFrom sets the "event_from" field. +func (_u *MeterUpdate) SetEventFrom(v time.Time) *MeterUpdate { + _u.mutation.SetEventFrom(v) + return _u +} + +// SetNillableEventFrom sets the "event_from" field if the given value is not nil. +func (_u *MeterUpdate) SetNillableEventFrom(v *time.Time) *MeterUpdate { + if v != nil { + _u.SetEventFrom(*v) + } + return _u +} + +// ClearEventFrom clears the value of the "event_from" field. +func (_u *MeterUpdate) ClearEventFrom() *MeterUpdate { + _u.mutation.ClearEventFrom() + return _u +} + +// AddFeatureIDs adds the "feature" edge to the Feature entity by IDs. +func (_u *MeterUpdate) AddFeatureIDs(ids ...string) *MeterUpdate { + _u.mutation.AddFeatureIDs(ids...) + return _u +} + +// AddFeature adds the "feature" edges to the Feature entity. +func (_u *MeterUpdate) AddFeature(v ...*Feature) *MeterUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddFeatureIDs(ids...) +} + +// Mutation returns the MeterMutation object of the builder. +func (_u *MeterUpdate) Mutation() *MeterMutation { + return _u.mutation +} + +// ClearFeature clears all "feature" edges to the Feature entity. +func (_u *MeterUpdate) ClearFeature() *MeterUpdate { + _u.mutation.ClearFeature() + return _u +} + +// RemoveFeatureIDs removes the "feature" edge to Feature entities by IDs. +func (_u *MeterUpdate) RemoveFeatureIDs(ids ...string) *MeterUpdate { + _u.mutation.RemoveFeatureIDs(ids...) + return _u +} + +// RemoveFeature removes "feature" edges to Feature entities. +func (_u *MeterUpdate) RemoveFeature(v ...*Feature) *MeterUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveFeatureIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *MeterUpdate) 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 *MeterUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *MeterUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *MeterUpdate) 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 *MeterUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := dbmeter.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +func (_u *MeterUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(dbmeter.Table, dbmeter.Columns, sqlgraph.NewFieldSpec(dbmeter.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.Metadata(); ok { + _spec.SetField(dbmeter.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(dbmeter.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(dbmeter.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(dbmeter.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(dbmeter.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(dbmeter.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(dbmeter.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(dbmeter.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(dbmeter.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(dbmeter.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.ValueProperty(); ok { + _spec.SetField(dbmeter.FieldValueProperty, field.TypeString, value) + } + if _u.mutation.ValuePropertyCleared() { + _spec.ClearField(dbmeter.FieldValueProperty, field.TypeString) + } + if value, ok := _u.mutation.GroupBy(); ok { + _spec.SetField(dbmeter.FieldGroupBy, field.TypeJSON, value) + } + if _u.mutation.GroupByCleared() { + _spec.ClearField(dbmeter.FieldGroupBy, field.TypeJSON) + } + if value, ok := _u.mutation.EventFrom(); ok { + _spec.SetField(dbmeter.FieldEventFrom, field.TypeTime, value) + } + if _u.mutation.EventFromCleared() { + _spec.ClearField(dbmeter.FieldEventFrom, field.TypeTime) + } + if _u.mutation.FeatureCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbmeter.FeatureTable, + Columns: []string{dbmeter.FeatureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbfeature.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedFeatureIDs(); len(nodes) > 0 && !_u.mutation.FeatureCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbmeter.FeatureTable, + Columns: []string{dbmeter.FeatureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbfeature.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.FeatureIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbmeter.FeatureTable, + Columns: []string{dbmeter.FeatureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbfeature.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{dbmeter.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// MeterUpdateOne is the builder for updating a single Meter entity. +type MeterUpdateOne struct { + config + fields []string + hooks []Hook + mutation *MeterMutation +} + +// SetMetadata sets the "metadata" field. +func (_u *MeterUpdateOne) SetMetadata(v map[string]string) *MeterUpdateOne { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *MeterUpdateOne) ClearMetadata() *MeterUpdateOne { + _u.mutation.ClearMetadata() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *MeterUpdateOne) SetUpdatedAt(v time.Time) *MeterUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *MeterUpdateOne) SetDeletedAt(v time.Time) *MeterUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *MeterUpdateOne) SetNillableDeletedAt(v *time.Time) *MeterUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *MeterUpdateOne) ClearDeletedAt() *MeterUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetName sets the "name" field. +func (_u *MeterUpdateOne) SetName(v string) *MeterUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *MeterUpdateOne) SetNillableName(v *string) *MeterUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *MeterUpdateOne) SetDescription(v string) *MeterUpdateOne { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *MeterUpdateOne) SetNillableDescription(v *string) *MeterUpdateOne { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *MeterUpdateOne) ClearDescription() *MeterUpdateOne { + _u.mutation.ClearDescription() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *MeterUpdateOne) SetAnnotations(v models.Annotations) *MeterUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *MeterUpdateOne) ClearAnnotations() *MeterUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetValueProperty sets the "value_property" field. +func (_u *MeterUpdateOne) SetValueProperty(v string) *MeterUpdateOne { + _u.mutation.SetValueProperty(v) + return _u +} + +// SetNillableValueProperty sets the "value_property" field if the given value is not nil. +func (_u *MeterUpdateOne) SetNillableValueProperty(v *string) *MeterUpdateOne { + if v != nil { + _u.SetValueProperty(*v) + } + return _u +} + +// ClearValueProperty clears the value of the "value_property" field. +func (_u *MeterUpdateOne) ClearValueProperty() *MeterUpdateOne { + _u.mutation.ClearValueProperty() + return _u +} + +// SetGroupBy sets the "group_by" field. +func (_u *MeterUpdateOne) SetGroupBy(v map[string]string) *MeterUpdateOne { + _u.mutation.SetGroupBy(v) + return _u +} + +// ClearGroupBy clears the value of the "group_by" field. +func (_u *MeterUpdateOne) ClearGroupBy() *MeterUpdateOne { + _u.mutation.ClearGroupBy() + return _u +} + +// SetEventFrom sets the "event_from" field. +func (_u *MeterUpdateOne) SetEventFrom(v time.Time) *MeterUpdateOne { + _u.mutation.SetEventFrom(v) + return _u +} + +// SetNillableEventFrom sets the "event_from" field if the given value is not nil. +func (_u *MeterUpdateOne) SetNillableEventFrom(v *time.Time) *MeterUpdateOne { + if v != nil { + _u.SetEventFrom(*v) + } + return _u +} + +// ClearEventFrom clears the value of the "event_from" field. +func (_u *MeterUpdateOne) ClearEventFrom() *MeterUpdateOne { + _u.mutation.ClearEventFrom() + return _u +} + +// AddFeatureIDs adds the "feature" edge to the Feature entity by IDs. +func (_u *MeterUpdateOne) AddFeatureIDs(ids ...string) *MeterUpdateOne { + _u.mutation.AddFeatureIDs(ids...) + return _u +} + +// AddFeature adds the "feature" edges to the Feature entity. +func (_u *MeterUpdateOne) AddFeature(v ...*Feature) *MeterUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddFeatureIDs(ids...) +} + +// Mutation returns the MeterMutation object of the builder. +func (_u *MeterUpdateOne) Mutation() *MeterMutation { + return _u.mutation +} + +// ClearFeature clears all "feature" edges to the Feature entity. +func (_u *MeterUpdateOne) ClearFeature() *MeterUpdateOne { + _u.mutation.ClearFeature() + return _u +} + +// RemoveFeatureIDs removes the "feature" edge to Feature entities by IDs. +func (_u *MeterUpdateOne) RemoveFeatureIDs(ids ...string) *MeterUpdateOne { + _u.mutation.RemoveFeatureIDs(ids...) + return _u +} + +// RemoveFeature removes "feature" edges to Feature entities. +func (_u *MeterUpdateOne) RemoveFeature(v ...*Feature) *MeterUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveFeatureIDs(ids...) +} + +// Where appends a list predicates to the MeterUpdate builder. +func (_u *MeterUpdateOne) Where(ps ...predicate.Meter) *MeterUpdateOne { + _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 *MeterUpdateOne) Select(field string, fields ...string) *MeterUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Meter entity. +func (_u *MeterUpdateOne) Save(ctx context.Context) (*Meter, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *MeterUpdateOne) SaveX(ctx context.Context) *Meter { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *MeterUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *MeterUpdateOne) 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 *MeterUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := dbmeter.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +func (_u *MeterUpdateOne) sqlSave(ctx context.Context) (_node *Meter, err error) { + _spec := sqlgraph.NewUpdateSpec(dbmeter.Table, dbmeter.Columns, sqlgraph.NewFieldSpec(dbmeter.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "Meter.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, dbmeter.FieldID) + for _, f := range fields { + if !dbmeter.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != dbmeter.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.Metadata(); ok { + _spec.SetField(dbmeter.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(dbmeter.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(dbmeter.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(dbmeter.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(dbmeter.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(dbmeter.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(dbmeter.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(dbmeter.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(dbmeter.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(dbmeter.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.ValueProperty(); ok { + _spec.SetField(dbmeter.FieldValueProperty, field.TypeString, value) + } + if _u.mutation.ValuePropertyCleared() { + _spec.ClearField(dbmeter.FieldValueProperty, field.TypeString) + } + if value, ok := _u.mutation.GroupBy(); ok { + _spec.SetField(dbmeter.FieldGroupBy, field.TypeJSON, value) + } + if _u.mutation.GroupByCleared() { + _spec.ClearField(dbmeter.FieldGroupBy, field.TypeJSON) + } + if value, ok := _u.mutation.EventFrom(); ok { + _spec.SetField(dbmeter.FieldEventFrom, field.TypeTime, value) + } + if _u.mutation.EventFromCleared() { + _spec.ClearField(dbmeter.FieldEventFrom, field.TypeTime) + } + if _u.mutation.FeatureCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbmeter.FeatureTable, + Columns: []string{dbmeter.FeatureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbfeature.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedFeatureIDs(); len(nodes) > 0 && !_u.mutation.FeatureCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbmeter.FeatureTable, + Columns: []string{dbmeter.FeatureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbfeature.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.FeatureIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: dbmeter.FeatureTable, + Columns: []string{dbmeter.FeatureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbfeature.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &Meter{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{dbmeter.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/ent/db/migrate/migrate.go b/ent/db/migrate/migrate.go new file mode 100644 index 0000000000000000000000000000000000000000..d8d3bcb81c71ae88b19cff8d868e55355460f039 --- /dev/null +++ b/ent/db/migrate/migrate.go @@ -0,0 +1,96 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "context" + "fmt" + "io" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql/schema" +) + +var ( + // WithGlobalUniqueID sets the universal ids options to the migration. + // If this option is enabled, ent migration will allocate a 1<<32 range + // for the ids of each entity (table). + // Note that this option cannot be applied on tables that already exist. + WithGlobalUniqueID = schema.WithGlobalUniqueID + // WithDropColumn sets the drop column option to the migration. + // If this option is enabled, ent migration will drop old columns + // that were used for both fields and edges. This defaults to false. + WithDropColumn = schema.WithDropColumn + // WithDropIndex sets the drop index option to the migration. + // If this option is enabled, ent migration will drop old indexes + // that were defined in the schema. This defaults to false. + // Note that unique constraints are defined using `UNIQUE INDEX`, + // and therefore, it's recommended to enable this option to get more + // flexibility in the schema changes. + WithDropIndex = schema.WithDropIndex + // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. + WithForeignKeys = schema.WithForeignKeys +) + +// Schema is the API for creating, migrating and dropping a schema. +type Schema struct { + drv dialect.Driver +} + +// NewSchema creates a new schema client. +func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } + +// Create creates all schema resources. +func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { + return Create(ctx, s, Tables, opts...) +} + +// Create creates all table resources using the given schema driver. +func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error { + migrate, err := schema.NewMigrate(s.drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Create(ctx, tables...) +} + +// Diff compares the state read from a database connection or migration directory with +// the state defined by the Ent schema. Changes will be written to new migration files. +func Diff(ctx context.Context, url string, opts ...schema.MigrateOption) error { + return NamedDiff(ctx, url, "changes", opts...) +} + +// NamedDiff compares the state read from a database connection or migration directory with +// the state defined by the Ent schema. Changes will be written to new named migration files. +func NamedDiff(ctx context.Context, url, name string, opts ...schema.MigrateOption) error { + return schema.Diff(ctx, url, name, Tables, opts...) +} + +// Diff creates a migration file containing the statements to resolve the diff +// between the Ent schema and the connected database. +func (s *Schema) Diff(ctx context.Context, opts ...schema.MigrateOption) error { + migrate, err := schema.NewMigrate(s.drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Diff(ctx, Tables...) +} + +// NamedDiff creates a named migration file containing the statements to resolve the diff +// between the Ent schema and the connected database. +func (s *Schema) NamedDiff(ctx context.Context, name string, opts ...schema.MigrateOption) error { + migrate, err := schema.NewMigrate(s.drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.NamedDiff(ctx, name, Tables...) +} + +// WriteTo writes the schema changes to w instead of running them against the database. +// +// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { +// log.Fatal(err) +// } +func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { + return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...) +} diff --git a/ent/db/migrate/schema.go b/ent/db/migrate/schema.go new file mode 100644 index 0000000000000000000000000000000000000000..8427239fe5f025a1f3dbdf801b5cfe98477e9ffd --- /dev/null +++ b/ent/db/migrate/schema.go @@ -0,0 +1,5688 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // AddonsColumns holds the columns for the "addons" table. + AddonsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "key", Type: field.TypeString}, + {Name: "version", Type: field.TypeInt}, + {Name: "currency", Type: field.TypeString, Default: "USD"}, + {Name: "instance_type", Type: field.TypeEnum, Enums: []string{"single", "multiple"}, Default: "single"}, + {Name: "effective_from", Type: field.TypeTime, Nullable: true}, + {Name: "effective_to", Type: field.TypeTime, Nullable: true}, + {Name: "annotations", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + } + // AddonsTable holds the schema information for the "addons" table. + AddonsTable = &schema.Table{ + Name: "addons", + Columns: AddonsColumns, + PrimaryKey: []*schema.Column{AddonsColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "addon_id", + Unique: true, + Columns: []*schema.Column{AddonsColumns[0]}, + }, + { + Name: "addon_namespace", + Unique: false, + Columns: []*schema.Column{AddonsColumns[1]}, + }, + { + Name: "addon_namespace_id", + Unique: true, + Columns: []*schema.Column{AddonsColumns[1], AddonsColumns[0]}, + }, + { + Name: "addon_namespace_key_deleted_at", + Unique: true, + Columns: []*schema.Column{AddonsColumns[1], AddonsColumns[8], AddonsColumns[5]}, + }, + { + Name: "addon_namespace_key_version", + Unique: true, + Columns: []*schema.Column{AddonsColumns[1], AddonsColumns[8], AddonsColumns[9]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + { + Name: "addon_annotations", + Unique: false, + Columns: []*schema.Column{AddonsColumns[14]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + }, + } + // AddonRateCardsColumns holds the columns for the "addon_rate_cards" table. + AddonRateCardsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "key", Type: field.TypeString}, + {Name: "tax_behavior", Type: field.TypeEnum, Nullable: true, Enums: []string{"inclusive", "exclusive"}}, + {Name: "type", Type: field.TypeEnum, Enums: []string{"flat_fee", "usage_based"}}, + {Name: "feature_key", Type: field.TypeString, Nullable: true}, + {Name: "entitlement_template", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "tax_config", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "billing_cadence", Type: field.TypeString, Nullable: true}, + {Name: "price", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "discounts", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "unit_config", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "addon_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "feature_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "tax_code_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // AddonRateCardsTable holds the schema information for the "addon_rate_cards" table. + AddonRateCardsTable = &schema.Table{ + Name: "addon_rate_cards", + Columns: AddonRateCardsColumns, + PrimaryKey: []*schema.Column{AddonRateCardsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "addon_rate_cards_addons_ratecards", + Columns: []*schema.Column{AddonRateCardsColumns[18]}, + RefColumns: []*schema.Column{AddonsColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "addon_rate_cards_features_addon_ratecard", + Columns: []*schema.Column{AddonRateCardsColumns[19]}, + RefColumns: []*schema.Column{FeaturesColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "addon_rate_cards_tax_codes_addon_rate_cards", + Columns: []*schema.Column{AddonRateCardsColumns[20]}, + RefColumns: []*schema.Column{TaxCodesColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + Indexes: []*schema.Index{ + { + Name: "addonratecard_id", + Unique: true, + Columns: []*schema.Column{AddonRateCardsColumns[0]}, + }, + { + Name: "addonratecard_namespace", + Unique: false, + Columns: []*schema.Column{AddonRateCardsColumns[1]}, + }, + { + Name: "addonratecard_namespace_id", + Unique: true, + Columns: []*schema.Column{AddonRateCardsColumns[1], AddonRateCardsColumns[0]}, + }, + { + Name: "addonratecard_namespace_key_deleted_at", + Unique: true, + Columns: []*schema.Column{AddonRateCardsColumns[1], AddonRateCardsColumns[8], AddonRateCardsColumns[5]}, + }, + { + Name: "addonratecard_tax_code_id", + Unique: false, + Columns: []*schema.Column{AddonRateCardsColumns[20]}, + }, + { + Name: "addonratecard_addon_id_key", + Unique: true, + Columns: []*schema.Column{AddonRateCardsColumns[18], AddonRateCardsColumns[8]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + { + Name: "addonratecard_addon_id_feature_key", + Unique: true, + Columns: []*schema.Column{AddonRateCardsColumns[18], AddonRateCardsColumns[11]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + }, + } + // AppsColumns holds the columns for the "apps" table. + AppsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "type", Type: field.TypeString}, + {Name: "status", Type: field.TypeString}, + } + // AppsTable holds the schema information for the "apps" table. + AppsTable = &schema.Table{ + Name: "apps", + Columns: AppsColumns, + PrimaryKey: []*schema.Column{AppsColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "app_id", + Unique: true, + Columns: []*schema.Column{AppsColumns[0]}, + }, + { + Name: "app_namespace", + Unique: false, + Columns: []*schema.Column{AppsColumns[1]}, + }, + { + Name: "app_namespace_id", + Unique: true, + Columns: []*schema.Column{AppsColumns[1], AppsColumns[0]}, + }, + { + Name: "app_namespace_type", + Unique: false, + Columns: []*schema.Column{AppsColumns[1], AppsColumns[8]}, + }, + }, + } + // AppCustomInvoicingsColumns holds the columns for the "app_custom_invoicings" table. + AppCustomInvoicingsColumns = []*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: "enable_draft_sync_hook", Type: field.TypeBool, Default: false}, + {Name: "enable_issuing_sync_hook", Type: field.TypeBool, Default: false}, + } + // AppCustomInvoicingsTable holds the schema information for the "app_custom_invoicings" table. + AppCustomInvoicingsTable = &schema.Table{ + Name: "app_custom_invoicings", + Columns: AppCustomInvoicingsColumns, + PrimaryKey: []*schema.Column{AppCustomInvoicingsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "app_custom_invoicings_apps_app", + Columns: []*schema.Column{AppCustomInvoicingsColumns[0]}, + RefColumns: []*schema.Column{AppsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "appcustominvoicing_id", + Unique: true, + Columns: []*schema.Column{AppCustomInvoicingsColumns[0]}, + }, + { + Name: "appcustominvoicing_namespace", + Unique: false, + Columns: []*schema.Column{AppCustomInvoicingsColumns[1]}, + }, + { + Name: "appcustominvoicing_namespace_id", + Unique: true, + Columns: []*schema.Column{AppCustomInvoicingsColumns[1], AppCustomInvoicingsColumns[0]}, + }, + }, + } + // AppCustomInvoicingCustomersColumns holds the columns for the "app_custom_invoicing_customers" table. + AppCustomInvoicingCustomersColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: 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: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "app_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "customer_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // AppCustomInvoicingCustomersTable holds the schema information for the "app_custom_invoicing_customers" table. + AppCustomInvoicingCustomersTable = &schema.Table{ + Name: "app_custom_invoicing_customers", + Columns: AppCustomInvoicingCustomersColumns, + PrimaryKey: []*schema.Column{AppCustomInvoicingCustomersColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "app_custom_invoicing_customers_app_custom_invoicings_customer_apps", + Columns: []*schema.Column{AppCustomInvoicingCustomersColumns[6]}, + RefColumns: []*schema.Column{AppCustomInvoicingsColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "app_custom_invoicing_customers_customers_customer", + Columns: []*schema.Column{AppCustomInvoicingCustomersColumns[7]}, + RefColumns: []*schema.Column{CustomersColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "appcustominvoicingcustomer_namespace", + Unique: false, + Columns: []*schema.Column{AppCustomInvoicingCustomersColumns[1]}, + }, + { + Name: "appcustominvoicingcustomer_namespace_app_id_customer_id", + Unique: true, + Columns: []*schema.Column{AppCustomInvoicingCustomersColumns[1], AppCustomInvoicingCustomersColumns[6], AppCustomInvoicingCustomersColumns[7]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + }, + } + // AppCustomersColumns holds the columns for the "app_customers" table. + AppCustomersColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: 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: "app_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "customer_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // AppCustomersTable holds the schema information for the "app_customers" table. + AppCustomersTable = &schema.Table{ + Name: "app_customers", + Columns: AppCustomersColumns, + PrimaryKey: []*schema.Column{AppCustomersColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "app_customers_apps_customer_apps", + Columns: []*schema.Column{AppCustomersColumns[5]}, + RefColumns: []*schema.Column{AppsColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "app_customers_customers_apps", + Columns: []*schema.Column{AppCustomersColumns[6]}, + RefColumns: []*schema.Column{CustomersColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "appcustomer_namespace", + Unique: false, + Columns: []*schema.Column{AppCustomersColumns[1]}, + }, + { + Name: "appcustomer_namespace_app_id_customer_id", + Unique: true, + Columns: []*schema.Column{AppCustomersColumns[1], AppCustomersColumns[5], AppCustomersColumns[6]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + }, + } + // AppStripesColumns holds the columns for the "app_stripes" table. + AppStripesColumns = []*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: "stripe_account_id", Type: field.TypeString}, + {Name: "stripe_livemode", Type: field.TypeBool}, + {Name: "api_key", Type: field.TypeString}, + {Name: "masked_api_key", Type: field.TypeString}, + {Name: "stripe_webhook_id", Type: field.TypeString}, + {Name: "webhook_secret", Type: field.TypeString}, + } + // AppStripesTable holds the schema information for the "app_stripes" table. + AppStripesTable = &schema.Table{ + Name: "app_stripes", + Columns: AppStripesColumns, + PrimaryKey: []*schema.Column{AppStripesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "app_stripes_apps_app", + Columns: []*schema.Column{AppStripesColumns[0]}, + RefColumns: []*schema.Column{AppsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "appstripe_id", + Unique: true, + Columns: []*schema.Column{AppStripesColumns[0]}, + }, + { + Name: "appstripe_namespace", + Unique: false, + Columns: []*schema.Column{AppStripesColumns[1]}, + }, + { + Name: "appstripe_namespace_stripe_account_id_stripe_livemode", + Unique: true, + Columns: []*schema.Column{AppStripesColumns[1], AppStripesColumns[5], AppStripesColumns[6]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + }, + } + // AppStripeCustomersColumns holds the columns for the "app_stripe_customers" table. + AppStripeCustomersColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: 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: "stripe_customer_id", Type: field.TypeString}, + {Name: "stripe_default_payment_method_id", Type: field.TypeString, Nullable: true}, + {Name: "app_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "customer_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // AppStripeCustomersTable holds the schema information for the "app_stripe_customers" table. + AppStripeCustomersTable = &schema.Table{ + Name: "app_stripe_customers", + Columns: AppStripeCustomersColumns, + PrimaryKey: []*schema.Column{AppStripeCustomersColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "app_stripe_customers_app_stripes_customer_apps", + Columns: []*schema.Column{AppStripeCustomersColumns[7]}, + RefColumns: []*schema.Column{AppStripesColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "app_stripe_customers_customers_customer", + Columns: []*schema.Column{AppStripeCustomersColumns[8]}, + RefColumns: []*schema.Column{CustomersColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "appstripecustomer_namespace", + Unique: false, + Columns: []*schema.Column{AppStripeCustomersColumns[1]}, + }, + { + Name: "appstripecustomer_namespace_app_id_customer_id", + Unique: true, + Columns: []*schema.Column{AppStripeCustomersColumns[1], AppStripeCustomersColumns[7], AppStripeCustomersColumns[8]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + { + Name: "appstripecustomer_app_id_stripe_customer_id", + Unique: true, + Columns: []*schema.Column{AppStripeCustomersColumns[7], AppStripeCustomersColumns[5]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + }, + } + // BalanceSnapshotsColumns holds the columns for the "balance_snapshots" table. + BalanceSnapshotsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: 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: "grant_balances", Type: field.TypeJSON, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "usage", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "balance", Type: field.TypeFloat64, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "overage", Type: field.TypeFloat64, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "at", Type: field.TypeTime}, + {Name: "owner_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // BalanceSnapshotsTable holds the schema information for the "balance_snapshots" table. + BalanceSnapshotsTable = &schema.Table{ + Name: "balance_snapshots", + Columns: BalanceSnapshotsColumns, + PrimaryKey: []*schema.Column{BalanceSnapshotsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "balance_snapshots_entitlements_balance_snapshot", + Columns: []*schema.Column{BalanceSnapshotsColumns[10]}, + RefColumns: []*schema.Column{EntitlementsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "balancesnapshot_namespace", + Unique: false, + Columns: []*schema.Column{BalanceSnapshotsColumns[1]}, + }, + { + Name: "balancesnapshot_namespace_owner_id_at", + Unique: false, + Columns: []*schema.Column{BalanceSnapshotsColumns[1], BalanceSnapshotsColumns[10], BalanceSnapshotsColumns[9]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + }, + } + // BillingCustomerLocksColumns holds the columns for the "billing_customer_locks" table. + BillingCustomerLocksColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "customer_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // BillingCustomerLocksTable holds the schema information for the "billing_customer_locks" table. + BillingCustomerLocksTable = &schema.Table{ + Name: "billing_customer_locks", + Columns: BillingCustomerLocksColumns, + PrimaryKey: []*schema.Column{BillingCustomerLocksColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "billingcustomerlock_namespace", + Unique: false, + Columns: []*schema.Column{BillingCustomerLocksColumns[1]}, + }, + { + Name: "billingcustomerlock_id", + Unique: true, + Columns: []*schema.Column{BillingCustomerLocksColumns[0]}, + }, + { + Name: "billingcustomerlock_namespace_customer_id", + Unique: true, + Columns: []*schema.Column{BillingCustomerLocksColumns[1], BillingCustomerLocksColumns[2]}, + }, + }, + } + // BillingCustomerOverridesColumns holds the columns for the "billing_customer_overrides" table. + BillingCustomerOverridesColumns = []*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: "tax_behavior", Type: field.TypeEnum, Nullable: true, Enums: []string{"inclusive", "exclusive"}}, + {Name: "collection_alignment", Type: field.TypeEnum, Nullable: true, Enums: []string{"subscription", "anchored"}}, + {Name: "anchored_alignment_detail", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "line_collection_period", Type: field.TypeString, Nullable: true}, + {Name: "invoice_auto_advance", Type: field.TypeBool, Nullable: true}, + {Name: "invoice_draft_period", Type: field.TypeString, Nullable: true}, + {Name: "invoice_due_after", Type: field.TypeString, Nullable: true}, + {Name: "invoice_collection_method", Type: field.TypeEnum, Nullable: true, Enums: []string{"charge_automatically", "send_invoice"}}, + {Name: "invoice_progressive_billing", Type: field.TypeBool, Nullable: true}, + {Name: "invoice_default_tax_config", Type: field.TypeJSON, Nullable: true}, + {Name: "billing_profile_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "customer_id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "tax_code_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // BillingCustomerOverridesTable holds the schema information for the "billing_customer_overrides" table. + BillingCustomerOverridesTable = &schema.Table{ + Name: "billing_customer_overrides", + Columns: BillingCustomerOverridesColumns, + PrimaryKey: []*schema.Column{BillingCustomerOverridesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "billing_customer_overrides_billing_profiles_billing_customer_override", + Columns: []*schema.Column{BillingCustomerOverridesColumns[15]}, + RefColumns: []*schema.Column{BillingProfilesColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "billing_customer_overrides_customers_billing_customer_override", + Columns: []*schema.Column{BillingCustomerOverridesColumns[16]}, + RefColumns: []*schema.Column{CustomersColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "billing_customer_overrides_tax_codes_billing_customer_overrides", + Columns: []*schema.Column{BillingCustomerOverridesColumns[17]}, + RefColumns: []*schema.Column{TaxCodesColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + Indexes: []*schema.Index{ + { + Name: "billingcustomeroverride_id", + Unique: true, + Columns: []*schema.Column{BillingCustomerOverridesColumns[0]}, + }, + { + Name: "billingcustomeroverride_namespace", + Unique: false, + Columns: []*schema.Column{BillingCustomerOverridesColumns[1]}, + }, + { + Name: "billingcustomeroverride_tax_code_id", + Unique: false, + Columns: []*schema.Column{BillingCustomerOverridesColumns[17]}, + }, + { + Name: "billingcustomeroverride_namespace_id", + Unique: true, + Columns: []*schema.Column{BillingCustomerOverridesColumns[1], BillingCustomerOverridesColumns[0]}, + }, + { + Name: "billingcustomeroverride_namespace_customer_id", + Unique: true, + Columns: []*schema.Column{BillingCustomerOverridesColumns[1], BillingCustomerOverridesColumns[16]}, + }, + }, + } + // BillingInvoicesColumns holds the columns for the "billing_invoices" table. + BillingInvoicesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "supplier_address_country", Type: field.TypeString, Nullable: true, Size: 2}, + {Name: "supplier_address_postal_code", Type: field.TypeString, Nullable: true}, + {Name: "supplier_address_state", Type: field.TypeString, Nullable: true}, + {Name: "supplier_address_city", Type: field.TypeString, Nullable: true}, + {Name: "supplier_address_line1", Type: field.TypeString, Nullable: true}, + {Name: "supplier_address_line2", Type: field.TypeString, Nullable: true}, + {Name: "supplier_address_phone_number", Type: field.TypeString, Nullable: true}, + {Name: "customer_address_country", Type: field.TypeString, Nullable: true, Size: 2}, + {Name: "customer_address_postal_code", Type: field.TypeString, Nullable: true}, + {Name: "customer_address_state", Type: field.TypeString, Nullable: true}, + {Name: "customer_address_city", Type: field.TypeString, Nullable: true}, + {Name: "customer_address_line1", Type: field.TypeString, Nullable: true}, + {Name: "customer_address_line2", Type: field.TypeString, Nullable: true}, + {Name: "customer_address_phone_number", Type: field.TypeString, Nullable: true}, + {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: "invoicing_app_external_id", Type: field.TypeString, Nullable: true}, + {Name: "payment_app_external_id", Type: field.TypeString, Nullable: true}, + {Name: "tax_app_external_id", Type: field.TypeString, Nullable: true}, + {Name: "supplier_name", Type: field.TypeString}, + {Name: "supplier_tax_code", Type: field.TypeString, Nullable: true}, + {Name: "customer_key", Type: field.TypeString, Nullable: true}, + {Name: "customer_name", Type: field.TypeString}, + {Name: "customer_usage_attribution", Type: field.TypeJSON, Nullable: true}, + {Name: "number", Type: field.TypeString}, + {Name: "type", Type: field.TypeEnum, Enums: []string{"standard", "gathering"}}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "voided_at", Type: field.TypeTime, Nullable: true}, + {Name: "issued_at", Type: field.TypeTime, Nullable: true}, + {Name: "sent_to_customer_at", Type: field.TypeTime, Nullable: true}, + {Name: "draft_until", Type: field.TypeTime, Nullable: true}, + {Name: "quantity_snapshoted_at", Type: field.TypeTime, Nullable: true}, + {Name: "deletion_source", Type: field.TypeEnum, Nullable: true, Enums: []string{"system", "api_request"}}, + {Name: "currency", Type: field.TypeString, SchemaType: map[string]string{"postgres": "varchar(3)"}}, + {Name: "due_at", Type: field.TypeTime, Nullable: true}, + {Name: "status", Type: field.TypeEnum, Enums: []string{"gathering", "draft.created", "draft.waiting_for_collection", "draft.collecting", "draft.updating", "draft.manual_approval_needed", "draft.validating", "draft.invalid", "draft.syncing", "draft.sync_failed", "draft.waiting_auto_approval", "draft.ready_to_issue", "delete.in_progress", "delete.syncing", "delete.failed", "deleted", "issuing.syncing", "issuing.failed", "issuing.charge_booking", "issuing.charge_booking_failed", "issued", "payment_processing.pending", "payment_processing.booking_authorized", "payment_processing.booking_authorized_failed", "payment_processing.booking_authorized_and_settled", "payment_processing.booking_authorized_and_settled_failed", "payment_processing.authorized", "payment_processing.failed", "payment_processing.action_required", "payment_processing.booking_settled", "payment_processing.booking_settled_failed", "overdue", "paid", "uncollectible", "voided"}}, + {Name: "status_details_cache", Type: field.TypeJSON, Nullable: true}, + {Name: "period_start", Type: field.TypeTime, Nullable: true}, + {Name: "period_end", Type: field.TypeTime, Nullable: true}, + {Name: "collection_at", Type: field.TypeTime, Nullable: true}, + {Name: "payment_processing_entered_at", Type: field.TypeTime, Nullable: true}, + {Name: "schema_level", Type: field.TypeInt, Default: 2}, + {Name: "tax_app_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "invoicing_app_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "payment_app_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "source_billing_profile_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "workflow_config_id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "customer_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // BillingInvoicesTable holds the schema information for the "billing_invoices" table. + BillingInvoicesTable = &schema.Table{ + Name: "billing_invoices", + Columns: BillingInvoicesColumns, + PrimaryKey: []*schema.Column{BillingInvoicesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "billing_invoices_apps_billing_invoice_tax_app", + Columns: []*schema.Column{BillingInvoicesColumns[54]}, + RefColumns: []*schema.Column{AppsColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "billing_invoices_apps_billing_invoice_invoicing_app", + Columns: []*schema.Column{BillingInvoicesColumns[55]}, + RefColumns: []*schema.Column{AppsColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "billing_invoices_apps_billing_invoice_payment_app", + Columns: []*schema.Column{BillingInvoicesColumns[56]}, + RefColumns: []*schema.Column{AppsColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "billing_invoices_billing_profiles_billing_invoices", + Columns: []*schema.Column{BillingInvoicesColumns[57]}, + RefColumns: []*schema.Column{BillingProfilesColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "billing_invoices_billing_workflow_configs_billing_invoices", + Columns: []*schema.Column{BillingInvoicesColumns[58]}, + RefColumns: []*schema.Column{BillingWorkflowConfigsColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "billing_invoices_customers_billing_invoice", + Columns: []*schema.Column{BillingInvoicesColumns[59]}, + RefColumns: []*schema.Column{CustomersColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "billinginvoice_id", + Unique: true, + Columns: []*schema.Column{BillingInvoicesColumns[0]}, + }, + { + Name: "billinginvoice_namespace", + Unique: false, + Columns: []*schema.Column{BillingInvoicesColumns[1]}, + }, + { + Name: "billinginvoice_namespace_id", + Unique: false, + Columns: []*schema.Column{BillingInvoicesColumns[1], BillingInvoicesColumns[0]}, + }, + { + Name: "billinginvoice_namespace_customer_id", + Unique: false, + Columns: []*schema.Column{BillingInvoicesColumns[1], BillingInvoicesColumns[59]}, + }, + { + Name: "billinginvoice_namespace_status", + Unique: false, + Columns: []*schema.Column{BillingInvoicesColumns[1], BillingInvoicesColumns[47]}, + }, + { + Name: "billinginvoice_namespace_period_start", + Unique: false, + Columns: []*schema.Column{BillingInvoicesColumns[1], BillingInvoicesColumns[49]}, + }, + { + Name: "billinginvoice_namespace_created_at", + Unique: false, + Columns: []*schema.Column{BillingInvoicesColumns[1], BillingInvoicesColumns[3]}, + }, + { + Name: "billinginvoice_namespace_updated_at", + Unique: false, + Columns: []*schema.Column{BillingInvoicesColumns[1], BillingInvoicesColumns[4]}, + }, + { + Name: "billinginvoice_namespace_issued_at", + Unique: false, + Columns: []*schema.Column{BillingInvoicesColumns[1], BillingInvoicesColumns[40]}, + }, + { + Name: "billinginvoice_status_details_cache", + Unique: false, + Columns: []*schema.Column{BillingInvoicesColumns[48]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "billinginvoice_namespace_customer_id_currency", + Unique: true, + Columns: []*schema.Column{BillingInvoicesColumns[1], BillingInvoicesColumns[59], BillingInvoicesColumns[45]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL and status = 'gathering'", + }, + }, + }, + } + // BillingInvoiceFlatFeeLineConfigsColumns holds the columns for the "billing_invoice_flat_fee_line_configs" table. + BillingInvoiceFlatFeeLineConfigsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "per_unit_amount", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "category", Type: field.TypeEnum, Enums: []string{"regular", "commitment"}, Default: "regular"}, + {Name: "payment_term", Type: field.TypeEnum, Enums: []string{"in_advance", "in_arrears"}, Default: "in_advance"}, + {Name: "index", Type: field.TypeInt, Nullable: true}, + } + // BillingInvoiceFlatFeeLineConfigsTable holds the schema information for the "billing_invoice_flat_fee_line_configs" table. + BillingInvoiceFlatFeeLineConfigsTable = &schema.Table{ + Name: "billing_invoice_flat_fee_line_configs", + Columns: BillingInvoiceFlatFeeLineConfigsColumns, + PrimaryKey: []*schema.Column{BillingInvoiceFlatFeeLineConfigsColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "billinginvoiceflatfeelineconfig_namespace", + Unique: false, + Columns: []*schema.Column{BillingInvoiceFlatFeeLineConfigsColumns[1]}, + }, + { + Name: "billinginvoiceflatfeelineconfig_id", + Unique: true, + Columns: []*schema.Column{BillingInvoiceFlatFeeLineConfigsColumns[0]}, + }, + }, + } + // BillingInvoiceLinesColumns holds the columns for the "billing_invoice_lines" table. + BillingInvoiceLinesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "currency", Type: field.TypeString, SchemaType: map[string]string{"postgres": "varchar(3)"}}, + {Name: "tax_config", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "tax_behavior", Type: field.TypeEnum, Nullable: true, Enums: []string{"inclusive", "exclusive"}}, + {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: "invoicing_app_external_id", Type: field.TypeString, Nullable: true}, + {Name: "period_start", Type: field.TypeTime}, + {Name: "period_end", Type: field.TypeTime}, + {Name: "managed_by", Type: field.TypeEnum, Enums: []string{"subscription", "system", "manual"}}, + {Name: "invoice_at", Type: field.TypeTime}, + {Name: "override_collection_period_end", Type: field.TypeTime, Nullable: true}, + {Name: "type", Type: field.TypeEnum, Enums: []string{"flat_fee", "usage_based"}}, + {Name: "status", Type: field.TypeEnum, Enums: []string{"valid", "detailed"}}, + {Name: "quantity", Type: field.TypeOther, Nullable: true, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "ratecard_discounts", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {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: "engine", Type: field.TypeEnum, Enums: []string{"invoicing", "charge_flatfee", "charge_usagebased", "charge_creditpurchase"}, Default: "invoicing"}, + {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)"}}, + {Name: "fee_line_config_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "usage_based_line_config_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "parent_line_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "split_line_group_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "charge_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "subscription_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "subscription_item_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "subscription_phase_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "tax_code_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // BillingInvoiceLinesTable holds the schema information for the "billing_invoice_lines" table. + BillingInvoiceLinesTable = &schema.Table{ + Name: "billing_invoice_lines", + Columns: BillingInvoiceLinesColumns, + PrimaryKey: []*schema.Column{BillingInvoiceLinesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "billing_invoice_lines_billing_invoices_billing_invoice_lines", + Columns: []*schema.Column{BillingInvoiceLinesColumns[35]}, + 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[36]}, + 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[37]}, + RefColumns: []*schema.Column{BillingInvoiceUsageBasedLineConfigsColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "billing_invoice_lines_billing_invoice_lines_detailed_lines", + Columns: []*schema.Column{BillingInvoiceLinesColumns[38]}, + RefColumns: []*schema.Column{BillingInvoiceLinesColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "billing_invoice_lines_billing_invoice_split_line_groups_billing_invoice_lines", + Columns: []*schema.Column{BillingInvoiceLinesColumns[39]}, + RefColumns: []*schema.Column{BillingInvoiceSplitLineGroupsColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "billing_invoice_lines_charges_billing_invoice_lines", + Columns: []*schema.Column{BillingInvoiceLinesColumns[40]}, + RefColumns: []*schema.Column{ChargesColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "billing_invoice_lines_subscriptions_billing_lines", + Columns: []*schema.Column{BillingInvoiceLinesColumns[41]}, + RefColumns: []*schema.Column{SubscriptionsColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "billing_invoice_lines_subscription_items_billing_lines", + Columns: []*schema.Column{BillingInvoiceLinesColumns[42]}, + RefColumns: []*schema.Column{SubscriptionItemsColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "billing_invoice_lines_subscription_phases_billing_lines", + Columns: []*schema.Column{BillingInvoiceLinesColumns[43]}, + RefColumns: []*schema.Column{SubscriptionPhasesColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "billing_invoice_lines_tax_codes_billing_invoice_lines", + Columns: []*schema.Column{BillingInvoiceLinesColumns[44]}, + RefColumns: []*schema.Column{TaxCodesColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + Indexes: []*schema.Index{ + { + Name: "billinginvoiceline_annotations", + Unique: false, + Columns: []*schema.Column{BillingInvoiceLinesColumns[1]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "billinginvoiceline_id", + Unique: true, + Columns: []*schema.Column{BillingInvoiceLinesColumns[0]}, + }, + { + Name: "billinginvoiceline_namespace", + Unique: false, + Columns: []*schema.Column{BillingInvoiceLinesColumns[2]}, + }, + { + Name: "billinginvoiceline_namespace_id", + Unique: true, + Columns: []*schema.Column{BillingInvoiceLinesColumns[2], BillingInvoiceLinesColumns[0]}, + }, + { + Name: "billinginvoiceline_tax_code_id", + Unique: false, + Columns: []*schema.Column{BillingInvoiceLinesColumns[44]}, + }, + { + Name: "billinginvoiceline_namespace_invoice_id", + Unique: false, + Columns: []*schema.Column{BillingInvoiceLinesColumns[2], BillingInvoiceLinesColumns[35]}, + }, + { + Name: "billinginvoiceline_namespace_parent_line_id", + Unique: false, + Columns: []*schema.Column{BillingInvoiceLinesColumns[2], BillingInvoiceLinesColumns[38]}, + }, + { + Name: "billinginvoiceline_namespace_parent_line_id_child_unique_reference_id", + Unique: true, + Columns: []*schema.Column{BillingInvoiceLinesColumns[2], BillingInvoiceLinesColumns[38], BillingInvoiceLinesColumns[30]}, + Annotation: &entsql.IndexAnnotation{ + Where: "child_unique_reference_id IS NOT NULL AND deleted_at IS NULL", + }, + }, + { + Name: "billinginvoiceline_namespace_subscription_id_subscription_phase_id_subscription_item_id", + Unique: false, + Columns: []*schema.Column{BillingInvoiceLinesColumns[2], BillingInvoiceLinesColumns[41], BillingInvoiceLinesColumns[43], BillingInvoiceLinesColumns[42]}, + }, + }, + } + // BillingInvoiceLineDiscountsColumns holds the columns for the "billing_invoice_line_discounts" table. + BillingInvoiceLineDiscountsColumns = []*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: "invoicing_app_external_id", Type: field.TypeString, Nullable: true}, + {Name: "child_unique_reference_id", Type: field.TypeString, Nullable: true}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "reason", Type: field.TypeEnum, Enums: []string{"maximum_spend", "ratecard_percentage", "ratecard_usage"}}, + {Name: "amount", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "rounding_amount", Type: field.TypeOther, Nullable: true, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "source_discount", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "line_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // BillingInvoiceLineDiscountsTable holds the schema information for the "billing_invoice_line_discounts" table. + BillingInvoiceLineDiscountsTable = &schema.Table{ + Name: "billing_invoice_line_discounts", + Columns: BillingInvoiceLineDiscountsColumns, + PrimaryKey: []*schema.Column{BillingInvoiceLineDiscountsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "billing_invoice_line_discounts_billing_invoice_lines_line_amount_discounts", + Columns: []*schema.Column{BillingInvoiceLineDiscountsColumns[12]}, + RefColumns: []*schema.Column{BillingInvoiceLinesColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "billinginvoicelinediscount_id", + Unique: true, + Columns: []*schema.Column{BillingInvoiceLineDiscountsColumns[0]}, + }, + { + Name: "billinginvoicelinediscount_namespace", + Unique: false, + Columns: []*schema.Column{BillingInvoiceLineDiscountsColumns[1]}, + }, + { + Name: "billinginvoicelinediscount_namespace_line_id", + Unique: false, + Columns: []*schema.Column{BillingInvoiceLineDiscountsColumns[1], BillingInvoiceLineDiscountsColumns[12]}, + }, + { + Name: "billinginvoicelinediscount_namespace_line_id_child_unique_reference_id", + Unique: true, + Columns: []*schema.Column{BillingInvoiceLineDiscountsColumns[1], BillingInvoiceLineDiscountsColumns[12], BillingInvoiceLineDiscountsColumns[6]}, + Annotation: &entsql.IndexAnnotation{ + Where: "child_unique_reference_id IS NOT NULL AND deleted_at IS NULL", + }, + }, + }, + } + // BillingInvoiceLineUsageDiscountsColumns holds the columns for the "billing_invoice_line_usage_discounts" table. + BillingInvoiceLineUsageDiscountsColumns = []*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: "invoicing_app_external_id", Type: field.TypeString, Nullable: true}, + {Name: "child_unique_reference_id", Type: field.TypeString, Nullable: true}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "reason", Type: field.TypeEnum, Enums: []string{"maximum_spend", "ratecard_percentage", "ratecard_usage"}}, + {Name: "quantity", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "pre_line_period_quantity", Type: field.TypeOther, Nullable: true, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "reason_details", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "line_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // BillingInvoiceLineUsageDiscountsTable holds the schema information for the "billing_invoice_line_usage_discounts" table. + BillingInvoiceLineUsageDiscountsTable = &schema.Table{ + Name: "billing_invoice_line_usage_discounts", + Columns: BillingInvoiceLineUsageDiscountsColumns, + PrimaryKey: []*schema.Column{BillingInvoiceLineUsageDiscountsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "billing_invoice_line_usage_discounts_billing_invoice_lines_line_usage_discounts", + Columns: []*schema.Column{BillingInvoiceLineUsageDiscountsColumns[12]}, + RefColumns: []*schema.Column{BillingInvoiceLinesColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "billinginvoicelineusagediscount_id", + Unique: true, + Columns: []*schema.Column{BillingInvoiceLineUsageDiscountsColumns[0]}, + }, + { + Name: "billinginvoicelineusagediscount_namespace", + Unique: false, + Columns: []*schema.Column{BillingInvoiceLineUsageDiscountsColumns[1]}, + }, + { + Name: "billinginvoicelineusagediscount_namespace_line_id", + Unique: false, + Columns: []*schema.Column{BillingInvoiceLineUsageDiscountsColumns[1], BillingInvoiceLineUsageDiscountsColumns[12]}, + }, + { + Name: "billinginvoicelineusagediscount_namespace_line_id_child_unique_reference_id", + Unique: true, + Columns: []*schema.Column{BillingInvoiceLineUsageDiscountsColumns[1], BillingInvoiceLineUsageDiscountsColumns[12], BillingInvoiceLineUsageDiscountsColumns[6]}, + Annotation: &entsql.IndexAnnotation{ + Where: "child_unique_reference_id IS NOT NULL AND deleted_at IS NULL", + }, + }, + }, + } + // BillingInvoiceSplitLineGroupsColumns holds the columns for the "billing_invoice_split_line_groups" table. + BillingInvoiceSplitLineGroupsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "currency", Type: field.TypeString, SchemaType: map[string]string{"postgres": "varchar(3)"}}, + {Name: "service_period_start", Type: field.TypeTime}, + {Name: "service_period_end", Type: field.TypeTime}, + {Name: "unique_reference_id", Type: field.TypeString, Nullable: true}, + {Name: "ratecard_discounts", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "feature_key", Type: field.TypeString, Nullable: true}, + {Name: "price", Type: field.TypeString, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "subscription_billing_period_from", Type: field.TypeTime, Nullable: true}, + {Name: "subscription_billing_period_to", Type: field.TypeTime, Nullable: true}, + {Name: "charge_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "subscription_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "subscription_item_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "subscription_phase_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // BillingInvoiceSplitLineGroupsTable holds the schema information for the "billing_invoice_split_line_groups" table. + BillingInvoiceSplitLineGroupsTable = &schema.Table{ + Name: "billing_invoice_split_line_groups", + Columns: BillingInvoiceSplitLineGroupsColumns, + PrimaryKey: []*schema.Column{BillingInvoiceSplitLineGroupsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "billing_invoice_split_line_groups_charges_billing_split_line_groups", + Columns: []*schema.Column{BillingInvoiceSplitLineGroupsColumns[17]}, + RefColumns: []*schema.Column{ChargesColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "billing_invoice_split_line_groups_subscriptions_billing_split_line_groups", + Columns: []*schema.Column{BillingInvoiceSplitLineGroupsColumns[18]}, + RefColumns: []*schema.Column{SubscriptionsColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "billing_invoice_split_line_groups_subscription_items_billing_split_line_groups", + Columns: []*schema.Column{BillingInvoiceSplitLineGroupsColumns[19]}, + RefColumns: []*schema.Column{SubscriptionItemsColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "billing_invoice_split_line_groups_subscription_phases_billing_split_line_groups", + Columns: []*schema.Column{BillingInvoiceSplitLineGroupsColumns[20]}, + RefColumns: []*schema.Column{SubscriptionPhasesColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + Indexes: []*schema.Index{ + { + Name: "billinginvoicesplitlinegroup_id", + Unique: true, + Columns: []*schema.Column{BillingInvoiceSplitLineGroupsColumns[0]}, + }, + { + Name: "billinginvoicesplitlinegroup_namespace", + Unique: false, + Columns: []*schema.Column{BillingInvoiceSplitLineGroupsColumns[1]}, + }, + { + Name: "billinginvoicesplitlinegroup_namespace_id", + Unique: true, + Columns: []*schema.Column{BillingInvoiceSplitLineGroupsColumns[1], BillingInvoiceSplitLineGroupsColumns[0]}, + }, + { + Name: "billinginvoicesplitlinegroup_namespace_unique_reference_id", + Unique: true, + Columns: []*schema.Column{BillingInvoiceSplitLineGroupsColumns[1], BillingInvoiceSplitLineGroupsColumns[11]}, + Annotation: &entsql.IndexAnnotation{ + Where: "unique_reference_id IS NOT NULL AND deleted_at IS NULL", + }, + }, + }, + } + // BillingInvoiceUsageBasedLineConfigsColumns holds the columns for the "billing_invoice_usage_based_line_configs" table. + BillingInvoiceUsageBasedLineConfigsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "price_type", Type: field.TypeEnum, Enums: []string{"flat", "unit", "tiered", "dynamic", "package"}}, + {Name: "feature_key", Type: field.TypeString, Nullable: true}, + {Name: "price", Type: field.TypeString, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "pre_line_period_quantity", Type: field.TypeOther, Nullable: true, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "metered_pre_line_period_quantity", Type: field.TypeOther, Nullable: true, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "metered_quantity", Type: field.TypeOther, Nullable: true, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "unit_config", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + } + // BillingInvoiceUsageBasedLineConfigsTable holds the schema information for the "billing_invoice_usage_based_line_configs" table. + BillingInvoiceUsageBasedLineConfigsTable = &schema.Table{ + Name: "billing_invoice_usage_based_line_configs", + Columns: BillingInvoiceUsageBasedLineConfigsColumns, + PrimaryKey: []*schema.Column{BillingInvoiceUsageBasedLineConfigsColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "billinginvoiceusagebasedlineconfig_namespace", + Unique: false, + Columns: []*schema.Column{BillingInvoiceUsageBasedLineConfigsColumns[1]}, + }, + { + Name: "billinginvoiceusagebasedlineconfig_id", + Unique: true, + Columns: []*schema.Column{BillingInvoiceUsageBasedLineConfigsColumns[0]}, + }, + }, + } + // BillingInvoiceValidationIssuesColumns holds the columns for the "billing_invoice_validation_issues" table. + BillingInvoiceValidationIssuesColumns = []*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: "severity", Type: field.TypeEnum, Enums: []string{"critical", "warning"}}, + {Name: "code", Type: field.TypeString, Nullable: true}, + {Name: "message", Type: field.TypeString}, + {Name: "path", Type: field.TypeString, Nullable: true}, + {Name: "component", Type: field.TypeString}, + {Name: "dedupe_hash", Type: field.TypeBytes, Size: 32}, + {Name: "invoice_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // BillingInvoiceValidationIssuesTable holds the schema information for the "billing_invoice_validation_issues" table. + BillingInvoiceValidationIssuesTable = &schema.Table{ + Name: "billing_invoice_validation_issues", + Columns: BillingInvoiceValidationIssuesColumns, + PrimaryKey: []*schema.Column{BillingInvoiceValidationIssuesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "billing_invoice_validation_issues_billing_invoices_billing_invoice_validation_issues", + Columns: []*schema.Column{BillingInvoiceValidationIssuesColumns[11]}, + RefColumns: []*schema.Column{BillingInvoicesColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "billinginvoicevalidationissue_id", + Unique: true, + Columns: []*schema.Column{BillingInvoiceValidationIssuesColumns[0]}, + }, + { + Name: "billinginvoicevalidationissue_namespace", + Unique: false, + Columns: []*schema.Column{BillingInvoiceValidationIssuesColumns[1]}, + }, + { + Name: "billinginvoicevalidationissue_namespace_invoice_id_dedupe_hash", + Unique: true, + Columns: []*schema.Column{BillingInvoiceValidationIssuesColumns[1], BillingInvoiceValidationIssuesColumns[11], BillingInvoiceValidationIssuesColumns[10]}, + }, + }, + } + // BillingInvoiceWriteSchemaLevelsColumns holds the columns for the "billing_invoice_write_schema_levels" table. + BillingInvoiceWriteSchemaLevelsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString}, + {Name: "schema_level", Type: field.TypeInt}, + } + // BillingInvoiceWriteSchemaLevelsTable holds the schema information for the "billing_invoice_write_schema_levels" table. + BillingInvoiceWriteSchemaLevelsTable = &schema.Table{ + Name: "billing_invoice_write_schema_levels", + Columns: BillingInvoiceWriteSchemaLevelsColumns, + PrimaryKey: []*schema.Column{BillingInvoiceWriteSchemaLevelsColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "billinginvoicewriteschemalevel_id", + Unique: true, + Columns: []*schema.Column{BillingInvoiceWriteSchemaLevelsColumns[0]}, + }, + }, + } + // BillingProfilesColumns holds the columns for the "billing_profiles" table. + BillingProfilesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "supplier_address_country", Type: field.TypeString, Nullable: true, Size: 2}, + {Name: "supplier_address_postal_code", Type: field.TypeString, Nullable: true}, + {Name: "supplier_address_state", Type: field.TypeString, Nullable: true}, + {Name: "supplier_address_city", Type: field.TypeString, Nullable: true}, + {Name: "supplier_address_line1", Type: field.TypeString, Nullable: true}, + {Name: "supplier_address_line2", Type: field.TypeString, Nullable: true}, + {Name: "supplier_address_phone_number", Type: field.TypeString, Nullable: true}, + {Name: "default", Type: field.TypeBool, Default: false}, + {Name: "supplier_name", Type: field.TypeString}, + {Name: "supplier_tax_code", Type: field.TypeString, Nullable: true}, + {Name: "tax_app_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "invoicing_app_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "payment_app_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "workflow_config_id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // BillingProfilesTable holds the schema information for the "billing_profiles" table. + BillingProfilesTable = &schema.Table{ + Name: "billing_profiles", + Columns: BillingProfilesColumns, + PrimaryKey: []*schema.Column{BillingProfilesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "billing_profiles_apps_billing_profile_tax_app", + Columns: []*schema.Column{BillingProfilesColumns[18]}, + RefColumns: []*schema.Column{AppsColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "billing_profiles_apps_billing_profile_invoicing_app", + Columns: []*schema.Column{BillingProfilesColumns[19]}, + RefColumns: []*schema.Column{AppsColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "billing_profiles_apps_billing_profile_payment_app", + Columns: []*schema.Column{BillingProfilesColumns[20]}, + RefColumns: []*schema.Column{AppsColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "billing_profiles_billing_workflow_configs_billing_profile", + Columns: []*schema.Column{BillingProfilesColumns[21]}, + RefColumns: []*schema.Column{BillingWorkflowConfigsColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "billingprofile_id", + Unique: true, + Columns: []*schema.Column{BillingProfilesColumns[0]}, + }, + { + Name: "billingprofile_namespace", + Unique: false, + Columns: []*schema.Column{BillingProfilesColumns[1]}, + }, + { + Name: "billingprofile_namespace_id", + Unique: true, + Columns: []*schema.Column{BillingProfilesColumns[1], BillingProfilesColumns[0]}, + }, + { + Name: "billingprofile_namespace_default", + Unique: true, + Columns: []*schema.Column{BillingProfilesColumns[1], BillingProfilesColumns[15]}, + Annotation: &entsql.IndexAnnotation{ + Where: "\"default\" AND deleted_at IS NULL", + }, + }, + }, + } + // BillingSequenceNumbersColumns holds the columns for the "billing_sequence_numbers" table. + BillingSequenceNumbersColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "namespace", Type: field.TypeString}, + {Name: "scope", Type: field.TypeString}, + {Name: "last", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + } + // BillingSequenceNumbersTable holds the schema information for the "billing_sequence_numbers" table. + BillingSequenceNumbersTable = &schema.Table{ + Name: "billing_sequence_numbers", + Columns: BillingSequenceNumbersColumns, + PrimaryKey: []*schema.Column{BillingSequenceNumbersColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "billingsequencenumbers_namespace", + Unique: false, + Columns: []*schema.Column{BillingSequenceNumbersColumns[1]}, + }, + { + Name: "billingsequencenumbers_namespace_scope", + Unique: true, + Columns: []*schema.Column{BillingSequenceNumbersColumns[1], BillingSequenceNumbersColumns[2]}, + }, + }, + } + // BillingStandardInvoiceDetailedLinesColumns holds the columns for the "billing_standard_invoice_detailed_lines" table. + BillingStandardInvoiceDetailedLinesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "currency", Type: field.TypeString, SchemaType: map[string]string{"postgres": "varchar(3)"}}, + {Name: "service_period_start", Type: field.TypeTime}, + {Name: "service_period_end", Type: field.TypeTime}, + {Name: "quantity", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "invoicing_app_external_id", Type: field.TypeString, Nullable: true}, + {Name: "child_unique_reference_id", Type: field.TypeString}, + {Name: "per_unit_amount", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "category", Type: field.TypeEnum, Enums: []string{"regular", "commitment"}, Default: "regular"}, + {Name: "payment_term", Type: field.TypeEnum, Enums: []string{"in_advance", "in_arrears"}, Default: "in_advance"}, + {Name: "index", Type: field.TypeInt, Nullable: true}, + {Name: "credits_applied", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {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: "invoice_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "parent_line_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // BillingStandardInvoiceDetailedLinesTable holds the schema information for the "billing_standard_invoice_detailed_lines" table. + BillingStandardInvoiceDetailedLinesTable = &schema.Table{ + Name: "billing_standard_invoice_detailed_lines", + Columns: BillingStandardInvoiceDetailedLinesColumns, + PrimaryKey: []*schema.Column{BillingStandardInvoiceDetailedLinesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "billing_standard_invoice_detailed_lines_billing_invoices_billing_invoice_detailed_lines", + Columns: []*schema.Column{BillingStandardInvoiceDetailedLinesColumns[28]}, + RefColumns: []*schema.Column{BillingInvoicesColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "billing_standard_invoice_detailed_lines_billing_invoice_lines_detailed_lines_v2", + Columns: []*schema.Column{BillingStandardInvoiceDetailedLinesColumns[29]}, + RefColumns: []*schema.Column{BillingInvoiceLinesColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "billingstandardinvoicedetailedline_annotations", + Unique: false, + Columns: []*schema.Column{BillingStandardInvoiceDetailedLinesColumns[12]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "billingstandardinvoicedetailedline_id", + Unique: true, + Columns: []*schema.Column{BillingStandardInvoiceDetailedLinesColumns[0]}, + }, + { + Name: "billingstandardinvoicedetailedline_namespace", + Unique: false, + Columns: []*schema.Column{BillingStandardInvoiceDetailedLinesColumns[13]}, + }, + { + Name: "billingstandardinvoicedetailedline_namespace_id", + Unique: true, + Columns: []*schema.Column{BillingStandardInvoiceDetailedLinesColumns[13], BillingStandardInvoiceDetailedLinesColumns[0]}, + }, + { + Name: "billingstandardinvoicedetailedline_namespace_invoice_id", + Unique: false, + Columns: []*schema.Column{BillingStandardInvoiceDetailedLinesColumns[13], BillingStandardInvoiceDetailedLinesColumns[28]}, + }, + { + Name: "billingstandardinvoicedetailedline_namespace_parent_line_id", + Unique: false, + Columns: []*schema.Column{BillingStandardInvoiceDetailedLinesColumns[13], BillingStandardInvoiceDetailedLinesColumns[29]}, + }, + { + Name: "billingstdinvdetailedline_ns_parent_child_id", + Unique: true, + Columns: []*schema.Column{BillingStandardInvoiceDetailedLinesColumns[13], BillingStandardInvoiceDetailedLinesColumns[29], BillingStandardInvoiceDetailedLinesColumns[6]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + }, + } + // BillingStandardInvoiceDetailedLineAmountDiscountsColumns holds the columns for the "billing_standard_invoice_detailed_line_amount_discounts" table. + BillingStandardInvoiceDetailedLineAmountDiscountsColumns = []*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: "invoicing_app_external_id", Type: field.TypeString, Nullable: true}, + {Name: "child_unique_reference_id", Type: field.TypeString, Nullable: true}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "reason", Type: field.TypeEnum, Enums: []string{"maximum_spend", "ratecard_percentage", "ratecard_usage"}}, + {Name: "amount", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "rounding_amount", Type: field.TypeOther, Nullable: true, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "source_discount", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "line_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // BillingStandardInvoiceDetailedLineAmountDiscountsTable holds the schema information for the "billing_standard_invoice_detailed_line_amount_discounts" table. + BillingStandardInvoiceDetailedLineAmountDiscountsTable = &schema.Table{ + Name: "billing_standard_invoice_detailed_line_amount_discounts", + Columns: BillingStandardInvoiceDetailedLineAmountDiscountsColumns, + PrimaryKey: []*schema.Column{BillingStandardInvoiceDetailedLineAmountDiscountsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "billing_standard_invoice_detailed_line_amount_discounts_billing_standard_invoice_detailed_lines_amount_discounts", + Columns: []*schema.Column{BillingStandardInvoiceDetailedLineAmountDiscountsColumns[12]}, + RefColumns: []*schema.Column{BillingStandardInvoiceDetailedLinesColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "billingstandardinvoicedetailedlineamountdiscount_id", + Unique: true, + Columns: []*schema.Column{BillingStandardInvoiceDetailedLineAmountDiscountsColumns[0]}, + }, + { + Name: "billingstandardinvoicedetailedlineamountdiscount_namespace", + Unique: false, + Columns: []*schema.Column{BillingStandardInvoiceDetailedLineAmountDiscountsColumns[1]}, + }, + { + Name: "billingstandardinvoicedetailedlineamountdiscount_namespace_line_id", + Unique: false, + Columns: []*schema.Column{BillingStandardInvoiceDetailedLineAmountDiscountsColumns[1], BillingStandardInvoiceDetailedLineAmountDiscountsColumns[12]}, + }, + { + Name: "billingstdinvdetailedlineamntdiscount_ns_parent_child_id", + Unique: true, + Columns: []*schema.Column{BillingStandardInvoiceDetailedLineAmountDiscountsColumns[1], BillingStandardInvoiceDetailedLineAmountDiscountsColumns[12], BillingStandardInvoiceDetailedLineAmountDiscountsColumns[6]}, + Annotation: &entsql.IndexAnnotation{ + Where: "child_unique_reference_id IS NOT NULL AND deleted_at IS NULL", + }, + }, + }, + } + // BillingWorkflowConfigsColumns holds the columns for the "billing_workflow_configs" table. + BillingWorkflowConfigsColumns = []*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: "tax_behavior", Type: field.TypeEnum, Nullable: true, Enums: []string{"inclusive", "exclusive"}}, + {Name: "collection_alignment", Type: field.TypeEnum, Enums: []string{"subscription", "anchored"}}, + {Name: "anchored_alignment_detail", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "line_collection_period", Type: field.TypeString}, + {Name: "invoice_auto_advance", Type: field.TypeBool}, + {Name: "invoice_draft_period", Type: field.TypeString}, + {Name: "invoice_due_after", Type: field.TypeString}, + {Name: "invoice_collection_method", Type: field.TypeEnum, Enums: []string{"charge_automatically", "send_invoice"}}, + {Name: "invoice_progressive_billing", Type: field.TypeBool}, + {Name: "subscription_end_proration_mode", Type: field.TypeEnum, Enums: []string{"bill_full_period", "bill_actual_period"}, Default: "bill_actual_period"}, + {Name: "invoice_default_tax_settings", Type: field.TypeJSON, Nullable: true}, + {Name: "tax_enabled", Type: field.TypeBool, Default: true}, + {Name: "tax_enforced", Type: field.TypeBool, Default: false}, + {Name: "tax_code_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // BillingWorkflowConfigsTable holds the schema information for the "billing_workflow_configs" table. + BillingWorkflowConfigsTable = &schema.Table{ + Name: "billing_workflow_configs", + Columns: BillingWorkflowConfigsColumns, + PrimaryKey: []*schema.Column{BillingWorkflowConfigsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "billing_workflow_configs_tax_codes_billing_workflow_configs", + Columns: []*schema.Column{BillingWorkflowConfigsColumns[18]}, + RefColumns: []*schema.Column{TaxCodesColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + Indexes: []*schema.Index{ + { + Name: "billingworkflowconfig_id", + Unique: true, + Columns: []*schema.Column{BillingWorkflowConfigsColumns[0]}, + }, + { + Name: "billingworkflowconfig_namespace", + Unique: false, + Columns: []*schema.Column{BillingWorkflowConfigsColumns[1]}, + }, + { + Name: "billingworkflowconfig_tax_code_id", + Unique: false, + Columns: []*schema.Column{BillingWorkflowConfigsColumns[18]}, + }, + { + Name: "billingworkflowconfig_namespace_id", + Unique: false, + Columns: []*schema.Column{BillingWorkflowConfigsColumns[1], BillingWorkflowConfigsColumns[0]}, + }, + }, + } + // ChargesColumns holds the columns for the "charges" table. + ChargesColumns = []*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: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "unique_reference_id", Type: field.TypeString, Nullable: true}, + {Name: "type", Type: field.TypeString}, + {Name: "charge_credit_purchase_id", Type: field.TypeString, Unique: true, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "charge_flat_fee_id", Type: field.TypeString, Unique: true, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "charge_usage_based_id", Type: field.TypeString, Unique: true, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // ChargesTable holds the schema information for the "charges" table. + ChargesTable = &schema.Table{ + Name: "charges", + Columns: ChargesColumns, + PrimaryKey: []*schema.Column{ChargesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "charges_charge_credit_purchases_charge", + Columns: []*schema.Column{ChargesColumns[6]}, + RefColumns: []*schema.Column{ChargeCreditPurchasesColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "charges_charge_flat_fees_charge", + Columns: []*schema.Column{ChargesColumns[7]}, + RefColumns: []*schema.Column{ChargeFlatFeesColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "charges_charge_usage_based_charge", + Columns: []*schema.Column{ChargesColumns[8]}, + RefColumns: []*schema.Column{ChargeUsageBasedColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "charge_namespace", + Unique: false, + Columns: []*schema.Column{ChargesColumns[1]}, + }, + { + Name: "charge_id", + Unique: true, + Columns: []*schema.Column{ChargesColumns[0]}, + }, + { + Name: "charge_namespace_unique_reference_id", + Unique: true, + Columns: []*schema.Column{ChargesColumns[1], ChargesColumns[4]}, + Annotation: &entsql.IndexAnnotation{ + Where: "unique_reference_id IS NOT NULL AND deleted_at IS NULL", + }, + }, + }, + } + // ChargeCreditPurchasesColumns holds the columns for the "charge_credit_purchases" table. + ChargeCreditPurchasesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "service_period_from", Type: field.TypeTime}, + {Name: "service_period_to", Type: field.TypeTime}, + {Name: "billing_period_from", Type: field.TypeTime}, + {Name: "billing_period_to", Type: field.TypeTime}, + {Name: "full_service_period_from", Type: field.TypeTime}, + {Name: "full_service_period_to", Type: field.TypeTime}, + {Name: "status", Type: field.TypeEnum, Enums: []string{"created", "active", "final", "deleted"}}, + {Name: "unique_reference_id", Type: field.TypeString, Nullable: true}, + {Name: "currency", Type: field.TypeString, SchemaType: map[string]string{"postgres": "varchar(3)"}}, + {Name: "managed_by", Type: field.TypeEnum, Enums: []string{"subscription", "system", "manual"}}, + {Name: "advance_after", Type: field.TypeTime, Nullable: true}, + {Name: "tax_behavior", Type: field.TypeEnum, Nullable: true, Enums: []string{"inclusive", "exclusive"}}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "credit_amount", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "effective_at", Type: field.TypeTime, Nullable: true}, + {Name: "expires_at", Type: field.TypeTime, Nullable: true}, + {Name: "priority", Type: field.TypeInt, Nullable: true}, + {Name: "feature_filters", Type: field.TypeOther, Nullable: true, SchemaType: map[string]string{"postgres": "text[]"}}, + {Name: "settlement", Type: field.TypeString, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "status_detailed", Type: field.TypeEnum, Enums: []string{"created", "active", "active.initial_credit_grant", "active.payment.pending", "active.payment.authorized", "active.payment.paid_and_authorized", "active.payment.settled", "final", "deleted"}}, + {Name: "key", Type: field.TypeString, Nullable: true}, + {Name: "voided_at", Type: field.TypeTime, Nullable: true}, + {Name: "customer_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "subscription_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "subscription_item_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "subscription_phase_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "tax_code_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // ChargeCreditPurchasesTable holds the schema information for the "charge_credit_purchases" table. + ChargeCreditPurchasesTable = &schema.Table{ + Name: "charge_credit_purchases", + Columns: ChargeCreditPurchasesColumns, + PrimaryKey: []*schema.Column{ChargeCreditPurchasesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "charge_credit_purchases_customers_charges_credit_purchase", + Columns: []*schema.Column{ChargeCreditPurchasesColumns[30]}, + RefColumns: []*schema.Column{CustomersColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "charge_credit_purchases_subscriptions_charges_credit_purchase", + Columns: []*schema.Column{ChargeCreditPurchasesColumns[31]}, + RefColumns: []*schema.Column{SubscriptionsColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "charge_credit_purchases_subscription_items_charges_credit_purchase", + Columns: []*schema.Column{ChargeCreditPurchasesColumns[32]}, + RefColumns: []*schema.Column{SubscriptionItemsColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "charge_credit_purchases_subscription_phases_charges_credit_purchase", + Columns: []*schema.Column{ChargeCreditPurchasesColumns[33]}, + RefColumns: []*schema.Column{SubscriptionPhasesColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "charge_credit_purchases_tax_codes_charge_credit_purchases", + Columns: []*schema.Column{ChargeCreditPurchasesColumns[34]}, + RefColumns: []*schema.Column{TaxCodesColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargecreditpurchase_namespace_customer_id_unique_reference_id", + Unique: true, + Columns: []*schema.Column{ChargeCreditPurchasesColumns[14], ChargeCreditPurchasesColumns[30], ChargeCreditPurchasesColumns[8]}, + Annotation: &entsql.IndexAnnotation{ + Where: "unique_reference_id IS NOT NULL AND deleted_at IS NULL", + }, + }, + { + Name: "chargecreditpurchase_annotations", + Unique: false, + Columns: []*schema.Column{ChargeCreditPurchasesColumns[13]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "chargecreditpurchase_id", + Unique: true, + Columns: []*schema.Column{ChargeCreditPurchasesColumns[0]}, + }, + { + Name: "chargecreditpurchase_namespace", + Unique: false, + Columns: []*schema.Column{ChargeCreditPurchasesColumns[14]}, + }, + { + Name: "chargecreditpurchase_namespace_id", + Unique: true, + Columns: []*schema.Column{ChargeCreditPurchasesColumns[14], ChargeCreditPurchasesColumns[0]}, + }, + { + Name: "chargecreditpurchases_tax_code_id", + Unique: false, + Columns: []*schema.Column{ChargeCreditPurchasesColumns[34]}, + }, + { + Name: "chargecreditpurchase_namespace_key", + Unique: true, + Columns: []*schema.Column{ChargeCreditPurchasesColumns[14], ChargeCreditPurchasesColumns[28]}, + Annotation: &entsql.IndexAnnotation{ + Where: "key IS NOT NULL AND deleted_at IS NULL", + }, + }, + }, + } + // ChargeCreditPurchaseCreditGrantsColumns holds the columns for the "charge_credit_purchase_credit_grants" table. + ChargeCreditPurchaseCreditGrantsColumns = []*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: "transaction_group_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "granted_at", Type: field.TypeTime}, + {Name: "charge_id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // ChargeCreditPurchaseCreditGrantsTable holds the schema information for the "charge_credit_purchase_credit_grants" table. + ChargeCreditPurchaseCreditGrantsTable = &schema.Table{ + Name: "charge_credit_purchase_credit_grants", + Columns: ChargeCreditPurchaseCreditGrantsColumns, + PrimaryKey: []*schema.Column{ChargeCreditPurchaseCreditGrantsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "charge_credit_purchase_credit_grants_charge_credit_purchases_credit_grant", + Columns: []*schema.Column{ChargeCreditPurchaseCreditGrantsColumns[7]}, + RefColumns: []*schema.Column{ChargeCreditPurchasesColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargecreditpurchasecreditgrant_namespace", + Unique: false, + Columns: []*schema.Column{ChargeCreditPurchaseCreditGrantsColumns[1]}, + }, + { + Name: "chargecreditpurchasecreditgrant_id", + Unique: true, + Columns: []*schema.Column{ChargeCreditPurchaseCreditGrantsColumns[0]}, + }, + { + Name: "chargecreditpurchasecreditgrant_namespace_charge_id", + Unique: true, + Columns: []*schema.Column{ChargeCreditPurchaseCreditGrantsColumns[1], ChargeCreditPurchaseCreditGrantsColumns[7]}, + }, + }, + } + // ChargeCreditPurchaseExternalPaymentsColumns holds the columns for the "charge_credit_purchase_external_payments" table. + ChargeCreditPurchaseExternalPaymentsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, 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: "charge_id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // ChargeCreditPurchaseExternalPaymentsTable holds the schema information for the "charge_credit_purchase_external_payments" table. + ChargeCreditPurchaseExternalPaymentsTable = &schema.Table{ + Name: "charge_credit_purchase_external_payments", + Columns: ChargeCreditPurchaseExternalPaymentsColumns, + PrimaryKey: []*schema.Column{ChargeCreditPurchaseExternalPaymentsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "charge_credit_purchase_external_payments_charge_credit_purchases_external_payment", + Columns: []*schema.Column{ChargeCreditPurchaseExternalPaymentsColumns[14]}, + RefColumns: []*schema.Column{ChargeCreditPurchasesColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargecreditpurchaseexternalpayment_namespace", + Unique: false, + Columns: []*schema.Column{ChargeCreditPurchaseExternalPaymentsColumns[9]}, + }, + { + Name: "chargecreditpurchaseexternalpayment_id", + Unique: true, + Columns: []*schema.Column{ChargeCreditPurchaseExternalPaymentsColumns[0]}, + }, + { + Name: "chargecreditpurchaseexternalpayment_annotations", + Unique: false, + Columns: []*schema.Column{ChargeCreditPurchaseExternalPaymentsColumns[13]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + }, + } + // ChargeCreditPurchaseInvoicedPaymentsColumns holds the columns for the "charge_credit_purchase_invoiced_payments" table. + ChargeCreditPurchaseInvoicedPaymentsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "invoice_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: "line_id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "charge_id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // ChargeCreditPurchaseInvoicedPaymentsTable holds the schema information for the "charge_credit_purchase_invoiced_payments" table. + ChargeCreditPurchaseInvoicedPaymentsTable = &schema.Table{ + Name: "charge_credit_purchase_invoiced_payments", + Columns: ChargeCreditPurchaseInvoicedPaymentsColumns, + PrimaryKey: []*schema.Column{ChargeCreditPurchaseInvoicedPaymentsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "charge_credit_purchase_invoiced_payments_billing_invoice_lines_charge_credit_purchase_invoiced_payment", + Columns: []*schema.Column{ChargeCreditPurchaseInvoicedPaymentsColumns[15]}, + RefColumns: []*schema.Column{BillingInvoiceLinesColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "charge_credit_purchase_invoiced_payments_charge_credit_purchases_invoiced_payment", + Columns: []*schema.Column{ChargeCreditPurchaseInvoicedPaymentsColumns[16]}, + RefColumns: []*schema.Column{ChargeCreditPurchasesColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargecreditpurchaseinvoicedpayment_namespace", + Unique: false, + Columns: []*schema.Column{ChargeCreditPurchaseInvoicedPaymentsColumns[10]}, + }, + { + Name: "chargecreditpurchaseinvoicedpayment_id", + Unique: true, + Columns: []*schema.Column{ChargeCreditPurchaseInvoicedPaymentsColumns[0]}, + }, + { + Name: "chargecreditpurchaseinvoicedpayment_annotations", + Unique: false, + Columns: []*schema.Column{ChargeCreditPurchaseInvoicedPaymentsColumns[14]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "chargecreditpurchaseinvoicedpayment_namespace_charge_id", + Unique: true, + Columns: []*schema.Column{ChargeCreditPurchaseInvoicedPaymentsColumns[10], ChargeCreditPurchaseInvoicedPaymentsColumns[16]}, + }, + }, + } + // ChargeFlatFeesColumns holds the columns for the "charge_flat_fees" table. + ChargeFlatFeesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "service_period_from", Type: field.TypeTime}, + {Name: "service_period_to", Type: field.TypeTime}, + {Name: "billing_period_from", Type: field.TypeTime}, + {Name: "billing_period_to", Type: field.TypeTime}, + {Name: "full_service_period_from", Type: field.TypeTime}, + {Name: "full_service_period_to", Type: field.TypeTime}, + {Name: "status", Type: field.TypeEnum, Enums: []string{"created", "active", "final", "deleted"}}, + {Name: "unique_reference_id", Type: field.TypeString, Nullable: true}, + {Name: "currency", Type: field.TypeString, SchemaType: map[string]string{"postgres": "varchar(3)"}}, + {Name: "managed_by", Type: field.TypeEnum, Enums: []string{"subscription", "system", "manual"}}, + {Name: "advance_after", Type: field.TypeTime, Nullable: true}, + {Name: "tax_behavior", Type: field.TypeEnum, Nullable: true, Enums: []string{"inclusive", "exclusive"}}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "payment_term", Type: field.TypeString}, + {Name: "invoice_at", Type: field.TypeTime}, + {Name: "settlement_mode", Type: field.TypeEnum, Enums: []string{"credit_then_invoice", "credit_only"}}, + {Name: "intent_deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "discounts", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "pro_rating", Type: field.TypeEnum, Enums: []string{"prorate_prices", "no_prorate"}}, + {Name: "feature_key", Type: field.TypeString, Nullable: true}, + {Name: "amount_before_proration", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "amount_after_proration", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "status_detailed", Type: field.TypeEnum, Enums: []string{"created", "active", "active.realization.started", "active.realization.waiting_for_collection", "active.realization.processing", "active.realization.issuing", "active.realization.completed", "active.awaiting_payment_settlement", "final", "deleted"}}, + {Name: "current_realization_run_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "customer_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "feature_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "subscription_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "subscription_item_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "subscription_phase_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "tax_code_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // ChargeFlatFeesTable holds the schema information for the "charge_flat_fees" table. + ChargeFlatFeesTable = &schema.Table{ + Name: "charge_flat_fees", + Columns: ChargeFlatFeesColumns, + PrimaryKey: []*schema.Column{ChargeFlatFeesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "charge_flat_fees_charge_flat_fee_runs_current_run", + Columns: []*schema.Column{ChargeFlatFeesColumns[31]}, + RefColumns: []*schema.Column{ChargeFlatFeeRunsColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "charge_flat_fees_customers_charges_flat_fee", + Columns: []*schema.Column{ChargeFlatFeesColumns[32]}, + RefColumns: []*schema.Column{CustomersColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "charge_flat_fees_features_flat_fee_charges", + Columns: []*schema.Column{ChargeFlatFeesColumns[33]}, + RefColumns: []*schema.Column{FeaturesColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "charge_flat_fees_subscriptions_charges_flat_fee", + Columns: []*schema.Column{ChargeFlatFeesColumns[34]}, + RefColumns: []*schema.Column{SubscriptionsColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "charge_flat_fees_subscription_items_charges_flat_fee", + Columns: []*schema.Column{ChargeFlatFeesColumns[35]}, + RefColumns: []*schema.Column{SubscriptionItemsColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "charge_flat_fees_subscription_phases_charges_flat_fee", + Columns: []*schema.Column{ChargeFlatFeesColumns[36]}, + RefColumns: []*schema.Column{SubscriptionPhasesColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "charge_flat_fees_tax_codes_charge_flat_fees", + Columns: []*schema.Column{ChargeFlatFeesColumns[37]}, + RefColumns: []*schema.Column{TaxCodesColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargeflatfee_namespace_customer_id_unique_reference_id", + Unique: true, + Columns: []*schema.Column{ChargeFlatFeesColumns[14], ChargeFlatFeesColumns[32], ChargeFlatFeesColumns[8]}, + Annotation: &entsql.IndexAnnotation{ + Where: "unique_reference_id IS NOT NULL AND deleted_at IS NULL", + }, + }, + { + Name: "chargeflatfee_annotations", + Unique: false, + Columns: []*schema.Column{ChargeFlatFeesColumns[13]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "chargeflatfee_id", + Unique: true, + Columns: []*schema.Column{ChargeFlatFeesColumns[0]}, + }, + { + Name: "chargeflatfee_namespace", + Unique: false, + Columns: []*schema.Column{ChargeFlatFeesColumns[14]}, + }, + { + Name: "chargeflatfee_namespace_id", + Unique: true, + Columns: []*schema.Column{ChargeFlatFeesColumns[14], ChargeFlatFeesColumns[0]}, + }, + { + Name: "chargeflatfees_tax_code_id", + Unique: false, + Columns: []*schema.Column{ChargeFlatFeesColumns[37]}, + }, + }, + } + // ChargeFlatFeeOverridesColumns holds the columns for the "charge_flat_fee_overrides" table. + ChargeFlatFeeOverridesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "metadata", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "tax_behavior", Type: field.TypeString, Nullable: true}, + {Name: "intent_deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "service_period_from", Type: field.TypeTime}, + {Name: "service_period_to", Type: field.TypeTime}, + {Name: "full_service_period_from", Type: field.TypeTime}, + {Name: "full_service_period_to", Type: field.TypeTime}, + {Name: "billing_period_from", Type: field.TypeTime}, + {Name: "billing_period_to", Type: field.TypeTime}, + {Name: "invoice_at", Type: field.TypeTime}, + {Name: "feature_key", Type: field.TypeString, Nullable: true}, + {Name: "payment_term", Type: field.TypeString}, + {Name: "pro_rating", Type: field.TypeString, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "amount_before_proration", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "discounts", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "percentage_discounts", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "charge_id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "tax_code_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // ChargeFlatFeeOverridesTable holds the schema information for the "charge_flat_fee_overrides" table. + ChargeFlatFeeOverridesTable = &schema.Table{ + Name: "charge_flat_fee_overrides", + Columns: ChargeFlatFeeOverridesColumns, + PrimaryKey: []*schema.Column{ChargeFlatFeeOverridesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "charge_flat_fee_overrides_charge_flat_fees_intent_override", + Columns: []*schema.Column{ChargeFlatFeeOverridesColumns[20]}, + RefColumns: []*schema.Column{ChargeFlatFeesColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "charge_flat_fee_overrides_tax_codes_charge_flat_fee_overrides", + Columns: []*schema.Column{ChargeFlatFeeOverridesColumns[21]}, + RefColumns: []*schema.Column{TaxCodesColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargeflatfeeoverride_namespace", + Unique: false, + Columns: []*schema.Column{ChargeFlatFeeOverridesColumns[1]}, + }, + { + Name: "chargeflatfeeoverride_id", + Unique: true, + Columns: []*schema.Column{ChargeFlatFeeOverridesColumns[0]}, + }, + { + Name: "chargeflatfeeoverrides_tax_code_id", + Unique: false, + Columns: []*schema.Column{ChargeFlatFeeOverridesColumns[21]}, + }, + { + Name: "chargeflatfeeoverride_namespace_charge_id", + Unique: true, + Columns: []*schema.Column{ChargeFlatFeeOverridesColumns[1], ChargeFlatFeeOverridesColumns[20]}, + }, + }, + } + // ChargeFlatFeeRunsColumns holds the columns for the "charge_flat_fee_runs" table. + ChargeFlatFeeRunsColumns = []*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: "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: "type", Type: field.TypeEnum, Enums: []string{"final_realization", "invalid_due_to_unsupported_credit_note"}}, + {Name: "initial_type", Type: field.TypeEnum, Enums: []string{"final_realization", "invalid_due_to_unsupported_credit_note"}}, + {Name: "service_period_from", Type: field.TypeTime}, + {Name: "service_period_to", Type: field.TypeTime}, + {Name: "amount_after_proration", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "no_fiat_transaction_required", Type: field.TypeBool}, + {Name: "immutable", Type: field.TypeBool}, + {Name: "invoice_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "line_id", Type: field.TypeString, Unique: true, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "charge_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // ChargeFlatFeeRunsTable holds the schema information for the "charge_flat_fee_runs" table. + ChargeFlatFeeRunsTable = &schema.Table{ + Name: "charge_flat_fee_runs", + Columns: ChargeFlatFeeRunsColumns, + PrimaryKey: []*schema.Column{ChargeFlatFeeRunsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "charge_flat_fee_runs_billing_invoices_charge_flat_fee_runs", + Columns: []*schema.Column{ChargeFlatFeeRunsColumns[20]}, + RefColumns: []*schema.Column{BillingInvoicesColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "charge_flat_fee_runs_billing_invoice_lines_charge_flat_fee_runs", + Columns: []*schema.Column{ChargeFlatFeeRunsColumns[21]}, + RefColumns: []*schema.Column{BillingInvoiceLinesColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "charge_flat_fee_runs_charge_flat_fees_runs", + Columns: []*schema.Column{ChargeFlatFeeRunsColumns[22]}, + RefColumns: []*schema.Column{ChargeFlatFeesColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargeflatfeerun_namespace", + Unique: false, + Columns: []*schema.Column{ChargeFlatFeeRunsColumns[1]}, + }, + { + Name: "chargeflatfeerun_id", + Unique: true, + Columns: []*schema.Column{ChargeFlatFeeRunsColumns[0]}, + }, + { + Name: "chargeflatfeerun_namespace_charge_id", + Unique: false, + Columns: []*schema.Column{ChargeFlatFeeRunsColumns[1], ChargeFlatFeeRunsColumns[22]}, + }, + }, + } + // ChargeFlatFeeRunCreditAllocationsColumns holds the columns for the "charge_flat_fee_run_credit_allocations" table. + ChargeFlatFeeRunCreditAllocationsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: 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: "sort_hint", Type: field.TypeInt}, + {Name: "type", Type: field.TypeEnum, Enums: []string{"allocation", "correction"}}, + {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: "line_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "run_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "corrects_realization_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // ChargeFlatFeeRunCreditAllocationsTable holds the schema information for the "charge_flat_fee_run_credit_allocations" table. + ChargeFlatFeeRunCreditAllocationsTable = &schema.Table{ + Name: "charge_flat_fee_run_credit_allocations", + Columns: ChargeFlatFeeRunCreditAllocationsColumns, + PrimaryKey: []*schema.Column{ChargeFlatFeeRunCreditAllocationsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "charge_flat_fee_run_credit_allocations_billing_invoice_lines_charge_flat_fee_run_credit_allocations", + Columns: []*schema.Column{ChargeFlatFeeRunCreditAllocationsColumns[12]}, + RefColumns: []*schema.Column{BillingInvoiceLinesColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "charge_ff_credit_alloc_run", + Columns: []*schema.Column{ChargeFlatFeeRunCreditAllocationsColumns[13]}, + RefColumns: []*schema.Column{ChargeFlatFeeRunsColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "charge_flat_fee_run_credit_allocations_charge_flat_fee_run_credit_allocations_allocation", + Columns: []*schema.Column{ChargeFlatFeeRunCreditAllocationsColumns[14]}, + RefColumns: []*schema.Column{ChargeFlatFeeRunCreditAllocationsColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargeflatfeeruncreditallocations_namespace", + Unique: false, + Columns: []*schema.Column{ChargeFlatFeeRunCreditAllocationsColumns[7]}, + }, + { + Name: "chargeflatfeeruncreditallocations_id", + Unique: true, + Columns: []*schema.Column{ChargeFlatFeeRunCreditAllocationsColumns[0]}, + }, + { + Name: "chargeflatfeeruncreditallocations_annotations", + Unique: false, + Columns: []*schema.Column{ChargeFlatFeeRunCreditAllocationsColumns[11]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + }, + } + // ChargeFlatFeeRunDetailedLinesColumns holds the columns for the "charge_flat_fee_run_detailed_lines" table. + ChargeFlatFeeRunDetailedLinesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "currency", Type: field.TypeString, SchemaType: map[string]string{"postgres": "varchar(3)"}}, + {Name: "service_period_start", Type: field.TypeTime}, + {Name: "service_period_end", Type: field.TypeTime}, + {Name: "quantity", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "invoicing_app_external_id", Type: field.TypeString, Nullable: true}, + {Name: "child_unique_reference_id", Type: field.TypeString}, + {Name: "per_unit_amount", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "category", Type: field.TypeEnum, Enums: []string{"regular", "commitment"}, Default: "regular"}, + {Name: "payment_term", Type: field.TypeEnum, Enums: []string{"in_advance", "in_arrears"}, Default: "in_advance"}, + {Name: "index", Type: field.TypeInt, Nullable: true}, + {Name: "credits_applied", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {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: "pricer_reference_id", Type: field.TypeString}, + {Name: "run_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // ChargeFlatFeeRunDetailedLinesTable holds the schema information for the "charge_flat_fee_run_detailed_lines" table. + ChargeFlatFeeRunDetailedLinesTable = &schema.Table{ + Name: "charge_flat_fee_run_detailed_lines", + Columns: ChargeFlatFeeRunDetailedLinesColumns, + PrimaryKey: []*schema.Column{ChargeFlatFeeRunDetailedLinesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "charge_flat_fee_run_detailed_lines_charge_flat_fee_runs_detailed_lines", + Columns: []*schema.Column{ChargeFlatFeeRunDetailedLinesColumns[29]}, + RefColumns: []*schema.Column{ChargeFlatFeeRunsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargeflatfeerundetailedline_annotations", + Unique: false, + Columns: []*schema.Column{ChargeFlatFeeRunDetailedLinesColumns[12]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "chargeflatfeerundetailedline_id", + Unique: true, + Columns: []*schema.Column{ChargeFlatFeeRunDetailedLinesColumns[0]}, + }, + { + Name: "chargeflatfeerundetailedline_namespace", + Unique: false, + Columns: []*schema.Column{ChargeFlatFeeRunDetailedLinesColumns[13]}, + }, + { + Name: "chargeflatfeerundetailedline_namespace_id", + Unique: true, + Columns: []*schema.Column{ChargeFlatFeeRunDetailedLinesColumns[13], ChargeFlatFeeRunDetailedLinesColumns[0]}, + }, + { + Name: "chargeflatfeerundetailedline_namespace_run_id", + Unique: false, + Columns: []*schema.Column{ChargeFlatFeeRunDetailedLinesColumns[13], ChargeFlatFeeRunDetailedLinesColumns[29]}, + }, + { + Name: "chargeffdetailedline_ns_run_child_id", + Unique: true, + Columns: []*schema.Column{ChargeFlatFeeRunDetailedLinesColumns[13], ChargeFlatFeeRunDetailedLinesColumns[29], ChargeFlatFeeRunDetailedLinesColumns[6]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + }, + } + // ChargeFlatFeeRunInvoicedUsagesColumns holds the columns for the "charge_flat_fee_run_invoiced_usages" table. + ChargeFlatFeeRunInvoicedUsagesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "service_period_from", Type: field.TypeTime}, + {Name: "service_period_to", Type: field.TypeTime}, + {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)"}}, + } + // ChargeFlatFeeRunInvoicedUsagesTable holds the schema information for the "charge_flat_fee_run_invoiced_usages" table. + ChargeFlatFeeRunInvoicedUsagesTable = &schema.Table{ + Name: "charge_flat_fee_run_invoiced_usages", + Columns: ChargeFlatFeeRunInvoicedUsagesColumns, + PrimaryKey: []*schema.Column{ChargeFlatFeeRunInvoicedUsagesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "charge_flat_fee_run_invoiced_usages_charge_flat_fee_runs_invoiced_usage", + Columns: []*schema.Column{ChargeFlatFeeRunInvoicedUsagesColumns[17]}, + RefColumns: []*schema.Column{ChargeFlatFeeRunsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargeflatfeeruninvoicedusage_namespace", + Unique: false, + Columns: []*schema.Column{ChargeFlatFeeRunInvoicedUsagesColumns[4]}, + }, + { + Name: "chargeflatfeeruninvoicedusage_id", + Unique: true, + Columns: []*schema.Column{ChargeFlatFeeRunInvoicedUsagesColumns[0]}, + }, + { + Name: "chargeflatfeeruninvoicedusage_annotations", + Unique: false, + Columns: []*schema.Column{ChargeFlatFeeRunInvoicedUsagesColumns[8]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "chargeflatfeeruninvoicedusage_namespace_run_id", + Unique: true, + Columns: []*schema.Column{ChargeFlatFeeRunInvoicedUsagesColumns[4], ChargeFlatFeeRunInvoicedUsagesColumns[17]}, + }, + }, + } + // ChargeFlatFeeRunPaymentsColumns holds the columns for the "charge_flat_fee_run_payments" table. + ChargeFlatFeeRunPaymentsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "invoice_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: "line_id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "run_id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // ChargeFlatFeeRunPaymentsTable holds the schema information for the "charge_flat_fee_run_payments" table. + ChargeFlatFeeRunPaymentsTable = &schema.Table{ + Name: "charge_flat_fee_run_payments", + Columns: ChargeFlatFeeRunPaymentsColumns, + PrimaryKey: []*schema.Column{ChargeFlatFeeRunPaymentsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "charge_flat_fee_run_payments_billing_invoice_lines_charge_flat_fee_run_payment", + Columns: []*schema.Column{ChargeFlatFeeRunPaymentsColumns[15]}, + RefColumns: []*schema.Column{BillingInvoiceLinesColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "charge_flat_fee_run_payments_charge_flat_fee_runs_payment", + Columns: []*schema.Column{ChargeFlatFeeRunPaymentsColumns[16]}, + RefColumns: []*schema.Column{ChargeFlatFeeRunsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargeflatfeerunpayment_namespace", + Unique: false, + Columns: []*schema.Column{ChargeFlatFeeRunPaymentsColumns[10]}, + }, + { + Name: "chargeflatfeerunpayment_id", + Unique: true, + Columns: []*schema.Column{ChargeFlatFeeRunPaymentsColumns[0]}, + }, + { + Name: "chargeflatfeerunpayment_annotations", + Unique: false, + Columns: []*schema.Column{ChargeFlatFeeRunPaymentsColumns[14]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + }, + } + // 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: "service_period_from", Type: field.TypeTime}, + {Name: "service_period_to", Type: field.TypeTime}, + {Name: "billing_period_from", Type: field.TypeTime}, + {Name: "billing_period_to", Type: field.TypeTime}, + {Name: "full_service_period_from", Type: field.TypeTime}, + {Name: "full_service_period_to", Type: field.TypeTime}, + {Name: "status", Type: field.TypeEnum, Enums: []string{"created", "active", "final", "deleted"}}, + {Name: "unique_reference_id", Type: field.TypeString, Nullable: true}, + {Name: "currency", Type: field.TypeString, SchemaType: map[string]string{"postgres": "varchar(3)"}}, + {Name: "managed_by", Type: field.TypeEnum, Enums: []string{"subscription", "system", "manual"}}, + {Name: "advance_after", Type: field.TypeTime, Nullable: true}, + {Name: "tax_behavior", Type: field.TypeEnum, Nullable: true, Enums: []string{"inclusive", "exclusive"}}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "invoice_at", Type: field.TypeTime}, + {Name: "settlement_mode", Type: field.TypeEnum, Enums: []string{"credit_then_invoice", "credit_only"}}, + {Name: "intent_deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "discounts", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "feature_key", Type: field.TypeString}, + {Name: "rating_engine", Type: field.TypeEnum, Enums: []string{"delta", "period_preserving"}}, + {Name: "price", Type: field.TypeString, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "unit_config", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "status_detailed", Type: field.TypeEnum, Enums: []string{"created", "active", "active.realization.started", "active.realization.waiting_for_collection", "active.realization.processing", "active.realization.issuing", "active.realization.completed", "active.awaiting_payment_settlement", "final", "deleted"}}, + {Name: "current_realization_run_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "customer_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "feature_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "subscription_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "subscription_item_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "subscription_phase_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "tax_code_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // 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_charge_usage_based_runs_current_run", + Columns: []*schema.Column{ChargeUsageBasedColumns[30]}, + RefColumns: []*schema.Column{ChargeUsageBasedRunsColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "charge_usage_based_customers_charges_usage_based", + Columns: []*schema.Column{ChargeUsageBasedColumns[31]}, + RefColumns: []*schema.Column{CustomersColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "charge_usage_based_features_usage_based_charges", + Columns: []*schema.Column{ChargeUsageBasedColumns[32]}, + RefColumns: []*schema.Column{FeaturesColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "charge_usage_based_subscriptions_charges_usage_based", + Columns: []*schema.Column{ChargeUsageBasedColumns[33]}, + RefColumns: []*schema.Column{SubscriptionsColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "charge_usage_based_subscription_items_charges_usage_based", + Columns: []*schema.Column{ChargeUsageBasedColumns[34]}, + RefColumns: []*schema.Column{SubscriptionItemsColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "charge_usage_based_subscription_phases_charges_usage_based", + Columns: []*schema.Column{ChargeUsageBasedColumns[35]}, + RefColumns: []*schema.Column{SubscriptionPhasesColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "charge_usage_based_tax_codes_charge_usage_based", + Columns: []*schema.Column{ChargeUsageBasedColumns[36]}, + RefColumns: []*schema.Column{TaxCodesColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargeusagebased_namespace_customer_id_unique_reference_id", + Unique: true, + Columns: []*schema.Column{ChargeUsageBasedColumns[14], ChargeUsageBasedColumns[31], ChargeUsageBasedColumns[8]}, + Annotation: &entsql.IndexAnnotation{ + Where: "unique_reference_id IS NOT NULL AND deleted_at IS NULL", + }, + }, + { + Name: "chargeusagebased_annotations", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedColumns[13]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "chargeusagebased_id", + Unique: true, + Columns: []*schema.Column{ChargeUsageBasedColumns[0]}, + }, + { + Name: "chargeusagebased_namespace", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedColumns[14]}, + }, + { + Name: "chargeusagebased_namespace_id", + Unique: true, + Columns: []*schema.Column{ChargeUsageBasedColumns[14], ChargeUsageBasedColumns[0]}, + }, + { + Name: "chargeusagebased_tax_code_id", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedColumns[36]}, + }, + }, + } + // ChargeUsageBasedOverridesColumns holds the columns for the "charge_usage_based_overrides" table. + ChargeUsageBasedOverridesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "metadata", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "tax_behavior", Type: field.TypeString, Nullable: true}, + {Name: "intent_deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "service_period_from", Type: field.TypeTime}, + {Name: "service_period_to", Type: field.TypeTime}, + {Name: "full_service_period_from", Type: field.TypeTime}, + {Name: "full_service_period_to", Type: field.TypeTime}, + {Name: "billing_period_from", Type: field.TypeTime}, + {Name: "billing_period_to", Type: field.TypeTime}, + {Name: "invoice_at", Type: field.TypeTime}, + {Name: "feature_key", Type: field.TypeString, Nullable: true}, + {Name: "price", Type: field.TypeString, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "discounts", Type: field.TypeString, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "unit_config", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "charge_id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "tax_code_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // ChargeUsageBasedOverridesTable holds the schema information for the "charge_usage_based_overrides" table. + ChargeUsageBasedOverridesTable = &schema.Table{ + Name: "charge_usage_based_overrides", + Columns: ChargeUsageBasedOverridesColumns, + PrimaryKey: []*schema.Column{ChargeUsageBasedOverridesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "charge_usage_based_overrides_charge_usage_based_intent_override", + Columns: []*schema.Column{ChargeUsageBasedOverridesColumns[18]}, + RefColumns: []*schema.Column{ChargeUsageBasedColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "charge_usage_based_overrides_tax_codes_charge_usage_based_overrides", + Columns: []*schema.Column{ChargeUsageBasedOverridesColumns[19]}, + RefColumns: []*schema.Column{TaxCodesColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargeusagebasedoverride_namespace", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedOverridesColumns[1]}, + }, + { + Name: "chargeusagebasedoverride_id", + Unique: true, + Columns: []*schema.Column{ChargeUsageBasedOverridesColumns[0]}, + }, + { + Name: "chargeusagebasedoverrides_tax_code_id", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedOverridesColumns[19]}, + }, + { + Name: "chargeusagebasedoverride_namespace_charge_id", + Unique: true, + Columns: []*schema.Column{ChargeUsageBasedOverridesColumns[1], ChargeUsageBasedOverridesColumns[18]}, + }, + }, + } + // 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: "sort_hint", Type: field.TypeInt}, + {Name: "type", Type: field.TypeEnum, Enums: []string{"allocation", "correction"}}, + {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: "corrects_realization_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {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_run_credit_allocations_allocation", + Columns: []*schema.Column{ChargeUsageBasedRunCreditAllocationsColumns[13]}, + RefColumns: []*schema.Column{ChargeUsageBasedRunCreditAllocationsColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "charge_ub_run_credit_alloc_run", + Columns: []*schema.Column{ChargeUsageBasedRunCreditAllocationsColumns[14]}, + RefColumns: []*schema.Column{ChargeUsageBasedRunsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargeusagebasedruncreditallocations_namespace", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedRunCreditAllocationsColumns[8]}, + }, + { + Name: "chargeusagebasedruncreditallocations_id", + Unique: true, + Columns: []*schema.Column{ChargeUsageBasedRunCreditAllocationsColumns[0]}, + }, + { + Name: "chargeusagebasedruncreditallocations_annotations", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedRunCreditAllocationsColumns[12]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + }, + } + // ChargeUsageBasedRunDetailedLineColumns holds the columns for the "charge_usage_based_run_detailed_line" table. + ChargeUsageBasedRunDetailedLineColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "currency", Type: field.TypeString, SchemaType: map[string]string{"postgres": "varchar(3)"}}, + {Name: "service_period_start", Type: field.TypeTime}, + {Name: "service_period_end", Type: field.TypeTime}, + {Name: "quantity", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "invoicing_app_external_id", Type: field.TypeString, Nullable: true}, + {Name: "child_unique_reference_id", Type: field.TypeString}, + {Name: "per_unit_amount", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "category", Type: field.TypeEnum, Enums: []string{"regular", "commitment"}, Default: "regular"}, + {Name: "payment_term", Type: field.TypeEnum, Enums: []string{"in_advance", "in_arrears"}, Default: "in_advance"}, + {Name: "index", Type: field.TypeInt, Nullable: true}, + {Name: "credits_applied", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {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: "pricer_reference_id", Type: field.TypeString}, + {Name: "charge_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "run_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "corrects_run_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // ChargeUsageBasedRunDetailedLineTable holds the schema information for the "charge_usage_based_run_detailed_line" table. + ChargeUsageBasedRunDetailedLineTable = &schema.Table{ + Name: "charge_usage_based_run_detailed_line", + Columns: ChargeUsageBasedRunDetailedLineColumns, + PrimaryKey: []*schema.Column{ChargeUsageBasedRunDetailedLineColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "charge_usage_based_run_detailed_line_charge_usage_based_detailed_lines", + Columns: []*schema.Column{ChargeUsageBasedRunDetailedLineColumns[29]}, + RefColumns: []*schema.Column{ChargeUsageBasedColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "charge_usage_based_run_detailed_line_charge_usage_based_runs_detailed_lines", + Columns: []*schema.Column{ChargeUsageBasedRunDetailedLineColumns[30]}, + RefColumns: []*schema.Column{ChargeUsageBasedRunsColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "cub_run_corrected_detailed_lines", + Columns: []*schema.Column{ChargeUsageBasedRunDetailedLineColumns[31]}, + RefColumns: []*schema.Column{ChargeUsageBasedRunsColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargeusagebasedrundetailedline_annotations", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedRunDetailedLineColumns[12]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "chargeusagebasedrundetailedline_id", + Unique: true, + Columns: []*schema.Column{ChargeUsageBasedRunDetailedLineColumns[0]}, + }, + { + Name: "chargeusagebasedrundetailedline_namespace", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedRunDetailedLineColumns[13]}, + }, + { + Name: "chargeusagebasedrundetailedline_namespace_id", + Unique: true, + Columns: []*schema.Column{ChargeUsageBasedRunDetailedLineColumns[13], ChargeUsageBasedRunDetailedLineColumns[0]}, + }, + { + Name: "chargeusagebasedrundetailedline_namespace_charge_id", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedRunDetailedLineColumns[13], ChargeUsageBasedRunDetailedLineColumns[29]}, + }, + { + Name: "chargeusagebasedrundetailedline_namespace_run_id", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedRunDetailedLineColumns[13], ChargeUsageBasedRunDetailedLineColumns[30]}, + }, + { + Name: "chargeubdetailedline_ns_charge_run_child_id", + Unique: true, + Columns: []*schema.Column{ChargeUsageBasedRunDetailedLineColumns[13], ChargeUsageBasedRunDetailedLineColumns[29], ChargeUsageBasedRunDetailedLineColumns[30], ChargeUsageBasedRunDetailedLineColumns[6]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + }, + } + // 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: "service_period_from", Type: field.TypeTime}, + {Name: "service_period_to", Type: field.TypeTime}, + {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[17]}, + RefColumns: []*schema.Column{ChargeUsageBasedRunsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargeusagebasedruninvoicedusage_namespace", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedRunInvoicedUsagesColumns[4]}, + }, + { + Name: "chargeusagebasedruninvoicedusage_id", + Unique: true, + Columns: []*schema.Column{ChargeUsageBasedRunInvoicedUsagesColumns[0]}, + }, + { + Name: "chargeusagebasedruninvoicedusage_annotations", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedRunInvoicedUsagesColumns[8]}, + 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: "invoice_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[16]}, + RefColumns: []*schema.Column{ChargeUsageBasedRunsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargeusagebasedrunpayment_namespace", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedRunPaymentsColumns[11]}, + }, + { + Name: "chargeusagebasedrunpayment_id", + Unique: true, + Columns: []*schema.Column{ChargeUsageBasedRunPaymentsColumns[0]}, + }, + { + Name: "chargeusagebasedrunpayment_annotations", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedRunPaymentsColumns[15]}, + 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: "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: "type", Type: field.TypeEnum, Enums: []string{"final_realization", "partial_invoice", "invalid_due_to_unsupported_credit_note"}}, + {Name: "initial_type", Type: field.TypeEnum, Enums: []string{"final_realization", "partial_invoice", "invalid_due_to_unsupported_credit_note"}}, + {Name: "stored_at_lt", Type: field.TypeTime}, + {Name: "service_period_to", Type: field.TypeTime}, + {Name: "detailed_lines_present", Type: field.TypeBool}, + {Name: "metered_quantity", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "no_fiat_transaction_required", Type: field.TypeBool}, + {Name: "invoice_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "line_id", Type: field.TypeString, Unique: true, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "charge_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "feature_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_billing_invoices_charge_usage_based_runs", + Columns: []*schema.Column{ChargeUsageBasedRunsColumns[20]}, + RefColumns: []*schema.Column{BillingInvoicesColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "charge_usage_based_runs_billing_invoice_lines_charge_usage_based_run", + Columns: []*schema.Column{ChargeUsageBasedRunsColumns[21]}, + RefColumns: []*schema.Column{BillingInvoiceLinesColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "charge_usage_based_runs_charge_usage_based_runs", + Columns: []*schema.Column{ChargeUsageBasedRunsColumns[22]}, + RefColumns: []*schema.Column{ChargeUsageBasedColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "charge_usage_based_runs_features_usage_based_runs", + Columns: []*schema.Column{ChargeUsageBasedRunsColumns[23]}, + RefColumns: []*schema.Column{FeaturesColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + 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[22]}, + }, + }, + } + // CreditRealizationLineagesColumns holds the columns for the "credit_realization_lineages" table. + CreditRealizationLineagesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "root_realization_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "customer_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "currency", Type: field.TypeString, SchemaType: map[string]string{"postgres": "varchar(3)"}}, + {Name: "origin_kind", Type: field.TypeEnum, Enums: []string{"real_credit", "advance"}}, + {Name: "advance_features", Type: field.TypeOther, Nullable: true, SchemaType: map[string]string{"postgres": "text[]"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "charge_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // CreditRealizationLineagesTable holds the schema information for the "credit_realization_lineages" table. + CreditRealizationLineagesTable = &schema.Table{ + Name: "credit_realization_lineages", + Columns: CreditRealizationLineagesColumns, + PrimaryKey: []*schema.Column{CreditRealizationLineagesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "credit_realization_lineages_charges_credit_realization_lineages", + Columns: []*schema.Column{CreditRealizationLineagesColumns[8]}, + RefColumns: []*schema.Column{ChargesColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "creditrealizationlineage_id", + Unique: true, + Columns: []*schema.Column{CreditRealizationLineagesColumns[0]}, + }, + { + Name: "creditrealizationlineage_namespace", + Unique: false, + Columns: []*schema.Column{CreditRealizationLineagesColumns[1]}, + }, + { + Name: "creditrealizationlineage_namespace_root_realization_id", + Unique: true, + Columns: []*schema.Column{CreditRealizationLineagesColumns[1], CreditRealizationLineagesColumns[2]}, + }, + { + Name: "creditrealizationlineage_namespace_charge_id", + Unique: false, + Columns: []*schema.Column{CreditRealizationLineagesColumns[1], CreditRealizationLineagesColumns[8]}, + }, + { + Name: "creditrealizationlineage_namespace_customer_id", + Unique: false, + Columns: []*schema.Column{CreditRealizationLineagesColumns[1], CreditRealizationLineagesColumns[3]}, + }, + }, + } + // CreditRealizationLineageSegmentsColumns holds the columns for the "credit_realization_lineage_segments" table. + CreditRealizationLineageSegmentsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "amount", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "state", Type: field.TypeEnum, Enums: []string{"real_credit", "advance_uncovered", "advance_backfilled", "earnings_recognized"}}, + {Name: "backing_transaction_group_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "source_state", Type: field.TypeEnum, Nullable: true, Enums: []string{"real_credit", "advance_uncovered", "advance_backfilled", "earnings_recognized"}}, + {Name: "source_backing_transaction_group_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "closed_at", Type: field.TypeTime, Nullable: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "lineage_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // CreditRealizationLineageSegmentsTable holds the schema information for the "credit_realization_lineage_segments" table. + CreditRealizationLineageSegmentsTable = &schema.Table{ + Name: "credit_realization_lineage_segments", + Columns: CreditRealizationLineageSegmentsColumns, + PrimaryKey: []*schema.Column{CreditRealizationLineageSegmentsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "credit_realization_lineage_segments_credit_realization_lineages_segments", + Columns: []*schema.Column{CreditRealizationLineageSegmentsColumns[8]}, + RefColumns: []*schema.Column{CreditRealizationLineagesColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "creditrealizationlineagesegment_id", + Unique: true, + Columns: []*schema.Column{CreditRealizationLineageSegmentsColumns[0]}, + }, + { + Name: "creditrealizationlineagesegment_lineage_id", + Unique: false, + Columns: []*schema.Column{CreditRealizationLineageSegmentsColumns[8]}, + }, + { + Name: "creditrealizationlineagesegment_lineage_id_closed_at", + Unique: false, + Columns: []*schema.Column{CreditRealizationLineageSegmentsColumns[8], CreditRealizationLineageSegmentsColumns[6]}, + }, + }, + } + // 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)"}}, + {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: "fiat_code", Type: field.TypeString}, + {Name: "rate", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "effective_from", Type: field.TypeTime}, + {Name: "effective_to", Type: field.TypeTime, Nullable: true}, + {Name: "currency_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // CurrencyCostBasesTable holds the schema information for the "currency_cost_bases" table. + CurrencyCostBasesTable = &schema.Table{ + Name: "currency_cost_bases", + Columns: CurrencyCostBasesColumns, + PrimaryKey: []*schema.Column{CurrencyCostBasesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "currency_cost_bases_custom_currencies_cost_basis_history", + Columns: []*schema.Column{CurrencyCostBasesColumns[9]}, + RefColumns: []*schema.Column{CustomCurrenciesColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "currencycostbasis_namespace", + Unique: false, + Columns: []*schema.Column{CurrencyCostBasesColumns[1]}, + }, + { + Name: "currencycostbasis_id", + Unique: true, + Columns: []*schema.Column{CurrencyCostBasesColumns[0]}, + }, + { + Name: "currencycostbasis_namespace_currency_id_fiat_code_effective_from", + Unique: true, + Columns: []*schema.Column{CurrencyCostBasesColumns[1], CurrencyCostBasesColumns[9], CurrencyCostBasesColumns[5], CurrencyCostBasesColumns[7]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + }, + } + // CustomCurrenciesColumns holds the columns for the "custom_currencies" table. + CustomCurrenciesColumns = []*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: "code", Type: field.TypeString, Size: 24}, + {Name: "name", Type: field.TypeString}, + {Name: "symbol", Type: field.TypeString}, + } + // CustomCurrenciesTable holds the schema information for the "custom_currencies" table. + CustomCurrenciesTable = &schema.Table{ + Name: "custom_currencies", + Columns: CustomCurrenciesColumns, + PrimaryKey: []*schema.Column{CustomCurrenciesColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "customcurrency_namespace", + Unique: false, + Columns: []*schema.Column{CustomCurrenciesColumns[1]}, + }, + { + Name: "customcurrency_id", + Unique: true, + Columns: []*schema.Column{CustomCurrenciesColumns[0]}, + }, + { + Name: "customcurrency_namespace_code", + Unique: true, + Columns: []*schema.Column{CustomCurrenciesColumns[1], CustomCurrenciesColumns[5]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + { + Name: "customcurrency_namespace_id", + Unique: true, + Columns: []*schema.Column{CustomCurrenciesColumns[1], CustomCurrenciesColumns[0]}, + }, + }, + } + // CustomersColumns holds the columns for the "customers" table. + CustomersColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "billing_address_country", Type: field.TypeString, Nullable: true, Size: 2}, + {Name: "billing_address_postal_code", Type: field.TypeString, Nullable: true}, + {Name: "billing_address_state", Type: field.TypeString, Nullable: true}, + {Name: "billing_address_city", Type: field.TypeString, Nullable: true}, + {Name: "billing_address_line1", Type: field.TypeString, Nullable: true}, + {Name: "billing_address_line2", Type: field.TypeString, Nullable: true}, + {Name: "billing_address_phone_number", Type: field.TypeString, Nullable: true}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "key", Type: field.TypeString, Nullable: true}, + {Name: "primary_email", Type: field.TypeString, Nullable: true}, + {Name: "currency", Type: field.TypeString, Nullable: true, Size: 3}, + } + // CustomersTable holds the schema information for the "customers" table. + CustomersTable = &schema.Table{ + Name: "customers", + Columns: CustomersColumns, + PrimaryKey: []*schema.Column{CustomersColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "customer_id", + Unique: true, + Columns: []*schema.Column{CustomersColumns[0]}, + }, + { + Name: "customer_namespace", + Unique: false, + Columns: []*schema.Column{CustomersColumns[1]}, + }, + { + Name: "customer_namespace_id", + Unique: true, + Columns: []*schema.Column{CustomersColumns[1], CustomersColumns[0]}, + }, + { + Name: "customer_annotations", + Unique: false, + Columns: []*schema.Column{CustomersColumns[15]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "customer_namespace_key", + Unique: true, + Columns: []*schema.Column{CustomersColumns[1], CustomersColumns[16]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + { + Name: "customer_namespace_key_deleted_at", + Unique: false, + Columns: []*schema.Column{CustomersColumns[1], CustomersColumns[16], CustomersColumns[5]}, + }, + { + Name: "customer_name", + Unique: false, + Columns: []*schema.Column{CustomersColumns[6]}, + }, + { + Name: "customer_primary_email", + Unique: false, + Columns: []*schema.Column{CustomersColumns[17]}, + }, + { + Name: "customer_created_at", + Unique: false, + Columns: []*schema.Column{CustomersColumns[3]}, + }, + }, + } + // CustomerSubjectsColumns holds the columns for the "customer_subjects" table. + CustomerSubjectsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "namespace", Type: field.TypeString}, + {Name: "subject_key", Type: field.TypeString}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "customer_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // CustomerSubjectsTable holds the schema information for the "customer_subjects" table. + CustomerSubjectsTable = &schema.Table{ + Name: "customer_subjects", + Columns: CustomerSubjectsColumns, + PrimaryKey: []*schema.Column{CustomerSubjectsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "customer_subjects_customers_subjects", + Columns: []*schema.Column{CustomerSubjectsColumns[5]}, + RefColumns: []*schema.Column{CustomersColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "customersubjects_namespace", + Unique: false, + Columns: []*schema.Column{CustomerSubjectsColumns[1]}, + }, + { + Name: "customersubjects_namespace_customer_id_deleted_at", + Unique: false, + Columns: []*schema.Column{CustomerSubjectsColumns[1], CustomerSubjectsColumns[5], CustomerSubjectsColumns[4]}, + }, + { + Name: "customersubjects_namespace_subject_key", + Unique: true, + Columns: []*schema.Column{CustomerSubjectsColumns[1], CustomerSubjectsColumns[2]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + { + Name: "customersubjects_deleted_at", + Unique: false, + Columns: []*schema.Column{CustomerSubjectsColumns[4]}, + }, + { + Name: "customersubjects_subject_key", + Unique: false, + Columns: []*schema.Column{CustomerSubjectsColumns[2]}, + }, + { + Name: "customersubjects_customer_id", + Unique: false, + Columns: []*schema.Column{CustomerSubjectsColumns[5]}, + }, + { + Name: "customersubjects_deleted_at_customer_id", + Unique: false, + Columns: []*schema.Column{CustomerSubjectsColumns[4], CustomerSubjectsColumns[5]}, + }, + }, + } + // EntitlementsColumns holds the columns for the "entitlements" table. + EntitlementsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "entitlement_type", Type: field.TypeEnum, Enums: []string{"metered", "static", "boolean"}}, + {Name: "active_from", Type: field.TypeTime, Nullable: true}, + {Name: "active_to", Type: field.TypeTime, Nullable: true}, + {Name: "feature_key", Type: field.TypeString}, + {Name: "measure_usage_from", Type: field.TypeTime, Nullable: true}, + {Name: "issue_after_reset", Type: field.TypeFloat64, Nullable: true}, + {Name: "issue_after_reset_priority", Type: field.TypeUint8, Nullable: true}, + {Name: "is_soft_limit", Type: field.TypeBool, Nullable: true}, + {Name: "preserve_overage_at_reset", Type: field.TypeBool, Nullable: true}, + {Name: "config", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "usage_period_interval", Type: field.TypeString, Nullable: true}, + {Name: "usage_period_anchor", Type: field.TypeTime, Nullable: true}, + {Name: "current_usage_period_start", Type: field.TypeTime, Nullable: true}, + {Name: "current_usage_period_end", Type: field.TypeTime, Nullable: true}, + {Name: "annotations", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "customer_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "feature_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // EntitlementsTable holds the schema information for the "entitlements" table. + EntitlementsTable = &schema.Table{ + Name: "entitlements", + Columns: EntitlementsColumns, + PrimaryKey: []*schema.Column{EntitlementsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "entitlements_customers_entitlements", + Columns: []*schema.Column{EntitlementsColumns[21]}, + RefColumns: []*schema.Column{CustomersColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "entitlements_features_entitlement", + Columns: []*schema.Column{EntitlementsColumns[22]}, + RefColumns: []*schema.Column{FeaturesColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "entitlement_id", + Unique: true, + Columns: []*schema.Column{EntitlementsColumns[0]}, + }, + { + Name: "entitlement_namespace", + Unique: false, + Columns: []*schema.Column{EntitlementsColumns[1]}, + }, + { + Name: "entitlement_namespace_id", + Unique: false, + Columns: []*schema.Column{EntitlementsColumns[1], EntitlementsColumns[0]}, + }, + { + Name: "entitlement_namespace_customer_id", + Unique: false, + Columns: []*schema.Column{EntitlementsColumns[1], EntitlementsColumns[21]}, + }, + { + Name: "entitlement_namespace_id_customer_id", + Unique: false, + Columns: []*schema.Column{EntitlementsColumns[1], EntitlementsColumns[0], EntitlementsColumns[21]}, + }, + { + Name: "entitlement_namespace_feature_id_id", + Unique: false, + Columns: []*schema.Column{EntitlementsColumns[1], EntitlementsColumns[22], EntitlementsColumns[0]}, + }, + { + Name: "entitlement_namespace_current_usage_period_end", + Unique: false, + Columns: []*schema.Column{EntitlementsColumns[1], EntitlementsColumns[19]}, + }, + { + Name: "entitlement_current_usage_period_end_deleted_at", + Unique: false, + Columns: []*schema.Column{EntitlementsColumns[19], EntitlementsColumns[5]}, + }, + { + Name: "entitlement_created_at_id", + Unique: true, + Columns: []*schema.Column{EntitlementsColumns[3], EntitlementsColumns[0]}, + }, + }, + } + // FeaturesColumns holds the columns for the "features" table. + FeaturesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true, Size: 1024}, + {Name: "key", Type: field.TypeString}, + {Name: "meter_slug", Type: field.TypeString, Nullable: true}, + {Name: "meter_group_by_filters", Type: field.TypeJSON, Nullable: true}, + {Name: "advanced_meter_group_by_filters", Type: field.TypeJSON, Nullable: true}, + {Name: "unit_cost_type", Type: field.TypeString, Nullable: true}, + {Name: "unit_cost_manual_amount", Type: field.TypeOther, Nullable: true, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "unit_cost_llm_provider_property", Type: field.TypeString, Nullable: true}, + {Name: "unit_cost_llm_provider", Type: field.TypeString, Nullable: true}, + {Name: "unit_cost_llm_model_property", Type: field.TypeString, Nullable: true}, + {Name: "unit_cost_llm_model", Type: field.TypeString, Nullable: true}, + {Name: "unit_cost_llm_token_type_property", Type: field.TypeString, Nullable: true}, + {Name: "unit_cost_llm_token_type", Type: field.TypeString, Nullable: true}, + {Name: "archived_at", Type: field.TypeTime, Nullable: true}, + {Name: "meter_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // FeaturesTable holds the schema information for the "features" table. + FeaturesTable = &schema.Table{ + Name: "features", + Columns: FeaturesColumns, + PrimaryKey: []*schema.Column{FeaturesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "features_meters_feature", + Columns: []*schema.Column{FeaturesColumns[21]}, + RefColumns: []*schema.Column{MetersColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + Indexes: []*schema.Index{ + { + Name: "feature_id", + Unique: true, + Columns: []*schema.Column{FeaturesColumns[0]}, + }, + { + Name: "feature_namespace_id", + Unique: false, + Columns: []*schema.Column{FeaturesColumns[5], FeaturesColumns[0]}, + }, + { + Name: "feature_namespace_key", + Unique: true, + Columns: []*schema.Column{FeaturesColumns[5], FeaturesColumns[8]}, + Annotation: &entsql.IndexAnnotation{ + Where: "archived_at IS NULL", + }, + }, + { + Name: "feature_namespace_meter_slug", + Unique: false, + Columns: []*schema.Column{FeaturesColumns[5], FeaturesColumns[9]}, + Annotation: &entsql.IndexAnnotation{ + Where: "archived_at IS NULL", + }, + }, + { + Name: "feature_namespace_meter_id", + Unique: false, + Columns: []*schema.Column{FeaturesColumns[5], FeaturesColumns[21]}, + Annotation: &entsql.IndexAnnotation{ + Where: "archived_at IS NULL", + }, + }, + }, + } + // GrantsColumns holds the columns for the "grants" table. + GrantsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "amount", Type: field.TypeFloat64, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "priority", Type: field.TypeUint8, Default: 0}, + {Name: "effective_at", Type: field.TypeTime}, + {Name: "expiration", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "expires_at", Type: field.TypeTime, Nullable: true}, + {Name: "voided_at", Type: field.TypeTime, Nullable: true}, + {Name: "reset_max_rollover", Type: field.TypeFloat64, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "reset_min_rollover", Type: field.TypeFloat64, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "recurrence_period", Type: field.TypeString, Nullable: true}, + {Name: "recurrence_anchor", Type: field.TypeTime, Nullable: true}, + {Name: "owner_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // GrantsTable holds the schema information for the "grants" table. + GrantsTable = &schema.Table{ + Name: "grants", + Columns: GrantsColumns, + PrimaryKey: []*schema.Column{GrantsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "grants_entitlements_grant", + Columns: []*schema.Column{GrantsColumns[17]}, + RefColumns: []*schema.Column{EntitlementsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "grant_id", + Unique: true, + Columns: []*schema.Column{GrantsColumns[0]}, + }, + { + Name: "grant_namespace", + Unique: false, + Columns: []*schema.Column{GrantsColumns[1]}, + }, + { + Name: "grant_annotations", + Unique: false, + Columns: []*schema.Column{GrantsColumns[2]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "grant_namespace_owner_id", + Unique: false, + Columns: []*schema.Column{GrantsColumns[1], GrantsColumns[17]}, + }, + { + Name: "grant_effective_at_expires_at", + Unique: false, + Columns: []*schema.Column{GrantsColumns[9], GrantsColumns[11]}, + }, + }, + } + // LlmCostPricesColumns holds the columns for the "llm_cost_prices" table. + LlmCostPricesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "namespace", Type: field.TypeString, Nullable: true}, + {Name: "provider", Type: field.TypeString}, + {Name: "model_id", Type: field.TypeString}, + {Name: "model_name", Type: field.TypeString, Default: ""}, + {Name: "input_per_token", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "output_per_token", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "cache_read_per_token", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "reasoning_per_token", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "cache_write_per_token", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "currency", Type: field.TypeString, Default: "USD"}, + {Name: "source", Type: field.TypeString}, + {Name: "source_prices", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "effective_from", Type: field.TypeTime}, + {Name: "effective_to", Type: field.TypeTime, Nullable: true}, + } + // LlmCostPricesTable holds the schema information for the "llm_cost_prices" table. + LlmCostPricesTable = &schema.Table{ + Name: "llm_cost_prices", + Columns: LlmCostPricesColumns, + PrimaryKey: []*schema.Column{LlmCostPricesColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "llmcostprice_id", + Unique: true, + Columns: []*schema.Column{LlmCostPricesColumns[0]}, + }, + { + Name: "llmcostprice_provider_model_id_namespace_effective_from", + Unique: true, + Columns: []*schema.Column{LlmCostPricesColumns[6], LlmCostPricesColumns[7], LlmCostPricesColumns[5], LlmCostPricesColumns[17]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + { + Name: "llmcostprice_namespace_provider_model_id", + Unique: false, + Columns: []*schema.Column{LlmCostPricesColumns[5], LlmCostPricesColumns[6], LlmCostPricesColumns[7]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + { + Name: "llmcostprice_provider_model_id", + Unique: false, + Columns: []*schema.Column{LlmCostPricesColumns[6], LlmCostPricesColumns[7]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL AND namespace IS NULL", + }, + }, + }, + } + // LedgerAccountsColumns holds the columns for the "ledger_accounts" table. + LedgerAccountsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "account_type", Type: field.TypeString}, + } + // LedgerAccountsTable holds the schema information for the "ledger_accounts" table. + LedgerAccountsTable = &schema.Table{ + Name: "ledger_accounts", + Columns: LedgerAccountsColumns, + PrimaryKey: []*schema.Column{LedgerAccountsColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "ledgeraccount_id", + Unique: true, + Columns: []*schema.Column{LedgerAccountsColumns[0]}, + }, + { + Name: "ledgeraccount_namespace", + Unique: false, + Columns: []*schema.Column{LedgerAccountsColumns[1]}, + }, + { + Name: "ledgeraccount_annotations", + Unique: false, + Columns: []*schema.Column{LedgerAccountsColumns[2]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "ledgeraccount_namespace_id", + Unique: true, + Columns: []*schema.Column{LedgerAccountsColumns[1], LedgerAccountsColumns[0]}, + }, + }, + } + // LedgerBreakageRecordsColumns holds the columns for the "ledger_breakage_records" table. + LedgerBreakageRecordsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "kind", Type: field.TypeEnum, Enums: []string{"plan", "release", "reopen"}}, + {Name: "amount", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "customer_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "currency", Type: field.TypeString, SchemaType: map[string]string{"postgres": "varchar(3)"}}, + {Name: "credit_priority", Type: field.TypeInt}, + {Name: "expires_at", Type: field.TypeTime}, + {Name: "source_kind", Type: field.TypeEnum, Enums: []string{"credit_purchase", "usage", "usage_correction", "credit_purchase_correction", "advance_backfill"}}, + {Name: "source_charge_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "plan_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "release_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "source_entry_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "fbo_sub_account_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "breakage_sub_account_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "source_transaction_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "breakage_transaction_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "source_transaction_group_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "breakage_transaction_group_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // LedgerBreakageRecordsTable holds the schema information for the "ledger_breakage_records" table. + LedgerBreakageRecordsTable = &schema.Table{ + Name: "ledger_breakage_records", + Columns: LedgerBreakageRecordsColumns, + PrimaryKey: []*schema.Column{LedgerBreakageRecordsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "ledger_breakage_records_ledger_breakage_records_planned_releases", + Columns: []*schema.Column{LedgerBreakageRecordsColumns[14]}, + RefColumns: []*schema.Column{LedgerBreakageRecordsColumns[0]}, + OnDelete: schema.Restrict, + }, + { + Symbol: "ledger_breakage_records_ledger_breakage_records_release_reopens", + Columns: []*schema.Column{LedgerBreakageRecordsColumns[15]}, + RefColumns: []*schema.Column{LedgerBreakageRecordsColumns[0]}, + OnDelete: schema.Restrict, + }, + { + Symbol: "ledger_breakage_records_ledger_entries_source_breakage_records", + Columns: []*schema.Column{LedgerBreakageRecordsColumns[16]}, + RefColumns: []*schema.Column{LedgerEntriesColumns[0]}, + OnDelete: schema.Restrict, + }, + { + Symbol: "ledger_breakage_records_ledger_sub_accounts_fbo_breakage_records", + Columns: []*schema.Column{LedgerBreakageRecordsColumns[17]}, + RefColumns: []*schema.Column{LedgerSubAccountsColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "ledger_breakage_records_ledger_sub_accounts_breakage_records", + Columns: []*schema.Column{LedgerBreakageRecordsColumns[18]}, + RefColumns: []*schema.Column{LedgerSubAccountsColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "ledger_breakage_records_ledger_transactions_source_breakage_records", + Columns: []*schema.Column{LedgerBreakageRecordsColumns[19]}, + RefColumns: []*schema.Column{LedgerTransactionsColumns[0]}, + OnDelete: schema.Restrict, + }, + { + Symbol: "ledger_breakage_records_ledger_transactions_breakage_records", + Columns: []*schema.Column{LedgerBreakageRecordsColumns[20]}, + RefColumns: []*schema.Column{LedgerTransactionsColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "ledger_breakage_records_ledger_transaction_groups_source_breakage_records", + Columns: []*schema.Column{LedgerBreakageRecordsColumns[21]}, + RefColumns: []*schema.Column{LedgerTransactionGroupsColumns[0]}, + OnDelete: schema.Restrict, + }, + { + Symbol: "ledger_breakage_records_ledger_transaction_groups_breakage_records", + Columns: []*schema.Column{LedgerBreakageRecordsColumns[22]}, + RefColumns: []*schema.Column{LedgerTransactionGroupsColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "ledgerbreakagerecord_id", + Unique: true, + Columns: []*schema.Column{LedgerBreakageRecordsColumns[0]}, + }, + { + Name: "ledgerbreakagerecord_namespace", + Unique: false, + Columns: []*schema.Column{LedgerBreakageRecordsColumns[1]}, + }, + { + Name: "ledgerbreakagerecord_annotations", + Unique: false, + Columns: []*schema.Column{LedgerBreakageRecordsColumns[2]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "ledgerbreakagerecord_namespace_customer_id_currency_credit_", + Unique: false, + Columns: []*schema.Column{LedgerBreakageRecordsColumns[1], LedgerBreakageRecordsColumns[8], LedgerBreakageRecordsColumns[9], LedgerBreakageRecordsColumns[10], LedgerBreakageRecordsColumns[11], LedgerBreakageRecordsColumns[0]}, + }, + { + Name: "ledgerbreakagerecord_namespace_plan_id", + Unique: false, + Columns: []*schema.Column{LedgerBreakageRecordsColumns[1], LedgerBreakageRecordsColumns[14]}, + }, + { + Name: "ledgerbreakagerecord_namespace_source_charge_id", + Unique: false, + Columns: []*schema.Column{LedgerBreakageRecordsColumns[1], LedgerBreakageRecordsColumns[13]}, + }, + { + Name: "ledgerbreakagerecord_namespace_source_transaction_group_id", + Unique: false, + Columns: []*schema.Column{LedgerBreakageRecordsColumns[1], LedgerBreakageRecordsColumns[21]}, + }, + { + Name: "ledgerbreakagerecord_namespace_source_entry_id", + Unique: false, + Columns: []*schema.Column{LedgerBreakageRecordsColumns[1], LedgerBreakageRecordsColumns[16]}, + }, + { + Name: "ledgerbreakagerecord_namespace_breakage_transaction_group_id", + Unique: false, + Columns: []*schema.Column{LedgerBreakageRecordsColumns[1], LedgerBreakageRecordsColumns[22]}, + }, + }, + } + // LedgerCreditVoidRecordsColumns holds the columns for the "ledger_credit_void_records" table. + LedgerCreditVoidRecordsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "amount", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "customer_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "currency", Type: field.TypeString, SchemaType: map[string]string{"postgres": "varchar(3)"}}, + {Name: "voided_at", Type: field.TypeTime}, + {Name: "source_charge_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "void_transaction_group_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "void_transaction_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "fbo_sub_account_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "receivable_sub_account_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // LedgerCreditVoidRecordsTable holds the schema information for the "ledger_credit_void_records" table. + LedgerCreditVoidRecordsTable = &schema.Table{ + Name: "ledger_credit_void_records", + Columns: LedgerCreditVoidRecordsColumns, + PrimaryKey: []*schema.Column{LedgerCreditVoidRecordsColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "ledgercreditvoidrecord_id", + Unique: true, + Columns: []*schema.Column{LedgerCreditVoidRecordsColumns[0]}, + }, + { + Name: "ledgercreditvoidrecord_namespace", + Unique: false, + Columns: []*schema.Column{LedgerCreditVoidRecordsColumns[1]}, + }, + { + Name: "ledgercreditvoidrecord_annotations", + Unique: false, + Columns: []*schema.Column{LedgerCreditVoidRecordsColumns[2]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "ledgercreditvoidrecord_namespace_customer_currency_voided", + Unique: false, + Columns: []*schema.Column{LedgerCreditVoidRecordsColumns[1], LedgerCreditVoidRecordsColumns[7], LedgerCreditVoidRecordsColumns[8], LedgerCreditVoidRecordsColumns[9], LedgerCreditVoidRecordsColumns[0]}, + }, + { + Name: "ledgercreditvoidrecord_namespace_source_charge_id", + Unique: false, + Columns: []*schema.Column{LedgerCreditVoidRecordsColumns[1], LedgerCreditVoidRecordsColumns[10]}, + }, + { + Name: "ledgercreditvoidrecord_namespace_void_transaction_group_id", + Unique: false, + Columns: []*schema.Column{LedgerCreditVoidRecordsColumns[1], LedgerCreditVoidRecordsColumns[11]}, + }, + }, + } + // LedgerCustomerAccountsColumns holds the columns for the "ledger_customer_accounts" table. + LedgerCustomerAccountsColumns = []*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: "customer_id", Type: field.TypeString}, + {Name: "account_type", Type: field.TypeString}, + {Name: "account_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // LedgerCustomerAccountsTable holds the schema information for the "ledger_customer_accounts" table. + LedgerCustomerAccountsTable = &schema.Table{ + Name: "ledger_customer_accounts", + Columns: LedgerCustomerAccountsColumns, + PrimaryKey: []*schema.Column{LedgerCustomerAccountsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "ledger_customer_accounts_ledger_accounts_customer_accounts", + Columns: []*schema.Column{LedgerCustomerAccountsColumns[7]}, + RefColumns: []*schema.Column{LedgerAccountsColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "ledgercustomeraccount_id", + Unique: true, + Columns: []*schema.Column{LedgerCustomerAccountsColumns[0]}, + }, + { + Name: "ledgercustomeraccount_namespace", + Unique: false, + Columns: []*schema.Column{LedgerCustomerAccountsColumns[1]}, + }, + { + Name: "ledgercustomeraccount_namespace_id", + Unique: true, + Columns: []*schema.Column{LedgerCustomerAccountsColumns[1], LedgerCustomerAccountsColumns[0]}, + }, + { + Name: "ledgercustomeraccount_namespace_customer_id_account_type", + Unique: true, + Columns: []*schema.Column{LedgerCustomerAccountsColumns[1], LedgerCustomerAccountsColumns[5], LedgerCustomerAccountsColumns[6]}, + }, + }, + } + // LedgerEntriesColumns holds the columns for the "ledger_entries" table. + LedgerEntriesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "identity_key", Type: field.TypeString, Default: ""}, + {Name: "schema_version", Type: field.TypeInt, Default: 1}, + {Name: "source_charge_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "spend_charge_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: "sub_account_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "transaction_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // LedgerEntriesTable holds the schema information for the "ledger_entries" table. + LedgerEntriesTable = &schema.Table{ + Name: "ledger_entries", + Columns: LedgerEntriesColumns, + PrimaryKey: []*schema.Column{LedgerEntriesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "ledger_entries_ledger_sub_accounts_entries", + Columns: []*schema.Column{LedgerEntriesColumns[11]}, + RefColumns: []*schema.Column{LedgerSubAccountsColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "ledger_entries_ledger_transactions_entries", + Columns: []*schema.Column{LedgerEntriesColumns[12]}, + RefColumns: []*schema.Column{LedgerTransactionsColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "ledgerentry_id", + Unique: true, + Columns: []*schema.Column{LedgerEntriesColumns[0]}, + }, + { + Name: "ledgerentry_namespace", + Unique: false, + Columns: []*schema.Column{LedgerEntriesColumns[1]}, + }, + { + Name: "ledgerentry_annotations", + Unique: false, + Columns: []*schema.Column{LedgerEntriesColumns[2]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "ledgerentry_namespace_id", + Unique: true, + Columns: []*schema.Column{LedgerEntriesColumns[1], LedgerEntriesColumns[0]}, + }, + { + Name: "ledgerentry_namespace_transaction_id", + Unique: false, + Columns: []*schema.Column{LedgerEntriesColumns[1], LedgerEntriesColumns[12]}, + }, + { + Name: "ledgerentry_namespace_sub_account_id", + Unique: false, + Columns: []*schema.Column{LedgerEntriesColumns[1], LedgerEntriesColumns[11]}, + }, + { + Name: "ledgerentry_namespace_source_charge_id", + Unique: false, + Columns: []*schema.Column{LedgerEntriesColumns[1], LedgerEntriesColumns[8]}, + }, + { + Name: "ledgerentry_namespace_spend_charge_id", + Unique: false, + Columns: []*schema.Column{LedgerEntriesColumns[1], LedgerEntriesColumns[9]}, + }, + { + Name: "ledgerentry_namespace_source_charge_id_spend_charge_id", + Unique: false, + Columns: []*schema.Column{LedgerEntriesColumns[1], LedgerEntriesColumns[8], LedgerEntriesColumns[9]}, + }, + { + Name: "ledgerentry_transaction_id_sub_account_id_identity_key", + Unique: true, + Columns: []*schema.Column{LedgerEntriesColumns[12], LedgerEntriesColumns[11], LedgerEntriesColumns[6]}, + }, + { + Name: "ledgerentry_created_at_id", + Unique: false, + Columns: []*schema.Column{LedgerEntriesColumns[3], LedgerEntriesColumns[0]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + }, + } + // LedgerSubAccountsColumns holds the columns for the "ledger_sub_accounts" table. + LedgerSubAccountsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "account_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "route_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // LedgerSubAccountsTable holds the schema information for the "ledger_sub_accounts" table. + LedgerSubAccountsTable = &schema.Table{ + Name: "ledger_sub_accounts", + Columns: LedgerSubAccountsColumns, + PrimaryKey: []*schema.Column{LedgerSubAccountsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "ledger_sub_accounts_ledger_accounts_sub_accounts", + Columns: []*schema.Column{LedgerSubAccountsColumns[6]}, + RefColumns: []*schema.Column{LedgerAccountsColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "ledger_sub_accounts_ledger_sub_account_routes_sub_accounts", + Columns: []*schema.Column{LedgerSubAccountsColumns[7]}, + RefColumns: []*schema.Column{LedgerSubAccountRoutesColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "ledgersubaccount_id", + Unique: true, + Columns: []*schema.Column{LedgerSubAccountsColumns[0]}, + }, + { + Name: "ledgersubaccount_namespace", + Unique: false, + Columns: []*schema.Column{LedgerSubAccountsColumns[1]}, + }, + { + Name: "ledgersubaccount_annotations", + Unique: false, + Columns: []*schema.Column{LedgerSubAccountsColumns[2]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "ledgersubaccount_namespace_account_id_route_id", + Unique: true, + Columns: []*schema.Column{LedgerSubAccountsColumns[1], LedgerSubAccountsColumns[6], LedgerSubAccountsColumns[7]}, + }, + }, + } + // LedgerSubAccountRoutesColumns holds the columns for the "ledger_sub_account_routes" table. + LedgerSubAccountRoutesColumns = []*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: "routing_key_version", Type: field.TypeString}, + {Name: "routing_key", Type: field.TypeString}, + {Name: "currency", Type: field.TypeString}, + {Name: "tax_code", Type: field.TypeString, Nullable: true}, + {Name: "tax_behavior", Type: field.TypeString, Nullable: true}, + {Name: "features", Type: field.TypeOther, Nullable: true, SchemaType: map[string]string{"postgres": "text[]"}}, + {Name: "cost_basis", Type: field.TypeOther, Nullable: true, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "credit_priority", Type: field.TypeInt, Nullable: true}, + {Name: "transaction_authorization_status", Type: field.TypeString, Nullable: true}, + {Name: "account_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // LedgerSubAccountRoutesTable holds the schema information for the "ledger_sub_account_routes" table. + LedgerSubAccountRoutesTable = &schema.Table{ + Name: "ledger_sub_account_routes", + Columns: LedgerSubAccountRoutesColumns, + PrimaryKey: []*schema.Column{LedgerSubAccountRoutesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "ledger_sub_account_routes_ledger_accounts_sub_account_routes", + Columns: []*schema.Column{LedgerSubAccountRoutesColumns[14]}, + RefColumns: []*schema.Column{LedgerAccountsColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "ledgersubaccountroute_id", + Unique: true, + Columns: []*schema.Column{LedgerSubAccountRoutesColumns[0]}, + }, + { + Name: "ledgersubaccountroute_namespace", + Unique: false, + Columns: []*schema.Column{LedgerSubAccountRoutesColumns[1]}, + }, + { + Name: "ledgersubaccountroute_namespace_account_id_routing_key_version_routing_key", + Unique: true, + Columns: []*schema.Column{LedgerSubAccountRoutesColumns[1], LedgerSubAccountRoutesColumns[14], LedgerSubAccountRoutesColumns[5], LedgerSubAccountRoutesColumns[6]}, + }, + }, + } + // LedgerTransactionsColumns holds the columns for the "ledger_transactions" table. + LedgerTransactionsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "booked_at", Type: field.TypeTime}, + {Name: "group_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // LedgerTransactionsTable holds the schema information for the "ledger_transactions" table. + LedgerTransactionsTable = &schema.Table{ + Name: "ledger_transactions", + Columns: LedgerTransactionsColumns, + PrimaryKey: []*schema.Column{LedgerTransactionsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "ledger_transactions_ledger_transaction_groups_transactions", + Columns: []*schema.Column{LedgerTransactionsColumns[7]}, + RefColumns: []*schema.Column{LedgerTransactionGroupsColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "ledgertransaction_id", + Unique: true, + Columns: []*schema.Column{LedgerTransactionsColumns[0]}, + }, + { + Name: "ledgertransaction_namespace", + Unique: false, + Columns: []*schema.Column{LedgerTransactionsColumns[1]}, + }, + { + Name: "ledgertransaction_annotations", + Unique: false, + Columns: []*schema.Column{LedgerTransactionsColumns[2]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "ledgertransaction_namespace_id", + Unique: true, + Columns: []*schema.Column{LedgerTransactionsColumns[1], LedgerTransactionsColumns[0]}, + }, + { + Name: "ledgertransaction_namespace_group_id", + Unique: false, + Columns: []*schema.Column{LedgerTransactionsColumns[1], LedgerTransactionsColumns[7]}, + }, + { + Name: "ledgertransaction_namespace_booked_at", + Unique: false, + Columns: []*schema.Column{LedgerTransactionsColumns[1], LedgerTransactionsColumns[6]}, + }, + }, + } + // LedgerTransactionGroupsColumns holds the columns for the "ledger_transaction_groups" table. + LedgerTransactionGroupsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + } + // LedgerTransactionGroupsTable holds the schema information for the "ledger_transaction_groups" table. + LedgerTransactionGroupsTable = &schema.Table{ + Name: "ledger_transaction_groups", + Columns: LedgerTransactionGroupsColumns, + PrimaryKey: []*schema.Column{LedgerTransactionGroupsColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "ledgertransactiongroup_id", + Unique: true, + Columns: []*schema.Column{LedgerTransactionGroupsColumns[0]}, + }, + { + Name: "ledgertransactiongroup_namespace", + Unique: false, + Columns: []*schema.Column{LedgerTransactionGroupsColumns[1]}, + }, + { + Name: "ledgertransactiongroup_annotations", + Unique: false, + Columns: []*schema.Column{LedgerTransactionGroupsColumns[2]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "ledgertransactiongroup_namespace_id", + Unique: true, + Columns: []*schema.Column{LedgerTransactionGroupsColumns[1], LedgerTransactionGroupsColumns[0]}, + }, + }, + } + // MetersColumns holds the columns for the "meters" table. + MetersColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "key", Type: field.TypeString}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "event_type", Type: field.TypeString}, + {Name: "value_property", Type: field.TypeString, Nullable: true}, + {Name: "group_by", Type: field.TypeJSON, Nullable: true}, + {Name: "aggregation", Type: field.TypeEnum, Enums: []string{"SUM", "COUNT", "AVG", "MIN", "MAX", "UNIQUE_COUNT", "LATEST"}}, + {Name: "event_from", Type: field.TypeTime, Nullable: true}, + } + // MetersTable holds the schema information for the "meters" table. + MetersTable = &schema.Table{ + Name: "meters", + Columns: MetersColumns, + PrimaryKey: []*schema.Column{MetersColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "meter_id", + Unique: true, + Columns: []*schema.Column{MetersColumns[0]}, + }, + { + Name: "meter_namespace", + Unique: false, + Columns: []*schema.Column{MetersColumns[1]}, + }, + { + Name: "meter_namespace_id", + Unique: true, + Columns: []*schema.Column{MetersColumns[1], MetersColumns[0]}, + }, + { + Name: "meter_namespace_key_deleted_at", + Unique: true, + Columns: []*schema.Column{MetersColumns[1], MetersColumns[8], MetersColumns[5]}, + }, + { + Name: "meter_annotations", + Unique: false, + Columns: []*schema.Column{MetersColumns[9]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "meter_namespace_key", + Unique: true, + Columns: []*schema.Column{MetersColumns[1], MetersColumns[8]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + { + Name: "meter_namespace_event_type", + Unique: false, + Columns: []*schema.Column{MetersColumns[1], MetersColumns[10]}, + }, + }, + } + // NotificationChannelsColumns holds the columns for the "notification_channels" table. + NotificationChannelsColumns = []*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: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "type", Type: field.TypeEnum, Enums: []string{"WEBHOOK"}}, + {Name: "name", Type: field.TypeString}, + {Name: "disabled", Type: field.TypeBool, Nullable: true, Default: false}, + {Name: "config", Type: field.TypeString, SchemaType: map[string]string{"postgres": "jsonb"}}, + } + // NotificationChannelsTable holds the schema information for the "notification_channels" table. + NotificationChannelsTable = &schema.Table{ + Name: "notification_channels", + Columns: NotificationChannelsColumns, + PrimaryKey: []*schema.Column{NotificationChannelsColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "notificationchannel_id", + Unique: true, + Columns: []*schema.Column{NotificationChannelsColumns[0]}, + }, + { + Name: "notificationchannel_namespace", + Unique: false, + Columns: []*schema.Column{NotificationChannelsColumns[1]}, + }, + { + Name: "notificationchannel_annotations", + Unique: false, + Columns: []*schema.Column{NotificationChannelsColumns[5]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "notificationchannel_namespace_id", + Unique: false, + Columns: []*schema.Column{NotificationChannelsColumns[1], NotificationChannelsColumns[0]}, + }, + { + Name: "notificationchannel_namespace_type", + Unique: false, + Columns: []*schema.Column{NotificationChannelsColumns[1], NotificationChannelsColumns[7]}, + }, + }, + } + // NotificationEventsColumns holds the columns for the "notification_events" table. + NotificationEventsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "type", Type: field.TypeEnum, Enums: []string{"entitlements.balance.threshold", "entitlements.reset", "invoice.created", "invoice.updated"}}, + {Name: "payload", Type: field.TypeString, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "rule_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // NotificationEventsTable holds the schema information for the "notification_events" table. + NotificationEventsTable = &schema.Table{ + Name: "notification_events", + Columns: NotificationEventsColumns, + PrimaryKey: []*schema.Column{NotificationEventsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "notification_events_notification_rules_events", + Columns: []*schema.Column{NotificationEventsColumns[6]}, + RefColumns: []*schema.Column{NotificationRulesColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "notificationevent_id", + Unique: true, + Columns: []*schema.Column{NotificationEventsColumns[0]}, + }, + { + Name: "notificationevent_namespace", + Unique: false, + Columns: []*schema.Column{NotificationEventsColumns[1]}, + }, + { + Name: "notificationevent_annotations", + Unique: false, + Columns: []*schema.Column{NotificationEventsColumns[2]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "notificationevent_namespace_id", + Unique: false, + Columns: []*schema.Column{NotificationEventsColumns[1], NotificationEventsColumns[0]}, + }, + { + Name: "notificationevent_namespace_type", + Unique: false, + Columns: []*schema.Column{NotificationEventsColumns[1], NotificationEventsColumns[4]}, + }, + }, + } + // NotificationEventDeliveryStatusColumns holds the columns for the "notification_event_delivery_status" table. + NotificationEventDeliveryStatusColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "event_id", Type: field.TypeString}, + {Name: "channel_id", Type: field.TypeString}, + {Name: "state", Type: field.TypeEnum, Enums: []string{"SUCCESS", "FAILED", "SENDING", "PENDING", "RESENDING"}, Default: "PENDING"}, + {Name: "reason", Type: field.TypeString, Nullable: true}, + {Name: "next_attempt_at", Type: field.TypeTime, Nullable: true}, + {Name: "attempts", Type: field.TypeJSON, Nullable: true}, + } + // NotificationEventDeliveryStatusTable holds the schema information for the "notification_event_delivery_status" table. + NotificationEventDeliveryStatusTable = &schema.Table{ + Name: "notification_event_delivery_status", + Columns: NotificationEventDeliveryStatusColumns, + PrimaryKey: []*schema.Column{NotificationEventDeliveryStatusColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "notificationeventdeliverystatus_id", + Unique: true, + Columns: []*schema.Column{NotificationEventDeliveryStatusColumns[0]}, + }, + { + Name: "notificationeventdeliverystatus_namespace", + Unique: false, + Columns: []*schema.Column{NotificationEventDeliveryStatusColumns[1]}, + }, + { + Name: "notificationeventdeliverystatus_annotations", + Unique: false, + Columns: []*schema.Column{NotificationEventDeliveryStatusColumns[2]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "notificationeventdeliverystatus_namespace_id", + Unique: false, + Columns: []*schema.Column{NotificationEventDeliveryStatusColumns[1], NotificationEventDeliveryStatusColumns[0]}, + }, + { + Name: "notificationeventdeliverystatus_namespace_event_id_channel_id", + Unique: false, + Columns: []*schema.Column{NotificationEventDeliveryStatusColumns[1], NotificationEventDeliveryStatusColumns[5], NotificationEventDeliveryStatusColumns[6]}, + }, + { + Name: "notificationeventdeliverystatus_namespace_state", + Unique: false, + Columns: []*schema.Column{NotificationEventDeliveryStatusColumns[1], NotificationEventDeliveryStatusColumns[7]}, + }, + { + Name: "notificationeventdeliverystatus_namespace_state_next_attempt_at", + Unique: false, + Columns: []*schema.Column{NotificationEventDeliveryStatusColumns[1], NotificationEventDeliveryStatusColumns[7], NotificationEventDeliveryStatusColumns[9]}, + }, + }, + } + // NotificationRulesColumns holds the columns for the "notification_rules" table. + NotificationRulesColumns = []*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: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "type", Type: field.TypeEnum, Enums: []string{"entitlements.balance.threshold", "entitlements.reset", "invoice.created", "invoice.updated"}}, + {Name: "name", Type: field.TypeString}, + {Name: "disabled", Type: field.TypeBool, Nullable: true, Default: false}, + {Name: "config", Type: field.TypeString, SchemaType: map[string]string{"postgres": "jsonb"}}, + } + // NotificationRulesTable holds the schema information for the "notification_rules" table. + NotificationRulesTable = &schema.Table{ + Name: "notification_rules", + Columns: NotificationRulesColumns, + PrimaryKey: []*schema.Column{NotificationRulesColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "notificationrule_id", + Unique: true, + Columns: []*schema.Column{NotificationRulesColumns[0]}, + }, + { + Name: "notificationrule_namespace", + Unique: false, + Columns: []*schema.Column{NotificationRulesColumns[1]}, + }, + { + Name: "notificationrule_annotations", + Unique: false, + Columns: []*schema.Column{NotificationRulesColumns[5]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "notificationrule_namespace_id", + Unique: false, + Columns: []*schema.Column{NotificationRulesColumns[1], NotificationRulesColumns[0]}, + }, + { + Name: "notificationrule_namespace_type", + Unique: false, + Columns: []*schema.Column{NotificationRulesColumns[1], NotificationRulesColumns[7]}, + }, + }, + } + // OrganizationDefaultTaxCodesColumns holds the columns for the "organization_default_tax_codes" table. + OrganizationDefaultTaxCodesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "namespace", Type: field.TypeString}, + {Name: "invoicing_tax_code_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "credit_grant_tax_code_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // OrganizationDefaultTaxCodesTable holds the schema information for the "organization_default_tax_codes" table. + OrganizationDefaultTaxCodesTable = &schema.Table{ + Name: "organization_default_tax_codes", + Columns: OrganizationDefaultTaxCodesColumns, + PrimaryKey: []*schema.Column{OrganizationDefaultTaxCodesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "org_dtc_invoicing_tax_code_fk", + Columns: []*schema.Column{OrganizationDefaultTaxCodesColumns[5]}, + RefColumns: []*schema.Column{TaxCodesColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "org_dtc_credit_grant_tax_code_fk", + Columns: []*schema.Column{OrganizationDefaultTaxCodesColumns[6]}, + RefColumns: []*schema.Column{TaxCodesColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "organizationdefaulttaxcodes_id", + Unique: true, + Columns: []*schema.Column{OrganizationDefaultTaxCodesColumns[0]}, + }, + { + Name: "organizationdefaulttaxcodes_namespace", + Unique: true, + Columns: []*schema.Column{OrganizationDefaultTaxCodesColumns[4]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + }, + } + // PlansColumns holds the columns for the "plans" table. + PlansColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "key", Type: field.TypeString}, + {Name: "version", Type: field.TypeInt}, + {Name: "currency", Type: field.TypeString, Default: "USD"}, + {Name: "billing_cadence", Type: field.TypeString}, + {Name: "pro_rating_config", Type: field.TypeString, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "effective_from", Type: field.TypeTime, Nullable: true}, + {Name: "effective_to", Type: field.TypeTime, Nullable: true}, + {Name: "settlement_mode", Type: field.TypeEnum, Enums: []string{"credit_then_invoice", "credit_only"}, Default: "credit_then_invoice"}, + } + // PlansTable holds the schema information for the "plans" table. + PlansTable = &schema.Table{ + Name: "plans", + Columns: PlansColumns, + PrimaryKey: []*schema.Column{PlansColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "plan_id", + Unique: true, + Columns: []*schema.Column{PlansColumns[0]}, + }, + { + Name: "plan_namespace", + Unique: false, + Columns: []*schema.Column{PlansColumns[1]}, + }, + { + Name: "plan_namespace_id", + Unique: true, + Columns: []*schema.Column{PlansColumns[1], PlansColumns[0]}, + }, + { + Name: "plan_namespace_key_deleted_at", + Unique: true, + Columns: []*schema.Column{PlansColumns[1], PlansColumns[8], PlansColumns[5]}, + }, + { + Name: "plan_namespace_key_version", + Unique: true, + Columns: []*schema.Column{PlansColumns[1], PlansColumns[8], PlansColumns[9]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + }, + } + // PlanAddonsColumns holds the columns for the "plan_addons" table. + PlanAddonsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "from_plan_phase", Type: field.TypeString}, + {Name: "max_quantity", Type: field.TypeInt, Nullable: true}, + {Name: "addon_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "plan_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // PlanAddonsTable holds the schema information for the "plan_addons" table. + PlanAddonsTable = &schema.Table{ + Name: "plan_addons", + Columns: PlanAddonsColumns, + PrimaryKey: []*schema.Column{PlanAddonsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "plan_addons_addons_plans", + Columns: []*schema.Column{PlanAddonsColumns[9]}, + RefColumns: []*schema.Column{AddonsColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "plan_addons_plans_addons", + Columns: []*schema.Column{PlanAddonsColumns[10]}, + RefColumns: []*schema.Column{PlansColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "planaddon_id", + Unique: true, + Columns: []*schema.Column{PlanAddonsColumns[0]}, + }, + { + Name: "planaddon_namespace", + Unique: false, + Columns: []*schema.Column{PlanAddonsColumns[1]}, + }, + { + Name: "planaddon_annotations", + Unique: false, + Columns: []*schema.Column{PlanAddonsColumns[3]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "planaddon_namespace_plan_id_addon_id", + Unique: true, + Columns: []*schema.Column{PlanAddonsColumns[1], PlanAddonsColumns[10], PlanAddonsColumns[9]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + }, + } + // PlanPhasesColumns holds the columns for the "plan_phases" table. + PlanPhasesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "key", Type: field.TypeString}, + {Name: "index", Type: field.TypeUint8}, + {Name: "duration", Type: field.TypeString, Nullable: true}, + {Name: "plan_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // PlanPhasesTable holds the schema information for the "plan_phases" table. + PlanPhasesTable = &schema.Table{ + Name: "plan_phases", + Columns: PlanPhasesColumns, + PrimaryKey: []*schema.Column{PlanPhasesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "plan_phases_plans_phases", + Columns: []*schema.Column{PlanPhasesColumns[11]}, + RefColumns: []*schema.Column{PlansColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "planphase_id", + Unique: true, + Columns: []*schema.Column{PlanPhasesColumns[0]}, + }, + { + Name: "planphase_namespace", + Unique: false, + Columns: []*schema.Column{PlanPhasesColumns[1]}, + }, + { + Name: "planphase_namespace_id", + Unique: true, + Columns: []*schema.Column{PlanPhasesColumns[1], PlanPhasesColumns[0]}, + }, + { + Name: "planphase_namespace_key_deleted_at", + Unique: true, + Columns: []*schema.Column{PlanPhasesColumns[1], PlanPhasesColumns[8], PlanPhasesColumns[5]}, + }, + { + Name: "planphase_namespace_key", + Unique: false, + Columns: []*schema.Column{PlanPhasesColumns[1], PlanPhasesColumns[8]}, + }, + { + Name: "planphase_plan_id_key", + Unique: true, + Columns: []*schema.Column{PlanPhasesColumns[11], PlanPhasesColumns[8]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + { + Name: "planphase_plan_id_index", + Unique: true, + Columns: []*schema.Column{PlanPhasesColumns[11], PlanPhasesColumns[9]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + }, + } + // PlanRateCardsColumns holds the columns for the "plan_rate_cards" table. + PlanRateCardsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "key", Type: field.TypeString}, + {Name: "tax_behavior", Type: field.TypeEnum, Nullable: true, Enums: []string{"inclusive", "exclusive"}}, + {Name: "type", Type: field.TypeEnum, Enums: []string{"flat_fee", "usage_based"}}, + {Name: "feature_key", Type: field.TypeString, Nullable: true}, + {Name: "entitlement_template", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "tax_config", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "billing_cadence", Type: field.TypeString, Nullable: true}, + {Name: "price", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "discounts", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "unit_config", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "feature_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "phase_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "tax_code_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // PlanRateCardsTable holds the schema information for the "plan_rate_cards" table. + PlanRateCardsTable = &schema.Table{ + Name: "plan_rate_cards", + Columns: PlanRateCardsColumns, + PrimaryKey: []*schema.Column{PlanRateCardsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "plan_rate_cards_features_ratecard", + Columns: []*schema.Column{PlanRateCardsColumns[18]}, + RefColumns: []*schema.Column{FeaturesColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "plan_rate_cards_plan_phases_ratecards", + Columns: []*schema.Column{PlanRateCardsColumns[19]}, + RefColumns: []*schema.Column{PlanPhasesColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "plan_rate_cards_tax_codes_plan_rate_cards", + Columns: []*schema.Column{PlanRateCardsColumns[20]}, + RefColumns: []*schema.Column{TaxCodesColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + Indexes: []*schema.Index{ + { + Name: "planratecard_id", + Unique: true, + Columns: []*schema.Column{PlanRateCardsColumns[0]}, + }, + { + Name: "planratecard_namespace", + Unique: false, + Columns: []*schema.Column{PlanRateCardsColumns[1]}, + }, + { + Name: "planratecard_namespace_id", + Unique: true, + Columns: []*schema.Column{PlanRateCardsColumns[1], PlanRateCardsColumns[0]}, + }, + { + Name: "planratecard_namespace_key_deleted_at", + Unique: true, + Columns: []*schema.Column{PlanRateCardsColumns[1], PlanRateCardsColumns[8], PlanRateCardsColumns[5]}, + }, + { + Name: "planratecard_tax_code_id", + Unique: false, + Columns: []*schema.Column{PlanRateCardsColumns[20]}, + }, + { + Name: "planratecard_phase_id_key", + Unique: true, + Columns: []*schema.Column{PlanRateCardsColumns[19], PlanRateCardsColumns[8]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + { + Name: "planratecard_phase_id_feature_key", + Unique: true, + Columns: []*schema.Column{PlanRateCardsColumns[19], PlanRateCardsColumns[11]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + }, + } + // SubjectsColumns holds the columns for the "subjects" table. + SubjectsColumns = []*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: "key", Type: field.TypeString}, + {Name: "display_name", Type: field.TypeString, Nullable: true}, + {Name: "stripe_customer_id", Type: field.TypeString, Nullable: true}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + } + // SubjectsTable holds the schema information for the "subjects" table. + SubjectsTable = &schema.Table{ + Name: "subjects", + Columns: SubjectsColumns, + PrimaryKey: []*schema.Column{SubjectsColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "subject_id", + Unique: true, + Columns: []*schema.Column{SubjectsColumns[0]}, + }, + { + Name: "subject_namespace", + Unique: false, + Columns: []*schema.Column{SubjectsColumns[1]}, + }, + { + Name: "subject_namespace_key", + Unique: true, + Columns: []*schema.Column{SubjectsColumns[1], SubjectsColumns[5]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + { + Name: "subject_namespace_key_deleted_at_unique", + Unique: true, + Columns: []*schema.Column{SubjectsColumns[1], SubjectsColumns[5], SubjectsColumns[4]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + { + Name: "subject_namespace_key_deleted_at", + Unique: false, + Columns: []*schema.Column{SubjectsColumns[1], SubjectsColumns[5], SubjectsColumns[4]}, + }, + { + Name: "subject_namespace_id", + Unique: true, + Columns: []*schema.Column{SubjectsColumns[1], SubjectsColumns[0]}, + }, + { + Name: "subject_display_name", + Unique: false, + Columns: []*schema.Column{SubjectsColumns[6]}, + }, + { + Name: "subject_created_at_id", + Unique: false, + Columns: []*schema.Column{SubjectsColumns[2], SubjectsColumns[0]}, + }, + }, + } + // SubscriptionsColumns holds the columns for the "subscriptions" table. + SubscriptionsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "active_from", Type: field.TypeTime}, + {Name: "active_to", Type: field.TypeTime, Nullable: true}, + {Name: "name", Type: field.TypeString, Default: "Subscription"}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "currency", Type: field.TypeString, Size: 3}, + {Name: "billing_anchor", Type: field.TypeTime}, + {Name: "billing_cadence", Type: field.TypeString}, + {Name: "pro_rating_config", Type: field.TypeString, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "settlement_mode", Type: field.TypeEnum, Enums: []string{"credit_then_invoice", "credit_only"}, Default: "credit_then_invoice"}, + {Name: "customer_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "plan_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // SubscriptionsTable holds the schema information for the "subscriptions" table. + SubscriptionsTable = &schema.Table{ + Name: "subscriptions", + Columns: SubscriptionsColumns, + PrimaryKey: []*schema.Column{SubscriptionsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "subscriptions_customers_subscription", + Columns: []*schema.Column{SubscriptionsColumns[16]}, + RefColumns: []*schema.Column{CustomersColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "subscriptions_plans_subscriptions", + Columns: []*schema.Column{SubscriptionsColumns[17]}, + RefColumns: []*schema.Column{PlansColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + Indexes: []*schema.Index{ + { + Name: "subscription_id", + Unique: true, + Columns: []*schema.Column{SubscriptionsColumns[0]}, + }, + { + Name: "subscription_namespace", + Unique: false, + Columns: []*schema.Column{SubscriptionsColumns[1]}, + }, + { + Name: "subscription_annotations", + Unique: false, + Columns: []*schema.Column{SubscriptionsColumns[2]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "subscription_namespace_id", + Unique: false, + Columns: []*schema.Column{SubscriptionsColumns[1], SubscriptionsColumns[0]}, + }, + { + Name: "subscription_namespace_customer_id", + Unique: false, + Columns: []*schema.Column{SubscriptionsColumns[1], SubscriptionsColumns[16]}, + }, + }, + } + // SubscriptionAddonsColumns holds the columns for the "subscription_addons" table. + SubscriptionAddonsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "addon_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "subscription_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // SubscriptionAddonsTable holds the schema information for the "subscription_addons" table. + SubscriptionAddonsTable = &schema.Table{ + Name: "subscription_addons", + Columns: SubscriptionAddonsColumns, + PrimaryKey: []*schema.Column{SubscriptionAddonsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "subscription_addons_addons_subscription_addons", + Columns: []*schema.Column{SubscriptionAddonsColumns[6]}, + RefColumns: []*schema.Column{AddonsColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "subscription_addons_subscriptions_addons", + Columns: []*schema.Column{SubscriptionAddonsColumns[7]}, + RefColumns: []*schema.Column{SubscriptionsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "subscriptionaddon_id", + Unique: true, + Columns: []*schema.Column{SubscriptionAddonsColumns[0]}, + }, + { + Name: "subscriptionaddon_namespace", + Unique: false, + Columns: []*schema.Column{SubscriptionAddonsColumns[1]}, + }, + { + Name: "subscriptionaddon_namespace_subscription_id_addon_id", + Unique: true, + Columns: []*schema.Column{SubscriptionAddonsColumns[1], SubscriptionAddonsColumns[7], SubscriptionAddonsColumns[6]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + }, + } + // SubscriptionAddonQuantitiesColumns holds the columns for the "subscription_addon_quantities" table. + SubscriptionAddonQuantitiesColumns = []*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: "active_from", Type: field.TypeTime}, + {Name: "quantity", Type: field.TypeInt, Default: 1}, + {Name: "subscription_addon_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // SubscriptionAddonQuantitiesTable holds the schema information for the "subscription_addon_quantities" table. + SubscriptionAddonQuantitiesTable = &schema.Table{ + Name: "subscription_addon_quantities", + Columns: SubscriptionAddonQuantitiesColumns, + PrimaryKey: []*schema.Column{SubscriptionAddonQuantitiesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "subscription_addon_quantities_subscription_addons_quantities", + Columns: []*schema.Column{SubscriptionAddonQuantitiesColumns[7]}, + RefColumns: []*schema.Column{SubscriptionAddonsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "subscriptionaddonquantity_id", + Unique: true, + Columns: []*schema.Column{SubscriptionAddonQuantitiesColumns[0]}, + }, + { + Name: "subscriptionaddonquantity_namespace", + Unique: false, + Columns: []*schema.Column{SubscriptionAddonQuantitiesColumns[1]}, + }, + { + Name: "subscriptionaddonquantity_subscription_addon_id", + Unique: false, + Columns: []*schema.Column{SubscriptionAddonQuantitiesColumns[7]}, + }, + }, + } + // SubscriptionBillingSyncStatesColumns holds the columns for the "subscription_billing_sync_states" table. + SubscriptionBillingSyncStatesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "has_billables", Type: field.TypeBool}, + {Name: "synced_at", Type: field.TypeTime}, + {Name: "next_sync_after", Type: field.TypeTime, Nullable: true}, + {Name: "subscription_id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // SubscriptionBillingSyncStatesTable holds the schema information for the "subscription_billing_sync_states" table. + SubscriptionBillingSyncStatesTable = &schema.Table{ + Name: "subscription_billing_sync_states", + Columns: SubscriptionBillingSyncStatesColumns, + PrimaryKey: []*schema.Column{SubscriptionBillingSyncStatesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "subscription_billing_sync_states_subscriptions_billing_sync_state", + Columns: []*schema.Column{SubscriptionBillingSyncStatesColumns[5]}, + RefColumns: []*schema.Column{SubscriptionsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "subscriptionbillingsyncstate_id", + Unique: true, + Columns: []*schema.Column{SubscriptionBillingSyncStatesColumns[0]}, + }, + { + Name: "subscriptionbillingsyncstate_namespace", + Unique: false, + Columns: []*schema.Column{SubscriptionBillingSyncStatesColumns[1]}, + }, + { + Name: "subscriptionbillingsyncstate_namespace_subscription_id", + Unique: true, + Columns: []*schema.Column{SubscriptionBillingSyncStatesColumns[1], SubscriptionBillingSyncStatesColumns[5]}, + }, + }, + } + // SubscriptionItemsColumns holds the columns for the "subscription_items" table. + SubscriptionItemsColumns = []*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: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "tax_behavior", Type: field.TypeEnum, Nullable: true, Enums: []string{"inclusive", "exclusive"}}, + {Name: "annotations", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "active_from", Type: field.TypeTime}, + {Name: "active_to", Type: field.TypeTime, Nullable: true}, + {Name: "key", Type: field.TypeString}, + {Name: "restarts_billing_period", Type: field.TypeBool, Nullable: true}, + {Name: "active_from_override_relative_to_phase_start", Type: field.TypeString, Nullable: true}, + {Name: "active_to_override_relative_to_phase_start", Type: field.TypeString, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "feature_key", Type: field.TypeString, Nullable: true}, + {Name: "entitlement_template", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "tax_config", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "billing_cadence", Type: field.TypeString, Nullable: true}, + {Name: "price", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "discounts", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "unit_config", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "entitlement_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "phase_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "tax_code_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // SubscriptionItemsTable holds the schema information for the "subscription_items" table. + SubscriptionItemsTable = &schema.Table{ + Name: "subscription_items", + Columns: SubscriptionItemsColumns, + PrimaryKey: []*schema.Column{SubscriptionItemsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "subscription_items_entitlements_subscription_item", + Columns: []*schema.Column{SubscriptionItemsColumns[23]}, + RefColumns: []*schema.Column{EntitlementsColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "subscription_items_subscription_phases_items", + Columns: []*schema.Column{SubscriptionItemsColumns[24]}, + RefColumns: []*schema.Column{SubscriptionPhasesColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "subscription_items_tax_codes_subscription_items", + Columns: []*schema.Column{SubscriptionItemsColumns[25]}, + RefColumns: []*schema.Column{TaxCodesColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + Indexes: []*schema.Index{ + { + Name: "subscriptionitem_id", + Unique: true, + Columns: []*schema.Column{SubscriptionItemsColumns[0]}, + }, + { + Name: "subscriptionitem_namespace", + Unique: false, + Columns: []*schema.Column{SubscriptionItemsColumns[1]}, + }, + { + Name: "subscriptionitem_tax_code_id", + Unique: false, + Columns: []*schema.Column{SubscriptionItemsColumns[25]}, + }, + { + Name: "subscriptionitem_namespace_id", + Unique: false, + Columns: []*schema.Column{SubscriptionItemsColumns[1], SubscriptionItemsColumns[0]}, + }, + { + Name: "subscriptionitem_namespace_phase_id_key", + Unique: false, + Columns: []*schema.Column{SubscriptionItemsColumns[1], SubscriptionItemsColumns[24], SubscriptionItemsColumns[10]}, + }, + }, + } + // SubscriptionPhasesColumns holds the columns for the "subscription_phases" table. + SubscriptionPhasesColumns = []*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: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "key", Type: field.TypeString}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "active_from", Type: field.TypeTime}, + {Name: "sort_hint", Type: field.TypeUint8, Nullable: true}, + {Name: "subscription_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // SubscriptionPhasesTable holds the schema information for the "subscription_phases" table. + SubscriptionPhasesTable = &schema.Table{ + Name: "subscription_phases", + Columns: SubscriptionPhasesColumns, + PrimaryKey: []*schema.Column{SubscriptionPhasesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "subscription_phases_subscriptions_phases", + Columns: []*schema.Column{SubscriptionPhasesColumns[11]}, + RefColumns: []*schema.Column{SubscriptionsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "subscriptionphase_id", + Unique: true, + Columns: []*schema.Column{SubscriptionPhasesColumns[0]}, + }, + { + Name: "subscriptionphase_namespace", + Unique: false, + Columns: []*schema.Column{SubscriptionPhasesColumns[1]}, + }, + { + Name: "subscriptionphase_namespace_id", + Unique: false, + Columns: []*schema.Column{SubscriptionPhasesColumns[1], SubscriptionPhasesColumns[0]}, + }, + { + Name: "subscriptionphase_namespace_subscription_id", + Unique: false, + Columns: []*schema.Column{SubscriptionPhasesColumns[1], SubscriptionPhasesColumns[11]}, + }, + { + Name: "subscriptionphase_namespace_subscription_id_key", + Unique: false, + Columns: []*schema.Column{SubscriptionPhasesColumns[1], SubscriptionPhasesColumns[11], SubscriptionPhasesColumns[6]}, + }, + }, + } + // TaxCodesColumns holds the columns for the "tax_codes" table. + TaxCodesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + {Name: "key", Type: field.TypeString}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "app_mappings", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + } + // TaxCodesTable holds the schema information for the "tax_codes" table. + TaxCodesTable = &schema.Table{ + Name: "tax_codes", + Columns: TaxCodesColumns, + PrimaryKey: []*schema.Column{TaxCodesColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "taxcode_id", + Unique: true, + Columns: []*schema.Column{TaxCodesColumns[0]}, + }, + { + Name: "taxcode_namespace", + Unique: false, + Columns: []*schema.Column{TaxCodesColumns[1]}, + }, + { + Name: "taxcode_namespace_id", + Unique: true, + Columns: []*schema.Column{TaxCodesColumns[1], TaxCodesColumns[0]}, + }, + { + Name: "taxcode_namespace_key_deleted_at", + Unique: true, + Columns: []*schema.Column{TaxCodesColumns[1], TaxCodesColumns[8], TaxCodesColumns[5]}, + }, + { + Name: "taxcode_annotations", + Unique: false, + Columns: []*schema.Column{TaxCodesColumns[9]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "taxcode_namespace_key", + Unique: true, + Columns: []*schema.Column{TaxCodesColumns[1], TaxCodesColumns[8]}, + Annotation: &entsql.IndexAnnotation{ + Where: "deleted_at IS NULL", + }, + }, + }, + } + // UsageResetsColumns holds the columns for the "usage_resets" table. + UsageResetsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "reset_time", Type: field.TypeTime}, + {Name: "anchor", Type: field.TypeTime}, + {Name: "usage_period_interval", Type: field.TypeString}, + {Name: "entitlement_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // UsageResetsTable holds the schema information for the "usage_resets" table. + UsageResetsTable = &schema.Table{ + Name: "usage_resets", + Columns: UsageResetsColumns, + PrimaryKey: []*schema.Column{UsageResetsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "usage_resets_entitlements_usage_reset", + Columns: []*schema.Column{UsageResetsColumns[9]}, + RefColumns: []*schema.Column{EntitlementsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "usagereset_id", + Unique: true, + Columns: []*schema.Column{UsageResetsColumns[0]}, + }, + { + Name: "usagereset_namespace", + Unique: false, + Columns: []*schema.Column{UsageResetsColumns[1]}, + }, + { + Name: "usagereset_annotations", + Unique: false, + Columns: []*schema.Column{UsageResetsColumns[2]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + { + Name: "usagereset_namespace_entitlement_id", + Unique: false, + Columns: []*schema.Column{UsageResetsColumns[1], UsageResetsColumns[9]}, + }, + { + Name: "usagereset_namespace_entitlement_id_reset_time", + Unique: false, + Columns: []*schema.Column{UsageResetsColumns[1], UsageResetsColumns[9], UsageResetsColumns[6]}, + }, + }, + } + // NotificationChannelRulesColumns holds the columns for the "notification_channel_rules" table. + NotificationChannelRulesColumns = []*schema.Column{ + {Name: "notification_channel_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "notification_rule_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // NotificationChannelRulesTable holds the schema information for the "notification_channel_rules" table. + NotificationChannelRulesTable = &schema.Table{ + Name: "notification_channel_rules", + Columns: NotificationChannelRulesColumns, + PrimaryKey: []*schema.Column{NotificationChannelRulesColumns[0], NotificationChannelRulesColumns[1]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "notification_channel_rules_notification_channel_id", + Columns: []*schema.Column{NotificationChannelRulesColumns[0]}, + RefColumns: []*schema.Column{NotificationChannelsColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "notification_channel_rules_notification_rule_id", + Columns: []*schema.Column{NotificationChannelRulesColumns[1]}, + RefColumns: []*schema.Column{NotificationRulesColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + } + // NotificationEventDeliveryStatusEventsColumns holds the columns for the "notification_event_delivery_status_events" table. + NotificationEventDeliveryStatusEventsColumns = []*schema.Column{ + {Name: "notification_event_delivery_status_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "notification_event_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // NotificationEventDeliveryStatusEventsTable holds the schema information for the "notification_event_delivery_status_events" table. + NotificationEventDeliveryStatusEventsTable = &schema.Table{ + Name: "notification_event_delivery_status_events", + Columns: NotificationEventDeliveryStatusEventsColumns, + PrimaryKey: []*schema.Column{NotificationEventDeliveryStatusEventsColumns[0], NotificationEventDeliveryStatusEventsColumns[1]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "notification_event_delivery_status_events_notification_event_delivery_status_id", + Columns: []*schema.Column{NotificationEventDeliveryStatusEventsColumns[0]}, + RefColumns: []*schema.Column{NotificationEventDeliveryStatusColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "notification_event_delivery_status_events_notification_event_id", + Columns: []*schema.Column{NotificationEventDeliveryStatusEventsColumns[1]}, + RefColumns: []*schema.Column{NotificationEventsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + AddonsTable, + AddonRateCardsTable, + AppsTable, + AppCustomInvoicingsTable, + AppCustomInvoicingCustomersTable, + AppCustomersTable, + AppStripesTable, + AppStripeCustomersTable, + BalanceSnapshotsTable, + BillingCustomerLocksTable, + BillingCustomerOverridesTable, + BillingInvoicesTable, + BillingInvoiceFlatFeeLineConfigsTable, + BillingInvoiceLinesTable, + BillingInvoiceLineDiscountsTable, + BillingInvoiceLineUsageDiscountsTable, + BillingInvoiceSplitLineGroupsTable, + BillingInvoiceUsageBasedLineConfigsTable, + BillingInvoiceValidationIssuesTable, + BillingInvoiceWriteSchemaLevelsTable, + BillingProfilesTable, + BillingSequenceNumbersTable, + BillingStandardInvoiceDetailedLinesTable, + BillingStandardInvoiceDetailedLineAmountDiscountsTable, + BillingWorkflowConfigsTable, + ChargesTable, + ChargeCreditPurchasesTable, + ChargeCreditPurchaseCreditGrantsTable, + ChargeCreditPurchaseExternalPaymentsTable, + ChargeCreditPurchaseInvoicedPaymentsTable, + ChargeFlatFeesTable, + ChargeFlatFeeOverridesTable, + ChargeFlatFeeRunsTable, + ChargeFlatFeeRunCreditAllocationsTable, + ChargeFlatFeeRunDetailedLinesTable, + ChargeFlatFeeRunInvoicedUsagesTable, + ChargeFlatFeeRunPaymentsTable, + ChargeUsageBasedTable, + ChargeUsageBasedOverridesTable, + ChargeUsageBasedRunCreditAllocationsTable, + ChargeUsageBasedRunDetailedLineTable, + ChargeUsageBasedRunInvoicedUsagesTable, + ChargeUsageBasedRunPaymentsTable, + ChargeUsageBasedRunsTable, + CreditRealizationLineagesTable, + CreditRealizationLineageSegmentsTable, + CurrencyCostBasesTable, + CustomCurrenciesTable, + CustomersTable, + CustomerSubjectsTable, + EntitlementsTable, + FeaturesTable, + GrantsTable, + LlmCostPricesTable, + LedgerAccountsTable, + LedgerBreakageRecordsTable, + LedgerCreditVoidRecordsTable, + LedgerCustomerAccountsTable, + LedgerEntriesTable, + LedgerSubAccountsTable, + LedgerSubAccountRoutesTable, + LedgerTransactionsTable, + LedgerTransactionGroupsTable, + MetersTable, + NotificationChannelsTable, + NotificationEventsTable, + NotificationEventDeliveryStatusTable, + NotificationRulesTable, + OrganizationDefaultTaxCodesTable, + PlansTable, + PlanAddonsTable, + PlanPhasesTable, + PlanRateCardsTable, + SubjectsTable, + SubscriptionsTable, + SubscriptionAddonsTable, + SubscriptionAddonQuantitiesTable, + SubscriptionBillingSyncStatesTable, + SubscriptionItemsTable, + SubscriptionPhasesTable, + TaxCodesTable, + UsageResetsTable, + NotificationChannelRulesTable, + NotificationEventDeliveryStatusEventsTable, + } +) + +func init() { + AddonRateCardsTable.ForeignKeys[0].RefTable = AddonsTable + AddonRateCardsTable.ForeignKeys[1].RefTable = FeaturesTable + AddonRateCardsTable.ForeignKeys[2].RefTable = TaxCodesTable + AppCustomInvoicingsTable.ForeignKeys[0].RefTable = AppsTable + AppCustomInvoicingCustomersTable.ForeignKeys[0].RefTable = AppCustomInvoicingsTable + AppCustomInvoicingCustomersTable.ForeignKeys[1].RefTable = CustomersTable + AppCustomersTable.ForeignKeys[0].RefTable = AppsTable + AppCustomersTable.ForeignKeys[1].RefTable = CustomersTable + AppStripesTable.ForeignKeys[0].RefTable = AppsTable + AppStripeCustomersTable.ForeignKeys[0].RefTable = AppStripesTable + AppStripeCustomersTable.ForeignKeys[1].RefTable = CustomersTable + BalanceSnapshotsTable.ForeignKeys[0].RefTable = EntitlementsTable + BillingCustomerOverridesTable.ForeignKeys[0].RefTable = BillingProfilesTable + BillingCustomerOverridesTable.ForeignKeys[1].RefTable = CustomersTable + BillingCustomerOverridesTable.ForeignKeys[2].RefTable = TaxCodesTable + BillingInvoicesTable.ForeignKeys[0].RefTable = AppsTable + BillingInvoicesTable.ForeignKeys[1].RefTable = AppsTable + BillingInvoicesTable.ForeignKeys[2].RefTable = AppsTable + BillingInvoicesTable.ForeignKeys[3].RefTable = BillingProfilesTable + BillingInvoicesTable.ForeignKeys[4].RefTable = BillingWorkflowConfigsTable + BillingInvoicesTable.ForeignKeys[5].RefTable = CustomersTable + BillingInvoiceLinesTable.ForeignKeys[0].RefTable = BillingInvoicesTable + BillingInvoiceLinesTable.ForeignKeys[1].RefTable = BillingInvoiceFlatFeeLineConfigsTable + BillingInvoiceLinesTable.ForeignKeys[2].RefTable = BillingInvoiceUsageBasedLineConfigsTable + BillingInvoiceLinesTable.ForeignKeys[3].RefTable = BillingInvoiceLinesTable + BillingInvoiceLinesTable.ForeignKeys[4].RefTable = BillingInvoiceSplitLineGroupsTable + BillingInvoiceLinesTable.ForeignKeys[5].RefTable = ChargesTable + BillingInvoiceLinesTable.ForeignKeys[6].RefTable = SubscriptionsTable + BillingInvoiceLinesTable.ForeignKeys[7].RefTable = SubscriptionItemsTable + BillingInvoiceLinesTable.ForeignKeys[8].RefTable = SubscriptionPhasesTable + BillingInvoiceLinesTable.ForeignKeys[9].RefTable = TaxCodesTable + BillingInvoiceLineDiscountsTable.ForeignKeys[0].RefTable = BillingInvoiceLinesTable + BillingInvoiceLineUsageDiscountsTable.ForeignKeys[0].RefTable = BillingInvoiceLinesTable + BillingInvoiceSplitLineGroupsTable.ForeignKeys[0].RefTable = ChargesTable + BillingInvoiceSplitLineGroupsTable.ForeignKeys[1].RefTable = SubscriptionsTable + BillingInvoiceSplitLineGroupsTable.ForeignKeys[2].RefTable = SubscriptionItemsTable + BillingInvoiceSplitLineGroupsTable.ForeignKeys[3].RefTable = SubscriptionPhasesTable + BillingInvoiceValidationIssuesTable.ForeignKeys[0].RefTable = BillingInvoicesTable + BillingProfilesTable.ForeignKeys[0].RefTable = AppsTable + BillingProfilesTable.ForeignKeys[1].RefTable = AppsTable + BillingProfilesTable.ForeignKeys[2].RefTable = AppsTable + BillingProfilesTable.ForeignKeys[3].RefTable = BillingWorkflowConfigsTable + BillingStandardInvoiceDetailedLinesTable.ForeignKeys[0].RefTable = BillingInvoicesTable + BillingStandardInvoiceDetailedLinesTable.ForeignKeys[1].RefTable = BillingInvoiceLinesTable + BillingStandardInvoiceDetailedLinesTable.Annotation = &entsql.Annotation{} + BillingStandardInvoiceDetailedLinesTable.Annotation.Checks = map[string]string{ + "child_unique_reference_id_not_empty": "child_unique_reference_id <> ''", + } + BillingStandardInvoiceDetailedLineAmountDiscountsTable.ForeignKeys[0].RefTable = BillingStandardInvoiceDetailedLinesTable + BillingWorkflowConfigsTable.ForeignKeys[0].RefTable = TaxCodesTable + ChargesTable.ForeignKeys[0].RefTable = ChargeCreditPurchasesTable + ChargesTable.ForeignKeys[1].RefTable = ChargeFlatFeesTable + ChargesTable.ForeignKeys[2].RefTable = ChargeUsageBasedTable + ChargeCreditPurchasesTable.ForeignKeys[0].RefTable = CustomersTable + ChargeCreditPurchasesTable.ForeignKeys[1].RefTable = SubscriptionsTable + ChargeCreditPurchasesTable.ForeignKeys[2].RefTable = SubscriptionItemsTable + ChargeCreditPurchasesTable.ForeignKeys[3].RefTable = SubscriptionPhasesTable + ChargeCreditPurchasesTable.ForeignKeys[4].RefTable = TaxCodesTable + ChargeCreditPurchaseCreditGrantsTable.ForeignKeys[0].RefTable = ChargeCreditPurchasesTable + ChargeCreditPurchaseExternalPaymentsTable.ForeignKeys[0].RefTable = ChargeCreditPurchasesTable + ChargeCreditPurchaseInvoicedPaymentsTable.ForeignKeys[0].RefTable = BillingInvoiceLinesTable + ChargeCreditPurchaseInvoicedPaymentsTable.ForeignKeys[1].RefTable = ChargeCreditPurchasesTable + ChargeFlatFeesTable.ForeignKeys[0].RefTable = ChargeFlatFeeRunsTable + ChargeFlatFeesTable.ForeignKeys[1].RefTable = CustomersTable + ChargeFlatFeesTable.ForeignKeys[2].RefTable = FeaturesTable + ChargeFlatFeesTable.ForeignKeys[3].RefTable = SubscriptionsTable + ChargeFlatFeesTable.ForeignKeys[4].RefTable = SubscriptionItemsTable + ChargeFlatFeesTable.ForeignKeys[5].RefTable = SubscriptionPhasesTable + ChargeFlatFeesTable.ForeignKeys[6].RefTable = TaxCodesTable + ChargeFlatFeeOverridesTable.ForeignKeys[0].RefTable = ChargeFlatFeesTable + ChargeFlatFeeOverridesTable.ForeignKeys[1].RefTable = TaxCodesTable + ChargeFlatFeeRunsTable.ForeignKeys[0].RefTable = BillingInvoicesTable + ChargeFlatFeeRunsTable.ForeignKeys[1].RefTable = BillingInvoiceLinesTable + ChargeFlatFeeRunsTable.ForeignKeys[2].RefTable = ChargeFlatFeesTable + ChargeFlatFeeRunCreditAllocationsTable.ForeignKeys[0].RefTable = BillingInvoiceLinesTable + ChargeFlatFeeRunCreditAllocationsTable.ForeignKeys[1].RefTable = ChargeFlatFeeRunsTable + ChargeFlatFeeRunCreditAllocationsTable.ForeignKeys[2].RefTable = ChargeFlatFeeRunCreditAllocationsTable + ChargeFlatFeeRunDetailedLinesTable.ForeignKeys[0].RefTable = ChargeFlatFeeRunsTable + ChargeFlatFeeRunDetailedLinesTable.Annotation = &entsql.Annotation{} + ChargeFlatFeeRunDetailedLinesTable.Annotation.Checks = map[string]string{ + "child_unique_reference_id_not_empty": "child_unique_reference_id <> ''", + } + ChargeFlatFeeRunInvoicedUsagesTable.ForeignKeys[0].RefTable = ChargeFlatFeeRunsTable + ChargeFlatFeeRunPaymentsTable.ForeignKeys[0].RefTable = BillingInvoiceLinesTable + ChargeFlatFeeRunPaymentsTable.ForeignKeys[1].RefTable = ChargeFlatFeeRunsTable + ChargeUsageBasedTable.ForeignKeys[0].RefTable = ChargeUsageBasedRunsTable + ChargeUsageBasedTable.ForeignKeys[1].RefTable = CustomersTable + ChargeUsageBasedTable.ForeignKeys[2].RefTable = FeaturesTable + ChargeUsageBasedTable.ForeignKeys[3].RefTable = SubscriptionsTable + ChargeUsageBasedTable.ForeignKeys[4].RefTable = SubscriptionItemsTable + ChargeUsageBasedTable.ForeignKeys[5].RefTable = SubscriptionPhasesTable + ChargeUsageBasedTable.ForeignKeys[6].RefTable = TaxCodesTable + ChargeUsageBasedTable.Annotation = &entsql.Annotation{ + Table: "charge_usage_based", + } + ChargeUsageBasedOverridesTable.ForeignKeys[0].RefTable = ChargeUsageBasedTable + ChargeUsageBasedOverridesTable.ForeignKeys[1].RefTable = TaxCodesTable + ChargeUsageBasedRunCreditAllocationsTable.ForeignKeys[0].RefTable = ChargeUsageBasedRunCreditAllocationsTable + ChargeUsageBasedRunCreditAllocationsTable.ForeignKeys[1].RefTable = ChargeUsageBasedRunsTable + ChargeUsageBasedRunDetailedLineTable.ForeignKeys[0].RefTable = ChargeUsageBasedTable + ChargeUsageBasedRunDetailedLineTable.ForeignKeys[1].RefTable = ChargeUsageBasedRunsTable + ChargeUsageBasedRunDetailedLineTable.ForeignKeys[2].RefTable = ChargeUsageBasedRunsTable + ChargeUsageBasedRunDetailedLineTable.Annotation = &entsql.Annotation{ + Table: "charge_usage_based_run_detailed_line", + } + ChargeUsageBasedRunDetailedLineTable.Annotation.Checks = map[string]string{ + "child_unique_reference_id_not_empty": "child_unique_reference_id <> ''", + } + ChargeUsageBasedRunInvoicedUsagesTable.ForeignKeys[0].RefTable = ChargeUsageBasedRunsTable + ChargeUsageBasedRunPaymentsTable.ForeignKeys[0].RefTable = ChargeUsageBasedRunsTable + ChargeUsageBasedRunsTable.ForeignKeys[0].RefTable = BillingInvoicesTable + ChargeUsageBasedRunsTable.ForeignKeys[1].RefTable = BillingInvoiceLinesTable + ChargeUsageBasedRunsTable.ForeignKeys[2].RefTable = ChargeUsageBasedTable + ChargeUsageBasedRunsTable.ForeignKeys[3].RefTable = FeaturesTable + CreditRealizationLineagesTable.ForeignKeys[0].RefTable = ChargesTable + CreditRealizationLineageSegmentsTable.ForeignKeys[0].RefTable = CreditRealizationLineagesTable + CurrencyCostBasesTable.ForeignKeys[0].RefTable = CustomCurrenciesTable + CustomerSubjectsTable.ForeignKeys[0].RefTable = CustomersTable + EntitlementsTable.ForeignKeys[0].RefTable = CustomersTable + EntitlementsTable.ForeignKeys[1].RefTable = FeaturesTable + FeaturesTable.ForeignKeys[0].RefTable = MetersTable + FeaturesTable.Annotation = &entsql.Annotation{} + FeaturesTable.Annotation.Checks = map[string]string{ + "unit_cost_llm_model_mutual_exclusive": "NOT (unit_cost_llm_model_property IS NOT NULL AND unit_cost_llm_model IS NOT NULL)", + "unit_cost_llm_provider_mutual_exclusive": "NOT (unit_cost_llm_provider_property IS NOT NULL AND unit_cost_llm_provider IS NOT NULL)", + "unit_cost_llm_token_type_mutual_exclusive": "NOT (unit_cost_llm_token_type_property IS NOT NULL AND unit_cost_llm_token_type IS NOT NULL)", + } + GrantsTable.ForeignKeys[0].RefTable = EntitlementsTable + LedgerBreakageRecordsTable.ForeignKeys[0].RefTable = LedgerBreakageRecordsTable + LedgerBreakageRecordsTable.ForeignKeys[1].RefTable = LedgerBreakageRecordsTable + LedgerBreakageRecordsTable.ForeignKeys[2].RefTable = LedgerEntriesTable + LedgerBreakageRecordsTable.ForeignKeys[3].RefTable = LedgerSubAccountsTable + LedgerBreakageRecordsTable.ForeignKeys[4].RefTable = LedgerSubAccountsTable + LedgerBreakageRecordsTable.ForeignKeys[5].RefTable = LedgerTransactionsTable + LedgerBreakageRecordsTable.ForeignKeys[6].RefTable = LedgerTransactionsTable + LedgerBreakageRecordsTable.ForeignKeys[7].RefTable = LedgerTransactionGroupsTable + LedgerBreakageRecordsTable.ForeignKeys[8].RefTable = LedgerTransactionGroupsTable + LedgerCustomerAccountsTable.ForeignKeys[0].RefTable = LedgerAccountsTable + LedgerEntriesTable.ForeignKeys[0].RefTable = LedgerSubAccountsTable + LedgerEntriesTable.ForeignKeys[1].RefTable = LedgerTransactionsTable + LedgerSubAccountsTable.ForeignKeys[0].RefTable = LedgerAccountsTable + LedgerSubAccountsTable.ForeignKeys[1].RefTable = LedgerSubAccountRoutesTable + LedgerSubAccountRoutesTable.ForeignKeys[0].RefTable = LedgerAccountsTable + LedgerTransactionsTable.ForeignKeys[0].RefTable = LedgerTransactionGroupsTable + NotificationEventsTable.ForeignKeys[0].RefTable = NotificationRulesTable + OrganizationDefaultTaxCodesTable.ForeignKeys[0].RefTable = TaxCodesTable + OrganizationDefaultTaxCodesTable.ForeignKeys[1].RefTable = TaxCodesTable + PlanAddonsTable.ForeignKeys[0].RefTable = AddonsTable + PlanAddonsTable.ForeignKeys[1].RefTable = PlansTable + PlanPhasesTable.ForeignKeys[0].RefTable = PlansTable + PlanRateCardsTable.ForeignKeys[0].RefTable = FeaturesTable + PlanRateCardsTable.ForeignKeys[1].RefTable = PlanPhasesTable + PlanRateCardsTable.ForeignKeys[2].RefTable = TaxCodesTable + SubscriptionsTable.ForeignKeys[0].RefTable = CustomersTable + SubscriptionsTable.ForeignKeys[1].RefTable = PlansTable + SubscriptionAddonsTable.ForeignKeys[0].RefTable = AddonsTable + SubscriptionAddonsTable.ForeignKeys[1].RefTable = SubscriptionsTable + SubscriptionAddonQuantitiesTable.ForeignKeys[0].RefTable = SubscriptionAddonsTable + SubscriptionBillingSyncStatesTable.ForeignKeys[0].RefTable = SubscriptionsTable + SubscriptionItemsTable.ForeignKeys[0].RefTable = EntitlementsTable + SubscriptionItemsTable.ForeignKeys[1].RefTable = SubscriptionPhasesTable + SubscriptionItemsTable.ForeignKeys[2].RefTable = TaxCodesTable + SubscriptionPhasesTable.ForeignKeys[0].RefTable = SubscriptionsTable + UsageResetsTable.ForeignKeys[0].RefTable = EntitlementsTable + NotificationChannelRulesTable.ForeignKeys[0].RefTable = NotificationChannelsTable + NotificationChannelRulesTable.ForeignKeys[1].RefTable = NotificationRulesTable + NotificationEventDeliveryStatusEventsTable.ForeignKeys[0].RefTable = NotificationEventDeliveryStatusTable + NotificationEventDeliveryStatusEventsTable.ForeignKeys[1].RefTable = NotificationEventsTable +} diff --git a/ent/db/mutation.go b/ent/db/mutation.go new file mode 100644 index 0000000000000000000000000000000000000000..e8cecd860f8d70c77e836d24cdb42c05013e1e32 --- /dev/null +++ b/ent/db/mutation.go @@ -0,0 +1,116062 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "sync" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/alpacahq/alpacadecimal" + "github.com/lib/pq" + "github.com/openmeterio/openmeter/openmeter/app" + "github.com/openmeterio/openmeter/openmeter/billing" + "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/models/creditrealization" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/payment" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" + "github.com/openmeterio/openmeter/openmeter/billing/models/creditsapplied" + "github.com/openmeterio/openmeter/openmeter/billing/models/stddetailedline" + "github.com/openmeterio/openmeter/openmeter/credit/balance" + "github.com/openmeterio/openmeter/openmeter/credit/grant" + "github.com/openmeterio/openmeter/openmeter/ent/db/addon" + "github.com/openmeterio/openmeter/openmeter/ent/db/addonratecard" + dbapp "github.com/openmeterio/openmeter/openmeter/ent/db/app" + "github.com/openmeterio/openmeter/openmeter/ent/db/appcustomer" + "github.com/openmeterio/openmeter/openmeter/ent/db/appcustominvoicing" + "github.com/openmeterio/openmeter/openmeter/ent/db/appcustominvoicingcustomer" + "github.com/openmeterio/openmeter/openmeter/ent/db/appstripe" + "github.com/openmeterio/openmeter/openmeter/ent/db/appstripecustomer" + "github.com/openmeterio/openmeter/openmeter/ent/db/balancesnapshot" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingcustomerlock" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingcustomeroverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoice" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceflatfeelineconfig" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicelinediscount" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicelineusagediscount" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicesplitlinegroup" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoiceusagebasedlineconfig" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicevalidationissue" + "github.com/openmeterio/openmeter/openmeter/ent/db/billinginvoicewriteschemalevel" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingprofile" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingsequencenumbers" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingstandardinvoicedetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingstandardinvoicedetailedlineamountdiscount" + "github.com/openmeterio/openmeter/openmeter/ent/db/billingworkflowconfig" + "github.com/openmeterio/openmeter/openmeter/ent/db/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchase" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchasecreditgrant" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchaseexternalpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchaseinvoicedpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeoverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerun" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerundetailedline" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeerunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedoverride" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrundetailedline" + "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/creditrealizationlineage" + "github.com/openmeterio/openmeter/openmeter/ent/db/creditrealizationlineagesegment" + "github.com/openmeterio/openmeter/openmeter/ent/db/currencycostbasis" + "github.com/openmeterio/openmeter/openmeter/ent/db/customcurrency" + "github.com/openmeterio/openmeter/openmeter/ent/db/customer" + "github.com/openmeterio/openmeter/openmeter/ent/db/customersubjects" + "github.com/openmeterio/openmeter/openmeter/ent/db/entitlement" + dbfeature "github.com/openmeterio/openmeter/openmeter/ent/db/feature" + dbgrant "github.com/openmeterio/openmeter/openmeter/ent/db/grant" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgerbreakagerecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgercreditvoidrecord" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgercustomeraccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgerentry" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccount" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgersubaccountroute" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransaction" + "github.com/openmeterio/openmeter/openmeter/ent/db/ledgertransactiongroup" + "github.com/openmeterio/openmeter/openmeter/ent/db/llmcostprice" + dbmeter "github.com/openmeterio/openmeter/openmeter/ent/db/meter" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationchannel" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationevent" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationeventdeliverystatus" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationrule" + "github.com/openmeterio/openmeter/openmeter/ent/db/organizationdefaulttaxcodes" + "github.com/openmeterio/openmeter/openmeter/ent/db/plan" + "github.com/openmeterio/openmeter/openmeter/ent/db/planaddon" + "github.com/openmeterio/openmeter/openmeter/ent/db/planphase" + "github.com/openmeterio/openmeter/openmeter/ent/db/planratecard" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/ent/db/subject" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionaddon" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionaddonquantity" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionbillingsyncstate" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" + "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionphase" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" + "github.com/openmeterio/openmeter/openmeter/ent/db/usagereset" + "github.com/openmeterio/openmeter/openmeter/ledger" + "github.com/openmeterio/openmeter/openmeter/llmcost" + "github.com/openmeterio/openmeter/openmeter/meter" + "github.com/openmeterio/openmeter/openmeter/notification" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/openmeter/productcatalog/feature" + "github.com/openmeterio/openmeter/openmeter/taxcode" + "github.com/openmeterio/openmeter/pkg/currencyx" + "github.com/openmeterio/openmeter/pkg/datetime" + "github.com/openmeterio/openmeter/pkg/models" +) + +const ( + // Operation types. + OpCreate = ent.OpCreate + OpDelete = ent.OpDelete + OpDeleteOne = ent.OpDeleteOne + OpUpdate = ent.OpUpdate + OpUpdateOne = ent.OpUpdateOne + + // Node types. + TypeAddon = "Addon" + TypeAddonRateCard = "AddonRateCard" + TypeApp = "App" + TypeAppCustomInvoicing = "AppCustomInvoicing" + TypeAppCustomInvoicingCustomer = "AppCustomInvoicingCustomer" + TypeAppCustomer = "AppCustomer" + TypeAppStripe = "AppStripe" + TypeAppStripeCustomer = "AppStripeCustomer" + TypeBalanceSnapshot = "BalanceSnapshot" + TypeBillingCustomerLock = "BillingCustomerLock" + TypeBillingCustomerOverride = "BillingCustomerOverride" + TypeBillingInvoice = "BillingInvoice" + TypeBillingInvoiceFlatFeeLineConfig = "BillingInvoiceFlatFeeLineConfig" + TypeBillingInvoiceLine = "BillingInvoiceLine" + TypeBillingInvoiceLineDiscount = "BillingInvoiceLineDiscount" + TypeBillingInvoiceLineUsageDiscount = "BillingInvoiceLineUsageDiscount" + TypeBillingInvoiceSplitLineGroup = "BillingInvoiceSplitLineGroup" + TypeBillingInvoiceUsageBasedLineConfig = "BillingInvoiceUsageBasedLineConfig" + TypeBillingInvoiceValidationIssue = "BillingInvoiceValidationIssue" + TypeBillingInvoiceWriteSchemaLevel = "BillingInvoiceWriteSchemaLevel" + TypeBillingProfile = "BillingProfile" + TypeBillingSequenceNumbers = "BillingSequenceNumbers" + TypeBillingStandardInvoiceDetailedLine = "BillingStandardInvoiceDetailedLine" + TypeBillingStandardInvoiceDetailedLineAmountDiscount = "BillingStandardInvoiceDetailedLineAmountDiscount" + TypeBillingWorkflowConfig = "BillingWorkflowConfig" + TypeCharge = "Charge" + TypeChargeCreditPurchase = "ChargeCreditPurchase" + TypeChargeCreditPurchaseCreditGrant = "ChargeCreditPurchaseCreditGrant" + TypeChargeCreditPurchaseExternalPayment = "ChargeCreditPurchaseExternalPayment" + TypeChargeCreditPurchaseInvoicedPayment = "ChargeCreditPurchaseInvoicedPayment" + TypeChargeFlatFee = "ChargeFlatFee" + TypeChargeFlatFeeOverride = "ChargeFlatFeeOverride" + TypeChargeFlatFeeRun = "ChargeFlatFeeRun" + TypeChargeFlatFeeRunCreditAllocations = "ChargeFlatFeeRunCreditAllocations" + TypeChargeFlatFeeRunDetailedLine = "ChargeFlatFeeRunDetailedLine" + TypeChargeFlatFeeRunInvoicedUsage = "ChargeFlatFeeRunInvoicedUsage" + TypeChargeFlatFeeRunPayment = "ChargeFlatFeeRunPayment" + TypeChargeUsageBased = "ChargeUsageBased" + TypeChargeUsageBasedOverride = "ChargeUsageBasedOverride" + TypeChargeUsageBasedRunCreditAllocations = "ChargeUsageBasedRunCreditAllocations" + TypeChargeUsageBasedRunDetailedLine = "ChargeUsageBasedRunDetailedLine" + TypeChargeUsageBasedRunInvoicedUsage = "ChargeUsageBasedRunInvoicedUsage" + TypeChargeUsageBasedRunPayment = "ChargeUsageBasedRunPayment" + TypeChargeUsageBasedRuns = "ChargeUsageBasedRuns" + TypeChargesSearchV1 = "ChargesSearchV1" + TypeCreditRealizationLineage = "CreditRealizationLineage" + TypeCreditRealizationLineageSegment = "CreditRealizationLineageSegment" + TypeCurrencyCostBasis = "CurrencyCostBasis" + TypeCustomCurrency = "CustomCurrency" + TypeCustomer = "Customer" + TypeCustomerSubjects = "CustomerSubjects" + TypeEntitlement = "Entitlement" + TypeFeature = "Feature" + TypeGrant = "Grant" + TypeLLMCostPrice = "LLMCostPrice" + TypeLedgerAccount = "LedgerAccount" + TypeLedgerBreakageRecord = "LedgerBreakageRecord" + TypeLedgerCreditVoidRecord = "LedgerCreditVoidRecord" + TypeLedgerCustomerAccount = "LedgerCustomerAccount" + TypeLedgerEntry = "LedgerEntry" + TypeLedgerSubAccount = "LedgerSubAccount" + TypeLedgerSubAccountRoute = "LedgerSubAccountRoute" + TypeLedgerTransaction = "LedgerTransaction" + TypeLedgerTransactionGroup = "LedgerTransactionGroup" + TypeMeter = "Meter" + TypeNotificationChannel = "NotificationChannel" + TypeNotificationEvent = "NotificationEvent" + TypeNotificationEventDeliveryStatus = "NotificationEventDeliveryStatus" + TypeNotificationRule = "NotificationRule" + TypeOrganizationDefaultTaxCodes = "OrganizationDefaultTaxCodes" + TypePlan = "Plan" + TypePlanAddon = "PlanAddon" + TypePlanPhase = "PlanPhase" + TypePlanRateCard = "PlanRateCard" + TypeSubject = "Subject" + TypeSubscription = "Subscription" + TypeSubscriptionAddon = "SubscriptionAddon" + TypeSubscriptionAddonQuantity = "SubscriptionAddonQuantity" + TypeSubscriptionBillingSyncState = "SubscriptionBillingSyncState" + TypeSubscriptionItem = "SubscriptionItem" + TypeSubscriptionPhase = "SubscriptionPhase" + TypeTaxCode = "TaxCode" + TypeUsageReset = "UsageReset" +) + +// AddonMutation represents an operation that mutates the Addon nodes in the graph. +type AddonMutation struct { + config + op Op + typ string + id *string + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + name *string + description *string + key *string + version *int + addversion *int + currency *string + instance_type *productcatalog.AddonInstanceType + effective_from *time.Time + effective_to *time.Time + annotations *models.Annotations + clearedFields map[string]struct{} + ratecards map[string]struct{} + removedratecards map[string]struct{} + clearedratecards bool + plans map[string]struct{} + removedplans map[string]struct{} + clearedplans bool + subscription_addons map[string]struct{} + removedsubscription_addons map[string]struct{} + clearedsubscription_addons bool + done bool + oldValue func(context.Context) (*Addon, error) + predicates []predicate.Addon +} + +var _ ent.Mutation = (*AddonMutation)(nil) + +// addonOption allows management of the mutation configuration using functional options. +type addonOption func(*AddonMutation) + +// newAddonMutation creates new mutation for the Addon entity. +func newAddonMutation(c config, op Op, opts ...addonOption) *AddonMutation { + m := &AddonMutation{ + config: c, + op: op, + typ: TypeAddon, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAddonID sets the ID field of the mutation. +func withAddonID(id string) addonOption { + return func(m *AddonMutation) { + var ( + err error + once sync.Once + value *Addon + ) + m.oldValue = func(ctx context.Context) (*Addon, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Addon.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAddon sets the old Addon of the mutation. +func withAddon(node *Addon) addonOption { + return func(m *AddonMutation) { + m.oldValue = func(context.Context) (*Addon, 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 AddonMutation) 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 AddonMutation) 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 Addon entities. +func (m *AddonMutation) 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 *AddonMutation) 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 *AddonMutation) 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().Addon.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 *AddonMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *AddonMutation) 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 Addon entity. +// If the Addon 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 *AddonMutation) 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 *AddonMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *AddonMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *AddonMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the Addon entity. +// If the Addon 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 *AddonMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *AddonMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[addon.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *AddonMutation) MetadataCleared() bool { + _, ok := m.clearedFields[addon.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *AddonMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, addon.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *AddonMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *AddonMutation) 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 Addon entity. +// If the Addon 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 *AddonMutation) 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 *AddonMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *AddonMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *AddonMutation) 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 Addon entity. +// If the Addon 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 *AddonMutation) 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 *AddonMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *AddonMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *AddonMutation) 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 Addon entity. +// If the Addon 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 *AddonMutation) 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 *AddonMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[addon.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *AddonMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[addon.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *AddonMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, addon.FieldDeletedAt) +} + +// SetName sets the "name" field. +func (m *AddonMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *AddonMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the Addon entity. +// If the Addon 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 *AddonMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *AddonMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *AddonMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *AddonMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the Addon entity. +// If the Addon 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 *AddonMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *AddonMutation) ClearDescription() { + m.description = nil + m.clearedFields[addon.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *AddonMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[addon.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *AddonMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, addon.FieldDescription) +} + +// SetKey sets the "key" field. +func (m *AddonMutation) SetKey(s string) { + m.key = &s +} + +// Key returns the value of the "key" field in the mutation. +func (m *AddonMutation) Key() (r string, exists bool) { + v := m.key + if v == nil { + return + } + return *v, true +} + +// OldKey returns the old "key" field's value of the Addon entity. +// If the Addon 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 *AddonMutation) OldKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldKey: %w", err) + } + return oldValue.Key, nil +} + +// ResetKey resets all changes to the "key" field. +func (m *AddonMutation) ResetKey() { + m.key = nil +} + +// SetVersion sets the "version" field. +func (m *AddonMutation) SetVersion(i int) { + m.version = &i + m.addversion = nil +} + +// Version returns the value of the "version" field in the mutation. +func (m *AddonMutation) Version() (r int, exists bool) { + v := m.version + if v == nil { + return + } + return *v, true +} + +// OldVersion returns the old "version" field's value of the Addon entity. +// If the Addon 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 *AddonMutation) OldVersion(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldVersion is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldVersion requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldVersion: %w", err) + } + return oldValue.Version, nil +} + +// AddVersion adds i to the "version" field. +func (m *AddonMutation) AddVersion(i int) { + if m.addversion != nil { + *m.addversion += i + } else { + m.addversion = &i + } +} + +// AddedVersion returns the value that was added to the "version" field in this mutation. +func (m *AddonMutation) AddedVersion() (r int, exists bool) { + v := m.addversion + if v == nil { + return + } + return *v, true +} + +// ResetVersion resets all changes to the "version" field. +func (m *AddonMutation) ResetVersion() { + m.version = nil + m.addversion = nil +} + +// SetCurrency sets the "currency" field. +func (m *AddonMutation) SetCurrency(s string) { + m.currency = &s +} + +// Currency returns the value of the "currency" field in the mutation. +func (m *AddonMutation) Currency() (r string, exists bool) { + v := m.currency + if v == nil { + return + } + return *v, true +} + +// OldCurrency returns the old "currency" field's value of the Addon entity. +// If the Addon 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 *AddonMutation) OldCurrency(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrency is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrency requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrency: %w", err) + } + return oldValue.Currency, nil +} + +// ResetCurrency resets all changes to the "currency" field. +func (m *AddonMutation) ResetCurrency() { + m.currency = nil +} + +// SetInstanceType sets the "instance_type" field. +func (m *AddonMutation) SetInstanceType(pit productcatalog.AddonInstanceType) { + m.instance_type = &pit +} + +// InstanceType returns the value of the "instance_type" field in the mutation. +func (m *AddonMutation) InstanceType() (r productcatalog.AddonInstanceType, exists bool) { + v := m.instance_type + if v == nil { + return + } + return *v, true +} + +// OldInstanceType returns the old "instance_type" field's value of the Addon entity. +// If the Addon 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 *AddonMutation) OldInstanceType(ctx context.Context) (v productcatalog.AddonInstanceType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInstanceType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInstanceType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInstanceType: %w", err) + } + return oldValue.InstanceType, nil +} + +// ResetInstanceType resets all changes to the "instance_type" field. +func (m *AddonMutation) ResetInstanceType() { + m.instance_type = nil +} + +// SetEffectiveFrom sets the "effective_from" field. +func (m *AddonMutation) SetEffectiveFrom(t time.Time) { + m.effective_from = &t +} + +// EffectiveFrom returns the value of the "effective_from" field in the mutation. +func (m *AddonMutation) EffectiveFrom() (r time.Time, exists bool) { + v := m.effective_from + if v == nil { + return + } + return *v, true +} + +// OldEffectiveFrom returns the old "effective_from" field's value of the Addon entity. +// If the Addon 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 *AddonMutation) OldEffectiveFrom(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEffectiveFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEffectiveFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEffectiveFrom: %w", err) + } + return oldValue.EffectiveFrom, nil +} + +// ClearEffectiveFrom clears the value of the "effective_from" field. +func (m *AddonMutation) ClearEffectiveFrom() { + m.effective_from = nil + m.clearedFields[addon.FieldEffectiveFrom] = struct{}{} +} + +// EffectiveFromCleared returns if the "effective_from" field was cleared in this mutation. +func (m *AddonMutation) EffectiveFromCleared() bool { + _, ok := m.clearedFields[addon.FieldEffectiveFrom] + return ok +} + +// ResetEffectiveFrom resets all changes to the "effective_from" field. +func (m *AddonMutation) ResetEffectiveFrom() { + m.effective_from = nil + delete(m.clearedFields, addon.FieldEffectiveFrom) +} + +// SetEffectiveTo sets the "effective_to" field. +func (m *AddonMutation) SetEffectiveTo(t time.Time) { + m.effective_to = &t +} + +// EffectiveTo returns the value of the "effective_to" field in the mutation. +func (m *AddonMutation) EffectiveTo() (r time.Time, exists bool) { + v := m.effective_to + if v == nil { + return + } + return *v, true +} + +// OldEffectiveTo returns the old "effective_to" field's value of the Addon entity. +// If the Addon 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 *AddonMutation) OldEffectiveTo(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEffectiveTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEffectiveTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEffectiveTo: %w", err) + } + return oldValue.EffectiveTo, nil +} + +// ClearEffectiveTo clears the value of the "effective_to" field. +func (m *AddonMutation) ClearEffectiveTo() { + m.effective_to = nil + m.clearedFields[addon.FieldEffectiveTo] = struct{}{} +} + +// EffectiveToCleared returns if the "effective_to" field was cleared in this mutation. +func (m *AddonMutation) EffectiveToCleared() bool { + _, ok := m.clearedFields[addon.FieldEffectiveTo] + return ok +} + +// ResetEffectiveTo resets all changes to the "effective_to" field. +func (m *AddonMutation) ResetEffectiveTo() { + m.effective_to = nil + delete(m.clearedFields, addon.FieldEffectiveTo) +} + +// SetAnnotations sets the "annotations" field. +func (m *AddonMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *AddonMutation) 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 Addon entity. +// If the Addon 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 *AddonMutation) 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 *AddonMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[addon.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *AddonMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[addon.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *AddonMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, addon.FieldAnnotations) +} + +// AddRatecardIDs adds the "ratecards" edge to the AddonRateCard entity by ids. +func (m *AddonMutation) AddRatecardIDs(ids ...string) { + if m.ratecards == nil { + m.ratecards = make(map[string]struct{}) + } + for i := range ids { + m.ratecards[ids[i]] = struct{}{} + } +} + +// ClearRatecards clears the "ratecards" edge to the AddonRateCard entity. +func (m *AddonMutation) ClearRatecards() { + m.clearedratecards = true +} + +// RatecardsCleared reports if the "ratecards" edge to the AddonRateCard entity was cleared. +func (m *AddonMutation) RatecardsCleared() bool { + return m.clearedratecards +} + +// RemoveRatecardIDs removes the "ratecards" edge to the AddonRateCard entity by IDs. +func (m *AddonMutation) RemoveRatecardIDs(ids ...string) { + if m.removedratecards == nil { + m.removedratecards = make(map[string]struct{}) + } + for i := range ids { + delete(m.ratecards, ids[i]) + m.removedratecards[ids[i]] = struct{}{} + } +} + +// RemovedRatecards returns the removed IDs of the "ratecards" edge to the AddonRateCard entity. +func (m *AddonMutation) RemovedRatecardsIDs() (ids []string) { + for id := range m.removedratecards { + ids = append(ids, id) + } + return +} + +// RatecardsIDs returns the "ratecards" edge IDs in the mutation. +func (m *AddonMutation) RatecardsIDs() (ids []string) { + for id := range m.ratecards { + ids = append(ids, id) + } + return +} + +// ResetRatecards resets all changes to the "ratecards" edge. +func (m *AddonMutation) ResetRatecards() { + m.ratecards = nil + m.clearedratecards = false + m.removedratecards = nil +} + +// AddPlanIDs adds the "plans" edge to the PlanAddon entity by ids. +func (m *AddonMutation) AddPlanIDs(ids ...string) { + if m.plans == nil { + m.plans = make(map[string]struct{}) + } + for i := range ids { + m.plans[ids[i]] = struct{}{} + } +} + +// ClearPlans clears the "plans" edge to the PlanAddon entity. +func (m *AddonMutation) ClearPlans() { + m.clearedplans = true +} + +// PlansCleared reports if the "plans" edge to the PlanAddon entity was cleared. +func (m *AddonMutation) PlansCleared() bool { + return m.clearedplans +} + +// RemovePlanIDs removes the "plans" edge to the PlanAddon entity by IDs. +func (m *AddonMutation) RemovePlanIDs(ids ...string) { + if m.removedplans == nil { + m.removedplans = make(map[string]struct{}) + } + for i := range ids { + delete(m.plans, ids[i]) + m.removedplans[ids[i]] = struct{}{} + } +} + +// RemovedPlans returns the removed IDs of the "plans" edge to the PlanAddon entity. +func (m *AddonMutation) RemovedPlansIDs() (ids []string) { + for id := range m.removedplans { + ids = append(ids, id) + } + return +} + +// PlansIDs returns the "plans" edge IDs in the mutation. +func (m *AddonMutation) PlansIDs() (ids []string) { + for id := range m.plans { + ids = append(ids, id) + } + return +} + +// ResetPlans resets all changes to the "plans" edge. +func (m *AddonMutation) ResetPlans() { + m.plans = nil + m.clearedplans = false + m.removedplans = nil +} + +// AddSubscriptionAddonIDs adds the "subscription_addons" edge to the SubscriptionAddon entity by ids. +func (m *AddonMutation) AddSubscriptionAddonIDs(ids ...string) { + if m.subscription_addons == nil { + m.subscription_addons = make(map[string]struct{}) + } + for i := range ids { + m.subscription_addons[ids[i]] = struct{}{} + } +} + +// ClearSubscriptionAddons clears the "subscription_addons" edge to the SubscriptionAddon entity. +func (m *AddonMutation) ClearSubscriptionAddons() { + m.clearedsubscription_addons = true +} + +// SubscriptionAddonsCleared reports if the "subscription_addons" edge to the SubscriptionAddon entity was cleared. +func (m *AddonMutation) SubscriptionAddonsCleared() bool { + return m.clearedsubscription_addons +} + +// RemoveSubscriptionAddonIDs removes the "subscription_addons" edge to the SubscriptionAddon entity by IDs. +func (m *AddonMutation) RemoveSubscriptionAddonIDs(ids ...string) { + if m.removedsubscription_addons == nil { + m.removedsubscription_addons = make(map[string]struct{}) + } + for i := range ids { + delete(m.subscription_addons, ids[i]) + m.removedsubscription_addons[ids[i]] = struct{}{} + } +} + +// RemovedSubscriptionAddons returns the removed IDs of the "subscription_addons" edge to the SubscriptionAddon entity. +func (m *AddonMutation) RemovedSubscriptionAddonsIDs() (ids []string) { + for id := range m.removedsubscription_addons { + ids = append(ids, id) + } + return +} + +// SubscriptionAddonsIDs returns the "subscription_addons" edge IDs in the mutation. +func (m *AddonMutation) SubscriptionAddonsIDs() (ids []string) { + for id := range m.subscription_addons { + ids = append(ids, id) + } + return +} + +// ResetSubscriptionAddons resets all changes to the "subscription_addons" edge. +func (m *AddonMutation) ResetSubscriptionAddons() { + m.subscription_addons = nil + m.clearedsubscription_addons = false + m.removedsubscription_addons = nil +} + +// Where appends a list predicates to the AddonMutation builder. +func (m *AddonMutation) Where(ps ...predicate.Addon) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AddonMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AddonMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Addon, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AddonMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AddonMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Addon). +func (m *AddonMutation) 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 *AddonMutation) Fields() []string { + fields := make([]string, 0, 14) + if m.namespace != nil { + fields = append(fields, addon.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, addon.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, addon.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, addon.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, addon.FieldDeletedAt) + } + if m.name != nil { + fields = append(fields, addon.FieldName) + } + if m.description != nil { + fields = append(fields, addon.FieldDescription) + } + if m.key != nil { + fields = append(fields, addon.FieldKey) + } + if m.version != nil { + fields = append(fields, addon.FieldVersion) + } + if m.currency != nil { + fields = append(fields, addon.FieldCurrency) + } + if m.instance_type != nil { + fields = append(fields, addon.FieldInstanceType) + } + if m.effective_from != nil { + fields = append(fields, addon.FieldEffectiveFrom) + } + if m.effective_to != nil { + fields = append(fields, addon.FieldEffectiveTo) + } + if m.annotations != nil { + fields = append(fields, addon.FieldAnnotations) + } + 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 *AddonMutation) Field(name string) (ent.Value, bool) { + switch name { + case addon.FieldNamespace: + return m.Namespace() + case addon.FieldMetadata: + return m.Metadata() + case addon.FieldCreatedAt: + return m.CreatedAt() + case addon.FieldUpdatedAt: + return m.UpdatedAt() + case addon.FieldDeletedAt: + return m.DeletedAt() + case addon.FieldName: + return m.Name() + case addon.FieldDescription: + return m.Description() + case addon.FieldKey: + return m.Key() + case addon.FieldVersion: + return m.Version() + case addon.FieldCurrency: + return m.Currency() + case addon.FieldInstanceType: + return m.InstanceType() + case addon.FieldEffectiveFrom: + return m.EffectiveFrom() + case addon.FieldEffectiveTo: + return m.EffectiveTo() + case addon.FieldAnnotations: + return m.Annotations() + } + 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 *AddonMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case addon.FieldNamespace: + return m.OldNamespace(ctx) + case addon.FieldMetadata: + return m.OldMetadata(ctx) + case addon.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case addon.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case addon.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case addon.FieldName: + return m.OldName(ctx) + case addon.FieldDescription: + return m.OldDescription(ctx) + case addon.FieldKey: + return m.OldKey(ctx) + case addon.FieldVersion: + return m.OldVersion(ctx) + case addon.FieldCurrency: + return m.OldCurrency(ctx) + case addon.FieldInstanceType: + return m.OldInstanceType(ctx) + case addon.FieldEffectiveFrom: + return m.OldEffectiveFrom(ctx) + case addon.FieldEffectiveTo: + return m.OldEffectiveTo(ctx) + case addon.FieldAnnotations: + return m.OldAnnotations(ctx) + } + return nil, fmt.Errorf("unknown Addon 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 *AddonMutation) SetField(name string, value ent.Value) error { + switch name { + case addon.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case addon.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case addon.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 addon.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 addon.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 addon.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case addon.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case addon.FieldKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKey(v) + return nil + case addon.FieldVersion: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVersion(v) + return nil + case addon.FieldCurrency: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrency(v) + return nil + case addon.FieldInstanceType: + v, ok := value.(productcatalog.AddonInstanceType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInstanceType(v) + return nil + case addon.FieldEffectiveFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEffectiveFrom(v) + return nil + case addon.FieldEffectiveTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEffectiveTo(v) + return nil + case addon.FieldAnnotations: + v, ok := value.(models.Annotations) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAnnotations(v) + return nil + } + return fmt.Errorf("unknown Addon field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AddonMutation) AddedFields() []string { + var fields []string + if m.addversion != nil { + fields = append(fields, addon.FieldVersion) + } + return fields +} + +// 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 *AddonMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case addon.FieldVersion: + return m.AddedVersion() + } + 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 *AddonMutation) AddField(name string, value ent.Value) error { + switch name { + case addon.FieldVersion: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddVersion(v) + return nil + } + return fmt.Errorf("unknown Addon numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AddonMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(addon.FieldMetadata) { + fields = append(fields, addon.FieldMetadata) + } + if m.FieldCleared(addon.FieldDeletedAt) { + fields = append(fields, addon.FieldDeletedAt) + } + if m.FieldCleared(addon.FieldDescription) { + fields = append(fields, addon.FieldDescription) + } + if m.FieldCleared(addon.FieldEffectiveFrom) { + fields = append(fields, addon.FieldEffectiveFrom) + } + if m.FieldCleared(addon.FieldEffectiveTo) { + fields = append(fields, addon.FieldEffectiveTo) + } + if m.FieldCleared(addon.FieldAnnotations) { + fields = append(fields, addon.FieldAnnotations) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AddonMutation) 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 *AddonMutation) ClearField(name string) error { + switch name { + case addon.FieldMetadata: + m.ClearMetadata() + return nil + case addon.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case addon.FieldDescription: + m.ClearDescription() + return nil + case addon.FieldEffectiveFrom: + m.ClearEffectiveFrom() + return nil + case addon.FieldEffectiveTo: + m.ClearEffectiveTo() + return nil + case addon.FieldAnnotations: + m.ClearAnnotations() + return nil + } + return fmt.Errorf("unknown Addon 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 *AddonMutation) ResetField(name string) error { + switch name { + case addon.FieldNamespace: + m.ResetNamespace() + return nil + case addon.FieldMetadata: + m.ResetMetadata() + return nil + case addon.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case addon.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case addon.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case addon.FieldName: + m.ResetName() + return nil + case addon.FieldDescription: + m.ResetDescription() + return nil + case addon.FieldKey: + m.ResetKey() + return nil + case addon.FieldVersion: + m.ResetVersion() + return nil + case addon.FieldCurrency: + m.ResetCurrency() + return nil + case addon.FieldInstanceType: + m.ResetInstanceType() + return nil + case addon.FieldEffectiveFrom: + m.ResetEffectiveFrom() + return nil + case addon.FieldEffectiveTo: + m.ResetEffectiveTo() + return nil + case addon.FieldAnnotations: + m.ResetAnnotations() + return nil + } + return fmt.Errorf("unknown Addon field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AddonMutation) AddedEdges() []string { + edges := make([]string, 0, 3) + if m.ratecards != nil { + edges = append(edges, addon.EdgeRatecards) + } + if m.plans != nil { + edges = append(edges, addon.EdgePlans) + } + if m.subscription_addons != nil { + edges = append(edges, addon.EdgeSubscriptionAddons) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AddonMutation) AddedIDs(name string) []ent.Value { + switch name { + case addon.EdgeRatecards: + ids := make([]ent.Value, 0, len(m.ratecards)) + for id := range m.ratecards { + ids = append(ids, id) + } + return ids + case addon.EdgePlans: + ids := make([]ent.Value, 0, len(m.plans)) + for id := range m.plans { + ids = append(ids, id) + } + return ids + case addon.EdgeSubscriptionAddons: + ids := make([]ent.Value, 0, len(m.subscription_addons)) + for id := range m.subscription_addons { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AddonMutation) RemovedEdges() []string { + edges := make([]string, 0, 3) + if m.removedratecards != nil { + edges = append(edges, addon.EdgeRatecards) + } + if m.removedplans != nil { + edges = append(edges, addon.EdgePlans) + } + if m.removedsubscription_addons != nil { + edges = append(edges, addon.EdgeSubscriptionAddons) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AddonMutation) RemovedIDs(name string) []ent.Value { + switch name { + case addon.EdgeRatecards: + ids := make([]ent.Value, 0, len(m.removedratecards)) + for id := range m.removedratecards { + ids = append(ids, id) + } + return ids + case addon.EdgePlans: + ids := make([]ent.Value, 0, len(m.removedplans)) + for id := range m.removedplans { + ids = append(ids, id) + } + return ids + case addon.EdgeSubscriptionAddons: + ids := make([]ent.Value, 0, len(m.removedsubscription_addons)) + for id := range m.removedsubscription_addons { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AddonMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) + if m.clearedratecards { + edges = append(edges, addon.EdgeRatecards) + } + if m.clearedplans { + edges = append(edges, addon.EdgePlans) + } + if m.clearedsubscription_addons { + edges = append(edges, addon.EdgeSubscriptionAddons) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AddonMutation) EdgeCleared(name string) bool { + switch name { + case addon.EdgeRatecards: + return m.clearedratecards + case addon.EdgePlans: + return m.clearedplans + case addon.EdgeSubscriptionAddons: + return m.clearedsubscription_addons + } + 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 *AddonMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown Addon 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 *AddonMutation) ResetEdge(name string) error { + switch name { + case addon.EdgeRatecards: + m.ResetRatecards() + return nil + case addon.EdgePlans: + m.ResetPlans() + return nil + case addon.EdgeSubscriptionAddons: + m.ResetSubscriptionAddons() + return nil + } + return fmt.Errorf("unknown Addon edge %s", name) +} + +// AddonRateCardMutation represents an operation that mutates the AddonRateCard nodes in the graph. +type AddonRateCardMutation struct { + config + op Op + typ string + id *string + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + name *string + description *string + key *string + tax_behavior *productcatalog.TaxBehavior + _type *productcatalog.RateCardType + feature_key *string + entitlement_template **productcatalog.EntitlementTemplate + tax_config **productcatalog.TaxConfig + billing_cadence *datetime.ISODurationString + price **productcatalog.Price + discounts **productcatalog.Discounts + unit_config **productcatalog.UnitConfig + clearedFields map[string]struct{} + addon *string + clearedaddon bool + features *string + clearedfeatures bool + tax_code *string + clearedtax_code bool + done bool + oldValue func(context.Context) (*AddonRateCard, error) + predicates []predicate.AddonRateCard +} + +var _ ent.Mutation = (*AddonRateCardMutation)(nil) + +// addonratecardOption allows management of the mutation configuration using functional options. +type addonratecardOption func(*AddonRateCardMutation) + +// newAddonRateCardMutation creates new mutation for the AddonRateCard entity. +func newAddonRateCardMutation(c config, op Op, opts ...addonratecardOption) *AddonRateCardMutation { + m := &AddonRateCardMutation{ + config: c, + op: op, + typ: TypeAddonRateCard, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAddonRateCardID sets the ID field of the mutation. +func withAddonRateCardID(id string) addonratecardOption { + return func(m *AddonRateCardMutation) { + var ( + err error + once sync.Once + value *AddonRateCard + ) + m.oldValue = func(ctx context.Context) (*AddonRateCard, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().AddonRateCard.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAddonRateCard sets the old AddonRateCard of the mutation. +func withAddonRateCard(node *AddonRateCard) addonratecardOption { + return func(m *AddonRateCardMutation) { + m.oldValue = func(context.Context) (*AddonRateCard, 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 AddonRateCardMutation) 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 AddonRateCardMutation) 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 AddonRateCard entities. +func (m *AddonRateCardMutation) 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 *AddonRateCardMutation) 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 *AddonRateCardMutation) 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().AddonRateCard.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 *AddonRateCardMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *AddonRateCardMutation) 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 AddonRateCard entity. +// If the AddonRateCard 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 *AddonRateCardMutation) 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 *AddonRateCardMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *AddonRateCardMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *AddonRateCardMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the AddonRateCard entity. +// If the AddonRateCard 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 *AddonRateCardMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *AddonRateCardMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[addonratecard.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *AddonRateCardMutation) MetadataCleared() bool { + _, ok := m.clearedFields[addonratecard.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *AddonRateCardMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, addonratecard.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *AddonRateCardMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *AddonRateCardMutation) 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 AddonRateCard entity. +// If the AddonRateCard 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 *AddonRateCardMutation) 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 *AddonRateCardMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *AddonRateCardMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *AddonRateCardMutation) 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 AddonRateCard entity. +// If the AddonRateCard 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 *AddonRateCardMutation) 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 *AddonRateCardMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *AddonRateCardMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *AddonRateCardMutation) 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 AddonRateCard entity. +// If the AddonRateCard 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 *AddonRateCardMutation) 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 *AddonRateCardMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[addonratecard.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *AddonRateCardMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[addonratecard.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *AddonRateCardMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, addonratecard.FieldDeletedAt) +} + +// SetName sets the "name" field. +func (m *AddonRateCardMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *AddonRateCardMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the AddonRateCard entity. +// If the AddonRateCard 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 *AddonRateCardMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *AddonRateCardMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *AddonRateCardMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *AddonRateCardMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the AddonRateCard entity. +// If the AddonRateCard 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 *AddonRateCardMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *AddonRateCardMutation) ClearDescription() { + m.description = nil + m.clearedFields[addonratecard.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *AddonRateCardMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[addonratecard.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *AddonRateCardMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, addonratecard.FieldDescription) +} + +// SetKey sets the "key" field. +func (m *AddonRateCardMutation) SetKey(s string) { + m.key = &s +} + +// Key returns the value of the "key" field in the mutation. +func (m *AddonRateCardMutation) Key() (r string, exists bool) { + v := m.key + if v == nil { + return + } + return *v, true +} + +// OldKey returns the old "key" field's value of the AddonRateCard entity. +// If the AddonRateCard 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 *AddonRateCardMutation) OldKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldKey: %w", err) + } + return oldValue.Key, nil +} + +// ResetKey resets all changes to the "key" field. +func (m *AddonRateCardMutation) ResetKey() { + m.key = nil +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (m *AddonRateCardMutation) SetTaxCodeID(s string) { + m.tax_code = &s +} + +// TaxCodeID returns the value of the "tax_code_id" field in the mutation. +func (m *AddonRateCardMutation) TaxCodeID() (r string, exists bool) { + v := m.tax_code + if v == nil { + return + } + return *v, true +} + +// OldTaxCodeID returns the old "tax_code_id" field's value of the AddonRateCard entity. +// If the AddonRateCard 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 *AddonRateCardMutation) OldTaxCodeID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxCodeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxCodeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxCodeID: %w", err) + } + return oldValue.TaxCodeID, nil +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (m *AddonRateCardMutation) ClearTaxCodeID() { + m.tax_code = nil + m.clearedFields[addonratecard.FieldTaxCodeID] = struct{}{} +} + +// TaxCodeIDCleared returns if the "tax_code_id" field was cleared in this mutation. +func (m *AddonRateCardMutation) TaxCodeIDCleared() bool { + _, ok := m.clearedFields[addonratecard.FieldTaxCodeID] + return ok +} + +// ResetTaxCodeID resets all changes to the "tax_code_id" field. +func (m *AddonRateCardMutation) ResetTaxCodeID() { + m.tax_code = nil + delete(m.clearedFields, addonratecard.FieldTaxCodeID) +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (m *AddonRateCardMutation) SetTaxBehavior(pb productcatalog.TaxBehavior) { + m.tax_behavior = &pb +} + +// TaxBehavior returns the value of the "tax_behavior" field in the mutation. +func (m *AddonRateCardMutation) TaxBehavior() (r productcatalog.TaxBehavior, exists bool) { + v := m.tax_behavior + if v == nil { + return + } + return *v, true +} + +// OldTaxBehavior returns the old "tax_behavior" field's value of the AddonRateCard entity. +// If the AddonRateCard 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 *AddonRateCardMutation) OldTaxBehavior(ctx context.Context) (v *productcatalog.TaxBehavior, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxBehavior is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxBehavior requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxBehavior: %w", err) + } + return oldValue.TaxBehavior, nil +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (m *AddonRateCardMutation) ClearTaxBehavior() { + m.tax_behavior = nil + m.clearedFields[addonratecard.FieldTaxBehavior] = struct{}{} +} + +// TaxBehaviorCleared returns if the "tax_behavior" field was cleared in this mutation. +func (m *AddonRateCardMutation) TaxBehaviorCleared() bool { + _, ok := m.clearedFields[addonratecard.FieldTaxBehavior] + return ok +} + +// ResetTaxBehavior resets all changes to the "tax_behavior" field. +func (m *AddonRateCardMutation) ResetTaxBehavior() { + m.tax_behavior = nil + delete(m.clearedFields, addonratecard.FieldTaxBehavior) +} + +// SetType sets the "type" field. +func (m *AddonRateCardMutation) SetType(pct productcatalog.RateCardType) { + m._type = &pct +} + +// GetType returns the value of the "type" field in the mutation. +func (m *AddonRateCardMutation) GetType() (r productcatalog.RateCardType, exists bool) { + v := m._type + if v == nil { + return + } + return *v, true +} + +// OldType returns the old "type" field's value of the AddonRateCard entity. +// If the AddonRateCard 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 *AddonRateCardMutation) OldType(ctx context.Context) (v productcatalog.RateCardType, 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 *AddonRateCardMutation) ResetType() { + m._type = nil +} + +// SetFeatureKey sets the "feature_key" field. +func (m *AddonRateCardMutation) SetFeatureKey(s string) { + m.feature_key = &s +} + +// FeatureKey returns the value of the "feature_key" field in the mutation. +func (m *AddonRateCardMutation) 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 AddonRateCard entity. +// If the AddonRateCard 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 *AddonRateCardMutation) 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 +} + +// ClearFeatureKey clears the value of the "feature_key" field. +func (m *AddonRateCardMutation) ClearFeatureKey() { + m.feature_key = nil + m.clearedFields[addonratecard.FieldFeatureKey] = struct{}{} +} + +// FeatureKeyCleared returns if the "feature_key" field was cleared in this mutation. +func (m *AddonRateCardMutation) FeatureKeyCleared() bool { + _, ok := m.clearedFields[addonratecard.FieldFeatureKey] + return ok +} + +// ResetFeatureKey resets all changes to the "feature_key" field. +func (m *AddonRateCardMutation) ResetFeatureKey() { + m.feature_key = nil + delete(m.clearedFields, addonratecard.FieldFeatureKey) +} + +// SetEntitlementTemplate sets the "entitlement_template" field. +func (m *AddonRateCardMutation) SetEntitlementTemplate(pt *productcatalog.EntitlementTemplate) { + m.entitlement_template = &pt +} + +// EntitlementTemplate returns the value of the "entitlement_template" field in the mutation. +func (m *AddonRateCardMutation) EntitlementTemplate() (r *productcatalog.EntitlementTemplate, exists bool) { + v := m.entitlement_template + if v == nil { + return + } + return *v, true +} + +// OldEntitlementTemplate returns the old "entitlement_template" field's value of the AddonRateCard entity. +// If the AddonRateCard 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 *AddonRateCardMutation) OldEntitlementTemplate(ctx context.Context) (v *productcatalog.EntitlementTemplate, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEntitlementTemplate is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEntitlementTemplate requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEntitlementTemplate: %w", err) + } + return oldValue.EntitlementTemplate, nil +} + +// ClearEntitlementTemplate clears the value of the "entitlement_template" field. +func (m *AddonRateCardMutation) ClearEntitlementTemplate() { + m.entitlement_template = nil + m.clearedFields[addonratecard.FieldEntitlementTemplate] = struct{}{} +} + +// EntitlementTemplateCleared returns if the "entitlement_template" field was cleared in this mutation. +func (m *AddonRateCardMutation) EntitlementTemplateCleared() bool { + _, ok := m.clearedFields[addonratecard.FieldEntitlementTemplate] + return ok +} + +// ResetEntitlementTemplate resets all changes to the "entitlement_template" field. +func (m *AddonRateCardMutation) ResetEntitlementTemplate() { + m.entitlement_template = nil + delete(m.clearedFields, addonratecard.FieldEntitlementTemplate) +} + +// SetTaxConfig sets the "tax_config" field. +func (m *AddonRateCardMutation) SetTaxConfig(pc *productcatalog.TaxConfig) { + m.tax_config = &pc +} + +// TaxConfig returns the value of the "tax_config" field in the mutation. +func (m *AddonRateCardMutation) TaxConfig() (r *productcatalog.TaxConfig, exists bool) { + v := m.tax_config + if v == nil { + return + } + return *v, true +} + +// OldTaxConfig returns the old "tax_config" field's value of the AddonRateCard entity. +// If the AddonRateCard 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 *AddonRateCardMutation) OldTaxConfig(ctx context.Context) (v *productcatalog.TaxConfig, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxConfig is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxConfig requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxConfig: %w", err) + } + return oldValue.TaxConfig, nil +} + +// ClearTaxConfig clears the value of the "tax_config" field. +func (m *AddonRateCardMutation) ClearTaxConfig() { + m.tax_config = nil + m.clearedFields[addonratecard.FieldTaxConfig] = struct{}{} +} + +// TaxConfigCleared returns if the "tax_config" field was cleared in this mutation. +func (m *AddonRateCardMutation) TaxConfigCleared() bool { + _, ok := m.clearedFields[addonratecard.FieldTaxConfig] + return ok +} + +// ResetTaxConfig resets all changes to the "tax_config" field. +func (m *AddonRateCardMutation) ResetTaxConfig() { + m.tax_config = nil + delete(m.clearedFields, addonratecard.FieldTaxConfig) +} + +// SetBillingCadence sets the "billing_cadence" field. +func (m *AddonRateCardMutation) SetBillingCadence(dds datetime.ISODurationString) { + m.billing_cadence = &dds +} + +// BillingCadence returns the value of the "billing_cadence" field in the mutation. +func (m *AddonRateCardMutation) BillingCadence() (r datetime.ISODurationString, exists bool) { + v := m.billing_cadence + if v == nil { + return + } + return *v, true +} + +// OldBillingCadence returns the old "billing_cadence" field's value of the AddonRateCard entity. +// If the AddonRateCard 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 *AddonRateCardMutation) OldBillingCadence(ctx context.Context) (v *datetime.ISODurationString, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingCadence is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingCadence requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingCadence: %w", err) + } + return oldValue.BillingCadence, nil +} + +// ClearBillingCadence clears the value of the "billing_cadence" field. +func (m *AddonRateCardMutation) ClearBillingCadence() { + m.billing_cadence = nil + m.clearedFields[addonratecard.FieldBillingCadence] = struct{}{} +} + +// BillingCadenceCleared returns if the "billing_cadence" field was cleared in this mutation. +func (m *AddonRateCardMutation) BillingCadenceCleared() bool { + _, ok := m.clearedFields[addonratecard.FieldBillingCadence] + return ok +} + +// ResetBillingCadence resets all changes to the "billing_cadence" field. +func (m *AddonRateCardMutation) ResetBillingCadence() { + m.billing_cadence = nil + delete(m.clearedFields, addonratecard.FieldBillingCadence) +} + +// SetPrice sets the "price" field. +func (m *AddonRateCardMutation) SetPrice(pr *productcatalog.Price) { + m.price = &pr +} + +// Price returns the value of the "price" field in the mutation. +func (m *AddonRateCardMutation) 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 AddonRateCard entity. +// If the AddonRateCard 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 *AddonRateCardMutation) 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 +} + +// ClearPrice clears the value of the "price" field. +func (m *AddonRateCardMutation) ClearPrice() { + m.price = nil + m.clearedFields[addonratecard.FieldPrice] = struct{}{} +} + +// PriceCleared returns if the "price" field was cleared in this mutation. +func (m *AddonRateCardMutation) PriceCleared() bool { + _, ok := m.clearedFields[addonratecard.FieldPrice] + return ok +} + +// ResetPrice resets all changes to the "price" field. +func (m *AddonRateCardMutation) ResetPrice() { + m.price = nil + delete(m.clearedFields, addonratecard.FieldPrice) +} + +// SetDiscounts sets the "discounts" field. +func (m *AddonRateCardMutation) SetDiscounts(pr *productcatalog.Discounts) { + m.discounts = &pr +} + +// Discounts returns the value of the "discounts" field in the mutation. +func (m *AddonRateCardMutation) 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 AddonRateCard entity. +// If the AddonRateCard 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 *AddonRateCardMutation) 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 *AddonRateCardMutation) ClearDiscounts() { + m.discounts = nil + m.clearedFields[addonratecard.FieldDiscounts] = struct{}{} +} + +// DiscountsCleared returns if the "discounts" field was cleared in this mutation. +func (m *AddonRateCardMutation) DiscountsCleared() bool { + _, ok := m.clearedFields[addonratecard.FieldDiscounts] + return ok +} + +// ResetDiscounts resets all changes to the "discounts" field. +func (m *AddonRateCardMutation) ResetDiscounts() { + m.discounts = nil + delete(m.clearedFields, addonratecard.FieldDiscounts) +} + +// SetUnitConfig sets the "unit_config" field. +func (m *AddonRateCardMutation) SetUnitConfig(pc *productcatalog.UnitConfig) { + m.unit_config = &pc +} + +// UnitConfig returns the value of the "unit_config" field in the mutation. +func (m *AddonRateCardMutation) UnitConfig() (r *productcatalog.UnitConfig, exists bool) { + v := m.unit_config + if v == nil { + return + } + return *v, true +} + +// OldUnitConfig returns the old "unit_config" field's value of the AddonRateCard entity. +// If the AddonRateCard 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 *AddonRateCardMutation) OldUnitConfig(ctx context.Context) (v *productcatalog.UnitConfig, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUnitConfig is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUnitConfig requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUnitConfig: %w", err) + } + return oldValue.UnitConfig, nil +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (m *AddonRateCardMutation) ClearUnitConfig() { + m.unit_config = nil + m.clearedFields[addonratecard.FieldUnitConfig] = struct{}{} +} + +// UnitConfigCleared returns if the "unit_config" field was cleared in this mutation. +func (m *AddonRateCardMutation) UnitConfigCleared() bool { + _, ok := m.clearedFields[addonratecard.FieldUnitConfig] + return ok +} + +// ResetUnitConfig resets all changes to the "unit_config" field. +func (m *AddonRateCardMutation) ResetUnitConfig() { + m.unit_config = nil + delete(m.clearedFields, addonratecard.FieldUnitConfig) +} + +// SetAddonID sets the "addon_id" field. +func (m *AddonRateCardMutation) SetAddonID(s string) { + m.addon = &s +} + +// AddonID returns the value of the "addon_id" field in the mutation. +func (m *AddonRateCardMutation) AddonID() (r string, exists bool) { + v := m.addon + if v == nil { + return + } + return *v, true +} + +// OldAddonID returns the old "addon_id" field's value of the AddonRateCard entity. +// If the AddonRateCard 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 *AddonRateCardMutation) OldAddonID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAddonID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAddonID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAddonID: %w", err) + } + return oldValue.AddonID, nil +} + +// ResetAddonID resets all changes to the "addon_id" field. +func (m *AddonRateCardMutation) ResetAddonID() { + m.addon = nil +} + +// SetFeatureID sets the "feature_id" field. +func (m *AddonRateCardMutation) SetFeatureID(s string) { + m.features = &s +} + +// FeatureID returns the value of the "feature_id" field in the mutation. +func (m *AddonRateCardMutation) FeatureID() (r string, exists bool) { + v := m.features + if v == nil { + return + } + return *v, true +} + +// OldFeatureID returns the old "feature_id" field's value of the AddonRateCard entity. +// If the AddonRateCard 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 *AddonRateCardMutation) OldFeatureID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFeatureID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFeatureID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFeatureID: %w", err) + } + return oldValue.FeatureID, nil +} + +// ClearFeatureID clears the value of the "feature_id" field. +func (m *AddonRateCardMutation) ClearFeatureID() { + m.features = nil + m.clearedFields[addonratecard.FieldFeatureID] = struct{}{} +} + +// FeatureIDCleared returns if the "feature_id" field was cleared in this mutation. +func (m *AddonRateCardMutation) FeatureIDCleared() bool { + _, ok := m.clearedFields[addonratecard.FieldFeatureID] + return ok +} + +// ResetFeatureID resets all changes to the "feature_id" field. +func (m *AddonRateCardMutation) ResetFeatureID() { + m.features = nil + delete(m.clearedFields, addonratecard.FieldFeatureID) +} + +// ClearAddon clears the "addon" edge to the Addon entity. +func (m *AddonRateCardMutation) ClearAddon() { + m.clearedaddon = true + m.clearedFields[addonratecard.FieldAddonID] = struct{}{} +} + +// AddonCleared reports if the "addon" edge to the Addon entity was cleared. +func (m *AddonRateCardMutation) AddonCleared() bool { + return m.clearedaddon +} + +// AddonIDs returns the "addon" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// AddonID instead. It exists only for internal usage by the builders. +func (m *AddonRateCardMutation) AddonIDs() (ids []string) { + if id := m.addon; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetAddon resets all changes to the "addon" edge. +func (m *AddonRateCardMutation) ResetAddon() { + m.addon = nil + m.clearedaddon = false +} + +// SetFeaturesID sets the "features" edge to the Feature entity by id. +func (m *AddonRateCardMutation) SetFeaturesID(id string) { + m.features = &id +} + +// ClearFeatures clears the "features" edge to the Feature entity. +func (m *AddonRateCardMutation) ClearFeatures() { + m.clearedfeatures = true + m.clearedFields[addonratecard.FieldFeatureID] = struct{}{} +} + +// FeaturesCleared reports if the "features" edge to the Feature entity was cleared. +func (m *AddonRateCardMutation) FeaturesCleared() bool { + return m.FeatureIDCleared() || m.clearedfeatures +} + +// FeaturesID returns the "features" edge ID in the mutation. +func (m *AddonRateCardMutation) FeaturesID() (id string, exists bool) { + if m.features != nil { + return *m.features, true + } + return +} + +// FeaturesIDs returns the "features" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// FeaturesID instead. It exists only for internal usage by the builders. +func (m *AddonRateCardMutation) FeaturesIDs() (ids []string) { + if id := m.features; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetFeatures resets all changes to the "features" edge. +func (m *AddonRateCardMutation) ResetFeatures() { + m.features = nil + m.clearedfeatures = false +} + +// ClearTaxCode clears the "tax_code" edge to the TaxCode entity. +func (m *AddonRateCardMutation) ClearTaxCode() { + m.clearedtax_code = true + m.clearedFields[addonratecard.FieldTaxCodeID] = struct{}{} +} + +// TaxCodeCleared reports if the "tax_code" edge to the TaxCode entity was cleared. +func (m *AddonRateCardMutation) TaxCodeCleared() bool { + return m.TaxCodeIDCleared() || m.clearedtax_code +} + +// TaxCodeIDs returns the "tax_code" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TaxCodeID instead. It exists only for internal usage by the builders. +func (m *AddonRateCardMutation) TaxCodeIDs() (ids []string) { + if id := m.tax_code; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTaxCode resets all changes to the "tax_code" edge. +func (m *AddonRateCardMutation) ResetTaxCode() { + m.tax_code = nil + m.clearedtax_code = false +} + +// Where appends a list predicates to the AddonRateCardMutation builder. +func (m *AddonRateCardMutation) Where(ps ...predicate.AddonRateCard) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AddonRateCardMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AddonRateCardMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.AddonRateCard, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AddonRateCardMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AddonRateCardMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (AddonRateCard). +func (m *AddonRateCardMutation) 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 *AddonRateCardMutation) Fields() []string { + fields := make([]string, 0, 20) + if m.namespace != nil { + fields = append(fields, addonratecard.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, addonratecard.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, addonratecard.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, addonratecard.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, addonratecard.FieldDeletedAt) + } + if m.name != nil { + fields = append(fields, addonratecard.FieldName) + } + if m.description != nil { + fields = append(fields, addonratecard.FieldDescription) + } + if m.key != nil { + fields = append(fields, addonratecard.FieldKey) + } + if m.tax_code != nil { + fields = append(fields, addonratecard.FieldTaxCodeID) + } + if m.tax_behavior != nil { + fields = append(fields, addonratecard.FieldTaxBehavior) + } + if m._type != nil { + fields = append(fields, addonratecard.FieldType) + } + if m.feature_key != nil { + fields = append(fields, addonratecard.FieldFeatureKey) + } + if m.entitlement_template != nil { + fields = append(fields, addonratecard.FieldEntitlementTemplate) + } + if m.tax_config != nil { + fields = append(fields, addonratecard.FieldTaxConfig) + } + if m.billing_cadence != nil { + fields = append(fields, addonratecard.FieldBillingCadence) + } + if m.price != nil { + fields = append(fields, addonratecard.FieldPrice) + } + if m.discounts != nil { + fields = append(fields, addonratecard.FieldDiscounts) + } + if m.unit_config != nil { + fields = append(fields, addonratecard.FieldUnitConfig) + } + if m.addon != nil { + fields = append(fields, addonratecard.FieldAddonID) + } + if m.features != nil { + fields = append(fields, addonratecard.FieldFeatureID) + } + 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 *AddonRateCardMutation) Field(name string) (ent.Value, bool) { + switch name { + case addonratecard.FieldNamespace: + return m.Namespace() + case addonratecard.FieldMetadata: + return m.Metadata() + case addonratecard.FieldCreatedAt: + return m.CreatedAt() + case addonratecard.FieldUpdatedAt: + return m.UpdatedAt() + case addonratecard.FieldDeletedAt: + return m.DeletedAt() + case addonratecard.FieldName: + return m.Name() + case addonratecard.FieldDescription: + return m.Description() + case addonratecard.FieldKey: + return m.Key() + case addonratecard.FieldTaxCodeID: + return m.TaxCodeID() + case addonratecard.FieldTaxBehavior: + return m.TaxBehavior() + case addonratecard.FieldType: + return m.GetType() + case addonratecard.FieldFeatureKey: + return m.FeatureKey() + case addonratecard.FieldEntitlementTemplate: + return m.EntitlementTemplate() + case addonratecard.FieldTaxConfig: + return m.TaxConfig() + case addonratecard.FieldBillingCadence: + return m.BillingCadence() + case addonratecard.FieldPrice: + return m.Price() + case addonratecard.FieldDiscounts: + return m.Discounts() + case addonratecard.FieldUnitConfig: + return m.UnitConfig() + case addonratecard.FieldAddonID: + return m.AddonID() + case addonratecard.FieldFeatureID: + return m.FeatureID() + } + 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 *AddonRateCardMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case addonratecard.FieldNamespace: + return m.OldNamespace(ctx) + case addonratecard.FieldMetadata: + return m.OldMetadata(ctx) + case addonratecard.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case addonratecard.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case addonratecard.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case addonratecard.FieldName: + return m.OldName(ctx) + case addonratecard.FieldDescription: + return m.OldDescription(ctx) + case addonratecard.FieldKey: + return m.OldKey(ctx) + case addonratecard.FieldTaxCodeID: + return m.OldTaxCodeID(ctx) + case addonratecard.FieldTaxBehavior: + return m.OldTaxBehavior(ctx) + case addonratecard.FieldType: + return m.OldType(ctx) + case addonratecard.FieldFeatureKey: + return m.OldFeatureKey(ctx) + case addonratecard.FieldEntitlementTemplate: + return m.OldEntitlementTemplate(ctx) + case addonratecard.FieldTaxConfig: + return m.OldTaxConfig(ctx) + case addonratecard.FieldBillingCadence: + return m.OldBillingCadence(ctx) + case addonratecard.FieldPrice: + return m.OldPrice(ctx) + case addonratecard.FieldDiscounts: + return m.OldDiscounts(ctx) + case addonratecard.FieldUnitConfig: + return m.OldUnitConfig(ctx) + case addonratecard.FieldAddonID: + return m.OldAddonID(ctx) + case addonratecard.FieldFeatureID: + return m.OldFeatureID(ctx) + } + return nil, fmt.Errorf("unknown AddonRateCard 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 *AddonRateCardMutation) SetField(name string, value ent.Value) error { + switch name { + case addonratecard.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case addonratecard.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case addonratecard.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 addonratecard.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 addonratecard.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 addonratecard.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case addonratecard.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case addonratecard.FieldKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKey(v) + return nil + case addonratecard.FieldTaxCodeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxCodeID(v) + return nil + case addonratecard.FieldTaxBehavior: + v, ok := value.(productcatalog.TaxBehavior) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxBehavior(v) + return nil + case addonratecard.FieldType: + v, ok := value.(productcatalog.RateCardType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case addonratecard.FieldFeatureKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFeatureKey(v) + return nil + case addonratecard.FieldEntitlementTemplate: + v, ok := value.(*productcatalog.EntitlementTemplate) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEntitlementTemplate(v) + return nil + case addonratecard.FieldTaxConfig: + v, ok := value.(*productcatalog.TaxConfig) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxConfig(v) + return nil + case addonratecard.FieldBillingCadence: + v, ok := value.(datetime.ISODurationString) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingCadence(v) + return nil + case addonratecard.FieldPrice: + v, ok := value.(*productcatalog.Price) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPrice(v) + return nil + case addonratecard.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 addonratecard.FieldUnitConfig: + v, ok := value.(*productcatalog.UnitConfig) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUnitConfig(v) + return nil + case addonratecard.FieldAddonID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAddonID(v) + return nil + case addonratecard.FieldFeatureID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFeatureID(v) + return nil + } + return fmt.Errorf("unknown AddonRateCard field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AddonRateCardMutation) 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 *AddonRateCardMutation) 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 *AddonRateCardMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown AddonRateCard numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AddonRateCardMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(addonratecard.FieldMetadata) { + fields = append(fields, addonratecard.FieldMetadata) + } + if m.FieldCleared(addonratecard.FieldDeletedAt) { + fields = append(fields, addonratecard.FieldDeletedAt) + } + if m.FieldCleared(addonratecard.FieldDescription) { + fields = append(fields, addonratecard.FieldDescription) + } + if m.FieldCleared(addonratecard.FieldTaxCodeID) { + fields = append(fields, addonratecard.FieldTaxCodeID) + } + if m.FieldCleared(addonratecard.FieldTaxBehavior) { + fields = append(fields, addonratecard.FieldTaxBehavior) + } + if m.FieldCleared(addonratecard.FieldFeatureKey) { + fields = append(fields, addonratecard.FieldFeatureKey) + } + if m.FieldCleared(addonratecard.FieldEntitlementTemplate) { + fields = append(fields, addonratecard.FieldEntitlementTemplate) + } + if m.FieldCleared(addonratecard.FieldTaxConfig) { + fields = append(fields, addonratecard.FieldTaxConfig) + } + if m.FieldCleared(addonratecard.FieldBillingCadence) { + fields = append(fields, addonratecard.FieldBillingCadence) + } + if m.FieldCleared(addonratecard.FieldPrice) { + fields = append(fields, addonratecard.FieldPrice) + } + if m.FieldCleared(addonratecard.FieldDiscounts) { + fields = append(fields, addonratecard.FieldDiscounts) + } + if m.FieldCleared(addonratecard.FieldUnitConfig) { + fields = append(fields, addonratecard.FieldUnitConfig) + } + if m.FieldCleared(addonratecard.FieldFeatureID) { + fields = append(fields, addonratecard.FieldFeatureID) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AddonRateCardMutation) 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 *AddonRateCardMutation) ClearField(name string) error { + switch name { + case addonratecard.FieldMetadata: + m.ClearMetadata() + return nil + case addonratecard.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case addonratecard.FieldDescription: + m.ClearDescription() + return nil + case addonratecard.FieldTaxCodeID: + m.ClearTaxCodeID() + return nil + case addonratecard.FieldTaxBehavior: + m.ClearTaxBehavior() + return nil + case addonratecard.FieldFeatureKey: + m.ClearFeatureKey() + return nil + case addonratecard.FieldEntitlementTemplate: + m.ClearEntitlementTemplate() + return nil + case addonratecard.FieldTaxConfig: + m.ClearTaxConfig() + return nil + case addonratecard.FieldBillingCadence: + m.ClearBillingCadence() + return nil + case addonratecard.FieldPrice: + m.ClearPrice() + return nil + case addonratecard.FieldDiscounts: + m.ClearDiscounts() + return nil + case addonratecard.FieldUnitConfig: + m.ClearUnitConfig() + return nil + case addonratecard.FieldFeatureID: + m.ClearFeatureID() + return nil + } + return fmt.Errorf("unknown AddonRateCard 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 *AddonRateCardMutation) ResetField(name string) error { + switch name { + case addonratecard.FieldNamespace: + m.ResetNamespace() + return nil + case addonratecard.FieldMetadata: + m.ResetMetadata() + return nil + case addonratecard.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case addonratecard.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case addonratecard.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case addonratecard.FieldName: + m.ResetName() + return nil + case addonratecard.FieldDescription: + m.ResetDescription() + return nil + case addonratecard.FieldKey: + m.ResetKey() + return nil + case addonratecard.FieldTaxCodeID: + m.ResetTaxCodeID() + return nil + case addonratecard.FieldTaxBehavior: + m.ResetTaxBehavior() + return nil + case addonratecard.FieldType: + m.ResetType() + return nil + case addonratecard.FieldFeatureKey: + m.ResetFeatureKey() + return nil + case addonratecard.FieldEntitlementTemplate: + m.ResetEntitlementTemplate() + return nil + case addonratecard.FieldTaxConfig: + m.ResetTaxConfig() + return nil + case addonratecard.FieldBillingCadence: + m.ResetBillingCadence() + return nil + case addonratecard.FieldPrice: + m.ResetPrice() + return nil + case addonratecard.FieldDiscounts: + m.ResetDiscounts() + return nil + case addonratecard.FieldUnitConfig: + m.ResetUnitConfig() + return nil + case addonratecard.FieldAddonID: + m.ResetAddonID() + return nil + case addonratecard.FieldFeatureID: + m.ResetFeatureID() + return nil + } + return fmt.Errorf("unknown AddonRateCard field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AddonRateCardMutation) AddedEdges() []string { + edges := make([]string, 0, 3) + if m.addon != nil { + edges = append(edges, addonratecard.EdgeAddon) + } + if m.features != nil { + edges = append(edges, addonratecard.EdgeFeatures) + } + if m.tax_code != nil { + edges = append(edges, addonratecard.EdgeTaxCode) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AddonRateCardMutation) AddedIDs(name string) []ent.Value { + switch name { + case addonratecard.EdgeAddon: + if id := m.addon; id != nil { + return []ent.Value{*id} + } + case addonratecard.EdgeFeatures: + if id := m.features; id != nil { + return []ent.Value{*id} + } + case addonratecard.EdgeTaxCode: + if id := m.tax_code; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AddonRateCardMutation) RemovedEdges() []string { + edges := make([]string, 0, 3) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AddonRateCardMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AddonRateCardMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) + if m.clearedaddon { + edges = append(edges, addonratecard.EdgeAddon) + } + if m.clearedfeatures { + edges = append(edges, addonratecard.EdgeFeatures) + } + if m.clearedtax_code { + edges = append(edges, addonratecard.EdgeTaxCode) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AddonRateCardMutation) EdgeCleared(name string) bool { + switch name { + case addonratecard.EdgeAddon: + return m.clearedaddon + case addonratecard.EdgeFeatures: + return m.clearedfeatures + case addonratecard.EdgeTaxCode: + return m.clearedtax_code + } + 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 *AddonRateCardMutation) ClearEdge(name string) error { + switch name { + case addonratecard.EdgeAddon: + m.ClearAddon() + return nil + case addonratecard.EdgeFeatures: + m.ClearFeatures() + return nil + case addonratecard.EdgeTaxCode: + m.ClearTaxCode() + return nil + } + return fmt.Errorf("unknown AddonRateCard 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 *AddonRateCardMutation) ResetEdge(name string) error { + switch name { + case addonratecard.EdgeAddon: + m.ResetAddon() + return nil + case addonratecard.EdgeFeatures: + m.ResetFeatures() + return nil + case addonratecard.EdgeTaxCode: + m.ResetTaxCode() + return nil + } + return fmt.Errorf("unknown AddonRateCard edge %s", name) +} + +// AppMutation represents an operation that mutates the App nodes in the graph. +type AppMutation struct { + config + op Op + typ string + id *string + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + name *string + description *string + _type *app.AppType + status *app.AppStatus + clearedFields map[string]struct{} + customer_apps map[int]struct{} + removedcustomer_apps map[int]struct{} + clearedcustomer_apps bool + billing_profile_tax_app map[string]struct{} + removedbilling_profile_tax_app map[string]struct{} + clearedbilling_profile_tax_app bool + billing_profile_invoicing_app map[string]struct{} + removedbilling_profile_invoicing_app map[string]struct{} + clearedbilling_profile_invoicing_app bool + billing_profile_payment_app map[string]struct{} + removedbilling_profile_payment_app map[string]struct{} + clearedbilling_profile_payment_app bool + billing_invoice_tax_app map[string]struct{} + removedbilling_invoice_tax_app map[string]struct{} + clearedbilling_invoice_tax_app bool + billing_invoice_invoicing_app map[string]struct{} + removedbilling_invoice_invoicing_app map[string]struct{} + clearedbilling_invoice_invoicing_app bool + billing_invoice_payment_app map[string]struct{} + removedbilling_invoice_payment_app map[string]struct{} + clearedbilling_invoice_payment_app bool + done bool + oldValue func(context.Context) (*App, error) + predicates []predicate.App +} + +var _ ent.Mutation = (*AppMutation)(nil) + +// appOption allows management of the mutation configuration using functional options. +type appOption func(*AppMutation) + +// newAppMutation creates new mutation for the App entity. +func newAppMutation(c config, op Op, opts ...appOption) *AppMutation { + m := &AppMutation{ + config: c, + op: op, + typ: TypeApp, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAppID sets the ID field of the mutation. +func withAppID(id string) appOption { + return func(m *AppMutation) { + var ( + err error + once sync.Once + value *App + ) + m.oldValue = func(ctx context.Context) (*App, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().App.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withApp sets the old App of the mutation. +func withApp(node *App) appOption { + return func(m *AppMutation) { + m.oldValue = func(context.Context) (*App, 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 AppMutation) 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 AppMutation) 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 App entities. +func (m *AppMutation) 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 *AppMutation) 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 *AppMutation) 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().App.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 *AppMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *AppMutation) 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 App entity. +// If the App 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 *AppMutation) 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 *AppMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *AppMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *AppMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the App entity. +// If the App 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 *AppMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *AppMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[dbapp.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *AppMutation) MetadataCleared() bool { + _, ok := m.clearedFields[dbapp.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *AppMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, dbapp.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *AppMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *AppMutation) 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 App entity. +// If the App 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 *AppMutation) 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 *AppMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *AppMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *AppMutation) 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 App entity. +// If the App 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 *AppMutation) 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 *AppMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *AppMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *AppMutation) 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 App entity. +// If the App 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 *AppMutation) 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 *AppMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[dbapp.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *AppMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[dbapp.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *AppMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, dbapp.FieldDeletedAt) +} + +// SetName sets the "name" field. +func (m *AppMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *AppMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the App entity. +// If the App 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 *AppMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *AppMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *AppMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *AppMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the App entity. +// If the App 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 *AppMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *AppMutation) ClearDescription() { + m.description = nil + m.clearedFields[dbapp.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *AppMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[dbapp.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *AppMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, dbapp.FieldDescription) +} + +// SetType sets the "type" field. +func (m *AppMutation) SetType(at app.AppType) { + m._type = &at +} + +// GetType returns the value of the "type" field in the mutation. +func (m *AppMutation) GetType() (r app.AppType, exists bool) { + v := m._type + if v == nil { + return + } + return *v, true +} + +// OldType returns the old "type" field's value of the App entity. +// If the App 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 *AppMutation) OldType(ctx context.Context) (v app.AppType, 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 *AppMutation) ResetType() { + m._type = nil +} + +// SetStatus sets the "status" field. +func (m *AppMutation) SetStatus(as app.AppStatus) { + m.status = &as +} + +// Status returns the value of the "status" field in the mutation. +func (m *AppMutation) Status() (r app.AppStatus, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true +} + +// OldStatus returns the old "status" field's value of the App entity. +// If the App 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 *AppMutation) OldStatus(ctx context.Context) (v app.AppStatus, 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 *AppMutation) ResetStatus() { + m.status = nil +} + +// AddCustomerAppIDs adds the "customer_apps" edge to the AppCustomer entity by ids. +func (m *AppMutation) AddCustomerAppIDs(ids ...int) { + if m.customer_apps == nil { + m.customer_apps = make(map[int]struct{}) + } + for i := range ids { + m.customer_apps[ids[i]] = struct{}{} + } +} + +// ClearCustomerApps clears the "customer_apps" edge to the AppCustomer entity. +func (m *AppMutation) ClearCustomerApps() { + m.clearedcustomer_apps = true +} + +// CustomerAppsCleared reports if the "customer_apps" edge to the AppCustomer entity was cleared. +func (m *AppMutation) CustomerAppsCleared() bool { + return m.clearedcustomer_apps +} + +// RemoveCustomerAppIDs removes the "customer_apps" edge to the AppCustomer entity by IDs. +func (m *AppMutation) RemoveCustomerAppIDs(ids ...int) { + if m.removedcustomer_apps == nil { + m.removedcustomer_apps = make(map[int]struct{}) + } + for i := range ids { + delete(m.customer_apps, ids[i]) + m.removedcustomer_apps[ids[i]] = struct{}{} + } +} + +// RemovedCustomerApps returns the removed IDs of the "customer_apps" edge to the AppCustomer entity. +func (m *AppMutation) RemovedCustomerAppsIDs() (ids []int) { + for id := range m.removedcustomer_apps { + ids = append(ids, id) + } + return +} + +// CustomerAppsIDs returns the "customer_apps" edge IDs in the mutation. +func (m *AppMutation) CustomerAppsIDs() (ids []int) { + for id := range m.customer_apps { + ids = append(ids, id) + } + return +} + +// ResetCustomerApps resets all changes to the "customer_apps" edge. +func (m *AppMutation) ResetCustomerApps() { + m.customer_apps = nil + m.clearedcustomer_apps = false + m.removedcustomer_apps = nil +} + +// AddBillingProfileTaxAppIDs adds the "billing_profile_tax_app" edge to the BillingProfile entity by ids. +func (m *AppMutation) AddBillingProfileTaxAppIDs(ids ...string) { + if m.billing_profile_tax_app == nil { + m.billing_profile_tax_app = make(map[string]struct{}) + } + for i := range ids { + m.billing_profile_tax_app[ids[i]] = struct{}{} + } +} + +// ClearBillingProfileTaxApp clears the "billing_profile_tax_app" edge to the BillingProfile entity. +func (m *AppMutation) ClearBillingProfileTaxApp() { + m.clearedbilling_profile_tax_app = true +} + +// BillingProfileTaxAppCleared reports if the "billing_profile_tax_app" edge to the BillingProfile entity was cleared. +func (m *AppMutation) BillingProfileTaxAppCleared() bool { + return m.clearedbilling_profile_tax_app +} + +// RemoveBillingProfileTaxAppIDs removes the "billing_profile_tax_app" edge to the BillingProfile entity by IDs. +func (m *AppMutation) RemoveBillingProfileTaxAppIDs(ids ...string) { + if m.removedbilling_profile_tax_app == nil { + m.removedbilling_profile_tax_app = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_profile_tax_app, ids[i]) + m.removedbilling_profile_tax_app[ids[i]] = struct{}{} + } +} + +// RemovedBillingProfileTaxApp returns the removed IDs of the "billing_profile_tax_app" edge to the BillingProfile entity. +func (m *AppMutation) RemovedBillingProfileTaxAppIDs() (ids []string) { + for id := range m.removedbilling_profile_tax_app { + ids = append(ids, id) + } + return +} + +// BillingProfileTaxAppIDs returns the "billing_profile_tax_app" edge IDs in the mutation. +func (m *AppMutation) BillingProfileTaxAppIDs() (ids []string) { + for id := range m.billing_profile_tax_app { + ids = append(ids, id) + } + return +} + +// ResetBillingProfileTaxApp resets all changes to the "billing_profile_tax_app" edge. +func (m *AppMutation) ResetBillingProfileTaxApp() { + m.billing_profile_tax_app = nil + m.clearedbilling_profile_tax_app = false + m.removedbilling_profile_tax_app = nil +} + +// AddBillingProfileInvoicingAppIDs adds the "billing_profile_invoicing_app" edge to the BillingProfile entity by ids. +func (m *AppMutation) AddBillingProfileInvoicingAppIDs(ids ...string) { + if m.billing_profile_invoicing_app == nil { + m.billing_profile_invoicing_app = make(map[string]struct{}) + } + for i := range ids { + m.billing_profile_invoicing_app[ids[i]] = struct{}{} + } +} + +// ClearBillingProfileInvoicingApp clears the "billing_profile_invoicing_app" edge to the BillingProfile entity. +func (m *AppMutation) ClearBillingProfileInvoicingApp() { + m.clearedbilling_profile_invoicing_app = true +} + +// BillingProfileInvoicingAppCleared reports if the "billing_profile_invoicing_app" edge to the BillingProfile entity was cleared. +func (m *AppMutation) BillingProfileInvoicingAppCleared() bool { + return m.clearedbilling_profile_invoicing_app +} + +// RemoveBillingProfileInvoicingAppIDs removes the "billing_profile_invoicing_app" edge to the BillingProfile entity by IDs. +func (m *AppMutation) RemoveBillingProfileInvoicingAppIDs(ids ...string) { + if m.removedbilling_profile_invoicing_app == nil { + m.removedbilling_profile_invoicing_app = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_profile_invoicing_app, ids[i]) + m.removedbilling_profile_invoicing_app[ids[i]] = struct{}{} + } +} + +// RemovedBillingProfileInvoicingApp returns the removed IDs of the "billing_profile_invoicing_app" edge to the BillingProfile entity. +func (m *AppMutation) RemovedBillingProfileInvoicingAppIDs() (ids []string) { + for id := range m.removedbilling_profile_invoicing_app { + ids = append(ids, id) + } + return +} + +// BillingProfileInvoicingAppIDs returns the "billing_profile_invoicing_app" edge IDs in the mutation. +func (m *AppMutation) BillingProfileInvoicingAppIDs() (ids []string) { + for id := range m.billing_profile_invoicing_app { + ids = append(ids, id) + } + return +} + +// ResetBillingProfileInvoicingApp resets all changes to the "billing_profile_invoicing_app" edge. +func (m *AppMutation) ResetBillingProfileInvoicingApp() { + m.billing_profile_invoicing_app = nil + m.clearedbilling_profile_invoicing_app = false + m.removedbilling_profile_invoicing_app = nil +} + +// AddBillingProfilePaymentAppIDs adds the "billing_profile_payment_app" edge to the BillingProfile entity by ids. +func (m *AppMutation) AddBillingProfilePaymentAppIDs(ids ...string) { + if m.billing_profile_payment_app == nil { + m.billing_profile_payment_app = make(map[string]struct{}) + } + for i := range ids { + m.billing_profile_payment_app[ids[i]] = struct{}{} + } +} + +// ClearBillingProfilePaymentApp clears the "billing_profile_payment_app" edge to the BillingProfile entity. +func (m *AppMutation) ClearBillingProfilePaymentApp() { + m.clearedbilling_profile_payment_app = true +} + +// BillingProfilePaymentAppCleared reports if the "billing_profile_payment_app" edge to the BillingProfile entity was cleared. +func (m *AppMutation) BillingProfilePaymentAppCleared() bool { + return m.clearedbilling_profile_payment_app +} + +// RemoveBillingProfilePaymentAppIDs removes the "billing_profile_payment_app" edge to the BillingProfile entity by IDs. +func (m *AppMutation) RemoveBillingProfilePaymentAppIDs(ids ...string) { + if m.removedbilling_profile_payment_app == nil { + m.removedbilling_profile_payment_app = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_profile_payment_app, ids[i]) + m.removedbilling_profile_payment_app[ids[i]] = struct{}{} + } +} + +// RemovedBillingProfilePaymentApp returns the removed IDs of the "billing_profile_payment_app" edge to the BillingProfile entity. +func (m *AppMutation) RemovedBillingProfilePaymentAppIDs() (ids []string) { + for id := range m.removedbilling_profile_payment_app { + ids = append(ids, id) + } + return +} + +// BillingProfilePaymentAppIDs returns the "billing_profile_payment_app" edge IDs in the mutation. +func (m *AppMutation) BillingProfilePaymentAppIDs() (ids []string) { + for id := range m.billing_profile_payment_app { + ids = append(ids, id) + } + return +} + +// ResetBillingProfilePaymentApp resets all changes to the "billing_profile_payment_app" edge. +func (m *AppMutation) ResetBillingProfilePaymentApp() { + m.billing_profile_payment_app = nil + m.clearedbilling_profile_payment_app = false + m.removedbilling_profile_payment_app = nil +} + +// AddBillingInvoiceTaxAppIDs adds the "billing_invoice_tax_app" edge to the BillingInvoice entity by ids. +func (m *AppMutation) AddBillingInvoiceTaxAppIDs(ids ...string) { + if m.billing_invoice_tax_app == nil { + m.billing_invoice_tax_app = make(map[string]struct{}) + } + for i := range ids { + m.billing_invoice_tax_app[ids[i]] = struct{}{} + } +} + +// ClearBillingInvoiceTaxApp clears the "billing_invoice_tax_app" edge to the BillingInvoice entity. +func (m *AppMutation) ClearBillingInvoiceTaxApp() { + m.clearedbilling_invoice_tax_app = true +} + +// BillingInvoiceTaxAppCleared reports if the "billing_invoice_tax_app" edge to the BillingInvoice entity was cleared. +func (m *AppMutation) BillingInvoiceTaxAppCleared() bool { + return m.clearedbilling_invoice_tax_app +} + +// RemoveBillingInvoiceTaxAppIDs removes the "billing_invoice_tax_app" edge to the BillingInvoice entity by IDs. +func (m *AppMutation) RemoveBillingInvoiceTaxAppIDs(ids ...string) { + if m.removedbilling_invoice_tax_app == nil { + m.removedbilling_invoice_tax_app = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_invoice_tax_app, ids[i]) + m.removedbilling_invoice_tax_app[ids[i]] = struct{}{} + } +} + +// RemovedBillingInvoiceTaxApp returns the removed IDs of the "billing_invoice_tax_app" edge to the BillingInvoice entity. +func (m *AppMutation) RemovedBillingInvoiceTaxAppIDs() (ids []string) { + for id := range m.removedbilling_invoice_tax_app { + ids = append(ids, id) + } + return +} + +// BillingInvoiceTaxAppIDs returns the "billing_invoice_tax_app" edge IDs in the mutation. +func (m *AppMutation) BillingInvoiceTaxAppIDs() (ids []string) { + for id := range m.billing_invoice_tax_app { + ids = append(ids, id) + } + return +} + +// ResetBillingInvoiceTaxApp resets all changes to the "billing_invoice_tax_app" edge. +func (m *AppMutation) ResetBillingInvoiceTaxApp() { + m.billing_invoice_tax_app = nil + m.clearedbilling_invoice_tax_app = false + m.removedbilling_invoice_tax_app = nil +} + +// AddBillingInvoiceInvoicingAppIDs adds the "billing_invoice_invoicing_app" edge to the BillingInvoice entity by ids. +func (m *AppMutation) AddBillingInvoiceInvoicingAppIDs(ids ...string) { + if m.billing_invoice_invoicing_app == nil { + m.billing_invoice_invoicing_app = make(map[string]struct{}) + } + for i := range ids { + m.billing_invoice_invoicing_app[ids[i]] = struct{}{} + } +} + +// ClearBillingInvoiceInvoicingApp clears the "billing_invoice_invoicing_app" edge to the BillingInvoice entity. +func (m *AppMutation) ClearBillingInvoiceInvoicingApp() { + m.clearedbilling_invoice_invoicing_app = true +} + +// BillingInvoiceInvoicingAppCleared reports if the "billing_invoice_invoicing_app" edge to the BillingInvoice entity was cleared. +func (m *AppMutation) BillingInvoiceInvoicingAppCleared() bool { + return m.clearedbilling_invoice_invoicing_app +} + +// RemoveBillingInvoiceInvoicingAppIDs removes the "billing_invoice_invoicing_app" edge to the BillingInvoice entity by IDs. +func (m *AppMutation) RemoveBillingInvoiceInvoicingAppIDs(ids ...string) { + if m.removedbilling_invoice_invoicing_app == nil { + m.removedbilling_invoice_invoicing_app = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_invoice_invoicing_app, ids[i]) + m.removedbilling_invoice_invoicing_app[ids[i]] = struct{}{} + } +} + +// RemovedBillingInvoiceInvoicingApp returns the removed IDs of the "billing_invoice_invoicing_app" edge to the BillingInvoice entity. +func (m *AppMutation) RemovedBillingInvoiceInvoicingAppIDs() (ids []string) { + for id := range m.removedbilling_invoice_invoicing_app { + ids = append(ids, id) + } + return +} + +// BillingInvoiceInvoicingAppIDs returns the "billing_invoice_invoicing_app" edge IDs in the mutation. +func (m *AppMutation) BillingInvoiceInvoicingAppIDs() (ids []string) { + for id := range m.billing_invoice_invoicing_app { + ids = append(ids, id) + } + return +} + +// ResetBillingInvoiceInvoicingApp resets all changes to the "billing_invoice_invoicing_app" edge. +func (m *AppMutation) ResetBillingInvoiceInvoicingApp() { + m.billing_invoice_invoicing_app = nil + m.clearedbilling_invoice_invoicing_app = false + m.removedbilling_invoice_invoicing_app = nil +} + +// AddBillingInvoicePaymentAppIDs adds the "billing_invoice_payment_app" edge to the BillingInvoice entity by ids. +func (m *AppMutation) AddBillingInvoicePaymentAppIDs(ids ...string) { + if m.billing_invoice_payment_app == nil { + m.billing_invoice_payment_app = make(map[string]struct{}) + } + for i := range ids { + m.billing_invoice_payment_app[ids[i]] = struct{}{} + } +} + +// ClearBillingInvoicePaymentApp clears the "billing_invoice_payment_app" edge to the BillingInvoice entity. +func (m *AppMutation) ClearBillingInvoicePaymentApp() { + m.clearedbilling_invoice_payment_app = true +} + +// BillingInvoicePaymentAppCleared reports if the "billing_invoice_payment_app" edge to the BillingInvoice entity was cleared. +func (m *AppMutation) BillingInvoicePaymentAppCleared() bool { + return m.clearedbilling_invoice_payment_app +} + +// RemoveBillingInvoicePaymentAppIDs removes the "billing_invoice_payment_app" edge to the BillingInvoice entity by IDs. +func (m *AppMutation) RemoveBillingInvoicePaymentAppIDs(ids ...string) { + if m.removedbilling_invoice_payment_app == nil { + m.removedbilling_invoice_payment_app = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_invoice_payment_app, ids[i]) + m.removedbilling_invoice_payment_app[ids[i]] = struct{}{} + } +} + +// RemovedBillingInvoicePaymentApp returns the removed IDs of the "billing_invoice_payment_app" edge to the BillingInvoice entity. +func (m *AppMutation) RemovedBillingInvoicePaymentAppIDs() (ids []string) { + for id := range m.removedbilling_invoice_payment_app { + ids = append(ids, id) + } + return +} + +// BillingInvoicePaymentAppIDs returns the "billing_invoice_payment_app" edge IDs in the mutation. +func (m *AppMutation) BillingInvoicePaymentAppIDs() (ids []string) { + for id := range m.billing_invoice_payment_app { + ids = append(ids, id) + } + return +} + +// ResetBillingInvoicePaymentApp resets all changes to the "billing_invoice_payment_app" edge. +func (m *AppMutation) ResetBillingInvoicePaymentApp() { + m.billing_invoice_payment_app = nil + m.clearedbilling_invoice_payment_app = false + m.removedbilling_invoice_payment_app = nil +} + +// Where appends a list predicates to the AppMutation builder. +func (m *AppMutation) Where(ps ...predicate.App) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AppMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AppMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.App, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AppMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AppMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (App). +func (m *AppMutation) 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 *AppMutation) Fields() []string { + fields := make([]string, 0, 9) + if m.namespace != nil { + fields = append(fields, dbapp.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, dbapp.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, dbapp.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, dbapp.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, dbapp.FieldDeletedAt) + } + if m.name != nil { + fields = append(fields, dbapp.FieldName) + } + if m.description != nil { + fields = append(fields, dbapp.FieldDescription) + } + if m._type != nil { + fields = append(fields, dbapp.FieldType) + } + if m.status != nil { + fields = append(fields, dbapp.FieldStatus) + } + 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 *AppMutation) Field(name string) (ent.Value, bool) { + switch name { + case dbapp.FieldNamespace: + return m.Namespace() + case dbapp.FieldMetadata: + return m.Metadata() + case dbapp.FieldCreatedAt: + return m.CreatedAt() + case dbapp.FieldUpdatedAt: + return m.UpdatedAt() + case dbapp.FieldDeletedAt: + return m.DeletedAt() + case dbapp.FieldName: + return m.Name() + case dbapp.FieldDescription: + return m.Description() + case dbapp.FieldType: + return m.GetType() + case dbapp.FieldStatus: + return m.Status() + } + 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 *AppMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case dbapp.FieldNamespace: + return m.OldNamespace(ctx) + case dbapp.FieldMetadata: + return m.OldMetadata(ctx) + case dbapp.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case dbapp.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case dbapp.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case dbapp.FieldName: + return m.OldName(ctx) + case dbapp.FieldDescription: + return m.OldDescription(ctx) + case dbapp.FieldType: + return m.OldType(ctx) + case dbapp.FieldStatus: + return m.OldStatus(ctx) + } + return nil, fmt.Errorf("unknown App 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 *AppMutation) SetField(name string, value ent.Value) error { + switch name { + case dbapp.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case dbapp.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case dbapp.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 dbapp.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 dbapp.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 dbapp.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case dbapp.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case dbapp.FieldType: + v, ok := value.(app.AppType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case dbapp.FieldStatus: + v, ok := value.(app.AppStatus) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + } + return fmt.Errorf("unknown App field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AppMutation) 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 *AppMutation) 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 *AppMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown App numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AppMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(dbapp.FieldMetadata) { + fields = append(fields, dbapp.FieldMetadata) + } + if m.FieldCleared(dbapp.FieldDeletedAt) { + fields = append(fields, dbapp.FieldDeletedAt) + } + if m.FieldCleared(dbapp.FieldDescription) { + fields = append(fields, dbapp.FieldDescription) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AppMutation) 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 *AppMutation) ClearField(name string) error { + switch name { + case dbapp.FieldMetadata: + m.ClearMetadata() + return nil + case dbapp.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case dbapp.FieldDescription: + m.ClearDescription() + return nil + } + return fmt.Errorf("unknown App 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 *AppMutation) ResetField(name string) error { + switch name { + case dbapp.FieldNamespace: + m.ResetNamespace() + return nil + case dbapp.FieldMetadata: + m.ResetMetadata() + return nil + case dbapp.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case dbapp.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case dbapp.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case dbapp.FieldName: + m.ResetName() + return nil + case dbapp.FieldDescription: + m.ResetDescription() + return nil + case dbapp.FieldType: + m.ResetType() + return nil + case dbapp.FieldStatus: + m.ResetStatus() + return nil + } + return fmt.Errorf("unknown App field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AppMutation) AddedEdges() []string { + edges := make([]string, 0, 7) + if m.customer_apps != nil { + edges = append(edges, dbapp.EdgeCustomerApps) + } + if m.billing_profile_tax_app != nil { + edges = append(edges, dbapp.EdgeBillingProfileTaxApp) + } + if m.billing_profile_invoicing_app != nil { + edges = append(edges, dbapp.EdgeBillingProfileInvoicingApp) + } + if m.billing_profile_payment_app != nil { + edges = append(edges, dbapp.EdgeBillingProfilePaymentApp) + } + if m.billing_invoice_tax_app != nil { + edges = append(edges, dbapp.EdgeBillingInvoiceTaxApp) + } + if m.billing_invoice_invoicing_app != nil { + edges = append(edges, dbapp.EdgeBillingInvoiceInvoicingApp) + } + if m.billing_invoice_payment_app != nil { + edges = append(edges, dbapp.EdgeBillingInvoicePaymentApp) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AppMutation) AddedIDs(name string) []ent.Value { + switch name { + case dbapp.EdgeCustomerApps: + ids := make([]ent.Value, 0, len(m.customer_apps)) + for id := range m.customer_apps { + ids = append(ids, id) + } + return ids + case dbapp.EdgeBillingProfileTaxApp: + ids := make([]ent.Value, 0, len(m.billing_profile_tax_app)) + for id := range m.billing_profile_tax_app { + ids = append(ids, id) + } + return ids + case dbapp.EdgeBillingProfileInvoicingApp: + ids := make([]ent.Value, 0, len(m.billing_profile_invoicing_app)) + for id := range m.billing_profile_invoicing_app { + ids = append(ids, id) + } + return ids + case dbapp.EdgeBillingProfilePaymentApp: + ids := make([]ent.Value, 0, len(m.billing_profile_payment_app)) + for id := range m.billing_profile_payment_app { + ids = append(ids, id) + } + return ids + case dbapp.EdgeBillingInvoiceTaxApp: + ids := make([]ent.Value, 0, len(m.billing_invoice_tax_app)) + for id := range m.billing_invoice_tax_app { + ids = append(ids, id) + } + return ids + case dbapp.EdgeBillingInvoiceInvoicingApp: + ids := make([]ent.Value, 0, len(m.billing_invoice_invoicing_app)) + for id := range m.billing_invoice_invoicing_app { + ids = append(ids, id) + } + return ids + case dbapp.EdgeBillingInvoicePaymentApp: + ids := make([]ent.Value, 0, len(m.billing_invoice_payment_app)) + for id := range m.billing_invoice_payment_app { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AppMutation) RemovedEdges() []string { + edges := make([]string, 0, 7) + if m.removedcustomer_apps != nil { + edges = append(edges, dbapp.EdgeCustomerApps) + } + if m.removedbilling_profile_tax_app != nil { + edges = append(edges, dbapp.EdgeBillingProfileTaxApp) + } + if m.removedbilling_profile_invoicing_app != nil { + edges = append(edges, dbapp.EdgeBillingProfileInvoicingApp) + } + if m.removedbilling_profile_payment_app != nil { + edges = append(edges, dbapp.EdgeBillingProfilePaymentApp) + } + if m.removedbilling_invoice_tax_app != nil { + edges = append(edges, dbapp.EdgeBillingInvoiceTaxApp) + } + if m.removedbilling_invoice_invoicing_app != nil { + edges = append(edges, dbapp.EdgeBillingInvoiceInvoicingApp) + } + if m.removedbilling_invoice_payment_app != nil { + edges = append(edges, dbapp.EdgeBillingInvoicePaymentApp) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AppMutation) RemovedIDs(name string) []ent.Value { + switch name { + case dbapp.EdgeCustomerApps: + ids := make([]ent.Value, 0, len(m.removedcustomer_apps)) + for id := range m.removedcustomer_apps { + ids = append(ids, id) + } + return ids + case dbapp.EdgeBillingProfileTaxApp: + ids := make([]ent.Value, 0, len(m.removedbilling_profile_tax_app)) + for id := range m.removedbilling_profile_tax_app { + ids = append(ids, id) + } + return ids + case dbapp.EdgeBillingProfileInvoicingApp: + ids := make([]ent.Value, 0, len(m.removedbilling_profile_invoicing_app)) + for id := range m.removedbilling_profile_invoicing_app { + ids = append(ids, id) + } + return ids + case dbapp.EdgeBillingProfilePaymentApp: + ids := make([]ent.Value, 0, len(m.removedbilling_profile_payment_app)) + for id := range m.removedbilling_profile_payment_app { + ids = append(ids, id) + } + return ids + case dbapp.EdgeBillingInvoiceTaxApp: + ids := make([]ent.Value, 0, len(m.removedbilling_invoice_tax_app)) + for id := range m.removedbilling_invoice_tax_app { + ids = append(ids, id) + } + return ids + case dbapp.EdgeBillingInvoiceInvoicingApp: + ids := make([]ent.Value, 0, len(m.removedbilling_invoice_invoicing_app)) + for id := range m.removedbilling_invoice_invoicing_app { + ids = append(ids, id) + } + return ids + case dbapp.EdgeBillingInvoicePaymentApp: + ids := make([]ent.Value, 0, len(m.removedbilling_invoice_payment_app)) + for id := range m.removedbilling_invoice_payment_app { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AppMutation) ClearedEdges() []string { + edges := make([]string, 0, 7) + if m.clearedcustomer_apps { + edges = append(edges, dbapp.EdgeCustomerApps) + } + if m.clearedbilling_profile_tax_app { + edges = append(edges, dbapp.EdgeBillingProfileTaxApp) + } + if m.clearedbilling_profile_invoicing_app { + edges = append(edges, dbapp.EdgeBillingProfileInvoicingApp) + } + if m.clearedbilling_profile_payment_app { + edges = append(edges, dbapp.EdgeBillingProfilePaymentApp) + } + if m.clearedbilling_invoice_tax_app { + edges = append(edges, dbapp.EdgeBillingInvoiceTaxApp) + } + if m.clearedbilling_invoice_invoicing_app { + edges = append(edges, dbapp.EdgeBillingInvoiceInvoicingApp) + } + if m.clearedbilling_invoice_payment_app { + edges = append(edges, dbapp.EdgeBillingInvoicePaymentApp) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AppMutation) EdgeCleared(name string) bool { + switch name { + case dbapp.EdgeCustomerApps: + return m.clearedcustomer_apps + case dbapp.EdgeBillingProfileTaxApp: + return m.clearedbilling_profile_tax_app + case dbapp.EdgeBillingProfileInvoicingApp: + return m.clearedbilling_profile_invoicing_app + case dbapp.EdgeBillingProfilePaymentApp: + return m.clearedbilling_profile_payment_app + case dbapp.EdgeBillingInvoiceTaxApp: + return m.clearedbilling_invoice_tax_app + case dbapp.EdgeBillingInvoiceInvoicingApp: + return m.clearedbilling_invoice_invoicing_app + case dbapp.EdgeBillingInvoicePaymentApp: + return m.clearedbilling_invoice_payment_app + } + 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 *AppMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown App 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 *AppMutation) ResetEdge(name string) error { + switch name { + case dbapp.EdgeCustomerApps: + m.ResetCustomerApps() + return nil + case dbapp.EdgeBillingProfileTaxApp: + m.ResetBillingProfileTaxApp() + return nil + case dbapp.EdgeBillingProfileInvoicingApp: + m.ResetBillingProfileInvoicingApp() + return nil + case dbapp.EdgeBillingProfilePaymentApp: + m.ResetBillingProfilePaymentApp() + return nil + case dbapp.EdgeBillingInvoiceTaxApp: + m.ResetBillingInvoiceTaxApp() + return nil + case dbapp.EdgeBillingInvoiceInvoicingApp: + m.ResetBillingInvoiceInvoicingApp() + return nil + case dbapp.EdgeBillingInvoicePaymentApp: + m.ResetBillingInvoicePaymentApp() + return nil + } + return fmt.Errorf("unknown App edge %s", name) +} + +// AppCustomInvoicingMutation represents an operation that mutates the AppCustomInvoicing nodes in the graph. +type AppCustomInvoicingMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + enable_draft_sync_hook *bool + enable_issuing_sync_hook *bool + clearedFields map[string]struct{} + customer_apps map[int]struct{} + removedcustomer_apps map[int]struct{} + clearedcustomer_apps bool + app *string + clearedapp bool + done bool + oldValue func(context.Context) (*AppCustomInvoicing, error) + predicates []predicate.AppCustomInvoicing +} + +var _ ent.Mutation = (*AppCustomInvoicingMutation)(nil) + +// appcustominvoicingOption allows management of the mutation configuration using functional options. +type appcustominvoicingOption func(*AppCustomInvoicingMutation) + +// newAppCustomInvoicingMutation creates new mutation for the AppCustomInvoicing entity. +func newAppCustomInvoicingMutation(c config, op Op, opts ...appcustominvoicingOption) *AppCustomInvoicingMutation { + m := &AppCustomInvoicingMutation{ + config: c, + op: op, + typ: TypeAppCustomInvoicing, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAppCustomInvoicingID sets the ID field of the mutation. +func withAppCustomInvoicingID(id string) appcustominvoicingOption { + return func(m *AppCustomInvoicingMutation) { + var ( + err error + once sync.Once + value *AppCustomInvoicing + ) + m.oldValue = func(ctx context.Context) (*AppCustomInvoicing, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().AppCustomInvoicing.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAppCustomInvoicing sets the old AppCustomInvoicing of the mutation. +func withAppCustomInvoicing(node *AppCustomInvoicing) appcustominvoicingOption { + return func(m *AppCustomInvoicingMutation) { + m.oldValue = func(context.Context) (*AppCustomInvoicing, 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 AppCustomInvoicingMutation) 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 AppCustomInvoicingMutation) 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 AppCustomInvoicing entities. +func (m *AppCustomInvoicingMutation) 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 *AppCustomInvoicingMutation) 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 *AppCustomInvoicingMutation) 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().AppCustomInvoicing.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 *AppCustomInvoicingMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *AppCustomInvoicingMutation) 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 AppCustomInvoicing entity. +// If the AppCustomInvoicing 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 *AppCustomInvoicingMutation) 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 *AppCustomInvoicingMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *AppCustomInvoicingMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *AppCustomInvoicingMutation) 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 AppCustomInvoicing entity. +// If the AppCustomInvoicing 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 *AppCustomInvoicingMutation) 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 *AppCustomInvoicingMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *AppCustomInvoicingMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *AppCustomInvoicingMutation) 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 AppCustomInvoicing entity. +// If the AppCustomInvoicing 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 *AppCustomInvoicingMutation) 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 *AppCustomInvoicingMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *AppCustomInvoicingMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *AppCustomInvoicingMutation) 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 AppCustomInvoicing entity. +// If the AppCustomInvoicing 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 *AppCustomInvoicingMutation) 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 *AppCustomInvoicingMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[appcustominvoicing.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *AppCustomInvoicingMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[appcustominvoicing.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *AppCustomInvoicingMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, appcustominvoicing.FieldDeletedAt) +} + +// SetEnableDraftSyncHook sets the "enable_draft_sync_hook" field. +func (m *AppCustomInvoicingMutation) SetEnableDraftSyncHook(b bool) { + m.enable_draft_sync_hook = &b +} + +// EnableDraftSyncHook returns the value of the "enable_draft_sync_hook" field in the mutation. +func (m *AppCustomInvoicingMutation) EnableDraftSyncHook() (r bool, exists bool) { + v := m.enable_draft_sync_hook + if v == nil { + return + } + return *v, true +} + +// OldEnableDraftSyncHook returns the old "enable_draft_sync_hook" field's value of the AppCustomInvoicing entity. +// If the AppCustomInvoicing 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 *AppCustomInvoicingMutation) OldEnableDraftSyncHook(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEnableDraftSyncHook is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEnableDraftSyncHook requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEnableDraftSyncHook: %w", err) + } + return oldValue.EnableDraftSyncHook, nil +} + +// ResetEnableDraftSyncHook resets all changes to the "enable_draft_sync_hook" field. +func (m *AppCustomInvoicingMutation) ResetEnableDraftSyncHook() { + m.enable_draft_sync_hook = nil +} + +// SetEnableIssuingSyncHook sets the "enable_issuing_sync_hook" field. +func (m *AppCustomInvoicingMutation) SetEnableIssuingSyncHook(b bool) { + m.enable_issuing_sync_hook = &b +} + +// EnableIssuingSyncHook returns the value of the "enable_issuing_sync_hook" field in the mutation. +func (m *AppCustomInvoicingMutation) EnableIssuingSyncHook() (r bool, exists bool) { + v := m.enable_issuing_sync_hook + if v == nil { + return + } + return *v, true +} + +// OldEnableIssuingSyncHook returns the old "enable_issuing_sync_hook" field's value of the AppCustomInvoicing entity. +// If the AppCustomInvoicing 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 *AppCustomInvoicingMutation) OldEnableIssuingSyncHook(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEnableIssuingSyncHook is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEnableIssuingSyncHook requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEnableIssuingSyncHook: %w", err) + } + return oldValue.EnableIssuingSyncHook, nil +} + +// ResetEnableIssuingSyncHook resets all changes to the "enable_issuing_sync_hook" field. +func (m *AppCustomInvoicingMutation) ResetEnableIssuingSyncHook() { + m.enable_issuing_sync_hook = nil +} + +// AddCustomerAppIDs adds the "customer_apps" edge to the AppCustomInvoicingCustomer entity by ids. +func (m *AppCustomInvoicingMutation) AddCustomerAppIDs(ids ...int) { + if m.customer_apps == nil { + m.customer_apps = make(map[int]struct{}) + } + for i := range ids { + m.customer_apps[ids[i]] = struct{}{} + } +} + +// ClearCustomerApps clears the "customer_apps" edge to the AppCustomInvoicingCustomer entity. +func (m *AppCustomInvoicingMutation) ClearCustomerApps() { + m.clearedcustomer_apps = true +} + +// CustomerAppsCleared reports if the "customer_apps" edge to the AppCustomInvoicingCustomer entity was cleared. +func (m *AppCustomInvoicingMutation) CustomerAppsCleared() bool { + return m.clearedcustomer_apps +} + +// RemoveCustomerAppIDs removes the "customer_apps" edge to the AppCustomInvoicingCustomer entity by IDs. +func (m *AppCustomInvoicingMutation) RemoveCustomerAppIDs(ids ...int) { + if m.removedcustomer_apps == nil { + m.removedcustomer_apps = make(map[int]struct{}) + } + for i := range ids { + delete(m.customer_apps, ids[i]) + m.removedcustomer_apps[ids[i]] = struct{}{} + } +} + +// RemovedCustomerApps returns the removed IDs of the "customer_apps" edge to the AppCustomInvoicingCustomer entity. +func (m *AppCustomInvoicingMutation) RemovedCustomerAppsIDs() (ids []int) { + for id := range m.removedcustomer_apps { + ids = append(ids, id) + } + return +} + +// CustomerAppsIDs returns the "customer_apps" edge IDs in the mutation. +func (m *AppCustomInvoicingMutation) CustomerAppsIDs() (ids []int) { + for id := range m.customer_apps { + ids = append(ids, id) + } + return +} + +// ResetCustomerApps resets all changes to the "customer_apps" edge. +func (m *AppCustomInvoicingMutation) ResetCustomerApps() { + m.customer_apps = nil + m.clearedcustomer_apps = false + m.removedcustomer_apps = nil +} + +// SetAppID sets the "app" edge to the App entity by id. +func (m *AppCustomInvoicingMutation) SetAppID(id string) { + m.app = &id +} + +// ClearApp clears the "app" edge to the App entity. +func (m *AppCustomInvoicingMutation) ClearApp() { + m.clearedapp = true +} + +// AppCleared reports if the "app" edge to the App entity was cleared. +func (m *AppCustomInvoicingMutation) AppCleared() bool { + return m.clearedapp +} + +// AppID returns the "app" edge ID in the mutation. +func (m *AppCustomInvoicingMutation) AppID() (id string, exists bool) { + if m.app != nil { + return *m.app, true + } + return +} + +// AppIDs returns the "app" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// AppID instead. It exists only for internal usage by the builders. +func (m *AppCustomInvoicingMutation) AppIDs() (ids []string) { + if id := m.app; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetApp resets all changes to the "app" edge. +func (m *AppCustomInvoicingMutation) ResetApp() { + m.app = nil + m.clearedapp = false +} + +// Where appends a list predicates to the AppCustomInvoicingMutation builder. +func (m *AppCustomInvoicingMutation) Where(ps ...predicate.AppCustomInvoicing) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AppCustomInvoicingMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AppCustomInvoicingMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.AppCustomInvoicing, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AppCustomInvoicingMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AppCustomInvoicingMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (AppCustomInvoicing). +func (m *AppCustomInvoicingMutation) 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 *AppCustomInvoicingMutation) Fields() []string { + fields := make([]string, 0, 6) + if m.namespace != nil { + fields = append(fields, appcustominvoicing.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, appcustominvoicing.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, appcustominvoicing.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, appcustominvoicing.FieldDeletedAt) + } + if m.enable_draft_sync_hook != nil { + fields = append(fields, appcustominvoicing.FieldEnableDraftSyncHook) + } + if m.enable_issuing_sync_hook != nil { + fields = append(fields, appcustominvoicing.FieldEnableIssuingSyncHook) + } + 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 *AppCustomInvoicingMutation) Field(name string) (ent.Value, bool) { + switch name { + case appcustominvoicing.FieldNamespace: + return m.Namespace() + case appcustominvoicing.FieldCreatedAt: + return m.CreatedAt() + case appcustominvoicing.FieldUpdatedAt: + return m.UpdatedAt() + case appcustominvoicing.FieldDeletedAt: + return m.DeletedAt() + case appcustominvoicing.FieldEnableDraftSyncHook: + return m.EnableDraftSyncHook() + case appcustominvoicing.FieldEnableIssuingSyncHook: + return m.EnableIssuingSyncHook() + } + 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 *AppCustomInvoicingMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case appcustominvoicing.FieldNamespace: + return m.OldNamespace(ctx) + case appcustominvoicing.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case appcustominvoicing.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case appcustominvoicing.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case appcustominvoicing.FieldEnableDraftSyncHook: + return m.OldEnableDraftSyncHook(ctx) + case appcustominvoicing.FieldEnableIssuingSyncHook: + return m.OldEnableIssuingSyncHook(ctx) + } + return nil, fmt.Errorf("unknown AppCustomInvoicing 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 *AppCustomInvoicingMutation) SetField(name string, value ent.Value) error { + switch name { + case appcustominvoicing.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case appcustominvoicing.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 appcustominvoicing.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 appcustominvoicing.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 appcustominvoicing.FieldEnableDraftSyncHook: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEnableDraftSyncHook(v) + return nil + case appcustominvoicing.FieldEnableIssuingSyncHook: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEnableIssuingSyncHook(v) + return nil + } + return fmt.Errorf("unknown AppCustomInvoicing field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AppCustomInvoicingMutation) 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 *AppCustomInvoicingMutation) 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 *AppCustomInvoicingMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown AppCustomInvoicing numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AppCustomInvoicingMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(appcustominvoicing.FieldDeletedAt) { + fields = append(fields, appcustominvoicing.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AppCustomInvoicingMutation) 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 *AppCustomInvoicingMutation) ClearField(name string) error { + switch name { + case appcustominvoicing.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown AppCustomInvoicing 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 *AppCustomInvoicingMutation) ResetField(name string) error { + switch name { + case appcustominvoicing.FieldNamespace: + m.ResetNamespace() + return nil + case appcustominvoicing.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case appcustominvoicing.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case appcustominvoicing.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case appcustominvoicing.FieldEnableDraftSyncHook: + m.ResetEnableDraftSyncHook() + return nil + case appcustominvoicing.FieldEnableIssuingSyncHook: + m.ResetEnableIssuingSyncHook() + return nil + } + return fmt.Errorf("unknown AppCustomInvoicing field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AppCustomInvoicingMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.customer_apps != nil { + edges = append(edges, appcustominvoicing.EdgeCustomerApps) + } + if m.app != nil { + edges = append(edges, appcustominvoicing.EdgeApp) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AppCustomInvoicingMutation) AddedIDs(name string) []ent.Value { + switch name { + case appcustominvoicing.EdgeCustomerApps: + ids := make([]ent.Value, 0, len(m.customer_apps)) + for id := range m.customer_apps { + ids = append(ids, id) + } + return ids + case appcustominvoicing.EdgeApp: + if id := m.app; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AppCustomInvoicingMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedcustomer_apps != nil { + edges = append(edges, appcustominvoicing.EdgeCustomerApps) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AppCustomInvoicingMutation) RemovedIDs(name string) []ent.Value { + switch name { + case appcustominvoicing.EdgeCustomerApps: + ids := make([]ent.Value, 0, len(m.removedcustomer_apps)) + for id := range m.removedcustomer_apps { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AppCustomInvoicingMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedcustomer_apps { + edges = append(edges, appcustominvoicing.EdgeCustomerApps) + } + if m.clearedapp { + edges = append(edges, appcustominvoicing.EdgeApp) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AppCustomInvoicingMutation) EdgeCleared(name string) bool { + switch name { + case appcustominvoicing.EdgeCustomerApps: + return m.clearedcustomer_apps + case appcustominvoicing.EdgeApp: + return m.clearedapp + } + 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 *AppCustomInvoicingMutation) ClearEdge(name string) error { + switch name { + case appcustominvoicing.EdgeApp: + m.ClearApp() + return nil + } + return fmt.Errorf("unknown AppCustomInvoicing 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 *AppCustomInvoicingMutation) ResetEdge(name string) error { + switch name { + case appcustominvoicing.EdgeCustomerApps: + m.ResetCustomerApps() + return nil + case appcustominvoicing.EdgeApp: + m.ResetApp() + return nil + } + return fmt.Errorf("unknown AppCustomInvoicing edge %s", name) +} + +// AppCustomInvoicingCustomerMutation represents an operation that mutates the AppCustomInvoicingCustomer nodes in the graph. +type AppCustomInvoicingCustomerMutation struct { + config + op Op + typ string + id *int + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + metadata *map[string]string + clearedFields map[string]struct{} + custom_invoicing_app *string + clearedcustom_invoicing_app bool + customer *string + clearedcustomer bool + done bool + oldValue func(context.Context) (*AppCustomInvoicingCustomer, error) + predicates []predicate.AppCustomInvoicingCustomer +} + +var _ ent.Mutation = (*AppCustomInvoicingCustomerMutation)(nil) + +// appcustominvoicingcustomerOption allows management of the mutation configuration using functional options. +type appcustominvoicingcustomerOption func(*AppCustomInvoicingCustomerMutation) + +// newAppCustomInvoicingCustomerMutation creates new mutation for the AppCustomInvoicingCustomer entity. +func newAppCustomInvoicingCustomerMutation(c config, op Op, opts ...appcustominvoicingcustomerOption) *AppCustomInvoicingCustomerMutation { + m := &AppCustomInvoicingCustomerMutation{ + config: c, + op: op, + typ: TypeAppCustomInvoicingCustomer, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAppCustomInvoicingCustomerID sets the ID field of the mutation. +func withAppCustomInvoicingCustomerID(id int) appcustominvoicingcustomerOption { + return func(m *AppCustomInvoicingCustomerMutation) { + var ( + err error + once sync.Once + value *AppCustomInvoicingCustomer + ) + m.oldValue = func(ctx context.Context) (*AppCustomInvoicingCustomer, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().AppCustomInvoicingCustomer.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAppCustomInvoicingCustomer sets the old AppCustomInvoicingCustomer of the mutation. +func withAppCustomInvoicingCustomer(node *AppCustomInvoicingCustomer) appcustominvoicingcustomerOption { + return func(m *AppCustomInvoicingCustomerMutation) { + m.oldValue = func(context.Context) (*AppCustomInvoicingCustomer, 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 AppCustomInvoicingCustomerMutation) 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 AppCustomInvoicingCustomerMutation) 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 +} + +// 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 *AppCustomInvoicingCustomerMutation) ID() (id int, 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 *AppCustomInvoicingCustomerMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().AppCustomInvoicingCustomer.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 *AppCustomInvoicingCustomerMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *AppCustomInvoicingCustomerMutation) 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 AppCustomInvoicingCustomer entity. +// If the AppCustomInvoicingCustomer 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 *AppCustomInvoicingCustomerMutation) 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 *AppCustomInvoicingCustomerMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *AppCustomInvoicingCustomerMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *AppCustomInvoicingCustomerMutation) 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 AppCustomInvoicingCustomer entity. +// If the AppCustomInvoicingCustomer 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 *AppCustomInvoicingCustomerMutation) 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 *AppCustomInvoicingCustomerMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *AppCustomInvoicingCustomerMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *AppCustomInvoicingCustomerMutation) 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 AppCustomInvoicingCustomer entity. +// If the AppCustomInvoicingCustomer 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 *AppCustomInvoicingCustomerMutation) 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 *AppCustomInvoicingCustomerMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *AppCustomInvoicingCustomerMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *AppCustomInvoicingCustomerMutation) 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 AppCustomInvoicingCustomer entity. +// If the AppCustomInvoicingCustomer 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 *AppCustomInvoicingCustomerMutation) 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 *AppCustomInvoicingCustomerMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[appcustominvoicingcustomer.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *AppCustomInvoicingCustomerMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[appcustominvoicingcustomer.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *AppCustomInvoicingCustomerMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, appcustominvoicingcustomer.FieldDeletedAt) +} + +// SetMetadata sets the "metadata" field. +func (m *AppCustomInvoicingCustomerMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *AppCustomInvoicingCustomerMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the AppCustomInvoicingCustomer entity. +// If the AppCustomInvoicingCustomer 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 *AppCustomInvoicingCustomerMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *AppCustomInvoicingCustomerMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[appcustominvoicingcustomer.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *AppCustomInvoicingCustomerMutation) MetadataCleared() bool { + _, ok := m.clearedFields[appcustominvoicingcustomer.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *AppCustomInvoicingCustomerMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, appcustominvoicingcustomer.FieldMetadata) +} + +// SetAppID sets the "app_id" field. +func (m *AppCustomInvoicingCustomerMutation) SetAppID(s string) { + m.custom_invoicing_app = &s +} + +// AppID returns the value of the "app_id" field in the mutation. +func (m *AppCustomInvoicingCustomerMutation) AppID() (r string, exists bool) { + v := m.custom_invoicing_app + if v == nil { + return + } + return *v, true +} + +// OldAppID returns the old "app_id" field's value of the AppCustomInvoicingCustomer entity. +// If the AppCustomInvoicingCustomer 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 *AppCustomInvoicingCustomerMutation) OldAppID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAppID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAppID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAppID: %w", err) + } + return oldValue.AppID, nil +} + +// ResetAppID resets all changes to the "app_id" field. +func (m *AppCustomInvoicingCustomerMutation) ResetAppID() { + m.custom_invoicing_app = nil +} + +// SetCustomerID sets the "customer_id" field. +func (m *AppCustomInvoicingCustomerMutation) SetCustomerID(s string) { + m.customer = &s +} + +// CustomerID returns the value of the "customer_id" field in the mutation. +func (m *AppCustomInvoicingCustomerMutation) CustomerID() (r string, exists bool) { + v := m.customer + if v == nil { + return + } + return *v, true +} + +// OldCustomerID returns the old "customer_id" field's value of the AppCustomInvoicingCustomer entity. +// If the AppCustomInvoicingCustomer 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 *AppCustomInvoicingCustomerMutation) OldCustomerID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerID: %w", err) + } + return oldValue.CustomerID, nil +} + +// ResetCustomerID resets all changes to the "customer_id" field. +func (m *AppCustomInvoicingCustomerMutation) ResetCustomerID() { + m.customer = nil +} + +// SetCustomInvoicingAppID sets the "custom_invoicing_app" edge to the AppCustomInvoicing entity by id. +func (m *AppCustomInvoicingCustomerMutation) SetCustomInvoicingAppID(id string) { + m.custom_invoicing_app = &id +} + +// ClearCustomInvoicingApp clears the "custom_invoicing_app" edge to the AppCustomInvoicing entity. +func (m *AppCustomInvoicingCustomerMutation) ClearCustomInvoicingApp() { + m.clearedcustom_invoicing_app = true + m.clearedFields[appcustominvoicingcustomer.FieldAppID] = struct{}{} +} + +// CustomInvoicingAppCleared reports if the "custom_invoicing_app" edge to the AppCustomInvoicing entity was cleared. +func (m *AppCustomInvoicingCustomerMutation) CustomInvoicingAppCleared() bool { + return m.clearedcustom_invoicing_app +} + +// CustomInvoicingAppID returns the "custom_invoicing_app" edge ID in the mutation. +func (m *AppCustomInvoicingCustomerMutation) CustomInvoicingAppID() (id string, exists bool) { + if m.custom_invoicing_app != nil { + return *m.custom_invoicing_app, true + } + return +} + +// CustomInvoicingAppIDs returns the "custom_invoicing_app" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CustomInvoicingAppID instead. It exists only for internal usage by the builders. +func (m *AppCustomInvoicingCustomerMutation) CustomInvoicingAppIDs() (ids []string) { + if id := m.custom_invoicing_app; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCustomInvoicingApp resets all changes to the "custom_invoicing_app" edge. +func (m *AppCustomInvoicingCustomerMutation) ResetCustomInvoicingApp() { + m.custom_invoicing_app = nil + m.clearedcustom_invoicing_app = false +} + +// ClearCustomer clears the "customer" edge to the Customer entity. +func (m *AppCustomInvoicingCustomerMutation) ClearCustomer() { + m.clearedcustomer = true + m.clearedFields[appcustominvoicingcustomer.FieldCustomerID] = struct{}{} +} + +// CustomerCleared reports if the "customer" edge to the Customer entity was cleared. +func (m *AppCustomInvoicingCustomerMutation) CustomerCleared() bool { + return m.clearedcustomer +} + +// CustomerIDs returns the "customer" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CustomerID instead. It exists only for internal usage by the builders. +func (m *AppCustomInvoicingCustomerMutation) CustomerIDs() (ids []string) { + if id := m.customer; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCustomer resets all changes to the "customer" edge. +func (m *AppCustomInvoicingCustomerMutation) ResetCustomer() { + m.customer = nil + m.clearedcustomer = false +} + +// Where appends a list predicates to the AppCustomInvoicingCustomerMutation builder. +func (m *AppCustomInvoicingCustomerMutation) Where(ps ...predicate.AppCustomInvoicingCustomer) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AppCustomInvoicingCustomerMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AppCustomInvoicingCustomerMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.AppCustomInvoicingCustomer, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AppCustomInvoicingCustomerMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AppCustomInvoicingCustomerMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (AppCustomInvoicingCustomer). +func (m *AppCustomInvoicingCustomerMutation) 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 *AppCustomInvoicingCustomerMutation) Fields() []string { + fields := make([]string, 0, 7) + if m.namespace != nil { + fields = append(fields, appcustominvoicingcustomer.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, appcustominvoicingcustomer.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, appcustominvoicingcustomer.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, appcustominvoicingcustomer.FieldDeletedAt) + } + if m.metadata != nil { + fields = append(fields, appcustominvoicingcustomer.FieldMetadata) + } + if m.custom_invoicing_app != nil { + fields = append(fields, appcustominvoicingcustomer.FieldAppID) + } + if m.customer != nil { + fields = append(fields, appcustominvoicingcustomer.FieldCustomerID) + } + 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 *AppCustomInvoicingCustomerMutation) Field(name string) (ent.Value, bool) { + switch name { + case appcustominvoicingcustomer.FieldNamespace: + return m.Namespace() + case appcustominvoicingcustomer.FieldCreatedAt: + return m.CreatedAt() + case appcustominvoicingcustomer.FieldUpdatedAt: + return m.UpdatedAt() + case appcustominvoicingcustomer.FieldDeletedAt: + return m.DeletedAt() + case appcustominvoicingcustomer.FieldMetadata: + return m.Metadata() + case appcustominvoicingcustomer.FieldAppID: + return m.AppID() + case appcustominvoicingcustomer.FieldCustomerID: + return m.CustomerID() + } + 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 *AppCustomInvoicingCustomerMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case appcustominvoicingcustomer.FieldNamespace: + return m.OldNamespace(ctx) + case appcustominvoicingcustomer.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case appcustominvoicingcustomer.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case appcustominvoicingcustomer.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case appcustominvoicingcustomer.FieldMetadata: + return m.OldMetadata(ctx) + case appcustominvoicingcustomer.FieldAppID: + return m.OldAppID(ctx) + case appcustominvoicingcustomer.FieldCustomerID: + return m.OldCustomerID(ctx) + } + return nil, fmt.Errorf("unknown AppCustomInvoicingCustomer 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 *AppCustomInvoicingCustomerMutation) SetField(name string, value ent.Value) error { + switch name { + case appcustominvoicingcustomer.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case appcustominvoicingcustomer.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 appcustominvoicingcustomer.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 appcustominvoicingcustomer.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 appcustominvoicingcustomer.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case appcustominvoicingcustomer.FieldAppID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAppID(v) + return nil + case appcustominvoicingcustomer.FieldCustomerID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerID(v) + return nil + } + return fmt.Errorf("unknown AppCustomInvoicingCustomer field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AppCustomInvoicingCustomerMutation) 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 *AppCustomInvoicingCustomerMutation) 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 *AppCustomInvoicingCustomerMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown AppCustomInvoicingCustomer numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AppCustomInvoicingCustomerMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(appcustominvoicingcustomer.FieldDeletedAt) { + fields = append(fields, appcustominvoicingcustomer.FieldDeletedAt) + } + if m.FieldCleared(appcustominvoicingcustomer.FieldMetadata) { + fields = append(fields, appcustominvoicingcustomer.FieldMetadata) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AppCustomInvoicingCustomerMutation) 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 *AppCustomInvoicingCustomerMutation) ClearField(name string) error { + switch name { + case appcustominvoicingcustomer.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case appcustominvoicingcustomer.FieldMetadata: + m.ClearMetadata() + return nil + } + return fmt.Errorf("unknown AppCustomInvoicingCustomer 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 *AppCustomInvoicingCustomerMutation) ResetField(name string) error { + switch name { + case appcustominvoicingcustomer.FieldNamespace: + m.ResetNamespace() + return nil + case appcustominvoicingcustomer.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case appcustominvoicingcustomer.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case appcustominvoicingcustomer.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case appcustominvoicingcustomer.FieldMetadata: + m.ResetMetadata() + return nil + case appcustominvoicingcustomer.FieldAppID: + m.ResetAppID() + return nil + case appcustominvoicingcustomer.FieldCustomerID: + m.ResetCustomerID() + return nil + } + return fmt.Errorf("unknown AppCustomInvoicingCustomer field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AppCustomInvoicingCustomerMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.custom_invoicing_app != nil { + edges = append(edges, appcustominvoicingcustomer.EdgeCustomInvoicingApp) + } + if m.customer != nil { + edges = append(edges, appcustominvoicingcustomer.EdgeCustomer) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AppCustomInvoicingCustomerMutation) AddedIDs(name string) []ent.Value { + switch name { + case appcustominvoicingcustomer.EdgeCustomInvoicingApp: + if id := m.custom_invoicing_app; id != nil { + return []ent.Value{*id} + } + case appcustominvoicingcustomer.EdgeCustomer: + if id := m.customer; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AppCustomInvoicingCustomerMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AppCustomInvoicingCustomerMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AppCustomInvoicingCustomerMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedcustom_invoicing_app { + edges = append(edges, appcustominvoicingcustomer.EdgeCustomInvoicingApp) + } + if m.clearedcustomer { + edges = append(edges, appcustominvoicingcustomer.EdgeCustomer) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AppCustomInvoicingCustomerMutation) EdgeCleared(name string) bool { + switch name { + case appcustominvoicingcustomer.EdgeCustomInvoicingApp: + return m.clearedcustom_invoicing_app + case appcustominvoicingcustomer.EdgeCustomer: + return m.clearedcustomer + } + 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 *AppCustomInvoicingCustomerMutation) ClearEdge(name string) error { + switch name { + case appcustominvoicingcustomer.EdgeCustomInvoicingApp: + m.ClearCustomInvoicingApp() + return nil + case appcustominvoicingcustomer.EdgeCustomer: + m.ClearCustomer() + return nil + } + return fmt.Errorf("unknown AppCustomInvoicingCustomer 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 *AppCustomInvoicingCustomerMutation) ResetEdge(name string) error { + switch name { + case appcustominvoicingcustomer.EdgeCustomInvoicingApp: + m.ResetCustomInvoicingApp() + return nil + case appcustominvoicingcustomer.EdgeCustomer: + m.ResetCustomer() + return nil + } + return fmt.Errorf("unknown AppCustomInvoicingCustomer edge %s", name) +} + +// AppCustomerMutation represents an operation that mutates the AppCustomer nodes in the graph. +type AppCustomerMutation struct { + config + op Op + typ string + id *int + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + clearedFields map[string]struct{} + app *string + clearedapp bool + customer *string + clearedcustomer bool + done bool + oldValue func(context.Context) (*AppCustomer, error) + predicates []predicate.AppCustomer +} + +var _ ent.Mutation = (*AppCustomerMutation)(nil) + +// appcustomerOption allows management of the mutation configuration using functional options. +type appcustomerOption func(*AppCustomerMutation) + +// newAppCustomerMutation creates new mutation for the AppCustomer entity. +func newAppCustomerMutation(c config, op Op, opts ...appcustomerOption) *AppCustomerMutation { + m := &AppCustomerMutation{ + config: c, + op: op, + typ: TypeAppCustomer, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAppCustomerID sets the ID field of the mutation. +func withAppCustomerID(id int) appcustomerOption { + return func(m *AppCustomerMutation) { + var ( + err error + once sync.Once + value *AppCustomer + ) + m.oldValue = func(ctx context.Context) (*AppCustomer, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().AppCustomer.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAppCustomer sets the old AppCustomer of the mutation. +func withAppCustomer(node *AppCustomer) appcustomerOption { + return func(m *AppCustomerMutation) { + m.oldValue = func(context.Context) (*AppCustomer, 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 AppCustomerMutation) 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 AppCustomerMutation) 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 +} + +// 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 *AppCustomerMutation) ID() (id int, 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 *AppCustomerMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().AppCustomer.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 *AppCustomerMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *AppCustomerMutation) 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 AppCustomer entity. +// If the AppCustomer 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 *AppCustomerMutation) 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 *AppCustomerMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *AppCustomerMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *AppCustomerMutation) 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 AppCustomer entity. +// If the AppCustomer 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 *AppCustomerMutation) 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 *AppCustomerMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *AppCustomerMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *AppCustomerMutation) 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 AppCustomer entity. +// If the AppCustomer 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 *AppCustomerMutation) 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 *AppCustomerMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *AppCustomerMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *AppCustomerMutation) 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 AppCustomer entity. +// If the AppCustomer 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 *AppCustomerMutation) 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 *AppCustomerMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[appcustomer.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *AppCustomerMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[appcustomer.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *AppCustomerMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, appcustomer.FieldDeletedAt) +} + +// SetAppID sets the "app_id" field. +func (m *AppCustomerMutation) SetAppID(s string) { + m.app = &s +} + +// AppID returns the value of the "app_id" field in the mutation. +func (m *AppCustomerMutation) AppID() (r string, exists bool) { + v := m.app + if v == nil { + return + } + return *v, true +} + +// OldAppID returns the old "app_id" field's value of the AppCustomer entity. +// If the AppCustomer 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 *AppCustomerMutation) OldAppID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAppID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAppID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAppID: %w", err) + } + return oldValue.AppID, nil +} + +// ResetAppID resets all changes to the "app_id" field. +func (m *AppCustomerMutation) ResetAppID() { + m.app = nil +} + +// SetCustomerID sets the "customer_id" field. +func (m *AppCustomerMutation) SetCustomerID(s string) { + m.customer = &s +} + +// CustomerID returns the value of the "customer_id" field in the mutation. +func (m *AppCustomerMutation) CustomerID() (r string, exists bool) { + v := m.customer + if v == nil { + return + } + return *v, true +} + +// OldCustomerID returns the old "customer_id" field's value of the AppCustomer entity. +// If the AppCustomer 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 *AppCustomerMutation) OldCustomerID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerID: %w", err) + } + return oldValue.CustomerID, nil +} + +// ResetCustomerID resets all changes to the "customer_id" field. +func (m *AppCustomerMutation) ResetCustomerID() { + m.customer = nil +} + +// ClearApp clears the "app" edge to the App entity. +func (m *AppCustomerMutation) ClearApp() { + m.clearedapp = true + m.clearedFields[appcustomer.FieldAppID] = struct{}{} +} + +// AppCleared reports if the "app" edge to the App entity was cleared. +func (m *AppCustomerMutation) AppCleared() bool { + return m.clearedapp +} + +// AppIDs returns the "app" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// AppID instead. It exists only for internal usage by the builders. +func (m *AppCustomerMutation) AppIDs() (ids []string) { + if id := m.app; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetApp resets all changes to the "app" edge. +func (m *AppCustomerMutation) ResetApp() { + m.app = nil + m.clearedapp = false +} + +// ClearCustomer clears the "customer" edge to the Customer entity. +func (m *AppCustomerMutation) ClearCustomer() { + m.clearedcustomer = true + m.clearedFields[appcustomer.FieldCustomerID] = struct{}{} +} + +// CustomerCleared reports if the "customer" edge to the Customer entity was cleared. +func (m *AppCustomerMutation) CustomerCleared() bool { + return m.clearedcustomer +} + +// CustomerIDs returns the "customer" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CustomerID instead. It exists only for internal usage by the builders. +func (m *AppCustomerMutation) CustomerIDs() (ids []string) { + if id := m.customer; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCustomer resets all changes to the "customer" edge. +func (m *AppCustomerMutation) ResetCustomer() { + m.customer = nil + m.clearedcustomer = false +} + +// Where appends a list predicates to the AppCustomerMutation builder. +func (m *AppCustomerMutation) Where(ps ...predicate.AppCustomer) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AppCustomerMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AppCustomerMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.AppCustomer, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AppCustomerMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AppCustomerMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (AppCustomer). +func (m *AppCustomerMutation) 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 *AppCustomerMutation) Fields() []string { + fields := make([]string, 0, 6) + if m.namespace != nil { + fields = append(fields, appcustomer.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, appcustomer.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, appcustomer.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, appcustomer.FieldDeletedAt) + } + if m.app != nil { + fields = append(fields, appcustomer.FieldAppID) + } + if m.customer != nil { + fields = append(fields, appcustomer.FieldCustomerID) + } + 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 *AppCustomerMutation) Field(name string) (ent.Value, bool) { + switch name { + case appcustomer.FieldNamespace: + return m.Namespace() + case appcustomer.FieldCreatedAt: + return m.CreatedAt() + case appcustomer.FieldUpdatedAt: + return m.UpdatedAt() + case appcustomer.FieldDeletedAt: + return m.DeletedAt() + case appcustomer.FieldAppID: + return m.AppID() + case appcustomer.FieldCustomerID: + return m.CustomerID() + } + 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 *AppCustomerMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case appcustomer.FieldNamespace: + return m.OldNamespace(ctx) + case appcustomer.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case appcustomer.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case appcustomer.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case appcustomer.FieldAppID: + return m.OldAppID(ctx) + case appcustomer.FieldCustomerID: + return m.OldCustomerID(ctx) + } + return nil, fmt.Errorf("unknown AppCustomer 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 *AppCustomerMutation) SetField(name string, value ent.Value) error { + switch name { + case appcustomer.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case appcustomer.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 appcustomer.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 appcustomer.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 appcustomer.FieldAppID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAppID(v) + return nil + case appcustomer.FieldCustomerID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerID(v) + return nil + } + return fmt.Errorf("unknown AppCustomer field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AppCustomerMutation) 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 *AppCustomerMutation) 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 *AppCustomerMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown AppCustomer numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AppCustomerMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(appcustomer.FieldDeletedAt) { + fields = append(fields, appcustomer.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AppCustomerMutation) 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 *AppCustomerMutation) ClearField(name string) error { + switch name { + case appcustomer.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown AppCustomer 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 *AppCustomerMutation) ResetField(name string) error { + switch name { + case appcustomer.FieldNamespace: + m.ResetNamespace() + return nil + case appcustomer.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case appcustomer.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case appcustomer.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case appcustomer.FieldAppID: + m.ResetAppID() + return nil + case appcustomer.FieldCustomerID: + m.ResetCustomerID() + return nil + } + return fmt.Errorf("unknown AppCustomer field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AppCustomerMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.app != nil { + edges = append(edges, appcustomer.EdgeApp) + } + if m.customer != nil { + edges = append(edges, appcustomer.EdgeCustomer) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AppCustomerMutation) AddedIDs(name string) []ent.Value { + switch name { + case appcustomer.EdgeApp: + if id := m.app; id != nil { + return []ent.Value{*id} + } + case appcustomer.EdgeCustomer: + if id := m.customer; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AppCustomerMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AppCustomerMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AppCustomerMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedapp { + edges = append(edges, appcustomer.EdgeApp) + } + if m.clearedcustomer { + edges = append(edges, appcustomer.EdgeCustomer) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AppCustomerMutation) EdgeCleared(name string) bool { + switch name { + case appcustomer.EdgeApp: + return m.clearedapp + case appcustomer.EdgeCustomer: + return m.clearedcustomer + } + 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 *AppCustomerMutation) ClearEdge(name string) error { + switch name { + case appcustomer.EdgeApp: + m.ClearApp() + return nil + case appcustomer.EdgeCustomer: + m.ClearCustomer() + return nil + } + return fmt.Errorf("unknown AppCustomer 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 *AppCustomerMutation) ResetEdge(name string) error { + switch name { + case appcustomer.EdgeApp: + m.ResetApp() + return nil + case appcustomer.EdgeCustomer: + m.ResetCustomer() + return nil + } + return fmt.Errorf("unknown AppCustomer edge %s", name) +} + +// AppStripeMutation represents an operation that mutates the AppStripe nodes in the graph. +type AppStripeMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + stripe_account_id *string + stripe_livemode *bool + api_key *string + masked_api_key *string + stripe_webhook_id *string + webhook_secret *string + clearedFields map[string]struct{} + customer_apps map[int]struct{} + removedcustomer_apps map[int]struct{} + clearedcustomer_apps bool + app *string + clearedapp bool + done bool + oldValue func(context.Context) (*AppStripe, error) + predicates []predicate.AppStripe +} + +var _ ent.Mutation = (*AppStripeMutation)(nil) + +// appstripeOption allows management of the mutation configuration using functional options. +type appstripeOption func(*AppStripeMutation) + +// newAppStripeMutation creates new mutation for the AppStripe entity. +func newAppStripeMutation(c config, op Op, opts ...appstripeOption) *AppStripeMutation { + m := &AppStripeMutation{ + config: c, + op: op, + typ: TypeAppStripe, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAppStripeID sets the ID field of the mutation. +func withAppStripeID(id string) appstripeOption { + return func(m *AppStripeMutation) { + var ( + err error + once sync.Once + value *AppStripe + ) + m.oldValue = func(ctx context.Context) (*AppStripe, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().AppStripe.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAppStripe sets the old AppStripe of the mutation. +func withAppStripe(node *AppStripe) appstripeOption { + return func(m *AppStripeMutation) { + m.oldValue = func(context.Context) (*AppStripe, 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 AppStripeMutation) 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 AppStripeMutation) 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 AppStripe entities. +func (m *AppStripeMutation) 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 *AppStripeMutation) 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 *AppStripeMutation) 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().AppStripe.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 *AppStripeMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *AppStripeMutation) 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 AppStripe entity. +// If the AppStripe 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 *AppStripeMutation) 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 *AppStripeMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *AppStripeMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *AppStripeMutation) 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 AppStripe entity. +// If the AppStripe 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 *AppStripeMutation) 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 *AppStripeMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *AppStripeMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *AppStripeMutation) 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 AppStripe entity. +// If the AppStripe 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 *AppStripeMutation) 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 *AppStripeMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *AppStripeMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *AppStripeMutation) 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 AppStripe entity. +// If the AppStripe 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 *AppStripeMutation) 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 *AppStripeMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[appstripe.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *AppStripeMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[appstripe.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *AppStripeMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, appstripe.FieldDeletedAt) +} + +// SetStripeAccountID sets the "stripe_account_id" field. +func (m *AppStripeMutation) SetStripeAccountID(s string) { + m.stripe_account_id = &s +} + +// StripeAccountID returns the value of the "stripe_account_id" field in the mutation. +func (m *AppStripeMutation) StripeAccountID() (r string, exists bool) { + v := m.stripe_account_id + if v == nil { + return + } + return *v, true +} + +// OldStripeAccountID returns the old "stripe_account_id" field's value of the AppStripe entity. +// If the AppStripe 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 *AppStripeMutation) OldStripeAccountID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStripeAccountID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStripeAccountID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStripeAccountID: %w", err) + } + return oldValue.StripeAccountID, nil +} + +// ResetStripeAccountID resets all changes to the "stripe_account_id" field. +func (m *AppStripeMutation) ResetStripeAccountID() { + m.stripe_account_id = nil +} + +// SetStripeLivemode sets the "stripe_livemode" field. +func (m *AppStripeMutation) SetStripeLivemode(b bool) { + m.stripe_livemode = &b +} + +// StripeLivemode returns the value of the "stripe_livemode" field in the mutation. +func (m *AppStripeMutation) StripeLivemode() (r bool, exists bool) { + v := m.stripe_livemode + if v == nil { + return + } + return *v, true +} + +// OldStripeLivemode returns the old "stripe_livemode" field's value of the AppStripe entity. +// If the AppStripe 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 *AppStripeMutation) OldStripeLivemode(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStripeLivemode is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStripeLivemode requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStripeLivemode: %w", err) + } + return oldValue.StripeLivemode, nil +} + +// ResetStripeLivemode resets all changes to the "stripe_livemode" field. +func (m *AppStripeMutation) ResetStripeLivemode() { + m.stripe_livemode = nil +} + +// SetAPIKey sets the "api_key" field. +func (m *AppStripeMutation) SetAPIKey(s string) { + m.api_key = &s +} + +// APIKey returns the value of the "api_key" field in the mutation. +func (m *AppStripeMutation) APIKey() (r string, exists bool) { + v := m.api_key + if v == nil { + return + } + return *v, true +} + +// OldAPIKey returns the old "api_key" field's value of the AppStripe entity. +// If the AppStripe 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 *AppStripeMutation) OldAPIKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAPIKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAPIKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAPIKey: %w", err) + } + return oldValue.APIKey, nil +} + +// ResetAPIKey resets all changes to the "api_key" field. +func (m *AppStripeMutation) ResetAPIKey() { + m.api_key = nil +} + +// SetMaskedAPIKey sets the "masked_api_key" field. +func (m *AppStripeMutation) SetMaskedAPIKey(s string) { + m.masked_api_key = &s +} + +// MaskedAPIKey returns the value of the "masked_api_key" field in the mutation. +func (m *AppStripeMutation) MaskedAPIKey() (r string, exists bool) { + v := m.masked_api_key + if v == nil { + return + } + return *v, true +} + +// OldMaskedAPIKey returns the old "masked_api_key" field's value of the AppStripe entity. +// If the AppStripe 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 *AppStripeMutation) OldMaskedAPIKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMaskedAPIKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMaskedAPIKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMaskedAPIKey: %w", err) + } + return oldValue.MaskedAPIKey, nil +} + +// ResetMaskedAPIKey resets all changes to the "masked_api_key" field. +func (m *AppStripeMutation) ResetMaskedAPIKey() { + m.masked_api_key = nil +} + +// SetStripeWebhookID sets the "stripe_webhook_id" field. +func (m *AppStripeMutation) SetStripeWebhookID(s string) { + m.stripe_webhook_id = &s +} + +// StripeWebhookID returns the value of the "stripe_webhook_id" field in the mutation. +func (m *AppStripeMutation) StripeWebhookID() (r string, exists bool) { + v := m.stripe_webhook_id + if v == nil { + return + } + return *v, true +} + +// OldStripeWebhookID returns the old "stripe_webhook_id" field's value of the AppStripe entity. +// If the AppStripe 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 *AppStripeMutation) OldStripeWebhookID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStripeWebhookID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStripeWebhookID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStripeWebhookID: %w", err) + } + return oldValue.StripeWebhookID, nil +} + +// ResetStripeWebhookID resets all changes to the "stripe_webhook_id" field. +func (m *AppStripeMutation) ResetStripeWebhookID() { + m.stripe_webhook_id = nil +} + +// SetWebhookSecret sets the "webhook_secret" field. +func (m *AppStripeMutation) SetWebhookSecret(s string) { + m.webhook_secret = &s +} + +// WebhookSecret returns the value of the "webhook_secret" field in the mutation. +func (m *AppStripeMutation) WebhookSecret() (r string, exists bool) { + v := m.webhook_secret + if v == nil { + return + } + return *v, true +} + +// OldWebhookSecret returns the old "webhook_secret" field's value of the AppStripe entity. +// If the AppStripe 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 *AppStripeMutation) OldWebhookSecret(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldWebhookSecret is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldWebhookSecret requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldWebhookSecret: %w", err) + } + return oldValue.WebhookSecret, nil +} + +// ResetWebhookSecret resets all changes to the "webhook_secret" field. +func (m *AppStripeMutation) ResetWebhookSecret() { + m.webhook_secret = nil +} + +// AddCustomerAppIDs adds the "customer_apps" edge to the AppStripeCustomer entity by ids. +func (m *AppStripeMutation) AddCustomerAppIDs(ids ...int) { + if m.customer_apps == nil { + m.customer_apps = make(map[int]struct{}) + } + for i := range ids { + m.customer_apps[ids[i]] = struct{}{} + } +} + +// ClearCustomerApps clears the "customer_apps" edge to the AppStripeCustomer entity. +func (m *AppStripeMutation) ClearCustomerApps() { + m.clearedcustomer_apps = true +} + +// CustomerAppsCleared reports if the "customer_apps" edge to the AppStripeCustomer entity was cleared. +func (m *AppStripeMutation) CustomerAppsCleared() bool { + return m.clearedcustomer_apps +} + +// RemoveCustomerAppIDs removes the "customer_apps" edge to the AppStripeCustomer entity by IDs. +func (m *AppStripeMutation) RemoveCustomerAppIDs(ids ...int) { + if m.removedcustomer_apps == nil { + m.removedcustomer_apps = make(map[int]struct{}) + } + for i := range ids { + delete(m.customer_apps, ids[i]) + m.removedcustomer_apps[ids[i]] = struct{}{} + } +} + +// RemovedCustomerApps returns the removed IDs of the "customer_apps" edge to the AppStripeCustomer entity. +func (m *AppStripeMutation) RemovedCustomerAppsIDs() (ids []int) { + for id := range m.removedcustomer_apps { + ids = append(ids, id) + } + return +} + +// CustomerAppsIDs returns the "customer_apps" edge IDs in the mutation. +func (m *AppStripeMutation) CustomerAppsIDs() (ids []int) { + for id := range m.customer_apps { + ids = append(ids, id) + } + return +} + +// ResetCustomerApps resets all changes to the "customer_apps" edge. +func (m *AppStripeMutation) ResetCustomerApps() { + m.customer_apps = nil + m.clearedcustomer_apps = false + m.removedcustomer_apps = nil +} + +// SetAppID sets the "app" edge to the App entity by id. +func (m *AppStripeMutation) SetAppID(id string) { + m.app = &id +} + +// ClearApp clears the "app" edge to the App entity. +func (m *AppStripeMutation) ClearApp() { + m.clearedapp = true +} + +// AppCleared reports if the "app" edge to the App entity was cleared. +func (m *AppStripeMutation) AppCleared() bool { + return m.clearedapp +} + +// AppID returns the "app" edge ID in the mutation. +func (m *AppStripeMutation) AppID() (id string, exists bool) { + if m.app != nil { + return *m.app, true + } + return +} + +// AppIDs returns the "app" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// AppID instead. It exists only for internal usage by the builders. +func (m *AppStripeMutation) AppIDs() (ids []string) { + if id := m.app; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetApp resets all changes to the "app" edge. +func (m *AppStripeMutation) ResetApp() { + m.app = nil + m.clearedapp = false +} + +// Where appends a list predicates to the AppStripeMutation builder. +func (m *AppStripeMutation) Where(ps ...predicate.AppStripe) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AppStripeMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AppStripeMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.AppStripe, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AppStripeMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AppStripeMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (AppStripe). +func (m *AppStripeMutation) 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 *AppStripeMutation) Fields() []string { + fields := make([]string, 0, 10) + if m.namespace != nil { + fields = append(fields, appstripe.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, appstripe.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, appstripe.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, appstripe.FieldDeletedAt) + } + if m.stripe_account_id != nil { + fields = append(fields, appstripe.FieldStripeAccountID) + } + if m.stripe_livemode != nil { + fields = append(fields, appstripe.FieldStripeLivemode) + } + if m.api_key != nil { + fields = append(fields, appstripe.FieldAPIKey) + } + if m.masked_api_key != nil { + fields = append(fields, appstripe.FieldMaskedAPIKey) + } + if m.stripe_webhook_id != nil { + fields = append(fields, appstripe.FieldStripeWebhookID) + } + if m.webhook_secret != nil { + fields = append(fields, appstripe.FieldWebhookSecret) + } + 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 *AppStripeMutation) Field(name string) (ent.Value, bool) { + switch name { + case appstripe.FieldNamespace: + return m.Namespace() + case appstripe.FieldCreatedAt: + return m.CreatedAt() + case appstripe.FieldUpdatedAt: + return m.UpdatedAt() + case appstripe.FieldDeletedAt: + return m.DeletedAt() + case appstripe.FieldStripeAccountID: + return m.StripeAccountID() + case appstripe.FieldStripeLivemode: + return m.StripeLivemode() + case appstripe.FieldAPIKey: + return m.APIKey() + case appstripe.FieldMaskedAPIKey: + return m.MaskedAPIKey() + case appstripe.FieldStripeWebhookID: + return m.StripeWebhookID() + case appstripe.FieldWebhookSecret: + return m.WebhookSecret() + } + 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 *AppStripeMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case appstripe.FieldNamespace: + return m.OldNamespace(ctx) + case appstripe.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case appstripe.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case appstripe.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case appstripe.FieldStripeAccountID: + return m.OldStripeAccountID(ctx) + case appstripe.FieldStripeLivemode: + return m.OldStripeLivemode(ctx) + case appstripe.FieldAPIKey: + return m.OldAPIKey(ctx) + case appstripe.FieldMaskedAPIKey: + return m.OldMaskedAPIKey(ctx) + case appstripe.FieldStripeWebhookID: + return m.OldStripeWebhookID(ctx) + case appstripe.FieldWebhookSecret: + return m.OldWebhookSecret(ctx) + } + return nil, fmt.Errorf("unknown AppStripe 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 *AppStripeMutation) SetField(name string, value ent.Value) error { + switch name { + case appstripe.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case appstripe.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 appstripe.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 appstripe.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 appstripe.FieldStripeAccountID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStripeAccountID(v) + return nil + case appstripe.FieldStripeLivemode: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStripeLivemode(v) + return nil + case appstripe.FieldAPIKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAPIKey(v) + return nil + case appstripe.FieldMaskedAPIKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMaskedAPIKey(v) + return nil + case appstripe.FieldStripeWebhookID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStripeWebhookID(v) + return nil + case appstripe.FieldWebhookSecret: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetWebhookSecret(v) + return nil + } + return fmt.Errorf("unknown AppStripe field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AppStripeMutation) 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 *AppStripeMutation) 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 *AppStripeMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown AppStripe numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AppStripeMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(appstripe.FieldDeletedAt) { + fields = append(fields, appstripe.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AppStripeMutation) 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 *AppStripeMutation) ClearField(name string) error { + switch name { + case appstripe.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown AppStripe 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 *AppStripeMutation) ResetField(name string) error { + switch name { + case appstripe.FieldNamespace: + m.ResetNamespace() + return nil + case appstripe.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case appstripe.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case appstripe.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case appstripe.FieldStripeAccountID: + m.ResetStripeAccountID() + return nil + case appstripe.FieldStripeLivemode: + m.ResetStripeLivemode() + return nil + case appstripe.FieldAPIKey: + m.ResetAPIKey() + return nil + case appstripe.FieldMaskedAPIKey: + m.ResetMaskedAPIKey() + return nil + case appstripe.FieldStripeWebhookID: + m.ResetStripeWebhookID() + return nil + case appstripe.FieldWebhookSecret: + m.ResetWebhookSecret() + return nil + } + return fmt.Errorf("unknown AppStripe field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AppStripeMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.customer_apps != nil { + edges = append(edges, appstripe.EdgeCustomerApps) + } + if m.app != nil { + edges = append(edges, appstripe.EdgeApp) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AppStripeMutation) AddedIDs(name string) []ent.Value { + switch name { + case appstripe.EdgeCustomerApps: + ids := make([]ent.Value, 0, len(m.customer_apps)) + for id := range m.customer_apps { + ids = append(ids, id) + } + return ids + case appstripe.EdgeApp: + if id := m.app; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AppStripeMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedcustomer_apps != nil { + edges = append(edges, appstripe.EdgeCustomerApps) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AppStripeMutation) RemovedIDs(name string) []ent.Value { + switch name { + case appstripe.EdgeCustomerApps: + ids := make([]ent.Value, 0, len(m.removedcustomer_apps)) + for id := range m.removedcustomer_apps { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AppStripeMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedcustomer_apps { + edges = append(edges, appstripe.EdgeCustomerApps) + } + if m.clearedapp { + edges = append(edges, appstripe.EdgeApp) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AppStripeMutation) EdgeCleared(name string) bool { + switch name { + case appstripe.EdgeCustomerApps: + return m.clearedcustomer_apps + case appstripe.EdgeApp: + return m.clearedapp + } + 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 *AppStripeMutation) ClearEdge(name string) error { + switch name { + case appstripe.EdgeApp: + m.ClearApp() + return nil + } + return fmt.Errorf("unknown AppStripe 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 *AppStripeMutation) ResetEdge(name string) error { + switch name { + case appstripe.EdgeCustomerApps: + m.ResetCustomerApps() + return nil + case appstripe.EdgeApp: + m.ResetApp() + return nil + } + return fmt.Errorf("unknown AppStripe edge %s", name) +} + +// AppStripeCustomerMutation represents an operation that mutates the AppStripeCustomer nodes in the graph. +type AppStripeCustomerMutation struct { + config + op Op + typ string + id *int + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + stripe_customer_id *string + stripe_default_payment_method_id *string + clearedFields map[string]struct{} + stripe_app *string + clearedstripe_app bool + customer *string + clearedcustomer bool + done bool + oldValue func(context.Context) (*AppStripeCustomer, error) + predicates []predicate.AppStripeCustomer +} + +var _ ent.Mutation = (*AppStripeCustomerMutation)(nil) + +// appstripecustomerOption allows management of the mutation configuration using functional options. +type appstripecustomerOption func(*AppStripeCustomerMutation) + +// newAppStripeCustomerMutation creates new mutation for the AppStripeCustomer entity. +func newAppStripeCustomerMutation(c config, op Op, opts ...appstripecustomerOption) *AppStripeCustomerMutation { + m := &AppStripeCustomerMutation{ + config: c, + op: op, + typ: TypeAppStripeCustomer, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAppStripeCustomerID sets the ID field of the mutation. +func withAppStripeCustomerID(id int) appstripecustomerOption { + return func(m *AppStripeCustomerMutation) { + var ( + err error + once sync.Once + value *AppStripeCustomer + ) + m.oldValue = func(ctx context.Context) (*AppStripeCustomer, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().AppStripeCustomer.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAppStripeCustomer sets the old AppStripeCustomer of the mutation. +func withAppStripeCustomer(node *AppStripeCustomer) appstripecustomerOption { + return func(m *AppStripeCustomerMutation) { + m.oldValue = func(context.Context) (*AppStripeCustomer, 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 AppStripeCustomerMutation) 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 AppStripeCustomerMutation) 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 +} + +// 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 *AppStripeCustomerMutation) ID() (id int, 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 *AppStripeCustomerMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().AppStripeCustomer.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 *AppStripeCustomerMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *AppStripeCustomerMutation) 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 AppStripeCustomer entity. +// If the AppStripeCustomer 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 *AppStripeCustomerMutation) 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 *AppStripeCustomerMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *AppStripeCustomerMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *AppStripeCustomerMutation) 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 AppStripeCustomer entity. +// If the AppStripeCustomer 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 *AppStripeCustomerMutation) 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 *AppStripeCustomerMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *AppStripeCustomerMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *AppStripeCustomerMutation) 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 AppStripeCustomer entity. +// If the AppStripeCustomer 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 *AppStripeCustomerMutation) 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 *AppStripeCustomerMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *AppStripeCustomerMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *AppStripeCustomerMutation) 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 AppStripeCustomer entity. +// If the AppStripeCustomer 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 *AppStripeCustomerMutation) 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 *AppStripeCustomerMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[appstripecustomer.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *AppStripeCustomerMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[appstripecustomer.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *AppStripeCustomerMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, appstripecustomer.FieldDeletedAt) +} + +// SetAppID sets the "app_id" field. +func (m *AppStripeCustomerMutation) SetAppID(s string) { + m.stripe_app = &s +} + +// AppID returns the value of the "app_id" field in the mutation. +func (m *AppStripeCustomerMutation) AppID() (r string, exists bool) { + v := m.stripe_app + if v == nil { + return + } + return *v, true +} + +// OldAppID returns the old "app_id" field's value of the AppStripeCustomer entity. +// If the AppStripeCustomer 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 *AppStripeCustomerMutation) OldAppID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAppID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAppID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAppID: %w", err) + } + return oldValue.AppID, nil +} + +// ResetAppID resets all changes to the "app_id" field. +func (m *AppStripeCustomerMutation) ResetAppID() { + m.stripe_app = nil +} + +// SetCustomerID sets the "customer_id" field. +func (m *AppStripeCustomerMutation) SetCustomerID(s string) { + m.customer = &s +} + +// CustomerID returns the value of the "customer_id" field in the mutation. +func (m *AppStripeCustomerMutation) CustomerID() (r string, exists bool) { + v := m.customer + if v == nil { + return + } + return *v, true +} + +// OldCustomerID returns the old "customer_id" field's value of the AppStripeCustomer entity. +// If the AppStripeCustomer 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 *AppStripeCustomerMutation) OldCustomerID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerID: %w", err) + } + return oldValue.CustomerID, nil +} + +// ResetCustomerID resets all changes to the "customer_id" field. +func (m *AppStripeCustomerMutation) ResetCustomerID() { + m.customer = nil +} + +// SetStripeCustomerID sets the "stripe_customer_id" field. +func (m *AppStripeCustomerMutation) SetStripeCustomerID(s string) { + m.stripe_customer_id = &s +} + +// StripeCustomerID returns the value of the "stripe_customer_id" field in the mutation. +func (m *AppStripeCustomerMutation) StripeCustomerID() (r string, exists bool) { + v := m.stripe_customer_id + if v == nil { + return + } + return *v, true +} + +// OldStripeCustomerID returns the old "stripe_customer_id" field's value of the AppStripeCustomer entity. +// If the AppStripeCustomer 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 *AppStripeCustomerMutation) OldStripeCustomerID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStripeCustomerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStripeCustomerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStripeCustomerID: %w", err) + } + return oldValue.StripeCustomerID, nil +} + +// ResetStripeCustomerID resets all changes to the "stripe_customer_id" field. +func (m *AppStripeCustomerMutation) ResetStripeCustomerID() { + m.stripe_customer_id = nil +} + +// SetStripeDefaultPaymentMethodID sets the "stripe_default_payment_method_id" field. +func (m *AppStripeCustomerMutation) SetStripeDefaultPaymentMethodID(s string) { + m.stripe_default_payment_method_id = &s +} + +// StripeDefaultPaymentMethodID returns the value of the "stripe_default_payment_method_id" field in the mutation. +func (m *AppStripeCustomerMutation) StripeDefaultPaymentMethodID() (r string, exists bool) { + v := m.stripe_default_payment_method_id + if v == nil { + return + } + return *v, true +} + +// OldStripeDefaultPaymentMethodID returns the old "stripe_default_payment_method_id" field's value of the AppStripeCustomer entity. +// If the AppStripeCustomer 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 *AppStripeCustomerMutation) OldStripeDefaultPaymentMethodID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStripeDefaultPaymentMethodID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStripeDefaultPaymentMethodID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStripeDefaultPaymentMethodID: %w", err) + } + return oldValue.StripeDefaultPaymentMethodID, nil +} + +// ClearStripeDefaultPaymentMethodID clears the value of the "stripe_default_payment_method_id" field. +func (m *AppStripeCustomerMutation) ClearStripeDefaultPaymentMethodID() { + m.stripe_default_payment_method_id = nil + m.clearedFields[appstripecustomer.FieldStripeDefaultPaymentMethodID] = struct{}{} +} + +// StripeDefaultPaymentMethodIDCleared returns if the "stripe_default_payment_method_id" field was cleared in this mutation. +func (m *AppStripeCustomerMutation) StripeDefaultPaymentMethodIDCleared() bool { + _, ok := m.clearedFields[appstripecustomer.FieldStripeDefaultPaymentMethodID] + return ok +} + +// ResetStripeDefaultPaymentMethodID resets all changes to the "stripe_default_payment_method_id" field. +func (m *AppStripeCustomerMutation) ResetStripeDefaultPaymentMethodID() { + m.stripe_default_payment_method_id = nil + delete(m.clearedFields, appstripecustomer.FieldStripeDefaultPaymentMethodID) +} + +// SetStripeAppID sets the "stripe_app" edge to the AppStripe entity by id. +func (m *AppStripeCustomerMutation) SetStripeAppID(id string) { + m.stripe_app = &id +} + +// ClearStripeApp clears the "stripe_app" edge to the AppStripe entity. +func (m *AppStripeCustomerMutation) ClearStripeApp() { + m.clearedstripe_app = true + m.clearedFields[appstripecustomer.FieldAppID] = struct{}{} +} + +// StripeAppCleared reports if the "stripe_app" edge to the AppStripe entity was cleared. +func (m *AppStripeCustomerMutation) StripeAppCleared() bool { + return m.clearedstripe_app +} + +// StripeAppID returns the "stripe_app" edge ID in the mutation. +func (m *AppStripeCustomerMutation) StripeAppID() (id string, exists bool) { + if m.stripe_app != nil { + return *m.stripe_app, true + } + return +} + +// StripeAppIDs returns the "stripe_app" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// StripeAppID instead. It exists only for internal usage by the builders. +func (m *AppStripeCustomerMutation) StripeAppIDs() (ids []string) { + if id := m.stripe_app; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetStripeApp resets all changes to the "stripe_app" edge. +func (m *AppStripeCustomerMutation) ResetStripeApp() { + m.stripe_app = nil + m.clearedstripe_app = false +} + +// ClearCustomer clears the "customer" edge to the Customer entity. +func (m *AppStripeCustomerMutation) ClearCustomer() { + m.clearedcustomer = true + m.clearedFields[appstripecustomer.FieldCustomerID] = struct{}{} +} + +// CustomerCleared reports if the "customer" edge to the Customer entity was cleared. +func (m *AppStripeCustomerMutation) CustomerCleared() bool { + return m.clearedcustomer +} + +// CustomerIDs returns the "customer" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CustomerID instead. It exists only for internal usage by the builders. +func (m *AppStripeCustomerMutation) CustomerIDs() (ids []string) { + if id := m.customer; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCustomer resets all changes to the "customer" edge. +func (m *AppStripeCustomerMutation) ResetCustomer() { + m.customer = nil + m.clearedcustomer = false +} + +// Where appends a list predicates to the AppStripeCustomerMutation builder. +func (m *AppStripeCustomerMutation) Where(ps ...predicate.AppStripeCustomer) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AppStripeCustomerMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AppStripeCustomerMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.AppStripeCustomer, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AppStripeCustomerMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AppStripeCustomerMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (AppStripeCustomer). +func (m *AppStripeCustomerMutation) 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 *AppStripeCustomerMutation) Fields() []string { + fields := make([]string, 0, 8) + if m.namespace != nil { + fields = append(fields, appstripecustomer.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, appstripecustomer.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, appstripecustomer.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, appstripecustomer.FieldDeletedAt) + } + if m.stripe_app != nil { + fields = append(fields, appstripecustomer.FieldAppID) + } + if m.customer != nil { + fields = append(fields, appstripecustomer.FieldCustomerID) + } + if m.stripe_customer_id != nil { + fields = append(fields, appstripecustomer.FieldStripeCustomerID) + } + if m.stripe_default_payment_method_id != nil { + fields = append(fields, appstripecustomer.FieldStripeDefaultPaymentMethodID) + } + 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 *AppStripeCustomerMutation) Field(name string) (ent.Value, bool) { + switch name { + case appstripecustomer.FieldNamespace: + return m.Namespace() + case appstripecustomer.FieldCreatedAt: + return m.CreatedAt() + case appstripecustomer.FieldUpdatedAt: + return m.UpdatedAt() + case appstripecustomer.FieldDeletedAt: + return m.DeletedAt() + case appstripecustomer.FieldAppID: + return m.AppID() + case appstripecustomer.FieldCustomerID: + return m.CustomerID() + case appstripecustomer.FieldStripeCustomerID: + return m.StripeCustomerID() + case appstripecustomer.FieldStripeDefaultPaymentMethodID: + return m.StripeDefaultPaymentMethodID() + } + 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 *AppStripeCustomerMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case appstripecustomer.FieldNamespace: + return m.OldNamespace(ctx) + case appstripecustomer.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case appstripecustomer.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case appstripecustomer.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case appstripecustomer.FieldAppID: + return m.OldAppID(ctx) + case appstripecustomer.FieldCustomerID: + return m.OldCustomerID(ctx) + case appstripecustomer.FieldStripeCustomerID: + return m.OldStripeCustomerID(ctx) + case appstripecustomer.FieldStripeDefaultPaymentMethodID: + return m.OldStripeDefaultPaymentMethodID(ctx) + } + return nil, fmt.Errorf("unknown AppStripeCustomer 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 *AppStripeCustomerMutation) SetField(name string, value ent.Value) error { + switch name { + case appstripecustomer.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case appstripecustomer.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 appstripecustomer.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 appstripecustomer.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 appstripecustomer.FieldAppID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAppID(v) + return nil + case appstripecustomer.FieldCustomerID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerID(v) + return nil + case appstripecustomer.FieldStripeCustomerID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStripeCustomerID(v) + return nil + case appstripecustomer.FieldStripeDefaultPaymentMethodID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStripeDefaultPaymentMethodID(v) + return nil + } + return fmt.Errorf("unknown AppStripeCustomer field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AppStripeCustomerMutation) 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 *AppStripeCustomerMutation) 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 *AppStripeCustomerMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown AppStripeCustomer numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AppStripeCustomerMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(appstripecustomer.FieldDeletedAt) { + fields = append(fields, appstripecustomer.FieldDeletedAt) + } + if m.FieldCleared(appstripecustomer.FieldStripeDefaultPaymentMethodID) { + fields = append(fields, appstripecustomer.FieldStripeDefaultPaymentMethodID) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AppStripeCustomerMutation) 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 *AppStripeCustomerMutation) ClearField(name string) error { + switch name { + case appstripecustomer.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case appstripecustomer.FieldStripeDefaultPaymentMethodID: + m.ClearStripeDefaultPaymentMethodID() + return nil + } + return fmt.Errorf("unknown AppStripeCustomer 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 *AppStripeCustomerMutation) ResetField(name string) error { + switch name { + case appstripecustomer.FieldNamespace: + m.ResetNamespace() + return nil + case appstripecustomer.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case appstripecustomer.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case appstripecustomer.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case appstripecustomer.FieldAppID: + m.ResetAppID() + return nil + case appstripecustomer.FieldCustomerID: + m.ResetCustomerID() + return nil + case appstripecustomer.FieldStripeCustomerID: + m.ResetStripeCustomerID() + return nil + case appstripecustomer.FieldStripeDefaultPaymentMethodID: + m.ResetStripeDefaultPaymentMethodID() + return nil + } + return fmt.Errorf("unknown AppStripeCustomer field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AppStripeCustomerMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.stripe_app != nil { + edges = append(edges, appstripecustomer.EdgeStripeApp) + } + if m.customer != nil { + edges = append(edges, appstripecustomer.EdgeCustomer) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AppStripeCustomerMutation) AddedIDs(name string) []ent.Value { + switch name { + case appstripecustomer.EdgeStripeApp: + if id := m.stripe_app; id != nil { + return []ent.Value{*id} + } + case appstripecustomer.EdgeCustomer: + if id := m.customer; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AppStripeCustomerMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AppStripeCustomerMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AppStripeCustomerMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedstripe_app { + edges = append(edges, appstripecustomer.EdgeStripeApp) + } + if m.clearedcustomer { + edges = append(edges, appstripecustomer.EdgeCustomer) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AppStripeCustomerMutation) EdgeCleared(name string) bool { + switch name { + case appstripecustomer.EdgeStripeApp: + return m.clearedstripe_app + case appstripecustomer.EdgeCustomer: + return m.clearedcustomer + } + 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 *AppStripeCustomerMutation) ClearEdge(name string) error { + switch name { + case appstripecustomer.EdgeStripeApp: + m.ClearStripeApp() + return nil + case appstripecustomer.EdgeCustomer: + m.ClearCustomer() + return nil + } + return fmt.Errorf("unknown AppStripeCustomer 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 *AppStripeCustomerMutation) ResetEdge(name string) error { + switch name { + case appstripecustomer.EdgeStripeApp: + m.ResetStripeApp() + return nil + case appstripecustomer.EdgeCustomer: + m.ResetCustomer() + return nil + } + return fmt.Errorf("unknown AppStripeCustomer edge %s", name) +} + +// BalanceSnapshotMutation represents an operation that mutates the BalanceSnapshot nodes in the graph. +type BalanceSnapshotMutation struct { + config + op Op + typ string + id *int + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + grant_balances *balance.Map + usage **balance.SnapshottedUsage + balance *float64 + addbalance *float64 + overage *float64 + addoverage *float64 + at *time.Time + clearedFields map[string]struct{} + entitlement *string + clearedentitlement bool + done bool + oldValue func(context.Context) (*BalanceSnapshot, error) + predicates []predicate.BalanceSnapshot +} + +var _ ent.Mutation = (*BalanceSnapshotMutation)(nil) + +// balancesnapshotOption allows management of the mutation configuration using functional options. +type balancesnapshotOption func(*BalanceSnapshotMutation) + +// newBalanceSnapshotMutation creates new mutation for the BalanceSnapshot entity. +func newBalanceSnapshotMutation(c config, op Op, opts ...balancesnapshotOption) *BalanceSnapshotMutation { + m := &BalanceSnapshotMutation{ + config: c, + op: op, + typ: TypeBalanceSnapshot, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBalanceSnapshotID sets the ID field of the mutation. +func withBalanceSnapshotID(id int) balancesnapshotOption { + return func(m *BalanceSnapshotMutation) { + var ( + err error + once sync.Once + value *BalanceSnapshot + ) + m.oldValue = func(ctx context.Context) (*BalanceSnapshot, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().BalanceSnapshot.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBalanceSnapshot sets the old BalanceSnapshot of the mutation. +func withBalanceSnapshot(node *BalanceSnapshot) balancesnapshotOption { + return func(m *BalanceSnapshotMutation) { + m.oldValue = func(context.Context) (*BalanceSnapshot, 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 BalanceSnapshotMutation) 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 BalanceSnapshotMutation) 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 +} + +// 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 *BalanceSnapshotMutation) ID() (id int, 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 *BalanceSnapshotMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().BalanceSnapshot.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 *BalanceSnapshotMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *BalanceSnapshotMutation) 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 BalanceSnapshot entity. +// If the BalanceSnapshot 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 *BalanceSnapshotMutation) 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 *BalanceSnapshotMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *BalanceSnapshotMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *BalanceSnapshotMutation) 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 BalanceSnapshot entity. +// If the BalanceSnapshot 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 *BalanceSnapshotMutation) 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 *BalanceSnapshotMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *BalanceSnapshotMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *BalanceSnapshotMutation) 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 BalanceSnapshot entity. +// If the BalanceSnapshot 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 *BalanceSnapshotMutation) 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 *BalanceSnapshotMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *BalanceSnapshotMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *BalanceSnapshotMutation) 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 BalanceSnapshot entity. +// If the BalanceSnapshot 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 *BalanceSnapshotMutation) 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 *BalanceSnapshotMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[balancesnapshot.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *BalanceSnapshotMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[balancesnapshot.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *BalanceSnapshotMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, balancesnapshot.FieldDeletedAt) +} + +// SetOwnerID sets the "owner_id" field. +func (m *BalanceSnapshotMutation) SetOwnerID(s string) { + m.entitlement = &s +} + +// OwnerID returns the value of the "owner_id" field in the mutation. +func (m *BalanceSnapshotMutation) OwnerID() (r string, exists bool) { + v := m.entitlement + if v == nil { + return + } + return *v, true +} + +// OldOwnerID returns the old "owner_id" field's value of the BalanceSnapshot entity. +// If the BalanceSnapshot 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 *BalanceSnapshotMutation) OldOwnerID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOwnerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOwnerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOwnerID: %w", err) + } + return oldValue.OwnerID, nil +} + +// ResetOwnerID resets all changes to the "owner_id" field. +func (m *BalanceSnapshotMutation) ResetOwnerID() { + m.entitlement = nil +} + +// SetGrantBalances sets the "grant_balances" field. +func (m *BalanceSnapshotMutation) SetGrantBalances(b balance.Map) { + m.grant_balances = &b +} + +// GrantBalances returns the value of the "grant_balances" field in the mutation. +func (m *BalanceSnapshotMutation) GrantBalances() (r balance.Map, exists bool) { + v := m.grant_balances + if v == nil { + return + } + return *v, true +} + +// OldGrantBalances returns the old "grant_balances" field's value of the BalanceSnapshot entity. +// If the BalanceSnapshot 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 *BalanceSnapshotMutation) OldGrantBalances(ctx context.Context) (v balance.Map, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldGrantBalances is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldGrantBalances requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldGrantBalances: %w", err) + } + return oldValue.GrantBalances, nil +} + +// ResetGrantBalances resets all changes to the "grant_balances" field. +func (m *BalanceSnapshotMutation) ResetGrantBalances() { + m.grant_balances = nil +} + +// SetUsage sets the "usage" field. +func (m *BalanceSnapshotMutation) SetUsage(bu *balance.SnapshottedUsage) { + m.usage = &bu +} + +// Usage returns the value of the "usage" field in the mutation. +func (m *BalanceSnapshotMutation) Usage() (r *balance.SnapshottedUsage, exists bool) { + v := m.usage + if v == nil { + return + } + return *v, true +} + +// OldUsage returns the old "usage" field's value of the BalanceSnapshot entity. +// If the BalanceSnapshot 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 *BalanceSnapshotMutation) OldUsage(ctx context.Context) (v *balance.SnapshottedUsage, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUsage is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUsage requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUsage: %w", err) + } + return oldValue.Usage, nil +} + +// ClearUsage clears the value of the "usage" field. +func (m *BalanceSnapshotMutation) ClearUsage() { + m.usage = nil + m.clearedFields[balancesnapshot.FieldUsage] = struct{}{} +} + +// UsageCleared returns if the "usage" field was cleared in this mutation. +func (m *BalanceSnapshotMutation) UsageCleared() bool { + _, ok := m.clearedFields[balancesnapshot.FieldUsage] + return ok +} + +// ResetUsage resets all changes to the "usage" field. +func (m *BalanceSnapshotMutation) ResetUsage() { + m.usage = nil + delete(m.clearedFields, balancesnapshot.FieldUsage) +} + +// SetBalance sets the "balance" field. +func (m *BalanceSnapshotMutation) SetBalance(f float64) { + m.balance = &f + m.addbalance = nil +} + +// Balance returns the value of the "balance" field in the mutation. +func (m *BalanceSnapshotMutation) Balance() (r float64, exists bool) { + v := m.balance + if v == nil { + return + } + return *v, true +} + +// OldBalance returns the old "balance" field's value of the BalanceSnapshot entity. +// If the BalanceSnapshot 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 *BalanceSnapshotMutation) OldBalance(ctx context.Context) (v float64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBalance is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBalance requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBalance: %w", err) + } + return oldValue.Balance, nil +} + +// AddBalance adds f to the "balance" field. +func (m *BalanceSnapshotMutation) AddBalance(f float64) { + if m.addbalance != nil { + *m.addbalance += f + } else { + m.addbalance = &f + } +} + +// AddedBalance returns the value that was added to the "balance" field in this mutation. +func (m *BalanceSnapshotMutation) AddedBalance() (r float64, exists bool) { + v := m.addbalance + if v == nil { + return + } + return *v, true +} + +// ResetBalance resets all changes to the "balance" field. +func (m *BalanceSnapshotMutation) ResetBalance() { + m.balance = nil + m.addbalance = nil +} + +// SetOverage sets the "overage" field. +func (m *BalanceSnapshotMutation) SetOverage(f float64) { + m.overage = &f + m.addoverage = nil +} + +// Overage returns the value of the "overage" field in the mutation. +func (m *BalanceSnapshotMutation) Overage() (r float64, exists bool) { + v := m.overage + if v == nil { + return + } + return *v, true +} + +// OldOverage returns the old "overage" field's value of the BalanceSnapshot entity. +// If the BalanceSnapshot 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 *BalanceSnapshotMutation) OldOverage(ctx context.Context) (v float64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOverage is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOverage requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOverage: %w", err) + } + return oldValue.Overage, nil +} + +// AddOverage adds f to the "overage" field. +func (m *BalanceSnapshotMutation) AddOverage(f float64) { + if m.addoverage != nil { + *m.addoverage += f + } else { + m.addoverage = &f + } +} + +// AddedOverage returns the value that was added to the "overage" field in this mutation. +func (m *BalanceSnapshotMutation) AddedOverage() (r float64, exists bool) { + v := m.addoverage + if v == nil { + return + } + return *v, true +} + +// ResetOverage resets all changes to the "overage" field. +func (m *BalanceSnapshotMutation) ResetOverage() { + m.overage = nil + m.addoverage = nil +} + +// SetAt sets the "at" field. +func (m *BalanceSnapshotMutation) SetAt(t time.Time) { + m.at = &t +} + +// At returns the value of the "at" field in the mutation. +func (m *BalanceSnapshotMutation) At() (r time.Time, exists bool) { + v := m.at + if v == nil { + return + } + return *v, true +} + +// OldAt returns the old "at" field's value of the BalanceSnapshot entity. +// If the BalanceSnapshot 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 *BalanceSnapshotMutation) OldAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAt: %w", err) + } + return oldValue.At, nil +} + +// ResetAt resets all changes to the "at" field. +func (m *BalanceSnapshotMutation) ResetAt() { + m.at = nil +} + +// SetEntitlementID sets the "entitlement" edge to the Entitlement entity by id. +func (m *BalanceSnapshotMutation) SetEntitlementID(id string) { + m.entitlement = &id +} + +// ClearEntitlement clears the "entitlement" edge to the Entitlement entity. +func (m *BalanceSnapshotMutation) ClearEntitlement() { + m.clearedentitlement = true + m.clearedFields[balancesnapshot.FieldOwnerID] = struct{}{} +} + +// EntitlementCleared reports if the "entitlement" edge to the Entitlement entity was cleared. +func (m *BalanceSnapshotMutation) EntitlementCleared() bool { + return m.clearedentitlement +} + +// EntitlementID returns the "entitlement" edge ID in the mutation. +func (m *BalanceSnapshotMutation) EntitlementID() (id string, exists bool) { + if m.entitlement != nil { + return *m.entitlement, true + } + return +} + +// EntitlementIDs returns the "entitlement" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// EntitlementID instead. It exists only for internal usage by the builders. +func (m *BalanceSnapshotMutation) EntitlementIDs() (ids []string) { + if id := m.entitlement; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetEntitlement resets all changes to the "entitlement" edge. +func (m *BalanceSnapshotMutation) ResetEntitlement() { + m.entitlement = nil + m.clearedentitlement = false +} + +// Where appends a list predicates to the BalanceSnapshotMutation builder. +func (m *BalanceSnapshotMutation) Where(ps ...predicate.BalanceSnapshot) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BalanceSnapshotMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BalanceSnapshotMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BalanceSnapshot, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BalanceSnapshotMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BalanceSnapshotMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BalanceSnapshot). +func (m *BalanceSnapshotMutation) 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 *BalanceSnapshotMutation) Fields() []string { + fields := make([]string, 0, 10) + if m.namespace != nil { + fields = append(fields, balancesnapshot.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, balancesnapshot.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, balancesnapshot.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, balancesnapshot.FieldDeletedAt) + } + if m.entitlement != nil { + fields = append(fields, balancesnapshot.FieldOwnerID) + } + if m.grant_balances != nil { + fields = append(fields, balancesnapshot.FieldGrantBalances) + } + if m.usage != nil { + fields = append(fields, balancesnapshot.FieldUsage) + } + if m.balance != nil { + fields = append(fields, balancesnapshot.FieldBalance) + } + if m.overage != nil { + fields = append(fields, balancesnapshot.FieldOverage) + } + if m.at != nil { + fields = append(fields, balancesnapshot.FieldAt) + } + 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 *BalanceSnapshotMutation) Field(name string) (ent.Value, bool) { + switch name { + case balancesnapshot.FieldNamespace: + return m.Namespace() + case balancesnapshot.FieldCreatedAt: + return m.CreatedAt() + case balancesnapshot.FieldUpdatedAt: + return m.UpdatedAt() + case balancesnapshot.FieldDeletedAt: + return m.DeletedAt() + case balancesnapshot.FieldOwnerID: + return m.OwnerID() + case balancesnapshot.FieldGrantBalances: + return m.GrantBalances() + case balancesnapshot.FieldUsage: + return m.Usage() + case balancesnapshot.FieldBalance: + return m.Balance() + case balancesnapshot.FieldOverage: + return m.Overage() + case balancesnapshot.FieldAt: + return m.At() + } + 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 *BalanceSnapshotMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case balancesnapshot.FieldNamespace: + return m.OldNamespace(ctx) + case balancesnapshot.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case balancesnapshot.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case balancesnapshot.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case balancesnapshot.FieldOwnerID: + return m.OldOwnerID(ctx) + case balancesnapshot.FieldGrantBalances: + return m.OldGrantBalances(ctx) + case balancesnapshot.FieldUsage: + return m.OldUsage(ctx) + case balancesnapshot.FieldBalance: + return m.OldBalance(ctx) + case balancesnapshot.FieldOverage: + return m.OldOverage(ctx) + case balancesnapshot.FieldAt: + return m.OldAt(ctx) + } + return nil, fmt.Errorf("unknown BalanceSnapshot 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 *BalanceSnapshotMutation) SetField(name string, value ent.Value) error { + switch name { + case balancesnapshot.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case balancesnapshot.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 balancesnapshot.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 balancesnapshot.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 balancesnapshot.FieldOwnerID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOwnerID(v) + return nil + case balancesnapshot.FieldGrantBalances: + v, ok := value.(balance.Map) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetGrantBalances(v) + return nil + case balancesnapshot.FieldUsage: + v, ok := value.(*balance.SnapshottedUsage) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUsage(v) + return nil + case balancesnapshot.FieldBalance: + v, ok := value.(float64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBalance(v) + return nil + case balancesnapshot.FieldOverage: + v, ok := value.(float64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOverage(v) + return nil + case balancesnapshot.FieldAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAt(v) + return nil + } + return fmt.Errorf("unknown BalanceSnapshot field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BalanceSnapshotMutation) AddedFields() []string { + var fields []string + if m.addbalance != nil { + fields = append(fields, balancesnapshot.FieldBalance) + } + if m.addoverage != nil { + fields = append(fields, balancesnapshot.FieldOverage) + } + return fields +} + +// 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 *BalanceSnapshotMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case balancesnapshot.FieldBalance: + return m.AddedBalance() + case balancesnapshot.FieldOverage: + return m.AddedOverage() + } + 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 *BalanceSnapshotMutation) AddField(name string, value ent.Value) error { + switch name { + case balancesnapshot.FieldBalance: + v, ok := value.(float64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddBalance(v) + return nil + case balancesnapshot.FieldOverage: + v, ok := value.(float64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddOverage(v) + return nil + } + return fmt.Errorf("unknown BalanceSnapshot numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BalanceSnapshotMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(balancesnapshot.FieldDeletedAt) { + fields = append(fields, balancesnapshot.FieldDeletedAt) + } + if m.FieldCleared(balancesnapshot.FieldUsage) { + fields = append(fields, balancesnapshot.FieldUsage) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BalanceSnapshotMutation) 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 *BalanceSnapshotMutation) ClearField(name string) error { + switch name { + case balancesnapshot.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case balancesnapshot.FieldUsage: + m.ClearUsage() + return nil + } + return fmt.Errorf("unknown BalanceSnapshot 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 *BalanceSnapshotMutation) ResetField(name string) error { + switch name { + case balancesnapshot.FieldNamespace: + m.ResetNamespace() + return nil + case balancesnapshot.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case balancesnapshot.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case balancesnapshot.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case balancesnapshot.FieldOwnerID: + m.ResetOwnerID() + return nil + case balancesnapshot.FieldGrantBalances: + m.ResetGrantBalances() + return nil + case balancesnapshot.FieldUsage: + m.ResetUsage() + return nil + case balancesnapshot.FieldBalance: + m.ResetBalance() + return nil + case balancesnapshot.FieldOverage: + m.ResetOverage() + return nil + case balancesnapshot.FieldAt: + m.ResetAt() + return nil + } + return fmt.Errorf("unknown BalanceSnapshot field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BalanceSnapshotMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.entitlement != nil { + edges = append(edges, balancesnapshot.EdgeEntitlement) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BalanceSnapshotMutation) AddedIDs(name string) []ent.Value { + switch name { + case balancesnapshot.EdgeEntitlement: + if id := m.entitlement; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BalanceSnapshotMutation) 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 *BalanceSnapshotMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BalanceSnapshotMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedentitlement { + edges = append(edges, balancesnapshot.EdgeEntitlement) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BalanceSnapshotMutation) EdgeCleared(name string) bool { + switch name { + case balancesnapshot.EdgeEntitlement: + return m.clearedentitlement + } + 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 *BalanceSnapshotMutation) ClearEdge(name string) error { + switch name { + case balancesnapshot.EdgeEntitlement: + m.ClearEntitlement() + return nil + } + return fmt.Errorf("unknown BalanceSnapshot 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 *BalanceSnapshotMutation) ResetEdge(name string) error { + switch name { + case balancesnapshot.EdgeEntitlement: + m.ResetEntitlement() + return nil + } + return fmt.Errorf("unknown BalanceSnapshot edge %s", name) +} + +// BillingCustomerLockMutation represents an operation that mutates the BillingCustomerLock nodes in the graph. +type BillingCustomerLockMutation struct { + config + op Op + typ string + id *string + namespace *string + customer_id *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*BillingCustomerLock, error) + predicates []predicate.BillingCustomerLock +} + +var _ ent.Mutation = (*BillingCustomerLockMutation)(nil) + +// billingcustomerlockOption allows management of the mutation configuration using functional options. +type billingcustomerlockOption func(*BillingCustomerLockMutation) + +// newBillingCustomerLockMutation creates new mutation for the BillingCustomerLock entity. +func newBillingCustomerLockMutation(c config, op Op, opts ...billingcustomerlockOption) *BillingCustomerLockMutation { + m := &BillingCustomerLockMutation{ + config: c, + op: op, + typ: TypeBillingCustomerLock, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBillingCustomerLockID sets the ID field of the mutation. +func withBillingCustomerLockID(id string) billingcustomerlockOption { + return func(m *BillingCustomerLockMutation) { + var ( + err error + once sync.Once + value *BillingCustomerLock + ) + m.oldValue = func(ctx context.Context) (*BillingCustomerLock, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().BillingCustomerLock.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBillingCustomerLock sets the old BillingCustomerLock of the mutation. +func withBillingCustomerLock(node *BillingCustomerLock) billingcustomerlockOption { + return func(m *BillingCustomerLockMutation) { + m.oldValue = func(context.Context) (*BillingCustomerLock, 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 BillingCustomerLockMutation) 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 BillingCustomerLockMutation) 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 BillingCustomerLock entities. +func (m *BillingCustomerLockMutation) 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 *BillingCustomerLockMutation) 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 *BillingCustomerLockMutation) 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().BillingCustomerLock.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 *BillingCustomerLockMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *BillingCustomerLockMutation) 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 BillingCustomerLock entity. +// If the BillingCustomerLock 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 *BillingCustomerLockMutation) 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 *BillingCustomerLockMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCustomerID sets the "customer_id" field. +func (m *BillingCustomerLockMutation) SetCustomerID(s string) { + m.customer_id = &s +} + +// CustomerID returns the value of the "customer_id" field in the mutation. +func (m *BillingCustomerLockMutation) CustomerID() (r string, exists bool) { + v := m.customer_id + if v == nil { + return + } + return *v, true +} + +// OldCustomerID returns the old "customer_id" field's value of the BillingCustomerLock entity. +// If the BillingCustomerLock 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 *BillingCustomerLockMutation) OldCustomerID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerID: %w", err) + } + return oldValue.CustomerID, nil +} + +// ResetCustomerID resets all changes to the "customer_id" field. +func (m *BillingCustomerLockMutation) ResetCustomerID() { + m.customer_id = nil +} + +// Where appends a list predicates to the BillingCustomerLockMutation builder. +func (m *BillingCustomerLockMutation) Where(ps ...predicate.BillingCustomerLock) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BillingCustomerLockMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BillingCustomerLockMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillingCustomerLock, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BillingCustomerLockMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BillingCustomerLockMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BillingCustomerLock). +func (m *BillingCustomerLockMutation) 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 *BillingCustomerLockMutation) Fields() []string { + fields := make([]string, 0, 2) + if m.namespace != nil { + fields = append(fields, billingcustomerlock.FieldNamespace) + } + if m.customer_id != nil { + fields = append(fields, billingcustomerlock.FieldCustomerID) + } + 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 *BillingCustomerLockMutation) Field(name string) (ent.Value, bool) { + switch name { + case billingcustomerlock.FieldNamespace: + return m.Namespace() + case billingcustomerlock.FieldCustomerID: + return m.CustomerID() + } + 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 *BillingCustomerLockMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case billingcustomerlock.FieldNamespace: + return m.OldNamespace(ctx) + case billingcustomerlock.FieldCustomerID: + return m.OldCustomerID(ctx) + } + return nil, fmt.Errorf("unknown BillingCustomerLock 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 *BillingCustomerLockMutation) SetField(name string, value ent.Value) error { + switch name { + case billingcustomerlock.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case billingcustomerlock.FieldCustomerID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerID(v) + return nil + } + return fmt.Errorf("unknown BillingCustomerLock field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BillingCustomerLockMutation) 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 *BillingCustomerLockMutation) 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 *BillingCustomerLockMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown BillingCustomerLock numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BillingCustomerLockMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BillingCustomerLockMutation) 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 *BillingCustomerLockMutation) ClearField(name string) error { + return fmt.Errorf("unknown BillingCustomerLock 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 *BillingCustomerLockMutation) ResetField(name string) error { + switch name { + case billingcustomerlock.FieldNamespace: + m.ResetNamespace() + return nil + case billingcustomerlock.FieldCustomerID: + m.ResetCustomerID() + return nil + } + return fmt.Errorf("unknown BillingCustomerLock field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BillingCustomerLockMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BillingCustomerLockMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BillingCustomerLockMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *BillingCustomerLockMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BillingCustomerLockMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BillingCustomerLockMutation) EdgeCleared(name string) bool { + 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 *BillingCustomerLockMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown BillingCustomerLock 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 *BillingCustomerLockMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown BillingCustomerLock edge %s", name) +} + +// BillingCustomerOverrideMutation represents an operation that mutates the BillingCustomerOverride nodes in the graph. +type BillingCustomerOverrideMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + tax_behavior *productcatalog.TaxBehavior + collection_alignment *billing.AlignmentKind + anchored_alignment_detail **billing.AnchoredAlignmentDetail + line_collection_period *datetime.ISODurationString + invoice_auto_advance *bool + invoice_draft_period *datetime.ISODurationString + invoice_due_after *datetime.ISODurationString + invoice_collection_method *billing.CollectionMethod + invoice_progressive_billing *bool + invoice_default_tax_config *productcatalog.TaxConfig + clearedFields map[string]struct{} + customer *string + clearedcustomer bool + billing_profile *string + clearedbilling_profile bool + tax_code *string + clearedtax_code bool + done bool + oldValue func(context.Context) (*BillingCustomerOverride, error) + predicates []predicate.BillingCustomerOverride +} + +var _ ent.Mutation = (*BillingCustomerOverrideMutation)(nil) + +// billingcustomeroverrideOption allows management of the mutation configuration using functional options. +type billingcustomeroverrideOption func(*BillingCustomerOverrideMutation) + +// newBillingCustomerOverrideMutation creates new mutation for the BillingCustomerOverride entity. +func newBillingCustomerOverrideMutation(c config, op Op, opts ...billingcustomeroverrideOption) *BillingCustomerOverrideMutation { + m := &BillingCustomerOverrideMutation{ + config: c, + op: op, + typ: TypeBillingCustomerOverride, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBillingCustomerOverrideID sets the ID field of the mutation. +func withBillingCustomerOverrideID(id string) billingcustomeroverrideOption { + return func(m *BillingCustomerOverrideMutation) { + var ( + err error + once sync.Once + value *BillingCustomerOverride + ) + m.oldValue = func(ctx context.Context) (*BillingCustomerOverride, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().BillingCustomerOverride.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBillingCustomerOverride sets the old BillingCustomerOverride of the mutation. +func withBillingCustomerOverride(node *BillingCustomerOverride) billingcustomeroverrideOption { + return func(m *BillingCustomerOverrideMutation) { + m.oldValue = func(context.Context) (*BillingCustomerOverride, 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 BillingCustomerOverrideMutation) 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 BillingCustomerOverrideMutation) 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 BillingCustomerOverride entities. +func (m *BillingCustomerOverrideMutation) 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 *BillingCustomerOverrideMutation) 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 *BillingCustomerOverrideMutation) 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().BillingCustomerOverride.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 *BillingCustomerOverrideMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *BillingCustomerOverrideMutation) 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 BillingCustomerOverride entity. +// If the BillingCustomerOverride 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 *BillingCustomerOverrideMutation) 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 *BillingCustomerOverrideMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *BillingCustomerOverrideMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *BillingCustomerOverrideMutation) 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 BillingCustomerOverride entity. +// If the BillingCustomerOverride 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 *BillingCustomerOverrideMutation) 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 *BillingCustomerOverrideMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *BillingCustomerOverrideMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *BillingCustomerOverrideMutation) 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 BillingCustomerOverride entity. +// If the BillingCustomerOverride 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 *BillingCustomerOverrideMutation) 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 *BillingCustomerOverrideMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *BillingCustomerOverrideMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *BillingCustomerOverrideMutation) 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 BillingCustomerOverride entity. +// If the BillingCustomerOverride 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 *BillingCustomerOverrideMutation) 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 *BillingCustomerOverrideMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[billingcustomeroverride.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *BillingCustomerOverrideMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[billingcustomeroverride.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *BillingCustomerOverrideMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, billingcustomeroverride.FieldDeletedAt) +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (m *BillingCustomerOverrideMutation) SetTaxCodeID(s string) { + m.tax_code = &s +} + +// TaxCodeID returns the value of the "tax_code_id" field in the mutation. +func (m *BillingCustomerOverrideMutation) TaxCodeID() (r string, exists bool) { + v := m.tax_code + if v == nil { + return + } + return *v, true +} + +// OldTaxCodeID returns the old "tax_code_id" field's value of the BillingCustomerOverride entity. +// If the BillingCustomerOverride 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 *BillingCustomerOverrideMutation) OldTaxCodeID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxCodeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxCodeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxCodeID: %w", err) + } + return oldValue.TaxCodeID, nil +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (m *BillingCustomerOverrideMutation) ClearTaxCodeID() { + m.tax_code = nil + m.clearedFields[billingcustomeroverride.FieldTaxCodeID] = struct{}{} +} + +// TaxCodeIDCleared returns if the "tax_code_id" field was cleared in this mutation. +func (m *BillingCustomerOverrideMutation) TaxCodeIDCleared() bool { + _, ok := m.clearedFields[billingcustomeroverride.FieldTaxCodeID] + return ok +} + +// ResetTaxCodeID resets all changes to the "tax_code_id" field. +func (m *BillingCustomerOverrideMutation) ResetTaxCodeID() { + m.tax_code = nil + delete(m.clearedFields, billingcustomeroverride.FieldTaxCodeID) +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (m *BillingCustomerOverrideMutation) SetTaxBehavior(pb productcatalog.TaxBehavior) { + m.tax_behavior = &pb +} + +// TaxBehavior returns the value of the "tax_behavior" field in the mutation. +func (m *BillingCustomerOverrideMutation) TaxBehavior() (r productcatalog.TaxBehavior, exists bool) { + v := m.tax_behavior + if v == nil { + return + } + return *v, true +} + +// OldTaxBehavior returns the old "tax_behavior" field's value of the BillingCustomerOverride entity. +// If the BillingCustomerOverride 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 *BillingCustomerOverrideMutation) OldTaxBehavior(ctx context.Context) (v *productcatalog.TaxBehavior, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxBehavior is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxBehavior requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxBehavior: %w", err) + } + return oldValue.TaxBehavior, nil +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (m *BillingCustomerOverrideMutation) ClearTaxBehavior() { + m.tax_behavior = nil + m.clearedFields[billingcustomeroverride.FieldTaxBehavior] = struct{}{} +} + +// TaxBehaviorCleared returns if the "tax_behavior" field was cleared in this mutation. +func (m *BillingCustomerOverrideMutation) TaxBehaviorCleared() bool { + _, ok := m.clearedFields[billingcustomeroverride.FieldTaxBehavior] + return ok +} + +// ResetTaxBehavior resets all changes to the "tax_behavior" field. +func (m *BillingCustomerOverrideMutation) ResetTaxBehavior() { + m.tax_behavior = nil + delete(m.clearedFields, billingcustomeroverride.FieldTaxBehavior) +} + +// SetCustomerID sets the "customer_id" field. +func (m *BillingCustomerOverrideMutation) SetCustomerID(s string) { + m.customer = &s +} + +// CustomerID returns the value of the "customer_id" field in the mutation. +func (m *BillingCustomerOverrideMutation) CustomerID() (r string, exists bool) { + v := m.customer + if v == nil { + return + } + return *v, true +} + +// OldCustomerID returns the old "customer_id" field's value of the BillingCustomerOverride entity. +// If the BillingCustomerOverride 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 *BillingCustomerOverrideMutation) OldCustomerID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerID: %w", err) + } + return oldValue.CustomerID, nil +} + +// ResetCustomerID resets all changes to the "customer_id" field. +func (m *BillingCustomerOverrideMutation) ResetCustomerID() { + m.customer = nil +} + +// SetBillingProfileID sets the "billing_profile_id" field. +func (m *BillingCustomerOverrideMutation) SetBillingProfileID(s string) { + m.billing_profile = &s +} + +// BillingProfileID returns the value of the "billing_profile_id" field in the mutation. +func (m *BillingCustomerOverrideMutation) BillingProfileID() (r string, exists bool) { + v := m.billing_profile + if v == nil { + return + } + return *v, true +} + +// OldBillingProfileID returns the old "billing_profile_id" field's value of the BillingCustomerOverride entity. +// If the BillingCustomerOverride 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 *BillingCustomerOverrideMutation) OldBillingProfileID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingProfileID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingProfileID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingProfileID: %w", err) + } + return oldValue.BillingProfileID, nil +} + +// ClearBillingProfileID clears the value of the "billing_profile_id" field. +func (m *BillingCustomerOverrideMutation) ClearBillingProfileID() { + m.billing_profile = nil + m.clearedFields[billingcustomeroverride.FieldBillingProfileID] = struct{}{} +} + +// BillingProfileIDCleared returns if the "billing_profile_id" field was cleared in this mutation. +func (m *BillingCustomerOverrideMutation) BillingProfileIDCleared() bool { + _, ok := m.clearedFields[billingcustomeroverride.FieldBillingProfileID] + return ok +} + +// ResetBillingProfileID resets all changes to the "billing_profile_id" field. +func (m *BillingCustomerOverrideMutation) ResetBillingProfileID() { + m.billing_profile = nil + delete(m.clearedFields, billingcustomeroverride.FieldBillingProfileID) +} + +// SetCollectionAlignment sets the "collection_alignment" field. +func (m *BillingCustomerOverrideMutation) SetCollectionAlignment(bk billing.AlignmentKind) { + m.collection_alignment = &bk +} + +// CollectionAlignment returns the value of the "collection_alignment" field in the mutation. +func (m *BillingCustomerOverrideMutation) CollectionAlignment() (r billing.AlignmentKind, exists bool) { + v := m.collection_alignment + if v == nil { + return + } + return *v, true +} + +// OldCollectionAlignment returns the old "collection_alignment" field's value of the BillingCustomerOverride entity. +// If the BillingCustomerOverride 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 *BillingCustomerOverrideMutation) OldCollectionAlignment(ctx context.Context) (v *billing.AlignmentKind, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCollectionAlignment is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCollectionAlignment requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCollectionAlignment: %w", err) + } + return oldValue.CollectionAlignment, nil +} + +// ClearCollectionAlignment clears the value of the "collection_alignment" field. +func (m *BillingCustomerOverrideMutation) ClearCollectionAlignment() { + m.collection_alignment = nil + m.clearedFields[billingcustomeroverride.FieldCollectionAlignment] = struct{}{} +} + +// CollectionAlignmentCleared returns if the "collection_alignment" field was cleared in this mutation. +func (m *BillingCustomerOverrideMutation) CollectionAlignmentCleared() bool { + _, ok := m.clearedFields[billingcustomeroverride.FieldCollectionAlignment] + return ok +} + +// ResetCollectionAlignment resets all changes to the "collection_alignment" field. +func (m *BillingCustomerOverrideMutation) ResetCollectionAlignment() { + m.collection_alignment = nil + delete(m.clearedFields, billingcustomeroverride.FieldCollectionAlignment) +} + +// SetAnchoredAlignmentDetail sets the "anchored_alignment_detail" field. +func (m *BillingCustomerOverrideMutation) SetAnchoredAlignmentDetail(bad *billing.AnchoredAlignmentDetail) { + m.anchored_alignment_detail = &bad +} + +// AnchoredAlignmentDetail returns the value of the "anchored_alignment_detail" field in the mutation. +func (m *BillingCustomerOverrideMutation) AnchoredAlignmentDetail() (r *billing.AnchoredAlignmentDetail, exists bool) { + v := m.anchored_alignment_detail + if v == nil { + return + } + return *v, true +} + +// OldAnchoredAlignmentDetail returns the old "anchored_alignment_detail" field's value of the BillingCustomerOverride entity. +// If the BillingCustomerOverride 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 *BillingCustomerOverrideMutation) OldAnchoredAlignmentDetail(ctx context.Context) (v *billing.AnchoredAlignmentDetail, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAnchoredAlignmentDetail is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAnchoredAlignmentDetail requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAnchoredAlignmentDetail: %w", err) + } + return oldValue.AnchoredAlignmentDetail, nil +} + +// ClearAnchoredAlignmentDetail clears the value of the "anchored_alignment_detail" field. +func (m *BillingCustomerOverrideMutation) ClearAnchoredAlignmentDetail() { + m.anchored_alignment_detail = nil + m.clearedFields[billingcustomeroverride.FieldAnchoredAlignmentDetail] = struct{}{} +} + +// AnchoredAlignmentDetailCleared returns if the "anchored_alignment_detail" field was cleared in this mutation. +func (m *BillingCustomerOverrideMutation) AnchoredAlignmentDetailCleared() bool { + _, ok := m.clearedFields[billingcustomeroverride.FieldAnchoredAlignmentDetail] + return ok +} + +// ResetAnchoredAlignmentDetail resets all changes to the "anchored_alignment_detail" field. +func (m *BillingCustomerOverrideMutation) ResetAnchoredAlignmentDetail() { + m.anchored_alignment_detail = nil + delete(m.clearedFields, billingcustomeroverride.FieldAnchoredAlignmentDetail) +} + +// SetLineCollectionPeriod sets the "line_collection_period" field. +func (m *BillingCustomerOverrideMutation) SetLineCollectionPeriod(dds datetime.ISODurationString) { + m.line_collection_period = &dds +} + +// LineCollectionPeriod returns the value of the "line_collection_period" field in the mutation. +func (m *BillingCustomerOverrideMutation) LineCollectionPeriod() (r datetime.ISODurationString, exists bool) { + v := m.line_collection_period + if v == nil { + return + } + return *v, true +} + +// OldLineCollectionPeriod returns the old "line_collection_period" field's value of the BillingCustomerOverride entity. +// If the BillingCustomerOverride 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 *BillingCustomerOverrideMutation) OldLineCollectionPeriod(ctx context.Context) (v *datetime.ISODurationString, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLineCollectionPeriod is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLineCollectionPeriod requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLineCollectionPeriod: %w", err) + } + return oldValue.LineCollectionPeriod, nil +} + +// ClearLineCollectionPeriod clears the value of the "line_collection_period" field. +func (m *BillingCustomerOverrideMutation) ClearLineCollectionPeriod() { + m.line_collection_period = nil + m.clearedFields[billingcustomeroverride.FieldLineCollectionPeriod] = struct{}{} +} + +// LineCollectionPeriodCleared returns if the "line_collection_period" field was cleared in this mutation. +func (m *BillingCustomerOverrideMutation) LineCollectionPeriodCleared() bool { + _, ok := m.clearedFields[billingcustomeroverride.FieldLineCollectionPeriod] + return ok +} + +// ResetLineCollectionPeriod resets all changes to the "line_collection_period" field. +func (m *BillingCustomerOverrideMutation) ResetLineCollectionPeriod() { + m.line_collection_period = nil + delete(m.clearedFields, billingcustomeroverride.FieldLineCollectionPeriod) +} + +// SetInvoiceAutoAdvance sets the "invoice_auto_advance" field. +func (m *BillingCustomerOverrideMutation) SetInvoiceAutoAdvance(b bool) { + m.invoice_auto_advance = &b +} + +// InvoiceAutoAdvance returns the value of the "invoice_auto_advance" field in the mutation. +func (m *BillingCustomerOverrideMutation) InvoiceAutoAdvance() (r bool, exists bool) { + v := m.invoice_auto_advance + if v == nil { + return + } + return *v, true +} + +// OldInvoiceAutoAdvance returns the old "invoice_auto_advance" field's value of the BillingCustomerOverride entity. +// If the BillingCustomerOverride 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 *BillingCustomerOverrideMutation) OldInvoiceAutoAdvance(ctx context.Context) (v *bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceAutoAdvance is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceAutoAdvance requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceAutoAdvance: %w", err) + } + return oldValue.InvoiceAutoAdvance, nil +} + +// ClearInvoiceAutoAdvance clears the value of the "invoice_auto_advance" field. +func (m *BillingCustomerOverrideMutation) ClearInvoiceAutoAdvance() { + m.invoice_auto_advance = nil + m.clearedFields[billingcustomeroverride.FieldInvoiceAutoAdvance] = struct{}{} +} + +// InvoiceAutoAdvanceCleared returns if the "invoice_auto_advance" field was cleared in this mutation. +func (m *BillingCustomerOverrideMutation) InvoiceAutoAdvanceCleared() bool { + _, ok := m.clearedFields[billingcustomeroverride.FieldInvoiceAutoAdvance] + return ok +} + +// ResetInvoiceAutoAdvance resets all changes to the "invoice_auto_advance" field. +func (m *BillingCustomerOverrideMutation) ResetInvoiceAutoAdvance() { + m.invoice_auto_advance = nil + delete(m.clearedFields, billingcustomeroverride.FieldInvoiceAutoAdvance) +} + +// SetInvoiceDraftPeriod sets the "invoice_draft_period" field. +func (m *BillingCustomerOverrideMutation) SetInvoiceDraftPeriod(dds datetime.ISODurationString) { + m.invoice_draft_period = &dds +} + +// InvoiceDraftPeriod returns the value of the "invoice_draft_period" field in the mutation. +func (m *BillingCustomerOverrideMutation) InvoiceDraftPeriod() (r datetime.ISODurationString, exists bool) { + v := m.invoice_draft_period + if v == nil { + return + } + return *v, true +} + +// OldInvoiceDraftPeriod returns the old "invoice_draft_period" field's value of the BillingCustomerOverride entity. +// If the BillingCustomerOverride 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 *BillingCustomerOverrideMutation) OldInvoiceDraftPeriod(ctx context.Context) (v *datetime.ISODurationString, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceDraftPeriod is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceDraftPeriod requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceDraftPeriod: %w", err) + } + return oldValue.InvoiceDraftPeriod, nil +} + +// ClearInvoiceDraftPeriod clears the value of the "invoice_draft_period" field. +func (m *BillingCustomerOverrideMutation) ClearInvoiceDraftPeriod() { + m.invoice_draft_period = nil + m.clearedFields[billingcustomeroverride.FieldInvoiceDraftPeriod] = struct{}{} +} + +// InvoiceDraftPeriodCleared returns if the "invoice_draft_period" field was cleared in this mutation. +func (m *BillingCustomerOverrideMutation) InvoiceDraftPeriodCleared() bool { + _, ok := m.clearedFields[billingcustomeroverride.FieldInvoiceDraftPeriod] + return ok +} + +// ResetInvoiceDraftPeriod resets all changes to the "invoice_draft_period" field. +func (m *BillingCustomerOverrideMutation) ResetInvoiceDraftPeriod() { + m.invoice_draft_period = nil + delete(m.clearedFields, billingcustomeroverride.FieldInvoiceDraftPeriod) +} + +// SetInvoiceDueAfter sets the "invoice_due_after" field. +func (m *BillingCustomerOverrideMutation) SetInvoiceDueAfter(dds datetime.ISODurationString) { + m.invoice_due_after = &dds +} + +// InvoiceDueAfter returns the value of the "invoice_due_after" field in the mutation. +func (m *BillingCustomerOverrideMutation) InvoiceDueAfter() (r datetime.ISODurationString, exists bool) { + v := m.invoice_due_after + if v == nil { + return + } + return *v, true +} + +// OldInvoiceDueAfter returns the old "invoice_due_after" field's value of the BillingCustomerOverride entity. +// If the BillingCustomerOverride 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 *BillingCustomerOverrideMutation) OldInvoiceDueAfter(ctx context.Context) (v *datetime.ISODurationString, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceDueAfter is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceDueAfter requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceDueAfter: %w", err) + } + return oldValue.InvoiceDueAfter, nil +} + +// ClearInvoiceDueAfter clears the value of the "invoice_due_after" field. +func (m *BillingCustomerOverrideMutation) ClearInvoiceDueAfter() { + m.invoice_due_after = nil + m.clearedFields[billingcustomeroverride.FieldInvoiceDueAfter] = struct{}{} +} + +// InvoiceDueAfterCleared returns if the "invoice_due_after" field was cleared in this mutation. +func (m *BillingCustomerOverrideMutation) InvoiceDueAfterCleared() bool { + _, ok := m.clearedFields[billingcustomeroverride.FieldInvoiceDueAfter] + return ok +} + +// ResetInvoiceDueAfter resets all changes to the "invoice_due_after" field. +func (m *BillingCustomerOverrideMutation) ResetInvoiceDueAfter() { + m.invoice_due_after = nil + delete(m.clearedFields, billingcustomeroverride.FieldInvoiceDueAfter) +} + +// SetInvoiceCollectionMethod sets the "invoice_collection_method" field. +func (m *BillingCustomerOverrideMutation) SetInvoiceCollectionMethod(bm billing.CollectionMethod) { + m.invoice_collection_method = &bm +} + +// InvoiceCollectionMethod returns the value of the "invoice_collection_method" field in the mutation. +func (m *BillingCustomerOverrideMutation) InvoiceCollectionMethod() (r billing.CollectionMethod, exists bool) { + v := m.invoice_collection_method + if v == nil { + return + } + return *v, true +} + +// OldInvoiceCollectionMethod returns the old "invoice_collection_method" field's value of the BillingCustomerOverride entity. +// If the BillingCustomerOverride 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 *BillingCustomerOverrideMutation) OldInvoiceCollectionMethod(ctx context.Context) (v *billing.CollectionMethod, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceCollectionMethod is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceCollectionMethod requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceCollectionMethod: %w", err) + } + return oldValue.InvoiceCollectionMethod, nil +} + +// ClearInvoiceCollectionMethod clears the value of the "invoice_collection_method" field. +func (m *BillingCustomerOverrideMutation) ClearInvoiceCollectionMethod() { + m.invoice_collection_method = nil + m.clearedFields[billingcustomeroverride.FieldInvoiceCollectionMethod] = struct{}{} +} + +// InvoiceCollectionMethodCleared returns if the "invoice_collection_method" field was cleared in this mutation. +func (m *BillingCustomerOverrideMutation) InvoiceCollectionMethodCleared() bool { + _, ok := m.clearedFields[billingcustomeroverride.FieldInvoiceCollectionMethod] + return ok +} + +// ResetInvoiceCollectionMethod resets all changes to the "invoice_collection_method" field. +func (m *BillingCustomerOverrideMutation) ResetInvoiceCollectionMethod() { + m.invoice_collection_method = nil + delete(m.clearedFields, billingcustomeroverride.FieldInvoiceCollectionMethod) +} + +// SetInvoiceProgressiveBilling sets the "invoice_progressive_billing" field. +func (m *BillingCustomerOverrideMutation) SetInvoiceProgressiveBilling(b bool) { + m.invoice_progressive_billing = &b +} + +// InvoiceProgressiveBilling returns the value of the "invoice_progressive_billing" field in the mutation. +func (m *BillingCustomerOverrideMutation) InvoiceProgressiveBilling() (r bool, exists bool) { + v := m.invoice_progressive_billing + if v == nil { + return + } + return *v, true +} + +// OldInvoiceProgressiveBilling returns the old "invoice_progressive_billing" field's value of the BillingCustomerOverride entity. +// If the BillingCustomerOverride 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 *BillingCustomerOverrideMutation) OldInvoiceProgressiveBilling(ctx context.Context) (v *bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceProgressiveBilling is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceProgressiveBilling requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceProgressiveBilling: %w", err) + } + return oldValue.InvoiceProgressiveBilling, nil +} + +// ClearInvoiceProgressiveBilling clears the value of the "invoice_progressive_billing" field. +func (m *BillingCustomerOverrideMutation) ClearInvoiceProgressiveBilling() { + m.invoice_progressive_billing = nil + m.clearedFields[billingcustomeroverride.FieldInvoiceProgressiveBilling] = struct{}{} +} + +// InvoiceProgressiveBillingCleared returns if the "invoice_progressive_billing" field was cleared in this mutation. +func (m *BillingCustomerOverrideMutation) InvoiceProgressiveBillingCleared() bool { + _, ok := m.clearedFields[billingcustomeroverride.FieldInvoiceProgressiveBilling] + return ok +} + +// ResetInvoiceProgressiveBilling resets all changes to the "invoice_progressive_billing" field. +func (m *BillingCustomerOverrideMutation) ResetInvoiceProgressiveBilling() { + m.invoice_progressive_billing = nil + delete(m.clearedFields, billingcustomeroverride.FieldInvoiceProgressiveBilling) +} + +// SetInvoiceDefaultTaxConfig sets the "invoice_default_tax_config" field. +func (m *BillingCustomerOverrideMutation) SetInvoiceDefaultTaxConfig(pc productcatalog.TaxConfig) { + m.invoice_default_tax_config = &pc +} + +// InvoiceDefaultTaxConfig returns the value of the "invoice_default_tax_config" field in the mutation. +func (m *BillingCustomerOverrideMutation) InvoiceDefaultTaxConfig() (r productcatalog.TaxConfig, exists bool) { + v := m.invoice_default_tax_config + if v == nil { + return + } + return *v, true +} + +// OldInvoiceDefaultTaxConfig returns the old "invoice_default_tax_config" field's value of the BillingCustomerOverride entity. +// If the BillingCustomerOverride 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 *BillingCustomerOverrideMutation) OldInvoiceDefaultTaxConfig(ctx context.Context) (v productcatalog.TaxConfig, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceDefaultTaxConfig is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceDefaultTaxConfig requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceDefaultTaxConfig: %w", err) + } + return oldValue.InvoiceDefaultTaxConfig, nil +} + +// ClearInvoiceDefaultTaxConfig clears the value of the "invoice_default_tax_config" field. +func (m *BillingCustomerOverrideMutation) ClearInvoiceDefaultTaxConfig() { + m.invoice_default_tax_config = nil + m.clearedFields[billingcustomeroverride.FieldInvoiceDefaultTaxConfig] = struct{}{} +} + +// InvoiceDefaultTaxConfigCleared returns if the "invoice_default_tax_config" field was cleared in this mutation. +func (m *BillingCustomerOverrideMutation) InvoiceDefaultTaxConfigCleared() bool { + _, ok := m.clearedFields[billingcustomeroverride.FieldInvoiceDefaultTaxConfig] + return ok +} + +// ResetInvoiceDefaultTaxConfig resets all changes to the "invoice_default_tax_config" field. +func (m *BillingCustomerOverrideMutation) ResetInvoiceDefaultTaxConfig() { + m.invoice_default_tax_config = nil + delete(m.clearedFields, billingcustomeroverride.FieldInvoiceDefaultTaxConfig) +} + +// ClearCustomer clears the "customer" edge to the Customer entity. +func (m *BillingCustomerOverrideMutation) ClearCustomer() { + m.clearedcustomer = true + m.clearedFields[billingcustomeroverride.FieldCustomerID] = struct{}{} +} + +// CustomerCleared reports if the "customer" edge to the Customer entity was cleared. +func (m *BillingCustomerOverrideMutation) CustomerCleared() bool { + return m.clearedcustomer +} + +// CustomerIDs returns the "customer" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CustomerID instead. It exists only for internal usage by the builders. +func (m *BillingCustomerOverrideMutation) CustomerIDs() (ids []string) { + if id := m.customer; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCustomer resets all changes to the "customer" edge. +func (m *BillingCustomerOverrideMutation) ResetCustomer() { + m.customer = nil + m.clearedcustomer = false +} + +// ClearBillingProfile clears the "billing_profile" edge to the BillingProfile entity. +func (m *BillingCustomerOverrideMutation) ClearBillingProfile() { + m.clearedbilling_profile = true + m.clearedFields[billingcustomeroverride.FieldBillingProfileID] = struct{}{} +} + +// BillingProfileCleared reports if the "billing_profile" edge to the BillingProfile entity was cleared. +func (m *BillingCustomerOverrideMutation) BillingProfileCleared() bool { + return m.BillingProfileIDCleared() || m.clearedbilling_profile +} + +// BillingProfileIDs returns the "billing_profile" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BillingProfileID instead. It exists only for internal usage by the builders. +func (m *BillingCustomerOverrideMutation) BillingProfileIDs() (ids []string) { + if id := m.billing_profile; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBillingProfile resets all changes to the "billing_profile" edge. +func (m *BillingCustomerOverrideMutation) ResetBillingProfile() { + m.billing_profile = nil + m.clearedbilling_profile = false +} + +// ClearTaxCode clears the "tax_code" edge to the TaxCode entity. +func (m *BillingCustomerOverrideMutation) ClearTaxCode() { + m.clearedtax_code = true + m.clearedFields[billingcustomeroverride.FieldTaxCodeID] = struct{}{} +} + +// TaxCodeCleared reports if the "tax_code" edge to the TaxCode entity was cleared. +func (m *BillingCustomerOverrideMutation) TaxCodeCleared() bool { + return m.TaxCodeIDCleared() || m.clearedtax_code +} + +// TaxCodeIDs returns the "tax_code" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TaxCodeID instead. It exists only for internal usage by the builders. +func (m *BillingCustomerOverrideMutation) TaxCodeIDs() (ids []string) { + if id := m.tax_code; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTaxCode resets all changes to the "tax_code" edge. +func (m *BillingCustomerOverrideMutation) ResetTaxCode() { + m.tax_code = nil + m.clearedtax_code = false +} + +// Where appends a list predicates to the BillingCustomerOverrideMutation builder. +func (m *BillingCustomerOverrideMutation) Where(ps ...predicate.BillingCustomerOverride) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BillingCustomerOverrideMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BillingCustomerOverrideMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillingCustomerOverride, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BillingCustomerOverrideMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BillingCustomerOverrideMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BillingCustomerOverride). +func (m *BillingCustomerOverrideMutation) 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 *BillingCustomerOverrideMutation) Fields() []string { + fields := make([]string, 0, 17) + if m.namespace != nil { + fields = append(fields, billingcustomeroverride.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, billingcustomeroverride.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, billingcustomeroverride.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, billingcustomeroverride.FieldDeletedAt) + } + if m.tax_code != nil { + fields = append(fields, billingcustomeroverride.FieldTaxCodeID) + } + if m.tax_behavior != nil { + fields = append(fields, billingcustomeroverride.FieldTaxBehavior) + } + if m.customer != nil { + fields = append(fields, billingcustomeroverride.FieldCustomerID) + } + if m.billing_profile != nil { + fields = append(fields, billingcustomeroverride.FieldBillingProfileID) + } + if m.collection_alignment != nil { + fields = append(fields, billingcustomeroverride.FieldCollectionAlignment) + } + if m.anchored_alignment_detail != nil { + fields = append(fields, billingcustomeroverride.FieldAnchoredAlignmentDetail) + } + if m.line_collection_period != nil { + fields = append(fields, billingcustomeroverride.FieldLineCollectionPeriod) + } + if m.invoice_auto_advance != nil { + fields = append(fields, billingcustomeroverride.FieldInvoiceAutoAdvance) + } + if m.invoice_draft_period != nil { + fields = append(fields, billingcustomeroverride.FieldInvoiceDraftPeriod) + } + if m.invoice_due_after != nil { + fields = append(fields, billingcustomeroverride.FieldInvoiceDueAfter) + } + if m.invoice_collection_method != nil { + fields = append(fields, billingcustomeroverride.FieldInvoiceCollectionMethod) + } + if m.invoice_progressive_billing != nil { + fields = append(fields, billingcustomeroverride.FieldInvoiceProgressiveBilling) + } + if m.invoice_default_tax_config != nil { + fields = append(fields, billingcustomeroverride.FieldInvoiceDefaultTaxConfig) + } + 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 *BillingCustomerOverrideMutation) Field(name string) (ent.Value, bool) { + switch name { + case billingcustomeroverride.FieldNamespace: + return m.Namespace() + case billingcustomeroverride.FieldCreatedAt: + return m.CreatedAt() + case billingcustomeroverride.FieldUpdatedAt: + return m.UpdatedAt() + case billingcustomeroverride.FieldDeletedAt: + return m.DeletedAt() + case billingcustomeroverride.FieldTaxCodeID: + return m.TaxCodeID() + case billingcustomeroverride.FieldTaxBehavior: + return m.TaxBehavior() + case billingcustomeroverride.FieldCustomerID: + return m.CustomerID() + case billingcustomeroverride.FieldBillingProfileID: + return m.BillingProfileID() + case billingcustomeroverride.FieldCollectionAlignment: + return m.CollectionAlignment() + case billingcustomeroverride.FieldAnchoredAlignmentDetail: + return m.AnchoredAlignmentDetail() + case billingcustomeroverride.FieldLineCollectionPeriod: + return m.LineCollectionPeriod() + case billingcustomeroverride.FieldInvoiceAutoAdvance: + return m.InvoiceAutoAdvance() + case billingcustomeroverride.FieldInvoiceDraftPeriod: + return m.InvoiceDraftPeriod() + case billingcustomeroverride.FieldInvoiceDueAfter: + return m.InvoiceDueAfter() + case billingcustomeroverride.FieldInvoiceCollectionMethod: + return m.InvoiceCollectionMethod() + case billingcustomeroverride.FieldInvoiceProgressiveBilling: + return m.InvoiceProgressiveBilling() + case billingcustomeroverride.FieldInvoiceDefaultTaxConfig: + return m.InvoiceDefaultTaxConfig() + } + 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 *BillingCustomerOverrideMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case billingcustomeroverride.FieldNamespace: + return m.OldNamespace(ctx) + case billingcustomeroverride.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case billingcustomeroverride.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case billingcustomeroverride.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case billingcustomeroverride.FieldTaxCodeID: + return m.OldTaxCodeID(ctx) + case billingcustomeroverride.FieldTaxBehavior: + return m.OldTaxBehavior(ctx) + case billingcustomeroverride.FieldCustomerID: + return m.OldCustomerID(ctx) + case billingcustomeroverride.FieldBillingProfileID: + return m.OldBillingProfileID(ctx) + case billingcustomeroverride.FieldCollectionAlignment: + return m.OldCollectionAlignment(ctx) + case billingcustomeroverride.FieldAnchoredAlignmentDetail: + return m.OldAnchoredAlignmentDetail(ctx) + case billingcustomeroverride.FieldLineCollectionPeriod: + return m.OldLineCollectionPeriod(ctx) + case billingcustomeroverride.FieldInvoiceAutoAdvance: + return m.OldInvoiceAutoAdvance(ctx) + case billingcustomeroverride.FieldInvoiceDraftPeriod: + return m.OldInvoiceDraftPeriod(ctx) + case billingcustomeroverride.FieldInvoiceDueAfter: + return m.OldInvoiceDueAfter(ctx) + case billingcustomeroverride.FieldInvoiceCollectionMethod: + return m.OldInvoiceCollectionMethod(ctx) + case billingcustomeroverride.FieldInvoiceProgressiveBilling: + return m.OldInvoiceProgressiveBilling(ctx) + case billingcustomeroverride.FieldInvoiceDefaultTaxConfig: + return m.OldInvoiceDefaultTaxConfig(ctx) + } + return nil, fmt.Errorf("unknown BillingCustomerOverride 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 *BillingCustomerOverrideMutation) SetField(name string, value ent.Value) error { + switch name { + case billingcustomeroverride.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case billingcustomeroverride.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 billingcustomeroverride.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 billingcustomeroverride.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 billingcustomeroverride.FieldTaxCodeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxCodeID(v) + return nil + case billingcustomeroverride.FieldTaxBehavior: + v, ok := value.(productcatalog.TaxBehavior) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxBehavior(v) + return nil + case billingcustomeroverride.FieldCustomerID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerID(v) + return nil + case billingcustomeroverride.FieldBillingProfileID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingProfileID(v) + return nil + case billingcustomeroverride.FieldCollectionAlignment: + v, ok := value.(billing.AlignmentKind) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCollectionAlignment(v) + return nil + case billingcustomeroverride.FieldAnchoredAlignmentDetail: + v, ok := value.(*billing.AnchoredAlignmentDetail) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAnchoredAlignmentDetail(v) + return nil + case billingcustomeroverride.FieldLineCollectionPeriod: + v, ok := value.(datetime.ISODurationString) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLineCollectionPeriod(v) + return nil + case billingcustomeroverride.FieldInvoiceAutoAdvance: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceAutoAdvance(v) + return nil + case billingcustomeroverride.FieldInvoiceDraftPeriod: + v, ok := value.(datetime.ISODurationString) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceDraftPeriod(v) + return nil + case billingcustomeroverride.FieldInvoiceDueAfter: + v, ok := value.(datetime.ISODurationString) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceDueAfter(v) + return nil + case billingcustomeroverride.FieldInvoiceCollectionMethod: + v, ok := value.(billing.CollectionMethod) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceCollectionMethod(v) + return nil + case billingcustomeroverride.FieldInvoiceProgressiveBilling: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceProgressiveBilling(v) + return nil + case billingcustomeroverride.FieldInvoiceDefaultTaxConfig: + v, ok := value.(productcatalog.TaxConfig) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceDefaultTaxConfig(v) + return nil + } + return fmt.Errorf("unknown BillingCustomerOverride field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BillingCustomerOverrideMutation) 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 *BillingCustomerOverrideMutation) 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 *BillingCustomerOverrideMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown BillingCustomerOverride numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BillingCustomerOverrideMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(billingcustomeroverride.FieldDeletedAt) { + fields = append(fields, billingcustomeroverride.FieldDeletedAt) + } + if m.FieldCleared(billingcustomeroverride.FieldTaxCodeID) { + fields = append(fields, billingcustomeroverride.FieldTaxCodeID) + } + if m.FieldCleared(billingcustomeroverride.FieldTaxBehavior) { + fields = append(fields, billingcustomeroverride.FieldTaxBehavior) + } + if m.FieldCleared(billingcustomeroverride.FieldBillingProfileID) { + fields = append(fields, billingcustomeroverride.FieldBillingProfileID) + } + if m.FieldCleared(billingcustomeroverride.FieldCollectionAlignment) { + fields = append(fields, billingcustomeroverride.FieldCollectionAlignment) + } + if m.FieldCleared(billingcustomeroverride.FieldAnchoredAlignmentDetail) { + fields = append(fields, billingcustomeroverride.FieldAnchoredAlignmentDetail) + } + if m.FieldCleared(billingcustomeroverride.FieldLineCollectionPeriod) { + fields = append(fields, billingcustomeroverride.FieldLineCollectionPeriod) + } + if m.FieldCleared(billingcustomeroverride.FieldInvoiceAutoAdvance) { + fields = append(fields, billingcustomeroverride.FieldInvoiceAutoAdvance) + } + if m.FieldCleared(billingcustomeroverride.FieldInvoiceDraftPeriod) { + fields = append(fields, billingcustomeroverride.FieldInvoiceDraftPeriod) + } + if m.FieldCleared(billingcustomeroverride.FieldInvoiceDueAfter) { + fields = append(fields, billingcustomeroverride.FieldInvoiceDueAfter) + } + if m.FieldCleared(billingcustomeroverride.FieldInvoiceCollectionMethod) { + fields = append(fields, billingcustomeroverride.FieldInvoiceCollectionMethod) + } + if m.FieldCleared(billingcustomeroverride.FieldInvoiceProgressiveBilling) { + fields = append(fields, billingcustomeroverride.FieldInvoiceProgressiveBilling) + } + if m.FieldCleared(billingcustomeroverride.FieldInvoiceDefaultTaxConfig) { + fields = append(fields, billingcustomeroverride.FieldInvoiceDefaultTaxConfig) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BillingCustomerOverrideMutation) 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 *BillingCustomerOverrideMutation) ClearField(name string) error { + switch name { + case billingcustomeroverride.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case billingcustomeroverride.FieldTaxCodeID: + m.ClearTaxCodeID() + return nil + case billingcustomeroverride.FieldTaxBehavior: + m.ClearTaxBehavior() + return nil + case billingcustomeroverride.FieldBillingProfileID: + m.ClearBillingProfileID() + return nil + case billingcustomeroverride.FieldCollectionAlignment: + m.ClearCollectionAlignment() + return nil + case billingcustomeroverride.FieldAnchoredAlignmentDetail: + m.ClearAnchoredAlignmentDetail() + return nil + case billingcustomeroverride.FieldLineCollectionPeriod: + m.ClearLineCollectionPeriod() + return nil + case billingcustomeroverride.FieldInvoiceAutoAdvance: + m.ClearInvoiceAutoAdvance() + return nil + case billingcustomeroverride.FieldInvoiceDraftPeriod: + m.ClearInvoiceDraftPeriod() + return nil + case billingcustomeroverride.FieldInvoiceDueAfter: + m.ClearInvoiceDueAfter() + return nil + case billingcustomeroverride.FieldInvoiceCollectionMethod: + m.ClearInvoiceCollectionMethod() + return nil + case billingcustomeroverride.FieldInvoiceProgressiveBilling: + m.ClearInvoiceProgressiveBilling() + return nil + case billingcustomeroverride.FieldInvoiceDefaultTaxConfig: + m.ClearInvoiceDefaultTaxConfig() + return nil + } + return fmt.Errorf("unknown BillingCustomerOverride 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 *BillingCustomerOverrideMutation) ResetField(name string) error { + switch name { + case billingcustomeroverride.FieldNamespace: + m.ResetNamespace() + return nil + case billingcustomeroverride.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case billingcustomeroverride.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case billingcustomeroverride.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case billingcustomeroverride.FieldTaxCodeID: + m.ResetTaxCodeID() + return nil + case billingcustomeroverride.FieldTaxBehavior: + m.ResetTaxBehavior() + return nil + case billingcustomeroverride.FieldCustomerID: + m.ResetCustomerID() + return nil + case billingcustomeroverride.FieldBillingProfileID: + m.ResetBillingProfileID() + return nil + case billingcustomeroverride.FieldCollectionAlignment: + m.ResetCollectionAlignment() + return nil + case billingcustomeroverride.FieldAnchoredAlignmentDetail: + m.ResetAnchoredAlignmentDetail() + return nil + case billingcustomeroverride.FieldLineCollectionPeriod: + m.ResetLineCollectionPeriod() + return nil + case billingcustomeroverride.FieldInvoiceAutoAdvance: + m.ResetInvoiceAutoAdvance() + return nil + case billingcustomeroverride.FieldInvoiceDraftPeriod: + m.ResetInvoiceDraftPeriod() + return nil + case billingcustomeroverride.FieldInvoiceDueAfter: + m.ResetInvoiceDueAfter() + return nil + case billingcustomeroverride.FieldInvoiceCollectionMethod: + m.ResetInvoiceCollectionMethod() + return nil + case billingcustomeroverride.FieldInvoiceProgressiveBilling: + m.ResetInvoiceProgressiveBilling() + return nil + case billingcustomeroverride.FieldInvoiceDefaultTaxConfig: + m.ResetInvoiceDefaultTaxConfig() + return nil + } + return fmt.Errorf("unknown BillingCustomerOverride field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BillingCustomerOverrideMutation) AddedEdges() []string { + edges := make([]string, 0, 3) + if m.customer != nil { + edges = append(edges, billingcustomeroverride.EdgeCustomer) + } + if m.billing_profile != nil { + edges = append(edges, billingcustomeroverride.EdgeBillingProfile) + } + if m.tax_code != nil { + edges = append(edges, billingcustomeroverride.EdgeTaxCode) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BillingCustomerOverrideMutation) AddedIDs(name string) []ent.Value { + switch name { + case billingcustomeroverride.EdgeCustomer: + if id := m.customer; id != nil { + return []ent.Value{*id} + } + case billingcustomeroverride.EdgeBillingProfile: + if id := m.billing_profile; id != nil { + return []ent.Value{*id} + } + case billingcustomeroverride.EdgeTaxCode: + if id := m.tax_code; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BillingCustomerOverrideMutation) RemovedEdges() []string { + edges := make([]string, 0, 3) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *BillingCustomerOverrideMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BillingCustomerOverrideMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) + if m.clearedcustomer { + edges = append(edges, billingcustomeroverride.EdgeCustomer) + } + if m.clearedbilling_profile { + edges = append(edges, billingcustomeroverride.EdgeBillingProfile) + } + if m.clearedtax_code { + edges = append(edges, billingcustomeroverride.EdgeTaxCode) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BillingCustomerOverrideMutation) EdgeCleared(name string) bool { + switch name { + case billingcustomeroverride.EdgeCustomer: + return m.clearedcustomer + case billingcustomeroverride.EdgeBillingProfile: + return m.clearedbilling_profile + case billingcustomeroverride.EdgeTaxCode: + return m.clearedtax_code + } + 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 *BillingCustomerOverrideMutation) ClearEdge(name string) error { + switch name { + case billingcustomeroverride.EdgeCustomer: + m.ClearCustomer() + return nil + case billingcustomeroverride.EdgeBillingProfile: + m.ClearBillingProfile() + return nil + case billingcustomeroverride.EdgeTaxCode: + m.ClearTaxCode() + return nil + } + return fmt.Errorf("unknown BillingCustomerOverride 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 *BillingCustomerOverrideMutation) ResetEdge(name string) error { + switch name { + case billingcustomeroverride.EdgeCustomer: + m.ResetCustomer() + return nil + case billingcustomeroverride.EdgeBillingProfile: + m.ResetBillingProfile() + return nil + case billingcustomeroverride.EdgeTaxCode: + m.ResetTaxCode() + return nil + } + return fmt.Errorf("unknown BillingCustomerOverride edge %s", name) +} + +// BillingInvoiceMutation represents an operation that mutates the BillingInvoice nodes in the graph. +type BillingInvoiceMutation struct { + config + op Op + typ string + id *string + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + supplier_address_country *models.CountryCode + supplier_address_postal_code *string + supplier_address_state *string + supplier_address_city *string + supplier_address_line1 *string + supplier_address_line2 *string + supplier_address_phone_number *string + customer_address_country *models.CountryCode + customer_address_postal_code *string + customer_address_state *string + customer_address_city *string + customer_address_line1 *string + customer_address_line2 *string + customer_address_phone_number *string + 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 + invoicing_app_external_id *string + payment_app_external_id *string + tax_app_external_id *string + supplier_name *string + supplier_tax_code *string + customer_key *string + customer_name *string + customer_usage_attribution **billing.VersionedCustomerUsageAttribution + number *string + _type *billing.InvoiceType + description *string + voided_at *time.Time + issued_at *time.Time + sent_to_customer_at *time.Time + draft_until *time.Time + quantity_snapshoted_at *time.Time + deletion_source *billing.ChangeSource + currency *currencyx.Code + due_at *time.Time + status *billing.StandardInvoiceStatus + status_details_cache *billing.StandardInvoiceStatusDetails + period_start *time.Time + period_end *time.Time + collection_at *time.Time + payment_processing_entered_at *time.Time + schema_level *int + addschema_level *int + clearedFields map[string]struct{} + source_billing_profile *string + clearedsource_billing_profile bool + billing_workflow_config *string + clearedbilling_workflow_config bool + billing_invoice_lines map[string]struct{} + removedbilling_invoice_lines map[string]struct{} + clearedbilling_invoice_lines bool + billing_invoice_detailed_lines map[string]struct{} + removedbilling_invoice_detailed_lines map[string]struct{} + clearedbilling_invoice_detailed_lines bool + billing_invoice_validation_issues map[string]struct{} + removedbilling_invoice_validation_issues map[string]struct{} + clearedbilling_invoice_validation_issues bool + charge_flat_fee_runs map[string]struct{} + removedcharge_flat_fee_runs map[string]struct{} + clearedcharge_flat_fee_runs bool + charge_usage_based_runs map[string]struct{} + removedcharge_usage_based_runs map[string]struct{} + clearedcharge_usage_based_runs bool + billing_invoice_customer *string + clearedbilling_invoice_customer bool + tax_app *string + clearedtax_app bool + invoicing_app *string + clearedinvoicing_app bool + payment_app *string + clearedpayment_app bool + done bool + oldValue func(context.Context) (*BillingInvoice, error) + predicates []predicate.BillingInvoice +} + +var _ ent.Mutation = (*BillingInvoiceMutation)(nil) + +// billinginvoiceOption allows management of the mutation configuration using functional options. +type billinginvoiceOption func(*BillingInvoiceMutation) + +// newBillingInvoiceMutation creates new mutation for the BillingInvoice entity. +func newBillingInvoiceMutation(c config, op Op, opts ...billinginvoiceOption) *BillingInvoiceMutation { + m := &BillingInvoiceMutation{ + config: c, + op: op, + typ: TypeBillingInvoice, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBillingInvoiceID sets the ID field of the mutation. +func withBillingInvoiceID(id string) billinginvoiceOption { + return func(m *BillingInvoiceMutation) { + var ( + err error + once sync.Once + value *BillingInvoice + ) + m.oldValue = func(ctx context.Context) (*BillingInvoice, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().BillingInvoice.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBillingInvoice sets the old BillingInvoice of the mutation. +func withBillingInvoice(node *BillingInvoice) billinginvoiceOption { + return func(m *BillingInvoiceMutation) { + m.oldValue = func(context.Context) (*BillingInvoice, 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 BillingInvoiceMutation) 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 BillingInvoiceMutation) 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 BillingInvoice entities. +func (m *BillingInvoiceMutation) 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 *BillingInvoiceMutation) 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 *BillingInvoiceMutation) 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().BillingInvoice.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 *BillingInvoiceMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *BillingInvoiceMutation) 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 BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) 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 *BillingInvoiceMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *BillingInvoiceMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *BillingInvoiceMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *BillingInvoiceMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[billinginvoice.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *BillingInvoiceMutation) MetadataCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *BillingInvoiceMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, billinginvoice.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *BillingInvoiceMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *BillingInvoiceMutation) 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 BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) 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 *BillingInvoiceMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *BillingInvoiceMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *BillingInvoiceMutation) 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 BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) 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 *BillingInvoiceMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *BillingInvoiceMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *BillingInvoiceMutation) 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 BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) 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 *BillingInvoiceMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[billinginvoice.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *BillingInvoiceMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *BillingInvoiceMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, billinginvoice.FieldDeletedAt) +} + +// SetSupplierAddressCountry sets the "supplier_address_country" field. +func (m *BillingInvoiceMutation) SetSupplierAddressCountry(mc models.CountryCode) { + m.supplier_address_country = &mc +} + +// SupplierAddressCountry returns the value of the "supplier_address_country" field in the mutation. +func (m *BillingInvoiceMutation) SupplierAddressCountry() (r models.CountryCode, exists bool) { + v := m.supplier_address_country + if v == nil { + return + } + return *v, true +} + +// OldSupplierAddressCountry returns the old "supplier_address_country" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldSupplierAddressCountry(ctx context.Context) (v *models.CountryCode, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSupplierAddressCountry is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSupplierAddressCountry requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSupplierAddressCountry: %w", err) + } + return oldValue.SupplierAddressCountry, nil +} + +// ClearSupplierAddressCountry clears the value of the "supplier_address_country" field. +func (m *BillingInvoiceMutation) ClearSupplierAddressCountry() { + m.supplier_address_country = nil + m.clearedFields[billinginvoice.FieldSupplierAddressCountry] = struct{}{} +} + +// SupplierAddressCountryCleared returns if the "supplier_address_country" field was cleared in this mutation. +func (m *BillingInvoiceMutation) SupplierAddressCountryCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldSupplierAddressCountry] + return ok +} + +// ResetSupplierAddressCountry resets all changes to the "supplier_address_country" field. +func (m *BillingInvoiceMutation) ResetSupplierAddressCountry() { + m.supplier_address_country = nil + delete(m.clearedFields, billinginvoice.FieldSupplierAddressCountry) +} + +// SetSupplierAddressPostalCode sets the "supplier_address_postal_code" field. +func (m *BillingInvoiceMutation) SetSupplierAddressPostalCode(s string) { + m.supplier_address_postal_code = &s +} + +// SupplierAddressPostalCode returns the value of the "supplier_address_postal_code" field in the mutation. +func (m *BillingInvoiceMutation) SupplierAddressPostalCode() (r string, exists bool) { + v := m.supplier_address_postal_code + if v == nil { + return + } + return *v, true +} + +// OldSupplierAddressPostalCode returns the old "supplier_address_postal_code" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldSupplierAddressPostalCode(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSupplierAddressPostalCode is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSupplierAddressPostalCode requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSupplierAddressPostalCode: %w", err) + } + return oldValue.SupplierAddressPostalCode, nil +} + +// ClearSupplierAddressPostalCode clears the value of the "supplier_address_postal_code" field. +func (m *BillingInvoiceMutation) ClearSupplierAddressPostalCode() { + m.supplier_address_postal_code = nil + m.clearedFields[billinginvoice.FieldSupplierAddressPostalCode] = struct{}{} +} + +// SupplierAddressPostalCodeCleared returns if the "supplier_address_postal_code" field was cleared in this mutation. +func (m *BillingInvoiceMutation) SupplierAddressPostalCodeCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldSupplierAddressPostalCode] + return ok +} + +// ResetSupplierAddressPostalCode resets all changes to the "supplier_address_postal_code" field. +func (m *BillingInvoiceMutation) ResetSupplierAddressPostalCode() { + m.supplier_address_postal_code = nil + delete(m.clearedFields, billinginvoice.FieldSupplierAddressPostalCode) +} + +// SetSupplierAddressState sets the "supplier_address_state" field. +func (m *BillingInvoiceMutation) SetSupplierAddressState(s string) { + m.supplier_address_state = &s +} + +// SupplierAddressState returns the value of the "supplier_address_state" field in the mutation. +func (m *BillingInvoiceMutation) SupplierAddressState() (r string, exists bool) { + v := m.supplier_address_state + if v == nil { + return + } + return *v, true +} + +// OldSupplierAddressState returns the old "supplier_address_state" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldSupplierAddressState(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSupplierAddressState is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSupplierAddressState requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSupplierAddressState: %w", err) + } + return oldValue.SupplierAddressState, nil +} + +// ClearSupplierAddressState clears the value of the "supplier_address_state" field. +func (m *BillingInvoiceMutation) ClearSupplierAddressState() { + m.supplier_address_state = nil + m.clearedFields[billinginvoice.FieldSupplierAddressState] = struct{}{} +} + +// SupplierAddressStateCleared returns if the "supplier_address_state" field was cleared in this mutation. +func (m *BillingInvoiceMutation) SupplierAddressStateCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldSupplierAddressState] + return ok +} + +// ResetSupplierAddressState resets all changes to the "supplier_address_state" field. +func (m *BillingInvoiceMutation) ResetSupplierAddressState() { + m.supplier_address_state = nil + delete(m.clearedFields, billinginvoice.FieldSupplierAddressState) +} + +// SetSupplierAddressCity sets the "supplier_address_city" field. +func (m *BillingInvoiceMutation) SetSupplierAddressCity(s string) { + m.supplier_address_city = &s +} + +// SupplierAddressCity returns the value of the "supplier_address_city" field in the mutation. +func (m *BillingInvoiceMutation) SupplierAddressCity() (r string, exists bool) { + v := m.supplier_address_city + if v == nil { + return + } + return *v, true +} + +// OldSupplierAddressCity returns the old "supplier_address_city" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldSupplierAddressCity(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSupplierAddressCity is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSupplierAddressCity requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSupplierAddressCity: %w", err) + } + return oldValue.SupplierAddressCity, nil +} + +// ClearSupplierAddressCity clears the value of the "supplier_address_city" field. +func (m *BillingInvoiceMutation) ClearSupplierAddressCity() { + m.supplier_address_city = nil + m.clearedFields[billinginvoice.FieldSupplierAddressCity] = struct{}{} +} + +// SupplierAddressCityCleared returns if the "supplier_address_city" field was cleared in this mutation. +func (m *BillingInvoiceMutation) SupplierAddressCityCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldSupplierAddressCity] + return ok +} + +// ResetSupplierAddressCity resets all changes to the "supplier_address_city" field. +func (m *BillingInvoiceMutation) ResetSupplierAddressCity() { + m.supplier_address_city = nil + delete(m.clearedFields, billinginvoice.FieldSupplierAddressCity) +} + +// SetSupplierAddressLine1 sets the "supplier_address_line1" field. +func (m *BillingInvoiceMutation) SetSupplierAddressLine1(s string) { + m.supplier_address_line1 = &s +} + +// SupplierAddressLine1 returns the value of the "supplier_address_line1" field in the mutation. +func (m *BillingInvoiceMutation) SupplierAddressLine1() (r string, exists bool) { + v := m.supplier_address_line1 + if v == nil { + return + } + return *v, true +} + +// OldSupplierAddressLine1 returns the old "supplier_address_line1" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldSupplierAddressLine1(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSupplierAddressLine1 is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSupplierAddressLine1 requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSupplierAddressLine1: %w", err) + } + return oldValue.SupplierAddressLine1, nil +} + +// ClearSupplierAddressLine1 clears the value of the "supplier_address_line1" field. +func (m *BillingInvoiceMutation) ClearSupplierAddressLine1() { + m.supplier_address_line1 = nil + m.clearedFields[billinginvoice.FieldSupplierAddressLine1] = struct{}{} +} + +// SupplierAddressLine1Cleared returns if the "supplier_address_line1" field was cleared in this mutation. +func (m *BillingInvoiceMutation) SupplierAddressLine1Cleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldSupplierAddressLine1] + return ok +} + +// ResetSupplierAddressLine1 resets all changes to the "supplier_address_line1" field. +func (m *BillingInvoiceMutation) ResetSupplierAddressLine1() { + m.supplier_address_line1 = nil + delete(m.clearedFields, billinginvoice.FieldSupplierAddressLine1) +} + +// SetSupplierAddressLine2 sets the "supplier_address_line2" field. +func (m *BillingInvoiceMutation) SetSupplierAddressLine2(s string) { + m.supplier_address_line2 = &s +} + +// SupplierAddressLine2 returns the value of the "supplier_address_line2" field in the mutation. +func (m *BillingInvoiceMutation) SupplierAddressLine2() (r string, exists bool) { + v := m.supplier_address_line2 + if v == nil { + return + } + return *v, true +} + +// OldSupplierAddressLine2 returns the old "supplier_address_line2" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldSupplierAddressLine2(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSupplierAddressLine2 is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSupplierAddressLine2 requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSupplierAddressLine2: %w", err) + } + return oldValue.SupplierAddressLine2, nil +} + +// ClearSupplierAddressLine2 clears the value of the "supplier_address_line2" field. +func (m *BillingInvoiceMutation) ClearSupplierAddressLine2() { + m.supplier_address_line2 = nil + m.clearedFields[billinginvoice.FieldSupplierAddressLine2] = struct{}{} +} + +// SupplierAddressLine2Cleared returns if the "supplier_address_line2" field was cleared in this mutation. +func (m *BillingInvoiceMutation) SupplierAddressLine2Cleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldSupplierAddressLine2] + return ok +} + +// ResetSupplierAddressLine2 resets all changes to the "supplier_address_line2" field. +func (m *BillingInvoiceMutation) ResetSupplierAddressLine2() { + m.supplier_address_line2 = nil + delete(m.clearedFields, billinginvoice.FieldSupplierAddressLine2) +} + +// SetSupplierAddressPhoneNumber sets the "supplier_address_phone_number" field. +func (m *BillingInvoiceMutation) SetSupplierAddressPhoneNumber(s string) { + m.supplier_address_phone_number = &s +} + +// SupplierAddressPhoneNumber returns the value of the "supplier_address_phone_number" field in the mutation. +func (m *BillingInvoiceMutation) SupplierAddressPhoneNumber() (r string, exists bool) { + v := m.supplier_address_phone_number + if v == nil { + return + } + return *v, true +} + +// OldSupplierAddressPhoneNumber returns the old "supplier_address_phone_number" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldSupplierAddressPhoneNumber(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSupplierAddressPhoneNumber is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSupplierAddressPhoneNumber requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSupplierAddressPhoneNumber: %w", err) + } + return oldValue.SupplierAddressPhoneNumber, nil +} + +// ClearSupplierAddressPhoneNumber clears the value of the "supplier_address_phone_number" field. +func (m *BillingInvoiceMutation) ClearSupplierAddressPhoneNumber() { + m.supplier_address_phone_number = nil + m.clearedFields[billinginvoice.FieldSupplierAddressPhoneNumber] = struct{}{} +} + +// SupplierAddressPhoneNumberCleared returns if the "supplier_address_phone_number" field was cleared in this mutation. +func (m *BillingInvoiceMutation) SupplierAddressPhoneNumberCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldSupplierAddressPhoneNumber] + return ok +} + +// ResetSupplierAddressPhoneNumber resets all changes to the "supplier_address_phone_number" field. +func (m *BillingInvoiceMutation) ResetSupplierAddressPhoneNumber() { + m.supplier_address_phone_number = nil + delete(m.clearedFields, billinginvoice.FieldSupplierAddressPhoneNumber) +} + +// SetCustomerAddressCountry sets the "customer_address_country" field. +func (m *BillingInvoiceMutation) SetCustomerAddressCountry(mc models.CountryCode) { + m.customer_address_country = &mc +} + +// CustomerAddressCountry returns the value of the "customer_address_country" field in the mutation. +func (m *BillingInvoiceMutation) CustomerAddressCountry() (r models.CountryCode, exists bool) { + v := m.customer_address_country + if v == nil { + return + } + return *v, true +} + +// OldCustomerAddressCountry returns the old "customer_address_country" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldCustomerAddressCountry(ctx context.Context) (v *models.CountryCode, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerAddressCountry is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerAddressCountry requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerAddressCountry: %w", err) + } + return oldValue.CustomerAddressCountry, nil +} + +// ClearCustomerAddressCountry clears the value of the "customer_address_country" field. +func (m *BillingInvoiceMutation) ClearCustomerAddressCountry() { + m.customer_address_country = nil + m.clearedFields[billinginvoice.FieldCustomerAddressCountry] = struct{}{} +} + +// CustomerAddressCountryCleared returns if the "customer_address_country" field was cleared in this mutation. +func (m *BillingInvoiceMutation) CustomerAddressCountryCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldCustomerAddressCountry] + return ok +} + +// ResetCustomerAddressCountry resets all changes to the "customer_address_country" field. +func (m *BillingInvoiceMutation) ResetCustomerAddressCountry() { + m.customer_address_country = nil + delete(m.clearedFields, billinginvoice.FieldCustomerAddressCountry) +} + +// SetCustomerAddressPostalCode sets the "customer_address_postal_code" field. +func (m *BillingInvoiceMutation) SetCustomerAddressPostalCode(s string) { + m.customer_address_postal_code = &s +} + +// CustomerAddressPostalCode returns the value of the "customer_address_postal_code" field in the mutation. +func (m *BillingInvoiceMutation) CustomerAddressPostalCode() (r string, exists bool) { + v := m.customer_address_postal_code + if v == nil { + return + } + return *v, true +} + +// OldCustomerAddressPostalCode returns the old "customer_address_postal_code" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldCustomerAddressPostalCode(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerAddressPostalCode is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerAddressPostalCode requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerAddressPostalCode: %w", err) + } + return oldValue.CustomerAddressPostalCode, nil +} + +// ClearCustomerAddressPostalCode clears the value of the "customer_address_postal_code" field. +func (m *BillingInvoiceMutation) ClearCustomerAddressPostalCode() { + m.customer_address_postal_code = nil + m.clearedFields[billinginvoice.FieldCustomerAddressPostalCode] = struct{}{} +} + +// CustomerAddressPostalCodeCleared returns if the "customer_address_postal_code" field was cleared in this mutation. +func (m *BillingInvoiceMutation) CustomerAddressPostalCodeCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldCustomerAddressPostalCode] + return ok +} + +// ResetCustomerAddressPostalCode resets all changes to the "customer_address_postal_code" field. +func (m *BillingInvoiceMutation) ResetCustomerAddressPostalCode() { + m.customer_address_postal_code = nil + delete(m.clearedFields, billinginvoice.FieldCustomerAddressPostalCode) +} + +// SetCustomerAddressState sets the "customer_address_state" field. +func (m *BillingInvoiceMutation) SetCustomerAddressState(s string) { + m.customer_address_state = &s +} + +// CustomerAddressState returns the value of the "customer_address_state" field in the mutation. +func (m *BillingInvoiceMutation) CustomerAddressState() (r string, exists bool) { + v := m.customer_address_state + if v == nil { + return + } + return *v, true +} + +// OldCustomerAddressState returns the old "customer_address_state" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldCustomerAddressState(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerAddressState is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerAddressState requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerAddressState: %w", err) + } + return oldValue.CustomerAddressState, nil +} + +// ClearCustomerAddressState clears the value of the "customer_address_state" field. +func (m *BillingInvoiceMutation) ClearCustomerAddressState() { + m.customer_address_state = nil + m.clearedFields[billinginvoice.FieldCustomerAddressState] = struct{}{} +} + +// CustomerAddressStateCleared returns if the "customer_address_state" field was cleared in this mutation. +func (m *BillingInvoiceMutation) CustomerAddressStateCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldCustomerAddressState] + return ok +} + +// ResetCustomerAddressState resets all changes to the "customer_address_state" field. +func (m *BillingInvoiceMutation) ResetCustomerAddressState() { + m.customer_address_state = nil + delete(m.clearedFields, billinginvoice.FieldCustomerAddressState) +} + +// SetCustomerAddressCity sets the "customer_address_city" field. +func (m *BillingInvoiceMutation) SetCustomerAddressCity(s string) { + m.customer_address_city = &s +} + +// CustomerAddressCity returns the value of the "customer_address_city" field in the mutation. +func (m *BillingInvoiceMutation) CustomerAddressCity() (r string, exists bool) { + v := m.customer_address_city + if v == nil { + return + } + return *v, true +} + +// OldCustomerAddressCity returns the old "customer_address_city" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldCustomerAddressCity(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerAddressCity is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerAddressCity requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerAddressCity: %w", err) + } + return oldValue.CustomerAddressCity, nil +} + +// ClearCustomerAddressCity clears the value of the "customer_address_city" field. +func (m *BillingInvoiceMutation) ClearCustomerAddressCity() { + m.customer_address_city = nil + m.clearedFields[billinginvoice.FieldCustomerAddressCity] = struct{}{} +} + +// CustomerAddressCityCleared returns if the "customer_address_city" field was cleared in this mutation. +func (m *BillingInvoiceMutation) CustomerAddressCityCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldCustomerAddressCity] + return ok +} + +// ResetCustomerAddressCity resets all changes to the "customer_address_city" field. +func (m *BillingInvoiceMutation) ResetCustomerAddressCity() { + m.customer_address_city = nil + delete(m.clearedFields, billinginvoice.FieldCustomerAddressCity) +} + +// SetCustomerAddressLine1 sets the "customer_address_line1" field. +func (m *BillingInvoiceMutation) SetCustomerAddressLine1(s string) { + m.customer_address_line1 = &s +} + +// CustomerAddressLine1 returns the value of the "customer_address_line1" field in the mutation. +func (m *BillingInvoiceMutation) CustomerAddressLine1() (r string, exists bool) { + v := m.customer_address_line1 + if v == nil { + return + } + return *v, true +} + +// OldCustomerAddressLine1 returns the old "customer_address_line1" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldCustomerAddressLine1(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerAddressLine1 is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerAddressLine1 requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerAddressLine1: %w", err) + } + return oldValue.CustomerAddressLine1, nil +} + +// ClearCustomerAddressLine1 clears the value of the "customer_address_line1" field. +func (m *BillingInvoiceMutation) ClearCustomerAddressLine1() { + m.customer_address_line1 = nil + m.clearedFields[billinginvoice.FieldCustomerAddressLine1] = struct{}{} +} + +// CustomerAddressLine1Cleared returns if the "customer_address_line1" field was cleared in this mutation. +func (m *BillingInvoiceMutation) CustomerAddressLine1Cleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldCustomerAddressLine1] + return ok +} + +// ResetCustomerAddressLine1 resets all changes to the "customer_address_line1" field. +func (m *BillingInvoiceMutation) ResetCustomerAddressLine1() { + m.customer_address_line1 = nil + delete(m.clearedFields, billinginvoice.FieldCustomerAddressLine1) +} + +// SetCustomerAddressLine2 sets the "customer_address_line2" field. +func (m *BillingInvoiceMutation) SetCustomerAddressLine2(s string) { + m.customer_address_line2 = &s +} + +// CustomerAddressLine2 returns the value of the "customer_address_line2" field in the mutation. +func (m *BillingInvoiceMutation) CustomerAddressLine2() (r string, exists bool) { + v := m.customer_address_line2 + if v == nil { + return + } + return *v, true +} + +// OldCustomerAddressLine2 returns the old "customer_address_line2" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldCustomerAddressLine2(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerAddressLine2 is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerAddressLine2 requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerAddressLine2: %w", err) + } + return oldValue.CustomerAddressLine2, nil +} + +// ClearCustomerAddressLine2 clears the value of the "customer_address_line2" field. +func (m *BillingInvoiceMutation) ClearCustomerAddressLine2() { + m.customer_address_line2 = nil + m.clearedFields[billinginvoice.FieldCustomerAddressLine2] = struct{}{} +} + +// CustomerAddressLine2Cleared returns if the "customer_address_line2" field was cleared in this mutation. +func (m *BillingInvoiceMutation) CustomerAddressLine2Cleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldCustomerAddressLine2] + return ok +} + +// ResetCustomerAddressLine2 resets all changes to the "customer_address_line2" field. +func (m *BillingInvoiceMutation) ResetCustomerAddressLine2() { + m.customer_address_line2 = nil + delete(m.clearedFields, billinginvoice.FieldCustomerAddressLine2) +} + +// SetCustomerAddressPhoneNumber sets the "customer_address_phone_number" field. +func (m *BillingInvoiceMutation) SetCustomerAddressPhoneNumber(s string) { + m.customer_address_phone_number = &s +} + +// CustomerAddressPhoneNumber returns the value of the "customer_address_phone_number" field in the mutation. +func (m *BillingInvoiceMutation) CustomerAddressPhoneNumber() (r string, exists bool) { + v := m.customer_address_phone_number + if v == nil { + return + } + return *v, true +} + +// OldCustomerAddressPhoneNumber returns the old "customer_address_phone_number" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldCustomerAddressPhoneNumber(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerAddressPhoneNumber is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerAddressPhoneNumber requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerAddressPhoneNumber: %w", err) + } + return oldValue.CustomerAddressPhoneNumber, nil +} + +// ClearCustomerAddressPhoneNumber clears the value of the "customer_address_phone_number" field. +func (m *BillingInvoiceMutation) ClearCustomerAddressPhoneNumber() { + m.customer_address_phone_number = nil + m.clearedFields[billinginvoice.FieldCustomerAddressPhoneNumber] = struct{}{} +} + +// CustomerAddressPhoneNumberCleared returns if the "customer_address_phone_number" field was cleared in this mutation. +func (m *BillingInvoiceMutation) CustomerAddressPhoneNumberCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldCustomerAddressPhoneNumber] + return ok +} + +// ResetCustomerAddressPhoneNumber resets all changes to the "customer_address_phone_number" field. +func (m *BillingInvoiceMutation) ResetCustomerAddressPhoneNumber() { + m.customer_address_phone_number = nil + delete(m.clearedFields, billinginvoice.FieldCustomerAddressPhoneNumber) +} + +// SetAmount sets the "amount" field. +func (m *BillingInvoiceMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *BillingInvoiceMutation) 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 BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) 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 *BillingInvoiceMutation) ResetAmount() { + m.amount = nil +} + +// SetTaxesTotal sets the "taxes_total" field. +func (m *BillingInvoiceMutation) SetTaxesTotal(a alpacadecimal.Decimal) { + m.taxes_total = &a +} + +// TaxesTotal returns the value of the "taxes_total" field in the mutation. +func (m *BillingInvoiceMutation) 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 BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) 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 *BillingInvoiceMutation) ResetTaxesTotal() { + m.taxes_total = nil +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (m *BillingInvoiceMutation) SetTaxesInclusiveTotal(a alpacadecimal.Decimal) { + m.taxes_inclusive_total = &a +} + +// TaxesInclusiveTotal returns the value of the "taxes_inclusive_total" field in the mutation. +func (m *BillingInvoiceMutation) 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 BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) 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 *BillingInvoiceMutation) ResetTaxesInclusiveTotal() { + m.taxes_inclusive_total = nil +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (m *BillingInvoiceMutation) SetTaxesExclusiveTotal(a alpacadecimal.Decimal) { + m.taxes_exclusive_total = &a +} + +// TaxesExclusiveTotal returns the value of the "taxes_exclusive_total" field in the mutation. +func (m *BillingInvoiceMutation) 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 BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) 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 *BillingInvoiceMutation) ResetTaxesExclusiveTotal() { + m.taxes_exclusive_total = nil +} + +// SetChargesTotal sets the "charges_total" field. +func (m *BillingInvoiceMutation) SetChargesTotal(a alpacadecimal.Decimal) { + m.charges_total = &a +} + +// ChargesTotal returns the value of the "charges_total" field in the mutation. +func (m *BillingInvoiceMutation) 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 BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) 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 *BillingInvoiceMutation) ResetChargesTotal() { + m.charges_total = nil +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (m *BillingInvoiceMutation) SetDiscountsTotal(a alpacadecimal.Decimal) { + m.discounts_total = &a +} + +// DiscountsTotal returns the value of the "discounts_total" field in the mutation. +func (m *BillingInvoiceMutation) 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 BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) 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 *BillingInvoiceMutation) ResetDiscountsTotal() { + m.discounts_total = nil +} + +// SetCreditsTotal sets the "credits_total" field. +func (m *BillingInvoiceMutation) SetCreditsTotal(a alpacadecimal.Decimal) { + m.credits_total = &a +} + +// CreditsTotal returns the value of the "credits_total" field in the mutation. +func (m *BillingInvoiceMutation) 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 BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) 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 *BillingInvoiceMutation) ResetCreditsTotal() { + m.credits_total = nil +} + +// SetTotal sets the "total" field. +func (m *BillingInvoiceMutation) SetTotal(a alpacadecimal.Decimal) { + m.total = &a +} + +// Total returns the value of the "total" field in the mutation. +func (m *BillingInvoiceMutation) 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 BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) 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 *BillingInvoiceMutation) ResetTotal() { + m.total = nil +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (m *BillingInvoiceMutation) SetInvoicingAppExternalID(s string) { + m.invoicing_app_external_id = &s +} + +// InvoicingAppExternalID returns the value of the "invoicing_app_external_id" field in the mutation. +func (m *BillingInvoiceMutation) InvoicingAppExternalID() (r string, exists bool) { + v := m.invoicing_app_external_id + if v == nil { + return + } + return *v, true +} + +// OldInvoicingAppExternalID returns the old "invoicing_app_external_id" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldInvoicingAppExternalID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoicingAppExternalID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoicingAppExternalID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoicingAppExternalID: %w", err) + } + return oldValue.InvoicingAppExternalID, nil +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (m *BillingInvoiceMutation) ClearInvoicingAppExternalID() { + m.invoicing_app_external_id = nil + m.clearedFields[billinginvoice.FieldInvoicingAppExternalID] = struct{}{} +} + +// InvoicingAppExternalIDCleared returns if the "invoicing_app_external_id" field was cleared in this mutation. +func (m *BillingInvoiceMutation) InvoicingAppExternalIDCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldInvoicingAppExternalID] + return ok +} + +// ResetInvoicingAppExternalID resets all changes to the "invoicing_app_external_id" field. +func (m *BillingInvoiceMutation) ResetInvoicingAppExternalID() { + m.invoicing_app_external_id = nil + delete(m.clearedFields, billinginvoice.FieldInvoicingAppExternalID) +} + +// SetPaymentAppExternalID sets the "payment_app_external_id" field. +func (m *BillingInvoiceMutation) SetPaymentAppExternalID(s string) { + m.payment_app_external_id = &s +} + +// PaymentAppExternalID returns the value of the "payment_app_external_id" field in the mutation. +func (m *BillingInvoiceMutation) PaymentAppExternalID() (r string, exists bool) { + v := m.payment_app_external_id + if v == nil { + return + } + return *v, true +} + +// OldPaymentAppExternalID returns the old "payment_app_external_id" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldPaymentAppExternalID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPaymentAppExternalID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPaymentAppExternalID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPaymentAppExternalID: %w", err) + } + return oldValue.PaymentAppExternalID, nil +} + +// ClearPaymentAppExternalID clears the value of the "payment_app_external_id" field. +func (m *BillingInvoiceMutation) ClearPaymentAppExternalID() { + m.payment_app_external_id = nil + m.clearedFields[billinginvoice.FieldPaymentAppExternalID] = struct{}{} +} + +// PaymentAppExternalIDCleared returns if the "payment_app_external_id" field was cleared in this mutation. +func (m *BillingInvoiceMutation) PaymentAppExternalIDCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldPaymentAppExternalID] + return ok +} + +// ResetPaymentAppExternalID resets all changes to the "payment_app_external_id" field. +func (m *BillingInvoiceMutation) ResetPaymentAppExternalID() { + m.payment_app_external_id = nil + delete(m.clearedFields, billinginvoice.FieldPaymentAppExternalID) +} + +// SetTaxAppExternalID sets the "tax_app_external_id" field. +func (m *BillingInvoiceMutation) SetTaxAppExternalID(s string) { + m.tax_app_external_id = &s +} + +// TaxAppExternalID returns the value of the "tax_app_external_id" field in the mutation. +func (m *BillingInvoiceMutation) TaxAppExternalID() (r string, exists bool) { + v := m.tax_app_external_id + if v == nil { + return + } + return *v, true +} + +// OldTaxAppExternalID returns the old "tax_app_external_id" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldTaxAppExternalID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxAppExternalID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxAppExternalID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxAppExternalID: %w", err) + } + return oldValue.TaxAppExternalID, nil +} + +// ClearTaxAppExternalID clears the value of the "tax_app_external_id" field. +func (m *BillingInvoiceMutation) ClearTaxAppExternalID() { + m.tax_app_external_id = nil + m.clearedFields[billinginvoice.FieldTaxAppExternalID] = struct{}{} +} + +// TaxAppExternalIDCleared returns if the "tax_app_external_id" field was cleared in this mutation. +func (m *BillingInvoiceMutation) TaxAppExternalIDCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldTaxAppExternalID] + return ok +} + +// ResetTaxAppExternalID resets all changes to the "tax_app_external_id" field. +func (m *BillingInvoiceMutation) ResetTaxAppExternalID() { + m.tax_app_external_id = nil + delete(m.clearedFields, billinginvoice.FieldTaxAppExternalID) +} + +// SetSupplierName sets the "supplier_name" field. +func (m *BillingInvoiceMutation) SetSupplierName(s string) { + m.supplier_name = &s +} + +// SupplierName returns the value of the "supplier_name" field in the mutation. +func (m *BillingInvoiceMutation) SupplierName() (r string, exists bool) { + v := m.supplier_name + if v == nil { + return + } + return *v, true +} + +// OldSupplierName returns the old "supplier_name" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldSupplierName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSupplierName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSupplierName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSupplierName: %w", err) + } + return oldValue.SupplierName, nil +} + +// ResetSupplierName resets all changes to the "supplier_name" field. +func (m *BillingInvoiceMutation) ResetSupplierName() { + m.supplier_name = nil +} + +// SetSupplierTaxCode sets the "supplier_tax_code" field. +func (m *BillingInvoiceMutation) SetSupplierTaxCode(s string) { + m.supplier_tax_code = &s +} + +// SupplierTaxCode returns the value of the "supplier_tax_code" field in the mutation. +func (m *BillingInvoiceMutation) SupplierTaxCode() (r string, exists bool) { + v := m.supplier_tax_code + if v == nil { + return + } + return *v, true +} + +// OldSupplierTaxCode returns the old "supplier_tax_code" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldSupplierTaxCode(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSupplierTaxCode is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSupplierTaxCode requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSupplierTaxCode: %w", err) + } + return oldValue.SupplierTaxCode, nil +} + +// ClearSupplierTaxCode clears the value of the "supplier_tax_code" field. +func (m *BillingInvoiceMutation) ClearSupplierTaxCode() { + m.supplier_tax_code = nil + m.clearedFields[billinginvoice.FieldSupplierTaxCode] = struct{}{} +} + +// SupplierTaxCodeCleared returns if the "supplier_tax_code" field was cleared in this mutation. +func (m *BillingInvoiceMutation) SupplierTaxCodeCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldSupplierTaxCode] + return ok +} + +// ResetSupplierTaxCode resets all changes to the "supplier_tax_code" field. +func (m *BillingInvoiceMutation) ResetSupplierTaxCode() { + m.supplier_tax_code = nil + delete(m.clearedFields, billinginvoice.FieldSupplierTaxCode) +} + +// SetCustomerKey sets the "customer_key" field. +func (m *BillingInvoiceMutation) SetCustomerKey(s string) { + m.customer_key = &s +} + +// CustomerKey returns the value of the "customer_key" field in the mutation. +func (m *BillingInvoiceMutation) CustomerKey() (r string, exists bool) { + v := m.customer_key + if v == nil { + return + } + return *v, true +} + +// OldCustomerKey returns the old "customer_key" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldCustomerKey(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerKey: %w", err) + } + return oldValue.CustomerKey, nil +} + +// ClearCustomerKey clears the value of the "customer_key" field. +func (m *BillingInvoiceMutation) ClearCustomerKey() { + m.customer_key = nil + m.clearedFields[billinginvoice.FieldCustomerKey] = struct{}{} +} + +// CustomerKeyCleared returns if the "customer_key" field was cleared in this mutation. +func (m *BillingInvoiceMutation) CustomerKeyCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldCustomerKey] + return ok +} + +// ResetCustomerKey resets all changes to the "customer_key" field. +func (m *BillingInvoiceMutation) ResetCustomerKey() { + m.customer_key = nil + delete(m.clearedFields, billinginvoice.FieldCustomerKey) +} + +// SetCustomerName sets the "customer_name" field. +func (m *BillingInvoiceMutation) SetCustomerName(s string) { + m.customer_name = &s +} + +// CustomerName returns the value of the "customer_name" field in the mutation. +func (m *BillingInvoiceMutation) CustomerName() (r string, exists bool) { + v := m.customer_name + if v == nil { + return + } + return *v, true +} + +// OldCustomerName returns the old "customer_name" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldCustomerName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerName: %w", err) + } + return oldValue.CustomerName, nil +} + +// ResetCustomerName resets all changes to the "customer_name" field. +func (m *BillingInvoiceMutation) ResetCustomerName() { + m.customer_name = nil +} + +// SetCustomerUsageAttribution sets the "customer_usage_attribution" field. +func (m *BillingInvoiceMutation) SetCustomerUsageAttribution(bcua *billing.VersionedCustomerUsageAttribution) { + m.customer_usage_attribution = &bcua +} + +// CustomerUsageAttribution returns the value of the "customer_usage_attribution" field in the mutation. +func (m *BillingInvoiceMutation) CustomerUsageAttribution() (r *billing.VersionedCustomerUsageAttribution, exists bool) { + v := m.customer_usage_attribution + if v == nil { + return + } + return *v, true +} + +// OldCustomerUsageAttribution returns the old "customer_usage_attribution" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldCustomerUsageAttribution(ctx context.Context) (v *billing.VersionedCustomerUsageAttribution, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerUsageAttribution is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerUsageAttribution requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerUsageAttribution: %w", err) + } + return oldValue.CustomerUsageAttribution, nil +} + +// ClearCustomerUsageAttribution clears the value of the "customer_usage_attribution" field. +func (m *BillingInvoiceMutation) ClearCustomerUsageAttribution() { + m.customer_usage_attribution = nil + m.clearedFields[billinginvoice.FieldCustomerUsageAttribution] = struct{}{} +} + +// CustomerUsageAttributionCleared returns if the "customer_usage_attribution" field was cleared in this mutation. +func (m *BillingInvoiceMutation) CustomerUsageAttributionCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldCustomerUsageAttribution] + return ok +} + +// ResetCustomerUsageAttribution resets all changes to the "customer_usage_attribution" field. +func (m *BillingInvoiceMutation) ResetCustomerUsageAttribution() { + m.customer_usage_attribution = nil + delete(m.clearedFields, billinginvoice.FieldCustomerUsageAttribution) +} + +// SetNumber sets the "number" field. +func (m *BillingInvoiceMutation) SetNumber(s string) { + m.number = &s +} + +// Number returns the value of the "number" field in the mutation. +func (m *BillingInvoiceMutation) Number() (r string, exists bool) { + v := m.number + if v == nil { + return + } + return *v, true +} + +// OldNumber returns the old "number" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldNumber(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNumber is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNumber requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNumber: %w", err) + } + return oldValue.Number, nil +} + +// ResetNumber resets all changes to the "number" field. +func (m *BillingInvoiceMutation) ResetNumber() { + m.number = nil +} + +// SetType sets the "type" field. +func (m *BillingInvoiceMutation) SetType(bt billing.InvoiceType) { + m._type = &bt +} + +// GetType returns the value of the "type" field in the mutation. +func (m *BillingInvoiceMutation) GetType() (r billing.InvoiceType, exists bool) { + v := m._type + if v == nil { + return + } + return *v, true +} + +// OldType returns the old "type" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldType(ctx context.Context) (v billing.InvoiceType, 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 *BillingInvoiceMutation) ResetType() { + m._type = nil +} + +// SetDescription sets the "description" field. +func (m *BillingInvoiceMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *BillingInvoiceMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *BillingInvoiceMutation) ClearDescription() { + m.description = nil + m.clearedFields[billinginvoice.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *BillingInvoiceMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *BillingInvoiceMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, billinginvoice.FieldDescription) +} + +// SetCustomerID sets the "customer_id" field. +func (m *BillingInvoiceMutation) SetCustomerID(s string) { + m.billing_invoice_customer = &s +} + +// CustomerID returns the value of the "customer_id" field in the mutation. +func (m *BillingInvoiceMutation) CustomerID() (r string, exists bool) { + v := m.billing_invoice_customer + if v == nil { + return + } + return *v, true +} + +// OldCustomerID returns the old "customer_id" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldCustomerID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerID: %w", err) + } + return oldValue.CustomerID, nil +} + +// ResetCustomerID resets all changes to the "customer_id" field. +func (m *BillingInvoiceMutation) ResetCustomerID() { + m.billing_invoice_customer = nil +} + +// SetSourceBillingProfileID sets the "source_billing_profile_id" field. +func (m *BillingInvoiceMutation) SetSourceBillingProfileID(s string) { + m.source_billing_profile = &s +} + +// SourceBillingProfileID returns the value of the "source_billing_profile_id" field in the mutation. +func (m *BillingInvoiceMutation) SourceBillingProfileID() (r string, exists bool) { + v := m.source_billing_profile + if v == nil { + return + } + return *v, true +} + +// OldSourceBillingProfileID returns the old "source_billing_profile_id" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldSourceBillingProfileID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSourceBillingProfileID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSourceBillingProfileID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSourceBillingProfileID: %w", err) + } + return oldValue.SourceBillingProfileID, nil +} + +// ResetSourceBillingProfileID resets all changes to the "source_billing_profile_id" field. +func (m *BillingInvoiceMutation) ResetSourceBillingProfileID() { + m.source_billing_profile = nil +} + +// SetVoidedAt sets the "voided_at" field. +func (m *BillingInvoiceMutation) SetVoidedAt(t time.Time) { + m.voided_at = &t +} + +// VoidedAt returns the value of the "voided_at" field in the mutation. +func (m *BillingInvoiceMutation) VoidedAt() (r time.Time, exists bool) { + v := m.voided_at + if v == nil { + return + } + return *v, true +} + +// OldVoidedAt returns the old "voided_at" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldVoidedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldVoidedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldVoidedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldVoidedAt: %w", err) + } + return oldValue.VoidedAt, nil +} + +// ClearVoidedAt clears the value of the "voided_at" field. +func (m *BillingInvoiceMutation) ClearVoidedAt() { + m.voided_at = nil + m.clearedFields[billinginvoice.FieldVoidedAt] = struct{}{} +} + +// VoidedAtCleared returns if the "voided_at" field was cleared in this mutation. +func (m *BillingInvoiceMutation) VoidedAtCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldVoidedAt] + return ok +} + +// ResetVoidedAt resets all changes to the "voided_at" field. +func (m *BillingInvoiceMutation) ResetVoidedAt() { + m.voided_at = nil + delete(m.clearedFields, billinginvoice.FieldVoidedAt) +} + +// SetIssuedAt sets the "issued_at" field. +func (m *BillingInvoiceMutation) SetIssuedAt(t time.Time) { + m.issued_at = &t +} + +// IssuedAt returns the value of the "issued_at" field in the mutation. +func (m *BillingInvoiceMutation) IssuedAt() (r time.Time, exists bool) { + v := m.issued_at + if v == nil { + return + } + return *v, true +} + +// OldIssuedAt returns the old "issued_at" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldIssuedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIssuedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIssuedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIssuedAt: %w", err) + } + return oldValue.IssuedAt, nil +} + +// ClearIssuedAt clears the value of the "issued_at" field. +func (m *BillingInvoiceMutation) ClearIssuedAt() { + m.issued_at = nil + m.clearedFields[billinginvoice.FieldIssuedAt] = struct{}{} +} + +// IssuedAtCleared returns if the "issued_at" field was cleared in this mutation. +func (m *BillingInvoiceMutation) IssuedAtCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldIssuedAt] + return ok +} + +// ResetIssuedAt resets all changes to the "issued_at" field. +func (m *BillingInvoiceMutation) ResetIssuedAt() { + m.issued_at = nil + delete(m.clearedFields, billinginvoice.FieldIssuedAt) +} + +// SetSentToCustomerAt sets the "sent_to_customer_at" field. +func (m *BillingInvoiceMutation) SetSentToCustomerAt(t time.Time) { + m.sent_to_customer_at = &t +} + +// SentToCustomerAt returns the value of the "sent_to_customer_at" field in the mutation. +func (m *BillingInvoiceMutation) SentToCustomerAt() (r time.Time, exists bool) { + v := m.sent_to_customer_at + if v == nil { + return + } + return *v, true +} + +// OldSentToCustomerAt returns the old "sent_to_customer_at" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldSentToCustomerAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSentToCustomerAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSentToCustomerAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSentToCustomerAt: %w", err) + } + return oldValue.SentToCustomerAt, nil +} + +// ClearSentToCustomerAt clears the value of the "sent_to_customer_at" field. +func (m *BillingInvoiceMutation) ClearSentToCustomerAt() { + m.sent_to_customer_at = nil + m.clearedFields[billinginvoice.FieldSentToCustomerAt] = struct{}{} +} + +// SentToCustomerAtCleared returns if the "sent_to_customer_at" field was cleared in this mutation. +func (m *BillingInvoiceMutation) SentToCustomerAtCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldSentToCustomerAt] + return ok +} + +// ResetSentToCustomerAt resets all changes to the "sent_to_customer_at" field. +func (m *BillingInvoiceMutation) ResetSentToCustomerAt() { + m.sent_to_customer_at = nil + delete(m.clearedFields, billinginvoice.FieldSentToCustomerAt) +} + +// SetDraftUntil sets the "draft_until" field. +func (m *BillingInvoiceMutation) SetDraftUntil(t time.Time) { + m.draft_until = &t +} + +// DraftUntil returns the value of the "draft_until" field in the mutation. +func (m *BillingInvoiceMutation) DraftUntil() (r time.Time, exists bool) { + v := m.draft_until + if v == nil { + return + } + return *v, true +} + +// OldDraftUntil returns the old "draft_until" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldDraftUntil(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDraftUntil is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDraftUntil requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDraftUntil: %w", err) + } + return oldValue.DraftUntil, nil +} + +// ClearDraftUntil clears the value of the "draft_until" field. +func (m *BillingInvoiceMutation) ClearDraftUntil() { + m.draft_until = nil + m.clearedFields[billinginvoice.FieldDraftUntil] = struct{}{} +} + +// DraftUntilCleared returns if the "draft_until" field was cleared in this mutation. +func (m *BillingInvoiceMutation) DraftUntilCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldDraftUntil] + return ok +} + +// ResetDraftUntil resets all changes to the "draft_until" field. +func (m *BillingInvoiceMutation) ResetDraftUntil() { + m.draft_until = nil + delete(m.clearedFields, billinginvoice.FieldDraftUntil) +} + +// SetQuantitySnapshotedAt sets the "quantity_snapshoted_at" field. +func (m *BillingInvoiceMutation) SetQuantitySnapshotedAt(t time.Time) { + m.quantity_snapshoted_at = &t +} + +// QuantitySnapshotedAt returns the value of the "quantity_snapshoted_at" field in the mutation. +func (m *BillingInvoiceMutation) QuantitySnapshotedAt() (r time.Time, exists bool) { + v := m.quantity_snapshoted_at + if v == nil { + return + } + return *v, true +} + +// OldQuantitySnapshotedAt returns the old "quantity_snapshoted_at" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldQuantitySnapshotedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldQuantitySnapshotedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldQuantitySnapshotedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldQuantitySnapshotedAt: %w", err) + } + return oldValue.QuantitySnapshotedAt, nil +} + +// ClearQuantitySnapshotedAt clears the value of the "quantity_snapshoted_at" field. +func (m *BillingInvoiceMutation) ClearQuantitySnapshotedAt() { + m.quantity_snapshoted_at = nil + m.clearedFields[billinginvoice.FieldQuantitySnapshotedAt] = struct{}{} +} + +// QuantitySnapshotedAtCleared returns if the "quantity_snapshoted_at" field was cleared in this mutation. +func (m *BillingInvoiceMutation) QuantitySnapshotedAtCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldQuantitySnapshotedAt] + return ok +} + +// ResetQuantitySnapshotedAt resets all changes to the "quantity_snapshoted_at" field. +func (m *BillingInvoiceMutation) ResetQuantitySnapshotedAt() { + m.quantity_snapshoted_at = nil + delete(m.clearedFields, billinginvoice.FieldQuantitySnapshotedAt) +} + +// SetDeletionSource sets the "deletion_source" field. +func (m *BillingInvoiceMutation) SetDeletionSource(bs billing.ChangeSource) { + m.deletion_source = &bs +} + +// DeletionSource returns the value of the "deletion_source" field in the mutation. +func (m *BillingInvoiceMutation) DeletionSource() (r billing.ChangeSource, exists bool) { + v := m.deletion_source + if v == nil { + return + } + return *v, true +} + +// OldDeletionSource returns the old "deletion_source" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldDeletionSource(ctx context.Context) (v *billing.ChangeSource, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDeletionSource is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDeletionSource requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeletionSource: %w", err) + } + return oldValue.DeletionSource, nil +} + +// ClearDeletionSource clears the value of the "deletion_source" field. +func (m *BillingInvoiceMutation) ClearDeletionSource() { + m.deletion_source = nil + m.clearedFields[billinginvoice.FieldDeletionSource] = struct{}{} +} + +// DeletionSourceCleared returns if the "deletion_source" field was cleared in this mutation. +func (m *BillingInvoiceMutation) DeletionSourceCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldDeletionSource] + return ok +} + +// ResetDeletionSource resets all changes to the "deletion_source" field. +func (m *BillingInvoiceMutation) ResetDeletionSource() { + m.deletion_source = nil + delete(m.clearedFields, billinginvoice.FieldDeletionSource) +} + +// SetCurrency sets the "currency" field. +func (m *BillingInvoiceMutation) SetCurrency(c currencyx.Code) { + m.currency = &c +} + +// Currency returns the value of the "currency" field in the mutation. +func (m *BillingInvoiceMutation) Currency() (r currencyx.Code, exists bool) { + v := m.currency + if v == nil { + return + } + return *v, true +} + +// OldCurrency returns the old "currency" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldCurrency(ctx context.Context) (v currencyx.Code, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrency is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrency requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrency: %w", err) + } + return oldValue.Currency, nil +} + +// ResetCurrency resets all changes to the "currency" field. +func (m *BillingInvoiceMutation) ResetCurrency() { + m.currency = nil +} + +// SetDueAt sets the "due_at" field. +func (m *BillingInvoiceMutation) SetDueAt(t time.Time) { + m.due_at = &t +} + +// DueAt returns the value of the "due_at" field in the mutation. +func (m *BillingInvoiceMutation) DueAt() (r time.Time, exists bool) { + v := m.due_at + if v == nil { + return + } + return *v, true +} + +// OldDueAt returns the old "due_at" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldDueAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDueAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDueAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDueAt: %w", err) + } + return oldValue.DueAt, nil +} + +// ClearDueAt clears the value of the "due_at" field. +func (m *BillingInvoiceMutation) ClearDueAt() { + m.due_at = nil + m.clearedFields[billinginvoice.FieldDueAt] = struct{}{} +} + +// DueAtCleared returns if the "due_at" field was cleared in this mutation. +func (m *BillingInvoiceMutation) DueAtCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldDueAt] + return ok +} + +// ResetDueAt resets all changes to the "due_at" field. +func (m *BillingInvoiceMutation) ResetDueAt() { + m.due_at = nil + delete(m.clearedFields, billinginvoice.FieldDueAt) +} + +// SetStatus sets the "status" field. +func (m *BillingInvoiceMutation) SetStatus(bis billing.StandardInvoiceStatus) { + m.status = &bis +} + +// Status returns the value of the "status" field in the mutation. +func (m *BillingInvoiceMutation) Status() (r billing.StandardInvoiceStatus, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true +} + +// OldStatus returns the old "status" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldStatus(ctx context.Context) (v billing.StandardInvoiceStatus, 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 *BillingInvoiceMutation) ResetStatus() { + m.status = nil +} + +// SetStatusDetailsCache sets the "status_details_cache" field. +func (m *BillingInvoiceMutation) SetStatusDetailsCache(bisd billing.StandardInvoiceStatusDetails) { + m.status_details_cache = &bisd +} + +// StatusDetailsCache returns the value of the "status_details_cache" field in the mutation. +func (m *BillingInvoiceMutation) StatusDetailsCache() (r billing.StandardInvoiceStatusDetails, exists bool) { + v := m.status_details_cache + if v == nil { + return + } + return *v, true +} + +// OldStatusDetailsCache returns the old "status_details_cache" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldStatusDetailsCache(ctx context.Context) (v billing.StandardInvoiceStatusDetails, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStatusDetailsCache is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStatusDetailsCache requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStatusDetailsCache: %w", err) + } + return oldValue.StatusDetailsCache, nil +} + +// ClearStatusDetailsCache clears the value of the "status_details_cache" field. +func (m *BillingInvoiceMutation) ClearStatusDetailsCache() { + m.status_details_cache = nil + m.clearedFields[billinginvoice.FieldStatusDetailsCache] = struct{}{} +} + +// StatusDetailsCacheCleared returns if the "status_details_cache" field was cleared in this mutation. +func (m *BillingInvoiceMutation) StatusDetailsCacheCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldStatusDetailsCache] + return ok +} + +// ResetStatusDetailsCache resets all changes to the "status_details_cache" field. +func (m *BillingInvoiceMutation) ResetStatusDetailsCache() { + m.status_details_cache = nil + delete(m.clearedFields, billinginvoice.FieldStatusDetailsCache) +} + +// SetWorkflowConfigID sets the "workflow_config_id" field. +func (m *BillingInvoiceMutation) SetWorkflowConfigID(s string) { + m.billing_workflow_config = &s +} + +// WorkflowConfigID returns the value of the "workflow_config_id" field in the mutation. +func (m *BillingInvoiceMutation) WorkflowConfigID() (r string, exists bool) { + v := m.billing_workflow_config + if v == nil { + return + } + return *v, true +} + +// OldWorkflowConfigID returns the old "workflow_config_id" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldWorkflowConfigID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldWorkflowConfigID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldWorkflowConfigID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldWorkflowConfigID: %w", err) + } + return oldValue.WorkflowConfigID, nil +} + +// ResetWorkflowConfigID resets all changes to the "workflow_config_id" field. +func (m *BillingInvoiceMutation) ResetWorkflowConfigID() { + m.billing_workflow_config = nil +} + +// SetTaxAppID sets the "tax_app_id" field. +func (m *BillingInvoiceMutation) SetTaxAppID(s string) { + m.tax_app = &s +} + +// TaxAppID returns the value of the "tax_app_id" field in the mutation. +func (m *BillingInvoiceMutation) TaxAppID() (r string, exists bool) { + v := m.tax_app + if v == nil { + return + } + return *v, true +} + +// OldTaxAppID returns the old "tax_app_id" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldTaxAppID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxAppID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxAppID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxAppID: %w", err) + } + return oldValue.TaxAppID, nil +} + +// ResetTaxAppID resets all changes to the "tax_app_id" field. +func (m *BillingInvoiceMutation) ResetTaxAppID() { + m.tax_app = nil +} + +// SetInvoicingAppID sets the "invoicing_app_id" field. +func (m *BillingInvoiceMutation) SetInvoicingAppID(s string) { + m.invoicing_app = &s +} + +// InvoicingAppID returns the value of the "invoicing_app_id" field in the mutation. +func (m *BillingInvoiceMutation) InvoicingAppID() (r string, exists bool) { + v := m.invoicing_app + if v == nil { + return + } + return *v, true +} + +// OldInvoicingAppID returns the old "invoicing_app_id" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldInvoicingAppID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoicingAppID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoicingAppID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoicingAppID: %w", err) + } + return oldValue.InvoicingAppID, nil +} + +// ResetInvoicingAppID resets all changes to the "invoicing_app_id" field. +func (m *BillingInvoiceMutation) ResetInvoicingAppID() { + m.invoicing_app = nil +} + +// SetPaymentAppID sets the "payment_app_id" field. +func (m *BillingInvoiceMutation) SetPaymentAppID(s string) { + m.payment_app = &s +} + +// PaymentAppID returns the value of the "payment_app_id" field in the mutation. +func (m *BillingInvoiceMutation) PaymentAppID() (r string, exists bool) { + v := m.payment_app + if v == nil { + return + } + return *v, true +} + +// OldPaymentAppID returns the old "payment_app_id" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldPaymentAppID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPaymentAppID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPaymentAppID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPaymentAppID: %w", err) + } + return oldValue.PaymentAppID, nil +} + +// ResetPaymentAppID resets all changes to the "payment_app_id" field. +func (m *BillingInvoiceMutation) ResetPaymentAppID() { + m.payment_app = nil +} + +// SetPeriodStart sets the "period_start" field. +func (m *BillingInvoiceMutation) SetPeriodStart(t time.Time) { + m.period_start = &t +} + +// PeriodStart returns the value of the "period_start" field in the mutation. +func (m *BillingInvoiceMutation) PeriodStart() (r time.Time, exists bool) { + v := m.period_start + if v == nil { + return + } + return *v, true +} + +// OldPeriodStart returns the old "period_start" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldPeriodStart(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPeriodStart is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPeriodStart requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPeriodStart: %w", err) + } + return oldValue.PeriodStart, nil +} + +// ClearPeriodStart clears the value of the "period_start" field. +func (m *BillingInvoiceMutation) ClearPeriodStart() { + m.period_start = nil + m.clearedFields[billinginvoice.FieldPeriodStart] = struct{}{} +} + +// PeriodStartCleared returns if the "period_start" field was cleared in this mutation. +func (m *BillingInvoiceMutation) PeriodStartCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldPeriodStart] + return ok +} + +// ResetPeriodStart resets all changes to the "period_start" field. +func (m *BillingInvoiceMutation) ResetPeriodStart() { + m.period_start = nil + delete(m.clearedFields, billinginvoice.FieldPeriodStart) +} + +// SetPeriodEnd sets the "period_end" field. +func (m *BillingInvoiceMutation) SetPeriodEnd(t time.Time) { + m.period_end = &t +} + +// PeriodEnd returns the value of the "period_end" field in the mutation. +func (m *BillingInvoiceMutation) PeriodEnd() (r time.Time, exists bool) { + v := m.period_end + if v == nil { + return + } + return *v, true +} + +// OldPeriodEnd returns the old "period_end" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldPeriodEnd(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPeriodEnd is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPeriodEnd requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPeriodEnd: %w", err) + } + return oldValue.PeriodEnd, nil +} + +// ClearPeriodEnd clears the value of the "period_end" field. +func (m *BillingInvoiceMutation) ClearPeriodEnd() { + m.period_end = nil + m.clearedFields[billinginvoice.FieldPeriodEnd] = struct{}{} +} + +// PeriodEndCleared returns if the "period_end" field was cleared in this mutation. +func (m *BillingInvoiceMutation) PeriodEndCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldPeriodEnd] + return ok +} + +// ResetPeriodEnd resets all changes to the "period_end" field. +func (m *BillingInvoiceMutation) ResetPeriodEnd() { + m.period_end = nil + delete(m.clearedFields, billinginvoice.FieldPeriodEnd) +} + +// SetCollectionAt sets the "collection_at" field. +func (m *BillingInvoiceMutation) SetCollectionAt(t time.Time) { + m.collection_at = &t +} + +// CollectionAt returns the value of the "collection_at" field in the mutation. +func (m *BillingInvoiceMutation) CollectionAt() (r time.Time, exists bool) { + v := m.collection_at + if v == nil { + return + } + return *v, true +} + +// OldCollectionAt returns the old "collection_at" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldCollectionAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCollectionAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCollectionAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCollectionAt: %w", err) + } + return oldValue.CollectionAt, nil +} + +// ClearCollectionAt clears the value of the "collection_at" field. +func (m *BillingInvoiceMutation) ClearCollectionAt() { + m.collection_at = nil + m.clearedFields[billinginvoice.FieldCollectionAt] = struct{}{} +} + +// CollectionAtCleared returns if the "collection_at" field was cleared in this mutation. +func (m *BillingInvoiceMutation) CollectionAtCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldCollectionAt] + return ok +} + +// ResetCollectionAt resets all changes to the "collection_at" field. +func (m *BillingInvoiceMutation) ResetCollectionAt() { + m.collection_at = nil + delete(m.clearedFields, billinginvoice.FieldCollectionAt) +} + +// SetPaymentProcessingEnteredAt sets the "payment_processing_entered_at" field. +func (m *BillingInvoiceMutation) SetPaymentProcessingEnteredAt(t time.Time) { + m.payment_processing_entered_at = &t +} + +// PaymentProcessingEnteredAt returns the value of the "payment_processing_entered_at" field in the mutation. +func (m *BillingInvoiceMutation) PaymentProcessingEnteredAt() (r time.Time, exists bool) { + v := m.payment_processing_entered_at + if v == nil { + return + } + return *v, true +} + +// OldPaymentProcessingEnteredAt returns the old "payment_processing_entered_at" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldPaymentProcessingEnteredAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPaymentProcessingEnteredAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPaymentProcessingEnteredAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPaymentProcessingEnteredAt: %w", err) + } + return oldValue.PaymentProcessingEnteredAt, nil +} + +// ClearPaymentProcessingEnteredAt clears the value of the "payment_processing_entered_at" field. +func (m *BillingInvoiceMutation) ClearPaymentProcessingEnteredAt() { + m.payment_processing_entered_at = nil + m.clearedFields[billinginvoice.FieldPaymentProcessingEnteredAt] = struct{}{} +} + +// PaymentProcessingEnteredAtCleared returns if the "payment_processing_entered_at" field was cleared in this mutation. +func (m *BillingInvoiceMutation) PaymentProcessingEnteredAtCleared() bool { + _, ok := m.clearedFields[billinginvoice.FieldPaymentProcessingEnteredAt] + return ok +} + +// ResetPaymentProcessingEnteredAt resets all changes to the "payment_processing_entered_at" field. +func (m *BillingInvoiceMutation) ResetPaymentProcessingEnteredAt() { + m.payment_processing_entered_at = nil + delete(m.clearedFields, billinginvoice.FieldPaymentProcessingEnteredAt) +} + +// SetSchemaLevel sets the "schema_level" field. +func (m *BillingInvoiceMutation) SetSchemaLevel(i int) { + m.schema_level = &i + m.addschema_level = nil +} + +// SchemaLevel returns the value of the "schema_level" field in the mutation. +func (m *BillingInvoiceMutation) SchemaLevel() (r int, exists bool) { + v := m.schema_level + if v == nil { + return + } + return *v, true +} + +// OldSchemaLevel returns the old "schema_level" field's value of the BillingInvoice entity. +// If the BillingInvoice 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 *BillingInvoiceMutation) OldSchemaLevel(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSchemaLevel is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSchemaLevel requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSchemaLevel: %w", err) + } + return oldValue.SchemaLevel, nil +} + +// AddSchemaLevel adds i to the "schema_level" field. +func (m *BillingInvoiceMutation) AddSchemaLevel(i int) { + if m.addschema_level != nil { + *m.addschema_level += i + } else { + m.addschema_level = &i + } +} + +// AddedSchemaLevel returns the value that was added to the "schema_level" field in this mutation. +func (m *BillingInvoiceMutation) AddedSchemaLevel() (r int, exists bool) { + v := m.addschema_level + if v == nil { + return + } + return *v, true +} + +// ResetSchemaLevel resets all changes to the "schema_level" field. +func (m *BillingInvoiceMutation) ResetSchemaLevel() { + m.schema_level = nil + m.addschema_level = nil +} + +// ClearSourceBillingProfile clears the "source_billing_profile" edge to the BillingProfile entity. +func (m *BillingInvoiceMutation) ClearSourceBillingProfile() { + m.clearedsource_billing_profile = true + m.clearedFields[billinginvoice.FieldSourceBillingProfileID] = struct{}{} +} + +// SourceBillingProfileCleared reports if the "source_billing_profile" edge to the BillingProfile entity was cleared. +func (m *BillingInvoiceMutation) SourceBillingProfileCleared() bool { + return m.clearedsource_billing_profile +} + +// SourceBillingProfileIDs returns the "source_billing_profile" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SourceBillingProfileID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceMutation) SourceBillingProfileIDs() (ids []string) { + if id := m.source_billing_profile; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSourceBillingProfile resets all changes to the "source_billing_profile" edge. +func (m *BillingInvoiceMutation) ResetSourceBillingProfile() { + m.source_billing_profile = nil + m.clearedsource_billing_profile = false +} + +// SetBillingWorkflowConfigID sets the "billing_workflow_config" edge to the BillingWorkflowConfig entity by id. +func (m *BillingInvoiceMutation) SetBillingWorkflowConfigID(id string) { + m.billing_workflow_config = &id +} + +// ClearBillingWorkflowConfig clears the "billing_workflow_config" edge to the BillingWorkflowConfig entity. +func (m *BillingInvoiceMutation) ClearBillingWorkflowConfig() { + m.clearedbilling_workflow_config = true + m.clearedFields[billinginvoice.FieldWorkflowConfigID] = struct{}{} +} + +// BillingWorkflowConfigCleared reports if the "billing_workflow_config" edge to the BillingWorkflowConfig entity was cleared. +func (m *BillingInvoiceMutation) BillingWorkflowConfigCleared() bool { + return m.clearedbilling_workflow_config +} + +// BillingWorkflowConfigID returns the "billing_workflow_config" edge ID in the mutation. +func (m *BillingInvoiceMutation) BillingWorkflowConfigID() (id string, exists bool) { + if m.billing_workflow_config != nil { + return *m.billing_workflow_config, true + } + return +} + +// BillingWorkflowConfigIDs returns the "billing_workflow_config" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BillingWorkflowConfigID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceMutation) BillingWorkflowConfigIDs() (ids []string) { + if id := m.billing_workflow_config; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBillingWorkflowConfig resets all changes to the "billing_workflow_config" edge. +func (m *BillingInvoiceMutation) ResetBillingWorkflowConfig() { + m.billing_workflow_config = nil + m.clearedbilling_workflow_config = false +} + +// AddBillingInvoiceLineIDs adds the "billing_invoice_lines" edge to the BillingInvoiceLine entity by ids. +func (m *BillingInvoiceMutation) AddBillingInvoiceLineIDs(ids ...string) { + if m.billing_invoice_lines == nil { + m.billing_invoice_lines = make(map[string]struct{}) + } + for i := range ids { + m.billing_invoice_lines[ids[i]] = struct{}{} + } +} + +// ClearBillingInvoiceLines clears the "billing_invoice_lines" edge to the BillingInvoiceLine entity. +func (m *BillingInvoiceMutation) ClearBillingInvoiceLines() { + m.clearedbilling_invoice_lines = true +} + +// BillingInvoiceLinesCleared reports if the "billing_invoice_lines" edge to the BillingInvoiceLine entity was cleared. +func (m *BillingInvoiceMutation) BillingInvoiceLinesCleared() bool { + return m.clearedbilling_invoice_lines +} + +// RemoveBillingInvoiceLineIDs removes the "billing_invoice_lines" edge to the BillingInvoiceLine entity by IDs. +func (m *BillingInvoiceMutation) RemoveBillingInvoiceLineIDs(ids ...string) { + if m.removedbilling_invoice_lines == nil { + m.removedbilling_invoice_lines = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_invoice_lines, ids[i]) + m.removedbilling_invoice_lines[ids[i]] = struct{}{} + } +} + +// RemovedBillingInvoiceLines returns the removed IDs of the "billing_invoice_lines" edge to the BillingInvoiceLine entity. +func (m *BillingInvoiceMutation) RemovedBillingInvoiceLinesIDs() (ids []string) { + for id := range m.removedbilling_invoice_lines { + ids = append(ids, id) + } + return +} + +// BillingInvoiceLinesIDs returns the "billing_invoice_lines" edge IDs in the mutation. +func (m *BillingInvoiceMutation) BillingInvoiceLinesIDs() (ids []string) { + for id := range m.billing_invoice_lines { + ids = append(ids, id) + } + return +} + +// ResetBillingInvoiceLines resets all changes to the "billing_invoice_lines" edge. +func (m *BillingInvoiceMutation) ResetBillingInvoiceLines() { + m.billing_invoice_lines = nil + m.clearedbilling_invoice_lines = false + m.removedbilling_invoice_lines = nil +} + +// AddBillingInvoiceDetailedLineIDs adds the "billing_invoice_detailed_lines" edge to the BillingStandardInvoiceDetailedLine entity by ids. +func (m *BillingInvoiceMutation) AddBillingInvoiceDetailedLineIDs(ids ...string) { + if m.billing_invoice_detailed_lines == nil { + m.billing_invoice_detailed_lines = make(map[string]struct{}) + } + for i := range ids { + m.billing_invoice_detailed_lines[ids[i]] = struct{}{} + } +} + +// ClearBillingInvoiceDetailedLines clears the "billing_invoice_detailed_lines" edge to the BillingStandardInvoiceDetailedLine entity. +func (m *BillingInvoiceMutation) ClearBillingInvoiceDetailedLines() { + m.clearedbilling_invoice_detailed_lines = true +} + +// BillingInvoiceDetailedLinesCleared reports if the "billing_invoice_detailed_lines" edge to the BillingStandardInvoiceDetailedLine entity was cleared. +func (m *BillingInvoiceMutation) BillingInvoiceDetailedLinesCleared() bool { + return m.clearedbilling_invoice_detailed_lines +} + +// RemoveBillingInvoiceDetailedLineIDs removes the "billing_invoice_detailed_lines" edge to the BillingStandardInvoiceDetailedLine entity by IDs. +func (m *BillingInvoiceMutation) RemoveBillingInvoiceDetailedLineIDs(ids ...string) { + if m.removedbilling_invoice_detailed_lines == nil { + m.removedbilling_invoice_detailed_lines = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_invoice_detailed_lines, ids[i]) + m.removedbilling_invoice_detailed_lines[ids[i]] = struct{}{} + } +} + +// RemovedBillingInvoiceDetailedLines returns the removed IDs of the "billing_invoice_detailed_lines" edge to the BillingStandardInvoiceDetailedLine entity. +func (m *BillingInvoiceMutation) RemovedBillingInvoiceDetailedLinesIDs() (ids []string) { + for id := range m.removedbilling_invoice_detailed_lines { + ids = append(ids, id) + } + return +} + +// BillingInvoiceDetailedLinesIDs returns the "billing_invoice_detailed_lines" edge IDs in the mutation. +func (m *BillingInvoiceMutation) BillingInvoiceDetailedLinesIDs() (ids []string) { + for id := range m.billing_invoice_detailed_lines { + ids = append(ids, id) + } + return +} + +// ResetBillingInvoiceDetailedLines resets all changes to the "billing_invoice_detailed_lines" edge. +func (m *BillingInvoiceMutation) ResetBillingInvoiceDetailedLines() { + m.billing_invoice_detailed_lines = nil + m.clearedbilling_invoice_detailed_lines = false + m.removedbilling_invoice_detailed_lines = nil +} + +// AddBillingInvoiceValidationIssueIDs adds the "billing_invoice_validation_issues" edge to the BillingInvoiceValidationIssue entity by ids. +func (m *BillingInvoiceMutation) AddBillingInvoiceValidationIssueIDs(ids ...string) { + if m.billing_invoice_validation_issues == nil { + m.billing_invoice_validation_issues = make(map[string]struct{}) + } + for i := range ids { + m.billing_invoice_validation_issues[ids[i]] = struct{}{} + } +} + +// ClearBillingInvoiceValidationIssues clears the "billing_invoice_validation_issues" edge to the BillingInvoiceValidationIssue entity. +func (m *BillingInvoiceMutation) ClearBillingInvoiceValidationIssues() { + m.clearedbilling_invoice_validation_issues = true +} + +// BillingInvoiceValidationIssuesCleared reports if the "billing_invoice_validation_issues" edge to the BillingInvoiceValidationIssue entity was cleared. +func (m *BillingInvoiceMutation) BillingInvoiceValidationIssuesCleared() bool { + return m.clearedbilling_invoice_validation_issues +} + +// RemoveBillingInvoiceValidationIssueIDs removes the "billing_invoice_validation_issues" edge to the BillingInvoiceValidationIssue entity by IDs. +func (m *BillingInvoiceMutation) RemoveBillingInvoiceValidationIssueIDs(ids ...string) { + if m.removedbilling_invoice_validation_issues == nil { + m.removedbilling_invoice_validation_issues = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_invoice_validation_issues, ids[i]) + m.removedbilling_invoice_validation_issues[ids[i]] = struct{}{} + } +} + +// RemovedBillingInvoiceValidationIssues returns the removed IDs of the "billing_invoice_validation_issues" edge to the BillingInvoiceValidationIssue entity. +func (m *BillingInvoiceMutation) RemovedBillingInvoiceValidationIssuesIDs() (ids []string) { + for id := range m.removedbilling_invoice_validation_issues { + ids = append(ids, id) + } + return +} + +// BillingInvoiceValidationIssuesIDs returns the "billing_invoice_validation_issues" edge IDs in the mutation. +func (m *BillingInvoiceMutation) BillingInvoiceValidationIssuesIDs() (ids []string) { + for id := range m.billing_invoice_validation_issues { + ids = append(ids, id) + } + return +} + +// ResetBillingInvoiceValidationIssues resets all changes to the "billing_invoice_validation_issues" edge. +func (m *BillingInvoiceMutation) ResetBillingInvoiceValidationIssues() { + m.billing_invoice_validation_issues = nil + m.clearedbilling_invoice_validation_issues = false + m.removedbilling_invoice_validation_issues = nil +} + +// AddChargeFlatFeeRunIDs adds the "charge_flat_fee_runs" edge to the ChargeFlatFeeRun entity by ids. +func (m *BillingInvoiceMutation) AddChargeFlatFeeRunIDs(ids ...string) { + if m.charge_flat_fee_runs == nil { + m.charge_flat_fee_runs = make(map[string]struct{}) + } + for i := range ids { + m.charge_flat_fee_runs[ids[i]] = struct{}{} + } +} + +// ClearChargeFlatFeeRuns clears the "charge_flat_fee_runs" edge to the ChargeFlatFeeRun entity. +func (m *BillingInvoiceMutation) ClearChargeFlatFeeRuns() { + m.clearedcharge_flat_fee_runs = true +} + +// ChargeFlatFeeRunsCleared reports if the "charge_flat_fee_runs" edge to the ChargeFlatFeeRun entity was cleared. +func (m *BillingInvoiceMutation) ChargeFlatFeeRunsCleared() bool { + return m.clearedcharge_flat_fee_runs +} + +// RemoveChargeFlatFeeRunIDs removes the "charge_flat_fee_runs" edge to the ChargeFlatFeeRun entity by IDs. +func (m *BillingInvoiceMutation) RemoveChargeFlatFeeRunIDs(ids ...string) { + if m.removedcharge_flat_fee_runs == nil { + m.removedcharge_flat_fee_runs = make(map[string]struct{}) + } + for i := range ids { + delete(m.charge_flat_fee_runs, ids[i]) + m.removedcharge_flat_fee_runs[ids[i]] = struct{}{} + } +} + +// RemovedChargeFlatFeeRuns returns the removed IDs of the "charge_flat_fee_runs" edge to the ChargeFlatFeeRun entity. +func (m *BillingInvoiceMutation) RemovedChargeFlatFeeRunsIDs() (ids []string) { + for id := range m.removedcharge_flat_fee_runs { + ids = append(ids, id) + } + return +} + +// ChargeFlatFeeRunsIDs returns the "charge_flat_fee_runs" edge IDs in the mutation. +func (m *BillingInvoiceMutation) ChargeFlatFeeRunsIDs() (ids []string) { + for id := range m.charge_flat_fee_runs { + ids = append(ids, id) + } + return +} + +// ResetChargeFlatFeeRuns resets all changes to the "charge_flat_fee_runs" edge. +func (m *BillingInvoiceMutation) ResetChargeFlatFeeRuns() { + m.charge_flat_fee_runs = nil + m.clearedcharge_flat_fee_runs = false + m.removedcharge_flat_fee_runs = nil +} + +// AddChargeUsageBasedRunIDs adds the "charge_usage_based_runs" edge to the ChargeUsageBasedRuns entity by ids. +func (m *BillingInvoiceMutation) AddChargeUsageBasedRunIDs(ids ...string) { + if m.charge_usage_based_runs == nil { + m.charge_usage_based_runs = make(map[string]struct{}) + } + for i := range ids { + m.charge_usage_based_runs[ids[i]] = struct{}{} + } +} + +// ClearChargeUsageBasedRuns clears the "charge_usage_based_runs" edge to the ChargeUsageBasedRuns entity. +func (m *BillingInvoiceMutation) ClearChargeUsageBasedRuns() { + m.clearedcharge_usage_based_runs = true +} + +// ChargeUsageBasedRunsCleared reports if the "charge_usage_based_runs" edge to the ChargeUsageBasedRuns entity was cleared. +func (m *BillingInvoiceMutation) ChargeUsageBasedRunsCleared() bool { + return m.clearedcharge_usage_based_runs +} + +// RemoveChargeUsageBasedRunIDs removes the "charge_usage_based_runs" edge to the ChargeUsageBasedRuns entity by IDs. +func (m *BillingInvoiceMutation) RemoveChargeUsageBasedRunIDs(ids ...string) { + if m.removedcharge_usage_based_runs == nil { + m.removedcharge_usage_based_runs = make(map[string]struct{}) + } + for i := range ids { + delete(m.charge_usage_based_runs, ids[i]) + m.removedcharge_usage_based_runs[ids[i]] = struct{}{} + } +} + +// RemovedChargeUsageBasedRuns returns the removed IDs of the "charge_usage_based_runs" edge to the ChargeUsageBasedRuns entity. +func (m *BillingInvoiceMutation) RemovedChargeUsageBasedRunsIDs() (ids []string) { + for id := range m.removedcharge_usage_based_runs { + ids = append(ids, id) + } + return +} + +// ChargeUsageBasedRunsIDs returns the "charge_usage_based_runs" edge IDs in the mutation. +func (m *BillingInvoiceMutation) ChargeUsageBasedRunsIDs() (ids []string) { + for id := range m.charge_usage_based_runs { + ids = append(ids, id) + } + return +} + +// ResetChargeUsageBasedRuns resets all changes to the "charge_usage_based_runs" edge. +func (m *BillingInvoiceMutation) ResetChargeUsageBasedRuns() { + m.charge_usage_based_runs = nil + m.clearedcharge_usage_based_runs = false + m.removedcharge_usage_based_runs = nil +} + +// SetBillingInvoiceCustomerID sets the "billing_invoice_customer" edge to the Customer entity by id. +func (m *BillingInvoiceMutation) SetBillingInvoiceCustomerID(id string) { + m.billing_invoice_customer = &id +} + +// ClearBillingInvoiceCustomer clears the "billing_invoice_customer" edge to the Customer entity. +func (m *BillingInvoiceMutation) ClearBillingInvoiceCustomer() { + m.clearedbilling_invoice_customer = true + m.clearedFields[billinginvoice.FieldCustomerID] = struct{}{} +} + +// BillingInvoiceCustomerCleared reports if the "billing_invoice_customer" edge to the Customer entity was cleared. +func (m *BillingInvoiceMutation) BillingInvoiceCustomerCleared() bool { + return m.clearedbilling_invoice_customer +} + +// BillingInvoiceCustomerID returns the "billing_invoice_customer" edge ID in the mutation. +func (m *BillingInvoiceMutation) BillingInvoiceCustomerID() (id string, exists bool) { + if m.billing_invoice_customer != nil { + return *m.billing_invoice_customer, true + } + return +} + +// BillingInvoiceCustomerIDs returns the "billing_invoice_customer" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BillingInvoiceCustomerID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceMutation) BillingInvoiceCustomerIDs() (ids []string) { + if id := m.billing_invoice_customer; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBillingInvoiceCustomer resets all changes to the "billing_invoice_customer" edge. +func (m *BillingInvoiceMutation) ResetBillingInvoiceCustomer() { + m.billing_invoice_customer = nil + m.clearedbilling_invoice_customer = false +} + +// ClearTaxApp clears the "tax_app" edge to the App entity. +func (m *BillingInvoiceMutation) ClearTaxApp() { + m.clearedtax_app = true + m.clearedFields[billinginvoice.FieldTaxAppID] = struct{}{} +} + +// TaxAppCleared reports if the "tax_app" edge to the App entity was cleared. +func (m *BillingInvoiceMutation) TaxAppCleared() bool { + return m.clearedtax_app +} + +// TaxAppIDs returns the "tax_app" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TaxAppID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceMutation) TaxAppIDs() (ids []string) { + if id := m.tax_app; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTaxApp resets all changes to the "tax_app" edge. +func (m *BillingInvoiceMutation) ResetTaxApp() { + m.tax_app = nil + m.clearedtax_app = false +} + +// ClearInvoicingApp clears the "invoicing_app" edge to the App entity. +func (m *BillingInvoiceMutation) ClearInvoicingApp() { + m.clearedinvoicing_app = true + m.clearedFields[billinginvoice.FieldInvoicingAppID] = struct{}{} +} + +// InvoicingAppCleared reports if the "invoicing_app" edge to the App entity was cleared. +func (m *BillingInvoiceMutation) InvoicingAppCleared() bool { + return m.clearedinvoicing_app +} + +// InvoicingAppIDs returns the "invoicing_app" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// InvoicingAppID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceMutation) InvoicingAppIDs() (ids []string) { + if id := m.invoicing_app; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetInvoicingApp resets all changes to the "invoicing_app" edge. +func (m *BillingInvoiceMutation) ResetInvoicingApp() { + m.invoicing_app = nil + m.clearedinvoicing_app = false +} + +// ClearPaymentApp clears the "payment_app" edge to the App entity. +func (m *BillingInvoiceMutation) ClearPaymentApp() { + m.clearedpayment_app = true + m.clearedFields[billinginvoice.FieldPaymentAppID] = struct{}{} +} + +// PaymentAppCleared reports if the "payment_app" edge to the App entity was cleared. +func (m *BillingInvoiceMutation) PaymentAppCleared() bool { + return m.clearedpayment_app +} + +// PaymentAppIDs returns the "payment_app" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// PaymentAppID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceMutation) PaymentAppIDs() (ids []string) { + if id := m.payment_app; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetPaymentApp resets all changes to the "payment_app" edge. +func (m *BillingInvoiceMutation) ResetPaymentApp() { + m.payment_app = nil + m.clearedpayment_app = false +} + +// Where appends a list predicates to the BillingInvoiceMutation builder. +func (m *BillingInvoiceMutation) Where(ps ...predicate.BillingInvoice) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BillingInvoiceMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BillingInvoiceMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillingInvoice, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BillingInvoiceMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BillingInvoiceMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BillingInvoice). +func (m *BillingInvoiceMutation) 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 *BillingInvoiceMutation) Fields() []string { + fields := make([]string, 0, 59) + if m.namespace != nil { + fields = append(fields, billinginvoice.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, billinginvoice.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, billinginvoice.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, billinginvoice.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, billinginvoice.FieldDeletedAt) + } + if m.supplier_address_country != nil { + fields = append(fields, billinginvoice.FieldSupplierAddressCountry) + } + if m.supplier_address_postal_code != nil { + fields = append(fields, billinginvoice.FieldSupplierAddressPostalCode) + } + if m.supplier_address_state != nil { + fields = append(fields, billinginvoice.FieldSupplierAddressState) + } + if m.supplier_address_city != nil { + fields = append(fields, billinginvoice.FieldSupplierAddressCity) + } + if m.supplier_address_line1 != nil { + fields = append(fields, billinginvoice.FieldSupplierAddressLine1) + } + if m.supplier_address_line2 != nil { + fields = append(fields, billinginvoice.FieldSupplierAddressLine2) + } + if m.supplier_address_phone_number != nil { + fields = append(fields, billinginvoice.FieldSupplierAddressPhoneNumber) + } + if m.customer_address_country != nil { + fields = append(fields, billinginvoice.FieldCustomerAddressCountry) + } + if m.customer_address_postal_code != nil { + fields = append(fields, billinginvoice.FieldCustomerAddressPostalCode) + } + if m.customer_address_state != nil { + fields = append(fields, billinginvoice.FieldCustomerAddressState) + } + if m.customer_address_city != nil { + fields = append(fields, billinginvoice.FieldCustomerAddressCity) + } + if m.customer_address_line1 != nil { + fields = append(fields, billinginvoice.FieldCustomerAddressLine1) + } + if m.customer_address_line2 != nil { + fields = append(fields, billinginvoice.FieldCustomerAddressLine2) + } + if m.customer_address_phone_number != nil { + fields = append(fields, billinginvoice.FieldCustomerAddressPhoneNumber) + } + if m.amount != nil { + fields = append(fields, billinginvoice.FieldAmount) + } + if m.taxes_total != nil { + fields = append(fields, billinginvoice.FieldTaxesTotal) + } + if m.taxes_inclusive_total != nil { + fields = append(fields, billinginvoice.FieldTaxesInclusiveTotal) + } + if m.taxes_exclusive_total != nil { + fields = append(fields, billinginvoice.FieldTaxesExclusiveTotal) + } + if m.charges_total != nil { + fields = append(fields, billinginvoice.FieldChargesTotal) + } + if m.discounts_total != nil { + fields = append(fields, billinginvoice.FieldDiscountsTotal) + } + if m.credits_total != nil { + fields = append(fields, billinginvoice.FieldCreditsTotal) + } + if m.total != nil { + fields = append(fields, billinginvoice.FieldTotal) + } + if m.invoicing_app_external_id != nil { + fields = append(fields, billinginvoice.FieldInvoicingAppExternalID) + } + if m.payment_app_external_id != nil { + fields = append(fields, billinginvoice.FieldPaymentAppExternalID) + } + if m.tax_app_external_id != nil { + fields = append(fields, billinginvoice.FieldTaxAppExternalID) + } + if m.supplier_name != nil { + fields = append(fields, billinginvoice.FieldSupplierName) + } + if m.supplier_tax_code != nil { + fields = append(fields, billinginvoice.FieldSupplierTaxCode) + } + if m.customer_key != nil { + fields = append(fields, billinginvoice.FieldCustomerKey) + } + if m.customer_name != nil { + fields = append(fields, billinginvoice.FieldCustomerName) + } + if m.customer_usage_attribution != nil { + fields = append(fields, billinginvoice.FieldCustomerUsageAttribution) + } + if m.number != nil { + fields = append(fields, billinginvoice.FieldNumber) + } + if m._type != nil { + fields = append(fields, billinginvoice.FieldType) + } + if m.description != nil { + fields = append(fields, billinginvoice.FieldDescription) + } + if m.billing_invoice_customer != nil { + fields = append(fields, billinginvoice.FieldCustomerID) + } + if m.source_billing_profile != nil { + fields = append(fields, billinginvoice.FieldSourceBillingProfileID) + } + if m.voided_at != nil { + fields = append(fields, billinginvoice.FieldVoidedAt) + } + if m.issued_at != nil { + fields = append(fields, billinginvoice.FieldIssuedAt) + } + if m.sent_to_customer_at != nil { + fields = append(fields, billinginvoice.FieldSentToCustomerAt) + } + if m.draft_until != nil { + fields = append(fields, billinginvoice.FieldDraftUntil) + } + if m.quantity_snapshoted_at != nil { + fields = append(fields, billinginvoice.FieldQuantitySnapshotedAt) + } + if m.deletion_source != nil { + fields = append(fields, billinginvoice.FieldDeletionSource) + } + if m.currency != nil { + fields = append(fields, billinginvoice.FieldCurrency) + } + if m.due_at != nil { + fields = append(fields, billinginvoice.FieldDueAt) + } + if m.status != nil { + fields = append(fields, billinginvoice.FieldStatus) + } + if m.status_details_cache != nil { + fields = append(fields, billinginvoice.FieldStatusDetailsCache) + } + if m.billing_workflow_config != nil { + fields = append(fields, billinginvoice.FieldWorkflowConfigID) + } + if m.tax_app != nil { + fields = append(fields, billinginvoice.FieldTaxAppID) + } + if m.invoicing_app != nil { + fields = append(fields, billinginvoice.FieldInvoicingAppID) + } + if m.payment_app != nil { + fields = append(fields, billinginvoice.FieldPaymentAppID) + } + if m.period_start != nil { + fields = append(fields, billinginvoice.FieldPeriodStart) + } + if m.period_end != nil { + fields = append(fields, billinginvoice.FieldPeriodEnd) + } + if m.collection_at != nil { + fields = append(fields, billinginvoice.FieldCollectionAt) + } + if m.payment_processing_entered_at != nil { + fields = append(fields, billinginvoice.FieldPaymentProcessingEnteredAt) + } + if m.schema_level != nil { + fields = append(fields, billinginvoice.FieldSchemaLevel) + } + 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 *BillingInvoiceMutation) Field(name string) (ent.Value, bool) { + switch name { + case billinginvoice.FieldNamespace: + return m.Namespace() + case billinginvoice.FieldMetadata: + return m.Metadata() + case billinginvoice.FieldCreatedAt: + return m.CreatedAt() + case billinginvoice.FieldUpdatedAt: + return m.UpdatedAt() + case billinginvoice.FieldDeletedAt: + return m.DeletedAt() + case billinginvoice.FieldSupplierAddressCountry: + return m.SupplierAddressCountry() + case billinginvoice.FieldSupplierAddressPostalCode: + return m.SupplierAddressPostalCode() + case billinginvoice.FieldSupplierAddressState: + return m.SupplierAddressState() + case billinginvoice.FieldSupplierAddressCity: + return m.SupplierAddressCity() + case billinginvoice.FieldSupplierAddressLine1: + return m.SupplierAddressLine1() + case billinginvoice.FieldSupplierAddressLine2: + return m.SupplierAddressLine2() + case billinginvoice.FieldSupplierAddressPhoneNumber: + return m.SupplierAddressPhoneNumber() + case billinginvoice.FieldCustomerAddressCountry: + return m.CustomerAddressCountry() + case billinginvoice.FieldCustomerAddressPostalCode: + return m.CustomerAddressPostalCode() + case billinginvoice.FieldCustomerAddressState: + return m.CustomerAddressState() + case billinginvoice.FieldCustomerAddressCity: + return m.CustomerAddressCity() + case billinginvoice.FieldCustomerAddressLine1: + return m.CustomerAddressLine1() + case billinginvoice.FieldCustomerAddressLine2: + return m.CustomerAddressLine2() + case billinginvoice.FieldCustomerAddressPhoneNumber: + return m.CustomerAddressPhoneNumber() + case billinginvoice.FieldAmount: + return m.Amount() + case billinginvoice.FieldTaxesTotal: + return m.TaxesTotal() + case billinginvoice.FieldTaxesInclusiveTotal: + return m.TaxesInclusiveTotal() + case billinginvoice.FieldTaxesExclusiveTotal: + return m.TaxesExclusiveTotal() + case billinginvoice.FieldChargesTotal: + return m.ChargesTotal() + case billinginvoice.FieldDiscountsTotal: + return m.DiscountsTotal() + case billinginvoice.FieldCreditsTotal: + return m.CreditsTotal() + case billinginvoice.FieldTotal: + return m.Total() + case billinginvoice.FieldInvoicingAppExternalID: + return m.InvoicingAppExternalID() + case billinginvoice.FieldPaymentAppExternalID: + return m.PaymentAppExternalID() + case billinginvoice.FieldTaxAppExternalID: + return m.TaxAppExternalID() + case billinginvoice.FieldSupplierName: + return m.SupplierName() + case billinginvoice.FieldSupplierTaxCode: + return m.SupplierTaxCode() + case billinginvoice.FieldCustomerKey: + return m.CustomerKey() + case billinginvoice.FieldCustomerName: + return m.CustomerName() + case billinginvoice.FieldCustomerUsageAttribution: + return m.CustomerUsageAttribution() + case billinginvoice.FieldNumber: + return m.Number() + case billinginvoice.FieldType: + return m.GetType() + case billinginvoice.FieldDescription: + return m.Description() + case billinginvoice.FieldCustomerID: + return m.CustomerID() + case billinginvoice.FieldSourceBillingProfileID: + return m.SourceBillingProfileID() + case billinginvoice.FieldVoidedAt: + return m.VoidedAt() + case billinginvoice.FieldIssuedAt: + return m.IssuedAt() + case billinginvoice.FieldSentToCustomerAt: + return m.SentToCustomerAt() + case billinginvoice.FieldDraftUntil: + return m.DraftUntil() + case billinginvoice.FieldQuantitySnapshotedAt: + return m.QuantitySnapshotedAt() + case billinginvoice.FieldDeletionSource: + return m.DeletionSource() + case billinginvoice.FieldCurrency: + return m.Currency() + case billinginvoice.FieldDueAt: + return m.DueAt() + case billinginvoice.FieldStatus: + return m.Status() + case billinginvoice.FieldStatusDetailsCache: + return m.StatusDetailsCache() + case billinginvoice.FieldWorkflowConfigID: + return m.WorkflowConfigID() + case billinginvoice.FieldTaxAppID: + return m.TaxAppID() + case billinginvoice.FieldInvoicingAppID: + return m.InvoicingAppID() + case billinginvoice.FieldPaymentAppID: + return m.PaymentAppID() + case billinginvoice.FieldPeriodStart: + return m.PeriodStart() + case billinginvoice.FieldPeriodEnd: + return m.PeriodEnd() + case billinginvoice.FieldCollectionAt: + return m.CollectionAt() + case billinginvoice.FieldPaymentProcessingEnteredAt: + return m.PaymentProcessingEnteredAt() + case billinginvoice.FieldSchemaLevel: + return m.SchemaLevel() + } + 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 *BillingInvoiceMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case billinginvoice.FieldNamespace: + return m.OldNamespace(ctx) + case billinginvoice.FieldMetadata: + return m.OldMetadata(ctx) + case billinginvoice.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case billinginvoice.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case billinginvoice.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case billinginvoice.FieldSupplierAddressCountry: + return m.OldSupplierAddressCountry(ctx) + case billinginvoice.FieldSupplierAddressPostalCode: + return m.OldSupplierAddressPostalCode(ctx) + case billinginvoice.FieldSupplierAddressState: + return m.OldSupplierAddressState(ctx) + case billinginvoice.FieldSupplierAddressCity: + return m.OldSupplierAddressCity(ctx) + case billinginvoice.FieldSupplierAddressLine1: + return m.OldSupplierAddressLine1(ctx) + case billinginvoice.FieldSupplierAddressLine2: + return m.OldSupplierAddressLine2(ctx) + case billinginvoice.FieldSupplierAddressPhoneNumber: + return m.OldSupplierAddressPhoneNumber(ctx) + case billinginvoice.FieldCustomerAddressCountry: + return m.OldCustomerAddressCountry(ctx) + case billinginvoice.FieldCustomerAddressPostalCode: + return m.OldCustomerAddressPostalCode(ctx) + case billinginvoice.FieldCustomerAddressState: + return m.OldCustomerAddressState(ctx) + case billinginvoice.FieldCustomerAddressCity: + return m.OldCustomerAddressCity(ctx) + case billinginvoice.FieldCustomerAddressLine1: + return m.OldCustomerAddressLine1(ctx) + case billinginvoice.FieldCustomerAddressLine2: + return m.OldCustomerAddressLine2(ctx) + case billinginvoice.FieldCustomerAddressPhoneNumber: + return m.OldCustomerAddressPhoneNumber(ctx) + case billinginvoice.FieldAmount: + return m.OldAmount(ctx) + case billinginvoice.FieldTaxesTotal: + return m.OldTaxesTotal(ctx) + case billinginvoice.FieldTaxesInclusiveTotal: + return m.OldTaxesInclusiveTotal(ctx) + case billinginvoice.FieldTaxesExclusiveTotal: + return m.OldTaxesExclusiveTotal(ctx) + case billinginvoice.FieldChargesTotal: + return m.OldChargesTotal(ctx) + case billinginvoice.FieldDiscountsTotal: + return m.OldDiscountsTotal(ctx) + case billinginvoice.FieldCreditsTotal: + return m.OldCreditsTotal(ctx) + case billinginvoice.FieldTotal: + return m.OldTotal(ctx) + case billinginvoice.FieldInvoicingAppExternalID: + return m.OldInvoicingAppExternalID(ctx) + case billinginvoice.FieldPaymentAppExternalID: + return m.OldPaymentAppExternalID(ctx) + case billinginvoice.FieldTaxAppExternalID: + return m.OldTaxAppExternalID(ctx) + case billinginvoice.FieldSupplierName: + return m.OldSupplierName(ctx) + case billinginvoice.FieldSupplierTaxCode: + return m.OldSupplierTaxCode(ctx) + case billinginvoice.FieldCustomerKey: + return m.OldCustomerKey(ctx) + case billinginvoice.FieldCustomerName: + return m.OldCustomerName(ctx) + case billinginvoice.FieldCustomerUsageAttribution: + return m.OldCustomerUsageAttribution(ctx) + case billinginvoice.FieldNumber: + return m.OldNumber(ctx) + case billinginvoice.FieldType: + return m.OldType(ctx) + case billinginvoice.FieldDescription: + return m.OldDescription(ctx) + case billinginvoice.FieldCustomerID: + return m.OldCustomerID(ctx) + case billinginvoice.FieldSourceBillingProfileID: + return m.OldSourceBillingProfileID(ctx) + case billinginvoice.FieldVoidedAt: + return m.OldVoidedAt(ctx) + case billinginvoice.FieldIssuedAt: + return m.OldIssuedAt(ctx) + case billinginvoice.FieldSentToCustomerAt: + return m.OldSentToCustomerAt(ctx) + case billinginvoice.FieldDraftUntil: + return m.OldDraftUntil(ctx) + case billinginvoice.FieldQuantitySnapshotedAt: + return m.OldQuantitySnapshotedAt(ctx) + case billinginvoice.FieldDeletionSource: + return m.OldDeletionSource(ctx) + case billinginvoice.FieldCurrency: + return m.OldCurrency(ctx) + case billinginvoice.FieldDueAt: + return m.OldDueAt(ctx) + case billinginvoice.FieldStatus: + return m.OldStatus(ctx) + case billinginvoice.FieldStatusDetailsCache: + return m.OldStatusDetailsCache(ctx) + case billinginvoice.FieldWorkflowConfigID: + return m.OldWorkflowConfigID(ctx) + case billinginvoice.FieldTaxAppID: + return m.OldTaxAppID(ctx) + case billinginvoice.FieldInvoicingAppID: + return m.OldInvoicingAppID(ctx) + case billinginvoice.FieldPaymentAppID: + return m.OldPaymentAppID(ctx) + case billinginvoice.FieldPeriodStart: + return m.OldPeriodStart(ctx) + case billinginvoice.FieldPeriodEnd: + return m.OldPeriodEnd(ctx) + case billinginvoice.FieldCollectionAt: + return m.OldCollectionAt(ctx) + case billinginvoice.FieldPaymentProcessingEnteredAt: + return m.OldPaymentProcessingEnteredAt(ctx) + case billinginvoice.FieldSchemaLevel: + return m.OldSchemaLevel(ctx) + } + return nil, fmt.Errorf("unknown BillingInvoice 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 *BillingInvoiceMutation) SetField(name string, value ent.Value) error { + switch name { + case billinginvoice.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case billinginvoice.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case billinginvoice.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 billinginvoice.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 billinginvoice.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 billinginvoice.FieldSupplierAddressCountry: + v, ok := value.(models.CountryCode) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSupplierAddressCountry(v) + return nil + case billinginvoice.FieldSupplierAddressPostalCode: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSupplierAddressPostalCode(v) + return nil + case billinginvoice.FieldSupplierAddressState: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSupplierAddressState(v) + return nil + case billinginvoice.FieldSupplierAddressCity: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSupplierAddressCity(v) + return nil + case billinginvoice.FieldSupplierAddressLine1: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSupplierAddressLine1(v) + return nil + case billinginvoice.FieldSupplierAddressLine2: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSupplierAddressLine2(v) + return nil + case billinginvoice.FieldSupplierAddressPhoneNumber: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSupplierAddressPhoneNumber(v) + return nil + case billinginvoice.FieldCustomerAddressCountry: + v, ok := value.(models.CountryCode) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerAddressCountry(v) + return nil + case billinginvoice.FieldCustomerAddressPostalCode: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerAddressPostalCode(v) + return nil + case billinginvoice.FieldCustomerAddressState: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerAddressState(v) + return nil + case billinginvoice.FieldCustomerAddressCity: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerAddressCity(v) + return nil + case billinginvoice.FieldCustomerAddressLine1: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerAddressLine1(v) + return nil + case billinginvoice.FieldCustomerAddressLine2: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerAddressLine2(v) + return nil + case billinginvoice.FieldCustomerAddressPhoneNumber: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerAddressPhoneNumber(v) + return nil + case billinginvoice.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 billinginvoice.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 billinginvoice.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 billinginvoice.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 billinginvoice.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 billinginvoice.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 billinginvoice.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 billinginvoice.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 billinginvoice.FieldInvoicingAppExternalID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoicingAppExternalID(v) + return nil + case billinginvoice.FieldPaymentAppExternalID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPaymentAppExternalID(v) + return nil + case billinginvoice.FieldTaxAppExternalID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxAppExternalID(v) + return nil + case billinginvoice.FieldSupplierName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSupplierName(v) + return nil + case billinginvoice.FieldSupplierTaxCode: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSupplierTaxCode(v) + return nil + case billinginvoice.FieldCustomerKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerKey(v) + return nil + case billinginvoice.FieldCustomerName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerName(v) + return nil + case billinginvoice.FieldCustomerUsageAttribution: + v, ok := value.(*billing.VersionedCustomerUsageAttribution) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerUsageAttribution(v) + return nil + case billinginvoice.FieldNumber: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNumber(v) + return nil + case billinginvoice.FieldType: + v, ok := value.(billing.InvoiceType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case billinginvoice.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case billinginvoice.FieldCustomerID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerID(v) + return nil + case billinginvoice.FieldSourceBillingProfileID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSourceBillingProfileID(v) + return nil + case billinginvoice.FieldVoidedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVoidedAt(v) + return nil + case billinginvoice.FieldIssuedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIssuedAt(v) + return nil + case billinginvoice.FieldSentToCustomerAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSentToCustomerAt(v) + return nil + case billinginvoice.FieldDraftUntil: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDraftUntil(v) + return nil + case billinginvoice.FieldQuantitySnapshotedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetQuantitySnapshotedAt(v) + return nil + case billinginvoice.FieldDeletionSource: + v, ok := value.(billing.ChangeSource) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeletionSource(v) + return nil + case billinginvoice.FieldCurrency: + v, ok := value.(currencyx.Code) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrency(v) + return nil + case billinginvoice.FieldDueAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDueAt(v) + return nil + case billinginvoice.FieldStatus: + v, ok := value.(billing.StandardInvoiceStatus) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case billinginvoice.FieldStatusDetailsCache: + v, ok := value.(billing.StandardInvoiceStatusDetails) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatusDetailsCache(v) + return nil + case billinginvoice.FieldWorkflowConfigID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetWorkflowConfigID(v) + return nil + case billinginvoice.FieldTaxAppID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxAppID(v) + return nil + case billinginvoice.FieldInvoicingAppID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoicingAppID(v) + return nil + case billinginvoice.FieldPaymentAppID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPaymentAppID(v) + return nil + case billinginvoice.FieldPeriodStart: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPeriodStart(v) + return nil + case billinginvoice.FieldPeriodEnd: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPeriodEnd(v) + return nil + case billinginvoice.FieldCollectionAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCollectionAt(v) + return nil + case billinginvoice.FieldPaymentProcessingEnteredAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPaymentProcessingEnteredAt(v) + return nil + case billinginvoice.FieldSchemaLevel: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSchemaLevel(v) + return nil + } + return fmt.Errorf("unknown BillingInvoice field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BillingInvoiceMutation) AddedFields() []string { + var fields []string + if m.addschema_level != nil { + fields = append(fields, billinginvoice.FieldSchemaLevel) + } + return fields +} + +// 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 *BillingInvoiceMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case billinginvoice.FieldSchemaLevel: + return m.AddedSchemaLevel() + } + 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 *BillingInvoiceMutation) AddField(name string, value ent.Value) error { + switch name { + case billinginvoice.FieldSchemaLevel: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddSchemaLevel(v) + return nil + } + return fmt.Errorf("unknown BillingInvoice numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BillingInvoiceMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(billinginvoice.FieldMetadata) { + fields = append(fields, billinginvoice.FieldMetadata) + } + if m.FieldCleared(billinginvoice.FieldDeletedAt) { + fields = append(fields, billinginvoice.FieldDeletedAt) + } + if m.FieldCleared(billinginvoice.FieldSupplierAddressCountry) { + fields = append(fields, billinginvoice.FieldSupplierAddressCountry) + } + if m.FieldCleared(billinginvoice.FieldSupplierAddressPostalCode) { + fields = append(fields, billinginvoice.FieldSupplierAddressPostalCode) + } + if m.FieldCleared(billinginvoice.FieldSupplierAddressState) { + fields = append(fields, billinginvoice.FieldSupplierAddressState) + } + if m.FieldCleared(billinginvoice.FieldSupplierAddressCity) { + fields = append(fields, billinginvoice.FieldSupplierAddressCity) + } + if m.FieldCleared(billinginvoice.FieldSupplierAddressLine1) { + fields = append(fields, billinginvoice.FieldSupplierAddressLine1) + } + if m.FieldCleared(billinginvoice.FieldSupplierAddressLine2) { + fields = append(fields, billinginvoice.FieldSupplierAddressLine2) + } + if m.FieldCleared(billinginvoice.FieldSupplierAddressPhoneNumber) { + fields = append(fields, billinginvoice.FieldSupplierAddressPhoneNumber) + } + if m.FieldCleared(billinginvoice.FieldCustomerAddressCountry) { + fields = append(fields, billinginvoice.FieldCustomerAddressCountry) + } + if m.FieldCleared(billinginvoice.FieldCustomerAddressPostalCode) { + fields = append(fields, billinginvoice.FieldCustomerAddressPostalCode) + } + if m.FieldCleared(billinginvoice.FieldCustomerAddressState) { + fields = append(fields, billinginvoice.FieldCustomerAddressState) + } + if m.FieldCleared(billinginvoice.FieldCustomerAddressCity) { + fields = append(fields, billinginvoice.FieldCustomerAddressCity) + } + if m.FieldCleared(billinginvoice.FieldCustomerAddressLine1) { + fields = append(fields, billinginvoice.FieldCustomerAddressLine1) + } + if m.FieldCleared(billinginvoice.FieldCustomerAddressLine2) { + fields = append(fields, billinginvoice.FieldCustomerAddressLine2) + } + if m.FieldCleared(billinginvoice.FieldCustomerAddressPhoneNumber) { + fields = append(fields, billinginvoice.FieldCustomerAddressPhoneNumber) + } + if m.FieldCleared(billinginvoice.FieldInvoicingAppExternalID) { + fields = append(fields, billinginvoice.FieldInvoicingAppExternalID) + } + if m.FieldCleared(billinginvoice.FieldPaymentAppExternalID) { + fields = append(fields, billinginvoice.FieldPaymentAppExternalID) + } + if m.FieldCleared(billinginvoice.FieldTaxAppExternalID) { + fields = append(fields, billinginvoice.FieldTaxAppExternalID) + } + if m.FieldCleared(billinginvoice.FieldSupplierTaxCode) { + fields = append(fields, billinginvoice.FieldSupplierTaxCode) + } + if m.FieldCleared(billinginvoice.FieldCustomerKey) { + fields = append(fields, billinginvoice.FieldCustomerKey) + } + if m.FieldCleared(billinginvoice.FieldCustomerUsageAttribution) { + fields = append(fields, billinginvoice.FieldCustomerUsageAttribution) + } + if m.FieldCleared(billinginvoice.FieldDescription) { + fields = append(fields, billinginvoice.FieldDescription) + } + if m.FieldCleared(billinginvoice.FieldVoidedAt) { + fields = append(fields, billinginvoice.FieldVoidedAt) + } + if m.FieldCleared(billinginvoice.FieldIssuedAt) { + fields = append(fields, billinginvoice.FieldIssuedAt) + } + if m.FieldCleared(billinginvoice.FieldSentToCustomerAt) { + fields = append(fields, billinginvoice.FieldSentToCustomerAt) + } + if m.FieldCleared(billinginvoice.FieldDraftUntil) { + fields = append(fields, billinginvoice.FieldDraftUntil) + } + if m.FieldCleared(billinginvoice.FieldQuantitySnapshotedAt) { + fields = append(fields, billinginvoice.FieldQuantitySnapshotedAt) + } + if m.FieldCleared(billinginvoice.FieldDeletionSource) { + fields = append(fields, billinginvoice.FieldDeletionSource) + } + if m.FieldCleared(billinginvoice.FieldDueAt) { + fields = append(fields, billinginvoice.FieldDueAt) + } + if m.FieldCleared(billinginvoice.FieldStatusDetailsCache) { + fields = append(fields, billinginvoice.FieldStatusDetailsCache) + } + if m.FieldCleared(billinginvoice.FieldPeriodStart) { + fields = append(fields, billinginvoice.FieldPeriodStart) + } + if m.FieldCleared(billinginvoice.FieldPeriodEnd) { + fields = append(fields, billinginvoice.FieldPeriodEnd) + } + if m.FieldCleared(billinginvoice.FieldCollectionAt) { + fields = append(fields, billinginvoice.FieldCollectionAt) + } + if m.FieldCleared(billinginvoice.FieldPaymentProcessingEnteredAt) { + fields = append(fields, billinginvoice.FieldPaymentProcessingEnteredAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BillingInvoiceMutation) 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 *BillingInvoiceMutation) ClearField(name string) error { + switch name { + case billinginvoice.FieldMetadata: + m.ClearMetadata() + return nil + case billinginvoice.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case billinginvoice.FieldSupplierAddressCountry: + m.ClearSupplierAddressCountry() + return nil + case billinginvoice.FieldSupplierAddressPostalCode: + m.ClearSupplierAddressPostalCode() + return nil + case billinginvoice.FieldSupplierAddressState: + m.ClearSupplierAddressState() + return nil + case billinginvoice.FieldSupplierAddressCity: + m.ClearSupplierAddressCity() + return nil + case billinginvoice.FieldSupplierAddressLine1: + m.ClearSupplierAddressLine1() + return nil + case billinginvoice.FieldSupplierAddressLine2: + m.ClearSupplierAddressLine2() + return nil + case billinginvoice.FieldSupplierAddressPhoneNumber: + m.ClearSupplierAddressPhoneNumber() + return nil + case billinginvoice.FieldCustomerAddressCountry: + m.ClearCustomerAddressCountry() + return nil + case billinginvoice.FieldCustomerAddressPostalCode: + m.ClearCustomerAddressPostalCode() + return nil + case billinginvoice.FieldCustomerAddressState: + m.ClearCustomerAddressState() + return nil + case billinginvoice.FieldCustomerAddressCity: + m.ClearCustomerAddressCity() + return nil + case billinginvoice.FieldCustomerAddressLine1: + m.ClearCustomerAddressLine1() + return nil + case billinginvoice.FieldCustomerAddressLine2: + m.ClearCustomerAddressLine2() + return nil + case billinginvoice.FieldCustomerAddressPhoneNumber: + m.ClearCustomerAddressPhoneNumber() + return nil + case billinginvoice.FieldInvoicingAppExternalID: + m.ClearInvoicingAppExternalID() + return nil + case billinginvoice.FieldPaymentAppExternalID: + m.ClearPaymentAppExternalID() + return nil + case billinginvoice.FieldTaxAppExternalID: + m.ClearTaxAppExternalID() + return nil + case billinginvoice.FieldSupplierTaxCode: + m.ClearSupplierTaxCode() + return nil + case billinginvoice.FieldCustomerKey: + m.ClearCustomerKey() + return nil + case billinginvoice.FieldCustomerUsageAttribution: + m.ClearCustomerUsageAttribution() + return nil + case billinginvoice.FieldDescription: + m.ClearDescription() + return nil + case billinginvoice.FieldVoidedAt: + m.ClearVoidedAt() + return nil + case billinginvoice.FieldIssuedAt: + m.ClearIssuedAt() + return nil + case billinginvoice.FieldSentToCustomerAt: + m.ClearSentToCustomerAt() + return nil + case billinginvoice.FieldDraftUntil: + m.ClearDraftUntil() + return nil + case billinginvoice.FieldQuantitySnapshotedAt: + m.ClearQuantitySnapshotedAt() + return nil + case billinginvoice.FieldDeletionSource: + m.ClearDeletionSource() + return nil + case billinginvoice.FieldDueAt: + m.ClearDueAt() + return nil + case billinginvoice.FieldStatusDetailsCache: + m.ClearStatusDetailsCache() + return nil + case billinginvoice.FieldPeriodStart: + m.ClearPeriodStart() + return nil + case billinginvoice.FieldPeriodEnd: + m.ClearPeriodEnd() + return nil + case billinginvoice.FieldCollectionAt: + m.ClearCollectionAt() + return nil + case billinginvoice.FieldPaymentProcessingEnteredAt: + m.ClearPaymentProcessingEnteredAt() + return nil + } + return fmt.Errorf("unknown BillingInvoice 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 *BillingInvoiceMutation) ResetField(name string) error { + switch name { + case billinginvoice.FieldNamespace: + m.ResetNamespace() + return nil + case billinginvoice.FieldMetadata: + m.ResetMetadata() + return nil + case billinginvoice.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case billinginvoice.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case billinginvoice.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case billinginvoice.FieldSupplierAddressCountry: + m.ResetSupplierAddressCountry() + return nil + case billinginvoice.FieldSupplierAddressPostalCode: + m.ResetSupplierAddressPostalCode() + return nil + case billinginvoice.FieldSupplierAddressState: + m.ResetSupplierAddressState() + return nil + case billinginvoice.FieldSupplierAddressCity: + m.ResetSupplierAddressCity() + return nil + case billinginvoice.FieldSupplierAddressLine1: + m.ResetSupplierAddressLine1() + return nil + case billinginvoice.FieldSupplierAddressLine2: + m.ResetSupplierAddressLine2() + return nil + case billinginvoice.FieldSupplierAddressPhoneNumber: + m.ResetSupplierAddressPhoneNumber() + return nil + case billinginvoice.FieldCustomerAddressCountry: + m.ResetCustomerAddressCountry() + return nil + case billinginvoice.FieldCustomerAddressPostalCode: + m.ResetCustomerAddressPostalCode() + return nil + case billinginvoice.FieldCustomerAddressState: + m.ResetCustomerAddressState() + return nil + case billinginvoice.FieldCustomerAddressCity: + m.ResetCustomerAddressCity() + return nil + case billinginvoice.FieldCustomerAddressLine1: + m.ResetCustomerAddressLine1() + return nil + case billinginvoice.FieldCustomerAddressLine2: + m.ResetCustomerAddressLine2() + return nil + case billinginvoice.FieldCustomerAddressPhoneNumber: + m.ResetCustomerAddressPhoneNumber() + return nil + case billinginvoice.FieldAmount: + m.ResetAmount() + return nil + case billinginvoice.FieldTaxesTotal: + m.ResetTaxesTotal() + return nil + case billinginvoice.FieldTaxesInclusiveTotal: + m.ResetTaxesInclusiveTotal() + return nil + case billinginvoice.FieldTaxesExclusiveTotal: + m.ResetTaxesExclusiveTotal() + return nil + case billinginvoice.FieldChargesTotal: + m.ResetChargesTotal() + return nil + case billinginvoice.FieldDiscountsTotal: + m.ResetDiscountsTotal() + return nil + case billinginvoice.FieldCreditsTotal: + m.ResetCreditsTotal() + return nil + case billinginvoice.FieldTotal: + m.ResetTotal() + return nil + case billinginvoice.FieldInvoicingAppExternalID: + m.ResetInvoicingAppExternalID() + return nil + case billinginvoice.FieldPaymentAppExternalID: + m.ResetPaymentAppExternalID() + return nil + case billinginvoice.FieldTaxAppExternalID: + m.ResetTaxAppExternalID() + return nil + case billinginvoice.FieldSupplierName: + m.ResetSupplierName() + return nil + case billinginvoice.FieldSupplierTaxCode: + m.ResetSupplierTaxCode() + return nil + case billinginvoice.FieldCustomerKey: + m.ResetCustomerKey() + return nil + case billinginvoice.FieldCustomerName: + m.ResetCustomerName() + return nil + case billinginvoice.FieldCustomerUsageAttribution: + m.ResetCustomerUsageAttribution() + return nil + case billinginvoice.FieldNumber: + m.ResetNumber() + return nil + case billinginvoice.FieldType: + m.ResetType() + return nil + case billinginvoice.FieldDescription: + m.ResetDescription() + return nil + case billinginvoice.FieldCustomerID: + m.ResetCustomerID() + return nil + case billinginvoice.FieldSourceBillingProfileID: + m.ResetSourceBillingProfileID() + return nil + case billinginvoice.FieldVoidedAt: + m.ResetVoidedAt() + return nil + case billinginvoice.FieldIssuedAt: + m.ResetIssuedAt() + return nil + case billinginvoice.FieldSentToCustomerAt: + m.ResetSentToCustomerAt() + return nil + case billinginvoice.FieldDraftUntil: + m.ResetDraftUntil() + return nil + case billinginvoice.FieldQuantitySnapshotedAt: + m.ResetQuantitySnapshotedAt() + return nil + case billinginvoice.FieldDeletionSource: + m.ResetDeletionSource() + return nil + case billinginvoice.FieldCurrency: + m.ResetCurrency() + return nil + case billinginvoice.FieldDueAt: + m.ResetDueAt() + return nil + case billinginvoice.FieldStatus: + m.ResetStatus() + return nil + case billinginvoice.FieldStatusDetailsCache: + m.ResetStatusDetailsCache() + return nil + case billinginvoice.FieldWorkflowConfigID: + m.ResetWorkflowConfigID() + return nil + case billinginvoice.FieldTaxAppID: + m.ResetTaxAppID() + return nil + case billinginvoice.FieldInvoicingAppID: + m.ResetInvoicingAppID() + return nil + case billinginvoice.FieldPaymentAppID: + m.ResetPaymentAppID() + return nil + case billinginvoice.FieldPeriodStart: + m.ResetPeriodStart() + return nil + case billinginvoice.FieldPeriodEnd: + m.ResetPeriodEnd() + return nil + case billinginvoice.FieldCollectionAt: + m.ResetCollectionAt() + return nil + case billinginvoice.FieldPaymentProcessingEnteredAt: + m.ResetPaymentProcessingEnteredAt() + return nil + case billinginvoice.FieldSchemaLevel: + m.ResetSchemaLevel() + return nil + } + return fmt.Errorf("unknown BillingInvoice field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BillingInvoiceMutation) AddedEdges() []string { + edges := make([]string, 0, 11) + if m.source_billing_profile != nil { + edges = append(edges, billinginvoice.EdgeSourceBillingProfile) + } + if m.billing_workflow_config != nil { + edges = append(edges, billinginvoice.EdgeBillingWorkflowConfig) + } + if m.billing_invoice_lines != nil { + edges = append(edges, billinginvoice.EdgeBillingInvoiceLines) + } + if m.billing_invoice_detailed_lines != nil { + edges = append(edges, billinginvoice.EdgeBillingInvoiceDetailedLines) + } + if m.billing_invoice_validation_issues != nil { + edges = append(edges, billinginvoice.EdgeBillingInvoiceValidationIssues) + } + if m.charge_flat_fee_runs != nil { + edges = append(edges, billinginvoice.EdgeChargeFlatFeeRuns) + } + if m.charge_usage_based_runs != nil { + edges = append(edges, billinginvoice.EdgeChargeUsageBasedRuns) + } + if m.billing_invoice_customer != nil { + edges = append(edges, billinginvoice.EdgeBillingInvoiceCustomer) + } + if m.tax_app != nil { + edges = append(edges, billinginvoice.EdgeTaxApp) + } + if m.invoicing_app != nil { + edges = append(edges, billinginvoice.EdgeInvoicingApp) + } + if m.payment_app != nil { + edges = append(edges, billinginvoice.EdgePaymentApp) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BillingInvoiceMutation) AddedIDs(name string) []ent.Value { + switch name { + case billinginvoice.EdgeSourceBillingProfile: + if id := m.source_billing_profile; id != nil { + return []ent.Value{*id} + } + case billinginvoice.EdgeBillingWorkflowConfig: + if id := m.billing_workflow_config; id != nil { + return []ent.Value{*id} + } + case billinginvoice.EdgeBillingInvoiceLines: + ids := make([]ent.Value, 0, len(m.billing_invoice_lines)) + for id := range m.billing_invoice_lines { + ids = append(ids, id) + } + return ids + case billinginvoice.EdgeBillingInvoiceDetailedLines: + ids := make([]ent.Value, 0, len(m.billing_invoice_detailed_lines)) + for id := range m.billing_invoice_detailed_lines { + ids = append(ids, id) + } + return ids + case billinginvoice.EdgeBillingInvoiceValidationIssues: + ids := make([]ent.Value, 0, len(m.billing_invoice_validation_issues)) + for id := range m.billing_invoice_validation_issues { + ids = append(ids, id) + } + return ids + case billinginvoice.EdgeChargeFlatFeeRuns: + ids := make([]ent.Value, 0, len(m.charge_flat_fee_runs)) + for id := range m.charge_flat_fee_runs { + ids = append(ids, id) + } + return ids + case billinginvoice.EdgeChargeUsageBasedRuns: + ids := make([]ent.Value, 0, len(m.charge_usage_based_runs)) + for id := range m.charge_usage_based_runs { + ids = append(ids, id) + } + return ids + case billinginvoice.EdgeBillingInvoiceCustomer: + if id := m.billing_invoice_customer; id != nil { + return []ent.Value{*id} + } + case billinginvoice.EdgeTaxApp: + if id := m.tax_app; id != nil { + return []ent.Value{*id} + } + case billinginvoice.EdgeInvoicingApp: + if id := m.invoicing_app; id != nil { + return []ent.Value{*id} + } + case billinginvoice.EdgePaymentApp: + if id := m.payment_app; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BillingInvoiceMutation) RemovedEdges() []string { + edges := make([]string, 0, 11) + if m.removedbilling_invoice_lines != nil { + edges = append(edges, billinginvoice.EdgeBillingInvoiceLines) + } + if m.removedbilling_invoice_detailed_lines != nil { + edges = append(edges, billinginvoice.EdgeBillingInvoiceDetailedLines) + } + if m.removedbilling_invoice_validation_issues != nil { + edges = append(edges, billinginvoice.EdgeBillingInvoiceValidationIssues) + } + if m.removedcharge_flat_fee_runs != nil { + edges = append(edges, billinginvoice.EdgeChargeFlatFeeRuns) + } + if m.removedcharge_usage_based_runs != nil { + edges = append(edges, billinginvoice.EdgeChargeUsageBasedRuns) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *BillingInvoiceMutation) RemovedIDs(name string) []ent.Value { + switch name { + case billinginvoice.EdgeBillingInvoiceLines: + ids := make([]ent.Value, 0, len(m.removedbilling_invoice_lines)) + for id := range m.removedbilling_invoice_lines { + ids = append(ids, id) + } + return ids + case billinginvoice.EdgeBillingInvoiceDetailedLines: + ids := make([]ent.Value, 0, len(m.removedbilling_invoice_detailed_lines)) + for id := range m.removedbilling_invoice_detailed_lines { + ids = append(ids, id) + } + return ids + case billinginvoice.EdgeBillingInvoiceValidationIssues: + ids := make([]ent.Value, 0, len(m.removedbilling_invoice_validation_issues)) + for id := range m.removedbilling_invoice_validation_issues { + ids = append(ids, id) + } + return ids + case billinginvoice.EdgeChargeFlatFeeRuns: + ids := make([]ent.Value, 0, len(m.removedcharge_flat_fee_runs)) + for id := range m.removedcharge_flat_fee_runs { + ids = append(ids, id) + } + return ids + case billinginvoice.EdgeChargeUsageBasedRuns: + ids := make([]ent.Value, 0, len(m.removedcharge_usage_based_runs)) + for id := range m.removedcharge_usage_based_runs { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BillingInvoiceMutation) ClearedEdges() []string { + edges := make([]string, 0, 11) + if m.clearedsource_billing_profile { + edges = append(edges, billinginvoice.EdgeSourceBillingProfile) + } + if m.clearedbilling_workflow_config { + edges = append(edges, billinginvoice.EdgeBillingWorkflowConfig) + } + if m.clearedbilling_invoice_lines { + edges = append(edges, billinginvoice.EdgeBillingInvoiceLines) + } + if m.clearedbilling_invoice_detailed_lines { + edges = append(edges, billinginvoice.EdgeBillingInvoiceDetailedLines) + } + if m.clearedbilling_invoice_validation_issues { + edges = append(edges, billinginvoice.EdgeBillingInvoiceValidationIssues) + } + if m.clearedcharge_flat_fee_runs { + edges = append(edges, billinginvoice.EdgeChargeFlatFeeRuns) + } + if m.clearedcharge_usage_based_runs { + edges = append(edges, billinginvoice.EdgeChargeUsageBasedRuns) + } + if m.clearedbilling_invoice_customer { + edges = append(edges, billinginvoice.EdgeBillingInvoiceCustomer) + } + if m.clearedtax_app { + edges = append(edges, billinginvoice.EdgeTaxApp) + } + if m.clearedinvoicing_app { + edges = append(edges, billinginvoice.EdgeInvoicingApp) + } + if m.clearedpayment_app { + edges = append(edges, billinginvoice.EdgePaymentApp) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BillingInvoiceMutation) EdgeCleared(name string) bool { + switch name { + case billinginvoice.EdgeSourceBillingProfile: + return m.clearedsource_billing_profile + case billinginvoice.EdgeBillingWorkflowConfig: + return m.clearedbilling_workflow_config + case billinginvoice.EdgeBillingInvoiceLines: + return m.clearedbilling_invoice_lines + case billinginvoice.EdgeBillingInvoiceDetailedLines: + return m.clearedbilling_invoice_detailed_lines + case billinginvoice.EdgeBillingInvoiceValidationIssues: + return m.clearedbilling_invoice_validation_issues + case billinginvoice.EdgeChargeFlatFeeRuns: + return m.clearedcharge_flat_fee_runs + case billinginvoice.EdgeChargeUsageBasedRuns: + return m.clearedcharge_usage_based_runs + case billinginvoice.EdgeBillingInvoiceCustomer: + return m.clearedbilling_invoice_customer + case billinginvoice.EdgeTaxApp: + return m.clearedtax_app + case billinginvoice.EdgeInvoicingApp: + return m.clearedinvoicing_app + case billinginvoice.EdgePaymentApp: + return m.clearedpayment_app + } + 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 *BillingInvoiceMutation) ClearEdge(name string) error { + switch name { + case billinginvoice.EdgeSourceBillingProfile: + m.ClearSourceBillingProfile() + return nil + case billinginvoice.EdgeBillingWorkflowConfig: + m.ClearBillingWorkflowConfig() + return nil + case billinginvoice.EdgeBillingInvoiceCustomer: + m.ClearBillingInvoiceCustomer() + return nil + case billinginvoice.EdgeTaxApp: + m.ClearTaxApp() + return nil + case billinginvoice.EdgeInvoicingApp: + m.ClearInvoicingApp() + return nil + case billinginvoice.EdgePaymentApp: + m.ClearPaymentApp() + return nil + } + return fmt.Errorf("unknown BillingInvoice 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 *BillingInvoiceMutation) ResetEdge(name string) error { + switch name { + case billinginvoice.EdgeSourceBillingProfile: + m.ResetSourceBillingProfile() + return nil + case billinginvoice.EdgeBillingWorkflowConfig: + m.ResetBillingWorkflowConfig() + return nil + case billinginvoice.EdgeBillingInvoiceLines: + m.ResetBillingInvoiceLines() + return nil + case billinginvoice.EdgeBillingInvoiceDetailedLines: + m.ResetBillingInvoiceDetailedLines() + return nil + case billinginvoice.EdgeBillingInvoiceValidationIssues: + m.ResetBillingInvoiceValidationIssues() + return nil + case billinginvoice.EdgeChargeFlatFeeRuns: + m.ResetChargeFlatFeeRuns() + return nil + case billinginvoice.EdgeChargeUsageBasedRuns: + m.ResetChargeUsageBasedRuns() + return nil + case billinginvoice.EdgeBillingInvoiceCustomer: + m.ResetBillingInvoiceCustomer() + return nil + case billinginvoice.EdgeTaxApp: + m.ResetTaxApp() + return nil + case billinginvoice.EdgeInvoicingApp: + m.ResetInvoicingApp() + return nil + case billinginvoice.EdgePaymentApp: + m.ResetPaymentApp() + return nil + } + return fmt.Errorf("unknown BillingInvoice edge %s", name) +} + +// BillingInvoiceFlatFeeLineConfigMutation represents an operation that mutates the BillingInvoiceFlatFeeLineConfig nodes in the graph. +type BillingInvoiceFlatFeeLineConfigMutation struct { + config + op Op + typ string + id *string + namespace *string + per_unit_amount *alpacadecimal.Decimal + category *stddetailedline.Category + payment_term *productcatalog.PaymentTermType + index *int + addindex *int + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*BillingInvoiceFlatFeeLineConfig, error) + predicates []predicate.BillingInvoiceFlatFeeLineConfig +} + +var _ ent.Mutation = (*BillingInvoiceFlatFeeLineConfigMutation)(nil) + +// billinginvoiceflatfeelineconfigOption allows management of the mutation configuration using functional options. +type billinginvoiceflatfeelineconfigOption func(*BillingInvoiceFlatFeeLineConfigMutation) + +// newBillingInvoiceFlatFeeLineConfigMutation creates new mutation for the BillingInvoiceFlatFeeLineConfig entity. +func newBillingInvoiceFlatFeeLineConfigMutation(c config, op Op, opts ...billinginvoiceflatfeelineconfigOption) *BillingInvoiceFlatFeeLineConfigMutation { + m := &BillingInvoiceFlatFeeLineConfigMutation{ + config: c, + op: op, + typ: TypeBillingInvoiceFlatFeeLineConfig, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBillingInvoiceFlatFeeLineConfigID sets the ID field of the mutation. +func withBillingInvoiceFlatFeeLineConfigID(id string) billinginvoiceflatfeelineconfigOption { + return func(m *BillingInvoiceFlatFeeLineConfigMutation) { + var ( + err error + once sync.Once + value *BillingInvoiceFlatFeeLineConfig + ) + m.oldValue = func(ctx context.Context) (*BillingInvoiceFlatFeeLineConfig, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().BillingInvoiceFlatFeeLineConfig.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBillingInvoiceFlatFeeLineConfig sets the old BillingInvoiceFlatFeeLineConfig of the mutation. +func withBillingInvoiceFlatFeeLineConfig(node *BillingInvoiceFlatFeeLineConfig) billinginvoiceflatfeelineconfigOption { + return func(m *BillingInvoiceFlatFeeLineConfigMutation) { + m.oldValue = func(context.Context) (*BillingInvoiceFlatFeeLineConfig, 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 BillingInvoiceFlatFeeLineConfigMutation) 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 BillingInvoiceFlatFeeLineConfigMutation) 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 BillingInvoiceFlatFeeLineConfig entities. +func (m *BillingInvoiceFlatFeeLineConfigMutation) 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 *BillingInvoiceFlatFeeLineConfigMutation) 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 *BillingInvoiceFlatFeeLineConfigMutation) 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().BillingInvoiceFlatFeeLineConfig.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 *BillingInvoiceFlatFeeLineConfigMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *BillingInvoiceFlatFeeLineConfigMutation) 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 BillingInvoiceFlatFeeLineConfig entity. +// If the BillingInvoiceFlatFeeLineConfig 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 *BillingInvoiceFlatFeeLineConfigMutation) 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 *BillingInvoiceFlatFeeLineConfigMutation) ResetNamespace() { + m.namespace = nil +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (m *BillingInvoiceFlatFeeLineConfigMutation) SetPerUnitAmount(a alpacadecimal.Decimal) { + m.per_unit_amount = &a +} + +// PerUnitAmount returns the value of the "per_unit_amount" field in the mutation. +func (m *BillingInvoiceFlatFeeLineConfigMutation) PerUnitAmount() (r alpacadecimal.Decimal, exists bool) { + v := m.per_unit_amount + if v == nil { + return + } + return *v, true +} + +// OldPerUnitAmount returns the old "per_unit_amount" field's value of the BillingInvoiceFlatFeeLineConfig entity. +// If the BillingInvoiceFlatFeeLineConfig 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 *BillingInvoiceFlatFeeLineConfigMutation) OldPerUnitAmount(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPerUnitAmount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPerUnitAmount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPerUnitAmount: %w", err) + } + return oldValue.PerUnitAmount, nil +} + +// ResetPerUnitAmount resets all changes to the "per_unit_amount" field. +func (m *BillingInvoiceFlatFeeLineConfigMutation) ResetPerUnitAmount() { + m.per_unit_amount = nil +} + +// SetCategory sets the "category" field. +func (m *BillingInvoiceFlatFeeLineConfigMutation) SetCategory(s stddetailedline.Category) { + m.category = &s +} + +// Category returns the value of the "category" field in the mutation. +func (m *BillingInvoiceFlatFeeLineConfigMutation) Category() (r stddetailedline.Category, exists bool) { + v := m.category + if v == nil { + return + } + return *v, true +} + +// OldCategory returns the old "category" field's value of the BillingInvoiceFlatFeeLineConfig entity. +// If the BillingInvoiceFlatFeeLineConfig 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 *BillingInvoiceFlatFeeLineConfigMutation) OldCategory(ctx context.Context) (v stddetailedline.Category, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCategory is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCategory requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCategory: %w", err) + } + return oldValue.Category, nil +} + +// ResetCategory resets all changes to the "category" field. +func (m *BillingInvoiceFlatFeeLineConfigMutation) ResetCategory() { + m.category = nil +} + +// SetPaymentTerm sets the "payment_term" field. +func (m *BillingInvoiceFlatFeeLineConfigMutation) SetPaymentTerm(ptt productcatalog.PaymentTermType) { + m.payment_term = &ptt +} + +// PaymentTerm returns the value of the "payment_term" field in the mutation. +func (m *BillingInvoiceFlatFeeLineConfigMutation) PaymentTerm() (r productcatalog.PaymentTermType, exists bool) { + v := m.payment_term + if v == nil { + return + } + return *v, true +} + +// OldPaymentTerm returns the old "payment_term" field's value of the BillingInvoiceFlatFeeLineConfig entity. +// If the BillingInvoiceFlatFeeLineConfig 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 *BillingInvoiceFlatFeeLineConfigMutation) OldPaymentTerm(ctx context.Context) (v productcatalog.PaymentTermType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPaymentTerm is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPaymentTerm requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPaymentTerm: %w", err) + } + return oldValue.PaymentTerm, nil +} + +// ResetPaymentTerm resets all changes to the "payment_term" field. +func (m *BillingInvoiceFlatFeeLineConfigMutation) ResetPaymentTerm() { + m.payment_term = nil +} + +// SetIndex sets the "index" field. +func (m *BillingInvoiceFlatFeeLineConfigMutation) SetIndex(i int) { + m.index = &i + m.addindex = nil +} + +// Index returns the value of the "index" field in the mutation. +func (m *BillingInvoiceFlatFeeLineConfigMutation) Index() (r int, exists bool) { + v := m.index + if v == nil { + return + } + return *v, true +} + +// OldIndex returns the old "index" field's value of the BillingInvoiceFlatFeeLineConfig entity. +// If the BillingInvoiceFlatFeeLineConfig 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 *BillingInvoiceFlatFeeLineConfigMutation) OldIndex(ctx context.Context) (v *int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIndex is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIndex requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIndex: %w", err) + } + return oldValue.Index, nil +} + +// AddIndex adds i to the "index" field. +func (m *BillingInvoiceFlatFeeLineConfigMutation) AddIndex(i int) { + if m.addindex != nil { + *m.addindex += i + } else { + m.addindex = &i + } +} + +// AddedIndex returns the value that was added to the "index" field in this mutation. +func (m *BillingInvoiceFlatFeeLineConfigMutation) AddedIndex() (r int, exists bool) { + v := m.addindex + if v == nil { + return + } + return *v, true +} + +// ClearIndex clears the value of the "index" field. +func (m *BillingInvoiceFlatFeeLineConfigMutation) ClearIndex() { + m.index = nil + m.addindex = nil + m.clearedFields[billinginvoiceflatfeelineconfig.FieldIndex] = struct{}{} +} + +// IndexCleared returns if the "index" field was cleared in this mutation. +func (m *BillingInvoiceFlatFeeLineConfigMutation) IndexCleared() bool { + _, ok := m.clearedFields[billinginvoiceflatfeelineconfig.FieldIndex] + return ok +} + +// ResetIndex resets all changes to the "index" field. +func (m *BillingInvoiceFlatFeeLineConfigMutation) ResetIndex() { + m.index = nil + m.addindex = nil + delete(m.clearedFields, billinginvoiceflatfeelineconfig.FieldIndex) +} + +// Where appends a list predicates to the BillingInvoiceFlatFeeLineConfigMutation builder. +func (m *BillingInvoiceFlatFeeLineConfigMutation) Where(ps ...predicate.BillingInvoiceFlatFeeLineConfig) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BillingInvoiceFlatFeeLineConfigMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BillingInvoiceFlatFeeLineConfigMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillingInvoiceFlatFeeLineConfig, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BillingInvoiceFlatFeeLineConfigMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BillingInvoiceFlatFeeLineConfigMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BillingInvoiceFlatFeeLineConfig). +func (m *BillingInvoiceFlatFeeLineConfigMutation) 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 *BillingInvoiceFlatFeeLineConfigMutation) Fields() []string { + fields := make([]string, 0, 5) + if m.namespace != nil { + fields = append(fields, billinginvoiceflatfeelineconfig.FieldNamespace) + } + if m.per_unit_amount != nil { + fields = append(fields, billinginvoiceflatfeelineconfig.FieldPerUnitAmount) + } + if m.category != nil { + fields = append(fields, billinginvoiceflatfeelineconfig.FieldCategory) + } + if m.payment_term != nil { + fields = append(fields, billinginvoiceflatfeelineconfig.FieldPaymentTerm) + } + if m.index != nil { + fields = append(fields, billinginvoiceflatfeelineconfig.FieldIndex) + } + 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 *BillingInvoiceFlatFeeLineConfigMutation) Field(name string) (ent.Value, bool) { + switch name { + case billinginvoiceflatfeelineconfig.FieldNamespace: + return m.Namespace() + case billinginvoiceflatfeelineconfig.FieldPerUnitAmount: + return m.PerUnitAmount() + case billinginvoiceflatfeelineconfig.FieldCategory: + return m.Category() + case billinginvoiceflatfeelineconfig.FieldPaymentTerm: + return m.PaymentTerm() + case billinginvoiceflatfeelineconfig.FieldIndex: + return m.Index() + } + 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 *BillingInvoiceFlatFeeLineConfigMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case billinginvoiceflatfeelineconfig.FieldNamespace: + return m.OldNamespace(ctx) + case billinginvoiceflatfeelineconfig.FieldPerUnitAmount: + return m.OldPerUnitAmount(ctx) + case billinginvoiceflatfeelineconfig.FieldCategory: + return m.OldCategory(ctx) + case billinginvoiceflatfeelineconfig.FieldPaymentTerm: + return m.OldPaymentTerm(ctx) + case billinginvoiceflatfeelineconfig.FieldIndex: + return m.OldIndex(ctx) + } + return nil, fmt.Errorf("unknown BillingInvoiceFlatFeeLineConfig 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 *BillingInvoiceFlatFeeLineConfigMutation) SetField(name string, value ent.Value) error { + switch name { + case billinginvoiceflatfeelineconfig.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case billinginvoiceflatfeelineconfig.FieldPerUnitAmount: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPerUnitAmount(v) + return nil + case billinginvoiceflatfeelineconfig.FieldCategory: + v, ok := value.(stddetailedline.Category) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCategory(v) + return nil + case billinginvoiceflatfeelineconfig.FieldPaymentTerm: + v, ok := value.(productcatalog.PaymentTermType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPaymentTerm(v) + return nil + case billinginvoiceflatfeelineconfig.FieldIndex: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIndex(v) + return nil + } + return fmt.Errorf("unknown BillingInvoiceFlatFeeLineConfig field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BillingInvoiceFlatFeeLineConfigMutation) AddedFields() []string { + var fields []string + if m.addindex != nil { + fields = append(fields, billinginvoiceflatfeelineconfig.FieldIndex) + } + return fields +} + +// 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 *BillingInvoiceFlatFeeLineConfigMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case billinginvoiceflatfeelineconfig.FieldIndex: + return m.AddedIndex() + } + 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 *BillingInvoiceFlatFeeLineConfigMutation) AddField(name string, value ent.Value) error { + switch name { + case billinginvoiceflatfeelineconfig.FieldIndex: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddIndex(v) + return nil + } + return fmt.Errorf("unknown BillingInvoiceFlatFeeLineConfig numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BillingInvoiceFlatFeeLineConfigMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(billinginvoiceflatfeelineconfig.FieldIndex) { + fields = append(fields, billinginvoiceflatfeelineconfig.FieldIndex) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BillingInvoiceFlatFeeLineConfigMutation) 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 *BillingInvoiceFlatFeeLineConfigMutation) ClearField(name string) error { + switch name { + case billinginvoiceflatfeelineconfig.FieldIndex: + m.ClearIndex() + return nil + } + return fmt.Errorf("unknown BillingInvoiceFlatFeeLineConfig 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 *BillingInvoiceFlatFeeLineConfigMutation) ResetField(name string) error { + switch name { + case billinginvoiceflatfeelineconfig.FieldNamespace: + m.ResetNamespace() + return nil + case billinginvoiceflatfeelineconfig.FieldPerUnitAmount: + m.ResetPerUnitAmount() + return nil + case billinginvoiceflatfeelineconfig.FieldCategory: + m.ResetCategory() + return nil + case billinginvoiceflatfeelineconfig.FieldPaymentTerm: + m.ResetPaymentTerm() + return nil + case billinginvoiceflatfeelineconfig.FieldIndex: + m.ResetIndex() + return nil + } + return fmt.Errorf("unknown BillingInvoiceFlatFeeLineConfig field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BillingInvoiceFlatFeeLineConfigMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BillingInvoiceFlatFeeLineConfigMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BillingInvoiceFlatFeeLineConfigMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *BillingInvoiceFlatFeeLineConfigMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BillingInvoiceFlatFeeLineConfigMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BillingInvoiceFlatFeeLineConfigMutation) EdgeCleared(name string) bool { + 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 *BillingInvoiceFlatFeeLineConfigMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown BillingInvoiceFlatFeeLineConfig 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 *BillingInvoiceFlatFeeLineConfigMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown BillingInvoiceFlatFeeLineConfig edge %s", name) +} + +// BillingInvoiceLineMutation represents an operation that mutates the BillingInvoiceLine nodes in the graph. +type BillingInvoiceLineMutation struct { + config + op Op + typ string + id *string + annotations *models.Annotations + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + name *string + description *string + currency *currencyx.Code + tax_config *billing.TaxConfig + tax_behavior *productcatalog.TaxBehavior + 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 + invoicing_app_external_id *string + period_start *time.Time + period_end *time.Time + managed_by *billing.InvoiceLineManagedBy + invoice_at *time.Time + override_collection_period_end *time.Time + _type *billing.InvoiceLineAdapterType + status *billing.InvoiceLineStatus + quantity *alpacadecimal.Decimal + ratecard_discounts **billing.Discounts + child_unique_reference_id *string + subscription_billing_period_from *time.Time + subscription_billing_period_to *time.Time + engine *billing.LineEngineType + credits_applied **creditsapplied.CreditsApplied + clearedFields map[string]struct{} + billing_invoice *string + clearedbilling_invoice bool + split_line_group *string + clearedsplit_line_group bool + flat_fee_line *string + clearedflat_fee_line bool + usage_based_line *string + clearedusage_based_line bool + parent_line *string + clearedparent_line bool + detailed_lines map[string]struct{} + removeddetailed_lines map[string]struct{} + cleareddetailed_lines bool + detailed_lines_v2 map[string]struct{} + removeddetailed_lines_v2 map[string]struct{} + cleareddetailed_lines_v2 bool + line_usage_discounts map[string]struct{} + removedline_usage_discounts map[string]struct{} + clearedline_usage_discounts bool + line_amount_discounts map[string]struct{} + removedline_amount_discounts map[string]struct{} + clearedline_amount_discounts bool + subscription *string + clearedsubscription bool + subscription_phase *string + clearedsubscription_phase bool + subscription_item *string + clearedsubscription_item bool + charge *string + clearedcharge bool + charge_flat_fee_run_payment *string + clearedcharge_flat_fee_run_payment bool + charge_flat_fee_run_credit_allocations map[string]struct{} + removedcharge_flat_fee_run_credit_allocations map[string]struct{} + clearedcharge_flat_fee_run_credit_allocations bool + charge_flat_fee_runs *string + clearedcharge_flat_fee_runs bool + charge_usage_based_run *string + clearedcharge_usage_based_run bool + charge_credit_purchase_invoiced_payment *string + clearedcharge_credit_purchase_invoiced_payment bool + tax_code *string + clearedtax_code bool + done bool + oldValue func(context.Context) (*BillingInvoiceLine, error) + predicates []predicate.BillingInvoiceLine +} + +var _ ent.Mutation = (*BillingInvoiceLineMutation)(nil) + +// billinginvoicelineOption allows management of the mutation configuration using functional options. +type billinginvoicelineOption func(*BillingInvoiceLineMutation) + +// newBillingInvoiceLineMutation creates new mutation for the BillingInvoiceLine entity. +func newBillingInvoiceLineMutation(c config, op Op, opts ...billinginvoicelineOption) *BillingInvoiceLineMutation { + m := &BillingInvoiceLineMutation{ + config: c, + op: op, + typ: TypeBillingInvoiceLine, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBillingInvoiceLineID sets the ID field of the mutation. +func withBillingInvoiceLineID(id string) billinginvoicelineOption { + return func(m *BillingInvoiceLineMutation) { + var ( + err error + once sync.Once + value *BillingInvoiceLine + ) + m.oldValue = func(ctx context.Context) (*BillingInvoiceLine, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().BillingInvoiceLine.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBillingInvoiceLine sets the old BillingInvoiceLine of the mutation. +func withBillingInvoiceLine(node *BillingInvoiceLine) billinginvoicelineOption { + return func(m *BillingInvoiceLineMutation) { + m.oldValue = func(context.Context) (*BillingInvoiceLine, 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 BillingInvoiceLineMutation) 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 BillingInvoiceLineMutation) 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 BillingInvoiceLine entities. +func (m *BillingInvoiceLineMutation) 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 *BillingInvoiceLineMutation) 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 *BillingInvoiceLineMutation) 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().BillingInvoiceLine.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetAnnotations sets the "annotations" field. +func (m *BillingInvoiceLineMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *BillingInvoiceLineMutation) 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 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) 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 *BillingInvoiceLineMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[billinginvoiceline.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *BillingInvoiceLineMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, billinginvoiceline.FieldAnnotations) +} + +// SetNamespace sets the "namespace" field. +func (m *BillingInvoiceLineMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *BillingInvoiceLineMutation) 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 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) 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 *BillingInvoiceLineMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *BillingInvoiceLineMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *BillingInvoiceLineMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" 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) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *BillingInvoiceLineMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[billinginvoiceline.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) MetadataCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *BillingInvoiceLineMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, billinginvoiceline.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *BillingInvoiceLineMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *BillingInvoiceLineMutation) 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 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) 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 *BillingInvoiceLineMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *BillingInvoiceLineMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *BillingInvoiceLineMutation) 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 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) 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 *BillingInvoiceLineMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *BillingInvoiceLineMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *BillingInvoiceLineMutation) 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 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) 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 *BillingInvoiceLineMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[billinginvoiceline.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *BillingInvoiceLineMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, billinginvoiceline.FieldDeletedAt) +} + +// SetName sets the "name" field. +func (m *BillingInvoiceLineMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *BillingInvoiceLineMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" 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) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *BillingInvoiceLineMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *BillingInvoiceLineMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *BillingInvoiceLineMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" 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) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *BillingInvoiceLineMutation) ClearDescription() { + m.description = nil + m.clearedFields[billinginvoiceline.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *BillingInvoiceLineMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, billinginvoiceline.FieldDescription) +} + +// SetCurrency sets the "currency" field. +func (m *BillingInvoiceLineMutation) SetCurrency(c currencyx.Code) { + m.currency = &c +} + +// Currency returns the value of the "currency" field in the mutation. +func (m *BillingInvoiceLineMutation) Currency() (r currencyx.Code, exists bool) { + v := m.currency + if v == nil { + return + } + return *v, true +} + +// OldCurrency returns the old "currency" 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) OldCurrency(ctx context.Context) (v currencyx.Code, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrency is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrency requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrency: %w", err) + } + return oldValue.Currency, nil +} + +// ResetCurrency resets all changes to the "currency" field. +func (m *BillingInvoiceLineMutation) ResetCurrency() { + m.currency = nil +} + +// SetTaxConfig sets the "tax_config" field. +func (m *BillingInvoiceLineMutation) SetTaxConfig(bc billing.TaxConfig) { + m.tax_config = &bc +} + +// TaxConfig returns the value of the "tax_config" field in the mutation. +func (m *BillingInvoiceLineMutation) TaxConfig() (r billing.TaxConfig, exists bool) { + v := m.tax_config + if v == nil { + return + } + return *v, true +} + +// OldTaxConfig returns the old "tax_config" 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) OldTaxConfig(ctx context.Context) (v billing.TaxConfig, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxConfig is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxConfig requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxConfig: %w", err) + } + return oldValue.TaxConfig, nil +} + +// ClearTaxConfig clears the value of the "tax_config" field. +func (m *BillingInvoiceLineMutation) ClearTaxConfig() { + m.tax_config = nil + m.clearedFields[billinginvoiceline.FieldTaxConfig] = struct{}{} +} + +// TaxConfigCleared returns if the "tax_config" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) TaxConfigCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldTaxConfig] + return ok +} + +// ResetTaxConfig resets all changes to the "tax_config" field. +func (m *BillingInvoiceLineMutation) ResetTaxConfig() { + m.tax_config = nil + delete(m.clearedFields, billinginvoiceline.FieldTaxConfig) +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (m *BillingInvoiceLineMutation) SetTaxCodeID(s string) { + m.tax_code = &s +} + +// TaxCodeID returns the value of the "tax_code_id" field in the mutation. +func (m *BillingInvoiceLineMutation) TaxCodeID() (r string, exists bool) { + v := m.tax_code + if v == nil { + return + } + return *v, true +} + +// OldTaxCodeID returns the old "tax_code_id" 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) OldTaxCodeID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxCodeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxCodeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxCodeID: %w", err) + } + return oldValue.TaxCodeID, nil +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (m *BillingInvoiceLineMutation) ClearTaxCodeID() { + m.tax_code = nil + m.clearedFields[billinginvoiceline.FieldTaxCodeID] = struct{}{} +} + +// TaxCodeIDCleared returns if the "tax_code_id" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) TaxCodeIDCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldTaxCodeID] + return ok +} + +// ResetTaxCodeID resets all changes to the "tax_code_id" field. +func (m *BillingInvoiceLineMutation) ResetTaxCodeID() { + m.tax_code = nil + delete(m.clearedFields, billinginvoiceline.FieldTaxCodeID) +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (m *BillingInvoiceLineMutation) SetTaxBehavior(pb productcatalog.TaxBehavior) { + m.tax_behavior = &pb +} + +// TaxBehavior returns the value of the "tax_behavior" field in the mutation. +func (m *BillingInvoiceLineMutation) TaxBehavior() (r productcatalog.TaxBehavior, exists bool) { + v := m.tax_behavior + if v == nil { + return + } + return *v, true +} + +// OldTaxBehavior returns the old "tax_behavior" 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) OldTaxBehavior(ctx context.Context) (v *productcatalog.TaxBehavior, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxBehavior is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxBehavior requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxBehavior: %w", err) + } + return oldValue.TaxBehavior, nil +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (m *BillingInvoiceLineMutation) ClearTaxBehavior() { + m.tax_behavior = nil + m.clearedFields[billinginvoiceline.FieldTaxBehavior] = struct{}{} +} + +// TaxBehaviorCleared returns if the "tax_behavior" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) TaxBehaviorCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldTaxBehavior] + return ok +} + +// ResetTaxBehavior resets all changes to the "tax_behavior" field. +func (m *BillingInvoiceLineMutation) ResetTaxBehavior() { + m.tax_behavior = nil + delete(m.clearedFields, billinginvoiceline.FieldTaxBehavior) +} + +// SetAmount sets the "amount" field. +func (m *BillingInvoiceLineMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *BillingInvoiceLineMutation) 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 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) 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 *BillingInvoiceLineMutation) ResetAmount() { + m.amount = nil +} + +// SetTaxesTotal sets the "taxes_total" field. +func (m *BillingInvoiceLineMutation) SetTaxesTotal(a alpacadecimal.Decimal) { + m.taxes_total = &a +} + +// TaxesTotal returns the value of the "taxes_total" field in the mutation. +func (m *BillingInvoiceLineMutation) 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 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) 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 *BillingInvoiceLineMutation) ResetTaxesTotal() { + m.taxes_total = nil +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (m *BillingInvoiceLineMutation) SetTaxesInclusiveTotal(a alpacadecimal.Decimal) { + m.taxes_inclusive_total = &a +} + +// TaxesInclusiveTotal returns the value of the "taxes_inclusive_total" field in the mutation. +func (m *BillingInvoiceLineMutation) 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 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) 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 *BillingInvoiceLineMutation) ResetTaxesInclusiveTotal() { + m.taxes_inclusive_total = nil +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (m *BillingInvoiceLineMutation) SetTaxesExclusiveTotal(a alpacadecimal.Decimal) { + m.taxes_exclusive_total = &a +} + +// TaxesExclusiveTotal returns the value of the "taxes_exclusive_total" field in the mutation. +func (m *BillingInvoiceLineMutation) 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 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) 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 *BillingInvoiceLineMutation) ResetTaxesExclusiveTotal() { + m.taxes_exclusive_total = nil +} + +// SetChargesTotal sets the "charges_total" field. +func (m *BillingInvoiceLineMutation) SetChargesTotal(a alpacadecimal.Decimal) { + m.charges_total = &a +} + +// ChargesTotal returns the value of the "charges_total" field in the mutation. +func (m *BillingInvoiceLineMutation) 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 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) 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 *BillingInvoiceLineMutation) ResetChargesTotal() { + m.charges_total = nil +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (m *BillingInvoiceLineMutation) SetDiscountsTotal(a alpacadecimal.Decimal) { + m.discounts_total = &a +} + +// DiscountsTotal returns the value of the "discounts_total" field in the mutation. +func (m *BillingInvoiceLineMutation) 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 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) 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 *BillingInvoiceLineMutation) ResetDiscountsTotal() { + m.discounts_total = nil +} + +// SetCreditsTotal sets the "credits_total" field. +func (m *BillingInvoiceLineMutation) SetCreditsTotal(a alpacadecimal.Decimal) { + m.credits_total = &a +} + +// CreditsTotal returns the value of the "credits_total" field in the mutation. +func (m *BillingInvoiceLineMutation) 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 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) 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 *BillingInvoiceLineMutation) ResetCreditsTotal() { + m.credits_total = nil +} + +// SetTotal sets the "total" field. +func (m *BillingInvoiceLineMutation) SetTotal(a alpacadecimal.Decimal) { + m.total = &a +} + +// Total returns the value of the "total" field in the mutation. +func (m *BillingInvoiceLineMutation) 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 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) 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 *BillingInvoiceLineMutation) ResetTotal() { + m.total = nil +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (m *BillingInvoiceLineMutation) SetInvoicingAppExternalID(s string) { + m.invoicing_app_external_id = &s +} + +// InvoicingAppExternalID returns the value of the "invoicing_app_external_id" field in the mutation. +func (m *BillingInvoiceLineMutation) InvoicingAppExternalID() (r string, exists bool) { + v := m.invoicing_app_external_id + if v == nil { + return + } + return *v, true +} + +// OldInvoicingAppExternalID returns the old "invoicing_app_external_id" 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) OldInvoicingAppExternalID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoicingAppExternalID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoicingAppExternalID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoicingAppExternalID: %w", err) + } + return oldValue.InvoicingAppExternalID, nil +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (m *BillingInvoiceLineMutation) ClearInvoicingAppExternalID() { + m.invoicing_app_external_id = nil + m.clearedFields[billinginvoiceline.FieldInvoicingAppExternalID] = struct{}{} +} + +// InvoicingAppExternalIDCleared returns if the "invoicing_app_external_id" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) InvoicingAppExternalIDCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldInvoicingAppExternalID] + return ok +} + +// ResetInvoicingAppExternalID resets all changes to the "invoicing_app_external_id" field. +func (m *BillingInvoiceLineMutation) ResetInvoicingAppExternalID() { + m.invoicing_app_external_id = nil + delete(m.clearedFields, billinginvoiceline.FieldInvoicingAppExternalID) +} + +// SetPeriodStart sets the "period_start" field. +func (m *BillingInvoiceLineMutation) SetPeriodStart(t time.Time) { + m.period_start = &t +} + +// PeriodStart returns the value of the "period_start" field in the mutation. +func (m *BillingInvoiceLineMutation) PeriodStart() (r time.Time, exists bool) { + v := m.period_start + if v == nil { + return + } + return *v, true +} + +// OldPeriodStart returns the old "period_start" 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) OldPeriodStart(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPeriodStart is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPeriodStart requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPeriodStart: %w", err) + } + return oldValue.PeriodStart, nil +} + +// ResetPeriodStart resets all changes to the "period_start" field. +func (m *BillingInvoiceLineMutation) ResetPeriodStart() { + m.period_start = nil +} + +// SetPeriodEnd sets the "period_end" field. +func (m *BillingInvoiceLineMutation) SetPeriodEnd(t time.Time) { + m.period_end = &t +} + +// PeriodEnd returns the value of the "period_end" field in the mutation. +func (m *BillingInvoiceLineMutation) PeriodEnd() (r time.Time, exists bool) { + v := m.period_end + if v == nil { + return + } + return *v, true +} + +// OldPeriodEnd returns the old "period_end" 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) OldPeriodEnd(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPeriodEnd is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPeriodEnd requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPeriodEnd: %w", err) + } + return oldValue.PeriodEnd, nil +} + +// ResetPeriodEnd resets all changes to the "period_end" field. +func (m *BillingInvoiceLineMutation) ResetPeriodEnd() { + m.period_end = nil +} + +// SetInvoiceID sets the "invoice_id" field. +func (m *BillingInvoiceLineMutation) SetInvoiceID(s string) { + m.billing_invoice = &s +} + +// InvoiceID returns the value of the "invoice_id" field in the mutation. +func (m *BillingInvoiceLineMutation) InvoiceID() (r string, exists bool) { + v := m.billing_invoice + if v == nil { + return + } + return *v, true +} + +// OldInvoiceID returns the old "invoice_id" 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) OldInvoiceID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceID: %w", err) + } + return oldValue.InvoiceID, nil +} + +// ResetInvoiceID resets all changes to the "invoice_id" field. +func (m *BillingInvoiceLineMutation) ResetInvoiceID() { + m.billing_invoice = nil +} + +// SetManagedBy sets the "managed_by" field. +func (m *BillingInvoiceLineMutation) SetManagedBy(blmb billing.InvoiceLineManagedBy) { + m.managed_by = &blmb +} + +// ManagedBy returns the value of the "managed_by" field in the mutation. +func (m *BillingInvoiceLineMutation) ManagedBy() (r billing.InvoiceLineManagedBy, exists bool) { + v := m.managed_by + if v == nil { + return + } + return *v, true +} + +// OldManagedBy returns the old "managed_by" 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) OldManagedBy(ctx context.Context) (v billing.InvoiceLineManagedBy, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldManagedBy is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldManagedBy requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldManagedBy: %w", err) + } + return oldValue.ManagedBy, nil +} + +// ResetManagedBy resets all changes to the "managed_by" field. +func (m *BillingInvoiceLineMutation) ResetManagedBy() { + m.managed_by = nil +} + +// SetParentLineID sets the "parent_line_id" field. +func (m *BillingInvoiceLineMutation) SetParentLineID(s string) { + m.parent_line = &s +} + +// ParentLineID returns the value of the "parent_line_id" field in the mutation. +func (m *BillingInvoiceLineMutation) ParentLineID() (r string, exists bool) { + v := m.parent_line + if v == nil { + return + } + return *v, true +} + +// OldParentLineID returns the old "parent_line_id" 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) OldParentLineID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldParentLineID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldParentLineID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldParentLineID: %w", err) + } + return oldValue.ParentLineID, nil +} + +// ClearParentLineID clears the value of the "parent_line_id" field. +func (m *BillingInvoiceLineMutation) ClearParentLineID() { + m.parent_line = nil + m.clearedFields[billinginvoiceline.FieldParentLineID] = struct{}{} +} + +// ParentLineIDCleared returns if the "parent_line_id" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) ParentLineIDCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldParentLineID] + return ok +} + +// ResetParentLineID resets all changes to the "parent_line_id" field. +func (m *BillingInvoiceLineMutation) ResetParentLineID() { + m.parent_line = nil + delete(m.clearedFields, billinginvoiceline.FieldParentLineID) +} + +// SetInvoiceAt sets the "invoice_at" field. +func (m *BillingInvoiceLineMutation) SetInvoiceAt(t time.Time) { + m.invoice_at = &t +} + +// InvoiceAt returns the value of the "invoice_at" field in the mutation. +func (m *BillingInvoiceLineMutation) 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 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) 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 *BillingInvoiceLineMutation) ResetInvoiceAt() { + m.invoice_at = nil +} + +// SetOverrideCollectionPeriodEnd sets the "override_collection_period_end" field. +func (m *BillingInvoiceLineMutation) SetOverrideCollectionPeriodEnd(t time.Time) { + m.override_collection_period_end = &t +} + +// OverrideCollectionPeriodEnd returns the value of the "override_collection_period_end" field in the mutation. +func (m *BillingInvoiceLineMutation) OverrideCollectionPeriodEnd() (r time.Time, exists bool) { + v := m.override_collection_period_end + if v == nil { + return + } + return *v, true +} + +// OldOverrideCollectionPeriodEnd returns the old "override_collection_period_end" 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) OldOverrideCollectionPeriodEnd(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOverrideCollectionPeriodEnd is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOverrideCollectionPeriodEnd requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOverrideCollectionPeriodEnd: %w", err) + } + return oldValue.OverrideCollectionPeriodEnd, nil +} + +// ClearOverrideCollectionPeriodEnd clears the value of the "override_collection_period_end" field. +func (m *BillingInvoiceLineMutation) ClearOverrideCollectionPeriodEnd() { + m.override_collection_period_end = nil + m.clearedFields[billinginvoiceline.FieldOverrideCollectionPeriodEnd] = struct{}{} +} + +// OverrideCollectionPeriodEndCleared returns if the "override_collection_period_end" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) OverrideCollectionPeriodEndCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldOverrideCollectionPeriodEnd] + return ok +} + +// ResetOverrideCollectionPeriodEnd resets all changes to the "override_collection_period_end" field. +func (m *BillingInvoiceLineMutation) ResetOverrideCollectionPeriodEnd() { + m.override_collection_period_end = nil + delete(m.clearedFields, billinginvoiceline.FieldOverrideCollectionPeriodEnd) +} + +// SetType sets the "type" field. +func (m *BillingInvoiceLineMutation) SetType(blat billing.InvoiceLineAdapterType) { + m._type = &blat +} + +// GetType returns the value of the "type" field in the mutation. +func (m *BillingInvoiceLineMutation) GetType() (r billing.InvoiceLineAdapterType, exists bool) { + v := m._type + if v == nil { + return + } + return *v, true +} + +// OldType returns the old "type" 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) OldType(ctx context.Context) (v billing.InvoiceLineAdapterType, 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 *BillingInvoiceLineMutation) ResetType() { + m._type = nil +} + +// SetStatus sets the "status" field. +func (m *BillingInvoiceLineMutation) SetStatus(bls billing.InvoiceLineStatus) { + m.status = &bls +} + +// Status returns the value of the "status" field in the mutation. +func (m *BillingInvoiceLineMutation) Status() (r billing.InvoiceLineStatus, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true +} + +// OldStatus returns the old "status" 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) OldStatus(ctx context.Context) (v billing.InvoiceLineStatus, 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 *BillingInvoiceLineMutation) ResetStatus() { + m.status = nil +} + +// SetQuantity sets the "quantity" field. +func (m *BillingInvoiceLineMutation) SetQuantity(a alpacadecimal.Decimal) { + m.quantity = &a +} + +// Quantity returns the value of the "quantity" field in the mutation. +func (m *BillingInvoiceLineMutation) Quantity() (r alpacadecimal.Decimal, exists bool) { + v := m.quantity + if v == nil { + return + } + return *v, true +} + +// OldQuantity returns the old "quantity" 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) OldQuantity(ctx context.Context) (v *alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldQuantity is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldQuantity requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldQuantity: %w", err) + } + return oldValue.Quantity, nil +} + +// ClearQuantity clears the value of the "quantity" field. +func (m *BillingInvoiceLineMutation) ClearQuantity() { + m.quantity = nil + m.clearedFields[billinginvoiceline.FieldQuantity] = struct{}{} +} + +// QuantityCleared returns if the "quantity" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) QuantityCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldQuantity] + return ok +} + +// ResetQuantity resets all changes to the "quantity" field. +func (m *BillingInvoiceLineMutation) ResetQuantity() { + m.quantity = nil + delete(m.clearedFields, billinginvoiceline.FieldQuantity) +} + +// SetRatecardDiscounts sets the "ratecard_discounts" field. +func (m *BillingInvoiceLineMutation) SetRatecardDiscounts(b *billing.Discounts) { + m.ratecard_discounts = &b +} + +// RatecardDiscounts returns the value of the "ratecard_discounts" field in the mutation. +func (m *BillingInvoiceLineMutation) RatecardDiscounts() (r *billing.Discounts, exists bool) { + v := m.ratecard_discounts + if v == nil { + return + } + return *v, true +} + +// OldRatecardDiscounts returns the old "ratecard_discounts" 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) OldRatecardDiscounts(ctx context.Context) (v *billing.Discounts, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRatecardDiscounts is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRatecardDiscounts requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRatecardDiscounts: %w", err) + } + return oldValue.RatecardDiscounts, nil +} + +// ClearRatecardDiscounts clears the value of the "ratecard_discounts" field. +func (m *BillingInvoiceLineMutation) ClearRatecardDiscounts() { + m.ratecard_discounts = nil + m.clearedFields[billinginvoiceline.FieldRatecardDiscounts] = struct{}{} +} + +// RatecardDiscountsCleared returns if the "ratecard_discounts" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) RatecardDiscountsCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldRatecardDiscounts] + return ok +} + +// ResetRatecardDiscounts resets all changes to the "ratecard_discounts" field. +func (m *BillingInvoiceLineMutation) ResetRatecardDiscounts() { + m.ratecard_discounts = nil + delete(m.clearedFields, billinginvoiceline.FieldRatecardDiscounts) +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (m *BillingInvoiceLineMutation) SetChildUniqueReferenceID(s string) { + m.child_unique_reference_id = &s +} + +// ChildUniqueReferenceID returns the value of the "child_unique_reference_id" field in the mutation. +func (m *BillingInvoiceLineMutation) ChildUniqueReferenceID() (r string, exists bool) { + v := m.child_unique_reference_id + if v == nil { + return + } + return *v, true +} + +// OldChildUniqueReferenceID returns the old "child_unique_reference_id" 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) OldChildUniqueReferenceID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldChildUniqueReferenceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldChildUniqueReferenceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldChildUniqueReferenceID: %w", err) + } + return oldValue.ChildUniqueReferenceID, nil +} + +// ClearChildUniqueReferenceID clears the value of the "child_unique_reference_id" field. +func (m *BillingInvoiceLineMutation) ClearChildUniqueReferenceID() { + m.child_unique_reference_id = nil + m.clearedFields[billinginvoiceline.FieldChildUniqueReferenceID] = struct{}{} +} + +// ChildUniqueReferenceIDCleared returns if the "child_unique_reference_id" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) ChildUniqueReferenceIDCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldChildUniqueReferenceID] + return ok +} + +// ResetChildUniqueReferenceID resets all changes to the "child_unique_reference_id" field. +func (m *BillingInvoiceLineMutation) ResetChildUniqueReferenceID() { + m.child_unique_reference_id = nil + delete(m.clearedFields, billinginvoiceline.FieldChildUniqueReferenceID) +} + +// SetSubscriptionID sets the "subscription_id" field. +func (m *BillingInvoiceLineMutation) SetSubscriptionID(s string) { + m.subscription = &s +} + +// SubscriptionID returns the value of the "subscription_id" field in the mutation. +func (m *BillingInvoiceLineMutation) SubscriptionID() (r string, exists bool) { + v := m.subscription + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionID returns the old "subscription_id" 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) OldSubscriptionID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionID: %w", err) + } + return oldValue.SubscriptionID, nil +} + +// ClearSubscriptionID clears the value of the "subscription_id" field. +func (m *BillingInvoiceLineMutation) ClearSubscriptionID() { + m.subscription = nil + m.clearedFields[billinginvoiceline.FieldSubscriptionID] = struct{}{} +} + +// SubscriptionIDCleared returns if the "subscription_id" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) SubscriptionIDCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldSubscriptionID] + return ok +} + +// ResetSubscriptionID resets all changes to the "subscription_id" field. +func (m *BillingInvoiceLineMutation) ResetSubscriptionID() { + m.subscription = nil + delete(m.clearedFields, billinginvoiceline.FieldSubscriptionID) +} + +// SetSubscriptionPhaseID sets the "subscription_phase_id" field. +func (m *BillingInvoiceLineMutation) SetSubscriptionPhaseID(s string) { + m.subscription_phase = &s +} + +// SubscriptionPhaseID returns the value of the "subscription_phase_id" field in the mutation. +func (m *BillingInvoiceLineMutation) SubscriptionPhaseID() (r string, exists bool) { + v := m.subscription_phase + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionPhaseID returns the old "subscription_phase_id" 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) OldSubscriptionPhaseID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionPhaseID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionPhaseID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionPhaseID: %w", err) + } + return oldValue.SubscriptionPhaseID, nil +} + +// ClearSubscriptionPhaseID clears the value of the "subscription_phase_id" field. +func (m *BillingInvoiceLineMutation) ClearSubscriptionPhaseID() { + m.subscription_phase = nil + m.clearedFields[billinginvoiceline.FieldSubscriptionPhaseID] = struct{}{} +} + +// SubscriptionPhaseIDCleared returns if the "subscription_phase_id" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) SubscriptionPhaseIDCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldSubscriptionPhaseID] + return ok +} + +// ResetSubscriptionPhaseID resets all changes to the "subscription_phase_id" field. +func (m *BillingInvoiceLineMutation) ResetSubscriptionPhaseID() { + m.subscription_phase = nil + delete(m.clearedFields, billinginvoiceline.FieldSubscriptionPhaseID) +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (m *BillingInvoiceLineMutation) SetSubscriptionItemID(s string) { + m.subscription_item = &s +} + +// SubscriptionItemID returns the value of the "subscription_item_id" field in the mutation. +func (m *BillingInvoiceLineMutation) SubscriptionItemID() (r string, exists bool) { + v := m.subscription_item + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionItemID returns the old "subscription_item_id" 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) OldSubscriptionItemID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionItemID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionItemID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionItemID: %w", err) + } + return oldValue.SubscriptionItemID, nil +} + +// ClearSubscriptionItemID clears the value of the "subscription_item_id" field. +func (m *BillingInvoiceLineMutation) ClearSubscriptionItemID() { + m.subscription_item = nil + m.clearedFields[billinginvoiceline.FieldSubscriptionItemID] = struct{}{} +} + +// SubscriptionItemIDCleared returns if the "subscription_item_id" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) SubscriptionItemIDCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldSubscriptionItemID] + return ok +} + +// ResetSubscriptionItemID resets all changes to the "subscription_item_id" field. +func (m *BillingInvoiceLineMutation) ResetSubscriptionItemID() { + m.subscription_item = nil + delete(m.clearedFields, billinginvoiceline.FieldSubscriptionItemID) +} + +// SetSubscriptionBillingPeriodFrom sets the "subscription_billing_period_from" field. +func (m *BillingInvoiceLineMutation) SetSubscriptionBillingPeriodFrom(t time.Time) { + m.subscription_billing_period_from = &t +} + +// SubscriptionBillingPeriodFrom returns the value of the "subscription_billing_period_from" field in the mutation. +func (m *BillingInvoiceLineMutation) SubscriptionBillingPeriodFrom() (r time.Time, exists bool) { + v := m.subscription_billing_period_from + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionBillingPeriodFrom returns the old "subscription_billing_period_from" 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) OldSubscriptionBillingPeriodFrom(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionBillingPeriodFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionBillingPeriodFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionBillingPeriodFrom: %w", err) + } + return oldValue.SubscriptionBillingPeriodFrom, nil +} + +// ClearSubscriptionBillingPeriodFrom clears the value of the "subscription_billing_period_from" field. +func (m *BillingInvoiceLineMutation) ClearSubscriptionBillingPeriodFrom() { + m.subscription_billing_period_from = nil + m.clearedFields[billinginvoiceline.FieldSubscriptionBillingPeriodFrom] = struct{}{} +} + +// SubscriptionBillingPeriodFromCleared returns if the "subscription_billing_period_from" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) SubscriptionBillingPeriodFromCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldSubscriptionBillingPeriodFrom] + return ok +} + +// ResetSubscriptionBillingPeriodFrom resets all changes to the "subscription_billing_period_from" field. +func (m *BillingInvoiceLineMutation) ResetSubscriptionBillingPeriodFrom() { + m.subscription_billing_period_from = nil + delete(m.clearedFields, billinginvoiceline.FieldSubscriptionBillingPeriodFrom) +} + +// SetSubscriptionBillingPeriodTo sets the "subscription_billing_period_to" field. +func (m *BillingInvoiceLineMutation) SetSubscriptionBillingPeriodTo(t time.Time) { + m.subscription_billing_period_to = &t +} + +// SubscriptionBillingPeriodTo returns the value of the "subscription_billing_period_to" field in the mutation. +func (m *BillingInvoiceLineMutation) SubscriptionBillingPeriodTo() (r time.Time, exists bool) { + v := m.subscription_billing_period_to + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionBillingPeriodTo returns the old "subscription_billing_period_to" 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) OldSubscriptionBillingPeriodTo(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionBillingPeriodTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionBillingPeriodTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionBillingPeriodTo: %w", err) + } + return oldValue.SubscriptionBillingPeriodTo, nil +} + +// ClearSubscriptionBillingPeriodTo clears the value of the "subscription_billing_period_to" field. +func (m *BillingInvoiceLineMutation) ClearSubscriptionBillingPeriodTo() { + m.subscription_billing_period_to = nil + m.clearedFields[billinginvoiceline.FieldSubscriptionBillingPeriodTo] = struct{}{} +} + +// SubscriptionBillingPeriodToCleared returns if the "subscription_billing_period_to" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) SubscriptionBillingPeriodToCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldSubscriptionBillingPeriodTo] + return ok +} + +// ResetSubscriptionBillingPeriodTo resets all changes to the "subscription_billing_period_to" field. +func (m *BillingInvoiceLineMutation) ResetSubscriptionBillingPeriodTo() { + m.subscription_billing_period_to = nil + delete(m.clearedFields, billinginvoiceline.FieldSubscriptionBillingPeriodTo) +} + +// SetSplitLineGroupID sets the "split_line_group_id" field. +func (m *BillingInvoiceLineMutation) SetSplitLineGroupID(s string) { + m.split_line_group = &s +} + +// SplitLineGroupID returns the value of the "split_line_group_id" field in the mutation. +func (m *BillingInvoiceLineMutation) SplitLineGroupID() (r string, exists bool) { + v := m.split_line_group + if v == nil { + return + } + return *v, true +} + +// OldSplitLineGroupID returns the old "split_line_group_id" 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) OldSplitLineGroupID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSplitLineGroupID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSplitLineGroupID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSplitLineGroupID: %w", err) + } + return oldValue.SplitLineGroupID, nil +} + +// ClearSplitLineGroupID clears the value of the "split_line_group_id" field. +func (m *BillingInvoiceLineMutation) ClearSplitLineGroupID() { + m.split_line_group = nil + m.clearedFields[billinginvoiceline.FieldSplitLineGroupID] = struct{}{} +} + +// SplitLineGroupIDCleared returns if the "split_line_group_id" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) SplitLineGroupIDCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldSplitLineGroupID] + return ok +} + +// ResetSplitLineGroupID resets all changes to the "split_line_group_id" field. +func (m *BillingInvoiceLineMutation) ResetSplitLineGroupID() { + m.split_line_group = nil + delete(m.clearedFields, billinginvoiceline.FieldSplitLineGroupID) +} + +// SetChargeID sets the "charge_id" field. +func (m *BillingInvoiceLineMutation) SetChargeID(s string) { + m.charge = &s +} + +// ChargeID returns the value of the "charge_id" field in the mutation. +func (m *BillingInvoiceLineMutation) ChargeID() (r string, exists bool) { + v := m.charge + if v == nil { + return + } + return *v, true +} + +// OldChargeID returns the old "charge_id" 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) 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 +} + +// ClearChargeID clears the value of the "charge_id" field. +func (m *BillingInvoiceLineMutation) ClearChargeID() { + m.charge = nil + m.clearedFields[billinginvoiceline.FieldChargeID] = struct{}{} +} + +// ChargeIDCleared returns if the "charge_id" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) ChargeIDCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldChargeID] + return ok +} + +// ResetChargeID resets all changes to the "charge_id" field. +func (m *BillingInvoiceLineMutation) ResetChargeID() { + m.charge = nil + delete(m.clearedFields, billinginvoiceline.FieldChargeID) +} + +// SetEngine sets the "engine" field. +func (m *BillingInvoiceLineMutation) SetEngine(bet billing.LineEngineType) { + m.engine = &bet +} + +// Engine returns the value of the "engine" field in the mutation. +func (m *BillingInvoiceLineMutation) Engine() (r billing.LineEngineType, exists bool) { + v := m.engine + if v == nil { + return + } + return *v, true +} + +// OldEngine returns the old "engine" 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) OldEngine(ctx context.Context) (v billing.LineEngineType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEngine is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEngine requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEngine: %w", err) + } + return oldValue.Engine, nil +} + +// ResetEngine resets all changes to the "engine" field. +func (m *BillingInvoiceLineMutation) ResetEngine() { + m.engine = nil +} + +// SetCreditsApplied sets the "credits_applied" field. +func (m *BillingInvoiceLineMutation) SetCreditsApplied(ca *creditsapplied.CreditsApplied) { + m.credits_applied = &ca +} + +// CreditsApplied returns the value of the "credits_applied" field in the mutation. +func (m *BillingInvoiceLineMutation) CreditsApplied() (r *creditsapplied.CreditsApplied, exists bool) { + v := m.credits_applied + if v == nil { + return + } + return *v, true +} + +// OldCreditsApplied returns the old "credits_applied" 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) OldCreditsApplied(ctx context.Context) (v *creditsapplied.CreditsApplied, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreditsApplied is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreditsApplied requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreditsApplied: %w", err) + } + return oldValue.CreditsApplied, nil +} + +// ClearCreditsApplied clears the value of the "credits_applied" field. +func (m *BillingInvoiceLineMutation) ClearCreditsApplied() { + m.credits_applied = nil + m.clearedFields[billinginvoiceline.FieldCreditsApplied] = struct{}{} +} + +// CreditsAppliedCleared returns if the "credits_applied" field was cleared in this mutation. +func (m *BillingInvoiceLineMutation) CreditsAppliedCleared() bool { + _, ok := m.clearedFields[billinginvoiceline.FieldCreditsApplied] + return ok +} + +// ResetCreditsApplied resets all changes to the "credits_applied" field. +func (m *BillingInvoiceLineMutation) ResetCreditsApplied() { + m.credits_applied = nil + delete(m.clearedFields, billinginvoiceline.FieldCreditsApplied) +} + +// SetBillingInvoiceID sets the "billing_invoice" edge to the BillingInvoice entity by id. +func (m *BillingInvoiceLineMutation) SetBillingInvoiceID(id string) { + m.billing_invoice = &id +} + +// ClearBillingInvoice clears the "billing_invoice" edge to the BillingInvoice entity. +func (m *BillingInvoiceLineMutation) ClearBillingInvoice() { + m.clearedbilling_invoice = true + m.clearedFields[billinginvoiceline.FieldInvoiceID] = struct{}{} +} + +// BillingInvoiceCleared reports if the "billing_invoice" edge to the BillingInvoice entity was cleared. +func (m *BillingInvoiceLineMutation) BillingInvoiceCleared() bool { + return m.clearedbilling_invoice +} + +// BillingInvoiceID returns the "billing_invoice" edge ID in the mutation. +func (m *BillingInvoiceLineMutation) BillingInvoiceID() (id string, exists bool) { + if m.billing_invoice != nil { + return *m.billing_invoice, true + } + return +} + +// BillingInvoiceIDs returns the "billing_invoice" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BillingInvoiceID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceLineMutation) BillingInvoiceIDs() (ids []string) { + if id := m.billing_invoice; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBillingInvoice resets all changes to the "billing_invoice" edge. +func (m *BillingInvoiceLineMutation) ResetBillingInvoice() { + m.billing_invoice = nil + m.clearedbilling_invoice = false +} + +// ClearSplitLineGroup clears the "split_line_group" edge to the BillingInvoiceSplitLineGroup entity. +func (m *BillingInvoiceLineMutation) ClearSplitLineGroup() { + m.clearedsplit_line_group = true + m.clearedFields[billinginvoiceline.FieldSplitLineGroupID] = struct{}{} +} + +// SplitLineGroupCleared reports if the "split_line_group" edge to the BillingInvoiceSplitLineGroup entity was cleared. +func (m *BillingInvoiceLineMutation) SplitLineGroupCleared() bool { + return m.SplitLineGroupIDCleared() || m.clearedsplit_line_group +} + +// SplitLineGroupIDs returns the "split_line_group" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SplitLineGroupID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceLineMutation) SplitLineGroupIDs() (ids []string) { + if id := m.split_line_group; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSplitLineGroup resets all changes to the "split_line_group" edge. +func (m *BillingInvoiceLineMutation) ResetSplitLineGroup() { + m.split_line_group = nil + m.clearedsplit_line_group = false +} + +// SetFlatFeeLineID sets the "flat_fee_line" edge to the BillingInvoiceFlatFeeLineConfig entity by id. +func (m *BillingInvoiceLineMutation) SetFlatFeeLineID(id string) { + m.flat_fee_line = &id +} + +// ClearFlatFeeLine clears the "flat_fee_line" edge to the BillingInvoiceFlatFeeLineConfig entity. +func (m *BillingInvoiceLineMutation) ClearFlatFeeLine() { + m.clearedflat_fee_line = true +} + +// FlatFeeLineCleared reports if the "flat_fee_line" edge to the BillingInvoiceFlatFeeLineConfig entity was cleared. +func (m *BillingInvoiceLineMutation) FlatFeeLineCleared() bool { + return m.clearedflat_fee_line +} + +// FlatFeeLineID returns the "flat_fee_line" edge ID in the mutation. +func (m *BillingInvoiceLineMutation) FlatFeeLineID() (id string, exists bool) { + if m.flat_fee_line != nil { + return *m.flat_fee_line, true + } + return +} + +// FlatFeeLineIDs returns the "flat_fee_line" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// FlatFeeLineID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceLineMutation) FlatFeeLineIDs() (ids []string) { + if id := m.flat_fee_line; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetFlatFeeLine resets all changes to the "flat_fee_line" edge. +func (m *BillingInvoiceLineMutation) ResetFlatFeeLine() { + m.flat_fee_line = nil + m.clearedflat_fee_line = false +} + +// SetUsageBasedLineID sets the "usage_based_line" edge to the BillingInvoiceUsageBasedLineConfig entity by id. +func (m *BillingInvoiceLineMutation) SetUsageBasedLineID(id string) { + m.usage_based_line = &id +} + +// ClearUsageBasedLine clears the "usage_based_line" edge to the BillingInvoiceUsageBasedLineConfig entity. +func (m *BillingInvoiceLineMutation) ClearUsageBasedLine() { + m.clearedusage_based_line = true +} + +// UsageBasedLineCleared reports if the "usage_based_line" edge to the BillingInvoiceUsageBasedLineConfig entity was cleared. +func (m *BillingInvoiceLineMutation) UsageBasedLineCleared() bool { + return m.clearedusage_based_line +} + +// UsageBasedLineID returns the "usage_based_line" edge ID in the mutation. +func (m *BillingInvoiceLineMutation) UsageBasedLineID() (id string, exists bool) { + if m.usage_based_line != nil { + return *m.usage_based_line, true + } + return +} + +// UsageBasedLineIDs returns the "usage_based_line" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UsageBasedLineID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceLineMutation) UsageBasedLineIDs() (ids []string) { + if id := m.usage_based_line; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetUsageBasedLine resets all changes to the "usage_based_line" edge. +func (m *BillingInvoiceLineMutation) ResetUsageBasedLine() { + m.usage_based_line = nil + m.clearedusage_based_line = false +} + +// ClearParentLine clears the "parent_line" edge to the BillingInvoiceLine entity. +func (m *BillingInvoiceLineMutation) ClearParentLine() { + m.clearedparent_line = true + m.clearedFields[billinginvoiceline.FieldParentLineID] = struct{}{} +} + +// ParentLineCleared reports if the "parent_line" edge to the BillingInvoiceLine entity was cleared. +func (m *BillingInvoiceLineMutation) ParentLineCleared() bool { + return m.ParentLineIDCleared() || m.clearedparent_line +} + +// ParentLineIDs returns the "parent_line" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ParentLineID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceLineMutation) ParentLineIDs() (ids []string) { + if id := m.parent_line; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetParentLine resets all changes to the "parent_line" edge. +func (m *BillingInvoiceLineMutation) ResetParentLine() { + m.parent_line = nil + m.clearedparent_line = false +} + +// AddDetailedLineIDs adds the "detailed_lines" edge to the BillingInvoiceLine entity by ids. +func (m *BillingInvoiceLineMutation) AddDetailedLineIDs(ids ...string) { + if m.detailed_lines == nil { + m.detailed_lines = make(map[string]struct{}) + } + for i := range ids { + m.detailed_lines[ids[i]] = struct{}{} + } +} + +// ClearDetailedLines clears the "detailed_lines" edge to the BillingInvoiceLine entity. +func (m *BillingInvoiceLineMutation) ClearDetailedLines() { + m.cleareddetailed_lines = true +} + +// DetailedLinesCleared reports if the "detailed_lines" edge to the BillingInvoiceLine entity was cleared. +func (m *BillingInvoiceLineMutation) DetailedLinesCleared() bool { + return m.cleareddetailed_lines +} + +// RemoveDetailedLineIDs removes the "detailed_lines" edge to the BillingInvoiceLine entity by IDs. +func (m *BillingInvoiceLineMutation) RemoveDetailedLineIDs(ids ...string) { + if m.removeddetailed_lines == nil { + m.removeddetailed_lines = make(map[string]struct{}) + } + for i := range ids { + delete(m.detailed_lines, ids[i]) + m.removeddetailed_lines[ids[i]] = struct{}{} + } +} + +// RemovedDetailedLines returns the removed IDs of the "detailed_lines" edge to the BillingInvoiceLine entity. +func (m *BillingInvoiceLineMutation) RemovedDetailedLinesIDs() (ids []string) { + for id := range m.removeddetailed_lines { + ids = append(ids, id) + } + return +} + +// DetailedLinesIDs returns the "detailed_lines" edge IDs in the mutation. +func (m *BillingInvoiceLineMutation) DetailedLinesIDs() (ids []string) { + for id := range m.detailed_lines { + ids = append(ids, id) + } + return +} + +// ResetDetailedLines resets all changes to the "detailed_lines" edge. +func (m *BillingInvoiceLineMutation) ResetDetailedLines() { + m.detailed_lines = nil + m.cleareddetailed_lines = false + m.removeddetailed_lines = nil +} + +// AddDetailedLinesV2IDs adds the "detailed_lines_v2" edge to the BillingStandardInvoiceDetailedLine entity by ids. +func (m *BillingInvoiceLineMutation) AddDetailedLinesV2IDs(ids ...string) { + if m.detailed_lines_v2 == nil { + m.detailed_lines_v2 = make(map[string]struct{}) + } + for i := range ids { + m.detailed_lines_v2[ids[i]] = struct{}{} + } +} + +// ClearDetailedLinesV2 clears the "detailed_lines_v2" edge to the BillingStandardInvoiceDetailedLine entity. +func (m *BillingInvoiceLineMutation) ClearDetailedLinesV2() { + m.cleareddetailed_lines_v2 = true +} + +// DetailedLinesV2Cleared reports if the "detailed_lines_v2" edge to the BillingStandardInvoiceDetailedLine entity was cleared. +func (m *BillingInvoiceLineMutation) DetailedLinesV2Cleared() bool { + return m.cleareddetailed_lines_v2 +} + +// RemoveDetailedLinesV2IDs removes the "detailed_lines_v2" edge to the BillingStandardInvoiceDetailedLine entity by IDs. +func (m *BillingInvoiceLineMutation) RemoveDetailedLinesV2IDs(ids ...string) { + if m.removeddetailed_lines_v2 == nil { + m.removeddetailed_lines_v2 = make(map[string]struct{}) + } + for i := range ids { + delete(m.detailed_lines_v2, ids[i]) + m.removeddetailed_lines_v2[ids[i]] = struct{}{} + } +} + +// RemovedDetailedLinesV2 returns the removed IDs of the "detailed_lines_v2" edge to the BillingStandardInvoiceDetailedLine entity. +func (m *BillingInvoiceLineMutation) RemovedDetailedLinesV2IDs() (ids []string) { + for id := range m.removeddetailed_lines_v2 { + ids = append(ids, id) + } + return +} + +// DetailedLinesV2IDs returns the "detailed_lines_v2" edge IDs in the mutation. +func (m *BillingInvoiceLineMutation) DetailedLinesV2IDs() (ids []string) { + for id := range m.detailed_lines_v2 { + ids = append(ids, id) + } + return +} + +// ResetDetailedLinesV2 resets all changes to the "detailed_lines_v2" edge. +func (m *BillingInvoiceLineMutation) ResetDetailedLinesV2() { + m.detailed_lines_v2 = nil + m.cleareddetailed_lines_v2 = false + m.removeddetailed_lines_v2 = nil +} + +// AddLineUsageDiscountIDs adds the "line_usage_discounts" edge to the BillingInvoiceLineUsageDiscount entity by ids. +func (m *BillingInvoiceLineMutation) AddLineUsageDiscountIDs(ids ...string) { + if m.line_usage_discounts == nil { + m.line_usage_discounts = make(map[string]struct{}) + } + for i := range ids { + m.line_usage_discounts[ids[i]] = struct{}{} + } +} + +// ClearLineUsageDiscounts clears the "line_usage_discounts" edge to the BillingInvoiceLineUsageDiscount entity. +func (m *BillingInvoiceLineMutation) ClearLineUsageDiscounts() { + m.clearedline_usage_discounts = true +} + +// LineUsageDiscountsCleared reports if the "line_usage_discounts" edge to the BillingInvoiceLineUsageDiscount entity was cleared. +func (m *BillingInvoiceLineMutation) LineUsageDiscountsCleared() bool { + return m.clearedline_usage_discounts +} + +// RemoveLineUsageDiscountIDs removes the "line_usage_discounts" edge to the BillingInvoiceLineUsageDiscount entity by IDs. +func (m *BillingInvoiceLineMutation) RemoveLineUsageDiscountIDs(ids ...string) { + if m.removedline_usage_discounts == nil { + m.removedline_usage_discounts = make(map[string]struct{}) + } + for i := range ids { + delete(m.line_usage_discounts, ids[i]) + m.removedline_usage_discounts[ids[i]] = struct{}{} + } +} + +// RemovedLineUsageDiscounts returns the removed IDs of the "line_usage_discounts" edge to the BillingInvoiceLineUsageDiscount entity. +func (m *BillingInvoiceLineMutation) RemovedLineUsageDiscountsIDs() (ids []string) { + for id := range m.removedline_usage_discounts { + ids = append(ids, id) + } + return +} + +// LineUsageDiscountsIDs returns the "line_usage_discounts" edge IDs in the mutation. +func (m *BillingInvoiceLineMutation) LineUsageDiscountsIDs() (ids []string) { + for id := range m.line_usage_discounts { + ids = append(ids, id) + } + return +} + +// ResetLineUsageDiscounts resets all changes to the "line_usage_discounts" edge. +func (m *BillingInvoiceLineMutation) ResetLineUsageDiscounts() { + m.line_usage_discounts = nil + m.clearedline_usage_discounts = false + m.removedline_usage_discounts = nil +} + +// AddLineAmountDiscountIDs adds the "line_amount_discounts" edge to the BillingInvoiceLineDiscount entity by ids. +func (m *BillingInvoiceLineMutation) AddLineAmountDiscountIDs(ids ...string) { + if m.line_amount_discounts == nil { + m.line_amount_discounts = make(map[string]struct{}) + } + for i := range ids { + m.line_amount_discounts[ids[i]] = struct{}{} + } +} + +// ClearLineAmountDiscounts clears the "line_amount_discounts" edge to the BillingInvoiceLineDiscount entity. +func (m *BillingInvoiceLineMutation) ClearLineAmountDiscounts() { + m.clearedline_amount_discounts = true +} + +// LineAmountDiscountsCleared reports if the "line_amount_discounts" edge to the BillingInvoiceLineDiscount entity was cleared. +func (m *BillingInvoiceLineMutation) LineAmountDiscountsCleared() bool { + return m.clearedline_amount_discounts +} + +// RemoveLineAmountDiscountIDs removes the "line_amount_discounts" edge to the BillingInvoiceLineDiscount entity by IDs. +func (m *BillingInvoiceLineMutation) RemoveLineAmountDiscountIDs(ids ...string) { + if m.removedline_amount_discounts == nil { + m.removedline_amount_discounts = make(map[string]struct{}) + } + for i := range ids { + delete(m.line_amount_discounts, ids[i]) + m.removedline_amount_discounts[ids[i]] = struct{}{} + } +} + +// RemovedLineAmountDiscounts returns the removed IDs of the "line_amount_discounts" edge to the BillingInvoiceLineDiscount entity. +func (m *BillingInvoiceLineMutation) RemovedLineAmountDiscountsIDs() (ids []string) { + for id := range m.removedline_amount_discounts { + ids = append(ids, id) + } + return +} + +// LineAmountDiscountsIDs returns the "line_amount_discounts" edge IDs in the mutation. +func (m *BillingInvoiceLineMutation) LineAmountDiscountsIDs() (ids []string) { + for id := range m.line_amount_discounts { + ids = append(ids, id) + } + return +} + +// ResetLineAmountDiscounts resets all changes to the "line_amount_discounts" edge. +func (m *BillingInvoiceLineMutation) ResetLineAmountDiscounts() { + m.line_amount_discounts = nil + m.clearedline_amount_discounts = false + m.removedline_amount_discounts = nil +} + +// ClearSubscription clears the "subscription" edge to the Subscription entity. +func (m *BillingInvoiceLineMutation) ClearSubscription() { + m.clearedsubscription = true + m.clearedFields[billinginvoiceline.FieldSubscriptionID] = struct{}{} +} + +// SubscriptionCleared reports if the "subscription" edge to the Subscription entity was cleared. +func (m *BillingInvoiceLineMutation) SubscriptionCleared() bool { + return m.SubscriptionIDCleared() || m.clearedsubscription +} + +// SubscriptionIDs returns the "subscription" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubscriptionID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceLineMutation) SubscriptionIDs() (ids []string) { + if id := m.subscription; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSubscription resets all changes to the "subscription" edge. +func (m *BillingInvoiceLineMutation) ResetSubscription() { + m.subscription = nil + m.clearedsubscription = false +} + +// ClearSubscriptionPhase clears the "subscription_phase" edge to the SubscriptionPhase entity. +func (m *BillingInvoiceLineMutation) ClearSubscriptionPhase() { + m.clearedsubscription_phase = true + m.clearedFields[billinginvoiceline.FieldSubscriptionPhaseID] = struct{}{} +} + +// SubscriptionPhaseCleared reports if the "subscription_phase" edge to the SubscriptionPhase entity was cleared. +func (m *BillingInvoiceLineMutation) SubscriptionPhaseCleared() bool { + return m.SubscriptionPhaseIDCleared() || m.clearedsubscription_phase +} + +// SubscriptionPhaseIDs returns the "subscription_phase" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubscriptionPhaseID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceLineMutation) SubscriptionPhaseIDs() (ids []string) { + if id := m.subscription_phase; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSubscriptionPhase resets all changes to the "subscription_phase" edge. +func (m *BillingInvoiceLineMutation) ResetSubscriptionPhase() { + m.subscription_phase = nil + m.clearedsubscription_phase = false +} + +// ClearSubscriptionItem clears the "subscription_item" edge to the SubscriptionItem entity. +func (m *BillingInvoiceLineMutation) ClearSubscriptionItem() { + m.clearedsubscription_item = true + m.clearedFields[billinginvoiceline.FieldSubscriptionItemID] = struct{}{} +} + +// SubscriptionItemCleared reports if the "subscription_item" edge to the SubscriptionItem entity was cleared. +func (m *BillingInvoiceLineMutation) SubscriptionItemCleared() bool { + return m.SubscriptionItemIDCleared() || m.clearedsubscription_item +} + +// SubscriptionItemIDs returns the "subscription_item" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubscriptionItemID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceLineMutation) SubscriptionItemIDs() (ids []string) { + if id := m.subscription_item; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSubscriptionItem resets all changes to the "subscription_item" edge. +func (m *BillingInvoiceLineMutation) ResetSubscriptionItem() { + m.subscription_item = nil + m.clearedsubscription_item = false +} + +// ClearCharge clears the "charge" edge to the Charge entity. +func (m *BillingInvoiceLineMutation) ClearCharge() { + m.clearedcharge = true + m.clearedFields[billinginvoiceline.FieldChargeID] = struct{}{} +} + +// ChargeCleared reports if the "charge" edge to the Charge entity was cleared. +func (m *BillingInvoiceLineMutation) ChargeCleared() bool { + return m.ChargeIDCleared() || m.clearedcharge +} + +// 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 *BillingInvoiceLineMutation) ChargeIDs() (ids []string) { + if id := m.charge; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCharge resets all changes to the "charge" edge. +func (m *BillingInvoiceLineMutation) ResetCharge() { + m.charge = nil + m.clearedcharge = false +} + +// SetChargeFlatFeeRunPaymentID sets the "charge_flat_fee_run_payment" edge to the ChargeFlatFeeRunPayment entity by id. +func (m *BillingInvoiceLineMutation) SetChargeFlatFeeRunPaymentID(id string) { + m.charge_flat_fee_run_payment = &id +} + +// ClearChargeFlatFeeRunPayment clears the "charge_flat_fee_run_payment" edge to the ChargeFlatFeeRunPayment entity. +func (m *BillingInvoiceLineMutation) ClearChargeFlatFeeRunPayment() { + m.clearedcharge_flat_fee_run_payment = true +} + +// ChargeFlatFeeRunPaymentCleared reports if the "charge_flat_fee_run_payment" edge to the ChargeFlatFeeRunPayment entity was cleared. +func (m *BillingInvoiceLineMutation) ChargeFlatFeeRunPaymentCleared() bool { + return m.clearedcharge_flat_fee_run_payment +} + +// ChargeFlatFeeRunPaymentID returns the "charge_flat_fee_run_payment" edge ID in the mutation. +func (m *BillingInvoiceLineMutation) ChargeFlatFeeRunPaymentID() (id string, exists bool) { + if m.charge_flat_fee_run_payment != nil { + return *m.charge_flat_fee_run_payment, true + } + return +} + +// ChargeFlatFeeRunPaymentIDs returns the "charge_flat_fee_run_payment" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ChargeFlatFeeRunPaymentID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceLineMutation) ChargeFlatFeeRunPaymentIDs() (ids []string) { + if id := m.charge_flat_fee_run_payment; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetChargeFlatFeeRunPayment resets all changes to the "charge_flat_fee_run_payment" edge. +func (m *BillingInvoiceLineMutation) ResetChargeFlatFeeRunPayment() { + m.charge_flat_fee_run_payment = nil + m.clearedcharge_flat_fee_run_payment = false +} + +// AddChargeFlatFeeRunCreditAllocationIDs adds the "charge_flat_fee_run_credit_allocations" edge to the ChargeFlatFeeRunCreditAllocations entity by ids. +func (m *BillingInvoiceLineMutation) AddChargeFlatFeeRunCreditAllocationIDs(ids ...string) { + if m.charge_flat_fee_run_credit_allocations == nil { + m.charge_flat_fee_run_credit_allocations = make(map[string]struct{}) + } + for i := range ids { + m.charge_flat_fee_run_credit_allocations[ids[i]] = struct{}{} + } +} + +// ClearChargeFlatFeeRunCreditAllocations clears the "charge_flat_fee_run_credit_allocations" edge to the ChargeFlatFeeRunCreditAllocations entity. +func (m *BillingInvoiceLineMutation) ClearChargeFlatFeeRunCreditAllocations() { + m.clearedcharge_flat_fee_run_credit_allocations = true +} + +// ChargeFlatFeeRunCreditAllocationsCleared reports if the "charge_flat_fee_run_credit_allocations" edge to the ChargeFlatFeeRunCreditAllocations entity was cleared. +func (m *BillingInvoiceLineMutation) ChargeFlatFeeRunCreditAllocationsCleared() bool { + return m.clearedcharge_flat_fee_run_credit_allocations +} + +// RemoveChargeFlatFeeRunCreditAllocationIDs removes the "charge_flat_fee_run_credit_allocations" edge to the ChargeFlatFeeRunCreditAllocations entity by IDs. +func (m *BillingInvoiceLineMutation) RemoveChargeFlatFeeRunCreditAllocationIDs(ids ...string) { + if m.removedcharge_flat_fee_run_credit_allocations == nil { + m.removedcharge_flat_fee_run_credit_allocations = make(map[string]struct{}) + } + for i := range ids { + delete(m.charge_flat_fee_run_credit_allocations, ids[i]) + m.removedcharge_flat_fee_run_credit_allocations[ids[i]] = struct{}{} + } +} + +// RemovedChargeFlatFeeRunCreditAllocations returns the removed IDs of the "charge_flat_fee_run_credit_allocations" edge to the ChargeFlatFeeRunCreditAllocations entity. +func (m *BillingInvoiceLineMutation) RemovedChargeFlatFeeRunCreditAllocationsIDs() (ids []string) { + for id := range m.removedcharge_flat_fee_run_credit_allocations { + ids = append(ids, id) + } + return +} + +// ChargeFlatFeeRunCreditAllocationsIDs returns the "charge_flat_fee_run_credit_allocations" edge IDs in the mutation. +func (m *BillingInvoiceLineMutation) ChargeFlatFeeRunCreditAllocationsIDs() (ids []string) { + for id := range m.charge_flat_fee_run_credit_allocations { + ids = append(ids, id) + } + return +} + +// ResetChargeFlatFeeRunCreditAllocations resets all changes to the "charge_flat_fee_run_credit_allocations" edge. +func (m *BillingInvoiceLineMutation) ResetChargeFlatFeeRunCreditAllocations() { + m.charge_flat_fee_run_credit_allocations = nil + m.clearedcharge_flat_fee_run_credit_allocations = false + m.removedcharge_flat_fee_run_credit_allocations = nil +} + +// SetChargeFlatFeeRunsID sets the "charge_flat_fee_runs" edge to the ChargeFlatFeeRun entity by id. +func (m *BillingInvoiceLineMutation) SetChargeFlatFeeRunsID(id string) { + m.charge_flat_fee_runs = &id +} + +// ClearChargeFlatFeeRuns clears the "charge_flat_fee_runs" edge to the ChargeFlatFeeRun entity. +func (m *BillingInvoiceLineMutation) ClearChargeFlatFeeRuns() { + m.clearedcharge_flat_fee_runs = true +} + +// ChargeFlatFeeRunsCleared reports if the "charge_flat_fee_runs" edge to the ChargeFlatFeeRun entity was cleared. +func (m *BillingInvoiceLineMutation) ChargeFlatFeeRunsCleared() bool { + return m.clearedcharge_flat_fee_runs +} + +// ChargeFlatFeeRunsID returns the "charge_flat_fee_runs" edge ID in the mutation. +func (m *BillingInvoiceLineMutation) ChargeFlatFeeRunsID() (id string, exists bool) { + if m.charge_flat_fee_runs != nil { + return *m.charge_flat_fee_runs, true + } + return +} + +// ChargeFlatFeeRunsIDs returns the "charge_flat_fee_runs" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ChargeFlatFeeRunsID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceLineMutation) ChargeFlatFeeRunsIDs() (ids []string) { + if id := m.charge_flat_fee_runs; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetChargeFlatFeeRuns resets all changes to the "charge_flat_fee_runs" edge. +func (m *BillingInvoiceLineMutation) ResetChargeFlatFeeRuns() { + m.charge_flat_fee_runs = nil + m.clearedcharge_flat_fee_runs = false +} + +// SetChargeUsageBasedRunID sets the "charge_usage_based_run" edge to the ChargeUsageBasedRuns entity by id. +func (m *BillingInvoiceLineMutation) SetChargeUsageBasedRunID(id string) { + m.charge_usage_based_run = &id +} + +// ClearChargeUsageBasedRun clears the "charge_usage_based_run" edge to the ChargeUsageBasedRuns entity. +func (m *BillingInvoiceLineMutation) ClearChargeUsageBasedRun() { + m.clearedcharge_usage_based_run = true +} + +// ChargeUsageBasedRunCleared reports if the "charge_usage_based_run" edge to the ChargeUsageBasedRuns entity was cleared. +func (m *BillingInvoiceLineMutation) ChargeUsageBasedRunCleared() bool { + return m.clearedcharge_usage_based_run +} + +// ChargeUsageBasedRunID returns the "charge_usage_based_run" edge ID in the mutation. +func (m *BillingInvoiceLineMutation) ChargeUsageBasedRunID() (id string, exists bool) { + if m.charge_usage_based_run != nil { + return *m.charge_usage_based_run, true + } + return +} + +// ChargeUsageBasedRunIDs returns the "charge_usage_based_run" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ChargeUsageBasedRunID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceLineMutation) ChargeUsageBasedRunIDs() (ids []string) { + if id := m.charge_usage_based_run; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetChargeUsageBasedRun resets all changes to the "charge_usage_based_run" edge. +func (m *BillingInvoiceLineMutation) ResetChargeUsageBasedRun() { + m.charge_usage_based_run = nil + m.clearedcharge_usage_based_run = false +} + +// SetChargeCreditPurchaseInvoicedPaymentID sets the "charge_credit_purchase_invoiced_payment" edge to the ChargeCreditPurchaseInvoicedPayment entity by id. +func (m *BillingInvoiceLineMutation) SetChargeCreditPurchaseInvoicedPaymentID(id string) { + m.charge_credit_purchase_invoiced_payment = &id +} + +// ClearChargeCreditPurchaseInvoicedPayment clears the "charge_credit_purchase_invoiced_payment" edge to the ChargeCreditPurchaseInvoicedPayment entity. +func (m *BillingInvoiceLineMutation) ClearChargeCreditPurchaseInvoicedPayment() { + m.clearedcharge_credit_purchase_invoiced_payment = true +} + +// ChargeCreditPurchaseInvoicedPaymentCleared reports if the "charge_credit_purchase_invoiced_payment" edge to the ChargeCreditPurchaseInvoicedPayment entity was cleared. +func (m *BillingInvoiceLineMutation) ChargeCreditPurchaseInvoicedPaymentCleared() bool { + return m.clearedcharge_credit_purchase_invoiced_payment +} + +// ChargeCreditPurchaseInvoicedPaymentID returns the "charge_credit_purchase_invoiced_payment" edge ID in the mutation. +func (m *BillingInvoiceLineMutation) ChargeCreditPurchaseInvoicedPaymentID() (id string, exists bool) { + if m.charge_credit_purchase_invoiced_payment != nil { + return *m.charge_credit_purchase_invoiced_payment, true + } + return +} + +// ChargeCreditPurchaseInvoicedPaymentIDs returns the "charge_credit_purchase_invoiced_payment" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ChargeCreditPurchaseInvoicedPaymentID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceLineMutation) ChargeCreditPurchaseInvoicedPaymentIDs() (ids []string) { + if id := m.charge_credit_purchase_invoiced_payment; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetChargeCreditPurchaseInvoicedPayment resets all changes to the "charge_credit_purchase_invoiced_payment" edge. +func (m *BillingInvoiceLineMutation) ResetChargeCreditPurchaseInvoicedPayment() { + m.charge_credit_purchase_invoiced_payment = nil + m.clearedcharge_credit_purchase_invoiced_payment = false +} + +// ClearTaxCode clears the "tax_code" edge to the TaxCode entity. +func (m *BillingInvoiceLineMutation) ClearTaxCode() { + m.clearedtax_code = true + m.clearedFields[billinginvoiceline.FieldTaxCodeID] = struct{}{} +} + +// TaxCodeCleared reports if the "tax_code" edge to the TaxCode entity was cleared. +func (m *BillingInvoiceLineMutation) TaxCodeCleared() bool { + return m.TaxCodeIDCleared() || m.clearedtax_code +} + +// TaxCodeIDs returns the "tax_code" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TaxCodeID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceLineMutation) TaxCodeIDs() (ids []string) { + if id := m.tax_code; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTaxCode resets all changes to the "tax_code" edge. +func (m *BillingInvoiceLineMutation) ResetTaxCode() { + m.tax_code = nil + m.clearedtax_code = false +} + +// Where appends a list predicates to the BillingInvoiceLineMutation builder. +func (m *BillingInvoiceLineMutation) Where(ps ...predicate.BillingInvoiceLine) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BillingInvoiceLineMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BillingInvoiceLineMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillingInvoiceLine, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BillingInvoiceLineMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BillingInvoiceLineMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BillingInvoiceLine). +func (m *BillingInvoiceLineMutation) 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 *BillingInvoiceLineMutation) Fields() []string { + fields := make([]string, 0, 42) + if m.annotations != nil { + fields = append(fields, billinginvoiceline.FieldAnnotations) + } + if m.namespace != nil { + fields = append(fields, billinginvoiceline.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, billinginvoiceline.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, billinginvoiceline.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, billinginvoiceline.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, billinginvoiceline.FieldDeletedAt) + } + if m.name != nil { + fields = append(fields, billinginvoiceline.FieldName) + } + if m.description != nil { + fields = append(fields, billinginvoiceline.FieldDescription) + } + if m.currency != nil { + fields = append(fields, billinginvoiceline.FieldCurrency) + } + if m.tax_config != nil { + fields = append(fields, billinginvoiceline.FieldTaxConfig) + } + if m.tax_code != nil { + fields = append(fields, billinginvoiceline.FieldTaxCodeID) + } + if m.tax_behavior != nil { + fields = append(fields, billinginvoiceline.FieldTaxBehavior) + } + if m.amount != nil { + fields = append(fields, billinginvoiceline.FieldAmount) + } + if m.taxes_total != nil { + fields = append(fields, billinginvoiceline.FieldTaxesTotal) + } + if m.taxes_inclusive_total != nil { + fields = append(fields, billinginvoiceline.FieldTaxesInclusiveTotal) + } + if m.taxes_exclusive_total != nil { + fields = append(fields, billinginvoiceline.FieldTaxesExclusiveTotal) + } + if m.charges_total != nil { + fields = append(fields, billinginvoiceline.FieldChargesTotal) + } + if m.discounts_total != nil { + fields = append(fields, billinginvoiceline.FieldDiscountsTotal) + } + if m.credits_total != nil { + fields = append(fields, billinginvoiceline.FieldCreditsTotal) + } + if m.total != nil { + fields = append(fields, billinginvoiceline.FieldTotal) + } + if m.invoicing_app_external_id != nil { + fields = append(fields, billinginvoiceline.FieldInvoicingAppExternalID) + } + if m.period_start != nil { + fields = append(fields, billinginvoiceline.FieldPeriodStart) + } + if m.period_end != nil { + fields = append(fields, billinginvoiceline.FieldPeriodEnd) + } + if m.billing_invoice != nil { + fields = append(fields, billinginvoiceline.FieldInvoiceID) + } + if m.managed_by != nil { + fields = append(fields, billinginvoiceline.FieldManagedBy) + } + if m.parent_line != nil { + fields = append(fields, billinginvoiceline.FieldParentLineID) + } + if m.invoice_at != nil { + fields = append(fields, billinginvoiceline.FieldInvoiceAt) + } + if m.override_collection_period_end != nil { + fields = append(fields, billinginvoiceline.FieldOverrideCollectionPeriodEnd) + } + if m._type != nil { + fields = append(fields, billinginvoiceline.FieldType) + } + if m.status != nil { + fields = append(fields, billinginvoiceline.FieldStatus) + } + if m.quantity != nil { + fields = append(fields, billinginvoiceline.FieldQuantity) + } + if m.ratecard_discounts != nil { + fields = append(fields, billinginvoiceline.FieldRatecardDiscounts) + } + if m.child_unique_reference_id != nil { + fields = append(fields, billinginvoiceline.FieldChildUniqueReferenceID) + } + if m.subscription != nil { + fields = append(fields, billinginvoiceline.FieldSubscriptionID) + } + if m.subscription_phase != nil { + fields = append(fields, billinginvoiceline.FieldSubscriptionPhaseID) + } + if m.subscription_item != nil { + fields = append(fields, billinginvoiceline.FieldSubscriptionItemID) + } + if m.subscription_billing_period_from != nil { + fields = append(fields, billinginvoiceline.FieldSubscriptionBillingPeriodFrom) + } + if m.subscription_billing_period_to != nil { + fields = append(fields, billinginvoiceline.FieldSubscriptionBillingPeriodTo) + } + if m.split_line_group != nil { + fields = append(fields, billinginvoiceline.FieldSplitLineGroupID) + } + if m.charge != nil { + fields = append(fields, billinginvoiceline.FieldChargeID) + } + if m.engine != nil { + fields = append(fields, billinginvoiceline.FieldEngine) + } + if m.credits_applied != nil { + fields = append(fields, billinginvoiceline.FieldCreditsApplied) + } + 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 *BillingInvoiceLineMutation) Field(name string) (ent.Value, bool) { + switch name { + case billinginvoiceline.FieldAnnotations: + return m.Annotations() + case billinginvoiceline.FieldNamespace: + return m.Namespace() + case billinginvoiceline.FieldMetadata: + return m.Metadata() + case billinginvoiceline.FieldCreatedAt: + return m.CreatedAt() + case billinginvoiceline.FieldUpdatedAt: + return m.UpdatedAt() + case billinginvoiceline.FieldDeletedAt: + return m.DeletedAt() + case billinginvoiceline.FieldName: + return m.Name() + case billinginvoiceline.FieldDescription: + return m.Description() + case billinginvoiceline.FieldCurrency: + return m.Currency() + case billinginvoiceline.FieldTaxConfig: + return m.TaxConfig() + case billinginvoiceline.FieldTaxCodeID: + return m.TaxCodeID() + case billinginvoiceline.FieldTaxBehavior: + return m.TaxBehavior() + case billinginvoiceline.FieldAmount: + return m.Amount() + case billinginvoiceline.FieldTaxesTotal: + return m.TaxesTotal() + case billinginvoiceline.FieldTaxesInclusiveTotal: + return m.TaxesInclusiveTotal() + case billinginvoiceline.FieldTaxesExclusiveTotal: + return m.TaxesExclusiveTotal() + case billinginvoiceline.FieldChargesTotal: + return m.ChargesTotal() + case billinginvoiceline.FieldDiscountsTotal: + return m.DiscountsTotal() + case billinginvoiceline.FieldCreditsTotal: + return m.CreditsTotal() + case billinginvoiceline.FieldTotal: + return m.Total() + case billinginvoiceline.FieldInvoicingAppExternalID: + return m.InvoicingAppExternalID() + case billinginvoiceline.FieldPeriodStart: + return m.PeriodStart() + case billinginvoiceline.FieldPeriodEnd: + return m.PeriodEnd() + case billinginvoiceline.FieldInvoiceID: + return m.InvoiceID() + case billinginvoiceline.FieldManagedBy: + return m.ManagedBy() + case billinginvoiceline.FieldParentLineID: + return m.ParentLineID() + case billinginvoiceline.FieldInvoiceAt: + return m.InvoiceAt() + case billinginvoiceline.FieldOverrideCollectionPeriodEnd: + return m.OverrideCollectionPeriodEnd() + case billinginvoiceline.FieldType: + return m.GetType() + case billinginvoiceline.FieldStatus: + return m.Status() + case billinginvoiceline.FieldQuantity: + return m.Quantity() + case billinginvoiceline.FieldRatecardDiscounts: + return m.RatecardDiscounts() + case billinginvoiceline.FieldChildUniqueReferenceID: + return m.ChildUniqueReferenceID() + case billinginvoiceline.FieldSubscriptionID: + return m.SubscriptionID() + case billinginvoiceline.FieldSubscriptionPhaseID: + return m.SubscriptionPhaseID() + case billinginvoiceline.FieldSubscriptionItemID: + return m.SubscriptionItemID() + case billinginvoiceline.FieldSubscriptionBillingPeriodFrom: + return m.SubscriptionBillingPeriodFrom() + case billinginvoiceline.FieldSubscriptionBillingPeriodTo: + return m.SubscriptionBillingPeriodTo() + case billinginvoiceline.FieldSplitLineGroupID: + return m.SplitLineGroupID() + case billinginvoiceline.FieldChargeID: + return m.ChargeID() + case billinginvoiceline.FieldEngine: + return m.Engine() + case billinginvoiceline.FieldCreditsApplied: + return m.CreditsApplied() + } + 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 *BillingInvoiceLineMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case billinginvoiceline.FieldAnnotations: + return m.OldAnnotations(ctx) + case billinginvoiceline.FieldNamespace: + return m.OldNamespace(ctx) + case billinginvoiceline.FieldMetadata: + return m.OldMetadata(ctx) + case billinginvoiceline.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case billinginvoiceline.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case billinginvoiceline.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case billinginvoiceline.FieldName: + return m.OldName(ctx) + case billinginvoiceline.FieldDescription: + return m.OldDescription(ctx) + case billinginvoiceline.FieldCurrency: + return m.OldCurrency(ctx) + case billinginvoiceline.FieldTaxConfig: + return m.OldTaxConfig(ctx) + case billinginvoiceline.FieldTaxCodeID: + return m.OldTaxCodeID(ctx) + case billinginvoiceline.FieldTaxBehavior: + return m.OldTaxBehavior(ctx) + case billinginvoiceline.FieldAmount: + return m.OldAmount(ctx) + case billinginvoiceline.FieldTaxesTotal: + return m.OldTaxesTotal(ctx) + case billinginvoiceline.FieldTaxesInclusiveTotal: + return m.OldTaxesInclusiveTotal(ctx) + case billinginvoiceline.FieldTaxesExclusiveTotal: + return m.OldTaxesExclusiveTotal(ctx) + case billinginvoiceline.FieldChargesTotal: + return m.OldChargesTotal(ctx) + case billinginvoiceline.FieldDiscountsTotal: + return m.OldDiscountsTotal(ctx) + case billinginvoiceline.FieldCreditsTotal: + return m.OldCreditsTotal(ctx) + case billinginvoiceline.FieldTotal: + return m.OldTotal(ctx) + case billinginvoiceline.FieldInvoicingAppExternalID: + return m.OldInvoicingAppExternalID(ctx) + case billinginvoiceline.FieldPeriodStart: + return m.OldPeriodStart(ctx) + case billinginvoiceline.FieldPeriodEnd: + return m.OldPeriodEnd(ctx) + case billinginvoiceline.FieldInvoiceID: + return m.OldInvoiceID(ctx) + case billinginvoiceline.FieldManagedBy: + return m.OldManagedBy(ctx) + case billinginvoiceline.FieldParentLineID: + return m.OldParentLineID(ctx) + case billinginvoiceline.FieldInvoiceAt: + return m.OldInvoiceAt(ctx) + case billinginvoiceline.FieldOverrideCollectionPeriodEnd: + return m.OldOverrideCollectionPeriodEnd(ctx) + case billinginvoiceline.FieldType: + return m.OldType(ctx) + case billinginvoiceline.FieldStatus: + return m.OldStatus(ctx) + case billinginvoiceline.FieldQuantity: + return m.OldQuantity(ctx) + case billinginvoiceline.FieldRatecardDiscounts: + return m.OldRatecardDiscounts(ctx) + case billinginvoiceline.FieldChildUniqueReferenceID: + return m.OldChildUniqueReferenceID(ctx) + case billinginvoiceline.FieldSubscriptionID: + return m.OldSubscriptionID(ctx) + case billinginvoiceline.FieldSubscriptionPhaseID: + return m.OldSubscriptionPhaseID(ctx) + case billinginvoiceline.FieldSubscriptionItemID: + return m.OldSubscriptionItemID(ctx) + case billinginvoiceline.FieldSubscriptionBillingPeriodFrom: + return m.OldSubscriptionBillingPeriodFrom(ctx) + case billinginvoiceline.FieldSubscriptionBillingPeriodTo: + return m.OldSubscriptionBillingPeriodTo(ctx) + case billinginvoiceline.FieldSplitLineGroupID: + return m.OldSplitLineGroupID(ctx) + case billinginvoiceline.FieldChargeID: + return m.OldChargeID(ctx) + case billinginvoiceline.FieldEngine: + return m.OldEngine(ctx) + case billinginvoiceline.FieldCreditsApplied: + return m.OldCreditsApplied(ctx) + } + return nil, fmt.Errorf("unknown BillingInvoiceLine 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 *BillingInvoiceLineMutation) SetField(name string, value ent.Value) error { + switch name { + case billinginvoiceline.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 billinginvoiceline.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case billinginvoiceline.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case billinginvoiceline.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 billinginvoiceline.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 billinginvoiceline.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 billinginvoiceline.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case billinginvoiceline.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case billinginvoiceline.FieldCurrency: + v, ok := value.(currencyx.Code) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrency(v) + return nil + case billinginvoiceline.FieldTaxConfig: + v, ok := value.(billing.TaxConfig) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxConfig(v) + return nil + case billinginvoiceline.FieldTaxCodeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxCodeID(v) + return nil + case billinginvoiceline.FieldTaxBehavior: + v, ok := value.(productcatalog.TaxBehavior) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxBehavior(v) + return nil + case billinginvoiceline.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 billinginvoiceline.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 billinginvoiceline.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 billinginvoiceline.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 billinginvoiceline.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 billinginvoiceline.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 billinginvoiceline.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 billinginvoiceline.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 billinginvoiceline.FieldInvoicingAppExternalID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoicingAppExternalID(v) + return nil + case billinginvoiceline.FieldPeriodStart: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPeriodStart(v) + return nil + case billinginvoiceline.FieldPeriodEnd: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPeriodEnd(v) + return nil + case billinginvoiceline.FieldInvoiceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceID(v) + return nil + case billinginvoiceline.FieldManagedBy: + v, ok := value.(billing.InvoiceLineManagedBy) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetManagedBy(v) + return nil + case billinginvoiceline.FieldParentLineID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetParentLineID(v) + return nil + case billinginvoiceline.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 billinginvoiceline.FieldOverrideCollectionPeriodEnd: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOverrideCollectionPeriodEnd(v) + return nil + case billinginvoiceline.FieldType: + v, ok := value.(billing.InvoiceLineAdapterType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case billinginvoiceline.FieldStatus: + v, ok := value.(billing.InvoiceLineStatus) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case billinginvoiceline.FieldQuantity: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetQuantity(v) + return nil + case billinginvoiceline.FieldRatecardDiscounts: + v, ok := value.(*billing.Discounts) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRatecardDiscounts(v) + return nil + case billinginvoiceline.FieldChildUniqueReferenceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChildUniqueReferenceID(v) + return nil + case billinginvoiceline.FieldSubscriptionID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionID(v) + return nil + case billinginvoiceline.FieldSubscriptionPhaseID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionPhaseID(v) + return nil + case billinginvoiceline.FieldSubscriptionItemID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionItemID(v) + return nil + case billinginvoiceline.FieldSubscriptionBillingPeriodFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionBillingPeriodFrom(v) + return nil + case billinginvoiceline.FieldSubscriptionBillingPeriodTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionBillingPeriodTo(v) + return nil + case billinginvoiceline.FieldSplitLineGroupID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSplitLineGroupID(v) + return nil + case billinginvoiceline.FieldChargeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChargeID(v) + return nil + case billinginvoiceline.FieldEngine: + v, ok := value.(billing.LineEngineType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEngine(v) + return nil + case billinginvoiceline.FieldCreditsApplied: + v, ok := value.(*creditsapplied.CreditsApplied) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreditsApplied(v) + return nil + } + return fmt.Errorf("unknown BillingInvoiceLine field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BillingInvoiceLineMutation) 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 *BillingInvoiceLineMutation) 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 *BillingInvoiceLineMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown BillingInvoiceLine numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BillingInvoiceLineMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(billinginvoiceline.FieldAnnotations) { + fields = append(fields, billinginvoiceline.FieldAnnotations) + } + if m.FieldCleared(billinginvoiceline.FieldMetadata) { + fields = append(fields, billinginvoiceline.FieldMetadata) + } + if m.FieldCleared(billinginvoiceline.FieldDeletedAt) { + fields = append(fields, billinginvoiceline.FieldDeletedAt) + } + if m.FieldCleared(billinginvoiceline.FieldDescription) { + fields = append(fields, billinginvoiceline.FieldDescription) + } + if m.FieldCleared(billinginvoiceline.FieldTaxConfig) { + fields = append(fields, billinginvoiceline.FieldTaxConfig) + } + if m.FieldCleared(billinginvoiceline.FieldTaxCodeID) { + fields = append(fields, billinginvoiceline.FieldTaxCodeID) + } + if m.FieldCleared(billinginvoiceline.FieldTaxBehavior) { + fields = append(fields, billinginvoiceline.FieldTaxBehavior) + } + if m.FieldCleared(billinginvoiceline.FieldInvoicingAppExternalID) { + fields = append(fields, billinginvoiceline.FieldInvoicingAppExternalID) + } + if m.FieldCleared(billinginvoiceline.FieldParentLineID) { + fields = append(fields, billinginvoiceline.FieldParentLineID) + } + if m.FieldCleared(billinginvoiceline.FieldOverrideCollectionPeriodEnd) { + fields = append(fields, billinginvoiceline.FieldOverrideCollectionPeriodEnd) + } + if m.FieldCleared(billinginvoiceline.FieldQuantity) { + fields = append(fields, billinginvoiceline.FieldQuantity) + } + if m.FieldCleared(billinginvoiceline.FieldRatecardDiscounts) { + fields = append(fields, billinginvoiceline.FieldRatecardDiscounts) + } + if m.FieldCleared(billinginvoiceline.FieldChildUniqueReferenceID) { + fields = append(fields, billinginvoiceline.FieldChildUniqueReferenceID) + } + if m.FieldCleared(billinginvoiceline.FieldSubscriptionID) { + fields = append(fields, billinginvoiceline.FieldSubscriptionID) + } + if m.FieldCleared(billinginvoiceline.FieldSubscriptionPhaseID) { + fields = append(fields, billinginvoiceline.FieldSubscriptionPhaseID) + } + if m.FieldCleared(billinginvoiceline.FieldSubscriptionItemID) { + fields = append(fields, billinginvoiceline.FieldSubscriptionItemID) + } + if m.FieldCleared(billinginvoiceline.FieldSubscriptionBillingPeriodFrom) { + fields = append(fields, billinginvoiceline.FieldSubscriptionBillingPeriodFrom) + } + if m.FieldCleared(billinginvoiceline.FieldSubscriptionBillingPeriodTo) { + fields = append(fields, billinginvoiceline.FieldSubscriptionBillingPeriodTo) + } + if m.FieldCleared(billinginvoiceline.FieldSplitLineGroupID) { + fields = append(fields, billinginvoiceline.FieldSplitLineGroupID) + } + if m.FieldCleared(billinginvoiceline.FieldChargeID) { + fields = append(fields, billinginvoiceline.FieldChargeID) + } + if m.FieldCleared(billinginvoiceline.FieldCreditsApplied) { + fields = append(fields, billinginvoiceline.FieldCreditsApplied) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BillingInvoiceLineMutation) 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 *BillingInvoiceLineMutation) ClearField(name string) error { + switch name { + case billinginvoiceline.FieldAnnotations: + m.ClearAnnotations() + return nil + case billinginvoiceline.FieldMetadata: + m.ClearMetadata() + return nil + case billinginvoiceline.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case billinginvoiceline.FieldDescription: + m.ClearDescription() + return nil + case billinginvoiceline.FieldTaxConfig: + m.ClearTaxConfig() + return nil + case billinginvoiceline.FieldTaxCodeID: + m.ClearTaxCodeID() + return nil + case billinginvoiceline.FieldTaxBehavior: + m.ClearTaxBehavior() + return nil + case billinginvoiceline.FieldInvoicingAppExternalID: + m.ClearInvoicingAppExternalID() + return nil + case billinginvoiceline.FieldParentLineID: + m.ClearParentLineID() + return nil + case billinginvoiceline.FieldOverrideCollectionPeriodEnd: + m.ClearOverrideCollectionPeriodEnd() + return nil + case billinginvoiceline.FieldQuantity: + m.ClearQuantity() + return nil + case billinginvoiceline.FieldRatecardDiscounts: + m.ClearRatecardDiscounts() + return nil + case billinginvoiceline.FieldChildUniqueReferenceID: + m.ClearChildUniqueReferenceID() + return nil + case billinginvoiceline.FieldSubscriptionID: + m.ClearSubscriptionID() + return nil + case billinginvoiceline.FieldSubscriptionPhaseID: + m.ClearSubscriptionPhaseID() + return nil + case billinginvoiceline.FieldSubscriptionItemID: + m.ClearSubscriptionItemID() + return nil + case billinginvoiceline.FieldSubscriptionBillingPeriodFrom: + m.ClearSubscriptionBillingPeriodFrom() + return nil + case billinginvoiceline.FieldSubscriptionBillingPeriodTo: + m.ClearSubscriptionBillingPeriodTo() + return nil + case billinginvoiceline.FieldSplitLineGroupID: + m.ClearSplitLineGroupID() + return nil + case billinginvoiceline.FieldChargeID: + m.ClearChargeID() + return nil + case billinginvoiceline.FieldCreditsApplied: + m.ClearCreditsApplied() + return nil + } + return fmt.Errorf("unknown BillingInvoiceLine 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 *BillingInvoiceLineMutation) ResetField(name string) error { + switch name { + case billinginvoiceline.FieldAnnotations: + m.ResetAnnotations() + return nil + case billinginvoiceline.FieldNamespace: + m.ResetNamespace() + return nil + case billinginvoiceline.FieldMetadata: + m.ResetMetadata() + return nil + case billinginvoiceline.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case billinginvoiceline.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case billinginvoiceline.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case billinginvoiceline.FieldName: + m.ResetName() + return nil + case billinginvoiceline.FieldDescription: + m.ResetDescription() + return nil + case billinginvoiceline.FieldCurrency: + m.ResetCurrency() + return nil + case billinginvoiceline.FieldTaxConfig: + m.ResetTaxConfig() + return nil + case billinginvoiceline.FieldTaxCodeID: + m.ResetTaxCodeID() + return nil + case billinginvoiceline.FieldTaxBehavior: + m.ResetTaxBehavior() + return nil + case billinginvoiceline.FieldAmount: + m.ResetAmount() + return nil + case billinginvoiceline.FieldTaxesTotal: + m.ResetTaxesTotal() + return nil + case billinginvoiceline.FieldTaxesInclusiveTotal: + m.ResetTaxesInclusiveTotal() + return nil + case billinginvoiceline.FieldTaxesExclusiveTotal: + m.ResetTaxesExclusiveTotal() + return nil + case billinginvoiceline.FieldChargesTotal: + m.ResetChargesTotal() + return nil + case billinginvoiceline.FieldDiscountsTotal: + m.ResetDiscountsTotal() + return nil + case billinginvoiceline.FieldCreditsTotal: + m.ResetCreditsTotal() + return nil + case billinginvoiceline.FieldTotal: + m.ResetTotal() + return nil + case billinginvoiceline.FieldInvoicingAppExternalID: + m.ResetInvoicingAppExternalID() + return nil + case billinginvoiceline.FieldPeriodStart: + m.ResetPeriodStart() + return nil + case billinginvoiceline.FieldPeriodEnd: + m.ResetPeriodEnd() + return nil + case billinginvoiceline.FieldInvoiceID: + m.ResetInvoiceID() + return nil + case billinginvoiceline.FieldManagedBy: + m.ResetManagedBy() + return nil + case billinginvoiceline.FieldParentLineID: + m.ResetParentLineID() + return nil + case billinginvoiceline.FieldInvoiceAt: + m.ResetInvoiceAt() + return nil + case billinginvoiceline.FieldOverrideCollectionPeriodEnd: + m.ResetOverrideCollectionPeriodEnd() + return nil + case billinginvoiceline.FieldType: + m.ResetType() + return nil + case billinginvoiceline.FieldStatus: + m.ResetStatus() + return nil + case billinginvoiceline.FieldQuantity: + m.ResetQuantity() + return nil + case billinginvoiceline.FieldRatecardDiscounts: + m.ResetRatecardDiscounts() + return nil + case billinginvoiceline.FieldChildUniqueReferenceID: + m.ResetChildUniqueReferenceID() + return nil + case billinginvoiceline.FieldSubscriptionID: + m.ResetSubscriptionID() + return nil + case billinginvoiceline.FieldSubscriptionPhaseID: + m.ResetSubscriptionPhaseID() + return nil + case billinginvoiceline.FieldSubscriptionItemID: + m.ResetSubscriptionItemID() + return nil + case billinginvoiceline.FieldSubscriptionBillingPeriodFrom: + m.ResetSubscriptionBillingPeriodFrom() + return nil + case billinginvoiceline.FieldSubscriptionBillingPeriodTo: + m.ResetSubscriptionBillingPeriodTo() + return nil + case billinginvoiceline.FieldSplitLineGroupID: + m.ResetSplitLineGroupID() + return nil + case billinginvoiceline.FieldChargeID: + m.ResetChargeID() + return nil + case billinginvoiceline.FieldEngine: + m.ResetEngine() + return nil + case billinginvoiceline.FieldCreditsApplied: + m.ResetCreditsApplied() + return nil + } + return fmt.Errorf("unknown BillingInvoiceLine field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BillingInvoiceLineMutation) AddedEdges() []string { + edges := make([]string, 0, 19) + if m.billing_invoice != nil { + edges = append(edges, billinginvoiceline.EdgeBillingInvoice) + } + if m.split_line_group != nil { + edges = append(edges, billinginvoiceline.EdgeSplitLineGroup) + } + if m.flat_fee_line != nil { + edges = append(edges, billinginvoiceline.EdgeFlatFeeLine) + } + if m.usage_based_line != nil { + edges = append(edges, billinginvoiceline.EdgeUsageBasedLine) + } + if m.parent_line != nil { + edges = append(edges, billinginvoiceline.EdgeParentLine) + } + if m.detailed_lines != nil { + edges = append(edges, billinginvoiceline.EdgeDetailedLines) + } + if m.detailed_lines_v2 != nil { + edges = append(edges, billinginvoiceline.EdgeDetailedLinesV2) + } + if m.line_usage_discounts != nil { + edges = append(edges, billinginvoiceline.EdgeLineUsageDiscounts) + } + if m.line_amount_discounts != nil { + edges = append(edges, billinginvoiceline.EdgeLineAmountDiscounts) + } + if m.subscription != nil { + edges = append(edges, billinginvoiceline.EdgeSubscription) + } + if m.subscription_phase != nil { + edges = append(edges, billinginvoiceline.EdgeSubscriptionPhase) + } + if m.subscription_item != nil { + edges = append(edges, billinginvoiceline.EdgeSubscriptionItem) + } + if m.charge != nil { + edges = append(edges, billinginvoiceline.EdgeCharge) + } + if m.charge_flat_fee_run_payment != nil { + edges = append(edges, billinginvoiceline.EdgeChargeFlatFeeRunPayment) + } + if m.charge_flat_fee_run_credit_allocations != nil { + edges = append(edges, billinginvoiceline.EdgeChargeFlatFeeRunCreditAllocations) + } + if m.charge_flat_fee_runs != nil { + edges = append(edges, billinginvoiceline.EdgeChargeFlatFeeRuns) + } + if m.charge_usage_based_run != nil { + edges = append(edges, billinginvoiceline.EdgeChargeUsageBasedRun) + } + if m.charge_credit_purchase_invoiced_payment != nil { + edges = append(edges, billinginvoiceline.EdgeChargeCreditPurchaseInvoicedPayment) + } + if m.tax_code != nil { + edges = append(edges, billinginvoiceline.EdgeTaxCode) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BillingInvoiceLineMutation) AddedIDs(name string) []ent.Value { + switch name { + case billinginvoiceline.EdgeBillingInvoice: + if id := m.billing_invoice; id != nil { + return []ent.Value{*id} + } + case billinginvoiceline.EdgeSplitLineGroup: + if id := m.split_line_group; id != nil { + return []ent.Value{*id} + } + case billinginvoiceline.EdgeFlatFeeLine: + if id := m.flat_fee_line; id != nil { + return []ent.Value{*id} + } + case billinginvoiceline.EdgeUsageBasedLine: + if id := m.usage_based_line; id != nil { + return []ent.Value{*id} + } + case billinginvoiceline.EdgeParentLine: + if id := m.parent_line; id != nil { + return []ent.Value{*id} + } + case billinginvoiceline.EdgeDetailedLines: + ids := make([]ent.Value, 0, len(m.detailed_lines)) + for id := range m.detailed_lines { + ids = append(ids, id) + } + return ids + case billinginvoiceline.EdgeDetailedLinesV2: + ids := make([]ent.Value, 0, len(m.detailed_lines_v2)) + for id := range m.detailed_lines_v2 { + ids = append(ids, id) + } + return ids + case billinginvoiceline.EdgeLineUsageDiscounts: + ids := make([]ent.Value, 0, len(m.line_usage_discounts)) + for id := range m.line_usage_discounts { + ids = append(ids, id) + } + return ids + case billinginvoiceline.EdgeLineAmountDiscounts: + ids := make([]ent.Value, 0, len(m.line_amount_discounts)) + for id := range m.line_amount_discounts { + ids = append(ids, id) + } + return ids + case billinginvoiceline.EdgeSubscription: + if id := m.subscription; id != nil { + return []ent.Value{*id} + } + case billinginvoiceline.EdgeSubscriptionPhase: + if id := m.subscription_phase; id != nil { + return []ent.Value{*id} + } + case billinginvoiceline.EdgeSubscriptionItem: + if id := m.subscription_item; id != nil { + return []ent.Value{*id} + } + case billinginvoiceline.EdgeCharge: + if id := m.charge; id != nil { + return []ent.Value{*id} + } + case billinginvoiceline.EdgeChargeFlatFeeRunPayment: + if id := m.charge_flat_fee_run_payment; id != nil { + return []ent.Value{*id} + } + case billinginvoiceline.EdgeChargeFlatFeeRunCreditAllocations: + ids := make([]ent.Value, 0, len(m.charge_flat_fee_run_credit_allocations)) + for id := range m.charge_flat_fee_run_credit_allocations { + ids = append(ids, id) + } + return ids + case billinginvoiceline.EdgeChargeFlatFeeRuns: + if id := m.charge_flat_fee_runs; id != nil { + return []ent.Value{*id} + } + case billinginvoiceline.EdgeChargeUsageBasedRun: + if id := m.charge_usage_based_run; id != nil { + return []ent.Value{*id} + } + case billinginvoiceline.EdgeChargeCreditPurchaseInvoicedPayment: + if id := m.charge_credit_purchase_invoiced_payment; id != nil { + return []ent.Value{*id} + } + case billinginvoiceline.EdgeTaxCode: + if id := m.tax_code; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BillingInvoiceLineMutation) RemovedEdges() []string { + edges := make([]string, 0, 19) + if m.removeddetailed_lines != nil { + edges = append(edges, billinginvoiceline.EdgeDetailedLines) + } + if m.removeddetailed_lines_v2 != nil { + edges = append(edges, billinginvoiceline.EdgeDetailedLinesV2) + } + if m.removedline_usage_discounts != nil { + edges = append(edges, billinginvoiceline.EdgeLineUsageDiscounts) + } + if m.removedline_amount_discounts != nil { + edges = append(edges, billinginvoiceline.EdgeLineAmountDiscounts) + } + if m.removedcharge_flat_fee_run_credit_allocations != nil { + edges = append(edges, billinginvoiceline.EdgeChargeFlatFeeRunCreditAllocations) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *BillingInvoiceLineMutation) RemovedIDs(name string) []ent.Value { + switch name { + case billinginvoiceline.EdgeDetailedLines: + ids := make([]ent.Value, 0, len(m.removeddetailed_lines)) + for id := range m.removeddetailed_lines { + ids = append(ids, id) + } + return ids + case billinginvoiceline.EdgeDetailedLinesV2: + ids := make([]ent.Value, 0, len(m.removeddetailed_lines_v2)) + for id := range m.removeddetailed_lines_v2 { + ids = append(ids, id) + } + return ids + case billinginvoiceline.EdgeLineUsageDiscounts: + ids := make([]ent.Value, 0, len(m.removedline_usage_discounts)) + for id := range m.removedline_usage_discounts { + ids = append(ids, id) + } + return ids + case billinginvoiceline.EdgeLineAmountDiscounts: + ids := make([]ent.Value, 0, len(m.removedline_amount_discounts)) + for id := range m.removedline_amount_discounts { + ids = append(ids, id) + } + return ids + case billinginvoiceline.EdgeChargeFlatFeeRunCreditAllocations: + ids := make([]ent.Value, 0, len(m.removedcharge_flat_fee_run_credit_allocations)) + for id := range m.removedcharge_flat_fee_run_credit_allocations { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BillingInvoiceLineMutation) ClearedEdges() []string { + edges := make([]string, 0, 19) + if m.clearedbilling_invoice { + edges = append(edges, billinginvoiceline.EdgeBillingInvoice) + } + if m.clearedsplit_line_group { + edges = append(edges, billinginvoiceline.EdgeSplitLineGroup) + } + if m.clearedflat_fee_line { + edges = append(edges, billinginvoiceline.EdgeFlatFeeLine) + } + if m.clearedusage_based_line { + edges = append(edges, billinginvoiceline.EdgeUsageBasedLine) + } + if m.clearedparent_line { + edges = append(edges, billinginvoiceline.EdgeParentLine) + } + if m.cleareddetailed_lines { + edges = append(edges, billinginvoiceline.EdgeDetailedLines) + } + if m.cleareddetailed_lines_v2 { + edges = append(edges, billinginvoiceline.EdgeDetailedLinesV2) + } + if m.clearedline_usage_discounts { + edges = append(edges, billinginvoiceline.EdgeLineUsageDiscounts) + } + if m.clearedline_amount_discounts { + edges = append(edges, billinginvoiceline.EdgeLineAmountDiscounts) + } + if m.clearedsubscription { + edges = append(edges, billinginvoiceline.EdgeSubscription) + } + if m.clearedsubscription_phase { + edges = append(edges, billinginvoiceline.EdgeSubscriptionPhase) + } + if m.clearedsubscription_item { + edges = append(edges, billinginvoiceline.EdgeSubscriptionItem) + } + if m.clearedcharge { + edges = append(edges, billinginvoiceline.EdgeCharge) + } + if m.clearedcharge_flat_fee_run_payment { + edges = append(edges, billinginvoiceline.EdgeChargeFlatFeeRunPayment) + } + if m.clearedcharge_flat_fee_run_credit_allocations { + edges = append(edges, billinginvoiceline.EdgeChargeFlatFeeRunCreditAllocations) + } + if m.clearedcharge_flat_fee_runs { + edges = append(edges, billinginvoiceline.EdgeChargeFlatFeeRuns) + } + if m.clearedcharge_usage_based_run { + edges = append(edges, billinginvoiceline.EdgeChargeUsageBasedRun) + } + if m.clearedcharge_credit_purchase_invoiced_payment { + edges = append(edges, billinginvoiceline.EdgeChargeCreditPurchaseInvoicedPayment) + } + if m.clearedtax_code { + edges = append(edges, billinginvoiceline.EdgeTaxCode) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BillingInvoiceLineMutation) EdgeCleared(name string) bool { + switch name { + case billinginvoiceline.EdgeBillingInvoice: + return m.clearedbilling_invoice + case billinginvoiceline.EdgeSplitLineGroup: + return m.clearedsplit_line_group + case billinginvoiceline.EdgeFlatFeeLine: + return m.clearedflat_fee_line + case billinginvoiceline.EdgeUsageBasedLine: + return m.clearedusage_based_line + case billinginvoiceline.EdgeParentLine: + return m.clearedparent_line + case billinginvoiceline.EdgeDetailedLines: + return m.cleareddetailed_lines + case billinginvoiceline.EdgeDetailedLinesV2: + return m.cleareddetailed_lines_v2 + case billinginvoiceline.EdgeLineUsageDiscounts: + return m.clearedline_usage_discounts + case billinginvoiceline.EdgeLineAmountDiscounts: + return m.clearedline_amount_discounts + case billinginvoiceline.EdgeSubscription: + return m.clearedsubscription + case billinginvoiceline.EdgeSubscriptionPhase: + return m.clearedsubscription_phase + case billinginvoiceline.EdgeSubscriptionItem: + return m.clearedsubscription_item + case billinginvoiceline.EdgeCharge: + return m.clearedcharge + case billinginvoiceline.EdgeChargeFlatFeeRunPayment: + return m.clearedcharge_flat_fee_run_payment + case billinginvoiceline.EdgeChargeFlatFeeRunCreditAllocations: + return m.clearedcharge_flat_fee_run_credit_allocations + case billinginvoiceline.EdgeChargeFlatFeeRuns: + return m.clearedcharge_flat_fee_runs + case billinginvoiceline.EdgeChargeUsageBasedRun: + return m.clearedcharge_usage_based_run + case billinginvoiceline.EdgeChargeCreditPurchaseInvoicedPayment: + return m.clearedcharge_credit_purchase_invoiced_payment + case billinginvoiceline.EdgeTaxCode: + return m.clearedtax_code + } + 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 *BillingInvoiceLineMutation) ClearEdge(name string) error { + switch name { + case billinginvoiceline.EdgeBillingInvoice: + m.ClearBillingInvoice() + return nil + case billinginvoiceline.EdgeSplitLineGroup: + m.ClearSplitLineGroup() + return nil + case billinginvoiceline.EdgeFlatFeeLine: + m.ClearFlatFeeLine() + return nil + case billinginvoiceline.EdgeUsageBasedLine: + m.ClearUsageBasedLine() + return nil + case billinginvoiceline.EdgeParentLine: + m.ClearParentLine() + return nil + case billinginvoiceline.EdgeSubscription: + m.ClearSubscription() + return nil + case billinginvoiceline.EdgeSubscriptionPhase: + m.ClearSubscriptionPhase() + return nil + case billinginvoiceline.EdgeSubscriptionItem: + m.ClearSubscriptionItem() + return nil + case billinginvoiceline.EdgeCharge: + m.ClearCharge() + return nil + case billinginvoiceline.EdgeChargeFlatFeeRunPayment: + m.ClearChargeFlatFeeRunPayment() + return nil + case billinginvoiceline.EdgeChargeFlatFeeRuns: + m.ClearChargeFlatFeeRuns() + return nil + case billinginvoiceline.EdgeChargeUsageBasedRun: + m.ClearChargeUsageBasedRun() + return nil + case billinginvoiceline.EdgeChargeCreditPurchaseInvoicedPayment: + m.ClearChargeCreditPurchaseInvoicedPayment() + return nil + case billinginvoiceline.EdgeTaxCode: + m.ClearTaxCode() + return nil + } + return fmt.Errorf("unknown BillingInvoiceLine 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 *BillingInvoiceLineMutation) ResetEdge(name string) error { + switch name { + case billinginvoiceline.EdgeBillingInvoice: + m.ResetBillingInvoice() + return nil + case billinginvoiceline.EdgeSplitLineGroup: + m.ResetSplitLineGroup() + return nil + case billinginvoiceline.EdgeFlatFeeLine: + m.ResetFlatFeeLine() + return nil + case billinginvoiceline.EdgeUsageBasedLine: + m.ResetUsageBasedLine() + return nil + case billinginvoiceline.EdgeParentLine: + m.ResetParentLine() + return nil + case billinginvoiceline.EdgeDetailedLines: + m.ResetDetailedLines() + return nil + case billinginvoiceline.EdgeDetailedLinesV2: + m.ResetDetailedLinesV2() + return nil + case billinginvoiceline.EdgeLineUsageDiscounts: + m.ResetLineUsageDiscounts() + return nil + case billinginvoiceline.EdgeLineAmountDiscounts: + m.ResetLineAmountDiscounts() + return nil + case billinginvoiceline.EdgeSubscription: + m.ResetSubscription() + return nil + case billinginvoiceline.EdgeSubscriptionPhase: + m.ResetSubscriptionPhase() + return nil + case billinginvoiceline.EdgeSubscriptionItem: + m.ResetSubscriptionItem() + return nil + case billinginvoiceline.EdgeCharge: + m.ResetCharge() + return nil + case billinginvoiceline.EdgeChargeFlatFeeRunPayment: + m.ResetChargeFlatFeeRunPayment() + return nil + case billinginvoiceline.EdgeChargeFlatFeeRunCreditAllocations: + m.ResetChargeFlatFeeRunCreditAllocations() + return nil + case billinginvoiceline.EdgeChargeFlatFeeRuns: + m.ResetChargeFlatFeeRuns() + return nil + case billinginvoiceline.EdgeChargeUsageBasedRun: + m.ResetChargeUsageBasedRun() + return nil + case billinginvoiceline.EdgeChargeCreditPurchaseInvoicedPayment: + m.ResetChargeCreditPurchaseInvoicedPayment() + return nil + case billinginvoiceline.EdgeTaxCode: + m.ResetTaxCode() + return nil + } + return fmt.Errorf("unknown BillingInvoiceLine edge %s", name) +} + +// BillingInvoiceLineDiscountMutation represents an operation that mutates the BillingInvoiceLineDiscount nodes in the graph. +type BillingInvoiceLineDiscountMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + invoicing_app_external_id *string + child_unique_reference_id *string + description *string + reason *billing.DiscountReasonType + amount *alpacadecimal.Decimal + rounding_amount *alpacadecimal.Decimal + source_discount **billing.DiscountReason + clearedFields map[string]struct{} + billing_invoice_line *string + clearedbilling_invoice_line bool + done bool + oldValue func(context.Context) (*BillingInvoiceLineDiscount, error) + predicates []predicate.BillingInvoiceLineDiscount +} + +var _ ent.Mutation = (*BillingInvoiceLineDiscountMutation)(nil) + +// billinginvoicelinediscountOption allows management of the mutation configuration using functional options. +type billinginvoicelinediscountOption func(*BillingInvoiceLineDiscountMutation) + +// newBillingInvoiceLineDiscountMutation creates new mutation for the BillingInvoiceLineDiscount entity. +func newBillingInvoiceLineDiscountMutation(c config, op Op, opts ...billinginvoicelinediscountOption) *BillingInvoiceLineDiscountMutation { + m := &BillingInvoiceLineDiscountMutation{ + config: c, + op: op, + typ: TypeBillingInvoiceLineDiscount, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBillingInvoiceLineDiscountID sets the ID field of the mutation. +func withBillingInvoiceLineDiscountID(id string) billinginvoicelinediscountOption { + return func(m *BillingInvoiceLineDiscountMutation) { + var ( + err error + once sync.Once + value *BillingInvoiceLineDiscount + ) + m.oldValue = func(ctx context.Context) (*BillingInvoiceLineDiscount, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().BillingInvoiceLineDiscount.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBillingInvoiceLineDiscount sets the old BillingInvoiceLineDiscount of the mutation. +func withBillingInvoiceLineDiscount(node *BillingInvoiceLineDiscount) billinginvoicelinediscountOption { + return func(m *BillingInvoiceLineDiscountMutation) { + m.oldValue = func(context.Context) (*BillingInvoiceLineDiscount, 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 BillingInvoiceLineDiscountMutation) 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 BillingInvoiceLineDiscountMutation) 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 BillingInvoiceLineDiscount entities. +func (m *BillingInvoiceLineDiscountMutation) 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 *BillingInvoiceLineDiscountMutation) 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 *BillingInvoiceLineDiscountMutation) 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().BillingInvoiceLineDiscount.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 *BillingInvoiceLineDiscountMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *BillingInvoiceLineDiscountMutation) 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 BillingInvoiceLineDiscount entity. +// If the BillingInvoiceLineDiscount 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 *BillingInvoiceLineDiscountMutation) 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 *BillingInvoiceLineDiscountMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *BillingInvoiceLineDiscountMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *BillingInvoiceLineDiscountMutation) 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 BillingInvoiceLineDiscount entity. +// If the BillingInvoiceLineDiscount 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 *BillingInvoiceLineDiscountMutation) 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 *BillingInvoiceLineDiscountMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *BillingInvoiceLineDiscountMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *BillingInvoiceLineDiscountMutation) 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 BillingInvoiceLineDiscount entity. +// If the BillingInvoiceLineDiscount 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 *BillingInvoiceLineDiscountMutation) 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 *BillingInvoiceLineDiscountMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *BillingInvoiceLineDiscountMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *BillingInvoiceLineDiscountMutation) 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 BillingInvoiceLineDiscount entity. +// If the BillingInvoiceLineDiscount 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 *BillingInvoiceLineDiscountMutation) 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 *BillingInvoiceLineDiscountMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[billinginvoicelinediscount.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *BillingInvoiceLineDiscountMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[billinginvoicelinediscount.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *BillingInvoiceLineDiscountMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, billinginvoicelinediscount.FieldDeletedAt) +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (m *BillingInvoiceLineDiscountMutation) SetInvoicingAppExternalID(s string) { + m.invoicing_app_external_id = &s +} + +// InvoicingAppExternalID returns the value of the "invoicing_app_external_id" field in the mutation. +func (m *BillingInvoiceLineDiscountMutation) InvoicingAppExternalID() (r string, exists bool) { + v := m.invoicing_app_external_id + if v == nil { + return + } + return *v, true +} + +// OldInvoicingAppExternalID returns the old "invoicing_app_external_id" field's value of the BillingInvoiceLineDiscount entity. +// If the BillingInvoiceLineDiscount 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 *BillingInvoiceLineDiscountMutation) OldInvoicingAppExternalID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoicingAppExternalID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoicingAppExternalID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoicingAppExternalID: %w", err) + } + return oldValue.InvoicingAppExternalID, nil +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (m *BillingInvoiceLineDiscountMutation) ClearInvoicingAppExternalID() { + m.invoicing_app_external_id = nil + m.clearedFields[billinginvoicelinediscount.FieldInvoicingAppExternalID] = struct{}{} +} + +// InvoicingAppExternalIDCleared returns if the "invoicing_app_external_id" field was cleared in this mutation. +func (m *BillingInvoiceLineDiscountMutation) InvoicingAppExternalIDCleared() bool { + _, ok := m.clearedFields[billinginvoicelinediscount.FieldInvoicingAppExternalID] + return ok +} + +// ResetInvoicingAppExternalID resets all changes to the "invoicing_app_external_id" field. +func (m *BillingInvoiceLineDiscountMutation) ResetInvoicingAppExternalID() { + m.invoicing_app_external_id = nil + delete(m.clearedFields, billinginvoicelinediscount.FieldInvoicingAppExternalID) +} + +// SetLineID sets the "line_id" field. +func (m *BillingInvoiceLineDiscountMutation) SetLineID(s string) { + m.billing_invoice_line = &s +} + +// LineID returns the value of the "line_id" field in the mutation. +func (m *BillingInvoiceLineDiscountMutation) LineID() (r string, exists bool) { + v := m.billing_invoice_line + if v == nil { + return + } + return *v, true +} + +// OldLineID returns the old "line_id" field's value of the BillingInvoiceLineDiscount entity. +// If the BillingInvoiceLineDiscount 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 *BillingInvoiceLineDiscountMutation) 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 *BillingInvoiceLineDiscountMutation) ResetLineID() { + m.billing_invoice_line = nil +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (m *BillingInvoiceLineDiscountMutation) SetChildUniqueReferenceID(s string) { + m.child_unique_reference_id = &s +} + +// ChildUniqueReferenceID returns the value of the "child_unique_reference_id" field in the mutation. +func (m *BillingInvoiceLineDiscountMutation) ChildUniqueReferenceID() (r string, exists bool) { + v := m.child_unique_reference_id + if v == nil { + return + } + return *v, true +} + +// OldChildUniqueReferenceID returns the old "child_unique_reference_id" field's value of the BillingInvoiceLineDiscount entity. +// If the BillingInvoiceLineDiscount 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 *BillingInvoiceLineDiscountMutation) OldChildUniqueReferenceID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldChildUniqueReferenceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldChildUniqueReferenceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldChildUniqueReferenceID: %w", err) + } + return oldValue.ChildUniqueReferenceID, nil +} + +// ClearChildUniqueReferenceID clears the value of the "child_unique_reference_id" field. +func (m *BillingInvoiceLineDiscountMutation) ClearChildUniqueReferenceID() { + m.child_unique_reference_id = nil + m.clearedFields[billinginvoicelinediscount.FieldChildUniqueReferenceID] = struct{}{} +} + +// ChildUniqueReferenceIDCleared returns if the "child_unique_reference_id" field was cleared in this mutation. +func (m *BillingInvoiceLineDiscountMutation) ChildUniqueReferenceIDCleared() bool { + _, ok := m.clearedFields[billinginvoicelinediscount.FieldChildUniqueReferenceID] + return ok +} + +// ResetChildUniqueReferenceID resets all changes to the "child_unique_reference_id" field. +func (m *BillingInvoiceLineDiscountMutation) ResetChildUniqueReferenceID() { + m.child_unique_reference_id = nil + delete(m.clearedFields, billinginvoicelinediscount.FieldChildUniqueReferenceID) +} + +// SetDescription sets the "description" field. +func (m *BillingInvoiceLineDiscountMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *BillingInvoiceLineDiscountMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the BillingInvoiceLineDiscount entity. +// If the BillingInvoiceLineDiscount 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 *BillingInvoiceLineDiscountMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *BillingInvoiceLineDiscountMutation) ClearDescription() { + m.description = nil + m.clearedFields[billinginvoicelinediscount.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *BillingInvoiceLineDiscountMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[billinginvoicelinediscount.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *BillingInvoiceLineDiscountMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, billinginvoicelinediscount.FieldDescription) +} + +// SetReason sets the "reason" field. +func (m *BillingInvoiceLineDiscountMutation) SetReason(brt billing.DiscountReasonType) { + m.reason = &brt +} + +// Reason returns the value of the "reason" field in the mutation. +func (m *BillingInvoiceLineDiscountMutation) Reason() (r billing.DiscountReasonType, exists bool) { + v := m.reason + if v == nil { + return + } + return *v, true +} + +// OldReason returns the old "reason" field's value of the BillingInvoiceLineDiscount entity. +// If the BillingInvoiceLineDiscount 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 *BillingInvoiceLineDiscountMutation) OldReason(ctx context.Context) (v billing.DiscountReasonType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldReason is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldReason requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldReason: %w", err) + } + return oldValue.Reason, nil +} + +// ResetReason resets all changes to the "reason" field. +func (m *BillingInvoiceLineDiscountMutation) ResetReason() { + m.reason = nil +} + +// SetAmount sets the "amount" field. +func (m *BillingInvoiceLineDiscountMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *BillingInvoiceLineDiscountMutation) 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 BillingInvoiceLineDiscount entity. +// If the BillingInvoiceLineDiscount 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 *BillingInvoiceLineDiscountMutation) 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 *BillingInvoiceLineDiscountMutation) ResetAmount() { + m.amount = nil +} + +// SetRoundingAmount sets the "rounding_amount" field. +func (m *BillingInvoiceLineDiscountMutation) SetRoundingAmount(a alpacadecimal.Decimal) { + m.rounding_amount = &a +} + +// RoundingAmount returns the value of the "rounding_amount" field in the mutation. +func (m *BillingInvoiceLineDiscountMutation) RoundingAmount() (r alpacadecimal.Decimal, exists bool) { + v := m.rounding_amount + if v == nil { + return + } + return *v, true +} + +// OldRoundingAmount returns the old "rounding_amount" field's value of the BillingInvoiceLineDiscount entity. +// If the BillingInvoiceLineDiscount 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 *BillingInvoiceLineDiscountMutation) OldRoundingAmount(ctx context.Context) (v *alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRoundingAmount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRoundingAmount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRoundingAmount: %w", err) + } + return oldValue.RoundingAmount, nil +} + +// ClearRoundingAmount clears the value of the "rounding_amount" field. +func (m *BillingInvoiceLineDiscountMutation) ClearRoundingAmount() { + m.rounding_amount = nil + m.clearedFields[billinginvoicelinediscount.FieldRoundingAmount] = struct{}{} +} + +// RoundingAmountCleared returns if the "rounding_amount" field was cleared in this mutation. +func (m *BillingInvoiceLineDiscountMutation) RoundingAmountCleared() bool { + _, ok := m.clearedFields[billinginvoicelinediscount.FieldRoundingAmount] + return ok +} + +// ResetRoundingAmount resets all changes to the "rounding_amount" field. +func (m *BillingInvoiceLineDiscountMutation) ResetRoundingAmount() { + m.rounding_amount = nil + delete(m.clearedFields, billinginvoicelinediscount.FieldRoundingAmount) +} + +// SetSourceDiscount sets the "source_discount" field. +func (m *BillingInvoiceLineDiscountMutation) SetSourceDiscount(br *billing.DiscountReason) { + m.source_discount = &br +} + +// SourceDiscount returns the value of the "source_discount" field in the mutation. +func (m *BillingInvoiceLineDiscountMutation) SourceDiscount() (r *billing.DiscountReason, exists bool) { + v := m.source_discount + if v == nil { + return + } + return *v, true +} + +// OldSourceDiscount returns the old "source_discount" field's value of the BillingInvoiceLineDiscount entity. +// If the BillingInvoiceLineDiscount 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 *BillingInvoiceLineDiscountMutation) OldSourceDiscount(ctx context.Context) (v *billing.DiscountReason, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSourceDiscount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSourceDiscount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSourceDiscount: %w", err) + } + return oldValue.SourceDiscount, nil +} + +// ClearSourceDiscount clears the value of the "source_discount" field. +func (m *BillingInvoiceLineDiscountMutation) ClearSourceDiscount() { + m.source_discount = nil + m.clearedFields[billinginvoicelinediscount.FieldSourceDiscount] = struct{}{} +} + +// SourceDiscountCleared returns if the "source_discount" field was cleared in this mutation. +func (m *BillingInvoiceLineDiscountMutation) SourceDiscountCleared() bool { + _, ok := m.clearedFields[billinginvoicelinediscount.FieldSourceDiscount] + return ok +} + +// ResetSourceDiscount resets all changes to the "source_discount" field. +func (m *BillingInvoiceLineDiscountMutation) ResetSourceDiscount() { + m.source_discount = nil + delete(m.clearedFields, billinginvoicelinediscount.FieldSourceDiscount) +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by id. +func (m *BillingInvoiceLineDiscountMutation) SetBillingInvoiceLineID(id string) { + m.billing_invoice_line = &id +} + +// ClearBillingInvoiceLine clears the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (m *BillingInvoiceLineDiscountMutation) ClearBillingInvoiceLine() { + m.clearedbilling_invoice_line = true + m.clearedFields[billinginvoicelinediscount.FieldLineID] = struct{}{} +} + +// BillingInvoiceLineCleared reports if the "billing_invoice_line" edge to the BillingInvoiceLine entity was cleared. +func (m *BillingInvoiceLineDiscountMutation) BillingInvoiceLineCleared() bool { + return m.clearedbilling_invoice_line +} + +// BillingInvoiceLineID returns the "billing_invoice_line" edge ID in the mutation. +func (m *BillingInvoiceLineDiscountMutation) BillingInvoiceLineID() (id string, exists bool) { + if m.billing_invoice_line != nil { + return *m.billing_invoice_line, true + } + return +} + +// BillingInvoiceLineIDs returns the "billing_invoice_line" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BillingInvoiceLineID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceLineDiscountMutation) BillingInvoiceLineIDs() (ids []string) { + if id := m.billing_invoice_line; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBillingInvoiceLine resets all changes to the "billing_invoice_line" edge. +func (m *BillingInvoiceLineDiscountMutation) ResetBillingInvoiceLine() { + m.billing_invoice_line = nil + m.clearedbilling_invoice_line = false +} + +// Where appends a list predicates to the BillingInvoiceLineDiscountMutation builder. +func (m *BillingInvoiceLineDiscountMutation) Where(ps ...predicate.BillingInvoiceLineDiscount) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BillingInvoiceLineDiscountMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BillingInvoiceLineDiscountMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillingInvoiceLineDiscount, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BillingInvoiceLineDiscountMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BillingInvoiceLineDiscountMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BillingInvoiceLineDiscount). +func (m *BillingInvoiceLineDiscountMutation) 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 *BillingInvoiceLineDiscountMutation) Fields() []string { + fields := make([]string, 0, 12) + if m.namespace != nil { + fields = append(fields, billinginvoicelinediscount.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, billinginvoicelinediscount.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, billinginvoicelinediscount.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, billinginvoicelinediscount.FieldDeletedAt) + } + if m.invoicing_app_external_id != nil { + fields = append(fields, billinginvoicelinediscount.FieldInvoicingAppExternalID) + } + if m.billing_invoice_line != nil { + fields = append(fields, billinginvoicelinediscount.FieldLineID) + } + if m.child_unique_reference_id != nil { + fields = append(fields, billinginvoicelinediscount.FieldChildUniqueReferenceID) + } + if m.description != nil { + fields = append(fields, billinginvoicelinediscount.FieldDescription) + } + if m.reason != nil { + fields = append(fields, billinginvoicelinediscount.FieldReason) + } + if m.amount != nil { + fields = append(fields, billinginvoicelinediscount.FieldAmount) + } + if m.rounding_amount != nil { + fields = append(fields, billinginvoicelinediscount.FieldRoundingAmount) + } + if m.source_discount != nil { + fields = append(fields, billinginvoicelinediscount.FieldSourceDiscount) + } + 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 *BillingInvoiceLineDiscountMutation) Field(name string) (ent.Value, bool) { + switch name { + case billinginvoicelinediscount.FieldNamespace: + return m.Namespace() + case billinginvoicelinediscount.FieldCreatedAt: + return m.CreatedAt() + case billinginvoicelinediscount.FieldUpdatedAt: + return m.UpdatedAt() + case billinginvoicelinediscount.FieldDeletedAt: + return m.DeletedAt() + case billinginvoicelinediscount.FieldInvoicingAppExternalID: + return m.InvoicingAppExternalID() + case billinginvoicelinediscount.FieldLineID: + return m.LineID() + case billinginvoicelinediscount.FieldChildUniqueReferenceID: + return m.ChildUniqueReferenceID() + case billinginvoicelinediscount.FieldDescription: + return m.Description() + case billinginvoicelinediscount.FieldReason: + return m.Reason() + case billinginvoicelinediscount.FieldAmount: + return m.Amount() + case billinginvoicelinediscount.FieldRoundingAmount: + return m.RoundingAmount() + case billinginvoicelinediscount.FieldSourceDiscount: + return m.SourceDiscount() + } + 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 *BillingInvoiceLineDiscountMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case billinginvoicelinediscount.FieldNamespace: + return m.OldNamespace(ctx) + case billinginvoicelinediscount.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case billinginvoicelinediscount.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case billinginvoicelinediscount.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case billinginvoicelinediscount.FieldInvoicingAppExternalID: + return m.OldInvoicingAppExternalID(ctx) + case billinginvoicelinediscount.FieldLineID: + return m.OldLineID(ctx) + case billinginvoicelinediscount.FieldChildUniqueReferenceID: + return m.OldChildUniqueReferenceID(ctx) + case billinginvoicelinediscount.FieldDescription: + return m.OldDescription(ctx) + case billinginvoicelinediscount.FieldReason: + return m.OldReason(ctx) + case billinginvoicelinediscount.FieldAmount: + return m.OldAmount(ctx) + case billinginvoicelinediscount.FieldRoundingAmount: + return m.OldRoundingAmount(ctx) + case billinginvoicelinediscount.FieldSourceDiscount: + return m.OldSourceDiscount(ctx) + } + return nil, fmt.Errorf("unknown BillingInvoiceLineDiscount 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 *BillingInvoiceLineDiscountMutation) SetField(name string, value ent.Value) error { + switch name { + case billinginvoicelinediscount.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case billinginvoicelinediscount.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 billinginvoicelinediscount.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 billinginvoicelinediscount.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 billinginvoicelinediscount.FieldInvoicingAppExternalID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoicingAppExternalID(v) + return nil + case billinginvoicelinediscount.FieldLineID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLineID(v) + return nil + case billinginvoicelinediscount.FieldChildUniqueReferenceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChildUniqueReferenceID(v) + return nil + case billinginvoicelinediscount.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case billinginvoicelinediscount.FieldReason: + v, ok := value.(billing.DiscountReasonType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetReason(v) + return nil + case billinginvoicelinediscount.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 billinginvoicelinediscount.FieldRoundingAmount: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRoundingAmount(v) + return nil + case billinginvoicelinediscount.FieldSourceDiscount: + v, ok := value.(*billing.DiscountReason) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSourceDiscount(v) + return nil + } + return fmt.Errorf("unknown BillingInvoiceLineDiscount field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BillingInvoiceLineDiscountMutation) 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 *BillingInvoiceLineDiscountMutation) 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 *BillingInvoiceLineDiscountMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown BillingInvoiceLineDiscount numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BillingInvoiceLineDiscountMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(billinginvoicelinediscount.FieldDeletedAt) { + fields = append(fields, billinginvoicelinediscount.FieldDeletedAt) + } + if m.FieldCleared(billinginvoicelinediscount.FieldInvoicingAppExternalID) { + fields = append(fields, billinginvoicelinediscount.FieldInvoicingAppExternalID) + } + if m.FieldCleared(billinginvoicelinediscount.FieldChildUniqueReferenceID) { + fields = append(fields, billinginvoicelinediscount.FieldChildUniqueReferenceID) + } + if m.FieldCleared(billinginvoicelinediscount.FieldDescription) { + fields = append(fields, billinginvoicelinediscount.FieldDescription) + } + if m.FieldCleared(billinginvoicelinediscount.FieldRoundingAmount) { + fields = append(fields, billinginvoicelinediscount.FieldRoundingAmount) + } + if m.FieldCleared(billinginvoicelinediscount.FieldSourceDiscount) { + fields = append(fields, billinginvoicelinediscount.FieldSourceDiscount) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BillingInvoiceLineDiscountMutation) 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 *BillingInvoiceLineDiscountMutation) ClearField(name string) error { + switch name { + case billinginvoicelinediscount.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case billinginvoicelinediscount.FieldInvoicingAppExternalID: + m.ClearInvoicingAppExternalID() + return nil + case billinginvoicelinediscount.FieldChildUniqueReferenceID: + m.ClearChildUniqueReferenceID() + return nil + case billinginvoicelinediscount.FieldDescription: + m.ClearDescription() + return nil + case billinginvoicelinediscount.FieldRoundingAmount: + m.ClearRoundingAmount() + return nil + case billinginvoicelinediscount.FieldSourceDiscount: + m.ClearSourceDiscount() + return nil + } + return fmt.Errorf("unknown BillingInvoiceLineDiscount 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 *BillingInvoiceLineDiscountMutation) ResetField(name string) error { + switch name { + case billinginvoicelinediscount.FieldNamespace: + m.ResetNamespace() + return nil + case billinginvoicelinediscount.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case billinginvoicelinediscount.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case billinginvoicelinediscount.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case billinginvoicelinediscount.FieldInvoicingAppExternalID: + m.ResetInvoicingAppExternalID() + return nil + case billinginvoicelinediscount.FieldLineID: + m.ResetLineID() + return nil + case billinginvoicelinediscount.FieldChildUniqueReferenceID: + m.ResetChildUniqueReferenceID() + return nil + case billinginvoicelinediscount.FieldDescription: + m.ResetDescription() + return nil + case billinginvoicelinediscount.FieldReason: + m.ResetReason() + return nil + case billinginvoicelinediscount.FieldAmount: + m.ResetAmount() + return nil + case billinginvoicelinediscount.FieldRoundingAmount: + m.ResetRoundingAmount() + return nil + case billinginvoicelinediscount.FieldSourceDiscount: + m.ResetSourceDiscount() + return nil + } + return fmt.Errorf("unknown BillingInvoiceLineDiscount field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BillingInvoiceLineDiscountMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.billing_invoice_line != nil { + edges = append(edges, billinginvoicelinediscount.EdgeBillingInvoiceLine) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BillingInvoiceLineDiscountMutation) AddedIDs(name string) []ent.Value { + switch name { + case billinginvoicelinediscount.EdgeBillingInvoiceLine: + if id := m.billing_invoice_line; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BillingInvoiceLineDiscountMutation) 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 *BillingInvoiceLineDiscountMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BillingInvoiceLineDiscountMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedbilling_invoice_line { + edges = append(edges, billinginvoicelinediscount.EdgeBillingInvoiceLine) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BillingInvoiceLineDiscountMutation) EdgeCleared(name string) bool { + switch name { + case billinginvoicelinediscount.EdgeBillingInvoiceLine: + return m.clearedbilling_invoice_line + } + 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 *BillingInvoiceLineDiscountMutation) ClearEdge(name string) error { + switch name { + case billinginvoicelinediscount.EdgeBillingInvoiceLine: + m.ClearBillingInvoiceLine() + return nil + } + return fmt.Errorf("unknown BillingInvoiceLineDiscount 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 *BillingInvoiceLineDiscountMutation) ResetEdge(name string) error { + switch name { + case billinginvoicelinediscount.EdgeBillingInvoiceLine: + m.ResetBillingInvoiceLine() + return nil + } + return fmt.Errorf("unknown BillingInvoiceLineDiscount edge %s", name) +} + +// BillingInvoiceLineUsageDiscountMutation represents an operation that mutates the BillingInvoiceLineUsageDiscount nodes in the graph. +type BillingInvoiceLineUsageDiscountMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + invoicing_app_external_id *string + child_unique_reference_id *string + description *string + reason *billing.DiscountReasonType + quantity *alpacadecimal.Decimal + pre_line_period_quantity *alpacadecimal.Decimal + reason_details **billing.DiscountReason + clearedFields map[string]struct{} + billing_invoice_line *string + clearedbilling_invoice_line bool + done bool + oldValue func(context.Context) (*BillingInvoiceLineUsageDiscount, error) + predicates []predicate.BillingInvoiceLineUsageDiscount +} + +var _ ent.Mutation = (*BillingInvoiceLineUsageDiscountMutation)(nil) + +// billinginvoicelineusagediscountOption allows management of the mutation configuration using functional options. +type billinginvoicelineusagediscountOption func(*BillingInvoiceLineUsageDiscountMutation) + +// newBillingInvoiceLineUsageDiscountMutation creates new mutation for the BillingInvoiceLineUsageDiscount entity. +func newBillingInvoiceLineUsageDiscountMutation(c config, op Op, opts ...billinginvoicelineusagediscountOption) *BillingInvoiceLineUsageDiscountMutation { + m := &BillingInvoiceLineUsageDiscountMutation{ + config: c, + op: op, + typ: TypeBillingInvoiceLineUsageDiscount, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBillingInvoiceLineUsageDiscountID sets the ID field of the mutation. +func withBillingInvoiceLineUsageDiscountID(id string) billinginvoicelineusagediscountOption { + return func(m *BillingInvoiceLineUsageDiscountMutation) { + var ( + err error + once sync.Once + value *BillingInvoiceLineUsageDiscount + ) + m.oldValue = func(ctx context.Context) (*BillingInvoiceLineUsageDiscount, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().BillingInvoiceLineUsageDiscount.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBillingInvoiceLineUsageDiscount sets the old BillingInvoiceLineUsageDiscount of the mutation. +func withBillingInvoiceLineUsageDiscount(node *BillingInvoiceLineUsageDiscount) billinginvoicelineusagediscountOption { + return func(m *BillingInvoiceLineUsageDiscountMutation) { + m.oldValue = func(context.Context) (*BillingInvoiceLineUsageDiscount, 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 BillingInvoiceLineUsageDiscountMutation) 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 BillingInvoiceLineUsageDiscountMutation) 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 BillingInvoiceLineUsageDiscount entities. +func (m *BillingInvoiceLineUsageDiscountMutation) 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 *BillingInvoiceLineUsageDiscountMutation) 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 *BillingInvoiceLineUsageDiscountMutation) 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().BillingInvoiceLineUsageDiscount.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 *BillingInvoiceLineUsageDiscountMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) 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 BillingInvoiceLineUsageDiscount entity. +// If the BillingInvoiceLineUsageDiscount 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 *BillingInvoiceLineUsageDiscountMutation) 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 *BillingInvoiceLineUsageDiscountMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *BillingInvoiceLineUsageDiscountMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) 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 BillingInvoiceLineUsageDiscount entity. +// If the BillingInvoiceLineUsageDiscount 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 *BillingInvoiceLineUsageDiscountMutation) 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 *BillingInvoiceLineUsageDiscountMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *BillingInvoiceLineUsageDiscountMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) 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 BillingInvoiceLineUsageDiscount entity. +// If the BillingInvoiceLineUsageDiscount 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 *BillingInvoiceLineUsageDiscountMutation) 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 *BillingInvoiceLineUsageDiscountMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *BillingInvoiceLineUsageDiscountMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) 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 BillingInvoiceLineUsageDiscount entity. +// If the BillingInvoiceLineUsageDiscount 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 *BillingInvoiceLineUsageDiscountMutation) 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 *BillingInvoiceLineUsageDiscountMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[billinginvoicelineusagediscount.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[billinginvoicelineusagediscount.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *BillingInvoiceLineUsageDiscountMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, billinginvoicelineusagediscount.FieldDeletedAt) +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (m *BillingInvoiceLineUsageDiscountMutation) SetInvoicingAppExternalID(s string) { + m.invoicing_app_external_id = &s +} + +// InvoicingAppExternalID returns the value of the "invoicing_app_external_id" field in the mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) InvoicingAppExternalID() (r string, exists bool) { + v := m.invoicing_app_external_id + if v == nil { + return + } + return *v, true +} + +// OldInvoicingAppExternalID returns the old "invoicing_app_external_id" field's value of the BillingInvoiceLineUsageDiscount entity. +// If the BillingInvoiceLineUsageDiscount 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 *BillingInvoiceLineUsageDiscountMutation) OldInvoicingAppExternalID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoicingAppExternalID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoicingAppExternalID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoicingAppExternalID: %w", err) + } + return oldValue.InvoicingAppExternalID, nil +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (m *BillingInvoiceLineUsageDiscountMutation) ClearInvoicingAppExternalID() { + m.invoicing_app_external_id = nil + m.clearedFields[billinginvoicelineusagediscount.FieldInvoicingAppExternalID] = struct{}{} +} + +// InvoicingAppExternalIDCleared returns if the "invoicing_app_external_id" field was cleared in this mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) InvoicingAppExternalIDCleared() bool { + _, ok := m.clearedFields[billinginvoicelineusagediscount.FieldInvoicingAppExternalID] + return ok +} + +// ResetInvoicingAppExternalID resets all changes to the "invoicing_app_external_id" field. +func (m *BillingInvoiceLineUsageDiscountMutation) ResetInvoicingAppExternalID() { + m.invoicing_app_external_id = nil + delete(m.clearedFields, billinginvoicelineusagediscount.FieldInvoicingAppExternalID) +} + +// SetLineID sets the "line_id" field. +func (m *BillingInvoiceLineUsageDiscountMutation) SetLineID(s string) { + m.billing_invoice_line = &s +} + +// LineID returns the value of the "line_id" field in the mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) LineID() (r string, exists bool) { + v := m.billing_invoice_line + if v == nil { + return + } + return *v, true +} + +// OldLineID returns the old "line_id" field's value of the BillingInvoiceLineUsageDiscount entity. +// If the BillingInvoiceLineUsageDiscount 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 *BillingInvoiceLineUsageDiscountMutation) 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 *BillingInvoiceLineUsageDiscountMutation) ResetLineID() { + m.billing_invoice_line = nil +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (m *BillingInvoiceLineUsageDiscountMutation) SetChildUniqueReferenceID(s string) { + m.child_unique_reference_id = &s +} + +// ChildUniqueReferenceID returns the value of the "child_unique_reference_id" field in the mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) ChildUniqueReferenceID() (r string, exists bool) { + v := m.child_unique_reference_id + if v == nil { + return + } + return *v, true +} + +// OldChildUniqueReferenceID returns the old "child_unique_reference_id" field's value of the BillingInvoiceLineUsageDiscount entity. +// If the BillingInvoiceLineUsageDiscount 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 *BillingInvoiceLineUsageDiscountMutation) OldChildUniqueReferenceID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldChildUniqueReferenceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldChildUniqueReferenceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldChildUniqueReferenceID: %w", err) + } + return oldValue.ChildUniqueReferenceID, nil +} + +// ClearChildUniqueReferenceID clears the value of the "child_unique_reference_id" field. +func (m *BillingInvoiceLineUsageDiscountMutation) ClearChildUniqueReferenceID() { + m.child_unique_reference_id = nil + m.clearedFields[billinginvoicelineusagediscount.FieldChildUniqueReferenceID] = struct{}{} +} + +// ChildUniqueReferenceIDCleared returns if the "child_unique_reference_id" field was cleared in this mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) ChildUniqueReferenceIDCleared() bool { + _, ok := m.clearedFields[billinginvoicelineusagediscount.FieldChildUniqueReferenceID] + return ok +} + +// ResetChildUniqueReferenceID resets all changes to the "child_unique_reference_id" field. +func (m *BillingInvoiceLineUsageDiscountMutation) ResetChildUniqueReferenceID() { + m.child_unique_reference_id = nil + delete(m.clearedFields, billinginvoicelineusagediscount.FieldChildUniqueReferenceID) +} + +// SetDescription sets the "description" field. +func (m *BillingInvoiceLineUsageDiscountMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the BillingInvoiceLineUsageDiscount entity. +// If the BillingInvoiceLineUsageDiscount 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 *BillingInvoiceLineUsageDiscountMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *BillingInvoiceLineUsageDiscountMutation) ClearDescription() { + m.description = nil + m.clearedFields[billinginvoicelineusagediscount.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[billinginvoicelineusagediscount.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *BillingInvoiceLineUsageDiscountMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, billinginvoicelineusagediscount.FieldDescription) +} + +// SetReason sets the "reason" field. +func (m *BillingInvoiceLineUsageDiscountMutation) SetReason(brt billing.DiscountReasonType) { + m.reason = &brt +} + +// Reason returns the value of the "reason" field in the mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) Reason() (r billing.DiscountReasonType, exists bool) { + v := m.reason + if v == nil { + return + } + return *v, true +} + +// OldReason returns the old "reason" field's value of the BillingInvoiceLineUsageDiscount entity. +// If the BillingInvoiceLineUsageDiscount 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 *BillingInvoiceLineUsageDiscountMutation) OldReason(ctx context.Context) (v billing.DiscountReasonType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldReason is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldReason requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldReason: %w", err) + } + return oldValue.Reason, nil +} + +// ResetReason resets all changes to the "reason" field. +func (m *BillingInvoiceLineUsageDiscountMutation) ResetReason() { + m.reason = nil +} + +// SetQuantity sets the "quantity" field. +func (m *BillingInvoiceLineUsageDiscountMutation) SetQuantity(a alpacadecimal.Decimal) { + m.quantity = &a +} + +// Quantity returns the value of the "quantity" field in the mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) Quantity() (r alpacadecimal.Decimal, exists bool) { + v := m.quantity + if v == nil { + return + } + return *v, true +} + +// OldQuantity returns the old "quantity" field's value of the BillingInvoiceLineUsageDiscount entity. +// If the BillingInvoiceLineUsageDiscount 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 *BillingInvoiceLineUsageDiscountMutation) OldQuantity(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldQuantity is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldQuantity requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldQuantity: %w", err) + } + return oldValue.Quantity, nil +} + +// ResetQuantity resets all changes to the "quantity" field. +func (m *BillingInvoiceLineUsageDiscountMutation) ResetQuantity() { + m.quantity = nil +} + +// SetPreLinePeriodQuantity sets the "pre_line_period_quantity" field. +func (m *BillingInvoiceLineUsageDiscountMutation) SetPreLinePeriodQuantity(a alpacadecimal.Decimal) { + m.pre_line_period_quantity = &a +} + +// PreLinePeriodQuantity returns the value of the "pre_line_period_quantity" field in the mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) PreLinePeriodQuantity() (r alpacadecimal.Decimal, exists bool) { + v := m.pre_line_period_quantity + if v == nil { + return + } + return *v, true +} + +// OldPreLinePeriodQuantity returns the old "pre_line_period_quantity" field's value of the BillingInvoiceLineUsageDiscount entity. +// If the BillingInvoiceLineUsageDiscount 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 *BillingInvoiceLineUsageDiscountMutation) OldPreLinePeriodQuantity(ctx context.Context) (v *alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPreLinePeriodQuantity is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPreLinePeriodQuantity requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPreLinePeriodQuantity: %w", err) + } + return oldValue.PreLinePeriodQuantity, nil +} + +// ClearPreLinePeriodQuantity clears the value of the "pre_line_period_quantity" field. +func (m *BillingInvoiceLineUsageDiscountMutation) ClearPreLinePeriodQuantity() { + m.pre_line_period_quantity = nil + m.clearedFields[billinginvoicelineusagediscount.FieldPreLinePeriodQuantity] = struct{}{} +} + +// PreLinePeriodQuantityCleared returns if the "pre_line_period_quantity" field was cleared in this mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) PreLinePeriodQuantityCleared() bool { + _, ok := m.clearedFields[billinginvoicelineusagediscount.FieldPreLinePeriodQuantity] + return ok +} + +// ResetPreLinePeriodQuantity resets all changes to the "pre_line_period_quantity" field. +func (m *BillingInvoiceLineUsageDiscountMutation) ResetPreLinePeriodQuantity() { + m.pre_line_period_quantity = nil + delete(m.clearedFields, billinginvoicelineusagediscount.FieldPreLinePeriodQuantity) +} + +// SetReasonDetails sets the "reason_details" field. +func (m *BillingInvoiceLineUsageDiscountMutation) SetReasonDetails(br *billing.DiscountReason) { + m.reason_details = &br +} + +// ReasonDetails returns the value of the "reason_details" field in the mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) ReasonDetails() (r *billing.DiscountReason, exists bool) { + v := m.reason_details + if v == nil { + return + } + return *v, true +} + +// OldReasonDetails returns the old "reason_details" field's value of the BillingInvoiceLineUsageDiscount entity. +// If the BillingInvoiceLineUsageDiscount 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 *BillingInvoiceLineUsageDiscountMutation) OldReasonDetails(ctx context.Context) (v *billing.DiscountReason, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldReasonDetails is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldReasonDetails requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldReasonDetails: %w", err) + } + return oldValue.ReasonDetails, nil +} + +// ClearReasonDetails clears the value of the "reason_details" field. +func (m *BillingInvoiceLineUsageDiscountMutation) ClearReasonDetails() { + m.reason_details = nil + m.clearedFields[billinginvoicelineusagediscount.FieldReasonDetails] = struct{}{} +} + +// ReasonDetailsCleared returns if the "reason_details" field was cleared in this mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) ReasonDetailsCleared() bool { + _, ok := m.clearedFields[billinginvoicelineusagediscount.FieldReasonDetails] + return ok +} + +// ResetReasonDetails resets all changes to the "reason_details" field. +func (m *BillingInvoiceLineUsageDiscountMutation) ResetReasonDetails() { + m.reason_details = nil + delete(m.clearedFields, billinginvoicelineusagediscount.FieldReasonDetails) +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by id. +func (m *BillingInvoiceLineUsageDiscountMutation) SetBillingInvoiceLineID(id string) { + m.billing_invoice_line = &id +} + +// ClearBillingInvoiceLine clears the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (m *BillingInvoiceLineUsageDiscountMutation) ClearBillingInvoiceLine() { + m.clearedbilling_invoice_line = true + m.clearedFields[billinginvoicelineusagediscount.FieldLineID] = struct{}{} +} + +// BillingInvoiceLineCleared reports if the "billing_invoice_line" edge to the BillingInvoiceLine entity was cleared. +func (m *BillingInvoiceLineUsageDiscountMutation) BillingInvoiceLineCleared() bool { + return m.clearedbilling_invoice_line +} + +// BillingInvoiceLineID returns the "billing_invoice_line" edge ID in the mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) BillingInvoiceLineID() (id string, exists bool) { + if m.billing_invoice_line != nil { + return *m.billing_invoice_line, true + } + return +} + +// BillingInvoiceLineIDs returns the "billing_invoice_line" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BillingInvoiceLineID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceLineUsageDiscountMutation) BillingInvoiceLineIDs() (ids []string) { + if id := m.billing_invoice_line; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBillingInvoiceLine resets all changes to the "billing_invoice_line" edge. +func (m *BillingInvoiceLineUsageDiscountMutation) ResetBillingInvoiceLine() { + m.billing_invoice_line = nil + m.clearedbilling_invoice_line = false +} + +// Where appends a list predicates to the BillingInvoiceLineUsageDiscountMutation builder. +func (m *BillingInvoiceLineUsageDiscountMutation) Where(ps ...predicate.BillingInvoiceLineUsageDiscount) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BillingInvoiceLineUsageDiscountMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BillingInvoiceLineUsageDiscountMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillingInvoiceLineUsageDiscount, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BillingInvoiceLineUsageDiscountMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BillingInvoiceLineUsageDiscountMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BillingInvoiceLineUsageDiscount). +func (m *BillingInvoiceLineUsageDiscountMutation) 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 *BillingInvoiceLineUsageDiscountMutation) Fields() []string { + fields := make([]string, 0, 12) + if m.namespace != nil { + fields = append(fields, billinginvoicelineusagediscount.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, billinginvoicelineusagediscount.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, billinginvoicelineusagediscount.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, billinginvoicelineusagediscount.FieldDeletedAt) + } + if m.invoicing_app_external_id != nil { + fields = append(fields, billinginvoicelineusagediscount.FieldInvoicingAppExternalID) + } + if m.billing_invoice_line != nil { + fields = append(fields, billinginvoicelineusagediscount.FieldLineID) + } + if m.child_unique_reference_id != nil { + fields = append(fields, billinginvoicelineusagediscount.FieldChildUniqueReferenceID) + } + if m.description != nil { + fields = append(fields, billinginvoicelineusagediscount.FieldDescription) + } + if m.reason != nil { + fields = append(fields, billinginvoicelineusagediscount.FieldReason) + } + if m.quantity != nil { + fields = append(fields, billinginvoicelineusagediscount.FieldQuantity) + } + if m.pre_line_period_quantity != nil { + fields = append(fields, billinginvoicelineusagediscount.FieldPreLinePeriodQuantity) + } + if m.reason_details != nil { + fields = append(fields, billinginvoicelineusagediscount.FieldReasonDetails) + } + 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 *BillingInvoiceLineUsageDiscountMutation) Field(name string) (ent.Value, bool) { + switch name { + case billinginvoicelineusagediscount.FieldNamespace: + return m.Namespace() + case billinginvoicelineusagediscount.FieldCreatedAt: + return m.CreatedAt() + case billinginvoicelineusagediscount.FieldUpdatedAt: + return m.UpdatedAt() + case billinginvoicelineusagediscount.FieldDeletedAt: + return m.DeletedAt() + case billinginvoicelineusagediscount.FieldInvoicingAppExternalID: + return m.InvoicingAppExternalID() + case billinginvoicelineusagediscount.FieldLineID: + return m.LineID() + case billinginvoicelineusagediscount.FieldChildUniqueReferenceID: + return m.ChildUniqueReferenceID() + case billinginvoicelineusagediscount.FieldDescription: + return m.Description() + case billinginvoicelineusagediscount.FieldReason: + return m.Reason() + case billinginvoicelineusagediscount.FieldQuantity: + return m.Quantity() + case billinginvoicelineusagediscount.FieldPreLinePeriodQuantity: + return m.PreLinePeriodQuantity() + case billinginvoicelineusagediscount.FieldReasonDetails: + return m.ReasonDetails() + } + 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 *BillingInvoiceLineUsageDiscountMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case billinginvoicelineusagediscount.FieldNamespace: + return m.OldNamespace(ctx) + case billinginvoicelineusagediscount.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case billinginvoicelineusagediscount.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case billinginvoicelineusagediscount.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case billinginvoicelineusagediscount.FieldInvoicingAppExternalID: + return m.OldInvoicingAppExternalID(ctx) + case billinginvoicelineusagediscount.FieldLineID: + return m.OldLineID(ctx) + case billinginvoicelineusagediscount.FieldChildUniqueReferenceID: + return m.OldChildUniqueReferenceID(ctx) + case billinginvoicelineusagediscount.FieldDescription: + return m.OldDescription(ctx) + case billinginvoicelineusagediscount.FieldReason: + return m.OldReason(ctx) + case billinginvoicelineusagediscount.FieldQuantity: + return m.OldQuantity(ctx) + case billinginvoicelineusagediscount.FieldPreLinePeriodQuantity: + return m.OldPreLinePeriodQuantity(ctx) + case billinginvoicelineusagediscount.FieldReasonDetails: + return m.OldReasonDetails(ctx) + } + return nil, fmt.Errorf("unknown BillingInvoiceLineUsageDiscount 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 *BillingInvoiceLineUsageDiscountMutation) SetField(name string, value ent.Value) error { + switch name { + case billinginvoicelineusagediscount.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case billinginvoicelineusagediscount.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 billinginvoicelineusagediscount.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 billinginvoicelineusagediscount.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 billinginvoicelineusagediscount.FieldInvoicingAppExternalID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoicingAppExternalID(v) + return nil + case billinginvoicelineusagediscount.FieldLineID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLineID(v) + return nil + case billinginvoicelineusagediscount.FieldChildUniqueReferenceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChildUniqueReferenceID(v) + return nil + case billinginvoicelineusagediscount.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case billinginvoicelineusagediscount.FieldReason: + v, ok := value.(billing.DiscountReasonType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetReason(v) + return nil + case billinginvoicelineusagediscount.FieldQuantity: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetQuantity(v) + return nil + case billinginvoicelineusagediscount.FieldPreLinePeriodQuantity: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPreLinePeriodQuantity(v) + return nil + case billinginvoicelineusagediscount.FieldReasonDetails: + v, ok := value.(*billing.DiscountReason) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetReasonDetails(v) + return nil + } + return fmt.Errorf("unknown BillingInvoiceLineUsageDiscount field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) 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 *BillingInvoiceLineUsageDiscountMutation) 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 *BillingInvoiceLineUsageDiscountMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown BillingInvoiceLineUsageDiscount numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(billinginvoicelineusagediscount.FieldDeletedAt) { + fields = append(fields, billinginvoicelineusagediscount.FieldDeletedAt) + } + if m.FieldCleared(billinginvoicelineusagediscount.FieldInvoicingAppExternalID) { + fields = append(fields, billinginvoicelineusagediscount.FieldInvoicingAppExternalID) + } + if m.FieldCleared(billinginvoicelineusagediscount.FieldChildUniqueReferenceID) { + fields = append(fields, billinginvoicelineusagediscount.FieldChildUniqueReferenceID) + } + if m.FieldCleared(billinginvoicelineusagediscount.FieldDescription) { + fields = append(fields, billinginvoicelineusagediscount.FieldDescription) + } + if m.FieldCleared(billinginvoicelineusagediscount.FieldPreLinePeriodQuantity) { + fields = append(fields, billinginvoicelineusagediscount.FieldPreLinePeriodQuantity) + } + if m.FieldCleared(billinginvoicelineusagediscount.FieldReasonDetails) { + fields = append(fields, billinginvoicelineusagediscount.FieldReasonDetails) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) 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 *BillingInvoiceLineUsageDiscountMutation) ClearField(name string) error { + switch name { + case billinginvoicelineusagediscount.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case billinginvoicelineusagediscount.FieldInvoicingAppExternalID: + m.ClearInvoicingAppExternalID() + return nil + case billinginvoicelineusagediscount.FieldChildUniqueReferenceID: + m.ClearChildUniqueReferenceID() + return nil + case billinginvoicelineusagediscount.FieldDescription: + m.ClearDescription() + return nil + case billinginvoicelineusagediscount.FieldPreLinePeriodQuantity: + m.ClearPreLinePeriodQuantity() + return nil + case billinginvoicelineusagediscount.FieldReasonDetails: + m.ClearReasonDetails() + return nil + } + return fmt.Errorf("unknown BillingInvoiceLineUsageDiscount 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 *BillingInvoiceLineUsageDiscountMutation) ResetField(name string) error { + switch name { + case billinginvoicelineusagediscount.FieldNamespace: + m.ResetNamespace() + return nil + case billinginvoicelineusagediscount.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case billinginvoicelineusagediscount.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case billinginvoicelineusagediscount.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case billinginvoicelineusagediscount.FieldInvoicingAppExternalID: + m.ResetInvoicingAppExternalID() + return nil + case billinginvoicelineusagediscount.FieldLineID: + m.ResetLineID() + return nil + case billinginvoicelineusagediscount.FieldChildUniqueReferenceID: + m.ResetChildUniqueReferenceID() + return nil + case billinginvoicelineusagediscount.FieldDescription: + m.ResetDescription() + return nil + case billinginvoicelineusagediscount.FieldReason: + m.ResetReason() + return nil + case billinginvoicelineusagediscount.FieldQuantity: + m.ResetQuantity() + return nil + case billinginvoicelineusagediscount.FieldPreLinePeriodQuantity: + m.ResetPreLinePeriodQuantity() + return nil + case billinginvoicelineusagediscount.FieldReasonDetails: + m.ResetReasonDetails() + return nil + } + return fmt.Errorf("unknown BillingInvoiceLineUsageDiscount field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.billing_invoice_line != nil { + edges = append(edges, billinginvoicelineusagediscount.EdgeBillingInvoiceLine) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) AddedIDs(name string) []ent.Value { + switch name { + case billinginvoicelineusagediscount.EdgeBillingInvoiceLine: + if id := m.billing_invoice_line; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) 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 *BillingInvoiceLineUsageDiscountMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedbilling_invoice_line { + edges = append(edges, billinginvoicelineusagediscount.EdgeBillingInvoiceLine) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BillingInvoiceLineUsageDiscountMutation) EdgeCleared(name string) bool { + switch name { + case billinginvoicelineusagediscount.EdgeBillingInvoiceLine: + return m.clearedbilling_invoice_line + } + 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 *BillingInvoiceLineUsageDiscountMutation) ClearEdge(name string) error { + switch name { + case billinginvoicelineusagediscount.EdgeBillingInvoiceLine: + m.ClearBillingInvoiceLine() + return nil + } + return fmt.Errorf("unknown BillingInvoiceLineUsageDiscount 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 *BillingInvoiceLineUsageDiscountMutation) ResetEdge(name string) error { + switch name { + case billinginvoicelineusagediscount.EdgeBillingInvoiceLine: + m.ResetBillingInvoiceLine() + return nil + } + return fmt.Errorf("unknown BillingInvoiceLineUsageDiscount edge %s", name) +} + +// BillingInvoiceSplitLineGroupMutation represents an operation that mutates the BillingInvoiceSplitLineGroup nodes in the graph. +type BillingInvoiceSplitLineGroupMutation struct { + config + op Op + typ string + id *string + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + name *string + description *string + currency *currencyx.Code + service_period_start *time.Time + service_period_end *time.Time + unique_reference_id *string + ratecard_discounts **billing.Discounts + feature_key *string + price **productcatalog.Price + subscription_billing_period_from *time.Time + subscription_billing_period_to *time.Time + clearedFields map[string]struct{} + billing_invoice_lines map[string]struct{} + removedbilling_invoice_lines map[string]struct{} + clearedbilling_invoice_lines bool + subscription *string + clearedsubscription bool + subscription_phase *string + clearedsubscription_phase bool + subscription_item *string + clearedsubscription_item bool + charge *string + clearedcharge bool + done bool + oldValue func(context.Context) (*BillingInvoiceSplitLineGroup, error) + predicates []predicate.BillingInvoiceSplitLineGroup +} + +var _ ent.Mutation = (*BillingInvoiceSplitLineGroupMutation)(nil) + +// billinginvoicesplitlinegroupOption allows management of the mutation configuration using functional options. +type billinginvoicesplitlinegroupOption func(*BillingInvoiceSplitLineGroupMutation) + +// newBillingInvoiceSplitLineGroupMutation creates new mutation for the BillingInvoiceSplitLineGroup entity. +func newBillingInvoiceSplitLineGroupMutation(c config, op Op, opts ...billinginvoicesplitlinegroupOption) *BillingInvoiceSplitLineGroupMutation { + m := &BillingInvoiceSplitLineGroupMutation{ + config: c, + op: op, + typ: TypeBillingInvoiceSplitLineGroup, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBillingInvoiceSplitLineGroupID sets the ID field of the mutation. +func withBillingInvoiceSplitLineGroupID(id string) billinginvoicesplitlinegroupOption { + return func(m *BillingInvoiceSplitLineGroupMutation) { + var ( + err error + once sync.Once + value *BillingInvoiceSplitLineGroup + ) + m.oldValue = func(ctx context.Context) (*BillingInvoiceSplitLineGroup, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().BillingInvoiceSplitLineGroup.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBillingInvoiceSplitLineGroup sets the old BillingInvoiceSplitLineGroup of the mutation. +func withBillingInvoiceSplitLineGroup(node *BillingInvoiceSplitLineGroup) billinginvoicesplitlinegroupOption { + return func(m *BillingInvoiceSplitLineGroupMutation) { + m.oldValue = func(context.Context) (*BillingInvoiceSplitLineGroup, 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 BillingInvoiceSplitLineGroupMutation) 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 BillingInvoiceSplitLineGroupMutation) 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 BillingInvoiceSplitLineGroup entities. +func (m *BillingInvoiceSplitLineGroupMutation) 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 *BillingInvoiceSplitLineGroupMutation) 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 *BillingInvoiceSplitLineGroupMutation) 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().BillingInvoiceSplitLineGroup.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 *BillingInvoiceSplitLineGroupMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) 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 BillingInvoiceSplitLineGroup entity. +// If the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) 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 *BillingInvoiceSplitLineGroupMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *BillingInvoiceSplitLineGroupMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the BillingInvoiceSplitLineGroup entity. +// If the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *BillingInvoiceSplitLineGroupMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[billinginvoicesplitlinegroup.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *BillingInvoiceSplitLineGroupMutation) MetadataCleared() bool { + _, ok := m.clearedFields[billinginvoicesplitlinegroup.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *BillingInvoiceSplitLineGroupMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, billinginvoicesplitlinegroup.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *BillingInvoiceSplitLineGroupMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) 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 BillingInvoiceSplitLineGroup entity. +// If the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) 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 *BillingInvoiceSplitLineGroupMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *BillingInvoiceSplitLineGroupMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) 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 BillingInvoiceSplitLineGroup entity. +// If the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) 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 *BillingInvoiceSplitLineGroupMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *BillingInvoiceSplitLineGroupMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) 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 BillingInvoiceSplitLineGroup entity. +// If the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) 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 *BillingInvoiceSplitLineGroupMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[billinginvoicesplitlinegroup.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *BillingInvoiceSplitLineGroupMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[billinginvoicesplitlinegroup.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *BillingInvoiceSplitLineGroupMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, billinginvoicesplitlinegroup.FieldDeletedAt) +} + +// SetName sets the "name" field. +func (m *BillingInvoiceSplitLineGroupMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the BillingInvoiceSplitLineGroup entity. +// If the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *BillingInvoiceSplitLineGroupMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *BillingInvoiceSplitLineGroupMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the BillingInvoiceSplitLineGroup entity. +// If the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *BillingInvoiceSplitLineGroupMutation) ClearDescription() { + m.description = nil + m.clearedFields[billinginvoicesplitlinegroup.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *BillingInvoiceSplitLineGroupMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[billinginvoicesplitlinegroup.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *BillingInvoiceSplitLineGroupMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, billinginvoicesplitlinegroup.FieldDescription) +} + +// SetCurrency sets the "currency" field. +func (m *BillingInvoiceSplitLineGroupMutation) SetCurrency(c currencyx.Code) { + m.currency = &c +} + +// Currency returns the value of the "currency" field in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) Currency() (r currencyx.Code, exists bool) { + v := m.currency + if v == nil { + return + } + return *v, true +} + +// OldCurrency returns the old "currency" field's value of the BillingInvoiceSplitLineGroup entity. +// If the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) OldCurrency(ctx context.Context) (v currencyx.Code, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrency is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrency requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrency: %w", err) + } + return oldValue.Currency, nil +} + +// ResetCurrency resets all changes to the "currency" field. +func (m *BillingInvoiceSplitLineGroupMutation) ResetCurrency() { + m.currency = nil +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (m *BillingInvoiceSplitLineGroupMutation) SetServicePeriodStart(t time.Time) { + m.service_period_start = &t +} + +// ServicePeriodStart returns the value of the "service_period_start" field in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) ServicePeriodStart() (r time.Time, exists bool) { + v := m.service_period_start + if v == nil { + return + } + return *v, true +} + +// OldServicePeriodStart returns the old "service_period_start" field's value of the BillingInvoiceSplitLineGroup entity. +// If the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) OldServicePeriodStart(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldServicePeriodStart is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldServicePeriodStart requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldServicePeriodStart: %w", err) + } + return oldValue.ServicePeriodStart, nil +} + +// ResetServicePeriodStart resets all changes to the "service_period_start" field. +func (m *BillingInvoiceSplitLineGroupMutation) ResetServicePeriodStart() { + m.service_period_start = nil +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (m *BillingInvoiceSplitLineGroupMutation) SetServicePeriodEnd(t time.Time) { + m.service_period_end = &t +} + +// ServicePeriodEnd returns the value of the "service_period_end" field in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) ServicePeriodEnd() (r time.Time, exists bool) { + v := m.service_period_end + if v == nil { + return + } + return *v, true +} + +// OldServicePeriodEnd returns the old "service_period_end" field's value of the BillingInvoiceSplitLineGroup entity. +// If the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) OldServicePeriodEnd(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldServicePeriodEnd is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldServicePeriodEnd requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldServicePeriodEnd: %w", err) + } + return oldValue.ServicePeriodEnd, nil +} + +// ResetServicePeriodEnd resets all changes to the "service_period_end" field. +func (m *BillingInvoiceSplitLineGroupMutation) ResetServicePeriodEnd() { + m.service_period_end = nil +} + +// SetUniqueReferenceID sets the "unique_reference_id" field. +func (m *BillingInvoiceSplitLineGroupMutation) SetUniqueReferenceID(s string) { + m.unique_reference_id = &s +} + +// UniqueReferenceID returns the value of the "unique_reference_id" field in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) UniqueReferenceID() (r string, exists bool) { + v := m.unique_reference_id + if v == nil { + return + } + return *v, true +} + +// OldUniqueReferenceID returns the old "unique_reference_id" field's value of the BillingInvoiceSplitLineGroup entity. +// If the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) OldUniqueReferenceID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUniqueReferenceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUniqueReferenceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUniqueReferenceID: %w", err) + } + return oldValue.UniqueReferenceID, nil +} + +// ClearUniqueReferenceID clears the value of the "unique_reference_id" field. +func (m *BillingInvoiceSplitLineGroupMutation) ClearUniqueReferenceID() { + m.unique_reference_id = nil + m.clearedFields[billinginvoicesplitlinegroup.FieldUniqueReferenceID] = struct{}{} +} + +// UniqueReferenceIDCleared returns if the "unique_reference_id" field was cleared in this mutation. +func (m *BillingInvoiceSplitLineGroupMutation) UniqueReferenceIDCleared() bool { + _, ok := m.clearedFields[billinginvoicesplitlinegroup.FieldUniqueReferenceID] + return ok +} + +// ResetUniqueReferenceID resets all changes to the "unique_reference_id" field. +func (m *BillingInvoiceSplitLineGroupMutation) ResetUniqueReferenceID() { + m.unique_reference_id = nil + delete(m.clearedFields, billinginvoicesplitlinegroup.FieldUniqueReferenceID) +} + +// SetRatecardDiscounts sets the "ratecard_discounts" field. +func (m *BillingInvoiceSplitLineGroupMutation) SetRatecardDiscounts(b *billing.Discounts) { + m.ratecard_discounts = &b +} + +// RatecardDiscounts returns the value of the "ratecard_discounts" field in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) RatecardDiscounts() (r *billing.Discounts, exists bool) { + v := m.ratecard_discounts + if v == nil { + return + } + return *v, true +} + +// OldRatecardDiscounts returns the old "ratecard_discounts" field's value of the BillingInvoiceSplitLineGroup entity. +// If the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) OldRatecardDiscounts(ctx context.Context) (v *billing.Discounts, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRatecardDiscounts is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRatecardDiscounts requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRatecardDiscounts: %w", err) + } + return oldValue.RatecardDiscounts, nil +} + +// ClearRatecardDiscounts clears the value of the "ratecard_discounts" field. +func (m *BillingInvoiceSplitLineGroupMutation) ClearRatecardDiscounts() { + m.ratecard_discounts = nil + m.clearedFields[billinginvoicesplitlinegroup.FieldRatecardDiscounts] = struct{}{} +} + +// RatecardDiscountsCleared returns if the "ratecard_discounts" field was cleared in this mutation. +func (m *BillingInvoiceSplitLineGroupMutation) RatecardDiscountsCleared() bool { + _, ok := m.clearedFields[billinginvoicesplitlinegroup.FieldRatecardDiscounts] + return ok +} + +// ResetRatecardDiscounts resets all changes to the "ratecard_discounts" field. +func (m *BillingInvoiceSplitLineGroupMutation) ResetRatecardDiscounts() { + m.ratecard_discounts = nil + delete(m.clearedFields, billinginvoicesplitlinegroup.FieldRatecardDiscounts) +} + +// SetFeatureKey sets the "feature_key" field. +func (m *BillingInvoiceSplitLineGroupMutation) SetFeatureKey(s string) { + m.feature_key = &s +} + +// FeatureKey returns the value of the "feature_key" field in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) 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 BillingInvoiceSplitLineGroup entity. +// If the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) 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 +} + +// ClearFeatureKey clears the value of the "feature_key" field. +func (m *BillingInvoiceSplitLineGroupMutation) ClearFeatureKey() { + m.feature_key = nil + m.clearedFields[billinginvoicesplitlinegroup.FieldFeatureKey] = struct{}{} +} + +// FeatureKeyCleared returns if the "feature_key" field was cleared in this mutation. +func (m *BillingInvoiceSplitLineGroupMutation) FeatureKeyCleared() bool { + _, ok := m.clearedFields[billinginvoicesplitlinegroup.FieldFeatureKey] + return ok +} + +// ResetFeatureKey resets all changes to the "feature_key" field. +func (m *BillingInvoiceSplitLineGroupMutation) ResetFeatureKey() { + m.feature_key = nil + delete(m.clearedFields, billinginvoicesplitlinegroup.FieldFeatureKey) +} + +// SetPrice sets the "price" field. +func (m *BillingInvoiceSplitLineGroupMutation) SetPrice(pr *productcatalog.Price) { + m.price = &pr +} + +// Price returns the value of the "price" field in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) 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 BillingInvoiceSplitLineGroup entity. +// If the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) 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 *BillingInvoiceSplitLineGroupMutation) ResetPrice() { + m.price = nil +} + +// SetSubscriptionID sets the "subscription_id" field. +func (m *BillingInvoiceSplitLineGroupMutation) SetSubscriptionID(s string) { + m.subscription = &s +} + +// SubscriptionID returns the value of the "subscription_id" field in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) SubscriptionID() (r string, exists bool) { + v := m.subscription + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionID returns the old "subscription_id" field's value of the BillingInvoiceSplitLineGroup entity. +// If the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) OldSubscriptionID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionID: %w", err) + } + return oldValue.SubscriptionID, nil +} + +// ClearSubscriptionID clears the value of the "subscription_id" field. +func (m *BillingInvoiceSplitLineGroupMutation) ClearSubscriptionID() { + m.subscription = nil + m.clearedFields[billinginvoicesplitlinegroup.FieldSubscriptionID] = struct{}{} +} + +// SubscriptionIDCleared returns if the "subscription_id" field was cleared in this mutation. +func (m *BillingInvoiceSplitLineGroupMutation) SubscriptionIDCleared() bool { + _, ok := m.clearedFields[billinginvoicesplitlinegroup.FieldSubscriptionID] + return ok +} + +// ResetSubscriptionID resets all changes to the "subscription_id" field. +func (m *BillingInvoiceSplitLineGroupMutation) ResetSubscriptionID() { + m.subscription = nil + delete(m.clearedFields, billinginvoicesplitlinegroup.FieldSubscriptionID) +} + +// SetSubscriptionPhaseID sets the "subscription_phase_id" field. +func (m *BillingInvoiceSplitLineGroupMutation) SetSubscriptionPhaseID(s string) { + m.subscription_phase = &s +} + +// SubscriptionPhaseID returns the value of the "subscription_phase_id" field in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) SubscriptionPhaseID() (r string, exists bool) { + v := m.subscription_phase + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionPhaseID returns the old "subscription_phase_id" field's value of the BillingInvoiceSplitLineGroup entity. +// If the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) OldSubscriptionPhaseID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionPhaseID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionPhaseID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionPhaseID: %w", err) + } + return oldValue.SubscriptionPhaseID, nil +} + +// ClearSubscriptionPhaseID clears the value of the "subscription_phase_id" field. +func (m *BillingInvoiceSplitLineGroupMutation) ClearSubscriptionPhaseID() { + m.subscription_phase = nil + m.clearedFields[billinginvoicesplitlinegroup.FieldSubscriptionPhaseID] = struct{}{} +} + +// SubscriptionPhaseIDCleared returns if the "subscription_phase_id" field was cleared in this mutation. +func (m *BillingInvoiceSplitLineGroupMutation) SubscriptionPhaseIDCleared() bool { + _, ok := m.clearedFields[billinginvoicesplitlinegroup.FieldSubscriptionPhaseID] + return ok +} + +// ResetSubscriptionPhaseID resets all changes to the "subscription_phase_id" field. +func (m *BillingInvoiceSplitLineGroupMutation) ResetSubscriptionPhaseID() { + m.subscription_phase = nil + delete(m.clearedFields, billinginvoicesplitlinegroup.FieldSubscriptionPhaseID) +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (m *BillingInvoiceSplitLineGroupMutation) SetSubscriptionItemID(s string) { + m.subscription_item = &s +} + +// SubscriptionItemID returns the value of the "subscription_item_id" field in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) SubscriptionItemID() (r string, exists bool) { + v := m.subscription_item + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionItemID returns the old "subscription_item_id" field's value of the BillingInvoiceSplitLineGroup entity. +// If the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) OldSubscriptionItemID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionItemID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionItemID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionItemID: %w", err) + } + return oldValue.SubscriptionItemID, nil +} + +// ClearSubscriptionItemID clears the value of the "subscription_item_id" field. +func (m *BillingInvoiceSplitLineGroupMutation) ClearSubscriptionItemID() { + m.subscription_item = nil + m.clearedFields[billinginvoicesplitlinegroup.FieldSubscriptionItemID] = struct{}{} +} + +// SubscriptionItemIDCleared returns if the "subscription_item_id" field was cleared in this mutation. +func (m *BillingInvoiceSplitLineGroupMutation) SubscriptionItemIDCleared() bool { + _, ok := m.clearedFields[billinginvoicesplitlinegroup.FieldSubscriptionItemID] + return ok +} + +// ResetSubscriptionItemID resets all changes to the "subscription_item_id" field. +func (m *BillingInvoiceSplitLineGroupMutation) ResetSubscriptionItemID() { + m.subscription_item = nil + delete(m.clearedFields, billinginvoicesplitlinegroup.FieldSubscriptionItemID) +} + +// SetSubscriptionBillingPeriodFrom sets the "subscription_billing_period_from" field. +func (m *BillingInvoiceSplitLineGroupMutation) SetSubscriptionBillingPeriodFrom(t time.Time) { + m.subscription_billing_period_from = &t +} + +// SubscriptionBillingPeriodFrom returns the value of the "subscription_billing_period_from" field in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) SubscriptionBillingPeriodFrom() (r time.Time, exists bool) { + v := m.subscription_billing_period_from + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionBillingPeriodFrom returns the old "subscription_billing_period_from" field's value of the BillingInvoiceSplitLineGroup entity. +// If the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) OldSubscriptionBillingPeriodFrom(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionBillingPeriodFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionBillingPeriodFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionBillingPeriodFrom: %w", err) + } + return oldValue.SubscriptionBillingPeriodFrom, nil +} + +// ClearSubscriptionBillingPeriodFrom clears the value of the "subscription_billing_period_from" field. +func (m *BillingInvoiceSplitLineGroupMutation) ClearSubscriptionBillingPeriodFrom() { + m.subscription_billing_period_from = nil + m.clearedFields[billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom] = struct{}{} +} + +// SubscriptionBillingPeriodFromCleared returns if the "subscription_billing_period_from" field was cleared in this mutation. +func (m *BillingInvoiceSplitLineGroupMutation) SubscriptionBillingPeriodFromCleared() bool { + _, ok := m.clearedFields[billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom] + return ok +} + +// ResetSubscriptionBillingPeriodFrom resets all changes to the "subscription_billing_period_from" field. +func (m *BillingInvoiceSplitLineGroupMutation) ResetSubscriptionBillingPeriodFrom() { + m.subscription_billing_period_from = nil + delete(m.clearedFields, billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom) +} + +// SetSubscriptionBillingPeriodTo sets the "subscription_billing_period_to" field. +func (m *BillingInvoiceSplitLineGroupMutation) SetSubscriptionBillingPeriodTo(t time.Time) { + m.subscription_billing_period_to = &t +} + +// SubscriptionBillingPeriodTo returns the value of the "subscription_billing_period_to" field in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) SubscriptionBillingPeriodTo() (r time.Time, exists bool) { + v := m.subscription_billing_period_to + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionBillingPeriodTo returns the old "subscription_billing_period_to" field's value of the BillingInvoiceSplitLineGroup entity. +// If the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) OldSubscriptionBillingPeriodTo(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionBillingPeriodTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionBillingPeriodTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionBillingPeriodTo: %w", err) + } + return oldValue.SubscriptionBillingPeriodTo, nil +} + +// ClearSubscriptionBillingPeriodTo clears the value of the "subscription_billing_period_to" field. +func (m *BillingInvoiceSplitLineGroupMutation) ClearSubscriptionBillingPeriodTo() { + m.subscription_billing_period_to = nil + m.clearedFields[billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo] = struct{}{} +} + +// SubscriptionBillingPeriodToCleared returns if the "subscription_billing_period_to" field was cleared in this mutation. +func (m *BillingInvoiceSplitLineGroupMutation) SubscriptionBillingPeriodToCleared() bool { + _, ok := m.clearedFields[billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo] + return ok +} + +// ResetSubscriptionBillingPeriodTo resets all changes to the "subscription_billing_period_to" field. +func (m *BillingInvoiceSplitLineGroupMutation) ResetSubscriptionBillingPeriodTo() { + m.subscription_billing_period_to = nil + delete(m.clearedFields, billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo) +} + +// SetChargeID sets the "charge_id" field. +func (m *BillingInvoiceSplitLineGroupMutation) SetChargeID(s string) { + m.charge = &s +} + +// ChargeID returns the value of the "charge_id" field in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) ChargeID() (r string, exists bool) { + v := m.charge + if v == nil { + return + } + return *v, true +} + +// OldChargeID returns the old "charge_id" field's value of the BillingInvoiceSplitLineGroup entity. +// If the BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) 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 +} + +// ClearChargeID clears the value of the "charge_id" field. +func (m *BillingInvoiceSplitLineGroupMutation) ClearChargeID() { + m.charge = nil + m.clearedFields[billinginvoicesplitlinegroup.FieldChargeID] = struct{}{} +} + +// ChargeIDCleared returns if the "charge_id" field was cleared in this mutation. +func (m *BillingInvoiceSplitLineGroupMutation) ChargeIDCleared() bool { + _, ok := m.clearedFields[billinginvoicesplitlinegroup.FieldChargeID] + return ok +} + +// ResetChargeID resets all changes to the "charge_id" field. +func (m *BillingInvoiceSplitLineGroupMutation) ResetChargeID() { + m.charge = nil + delete(m.clearedFields, billinginvoicesplitlinegroup.FieldChargeID) +} + +// AddBillingInvoiceLineIDs adds the "billing_invoice_lines" edge to the BillingInvoiceLine entity by ids. +func (m *BillingInvoiceSplitLineGroupMutation) AddBillingInvoiceLineIDs(ids ...string) { + if m.billing_invoice_lines == nil { + m.billing_invoice_lines = make(map[string]struct{}) + } + for i := range ids { + m.billing_invoice_lines[ids[i]] = struct{}{} + } +} + +// ClearBillingInvoiceLines clears the "billing_invoice_lines" edge to the BillingInvoiceLine entity. +func (m *BillingInvoiceSplitLineGroupMutation) ClearBillingInvoiceLines() { + m.clearedbilling_invoice_lines = true +} + +// BillingInvoiceLinesCleared reports if the "billing_invoice_lines" edge to the BillingInvoiceLine entity was cleared. +func (m *BillingInvoiceSplitLineGroupMutation) BillingInvoiceLinesCleared() bool { + return m.clearedbilling_invoice_lines +} + +// RemoveBillingInvoiceLineIDs removes the "billing_invoice_lines" edge to the BillingInvoiceLine entity by IDs. +func (m *BillingInvoiceSplitLineGroupMutation) RemoveBillingInvoiceLineIDs(ids ...string) { + if m.removedbilling_invoice_lines == nil { + m.removedbilling_invoice_lines = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_invoice_lines, ids[i]) + m.removedbilling_invoice_lines[ids[i]] = struct{}{} + } +} + +// RemovedBillingInvoiceLines returns the removed IDs of the "billing_invoice_lines" edge to the BillingInvoiceLine entity. +func (m *BillingInvoiceSplitLineGroupMutation) RemovedBillingInvoiceLinesIDs() (ids []string) { + for id := range m.removedbilling_invoice_lines { + ids = append(ids, id) + } + return +} + +// BillingInvoiceLinesIDs returns the "billing_invoice_lines" edge IDs in the mutation. +func (m *BillingInvoiceSplitLineGroupMutation) BillingInvoiceLinesIDs() (ids []string) { + for id := range m.billing_invoice_lines { + ids = append(ids, id) + } + return +} + +// ResetBillingInvoiceLines resets all changes to the "billing_invoice_lines" edge. +func (m *BillingInvoiceSplitLineGroupMutation) ResetBillingInvoiceLines() { + m.billing_invoice_lines = nil + m.clearedbilling_invoice_lines = false + m.removedbilling_invoice_lines = nil +} + +// ClearSubscription clears the "subscription" edge to the Subscription entity. +func (m *BillingInvoiceSplitLineGroupMutation) ClearSubscription() { + m.clearedsubscription = true + m.clearedFields[billinginvoicesplitlinegroup.FieldSubscriptionID] = struct{}{} +} + +// SubscriptionCleared reports if the "subscription" edge to the Subscription entity was cleared. +func (m *BillingInvoiceSplitLineGroupMutation) SubscriptionCleared() bool { + return m.SubscriptionIDCleared() || m.clearedsubscription +} + +// SubscriptionIDs returns the "subscription" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubscriptionID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceSplitLineGroupMutation) SubscriptionIDs() (ids []string) { + if id := m.subscription; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSubscription resets all changes to the "subscription" edge. +func (m *BillingInvoiceSplitLineGroupMutation) ResetSubscription() { + m.subscription = nil + m.clearedsubscription = false +} + +// ClearSubscriptionPhase clears the "subscription_phase" edge to the SubscriptionPhase entity. +func (m *BillingInvoiceSplitLineGroupMutation) ClearSubscriptionPhase() { + m.clearedsubscription_phase = true + m.clearedFields[billinginvoicesplitlinegroup.FieldSubscriptionPhaseID] = struct{}{} +} + +// SubscriptionPhaseCleared reports if the "subscription_phase" edge to the SubscriptionPhase entity was cleared. +func (m *BillingInvoiceSplitLineGroupMutation) SubscriptionPhaseCleared() bool { + return m.SubscriptionPhaseIDCleared() || m.clearedsubscription_phase +} + +// SubscriptionPhaseIDs returns the "subscription_phase" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubscriptionPhaseID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceSplitLineGroupMutation) SubscriptionPhaseIDs() (ids []string) { + if id := m.subscription_phase; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSubscriptionPhase resets all changes to the "subscription_phase" edge. +func (m *BillingInvoiceSplitLineGroupMutation) ResetSubscriptionPhase() { + m.subscription_phase = nil + m.clearedsubscription_phase = false +} + +// ClearSubscriptionItem clears the "subscription_item" edge to the SubscriptionItem entity. +func (m *BillingInvoiceSplitLineGroupMutation) ClearSubscriptionItem() { + m.clearedsubscription_item = true + m.clearedFields[billinginvoicesplitlinegroup.FieldSubscriptionItemID] = struct{}{} +} + +// SubscriptionItemCleared reports if the "subscription_item" edge to the SubscriptionItem entity was cleared. +func (m *BillingInvoiceSplitLineGroupMutation) SubscriptionItemCleared() bool { + return m.SubscriptionItemIDCleared() || m.clearedsubscription_item +} + +// SubscriptionItemIDs returns the "subscription_item" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubscriptionItemID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceSplitLineGroupMutation) SubscriptionItemIDs() (ids []string) { + if id := m.subscription_item; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSubscriptionItem resets all changes to the "subscription_item" edge. +func (m *BillingInvoiceSplitLineGroupMutation) ResetSubscriptionItem() { + m.subscription_item = nil + m.clearedsubscription_item = false +} + +// ClearCharge clears the "charge" edge to the Charge entity. +func (m *BillingInvoiceSplitLineGroupMutation) ClearCharge() { + m.clearedcharge = true + m.clearedFields[billinginvoicesplitlinegroup.FieldChargeID] = struct{}{} +} + +// ChargeCleared reports if the "charge" edge to the Charge entity was cleared. +func (m *BillingInvoiceSplitLineGroupMutation) ChargeCleared() bool { + return m.ChargeIDCleared() || m.clearedcharge +} + +// 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 *BillingInvoiceSplitLineGroupMutation) ChargeIDs() (ids []string) { + if id := m.charge; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCharge resets all changes to the "charge" edge. +func (m *BillingInvoiceSplitLineGroupMutation) ResetCharge() { + m.charge = nil + m.clearedcharge = false +} + +// Where appends a list predicates to the BillingInvoiceSplitLineGroupMutation builder. +func (m *BillingInvoiceSplitLineGroupMutation) Where(ps ...predicate.BillingInvoiceSplitLineGroup) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BillingInvoiceSplitLineGroupMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BillingInvoiceSplitLineGroupMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillingInvoiceSplitLineGroup, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BillingInvoiceSplitLineGroupMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BillingInvoiceSplitLineGroupMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BillingInvoiceSplitLineGroup). +func (m *BillingInvoiceSplitLineGroupMutation) 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 *BillingInvoiceSplitLineGroupMutation) Fields() []string { + fields := make([]string, 0, 20) + if m.namespace != nil { + fields = append(fields, billinginvoicesplitlinegroup.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, billinginvoicesplitlinegroup.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, billinginvoicesplitlinegroup.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, billinginvoicesplitlinegroup.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, billinginvoicesplitlinegroup.FieldDeletedAt) + } + if m.name != nil { + fields = append(fields, billinginvoicesplitlinegroup.FieldName) + } + if m.description != nil { + fields = append(fields, billinginvoicesplitlinegroup.FieldDescription) + } + if m.currency != nil { + fields = append(fields, billinginvoicesplitlinegroup.FieldCurrency) + } + if m.service_period_start != nil { + fields = append(fields, billinginvoicesplitlinegroup.FieldServicePeriodStart) + } + if m.service_period_end != nil { + fields = append(fields, billinginvoicesplitlinegroup.FieldServicePeriodEnd) + } + if m.unique_reference_id != nil { + fields = append(fields, billinginvoicesplitlinegroup.FieldUniqueReferenceID) + } + if m.ratecard_discounts != nil { + fields = append(fields, billinginvoicesplitlinegroup.FieldRatecardDiscounts) + } + if m.feature_key != nil { + fields = append(fields, billinginvoicesplitlinegroup.FieldFeatureKey) + } + if m.price != nil { + fields = append(fields, billinginvoicesplitlinegroup.FieldPrice) + } + if m.subscription != nil { + fields = append(fields, billinginvoicesplitlinegroup.FieldSubscriptionID) + } + if m.subscription_phase != nil { + fields = append(fields, billinginvoicesplitlinegroup.FieldSubscriptionPhaseID) + } + if m.subscription_item != nil { + fields = append(fields, billinginvoicesplitlinegroup.FieldSubscriptionItemID) + } + if m.subscription_billing_period_from != nil { + fields = append(fields, billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom) + } + if m.subscription_billing_period_to != nil { + fields = append(fields, billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo) + } + if m.charge != nil { + fields = append(fields, billinginvoicesplitlinegroup.FieldChargeID) + } + 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 *BillingInvoiceSplitLineGroupMutation) Field(name string) (ent.Value, bool) { + switch name { + case billinginvoicesplitlinegroup.FieldNamespace: + return m.Namespace() + case billinginvoicesplitlinegroup.FieldMetadata: + return m.Metadata() + case billinginvoicesplitlinegroup.FieldCreatedAt: + return m.CreatedAt() + case billinginvoicesplitlinegroup.FieldUpdatedAt: + return m.UpdatedAt() + case billinginvoicesplitlinegroup.FieldDeletedAt: + return m.DeletedAt() + case billinginvoicesplitlinegroup.FieldName: + return m.Name() + case billinginvoicesplitlinegroup.FieldDescription: + return m.Description() + case billinginvoicesplitlinegroup.FieldCurrency: + return m.Currency() + case billinginvoicesplitlinegroup.FieldServicePeriodStart: + return m.ServicePeriodStart() + case billinginvoicesplitlinegroup.FieldServicePeriodEnd: + return m.ServicePeriodEnd() + case billinginvoicesplitlinegroup.FieldUniqueReferenceID: + return m.UniqueReferenceID() + case billinginvoicesplitlinegroup.FieldRatecardDiscounts: + return m.RatecardDiscounts() + case billinginvoicesplitlinegroup.FieldFeatureKey: + return m.FeatureKey() + case billinginvoicesplitlinegroup.FieldPrice: + return m.Price() + case billinginvoicesplitlinegroup.FieldSubscriptionID: + return m.SubscriptionID() + case billinginvoicesplitlinegroup.FieldSubscriptionPhaseID: + return m.SubscriptionPhaseID() + case billinginvoicesplitlinegroup.FieldSubscriptionItemID: + return m.SubscriptionItemID() + case billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom: + return m.SubscriptionBillingPeriodFrom() + case billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo: + return m.SubscriptionBillingPeriodTo() + case billinginvoicesplitlinegroup.FieldChargeID: + return m.ChargeID() + } + 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 *BillingInvoiceSplitLineGroupMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case billinginvoicesplitlinegroup.FieldNamespace: + return m.OldNamespace(ctx) + case billinginvoicesplitlinegroup.FieldMetadata: + return m.OldMetadata(ctx) + case billinginvoicesplitlinegroup.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case billinginvoicesplitlinegroup.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case billinginvoicesplitlinegroup.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case billinginvoicesplitlinegroup.FieldName: + return m.OldName(ctx) + case billinginvoicesplitlinegroup.FieldDescription: + return m.OldDescription(ctx) + case billinginvoicesplitlinegroup.FieldCurrency: + return m.OldCurrency(ctx) + case billinginvoicesplitlinegroup.FieldServicePeriodStart: + return m.OldServicePeriodStart(ctx) + case billinginvoicesplitlinegroup.FieldServicePeriodEnd: + return m.OldServicePeriodEnd(ctx) + case billinginvoicesplitlinegroup.FieldUniqueReferenceID: + return m.OldUniqueReferenceID(ctx) + case billinginvoicesplitlinegroup.FieldRatecardDiscounts: + return m.OldRatecardDiscounts(ctx) + case billinginvoicesplitlinegroup.FieldFeatureKey: + return m.OldFeatureKey(ctx) + case billinginvoicesplitlinegroup.FieldPrice: + return m.OldPrice(ctx) + case billinginvoicesplitlinegroup.FieldSubscriptionID: + return m.OldSubscriptionID(ctx) + case billinginvoicesplitlinegroup.FieldSubscriptionPhaseID: + return m.OldSubscriptionPhaseID(ctx) + case billinginvoicesplitlinegroup.FieldSubscriptionItemID: + return m.OldSubscriptionItemID(ctx) + case billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom: + return m.OldSubscriptionBillingPeriodFrom(ctx) + case billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo: + return m.OldSubscriptionBillingPeriodTo(ctx) + case billinginvoicesplitlinegroup.FieldChargeID: + return m.OldChargeID(ctx) + } + return nil, fmt.Errorf("unknown BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) SetField(name string, value ent.Value) error { + switch name { + case billinginvoicesplitlinegroup.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case billinginvoicesplitlinegroup.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case billinginvoicesplitlinegroup.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 billinginvoicesplitlinegroup.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 billinginvoicesplitlinegroup.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 billinginvoicesplitlinegroup.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case billinginvoicesplitlinegroup.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case billinginvoicesplitlinegroup.FieldCurrency: + v, ok := value.(currencyx.Code) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrency(v) + return nil + case billinginvoicesplitlinegroup.FieldServicePeriodStart: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetServicePeriodStart(v) + return nil + case billinginvoicesplitlinegroup.FieldServicePeriodEnd: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetServicePeriodEnd(v) + return nil + case billinginvoicesplitlinegroup.FieldUniqueReferenceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUniqueReferenceID(v) + return nil + case billinginvoicesplitlinegroup.FieldRatecardDiscounts: + v, ok := value.(*billing.Discounts) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRatecardDiscounts(v) + return nil + case billinginvoicesplitlinegroup.FieldFeatureKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFeatureKey(v) + return nil + case billinginvoicesplitlinegroup.FieldPrice: + v, ok := value.(*productcatalog.Price) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPrice(v) + return nil + case billinginvoicesplitlinegroup.FieldSubscriptionID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionID(v) + return nil + case billinginvoicesplitlinegroup.FieldSubscriptionPhaseID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionPhaseID(v) + return nil + case billinginvoicesplitlinegroup.FieldSubscriptionItemID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionItemID(v) + return nil + case billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionBillingPeriodFrom(v) + return nil + case billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionBillingPeriodTo(v) + return nil + case billinginvoicesplitlinegroup.FieldChargeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChargeID(v) + return nil + } + return fmt.Errorf("unknown BillingInvoiceSplitLineGroup field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BillingInvoiceSplitLineGroupMutation) 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 *BillingInvoiceSplitLineGroupMutation) 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 *BillingInvoiceSplitLineGroupMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown BillingInvoiceSplitLineGroup numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BillingInvoiceSplitLineGroupMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(billinginvoicesplitlinegroup.FieldMetadata) { + fields = append(fields, billinginvoicesplitlinegroup.FieldMetadata) + } + if m.FieldCleared(billinginvoicesplitlinegroup.FieldDeletedAt) { + fields = append(fields, billinginvoicesplitlinegroup.FieldDeletedAt) + } + if m.FieldCleared(billinginvoicesplitlinegroup.FieldDescription) { + fields = append(fields, billinginvoicesplitlinegroup.FieldDescription) + } + if m.FieldCleared(billinginvoicesplitlinegroup.FieldUniqueReferenceID) { + fields = append(fields, billinginvoicesplitlinegroup.FieldUniqueReferenceID) + } + if m.FieldCleared(billinginvoicesplitlinegroup.FieldRatecardDiscounts) { + fields = append(fields, billinginvoicesplitlinegroup.FieldRatecardDiscounts) + } + if m.FieldCleared(billinginvoicesplitlinegroup.FieldFeatureKey) { + fields = append(fields, billinginvoicesplitlinegroup.FieldFeatureKey) + } + if m.FieldCleared(billinginvoicesplitlinegroup.FieldSubscriptionID) { + fields = append(fields, billinginvoicesplitlinegroup.FieldSubscriptionID) + } + if m.FieldCleared(billinginvoicesplitlinegroup.FieldSubscriptionPhaseID) { + fields = append(fields, billinginvoicesplitlinegroup.FieldSubscriptionPhaseID) + } + if m.FieldCleared(billinginvoicesplitlinegroup.FieldSubscriptionItemID) { + fields = append(fields, billinginvoicesplitlinegroup.FieldSubscriptionItemID) + } + if m.FieldCleared(billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom) { + fields = append(fields, billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom) + } + if m.FieldCleared(billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo) { + fields = append(fields, billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo) + } + if m.FieldCleared(billinginvoicesplitlinegroup.FieldChargeID) { + fields = append(fields, billinginvoicesplitlinegroup.FieldChargeID) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BillingInvoiceSplitLineGroupMutation) 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 *BillingInvoiceSplitLineGroupMutation) ClearField(name string) error { + switch name { + case billinginvoicesplitlinegroup.FieldMetadata: + m.ClearMetadata() + return nil + case billinginvoicesplitlinegroup.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case billinginvoicesplitlinegroup.FieldDescription: + m.ClearDescription() + return nil + case billinginvoicesplitlinegroup.FieldUniqueReferenceID: + m.ClearUniqueReferenceID() + return nil + case billinginvoicesplitlinegroup.FieldRatecardDiscounts: + m.ClearRatecardDiscounts() + return nil + case billinginvoicesplitlinegroup.FieldFeatureKey: + m.ClearFeatureKey() + return nil + case billinginvoicesplitlinegroup.FieldSubscriptionID: + m.ClearSubscriptionID() + return nil + case billinginvoicesplitlinegroup.FieldSubscriptionPhaseID: + m.ClearSubscriptionPhaseID() + return nil + case billinginvoicesplitlinegroup.FieldSubscriptionItemID: + m.ClearSubscriptionItemID() + return nil + case billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom: + m.ClearSubscriptionBillingPeriodFrom() + return nil + case billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo: + m.ClearSubscriptionBillingPeriodTo() + return nil + case billinginvoicesplitlinegroup.FieldChargeID: + m.ClearChargeID() + return nil + } + return fmt.Errorf("unknown BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) ResetField(name string) error { + switch name { + case billinginvoicesplitlinegroup.FieldNamespace: + m.ResetNamespace() + return nil + case billinginvoicesplitlinegroup.FieldMetadata: + m.ResetMetadata() + return nil + case billinginvoicesplitlinegroup.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case billinginvoicesplitlinegroup.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case billinginvoicesplitlinegroup.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case billinginvoicesplitlinegroup.FieldName: + m.ResetName() + return nil + case billinginvoicesplitlinegroup.FieldDescription: + m.ResetDescription() + return nil + case billinginvoicesplitlinegroup.FieldCurrency: + m.ResetCurrency() + return nil + case billinginvoicesplitlinegroup.FieldServicePeriodStart: + m.ResetServicePeriodStart() + return nil + case billinginvoicesplitlinegroup.FieldServicePeriodEnd: + m.ResetServicePeriodEnd() + return nil + case billinginvoicesplitlinegroup.FieldUniqueReferenceID: + m.ResetUniqueReferenceID() + return nil + case billinginvoicesplitlinegroup.FieldRatecardDiscounts: + m.ResetRatecardDiscounts() + return nil + case billinginvoicesplitlinegroup.FieldFeatureKey: + m.ResetFeatureKey() + return nil + case billinginvoicesplitlinegroup.FieldPrice: + m.ResetPrice() + return nil + case billinginvoicesplitlinegroup.FieldSubscriptionID: + m.ResetSubscriptionID() + return nil + case billinginvoicesplitlinegroup.FieldSubscriptionPhaseID: + m.ResetSubscriptionPhaseID() + return nil + case billinginvoicesplitlinegroup.FieldSubscriptionItemID: + m.ResetSubscriptionItemID() + return nil + case billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodFrom: + m.ResetSubscriptionBillingPeriodFrom() + return nil + case billinginvoicesplitlinegroup.FieldSubscriptionBillingPeriodTo: + m.ResetSubscriptionBillingPeriodTo() + return nil + case billinginvoicesplitlinegroup.FieldChargeID: + m.ResetChargeID() + return nil + } + return fmt.Errorf("unknown BillingInvoiceSplitLineGroup field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BillingInvoiceSplitLineGroupMutation) AddedEdges() []string { + edges := make([]string, 0, 5) + if m.billing_invoice_lines != nil { + edges = append(edges, billinginvoicesplitlinegroup.EdgeBillingInvoiceLines) + } + if m.subscription != nil { + edges = append(edges, billinginvoicesplitlinegroup.EdgeSubscription) + } + if m.subscription_phase != nil { + edges = append(edges, billinginvoicesplitlinegroup.EdgeSubscriptionPhase) + } + if m.subscription_item != nil { + edges = append(edges, billinginvoicesplitlinegroup.EdgeSubscriptionItem) + } + if m.charge != nil { + edges = append(edges, billinginvoicesplitlinegroup.EdgeCharge) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BillingInvoiceSplitLineGroupMutation) AddedIDs(name string) []ent.Value { + switch name { + case billinginvoicesplitlinegroup.EdgeBillingInvoiceLines: + ids := make([]ent.Value, 0, len(m.billing_invoice_lines)) + for id := range m.billing_invoice_lines { + ids = append(ids, id) + } + return ids + case billinginvoicesplitlinegroup.EdgeSubscription: + if id := m.subscription; id != nil { + return []ent.Value{*id} + } + case billinginvoicesplitlinegroup.EdgeSubscriptionPhase: + if id := m.subscription_phase; id != nil { + return []ent.Value{*id} + } + case billinginvoicesplitlinegroup.EdgeSubscriptionItem: + if id := m.subscription_item; id != nil { + return []ent.Value{*id} + } + case billinginvoicesplitlinegroup.EdgeCharge: + if id := m.charge; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BillingInvoiceSplitLineGroupMutation) RemovedEdges() []string { + edges := make([]string, 0, 5) + if m.removedbilling_invoice_lines != nil { + edges = append(edges, billinginvoicesplitlinegroup.EdgeBillingInvoiceLines) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *BillingInvoiceSplitLineGroupMutation) RemovedIDs(name string) []ent.Value { + switch name { + case billinginvoicesplitlinegroup.EdgeBillingInvoiceLines: + ids := make([]ent.Value, 0, len(m.removedbilling_invoice_lines)) + for id := range m.removedbilling_invoice_lines { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BillingInvoiceSplitLineGroupMutation) ClearedEdges() []string { + edges := make([]string, 0, 5) + if m.clearedbilling_invoice_lines { + edges = append(edges, billinginvoicesplitlinegroup.EdgeBillingInvoiceLines) + } + if m.clearedsubscription { + edges = append(edges, billinginvoicesplitlinegroup.EdgeSubscription) + } + if m.clearedsubscription_phase { + edges = append(edges, billinginvoicesplitlinegroup.EdgeSubscriptionPhase) + } + if m.clearedsubscription_item { + edges = append(edges, billinginvoicesplitlinegroup.EdgeSubscriptionItem) + } + if m.clearedcharge { + edges = append(edges, billinginvoicesplitlinegroup.EdgeCharge) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BillingInvoiceSplitLineGroupMutation) EdgeCleared(name string) bool { + switch name { + case billinginvoicesplitlinegroup.EdgeBillingInvoiceLines: + return m.clearedbilling_invoice_lines + case billinginvoicesplitlinegroup.EdgeSubscription: + return m.clearedsubscription + case billinginvoicesplitlinegroup.EdgeSubscriptionPhase: + return m.clearedsubscription_phase + case billinginvoicesplitlinegroup.EdgeSubscriptionItem: + return m.clearedsubscription_item + case billinginvoicesplitlinegroup.EdgeCharge: + return m.clearedcharge + } + 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 *BillingInvoiceSplitLineGroupMutation) ClearEdge(name string) error { + switch name { + case billinginvoicesplitlinegroup.EdgeSubscription: + m.ClearSubscription() + return nil + case billinginvoicesplitlinegroup.EdgeSubscriptionPhase: + m.ClearSubscriptionPhase() + return nil + case billinginvoicesplitlinegroup.EdgeSubscriptionItem: + m.ClearSubscriptionItem() + return nil + case billinginvoicesplitlinegroup.EdgeCharge: + m.ClearCharge() + return nil + } + return fmt.Errorf("unknown BillingInvoiceSplitLineGroup 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 *BillingInvoiceSplitLineGroupMutation) ResetEdge(name string) error { + switch name { + case billinginvoicesplitlinegroup.EdgeBillingInvoiceLines: + m.ResetBillingInvoiceLines() + return nil + case billinginvoicesplitlinegroup.EdgeSubscription: + m.ResetSubscription() + return nil + case billinginvoicesplitlinegroup.EdgeSubscriptionPhase: + m.ResetSubscriptionPhase() + return nil + case billinginvoicesplitlinegroup.EdgeSubscriptionItem: + m.ResetSubscriptionItem() + return nil + case billinginvoicesplitlinegroup.EdgeCharge: + m.ResetCharge() + return nil + } + return fmt.Errorf("unknown BillingInvoiceSplitLineGroup edge %s", name) +} + +// BillingInvoiceUsageBasedLineConfigMutation represents an operation that mutates the BillingInvoiceUsageBasedLineConfig nodes in the graph. +type BillingInvoiceUsageBasedLineConfigMutation struct { + config + op Op + typ string + id *string + namespace *string + price_type *productcatalog.PriceType + feature_key *string + price **productcatalog.Price + pre_line_period_quantity *alpacadecimal.Decimal + metered_pre_line_period_quantity *alpacadecimal.Decimal + metered_quantity *alpacadecimal.Decimal + unit_config **productcatalog.UnitConfig + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*BillingInvoiceUsageBasedLineConfig, error) + predicates []predicate.BillingInvoiceUsageBasedLineConfig +} + +var _ ent.Mutation = (*BillingInvoiceUsageBasedLineConfigMutation)(nil) + +// billinginvoiceusagebasedlineconfigOption allows management of the mutation configuration using functional options. +type billinginvoiceusagebasedlineconfigOption func(*BillingInvoiceUsageBasedLineConfigMutation) + +// newBillingInvoiceUsageBasedLineConfigMutation creates new mutation for the BillingInvoiceUsageBasedLineConfig entity. +func newBillingInvoiceUsageBasedLineConfigMutation(c config, op Op, opts ...billinginvoiceusagebasedlineconfigOption) *BillingInvoiceUsageBasedLineConfigMutation { + m := &BillingInvoiceUsageBasedLineConfigMutation{ + config: c, + op: op, + typ: TypeBillingInvoiceUsageBasedLineConfig, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBillingInvoiceUsageBasedLineConfigID sets the ID field of the mutation. +func withBillingInvoiceUsageBasedLineConfigID(id string) billinginvoiceusagebasedlineconfigOption { + return func(m *BillingInvoiceUsageBasedLineConfigMutation) { + var ( + err error + once sync.Once + value *BillingInvoiceUsageBasedLineConfig + ) + m.oldValue = func(ctx context.Context) (*BillingInvoiceUsageBasedLineConfig, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().BillingInvoiceUsageBasedLineConfig.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBillingInvoiceUsageBasedLineConfig sets the old BillingInvoiceUsageBasedLineConfig of the mutation. +func withBillingInvoiceUsageBasedLineConfig(node *BillingInvoiceUsageBasedLineConfig) billinginvoiceusagebasedlineconfigOption { + return func(m *BillingInvoiceUsageBasedLineConfigMutation) { + m.oldValue = func(context.Context) (*BillingInvoiceUsageBasedLineConfig, 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 BillingInvoiceUsageBasedLineConfigMutation) 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 BillingInvoiceUsageBasedLineConfigMutation) 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 BillingInvoiceUsageBasedLineConfig entities. +func (m *BillingInvoiceUsageBasedLineConfigMutation) 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 *BillingInvoiceUsageBasedLineConfigMutation) 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 *BillingInvoiceUsageBasedLineConfigMutation) 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().BillingInvoiceUsageBasedLineConfig.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 *BillingInvoiceUsageBasedLineConfigMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) 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 BillingInvoiceUsageBasedLineConfig entity. +// If the BillingInvoiceUsageBasedLineConfig 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 *BillingInvoiceUsageBasedLineConfigMutation) 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 *BillingInvoiceUsageBasedLineConfigMutation) ResetNamespace() { + m.namespace = nil +} + +// SetPriceType sets the "price_type" field. +func (m *BillingInvoiceUsageBasedLineConfigMutation) SetPriceType(pt productcatalog.PriceType) { + m.price_type = &pt +} + +// PriceType returns the value of the "price_type" field in the mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) PriceType() (r productcatalog.PriceType, exists bool) { + v := m.price_type + if v == nil { + return + } + return *v, true +} + +// OldPriceType returns the old "price_type" field's value of the BillingInvoiceUsageBasedLineConfig entity. +// If the BillingInvoiceUsageBasedLineConfig 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 *BillingInvoiceUsageBasedLineConfigMutation) OldPriceType(ctx context.Context) (v productcatalog.PriceType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPriceType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPriceType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPriceType: %w", err) + } + return oldValue.PriceType, nil +} + +// ResetPriceType resets all changes to the "price_type" field. +func (m *BillingInvoiceUsageBasedLineConfigMutation) ResetPriceType() { + m.price_type = nil +} + +// SetFeatureKey sets the "feature_key" field. +func (m *BillingInvoiceUsageBasedLineConfigMutation) SetFeatureKey(s string) { + m.feature_key = &s +} + +// FeatureKey returns the value of the "feature_key" field in the mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) 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 BillingInvoiceUsageBasedLineConfig entity. +// If the BillingInvoiceUsageBasedLineConfig 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 *BillingInvoiceUsageBasedLineConfigMutation) 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 +} + +// ClearFeatureKey clears the value of the "feature_key" field. +func (m *BillingInvoiceUsageBasedLineConfigMutation) ClearFeatureKey() { + m.feature_key = nil + m.clearedFields[billinginvoiceusagebasedlineconfig.FieldFeatureKey] = struct{}{} +} + +// FeatureKeyCleared returns if the "feature_key" field was cleared in this mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) FeatureKeyCleared() bool { + _, ok := m.clearedFields[billinginvoiceusagebasedlineconfig.FieldFeatureKey] + return ok +} + +// ResetFeatureKey resets all changes to the "feature_key" field. +func (m *BillingInvoiceUsageBasedLineConfigMutation) ResetFeatureKey() { + m.feature_key = nil + delete(m.clearedFields, billinginvoiceusagebasedlineconfig.FieldFeatureKey) +} + +// SetPrice sets the "price" field. +func (m *BillingInvoiceUsageBasedLineConfigMutation) SetPrice(pr *productcatalog.Price) { + m.price = &pr +} + +// Price returns the value of the "price" field in the mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) 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 BillingInvoiceUsageBasedLineConfig entity. +// If the BillingInvoiceUsageBasedLineConfig 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 *BillingInvoiceUsageBasedLineConfigMutation) 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 *BillingInvoiceUsageBasedLineConfigMutation) ResetPrice() { + m.price = nil +} + +// SetPreLinePeriodQuantity sets the "pre_line_period_quantity" field. +func (m *BillingInvoiceUsageBasedLineConfigMutation) SetPreLinePeriodQuantity(a alpacadecimal.Decimal) { + m.pre_line_period_quantity = &a +} + +// PreLinePeriodQuantity returns the value of the "pre_line_period_quantity" field in the mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) PreLinePeriodQuantity() (r alpacadecimal.Decimal, exists bool) { + v := m.pre_line_period_quantity + if v == nil { + return + } + return *v, true +} + +// OldPreLinePeriodQuantity returns the old "pre_line_period_quantity" field's value of the BillingInvoiceUsageBasedLineConfig entity. +// If the BillingInvoiceUsageBasedLineConfig 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 *BillingInvoiceUsageBasedLineConfigMutation) OldPreLinePeriodQuantity(ctx context.Context) (v *alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPreLinePeriodQuantity is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPreLinePeriodQuantity requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPreLinePeriodQuantity: %w", err) + } + return oldValue.PreLinePeriodQuantity, nil +} + +// ClearPreLinePeriodQuantity clears the value of the "pre_line_period_quantity" field. +func (m *BillingInvoiceUsageBasedLineConfigMutation) ClearPreLinePeriodQuantity() { + m.pre_line_period_quantity = nil + m.clearedFields[billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity] = struct{}{} +} + +// PreLinePeriodQuantityCleared returns if the "pre_line_period_quantity" field was cleared in this mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) PreLinePeriodQuantityCleared() bool { + _, ok := m.clearedFields[billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity] + return ok +} + +// ResetPreLinePeriodQuantity resets all changes to the "pre_line_period_quantity" field. +func (m *BillingInvoiceUsageBasedLineConfigMutation) ResetPreLinePeriodQuantity() { + m.pre_line_period_quantity = nil + delete(m.clearedFields, billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity) +} + +// SetMeteredPreLinePeriodQuantity sets the "metered_pre_line_period_quantity" field. +func (m *BillingInvoiceUsageBasedLineConfigMutation) SetMeteredPreLinePeriodQuantity(a alpacadecimal.Decimal) { + m.metered_pre_line_period_quantity = &a +} + +// MeteredPreLinePeriodQuantity returns the value of the "metered_pre_line_period_quantity" field in the mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) MeteredPreLinePeriodQuantity() (r alpacadecimal.Decimal, exists bool) { + v := m.metered_pre_line_period_quantity + if v == nil { + return + } + return *v, true +} + +// OldMeteredPreLinePeriodQuantity returns the old "metered_pre_line_period_quantity" field's value of the BillingInvoiceUsageBasedLineConfig entity. +// If the BillingInvoiceUsageBasedLineConfig 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 *BillingInvoiceUsageBasedLineConfigMutation) OldMeteredPreLinePeriodQuantity(ctx context.Context) (v *alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMeteredPreLinePeriodQuantity is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMeteredPreLinePeriodQuantity requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMeteredPreLinePeriodQuantity: %w", err) + } + return oldValue.MeteredPreLinePeriodQuantity, nil +} + +// ClearMeteredPreLinePeriodQuantity clears the value of the "metered_pre_line_period_quantity" field. +func (m *BillingInvoiceUsageBasedLineConfigMutation) ClearMeteredPreLinePeriodQuantity() { + m.metered_pre_line_period_quantity = nil + m.clearedFields[billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity] = struct{}{} +} + +// MeteredPreLinePeriodQuantityCleared returns if the "metered_pre_line_period_quantity" field was cleared in this mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) MeteredPreLinePeriodQuantityCleared() bool { + _, ok := m.clearedFields[billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity] + return ok +} + +// ResetMeteredPreLinePeriodQuantity resets all changes to the "metered_pre_line_period_quantity" field. +func (m *BillingInvoiceUsageBasedLineConfigMutation) ResetMeteredPreLinePeriodQuantity() { + m.metered_pre_line_period_quantity = nil + delete(m.clearedFields, billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity) +} + +// SetMeteredQuantity sets the "metered_quantity" field. +func (m *BillingInvoiceUsageBasedLineConfigMutation) SetMeteredQuantity(a alpacadecimal.Decimal) { + m.metered_quantity = &a +} + +// MeteredQuantity returns the value of the "metered_quantity" field in the mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) MeteredQuantity() (r alpacadecimal.Decimal, exists bool) { + v := m.metered_quantity + if v == nil { + return + } + return *v, true +} + +// OldMeteredQuantity returns the old "metered_quantity" field's value of the BillingInvoiceUsageBasedLineConfig entity. +// If the BillingInvoiceUsageBasedLineConfig 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 *BillingInvoiceUsageBasedLineConfigMutation) OldMeteredQuantity(ctx context.Context) (v *alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMeteredQuantity is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMeteredQuantity requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMeteredQuantity: %w", err) + } + return oldValue.MeteredQuantity, nil +} + +// ClearMeteredQuantity clears the value of the "metered_quantity" field. +func (m *BillingInvoiceUsageBasedLineConfigMutation) ClearMeteredQuantity() { + m.metered_quantity = nil + m.clearedFields[billinginvoiceusagebasedlineconfig.FieldMeteredQuantity] = struct{}{} +} + +// MeteredQuantityCleared returns if the "metered_quantity" field was cleared in this mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) MeteredQuantityCleared() bool { + _, ok := m.clearedFields[billinginvoiceusagebasedlineconfig.FieldMeteredQuantity] + return ok +} + +// ResetMeteredQuantity resets all changes to the "metered_quantity" field. +func (m *BillingInvoiceUsageBasedLineConfigMutation) ResetMeteredQuantity() { + m.metered_quantity = nil + delete(m.clearedFields, billinginvoiceusagebasedlineconfig.FieldMeteredQuantity) +} + +// SetUnitConfig sets the "unit_config" field. +func (m *BillingInvoiceUsageBasedLineConfigMutation) SetUnitConfig(pc *productcatalog.UnitConfig) { + m.unit_config = &pc +} + +// UnitConfig returns the value of the "unit_config" field in the mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) UnitConfig() (r *productcatalog.UnitConfig, exists bool) { + v := m.unit_config + if v == nil { + return + } + return *v, true +} + +// OldUnitConfig returns the old "unit_config" field's value of the BillingInvoiceUsageBasedLineConfig entity. +// If the BillingInvoiceUsageBasedLineConfig 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 *BillingInvoiceUsageBasedLineConfigMutation) OldUnitConfig(ctx context.Context) (v *productcatalog.UnitConfig, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUnitConfig is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUnitConfig requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUnitConfig: %w", err) + } + return oldValue.UnitConfig, nil +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (m *BillingInvoiceUsageBasedLineConfigMutation) ClearUnitConfig() { + m.unit_config = nil + m.clearedFields[billinginvoiceusagebasedlineconfig.FieldUnitConfig] = struct{}{} +} + +// UnitConfigCleared returns if the "unit_config" field was cleared in this mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) UnitConfigCleared() bool { + _, ok := m.clearedFields[billinginvoiceusagebasedlineconfig.FieldUnitConfig] + return ok +} + +// ResetUnitConfig resets all changes to the "unit_config" field. +func (m *BillingInvoiceUsageBasedLineConfigMutation) ResetUnitConfig() { + m.unit_config = nil + delete(m.clearedFields, billinginvoiceusagebasedlineconfig.FieldUnitConfig) +} + +// Where appends a list predicates to the BillingInvoiceUsageBasedLineConfigMutation builder. +func (m *BillingInvoiceUsageBasedLineConfigMutation) Where(ps ...predicate.BillingInvoiceUsageBasedLineConfig) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BillingInvoiceUsageBasedLineConfigMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BillingInvoiceUsageBasedLineConfigMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillingInvoiceUsageBasedLineConfig, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BillingInvoiceUsageBasedLineConfigMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BillingInvoiceUsageBasedLineConfig). +func (m *BillingInvoiceUsageBasedLineConfigMutation) 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 *BillingInvoiceUsageBasedLineConfigMutation) Fields() []string { + fields := make([]string, 0, 8) + if m.namespace != nil { + fields = append(fields, billinginvoiceusagebasedlineconfig.FieldNamespace) + } + if m.price_type != nil { + fields = append(fields, billinginvoiceusagebasedlineconfig.FieldPriceType) + } + if m.feature_key != nil { + fields = append(fields, billinginvoiceusagebasedlineconfig.FieldFeatureKey) + } + if m.price != nil { + fields = append(fields, billinginvoiceusagebasedlineconfig.FieldPrice) + } + if m.pre_line_period_quantity != nil { + fields = append(fields, billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity) + } + if m.metered_pre_line_period_quantity != nil { + fields = append(fields, billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity) + } + if m.metered_quantity != nil { + fields = append(fields, billinginvoiceusagebasedlineconfig.FieldMeteredQuantity) + } + if m.unit_config != nil { + fields = append(fields, billinginvoiceusagebasedlineconfig.FieldUnitConfig) + } + 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 *BillingInvoiceUsageBasedLineConfigMutation) Field(name string) (ent.Value, bool) { + switch name { + case billinginvoiceusagebasedlineconfig.FieldNamespace: + return m.Namespace() + case billinginvoiceusagebasedlineconfig.FieldPriceType: + return m.PriceType() + case billinginvoiceusagebasedlineconfig.FieldFeatureKey: + return m.FeatureKey() + case billinginvoiceusagebasedlineconfig.FieldPrice: + return m.Price() + case billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity: + return m.PreLinePeriodQuantity() + case billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity: + return m.MeteredPreLinePeriodQuantity() + case billinginvoiceusagebasedlineconfig.FieldMeteredQuantity: + return m.MeteredQuantity() + case billinginvoiceusagebasedlineconfig.FieldUnitConfig: + return m.UnitConfig() + } + 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 *BillingInvoiceUsageBasedLineConfigMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case billinginvoiceusagebasedlineconfig.FieldNamespace: + return m.OldNamespace(ctx) + case billinginvoiceusagebasedlineconfig.FieldPriceType: + return m.OldPriceType(ctx) + case billinginvoiceusagebasedlineconfig.FieldFeatureKey: + return m.OldFeatureKey(ctx) + case billinginvoiceusagebasedlineconfig.FieldPrice: + return m.OldPrice(ctx) + case billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity: + return m.OldPreLinePeriodQuantity(ctx) + case billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity: + return m.OldMeteredPreLinePeriodQuantity(ctx) + case billinginvoiceusagebasedlineconfig.FieldMeteredQuantity: + return m.OldMeteredQuantity(ctx) + case billinginvoiceusagebasedlineconfig.FieldUnitConfig: + return m.OldUnitConfig(ctx) + } + return nil, fmt.Errorf("unknown BillingInvoiceUsageBasedLineConfig 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 *BillingInvoiceUsageBasedLineConfigMutation) SetField(name string, value ent.Value) error { + switch name { + case billinginvoiceusagebasedlineconfig.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case billinginvoiceusagebasedlineconfig.FieldPriceType: + v, ok := value.(productcatalog.PriceType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPriceType(v) + return nil + case billinginvoiceusagebasedlineconfig.FieldFeatureKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFeatureKey(v) + return nil + case billinginvoiceusagebasedlineconfig.FieldPrice: + v, ok := value.(*productcatalog.Price) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPrice(v) + return nil + case billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPreLinePeriodQuantity(v) + return nil + case billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMeteredPreLinePeriodQuantity(v) + return nil + case billinginvoiceusagebasedlineconfig.FieldMeteredQuantity: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMeteredQuantity(v) + return nil + case billinginvoiceusagebasedlineconfig.FieldUnitConfig: + v, ok := value.(*productcatalog.UnitConfig) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUnitConfig(v) + return nil + } + return fmt.Errorf("unknown BillingInvoiceUsageBasedLineConfig field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) 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 *BillingInvoiceUsageBasedLineConfigMutation) 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 *BillingInvoiceUsageBasedLineConfigMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown BillingInvoiceUsageBasedLineConfig numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(billinginvoiceusagebasedlineconfig.FieldFeatureKey) { + fields = append(fields, billinginvoiceusagebasedlineconfig.FieldFeatureKey) + } + if m.FieldCleared(billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity) { + fields = append(fields, billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity) + } + if m.FieldCleared(billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity) { + fields = append(fields, billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity) + } + if m.FieldCleared(billinginvoiceusagebasedlineconfig.FieldMeteredQuantity) { + fields = append(fields, billinginvoiceusagebasedlineconfig.FieldMeteredQuantity) + } + if m.FieldCleared(billinginvoiceusagebasedlineconfig.FieldUnitConfig) { + fields = append(fields, billinginvoiceusagebasedlineconfig.FieldUnitConfig) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) 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 *BillingInvoiceUsageBasedLineConfigMutation) ClearField(name string) error { + switch name { + case billinginvoiceusagebasedlineconfig.FieldFeatureKey: + m.ClearFeatureKey() + return nil + case billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity: + m.ClearPreLinePeriodQuantity() + return nil + case billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity: + m.ClearMeteredPreLinePeriodQuantity() + return nil + case billinginvoiceusagebasedlineconfig.FieldMeteredQuantity: + m.ClearMeteredQuantity() + return nil + case billinginvoiceusagebasedlineconfig.FieldUnitConfig: + m.ClearUnitConfig() + return nil + } + return fmt.Errorf("unknown BillingInvoiceUsageBasedLineConfig 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 *BillingInvoiceUsageBasedLineConfigMutation) ResetField(name string) error { + switch name { + case billinginvoiceusagebasedlineconfig.FieldNamespace: + m.ResetNamespace() + return nil + case billinginvoiceusagebasedlineconfig.FieldPriceType: + m.ResetPriceType() + return nil + case billinginvoiceusagebasedlineconfig.FieldFeatureKey: + m.ResetFeatureKey() + return nil + case billinginvoiceusagebasedlineconfig.FieldPrice: + m.ResetPrice() + return nil + case billinginvoiceusagebasedlineconfig.FieldPreLinePeriodQuantity: + m.ResetPreLinePeriodQuantity() + return nil + case billinginvoiceusagebasedlineconfig.FieldMeteredPreLinePeriodQuantity: + m.ResetMeteredPreLinePeriodQuantity() + return nil + case billinginvoiceusagebasedlineconfig.FieldMeteredQuantity: + m.ResetMeteredQuantity() + return nil + case billinginvoiceusagebasedlineconfig.FieldUnitConfig: + m.ResetUnitConfig() + return nil + } + return fmt.Errorf("unknown BillingInvoiceUsageBasedLineConfig field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BillingInvoiceUsageBasedLineConfigMutation) EdgeCleared(name string) bool { + 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 *BillingInvoiceUsageBasedLineConfigMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown BillingInvoiceUsageBasedLineConfig 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 *BillingInvoiceUsageBasedLineConfigMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown BillingInvoiceUsageBasedLineConfig edge %s", name) +} + +// BillingInvoiceValidationIssueMutation represents an operation that mutates the BillingInvoiceValidationIssue nodes in the graph. +type BillingInvoiceValidationIssueMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + severity *billing.ValidationIssueSeverity + code *string + message *string + _path *string + component *string + dedupe_hash *[]byte + clearedFields map[string]struct{} + billing_invoice *string + clearedbilling_invoice bool + done bool + oldValue func(context.Context) (*BillingInvoiceValidationIssue, error) + predicates []predicate.BillingInvoiceValidationIssue +} + +var _ ent.Mutation = (*BillingInvoiceValidationIssueMutation)(nil) + +// billinginvoicevalidationissueOption allows management of the mutation configuration using functional options. +type billinginvoicevalidationissueOption func(*BillingInvoiceValidationIssueMutation) + +// newBillingInvoiceValidationIssueMutation creates new mutation for the BillingInvoiceValidationIssue entity. +func newBillingInvoiceValidationIssueMutation(c config, op Op, opts ...billinginvoicevalidationissueOption) *BillingInvoiceValidationIssueMutation { + m := &BillingInvoiceValidationIssueMutation{ + config: c, + op: op, + typ: TypeBillingInvoiceValidationIssue, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBillingInvoiceValidationIssueID sets the ID field of the mutation. +func withBillingInvoiceValidationIssueID(id string) billinginvoicevalidationissueOption { + return func(m *BillingInvoiceValidationIssueMutation) { + var ( + err error + once sync.Once + value *BillingInvoiceValidationIssue + ) + m.oldValue = func(ctx context.Context) (*BillingInvoiceValidationIssue, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().BillingInvoiceValidationIssue.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBillingInvoiceValidationIssue sets the old BillingInvoiceValidationIssue of the mutation. +func withBillingInvoiceValidationIssue(node *BillingInvoiceValidationIssue) billinginvoicevalidationissueOption { + return func(m *BillingInvoiceValidationIssueMutation) { + m.oldValue = func(context.Context) (*BillingInvoiceValidationIssue, 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 BillingInvoiceValidationIssueMutation) 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 BillingInvoiceValidationIssueMutation) 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 BillingInvoiceValidationIssue entities. +func (m *BillingInvoiceValidationIssueMutation) 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 *BillingInvoiceValidationIssueMutation) 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 *BillingInvoiceValidationIssueMutation) 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().BillingInvoiceValidationIssue.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 *BillingInvoiceValidationIssueMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *BillingInvoiceValidationIssueMutation) 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 BillingInvoiceValidationIssue entity. +// If the BillingInvoiceValidationIssue 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 *BillingInvoiceValidationIssueMutation) 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 *BillingInvoiceValidationIssueMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *BillingInvoiceValidationIssueMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *BillingInvoiceValidationIssueMutation) 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 BillingInvoiceValidationIssue entity. +// If the BillingInvoiceValidationIssue 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 *BillingInvoiceValidationIssueMutation) 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 *BillingInvoiceValidationIssueMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *BillingInvoiceValidationIssueMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *BillingInvoiceValidationIssueMutation) 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 BillingInvoiceValidationIssue entity. +// If the BillingInvoiceValidationIssue 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 *BillingInvoiceValidationIssueMutation) 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 *BillingInvoiceValidationIssueMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *BillingInvoiceValidationIssueMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *BillingInvoiceValidationIssueMutation) 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 BillingInvoiceValidationIssue entity. +// If the BillingInvoiceValidationIssue 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 *BillingInvoiceValidationIssueMutation) 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 *BillingInvoiceValidationIssueMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[billinginvoicevalidationissue.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *BillingInvoiceValidationIssueMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[billinginvoicevalidationissue.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *BillingInvoiceValidationIssueMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, billinginvoicevalidationissue.FieldDeletedAt) +} + +// SetInvoiceID sets the "invoice_id" field. +func (m *BillingInvoiceValidationIssueMutation) SetInvoiceID(s string) { + m.billing_invoice = &s +} + +// InvoiceID returns the value of the "invoice_id" field in the mutation. +func (m *BillingInvoiceValidationIssueMutation) InvoiceID() (r string, exists bool) { + v := m.billing_invoice + if v == nil { + return + } + return *v, true +} + +// OldInvoiceID returns the old "invoice_id" field's value of the BillingInvoiceValidationIssue entity. +// If the BillingInvoiceValidationIssue 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 *BillingInvoiceValidationIssueMutation) OldInvoiceID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceID: %w", err) + } + return oldValue.InvoiceID, nil +} + +// ResetInvoiceID resets all changes to the "invoice_id" field. +func (m *BillingInvoiceValidationIssueMutation) ResetInvoiceID() { + m.billing_invoice = nil +} + +// SetSeverity sets the "severity" field. +func (m *BillingInvoiceValidationIssueMutation) SetSeverity(bis billing.ValidationIssueSeverity) { + m.severity = &bis +} + +// Severity returns the value of the "severity" field in the mutation. +func (m *BillingInvoiceValidationIssueMutation) Severity() (r billing.ValidationIssueSeverity, exists bool) { + v := m.severity + if v == nil { + return + } + return *v, true +} + +// OldSeverity returns the old "severity" field's value of the BillingInvoiceValidationIssue entity. +// If the BillingInvoiceValidationIssue 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 *BillingInvoiceValidationIssueMutation) OldSeverity(ctx context.Context) (v billing.ValidationIssueSeverity, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSeverity is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSeverity requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSeverity: %w", err) + } + return oldValue.Severity, nil +} + +// ResetSeverity resets all changes to the "severity" field. +func (m *BillingInvoiceValidationIssueMutation) ResetSeverity() { + m.severity = nil +} + +// SetCode sets the "code" field. +func (m *BillingInvoiceValidationIssueMutation) SetCode(s string) { + m.code = &s +} + +// Code returns the value of the "code" field in the mutation. +func (m *BillingInvoiceValidationIssueMutation) Code() (r string, exists bool) { + v := m.code + if v == nil { + return + } + return *v, true +} + +// OldCode returns the old "code" field's value of the BillingInvoiceValidationIssue entity. +// If the BillingInvoiceValidationIssue 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 *BillingInvoiceValidationIssueMutation) OldCode(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCode is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCode requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCode: %w", err) + } + return oldValue.Code, nil +} + +// ClearCode clears the value of the "code" field. +func (m *BillingInvoiceValidationIssueMutation) ClearCode() { + m.code = nil + m.clearedFields[billinginvoicevalidationissue.FieldCode] = struct{}{} +} + +// CodeCleared returns if the "code" field was cleared in this mutation. +func (m *BillingInvoiceValidationIssueMutation) CodeCleared() bool { + _, ok := m.clearedFields[billinginvoicevalidationissue.FieldCode] + return ok +} + +// ResetCode resets all changes to the "code" field. +func (m *BillingInvoiceValidationIssueMutation) ResetCode() { + m.code = nil + delete(m.clearedFields, billinginvoicevalidationissue.FieldCode) +} + +// SetMessage sets the "message" field. +func (m *BillingInvoiceValidationIssueMutation) SetMessage(s string) { + m.message = &s +} + +// Message returns the value of the "message" field in the mutation. +func (m *BillingInvoiceValidationIssueMutation) Message() (r string, exists bool) { + v := m.message + if v == nil { + return + } + return *v, true +} + +// OldMessage returns the old "message" field's value of the BillingInvoiceValidationIssue entity. +// If the BillingInvoiceValidationIssue 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 *BillingInvoiceValidationIssueMutation) OldMessage(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMessage is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMessage requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMessage: %w", err) + } + return oldValue.Message, nil +} + +// ResetMessage resets all changes to the "message" field. +func (m *BillingInvoiceValidationIssueMutation) ResetMessage() { + m.message = nil +} + +// SetPath sets the "path" field. +func (m *BillingInvoiceValidationIssueMutation) SetPath(s string) { + m._path = &s +} + +// Path returns the value of the "path" field in the mutation. +func (m *BillingInvoiceValidationIssueMutation) Path() (r string, exists bool) { + v := m._path + if v == nil { + return + } + return *v, true +} + +// OldPath returns the old "path" field's value of the BillingInvoiceValidationIssue entity. +// If the BillingInvoiceValidationIssue 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 *BillingInvoiceValidationIssueMutation) OldPath(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPath is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPath requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPath: %w", err) + } + return oldValue.Path, nil +} + +// ClearPath clears the value of the "path" field. +func (m *BillingInvoiceValidationIssueMutation) ClearPath() { + m._path = nil + m.clearedFields[billinginvoicevalidationissue.FieldPath] = struct{}{} +} + +// PathCleared returns if the "path" field was cleared in this mutation. +func (m *BillingInvoiceValidationIssueMutation) PathCleared() bool { + _, ok := m.clearedFields[billinginvoicevalidationissue.FieldPath] + return ok +} + +// ResetPath resets all changes to the "path" field. +func (m *BillingInvoiceValidationIssueMutation) ResetPath() { + m._path = nil + delete(m.clearedFields, billinginvoicevalidationissue.FieldPath) +} + +// SetComponent sets the "component" field. +func (m *BillingInvoiceValidationIssueMutation) SetComponent(s string) { + m.component = &s +} + +// Component returns the value of the "component" field in the mutation. +func (m *BillingInvoiceValidationIssueMutation) Component() (r string, exists bool) { + v := m.component + if v == nil { + return + } + return *v, true +} + +// OldComponent returns the old "component" field's value of the BillingInvoiceValidationIssue entity. +// If the BillingInvoiceValidationIssue 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 *BillingInvoiceValidationIssueMutation) OldComponent(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldComponent is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldComponent requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldComponent: %w", err) + } + return oldValue.Component, nil +} + +// ResetComponent resets all changes to the "component" field. +func (m *BillingInvoiceValidationIssueMutation) ResetComponent() { + m.component = nil +} + +// SetDedupeHash sets the "dedupe_hash" field. +func (m *BillingInvoiceValidationIssueMutation) SetDedupeHash(b []byte) { + m.dedupe_hash = &b +} + +// DedupeHash returns the value of the "dedupe_hash" field in the mutation. +func (m *BillingInvoiceValidationIssueMutation) DedupeHash() (r []byte, exists bool) { + v := m.dedupe_hash + if v == nil { + return + } + return *v, true +} + +// OldDedupeHash returns the old "dedupe_hash" field's value of the BillingInvoiceValidationIssue entity. +// If the BillingInvoiceValidationIssue 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 *BillingInvoiceValidationIssueMutation) OldDedupeHash(ctx context.Context) (v []byte, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDedupeHash is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDedupeHash requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDedupeHash: %w", err) + } + return oldValue.DedupeHash, nil +} + +// ResetDedupeHash resets all changes to the "dedupe_hash" field. +func (m *BillingInvoiceValidationIssueMutation) ResetDedupeHash() { + m.dedupe_hash = nil +} + +// SetBillingInvoiceID sets the "billing_invoice" edge to the BillingInvoice entity by id. +func (m *BillingInvoiceValidationIssueMutation) SetBillingInvoiceID(id string) { + m.billing_invoice = &id +} + +// ClearBillingInvoice clears the "billing_invoice" edge to the BillingInvoice entity. +func (m *BillingInvoiceValidationIssueMutation) ClearBillingInvoice() { + m.clearedbilling_invoice = true + m.clearedFields[billinginvoicevalidationissue.FieldInvoiceID] = struct{}{} +} + +// BillingInvoiceCleared reports if the "billing_invoice" edge to the BillingInvoice entity was cleared. +func (m *BillingInvoiceValidationIssueMutation) BillingInvoiceCleared() bool { + return m.clearedbilling_invoice +} + +// BillingInvoiceID returns the "billing_invoice" edge ID in the mutation. +func (m *BillingInvoiceValidationIssueMutation) BillingInvoiceID() (id string, exists bool) { + if m.billing_invoice != nil { + return *m.billing_invoice, true + } + return +} + +// BillingInvoiceIDs returns the "billing_invoice" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BillingInvoiceID instead. It exists only for internal usage by the builders. +func (m *BillingInvoiceValidationIssueMutation) BillingInvoiceIDs() (ids []string) { + if id := m.billing_invoice; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBillingInvoice resets all changes to the "billing_invoice" edge. +func (m *BillingInvoiceValidationIssueMutation) ResetBillingInvoice() { + m.billing_invoice = nil + m.clearedbilling_invoice = false +} + +// Where appends a list predicates to the BillingInvoiceValidationIssueMutation builder. +func (m *BillingInvoiceValidationIssueMutation) Where(ps ...predicate.BillingInvoiceValidationIssue) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BillingInvoiceValidationIssueMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BillingInvoiceValidationIssueMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillingInvoiceValidationIssue, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BillingInvoiceValidationIssueMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BillingInvoiceValidationIssueMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BillingInvoiceValidationIssue). +func (m *BillingInvoiceValidationIssueMutation) 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 *BillingInvoiceValidationIssueMutation) Fields() []string { + fields := make([]string, 0, 11) + if m.namespace != nil { + fields = append(fields, billinginvoicevalidationissue.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, billinginvoicevalidationissue.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, billinginvoicevalidationissue.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, billinginvoicevalidationissue.FieldDeletedAt) + } + if m.billing_invoice != nil { + fields = append(fields, billinginvoicevalidationissue.FieldInvoiceID) + } + if m.severity != nil { + fields = append(fields, billinginvoicevalidationissue.FieldSeverity) + } + if m.code != nil { + fields = append(fields, billinginvoicevalidationissue.FieldCode) + } + if m.message != nil { + fields = append(fields, billinginvoicevalidationissue.FieldMessage) + } + if m._path != nil { + fields = append(fields, billinginvoicevalidationissue.FieldPath) + } + if m.component != nil { + fields = append(fields, billinginvoicevalidationissue.FieldComponent) + } + if m.dedupe_hash != nil { + fields = append(fields, billinginvoicevalidationissue.FieldDedupeHash) + } + 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 *BillingInvoiceValidationIssueMutation) Field(name string) (ent.Value, bool) { + switch name { + case billinginvoicevalidationissue.FieldNamespace: + return m.Namespace() + case billinginvoicevalidationissue.FieldCreatedAt: + return m.CreatedAt() + case billinginvoicevalidationissue.FieldUpdatedAt: + return m.UpdatedAt() + case billinginvoicevalidationissue.FieldDeletedAt: + return m.DeletedAt() + case billinginvoicevalidationissue.FieldInvoiceID: + return m.InvoiceID() + case billinginvoicevalidationissue.FieldSeverity: + return m.Severity() + case billinginvoicevalidationissue.FieldCode: + return m.Code() + case billinginvoicevalidationissue.FieldMessage: + return m.Message() + case billinginvoicevalidationissue.FieldPath: + return m.Path() + case billinginvoicevalidationissue.FieldComponent: + return m.Component() + case billinginvoicevalidationissue.FieldDedupeHash: + return m.DedupeHash() + } + 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 *BillingInvoiceValidationIssueMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case billinginvoicevalidationissue.FieldNamespace: + return m.OldNamespace(ctx) + case billinginvoicevalidationissue.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case billinginvoicevalidationissue.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case billinginvoicevalidationissue.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case billinginvoicevalidationissue.FieldInvoiceID: + return m.OldInvoiceID(ctx) + case billinginvoicevalidationissue.FieldSeverity: + return m.OldSeverity(ctx) + case billinginvoicevalidationissue.FieldCode: + return m.OldCode(ctx) + case billinginvoicevalidationissue.FieldMessage: + return m.OldMessage(ctx) + case billinginvoicevalidationissue.FieldPath: + return m.OldPath(ctx) + case billinginvoicevalidationissue.FieldComponent: + return m.OldComponent(ctx) + case billinginvoicevalidationissue.FieldDedupeHash: + return m.OldDedupeHash(ctx) + } + return nil, fmt.Errorf("unknown BillingInvoiceValidationIssue 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 *BillingInvoiceValidationIssueMutation) SetField(name string, value ent.Value) error { + switch name { + case billinginvoicevalidationissue.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case billinginvoicevalidationissue.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 billinginvoicevalidationissue.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 billinginvoicevalidationissue.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 billinginvoicevalidationissue.FieldInvoiceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceID(v) + return nil + case billinginvoicevalidationissue.FieldSeverity: + v, ok := value.(billing.ValidationIssueSeverity) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSeverity(v) + return nil + case billinginvoicevalidationissue.FieldCode: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCode(v) + return nil + case billinginvoicevalidationissue.FieldMessage: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMessage(v) + return nil + case billinginvoicevalidationissue.FieldPath: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPath(v) + return nil + case billinginvoicevalidationissue.FieldComponent: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetComponent(v) + return nil + case billinginvoicevalidationissue.FieldDedupeHash: + v, ok := value.([]byte) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDedupeHash(v) + return nil + } + return fmt.Errorf("unknown BillingInvoiceValidationIssue field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BillingInvoiceValidationIssueMutation) 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 *BillingInvoiceValidationIssueMutation) 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 *BillingInvoiceValidationIssueMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown BillingInvoiceValidationIssue numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BillingInvoiceValidationIssueMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(billinginvoicevalidationissue.FieldDeletedAt) { + fields = append(fields, billinginvoicevalidationissue.FieldDeletedAt) + } + if m.FieldCleared(billinginvoicevalidationissue.FieldCode) { + fields = append(fields, billinginvoicevalidationissue.FieldCode) + } + if m.FieldCleared(billinginvoicevalidationissue.FieldPath) { + fields = append(fields, billinginvoicevalidationissue.FieldPath) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BillingInvoiceValidationIssueMutation) 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 *BillingInvoiceValidationIssueMutation) ClearField(name string) error { + switch name { + case billinginvoicevalidationissue.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case billinginvoicevalidationissue.FieldCode: + m.ClearCode() + return nil + case billinginvoicevalidationissue.FieldPath: + m.ClearPath() + return nil + } + return fmt.Errorf("unknown BillingInvoiceValidationIssue 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 *BillingInvoiceValidationIssueMutation) ResetField(name string) error { + switch name { + case billinginvoicevalidationissue.FieldNamespace: + m.ResetNamespace() + return nil + case billinginvoicevalidationissue.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case billinginvoicevalidationissue.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case billinginvoicevalidationissue.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case billinginvoicevalidationissue.FieldInvoiceID: + m.ResetInvoiceID() + return nil + case billinginvoicevalidationissue.FieldSeverity: + m.ResetSeverity() + return nil + case billinginvoicevalidationissue.FieldCode: + m.ResetCode() + return nil + case billinginvoicevalidationissue.FieldMessage: + m.ResetMessage() + return nil + case billinginvoicevalidationissue.FieldPath: + m.ResetPath() + return nil + case billinginvoicevalidationissue.FieldComponent: + m.ResetComponent() + return nil + case billinginvoicevalidationissue.FieldDedupeHash: + m.ResetDedupeHash() + return nil + } + return fmt.Errorf("unknown BillingInvoiceValidationIssue field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BillingInvoiceValidationIssueMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.billing_invoice != nil { + edges = append(edges, billinginvoicevalidationissue.EdgeBillingInvoice) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BillingInvoiceValidationIssueMutation) AddedIDs(name string) []ent.Value { + switch name { + case billinginvoicevalidationissue.EdgeBillingInvoice: + if id := m.billing_invoice; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BillingInvoiceValidationIssueMutation) 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 *BillingInvoiceValidationIssueMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BillingInvoiceValidationIssueMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedbilling_invoice { + edges = append(edges, billinginvoicevalidationissue.EdgeBillingInvoice) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BillingInvoiceValidationIssueMutation) EdgeCleared(name string) bool { + switch name { + case billinginvoicevalidationissue.EdgeBillingInvoice: + return m.clearedbilling_invoice + } + 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 *BillingInvoiceValidationIssueMutation) ClearEdge(name string) error { + switch name { + case billinginvoicevalidationissue.EdgeBillingInvoice: + m.ClearBillingInvoice() + return nil + } + return fmt.Errorf("unknown BillingInvoiceValidationIssue 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 *BillingInvoiceValidationIssueMutation) ResetEdge(name string) error { + switch name { + case billinginvoicevalidationissue.EdgeBillingInvoice: + m.ResetBillingInvoice() + return nil + } + return fmt.Errorf("unknown BillingInvoiceValidationIssue edge %s", name) +} + +// BillingInvoiceWriteSchemaLevelMutation represents an operation that mutates the BillingInvoiceWriteSchemaLevel nodes in the graph. +type BillingInvoiceWriteSchemaLevelMutation struct { + config + op Op + typ string + id *string + schema_level *int + addschema_level *int + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*BillingInvoiceWriteSchemaLevel, error) + predicates []predicate.BillingInvoiceWriteSchemaLevel +} + +var _ ent.Mutation = (*BillingInvoiceWriteSchemaLevelMutation)(nil) + +// billinginvoicewriteschemalevelOption allows management of the mutation configuration using functional options. +type billinginvoicewriteschemalevelOption func(*BillingInvoiceWriteSchemaLevelMutation) + +// newBillingInvoiceWriteSchemaLevelMutation creates new mutation for the BillingInvoiceWriteSchemaLevel entity. +func newBillingInvoiceWriteSchemaLevelMutation(c config, op Op, opts ...billinginvoicewriteschemalevelOption) *BillingInvoiceWriteSchemaLevelMutation { + m := &BillingInvoiceWriteSchemaLevelMutation{ + config: c, + op: op, + typ: TypeBillingInvoiceWriteSchemaLevel, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBillingInvoiceWriteSchemaLevelID sets the ID field of the mutation. +func withBillingInvoiceWriteSchemaLevelID(id string) billinginvoicewriteschemalevelOption { + return func(m *BillingInvoiceWriteSchemaLevelMutation) { + var ( + err error + once sync.Once + value *BillingInvoiceWriteSchemaLevel + ) + m.oldValue = func(ctx context.Context) (*BillingInvoiceWriteSchemaLevel, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().BillingInvoiceWriteSchemaLevel.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBillingInvoiceWriteSchemaLevel sets the old BillingInvoiceWriteSchemaLevel of the mutation. +func withBillingInvoiceWriteSchemaLevel(node *BillingInvoiceWriteSchemaLevel) billinginvoicewriteschemalevelOption { + return func(m *BillingInvoiceWriteSchemaLevelMutation) { + m.oldValue = func(context.Context) (*BillingInvoiceWriteSchemaLevel, 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 BillingInvoiceWriteSchemaLevelMutation) 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 BillingInvoiceWriteSchemaLevelMutation) 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 BillingInvoiceWriteSchemaLevel entities. +func (m *BillingInvoiceWriteSchemaLevelMutation) 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 *BillingInvoiceWriteSchemaLevelMutation) 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 *BillingInvoiceWriteSchemaLevelMutation) 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().BillingInvoiceWriteSchemaLevel.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetSchemaLevel sets the "schema_level" field. +func (m *BillingInvoiceWriteSchemaLevelMutation) SetSchemaLevel(i int) { + m.schema_level = &i + m.addschema_level = nil +} + +// SchemaLevel returns the value of the "schema_level" field in the mutation. +func (m *BillingInvoiceWriteSchemaLevelMutation) SchemaLevel() (r int, exists bool) { + v := m.schema_level + if v == nil { + return + } + return *v, true +} + +// OldSchemaLevel returns the old "schema_level" field's value of the BillingInvoiceWriteSchemaLevel entity. +// If the BillingInvoiceWriteSchemaLevel 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 *BillingInvoiceWriteSchemaLevelMutation) OldSchemaLevel(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSchemaLevel is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSchemaLevel requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSchemaLevel: %w", err) + } + return oldValue.SchemaLevel, nil +} + +// AddSchemaLevel adds i to the "schema_level" field. +func (m *BillingInvoiceWriteSchemaLevelMutation) AddSchemaLevel(i int) { + if m.addschema_level != nil { + *m.addschema_level += i + } else { + m.addschema_level = &i + } +} + +// AddedSchemaLevel returns the value that was added to the "schema_level" field in this mutation. +func (m *BillingInvoiceWriteSchemaLevelMutation) AddedSchemaLevel() (r int, exists bool) { + v := m.addschema_level + if v == nil { + return + } + return *v, true +} + +// ResetSchemaLevel resets all changes to the "schema_level" field. +func (m *BillingInvoiceWriteSchemaLevelMutation) ResetSchemaLevel() { + m.schema_level = nil + m.addschema_level = nil +} + +// Where appends a list predicates to the BillingInvoiceWriteSchemaLevelMutation builder. +func (m *BillingInvoiceWriteSchemaLevelMutation) Where(ps ...predicate.BillingInvoiceWriteSchemaLevel) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BillingInvoiceWriteSchemaLevelMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BillingInvoiceWriteSchemaLevelMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillingInvoiceWriteSchemaLevel, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BillingInvoiceWriteSchemaLevelMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BillingInvoiceWriteSchemaLevelMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BillingInvoiceWriteSchemaLevel). +func (m *BillingInvoiceWriteSchemaLevelMutation) 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 *BillingInvoiceWriteSchemaLevelMutation) Fields() []string { + fields := make([]string, 0, 1) + if m.schema_level != nil { + fields = append(fields, billinginvoicewriteschemalevel.FieldSchemaLevel) + } + 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 *BillingInvoiceWriteSchemaLevelMutation) Field(name string) (ent.Value, bool) { + switch name { + case billinginvoicewriteschemalevel.FieldSchemaLevel: + return m.SchemaLevel() + } + 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 *BillingInvoiceWriteSchemaLevelMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case billinginvoicewriteschemalevel.FieldSchemaLevel: + return m.OldSchemaLevel(ctx) + } + return nil, fmt.Errorf("unknown BillingInvoiceWriteSchemaLevel 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 *BillingInvoiceWriteSchemaLevelMutation) SetField(name string, value ent.Value) error { + switch name { + case billinginvoicewriteschemalevel.FieldSchemaLevel: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSchemaLevel(v) + return nil + } + return fmt.Errorf("unknown BillingInvoiceWriteSchemaLevel field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BillingInvoiceWriteSchemaLevelMutation) AddedFields() []string { + var fields []string + if m.addschema_level != nil { + fields = append(fields, billinginvoicewriteschemalevel.FieldSchemaLevel) + } + return fields +} + +// 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 *BillingInvoiceWriteSchemaLevelMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case billinginvoicewriteschemalevel.FieldSchemaLevel: + return m.AddedSchemaLevel() + } + 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 *BillingInvoiceWriteSchemaLevelMutation) AddField(name string, value ent.Value) error { + switch name { + case billinginvoicewriteschemalevel.FieldSchemaLevel: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddSchemaLevel(v) + return nil + } + return fmt.Errorf("unknown BillingInvoiceWriteSchemaLevel numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BillingInvoiceWriteSchemaLevelMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BillingInvoiceWriteSchemaLevelMutation) 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 *BillingInvoiceWriteSchemaLevelMutation) ClearField(name string) error { + return fmt.Errorf("unknown BillingInvoiceWriteSchemaLevel 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 *BillingInvoiceWriteSchemaLevelMutation) ResetField(name string) error { + switch name { + case billinginvoicewriteschemalevel.FieldSchemaLevel: + m.ResetSchemaLevel() + return nil + } + return fmt.Errorf("unknown BillingInvoiceWriteSchemaLevel field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BillingInvoiceWriteSchemaLevelMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BillingInvoiceWriteSchemaLevelMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BillingInvoiceWriteSchemaLevelMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *BillingInvoiceWriteSchemaLevelMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BillingInvoiceWriteSchemaLevelMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BillingInvoiceWriteSchemaLevelMutation) EdgeCleared(name string) bool { + 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 *BillingInvoiceWriteSchemaLevelMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown BillingInvoiceWriteSchemaLevel 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 *BillingInvoiceWriteSchemaLevelMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown BillingInvoiceWriteSchemaLevel edge %s", name) +} + +// BillingProfileMutation represents an operation that mutates the BillingProfile nodes in the graph. +type BillingProfileMutation struct { + config + op Op + typ string + id *string + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + name *string + description *string + supplier_address_country *models.CountryCode + supplier_address_postal_code *string + supplier_address_state *string + supplier_address_city *string + supplier_address_line1 *string + supplier_address_line2 *string + supplier_address_phone_number *string + _default *bool + supplier_name *string + supplier_tax_code *string + clearedFields map[string]struct{} + billing_invoices map[string]struct{} + removedbilling_invoices map[string]struct{} + clearedbilling_invoices bool + billing_customer_override map[string]struct{} + removedbilling_customer_override map[string]struct{} + clearedbilling_customer_override bool + workflow_config *string + clearedworkflow_config bool + tax_app *string + clearedtax_app bool + invoicing_app *string + clearedinvoicing_app bool + payment_app *string + clearedpayment_app bool + done bool + oldValue func(context.Context) (*BillingProfile, error) + predicates []predicate.BillingProfile +} + +var _ ent.Mutation = (*BillingProfileMutation)(nil) + +// billingprofileOption allows management of the mutation configuration using functional options. +type billingprofileOption func(*BillingProfileMutation) + +// newBillingProfileMutation creates new mutation for the BillingProfile entity. +func newBillingProfileMutation(c config, op Op, opts ...billingprofileOption) *BillingProfileMutation { + m := &BillingProfileMutation{ + config: c, + op: op, + typ: TypeBillingProfile, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBillingProfileID sets the ID field of the mutation. +func withBillingProfileID(id string) billingprofileOption { + return func(m *BillingProfileMutation) { + var ( + err error + once sync.Once + value *BillingProfile + ) + m.oldValue = func(ctx context.Context) (*BillingProfile, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().BillingProfile.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBillingProfile sets the old BillingProfile of the mutation. +func withBillingProfile(node *BillingProfile) billingprofileOption { + return func(m *BillingProfileMutation) { + m.oldValue = func(context.Context) (*BillingProfile, 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 BillingProfileMutation) 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 BillingProfileMutation) 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 BillingProfile entities. +func (m *BillingProfileMutation) 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 *BillingProfileMutation) 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 *BillingProfileMutation) 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().BillingProfile.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 *BillingProfileMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *BillingProfileMutation) 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 BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) 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 *BillingProfileMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *BillingProfileMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *BillingProfileMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *BillingProfileMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[billingprofile.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *BillingProfileMutation) MetadataCleared() bool { + _, ok := m.clearedFields[billingprofile.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *BillingProfileMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, billingprofile.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *BillingProfileMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *BillingProfileMutation) 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 BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) 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 *BillingProfileMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *BillingProfileMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *BillingProfileMutation) 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 BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) 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 *BillingProfileMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *BillingProfileMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *BillingProfileMutation) 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 BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) 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 *BillingProfileMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[billingprofile.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *BillingProfileMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[billingprofile.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *BillingProfileMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, billingprofile.FieldDeletedAt) +} + +// SetName sets the "name" field. +func (m *BillingProfileMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *BillingProfileMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *BillingProfileMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *BillingProfileMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *BillingProfileMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *BillingProfileMutation) ClearDescription() { + m.description = nil + m.clearedFields[billingprofile.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *BillingProfileMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[billingprofile.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *BillingProfileMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, billingprofile.FieldDescription) +} + +// SetSupplierAddressCountry sets the "supplier_address_country" field. +func (m *BillingProfileMutation) SetSupplierAddressCountry(mc models.CountryCode) { + m.supplier_address_country = &mc +} + +// SupplierAddressCountry returns the value of the "supplier_address_country" field in the mutation. +func (m *BillingProfileMutation) SupplierAddressCountry() (r models.CountryCode, exists bool) { + v := m.supplier_address_country + if v == nil { + return + } + return *v, true +} + +// OldSupplierAddressCountry returns the old "supplier_address_country" field's value of the BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) OldSupplierAddressCountry(ctx context.Context) (v *models.CountryCode, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSupplierAddressCountry is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSupplierAddressCountry requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSupplierAddressCountry: %w", err) + } + return oldValue.SupplierAddressCountry, nil +} + +// ClearSupplierAddressCountry clears the value of the "supplier_address_country" field. +func (m *BillingProfileMutation) ClearSupplierAddressCountry() { + m.supplier_address_country = nil + m.clearedFields[billingprofile.FieldSupplierAddressCountry] = struct{}{} +} + +// SupplierAddressCountryCleared returns if the "supplier_address_country" field was cleared in this mutation. +func (m *BillingProfileMutation) SupplierAddressCountryCleared() bool { + _, ok := m.clearedFields[billingprofile.FieldSupplierAddressCountry] + return ok +} + +// ResetSupplierAddressCountry resets all changes to the "supplier_address_country" field. +func (m *BillingProfileMutation) ResetSupplierAddressCountry() { + m.supplier_address_country = nil + delete(m.clearedFields, billingprofile.FieldSupplierAddressCountry) +} + +// SetSupplierAddressPostalCode sets the "supplier_address_postal_code" field. +func (m *BillingProfileMutation) SetSupplierAddressPostalCode(s string) { + m.supplier_address_postal_code = &s +} + +// SupplierAddressPostalCode returns the value of the "supplier_address_postal_code" field in the mutation. +func (m *BillingProfileMutation) SupplierAddressPostalCode() (r string, exists bool) { + v := m.supplier_address_postal_code + if v == nil { + return + } + return *v, true +} + +// OldSupplierAddressPostalCode returns the old "supplier_address_postal_code" field's value of the BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) OldSupplierAddressPostalCode(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSupplierAddressPostalCode is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSupplierAddressPostalCode requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSupplierAddressPostalCode: %w", err) + } + return oldValue.SupplierAddressPostalCode, nil +} + +// ClearSupplierAddressPostalCode clears the value of the "supplier_address_postal_code" field. +func (m *BillingProfileMutation) ClearSupplierAddressPostalCode() { + m.supplier_address_postal_code = nil + m.clearedFields[billingprofile.FieldSupplierAddressPostalCode] = struct{}{} +} + +// SupplierAddressPostalCodeCleared returns if the "supplier_address_postal_code" field was cleared in this mutation. +func (m *BillingProfileMutation) SupplierAddressPostalCodeCleared() bool { + _, ok := m.clearedFields[billingprofile.FieldSupplierAddressPostalCode] + return ok +} + +// ResetSupplierAddressPostalCode resets all changes to the "supplier_address_postal_code" field. +func (m *BillingProfileMutation) ResetSupplierAddressPostalCode() { + m.supplier_address_postal_code = nil + delete(m.clearedFields, billingprofile.FieldSupplierAddressPostalCode) +} + +// SetSupplierAddressState sets the "supplier_address_state" field. +func (m *BillingProfileMutation) SetSupplierAddressState(s string) { + m.supplier_address_state = &s +} + +// SupplierAddressState returns the value of the "supplier_address_state" field in the mutation. +func (m *BillingProfileMutation) SupplierAddressState() (r string, exists bool) { + v := m.supplier_address_state + if v == nil { + return + } + return *v, true +} + +// OldSupplierAddressState returns the old "supplier_address_state" field's value of the BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) OldSupplierAddressState(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSupplierAddressState is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSupplierAddressState requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSupplierAddressState: %w", err) + } + return oldValue.SupplierAddressState, nil +} + +// ClearSupplierAddressState clears the value of the "supplier_address_state" field. +func (m *BillingProfileMutation) ClearSupplierAddressState() { + m.supplier_address_state = nil + m.clearedFields[billingprofile.FieldSupplierAddressState] = struct{}{} +} + +// SupplierAddressStateCleared returns if the "supplier_address_state" field was cleared in this mutation. +func (m *BillingProfileMutation) SupplierAddressStateCleared() bool { + _, ok := m.clearedFields[billingprofile.FieldSupplierAddressState] + return ok +} + +// ResetSupplierAddressState resets all changes to the "supplier_address_state" field. +func (m *BillingProfileMutation) ResetSupplierAddressState() { + m.supplier_address_state = nil + delete(m.clearedFields, billingprofile.FieldSupplierAddressState) +} + +// SetSupplierAddressCity sets the "supplier_address_city" field. +func (m *BillingProfileMutation) SetSupplierAddressCity(s string) { + m.supplier_address_city = &s +} + +// SupplierAddressCity returns the value of the "supplier_address_city" field in the mutation. +func (m *BillingProfileMutation) SupplierAddressCity() (r string, exists bool) { + v := m.supplier_address_city + if v == nil { + return + } + return *v, true +} + +// OldSupplierAddressCity returns the old "supplier_address_city" field's value of the BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) OldSupplierAddressCity(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSupplierAddressCity is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSupplierAddressCity requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSupplierAddressCity: %w", err) + } + return oldValue.SupplierAddressCity, nil +} + +// ClearSupplierAddressCity clears the value of the "supplier_address_city" field. +func (m *BillingProfileMutation) ClearSupplierAddressCity() { + m.supplier_address_city = nil + m.clearedFields[billingprofile.FieldSupplierAddressCity] = struct{}{} +} + +// SupplierAddressCityCleared returns if the "supplier_address_city" field was cleared in this mutation. +func (m *BillingProfileMutation) SupplierAddressCityCleared() bool { + _, ok := m.clearedFields[billingprofile.FieldSupplierAddressCity] + return ok +} + +// ResetSupplierAddressCity resets all changes to the "supplier_address_city" field. +func (m *BillingProfileMutation) ResetSupplierAddressCity() { + m.supplier_address_city = nil + delete(m.clearedFields, billingprofile.FieldSupplierAddressCity) +} + +// SetSupplierAddressLine1 sets the "supplier_address_line1" field. +func (m *BillingProfileMutation) SetSupplierAddressLine1(s string) { + m.supplier_address_line1 = &s +} + +// SupplierAddressLine1 returns the value of the "supplier_address_line1" field in the mutation. +func (m *BillingProfileMutation) SupplierAddressLine1() (r string, exists bool) { + v := m.supplier_address_line1 + if v == nil { + return + } + return *v, true +} + +// OldSupplierAddressLine1 returns the old "supplier_address_line1" field's value of the BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) OldSupplierAddressLine1(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSupplierAddressLine1 is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSupplierAddressLine1 requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSupplierAddressLine1: %w", err) + } + return oldValue.SupplierAddressLine1, nil +} + +// ClearSupplierAddressLine1 clears the value of the "supplier_address_line1" field. +func (m *BillingProfileMutation) ClearSupplierAddressLine1() { + m.supplier_address_line1 = nil + m.clearedFields[billingprofile.FieldSupplierAddressLine1] = struct{}{} +} + +// SupplierAddressLine1Cleared returns if the "supplier_address_line1" field was cleared in this mutation. +func (m *BillingProfileMutation) SupplierAddressLine1Cleared() bool { + _, ok := m.clearedFields[billingprofile.FieldSupplierAddressLine1] + return ok +} + +// ResetSupplierAddressLine1 resets all changes to the "supplier_address_line1" field. +func (m *BillingProfileMutation) ResetSupplierAddressLine1() { + m.supplier_address_line1 = nil + delete(m.clearedFields, billingprofile.FieldSupplierAddressLine1) +} + +// SetSupplierAddressLine2 sets the "supplier_address_line2" field. +func (m *BillingProfileMutation) SetSupplierAddressLine2(s string) { + m.supplier_address_line2 = &s +} + +// SupplierAddressLine2 returns the value of the "supplier_address_line2" field in the mutation. +func (m *BillingProfileMutation) SupplierAddressLine2() (r string, exists bool) { + v := m.supplier_address_line2 + if v == nil { + return + } + return *v, true +} + +// OldSupplierAddressLine2 returns the old "supplier_address_line2" field's value of the BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) OldSupplierAddressLine2(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSupplierAddressLine2 is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSupplierAddressLine2 requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSupplierAddressLine2: %w", err) + } + return oldValue.SupplierAddressLine2, nil +} + +// ClearSupplierAddressLine2 clears the value of the "supplier_address_line2" field. +func (m *BillingProfileMutation) ClearSupplierAddressLine2() { + m.supplier_address_line2 = nil + m.clearedFields[billingprofile.FieldSupplierAddressLine2] = struct{}{} +} + +// SupplierAddressLine2Cleared returns if the "supplier_address_line2" field was cleared in this mutation. +func (m *BillingProfileMutation) SupplierAddressLine2Cleared() bool { + _, ok := m.clearedFields[billingprofile.FieldSupplierAddressLine2] + return ok +} + +// ResetSupplierAddressLine2 resets all changes to the "supplier_address_line2" field. +func (m *BillingProfileMutation) ResetSupplierAddressLine2() { + m.supplier_address_line2 = nil + delete(m.clearedFields, billingprofile.FieldSupplierAddressLine2) +} + +// SetSupplierAddressPhoneNumber sets the "supplier_address_phone_number" field. +func (m *BillingProfileMutation) SetSupplierAddressPhoneNumber(s string) { + m.supplier_address_phone_number = &s +} + +// SupplierAddressPhoneNumber returns the value of the "supplier_address_phone_number" field in the mutation. +func (m *BillingProfileMutation) SupplierAddressPhoneNumber() (r string, exists bool) { + v := m.supplier_address_phone_number + if v == nil { + return + } + return *v, true +} + +// OldSupplierAddressPhoneNumber returns the old "supplier_address_phone_number" field's value of the BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) OldSupplierAddressPhoneNumber(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSupplierAddressPhoneNumber is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSupplierAddressPhoneNumber requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSupplierAddressPhoneNumber: %w", err) + } + return oldValue.SupplierAddressPhoneNumber, nil +} + +// ClearSupplierAddressPhoneNumber clears the value of the "supplier_address_phone_number" field. +func (m *BillingProfileMutation) ClearSupplierAddressPhoneNumber() { + m.supplier_address_phone_number = nil + m.clearedFields[billingprofile.FieldSupplierAddressPhoneNumber] = struct{}{} +} + +// SupplierAddressPhoneNumberCleared returns if the "supplier_address_phone_number" field was cleared in this mutation. +func (m *BillingProfileMutation) SupplierAddressPhoneNumberCleared() bool { + _, ok := m.clearedFields[billingprofile.FieldSupplierAddressPhoneNumber] + return ok +} + +// ResetSupplierAddressPhoneNumber resets all changes to the "supplier_address_phone_number" field. +func (m *BillingProfileMutation) ResetSupplierAddressPhoneNumber() { + m.supplier_address_phone_number = nil + delete(m.clearedFields, billingprofile.FieldSupplierAddressPhoneNumber) +} + +// SetTaxAppID sets the "tax_app_id" field. +func (m *BillingProfileMutation) SetTaxAppID(s string) { + m.tax_app = &s +} + +// TaxAppID returns the value of the "tax_app_id" field in the mutation. +func (m *BillingProfileMutation) TaxAppID() (r string, exists bool) { + v := m.tax_app + if v == nil { + return + } + return *v, true +} + +// OldTaxAppID returns the old "tax_app_id" field's value of the BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) OldTaxAppID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxAppID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxAppID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxAppID: %w", err) + } + return oldValue.TaxAppID, nil +} + +// ResetTaxAppID resets all changes to the "tax_app_id" field. +func (m *BillingProfileMutation) ResetTaxAppID() { + m.tax_app = nil +} + +// SetInvoicingAppID sets the "invoicing_app_id" field. +func (m *BillingProfileMutation) SetInvoicingAppID(s string) { + m.invoicing_app = &s +} + +// InvoicingAppID returns the value of the "invoicing_app_id" field in the mutation. +func (m *BillingProfileMutation) InvoicingAppID() (r string, exists bool) { + v := m.invoicing_app + if v == nil { + return + } + return *v, true +} + +// OldInvoicingAppID returns the old "invoicing_app_id" field's value of the BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) OldInvoicingAppID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoicingAppID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoicingAppID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoicingAppID: %w", err) + } + return oldValue.InvoicingAppID, nil +} + +// ResetInvoicingAppID resets all changes to the "invoicing_app_id" field. +func (m *BillingProfileMutation) ResetInvoicingAppID() { + m.invoicing_app = nil +} + +// SetPaymentAppID sets the "payment_app_id" field. +func (m *BillingProfileMutation) SetPaymentAppID(s string) { + m.payment_app = &s +} + +// PaymentAppID returns the value of the "payment_app_id" field in the mutation. +func (m *BillingProfileMutation) PaymentAppID() (r string, exists bool) { + v := m.payment_app + if v == nil { + return + } + return *v, true +} + +// OldPaymentAppID returns the old "payment_app_id" field's value of the BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) OldPaymentAppID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPaymentAppID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPaymentAppID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPaymentAppID: %w", err) + } + return oldValue.PaymentAppID, nil +} + +// ResetPaymentAppID resets all changes to the "payment_app_id" field. +func (m *BillingProfileMutation) ResetPaymentAppID() { + m.payment_app = nil +} + +// SetWorkflowConfigID sets the "workflow_config_id" field. +func (m *BillingProfileMutation) SetWorkflowConfigID(s string) { + m.workflow_config = &s +} + +// WorkflowConfigID returns the value of the "workflow_config_id" field in the mutation. +func (m *BillingProfileMutation) WorkflowConfigID() (r string, exists bool) { + v := m.workflow_config + if v == nil { + return + } + return *v, true +} + +// OldWorkflowConfigID returns the old "workflow_config_id" field's value of the BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) OldWorkflowConfigID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldWorkflowConfigID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldWorkflowConfigID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldWorkflowConfigID: %w", err) + } + return oldValue.WorkflowConfigID, nil +} + +// ResetWorkflowConfigID resets all changes to the "workflow_config_id" field. +func (m *BillingProfileMutation) ResetWorkflowConfigID() { + m.workflow_config = nil +} + +// SetDefault sets the "default" field. +func (m *BillingProfileMutation) SetDefault(b bool) { + m._default = &b +} + +// Default returns the value of the "default" field in the mutation. +func (m *BillingProfileMutation) Default() (r bool, exists bool) { + v := m._default + if v == nil { + return + } + return *v, true +} + +// OldDefault returns the old "default" field's value of the BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) OldDefault(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDefault is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDefault requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDefault: %w", err) + } + return oldValue.Default, nil +} + +// ResetDefault resets all changes to the "default" field. +func (m *BillingProfileMutation) ResetDefault() { + m._default = nil +} + +// SetSupplierName sets the "supplier_name" field. +func (m *BillingProfileMutation) SetSupplierName(s string) { + m.supplier_name = &s +} + +// SupplierName returns the value of the "supplier_name" field in the mutation. +func (m *BillingProfileMutation) SupplierName() (r string, exists bool) { + v := m.supplier_name + if v == nil { + return + } + return *v, true +} + +// OldSupplierName returns the old "supplier_name" field's value of the BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) OldSupplierName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSupplierName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSupplierName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSupplierName: %w", err) + } + return oldValue.SupplierName, nil +} + +// ResetSupplierName resets all changes to the "supplier_name" field. +func (m *BillingProfileMutation) ResetSupplierName() { + m.supplier_name = nil +} + +// SetSupplierTaxCode sets the "supplier_tax_code" field. +func (m *BillingProfileMutation) SetSupplierTaxCode(s string) { + m.supplier_tax_code = &s +} + +// SupplierTaxCode returns the value of the "supplier_tax_code" field in the mutation. +func (m *BillingProfileMutation) SupplierTaxCode() (r string, exists bool) { + v := m.supplier_tax_code + if v == nil { + return + } + return *v, true +} + +// OldSupplierTaxCode returns the old "supplier_tax_code" field's value of the BillingProfile entity. +// If the BillingProfile 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 *BillingProfileMutation) OldSupplierTaxCode(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSupplierTaxCode is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSupplierTaxCode requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSupplierTaxCode: %w", err) + } + return oldValue.SupplierTaxCode, nil +} + +// ClearSupplierTaxCode clears the value of the "supplier_tax_code" field. +func (m *BillingProfileMutation) ClearSupplierTaxCode() { + m.supplier_tax_code = nil + m.clearedFields[billingprofile.FieldSupplierTaxCode] = struct{}{} +} + +// SupplierTaxCodeCleared returns if the "supplier_tax_code" field was cleared in this mutation. +func (m *BillingProfileMutation) SupplierTaxCodeCleared() bool { + _, ok := m.clearedFields[billingprofile.FieldSupplierTaxCode] + return ok +} + +// ResetSupplierTaxCode resets all changes to the "supplier_tax_code" field. +func (m *BillingProfileMutation) ResetSupplierTaxCode() { + m.supplier_tax_code = nil + delete(m.clearedFields, billingprofile.FieldSupplierTaxCode) +} + +// AddBillingInvoiceIDs adds the "billing_invoices" edge to the BillingInvoice entity by ids. +func (m *BillingProfileMutation) AddBillingInvoiceIDs(ids ...string) { + if m.billing_invoices == nil { + m.billing_invoices = make(map[string]struct{}) + } + for i := range ids { + m.billing_invoices[ids[i]] = struct{}{} + } +} + +// ClearBillingInvoices clears the "billing_invoices" edge to the BillingInvoice entity. +func (m *BillingProfileMutation) ClearBillingInvoices() { + m.clearedbilling_invoices = true +} + +// BillingInvoicesCleared reports if the "billing_invoices" edge to the BillingInvoice entity was cleared. +func (m *BillingProfileMutation) BillingInvoicesCleared() bool { + return m.clearedbilling_invoices +} + +// RemoveBillingInvoiceIDs removes the "billing_invoices" edge to the BillingInvoice entity by IDs. +func (m *BillingProfileMutation) RemoveBillingInvoiceIDs(ids ...string) { + if m.removedbilling_invoices == nil { + m.removedbilling_invoices = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_invoices, ids[i]) + m.removedbilling_invoices[ids[i]] = struct{}{} + } +} + +// RemovedBillingInvoices returns the removed IDs of the "billing_invoices" edge to the BillingInvoice entity. +func (m *BillingProfileMutation) RemovedBillingInvoicesIDs() (ids []string) { + for id := range m.removedbilling_invoices { + ids = append(ids, id) + } + return +} + +// BillingInvoicesIDs returns the "billing_invoices" edge IDs in the mutation. +func (m *BillingProfileMutation) BillingInvoicesIDs() (ids []string) { + for id := range m.billing_invoices { + ids = append(ids, id) + } + return +} + +// ResetBillingInvoices resets all changes to the "billing_invoices" edge. +func (m *BillingProfileMutation) ResetBillingInvoices() { + m.billing_invoices = nil + m.clearedbilling_invoices = false + m.removedbilling_invoices = nil +} + +// AddBillingCustomerOverrideIDs adds the "billing_customer_override" edge to the BillingCustomerOverride entity by ids. +func (m *BillingProfileMutation) AddBillingCustomerOverrideIDs(ids ...string) { + if m.billing_customer_override == nil { + m.billing_customer_override = make(map[string]struct{}) + } + for i := range ids { + m.billing_customer_override[ids[i]] = struct{}{} + } +} + +// ClearBillingCustomerOverride clears the "billing_customer_override" edge to the BillingCustomerOverride entity. +func (m *BillingProfileMutation) ClearBillingCustomerOverride() { + m.clearedbilling_customer_override = true +} + +// BillingCustomerOverrideCleared reports if the "billing_customer_override" edge to the BillingCustomerOverride entity was cleared. +func (m *BillingProfileMutation) BillingCustomerOverrideCleared() bool { + return m.clearedbilling_customer_override +} + +// RemoveBillingCustomerOverrideIDs removes the "billing_customer_override" edge to the BillingCustomerOverride entity by IDs. +func (m *BillingProfileMutation) RemoveBillingCustomerOverrideIDs(ids ...string) { + if m.removedbilling_customer_override == nil { + m.removedbilling_customer_override = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_customer_override, ids[i]) + m.removedbilling_customer_override[ids[i]] = struct{}{} + } +} + +// RemovedBillingCustomerOverride returns the removed IDs of the "billing_customer_override" edge to the BillingCustomerOverride entity. +func (m *BillingProfileMutation) RemovedBillingCustomerOverrideIDs() (ids []string) { + for id := range m.removedbilling_customer_override { + ids = append(ids, id) + } + return +} + +// BillingCustomerOverrideIDs returns the "billing_customer_override" edge IDs in the mutation. +func (m *BillingProfileMutation) BillingCustomerOverrideIDs() (ids []string) { + for id := range m.billing_customer_override { + ids = append(ids, id) + } + return +} + +// ResetBillingCustomerOverride resets all changes to the "billing_customer_override" edge. +func (m *BillingProfileMutation) ResetBillingCustomerOverride() { + m.billing_customer_override = nil + m.clearedbilling_customer_override = false + m.removedbilling_customer_override = nil +} + +// ClearWorkflowConfig clears the "workflow_config" edge to the BillingWorkflowConfig entity. +func (m *BillingProfileMutation) ClearWorkflowConfig() { + m.clearedworkflow_config = true + m.clearedFields[billingprofile.FieldWorkflowConfigID] = struct{}{} +} + +// WorkflowConfigCleared reports if the "workflow_config" edge to the BillingWorkflowConfig entity was cleared. +func (m *BillingProfileMutation) WorkflowConfigCleared() bool { + return m.clearedworkflow_config +} + +// WorkflowConfigIDs returns the "workflow_config" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// WorkflowConfigID instead. It exists only for internal usage by the builders. +func (m *BillingProfileMutation) WorkflowConfigIDs() (ids []string) { + if id := m.workflow_config; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetWorkflowConfig resets all changes to the "workflow_config" edge. +func (m *BillingProfileMutation) ResetWorkflowConfig() { + m.workflow_config = nil + m.clearedworkflow_config = false +} + +// ClearTaxApp clears the "tax_app" edge to the App entity. +func (m *BillingProfileMutation) ClearTaxApp() { + m.clearedtax_app = true + m.clearedFields[billingprofile.FieldTaxAppID] = struct{}{} +} + +// TaxAppCleared reports if the "tax_app" edge to the App entity was cleared. +func (m *BillingProfileMutation) TaxAppCleared() bool { + return m.clearedtax_app +} + +// TaxAppIDs returns the "tax_app" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TaxAppID instead. It exists only for internal usage by the builders. +func (m *BillingProfileMutation) TaxAppIDs() (ids []string) { + if id := m.tax_app; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTaxApp resets all changes to the "tax_app" edge. +func (m *BillingProfileMutation) ResetTaxApp() { + m.tax_app = nil + m.clearedtax_app = false +} + +// ClearInvoicingApp clears the "invoicing_app" edge to the App entity. +func (m *BillingProfileMutation) ClearInvoicingApp() { + m.clearedinvoicing_app = true + m.clearedFields[billingprofile.FieldInvoicingAppID] = struct{}{} +} + +// InvoicingAppCleared reports if the "invoicing_app" edge to the App entity was cleared. +func (m *BillingProfileMutation) InvoicingAppCleared() bool { + return m.clearedinvoicing_app +} + +// InvoicingAppIDs returns the "invoicing_app" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// InvoicingAppID instead. It exists only for internal usage by the builders. +func (m *BillingProfileMutation) InvoicingAppIDs() (ids []string) { + if id := m.invoicing_app; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetInvoicingApp resets all changes to the "invoicing_app" edge. +func (m *BillingProfileMutation) ResetInvoicingApp() { + m.invoicing_app = nil + m.clearedinvoicing_app = false +} + +// ClearPaymentApp clears the "payment_app" edge to the App entity. +func (m *BillingProfileMutation) ClearPaymentApp() { + m.clearedpayment_app = true + m.clearedFields[billingprofile.FieldPaymentAppID] = struct{}{} +} + +// PaymentAppCleared reports if the "payment_app" edge to the App entity was cleared. +func (m *BillingProfileMutation) PaymentAppCleared() bool { + return m.clearedpayment_app +} + +// PaymentAppIDs returns the "payment_app" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// PaymentAppID instead. It exists only for internal usage by the builders. +func (m *BillingProfileMutation) PaymentAppIDs() (ids []string) { + if id := m.payment_app; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetPaymentApp resets all changes to the "payment_app" edge. +func (m *BillingProfileMutation) ResetPaymentApp() { + m.payment_app = nil + m.clearedpayment_app = false +} + +// Where appends a list predicates to the BillingProfileMutation builder. +func (m *BillingProfileMutation) Where(ps ...predicate.BillingProfile) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BillingProfileMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BillingProfileMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillingProfile, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BillingProfileMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BillingProfileMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BillingProfile). +func (m *BillingProfileMutation) 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 *BillingProfileMutation) Fields() []string { + fields := make([]string, 0, 21) + if m.namespace != nil { + fields = append(fields, billingprofile.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, billingprofile.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, billingprofile.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, billingprofile.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, billingprofile.FieldDeletedAt) + } + if m.name != nil { + fields = append(fields, billingprofile.FieldName) + } + if m.description != nil { + fields = append(fields, billingprofile.FieldDescription) + } + if m.supplier_address_country != nil { + fields = append(fields, billingprofile.FieldSupplierAddressCountry) + } + if m.supplier_address_postal_code != nil { + fields = append(fields, billingprofile.FieldSupplierAddressPostalCode) + } + if m.supplier_address_state != nil { + fields = append(fields, billingprofile.FieldSupplierAddressState) + } + if m.supplier_address_city != nil { + fields = append(fields, billingprofile.FieldSupplierAddressCity) + } + if m.supplier_address_line1 != nil { + fields = append(fields, billingprofile.FieldSupplierAddressLine1) + } + if m.supplier_address_line2 != nil { + fields = append(fields, billingprofile.FieldSupplierAddressLine2) + } + if m.supplier_address_phone_number != nil { + fields = append(fields, billingprofile.FieldSupplierAddressPhoneNumber) + } + if m.tax_app != nil { + fields = append(fields, billingprofile.FieldTaxAppID) + } + if m.invoicing_app != nil { + fields = append(fields, billingprofile.FieldInvoicingAppID) + } + if m.payment_app != nil { + fields = append(fields, billingprofile.FieldPaymentAppID) + } + if m.workflow_config != nil { + fields = append(fields, billingprofile.FieldWorkflowConfigID) + } + if m._default != nil { + fields = append(fields, billingprofile.FieldDefault) + } + if m.supplier_name != nil { + fields = append(fields, billingprofile.FieldSupplierName) + } + if m.supplier_tax_code != nil { + fields = append(fields, billingprofile.FieldSupplierTaxCode) + } + 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 *BillingProfileMutation) Field(name string) (ent.Value, bool) { + switch name { + case billingprofile.FieldNamespace: + return m.Namespace() + case billingprofile.FieldMetadata: + return m.Metadata() + case billingprofile.FieldCreatedAt: + return m.CreatedAt() + case billingprofile.FieldUpdatedAt: + return m.UpdatedAt() + case billingprofile.FieldDeletedAt: + return m.DeletedAt() + case billingprofile.FieldName: + return m.Name() + case billingprofile.FieldDescription: + return m.Description() + case billingprofile.FieldSupplierAddressCountry: + return m.SupplierAddressCountry() + case billingprofile.FieldSupplierAddressPostalCode: + return m.SupplierAddressPostalCode() + case billingprofile.FieldSupplierAddressState: + return m.SupplierAddressState() + case billingprofile.FieldSupplierAddressCity: + return m.SupplierAddressCity() + case billingprofile.FieldSupplierAddressLine1: + return m.SupplierAddressLine1() + case billingprofile.FieldSupplierAddressLine2: + return m.SupplierAddressLine2() + case billingprofile.FieldSupplierAddressPhoneNumber: + return m.SupplierAddressPhoneNumber() + case billingprofile.FieldTaxAppID: + return m.TaxAppID() + case billingprofile.FieldInvoicingAppID: + return m.InvoicingAppID() + case billingprofile.FieldPaymentAppID: + return m.PaymentAppID() + case billingprofile.FieldWorkflowConfigID: + return m.WorkflowConfigID() + case billingprofile.FieldDefault: + return m.Default() + case billingprofile.FieldSupplierName: + return m.SupplierName() + case billingprofile.FieldSupplierTaxCode: + return m.SupplierTaxCode() + } + 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 *BillingProfileMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case billingprofile.FieldNamespace: + return m.OldNamespace(ctx) + case billingprofile.FieldMetadata: + return m.OldMetadata(ctx) + case billingprofile.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case billingprofile.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case billingprofile.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case billingprofile.FieldName: + return m.OldName(ctx) + case billingprofile.FieldDescription: + return m.OldDescription(ctx) + case billingprofile.FieldSupplierAddressCountry: + return m.OldSupplierAddressCountry(ctx) + case billingprofile.FieldSupplierAddressPostalCode: + return m.OldSupplierAddressPostalCode(ctx) + case billingprofile.FieldSupplierAddressState: + return m.OldSupplierAddressState(ctx) + case billingprofile.FieldSupplierAddressCity: + return m.OldSupplierAddressCity(ctx) + case billingprofile.FieldSupplierAddressLine1: + return m.OldSupplierAddressLine1(ctx) + case billingprofile.FieldSupplierAddressLine2: + return m.OldSupplierAddressLine2(ctx) + case billingprofile.FieldSupplierAddressPhoneNumber: + return m.OldSupplierAddressPhoneNumber(ctx) + case billingprofile.FieldTaxAppID: + return m.OldTaxAppID(ctx) + case billingprofile.FieldInvoicingAppID: + return m.OldInvoicingAppID(ctx) + case billingprofile.FieldPaymentAppID: + return m.OldPaymentAppID(ctx) + case billingprofile.FieldWorkflowConfigID: + return m.OldWorkflowConfigID(ctx) + case billingprofile.FieldDefault: + return m.OldDefault(ctx) + case billingprofile.FieldSupplierName: + return m.OldSupplierName(ctx) + case billingprofile.FieldSupplierTaxCode: + return m.OldSupplierTaxCode(ctx) + } + return nil, fmt.Errorf("unknown BillingProfile 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 *BillingProfileMutation) SetField(name string, value ent.Value) error { + switch name { + case billingprofile.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case billingprofile.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case billingprofile.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 billingprofile.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 billingprofile.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 billingprofile.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case billingprofile.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case billingprofile.FieldSupplierAddressCountry: + v, ok := value.(models.CountryCode) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSupplierAddressCountry(v) + return nil + case billingprofile.FieldSupplierAddressPostalCode: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSupplierAddressPostalCode(v) + return nil + case billingprofile.FieldSupplierAddressState: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSupplierAddressState(v) + return nil + case billingprofile.FieldSupplierAddressCity: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSupplierAddressCity(v) + return nil + case billingprofile.FieldSupplierAddressLine1: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSupplierAddressLine1(v) + return nil + case billingprofile.FieldSupplierAddressLine2: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSupplierAddressLine2(v) + return nil + case billingprofile.FieldSupplierAddressPhoneNumber: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSupplierAddressPhoneNumber(v) + return nil + case billingprofile.FieldTaxAppID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxAppID(v) + return nil + case billingprofile.FieldInvoicingAppID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoicingAppID(v) + return nil + case billingprofile.FieldPaymentAppID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPaymentAppID(v) + return nil + case billingprofile.FieldWorkflowConfigID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetWorkflowConfigID(v) + return nil + case billingprofile.FieldDefault: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDefault(v) + return nil + case billingprofile.FieldSupplierName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSupplierName(v) + return nil + case billingprofile.FieldSupplierTaxCode: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSupplierTaxCode(v) + return nil + } + return fmt.Errorf("unknown BillingProfile field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BillingProfileMutation) 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 *BillingProfileMutation) 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 *BillingProfileMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown BillingProfile numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BillingProfileMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(billingprofile.FieldMetadata) { + fields = append(fields, billingprofile.FieldMetadata) + } + if m.FieldCleared(billingprofile.FieldDeletedAt) { + fields = append(fields, billingprofile.FieldDeletedAt) + } + if m.FieldCleared(billingprofile.FieldDescription) { + fields = append(fields, billingprofile.FieldDescription) + } + if m.FieldCleared(billingprofile.FieldSupplierAddressCountry) { + fields = append(fields, billingprofile.FieldSupplierAddressCountry) + } + if m.FieldCleared(billingprofile.FieldSupplierAddressPostalCode) { + fields = append(fields, billingprofile.FieldSupplierAddressPostalCode) + } + if m.FieldCleared(billingprofile.FieldSupplierAddressState) { + fields = append(fields, billingprofile.FieldSupplierAddressState) + } + if m.FieldCleared(billingprofile.FieldSupplierAddressCity) { + fields = append(fields, billingprofile.FieldSupplierAddressCity) + } + if m.FieldCleared(billingprofile.FieldSupplierAddressLine1) { + fields = append(fields, billingprofile.FieldSupplierAddressLine1) + } + if m.FieldCleared(billingprofile.FieldSupplierAddressLine2) { + fields = append(fields, billingprofile.FieldSupplierAddressLine2) + } + if m.FieldCleared(billingprofile.FieldSupplierAddressPhoneNumber) { + fields = append(fields, billingprofile.FieldSupplierAddressPhoneNumber) + } + if m.FieldCleared(billingprofile.FieldSupplierTaxCode) { + fields = append(fields, billingprofile.FieldSupplierTaxCode) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BillingProfileMutation) 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 *BillingProfileMutation) ClearField(name string) error { + switch name { + case billingprofile.FieldMetadata: + m.ClearMetadata() + return nil + case billingprofile.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case billingprofile.FieldDescription: + m.ClearDescription() + return nil + case billingprofile.FieldSupplierAddressCountry: + m.ClearSupplierAddressCountry() + return nil + case billingprofile.FieldSupplierAddressPostalCode: + m.ClearSupplierAddressPostalCode() + return nil + case billingprofile.FieldSupplierAddressState: + m.ClearSupplierAddressState() + return nil + case billingprofile.FieldSupplierAddressCity: + m.ClearSupplierAddressCity() + return nil + case billingprofile.FieldSupplierAddressLine1: + m.ClearSupplierAddressLine1() + return nil + case billingprofile.FieldSupplierAddressLine2: + m.ClearSupplierAddressLine2() + return nil + case billingprofile.FieldSupplierAddressPhoneNumber: + m.ClearSupplierAddressPhoneNumber() + return nil + case billingprofile.FieldSupplierTaxCode: + m.ClearSupplierTaxCode() + return nil + } + return fmt.Errorf("unknown BillingProfile 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 *BillingProfileMutation) ResetField(name string) error { + switch name { + case billingprofile.FieldNamespace: + m.ResetNamespace() + return nil + case billingprofile.FieldMetadata: + m.ResetMetadata() + return nil + case billingprofile.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case billingprofile.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case billingprofile.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case billingprofile.FieldName: + m.ResetName() + return nil + case billingprofile.FieldDescription: + m.ResetDescription() + return nil + case billingprofile.FieldSupplierAddressCountry: + m.ResetSupplierAddressCountry() + return nil + case billingprofile.FieldSupplierAddressPostalCode: + m.ResetSupplierAddressPostalCode() + return nil + case billingprofile.FieldSupplierAddressState: + m.ResetSupplierAddressState() + return nil + case billingprofile.FieldSupplierAddressCity: + m.ResetSupplierAddressCity() + return nil + case billingprofile.FieldSupplierAddressLine1: + m.ResetSupplierAddressLine1() + return nil + case billingprofile.FieldSupplierAddressLine2: + m.ResetSupplierAddressLine2() + return nil + case billingprofile.FieldSupplierAddressPhoneNumber: + m.ResetSupplierAddressPhoneNumber() + return nil + case billingprofile.FieldTaxAppID: + m.ResetTaxAppID() + return nil + case billingprofile.FieldInvoicingAppID: + m.ResetInvoicingAppID() + return nil + case billingprofile.FieldPaymentAppID: + m.ResetPaymentAppID() + return nil + case billingprofile.FieldWorkflowConfigID: + m.ResetWorkflowConfigID() + return nil + case billingprofile.FieldDefault: + m.ResetDefault() + return nil + case billingprofile.FieldSupplierName: + m.ResetSupplierName() + return nil + case billingprofile.FieldSupplierTaxCode: + m.ResetSupplierTaxCode() + return nil + } + return fmt.Errorf("unknown BillingProfile field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BillingProfileMutation) AddedEdges() []string { + edges := make([]string, 0, 6) + if m.billing_invoices != nil { + edges = append(edges, billingprofile.EdgeBillingInvoices) + } + if m.billing_customer_override != nil { + edges = append(edges, billingprofile.EdgeBillingCustomerOverride) + } + if m.workflow_config != nil { + edges = append(edges, billingprofile.EdgeWorkflowConfig) + } + if m.tax_app != nil { + edges = append(edges, billingprofile.EdgeTaxApp) + } + if m.invoicing_app != nil { + edges = append(edges, billingprofile.EdgeInvoicingApp) + } + if m.payment_app != nil { + edges = append(edges, billingprofile.EdgePaymentApp) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BillingProfileMutation) AddedIDs(name string) []ent.Value { + switch name { + case billingprofile.EdgeBillingInvoices: + ids := make([]ent.Value, 0, len(m.billing_invoices)) + for id := range m.billing_invoices { + ids = append(ids, id) + } + return ids + case billingprofile.EdgeBillingCustomerOverride: + ids := make([]ent.Value, 0, len(m.billing_customer_override)) + for id := range m.billing_customer_override { + ids = append(ids, id) + } + return ids + case billingprofile.EdgeWorkflowConfig: + if id := m.workflow_config; id != nil { + return []ent.Value{*id} + } + case billingprofile.EdgeTaxApp: + if id := m.tax_app; id != nil { + return []ent.Value{*id} + } + case billingprofile.EdgeInvoicingApp: + if id := m.invoicing_app; id != nil { + return []ent.Value{*id} + } + case billingprofile.EdgePaymentApp: + if id := m.payment_app; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BillingProfileMutation) RemovedEdges() []string { + edges := make([]string, 0, 6) + if m.removedbilling_invoices != nil { + edges = append(edges, billingprofile.EdgeBillingInvoices) + } + if m.removedbilling_customer_override != nil { + edges = append(edges, billingprofile.EdgeBillingCustomerOverride) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *BillingProfileMutation) RemovedIDs(name string) []ent.Value { + switch name { + case billingprofile.EdgeBillingInvoices: + ids := make([]ent.Value, 0, len(m.removedbilling_invoices)) + for id := range m.removedbilling_invoices { + ids = append(ids, id) + } + return ids + case billingprofile.EdgeBillingCustomerOverride: + ids := make([]ent.Value, 0, len(m.removedbilling_customer_override)) + for id := range m.removedbilling_customer_override { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BillingProfileMutation) ClearedEdges() []string { + edges := make([]string, 0, 6) + if m.clearedbilling_invoices { + edges = append(edges, billingprofile.EdgeBillingInvoices) + } + if m.clearedbilling_customer_override { + edges = append(edges, billingprofile.EdgeBillingCustomerOverride) + } + if m.clearedworkflow_config { + edges = append(edges, billingprofile.EdgeWorkflowConfig) + } + if m.clearedtax_app { + edges = append(edges, billingprofile.EdgeTaxApp) + } + if m.clearedinvoicing_app { + edges = append(edges, billingprofile.EdgeInvoicingApp) + } + if m.clearedpayment_app { + edges = append(edges, billingprofile.EdgePaymentApp) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BillingProfileMutation) EdgeCleared(name string) bool { + switch name { + case billingprofile.EdgeBillingInvoices: + return m.clearedbilling_invoices + case billingprofile.EdgeBillingCustomerOverride: + return m.clearedbilling_customer_override + case billingprofile.EdgeWorkflowConfig: + return m.clearedworkflow_config + case billingprofile.EdgeTaxApp: + return m.clearedtax_app + case billingprofile.EdgeInvoicingApp: + return m.clearedinvoicing_app + case billingprofile.EdgePaymentApp: + return m.clearedpayment_app + } + 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 *BillingProfileMutation) ClearEdge(name string) error { + switch name { + case billingprofile.EdgeWorkflowConfig: + m.ClearWorkflowConfig() + return nil + case billingprofile.EdgeTaxApp: + m.ClearTaxApp() + return nil + case billingprofile.EdgeInvoicingApp: + m.ClearInvoicingApp() + return nil + case billingprofile.EdgePaymentApp: + m.ClearPaymentApp() + return nil + } + return fmt.Errorf("unknown BillingProfile 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 *BillingProfileMutation) ResetEdge(name string) error { + switch name { + case billingprofile.EdgeBillingInvoices: + m.ResetBillingInvoices() + return nil + case billingprofile.EdgeBillingCustomerOverride: + m.ResetBillingCustomerOverride() + return nil + case billingprofile.EdgeWorkflowConfig: + m.ResetWorkflowConfig() + return nil + case billingprofile.EdgeTaxApp: + m.ResetTaxApp() + return nil + case billingprofile.EdgeInvoicingApp: + m.ResetInvoicingApp() + return nil + case billingprofile.EdgePaymentApp: + m.ResetPaymentApp() + return nil + } + return fmt.Errorf("unknown BillingProfile edge %s", name) +} + +// BillingSequenceNumbersMutation represents an operation that mutates the BillingSequenceNumbers nodes in the graph. +type BillingSequenceNumbersMutation struct { + config + op Op + typ string + id *int + namespace *string + scope *string + last *alpacadecimal.Decimal + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*BillingSequenceNumbers, error) + predicates []predicate.BillingSequenceNumbers +} + +var _ ent.Mutation = (*BillingSequenceNumbersMutation)(nil) + +// billingsequencenumbersOption allows management of the mutation configuration using functional options. +type billingsequencenumbersOption func(*BillingSequenceNumbersMutation) + +// newBillingSequenceNumbersMutation creates new mutation for the BillingSequenceNumbers entity. +func newBillingSequenceNumbersMutation(c config, op Op, opts ...billingsequencenumbersOption) *BillingSequenceNumbersMutation { + m := &BillingSequenceNumbersMutation{ + config: c, + op: op, + typ: TypeBillingSequenceNumbers, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBillingSequenceNumbersID sets the ID field of the mutation. +func withBillingSequenceNumbersID(id int) billingsequencenumbersOption { + return func(m *BillingSequenceNumbersMutation) { + var ( + err error + once sync.Once + value *BillingSequenceNumbers + ) + m.oldValue = func(ctx context.Context) (*BillingSequenceNumbers, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().BillingSequenceNumbers.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBillingSequenceNumbers sets the old BillingSequenceNumbers of the mutation. +func withBillingSequenceNumbers(node *BillingSequenceNumbers) billingsequencenumbersOption { + return func(m *BillingSequenceNumbersMutation) { + m.oldValue = func(context.Context) (*BillingSequenceNumbers, 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 BillingSequenceNumbersMutation) 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 BillingSequenceNumbersMutation) 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 +} + +// 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 *BillingSequenceNumbersMutation) ID() (id int, 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 *BillingSequenceNumbersMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().BillingSequenceNumbers.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 *BillingSequenceNumbersMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *BillingSequenceNumbersMutation) 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 BillingSequenceNumbers entity. +// If the BillingSequenceNumbers 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 *BillingSequenceNumbersMutation) 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 *BillingSequenceNumbersMutation) ResetNamespace() { + m.namespace = nil +} + +// SetScope sets the "scope" field. +func (m *BillingSequenceNumbersMutation) SetScope(s string) { + m.scope = &s +} + +// Scope returns the value of the "scope" field in the mutation. +func (m *BillingSequenceNumbersMutation) Scope() (r string, exists bool) { + v := m.scope + if v == nil { + return + } + return *v, true +} + +// OldScope returns the old "scope" field's value of the BillingSequenceNumbers entity. +// If the BillingSequenceNumbers 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 *BillingSequenceNumbersMutation) OldScope(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldScope is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldScope requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldScope: %w", err) + } + return oldValue.Scope, nil +} + +// ResetScope resets all changes to the "scope" field. +func (m *BillingSequenceNumbersMutation) ResetScope() { + m.scope = nil +} + +// SetLast sets the "last" field. +func (m *BillingSequenceNumbersMutation) SetLast(a alpacadecimal.Decimal) { + m.last = &a +} + +// Last returns the value of the "last" field in the mutation. +func (m *BillingSequenceNumbersMutation) Last() (r alpacadecimal.Decimal, exists bool) { + v := m.last + if v == nil { + return + } + return *v, true +} + +// OldLast returns the old "last" field's value of the BillingSequenceNumbers entity. +// If the BillingSequenceNumbers 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 *BillingSequenceNumbersMutation) OldLast(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLast is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLast requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLast: %w", err) + } + return oldValue.Last, nil +} + +// ResetLast resets all changes to the "last" field. +func (m *BillingSequenceNumbersMutation) ResetLast() { + m.last = nil +} + +// Where appends a list predicates to the BillingSequenceNumbersMutation builder. +func (m *BillingSequenceNumbersMutation) Where(ps ...predicate.BillingSequenceNumbers) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BillingSequenceNumbersMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BillingSequenceNumbersMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillingSequenceNumbers, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BillingSequenceNumbersMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BillingSequenceNumbersMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BillingSequenceNumbers). +func (m *BillingSequenceNumbersMutation) 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 *BillingSequenceNumbersMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.namespace != nil { + fields = append(fields, billingsequencenumbers.FieldNamespace) + } + if m.scope != nil { + fields = append(fields, billingsequencenumbers.FieldScope) + } + if m.last != nil { + fields = append(fields, billingsequencenumbers.FieldLast) + } + 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 *BillingSequenceNumbersMutation) Field(name string) (ent.Value, bool) { + switch name { + case billingsequencenumbers.FieldNamespace: + return m.Namespace() + case billingsequencenumbers.FieldScope: + return m.Scope() + case billingsequencenumbers.FieldLast: + return m.Last() + } + 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 *BillingSequenceNumbersMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case billingsequencenumbers.FieldNamespace: + return m.OldNamespace(ctx) + case billingsequencenumbers.FieldScope: + return m.OldScope(ctx) + case billingsequencenumbers.FieldLast: + return m.OldLast(ctx) + } + return nil, fmt.Errorf("unknown BillingSequenceNumbers 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 *BillingSequenceNumbersMutation) SetField(name string, value ent.Value) error { + switch name { + case billingsequencenumbers.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case billingsequencenumbers.FieldScope: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetScope(v) + return nil + case billingsequencenumbers.FieldLast: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLast(v) + return nil + } + return fmt.Errorf("unknown BillingSequenceNumbers field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BillingSequenceNumbersMutation) 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 *BillingSequenceNumbersMutation) 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 *BillingSequenceNumbersMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown BillingSequenceNumbers numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BillingSequenceNumbersMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BillingSequenceNumbersMutation) 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 *BillingSequenceNumbersMutation) ClearField(name string) error { + return fmt.Errorf("unknown BillingSequenceNumbers 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 *BillingSequenceNumbersMutation) ResetField(name string) error { + switch name { + case billingsequencenumbers.FieldNamespace: + m.ResetNamespace() + return nil + case billingsequencenumbers.FieldScope: + m.ResetScope() + return nil + case billingsequencenumbers.FieldLast: + m.ResetLast() + return nil + } + return fmt.Errorf("unknown BillingSequenceNumbers field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BillingSequenceNumbersMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BillingSequenceNumbersMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BillingSequenceNumbersMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *BillingSequenceNumbersMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BillingSequenceNumbersMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BillingSequenceNumbersMutation) EdgeCleared(name string) bool { + 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 *BillingSequenceNumbersMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown BillingSequenceNumbers 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 *BillingSequenceNumbersMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown BillingSequenceNumbers edge %s", name) +} + +// BillingStandardInvoiceDetailedLineMutation represents an operation that mutates the BillingStandardInvoiceDetailedLine nodes in the graph. +type BillingStandardInvoiceDetailedLineMutation struct { + config + op Op + typ string + id *string + currency *currencyx.Code + service_period_start *time.Time + service_period_end *time.Time + quantity *alpacadecimal.Decimal + invoicing_app_external_id *string + child_unique_reference_id *string + per_unit_amount *alpacadecimal.Decimal + category *stddetailedline.Category + payment_term *productcatalog.PaymentTermType + index *int + addindex *int + credits_applied **creditsapplied.CreditsApplied + annotations *models.Annotations + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + name *string + description *string + 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{} + billing_invoice *string + clearedbilling_invoice bool + billing_invoice_line *string + clearedbilling_invoice_line bool + amount_discounts map[string]struct{} + removedamount_discounts map[string]struct{} + clearedamount_discounts bool + done bool + oldValue func(context.Context) (*BillingStandardInvoiceDetailedLine, error) + predicates []predicate.BillingStandardInvoiceDetailedLine +} + +var _ ent.Mutation = (*BillingStandardInvoiceDetailedLineMutation)(nil) + +// billingstandardinvoicedetailedlineOption allows management of the mutation configuration using functional options. +type billingstandardinvoicedetailedlineOption func(*BillingStandardInvoiceDetailedLineMutation) + +// newBillingStandardInvoiceDetailedLineMutation creates new mutation for the BillingStandardInvoiceDetailedLine entity. +func newBillingStandardInvoiceDetailedLineMutation(c config, op Op, opts ...billingstandardinvoicedetailedlineOption) *BillingStandardInvoiceDetailedLineMutation { + m := &BillingStandardInvoiceDetailedLineMutation{ + config: c, + op: op, + typ: TypeBillingStandardInvoiceDetailedLine, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBillingStandardInvoiceDetailedLineID sets the ID field of the mutation. +func withBillingStandardInvoiceDetailedLineID(id string) billingstandardinvoicedetailedlineOption { + return func(m *BillingStandardInvoiceDetailedLineMutation) { + var ( + err error + once sync.Once + value *BillingStandardInvoiceDetailedLine + ) + m.oldValue = func(ctx context.Context) (*BillingStandardInvoiceDetailedLine, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().BillingStandardInvoiceDetailedLine.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBillingStandardInvoiceDetailedLine sets the old BillingStandardInvoiceDetailedLine of the mutation. +func withBillingStandardInvoiceDetailedLine(node *BillingStandardInvoiceDetailedLine) billingstandardinvoicedetailedlineOption { + return func(m *BillingStandardInvoiceDetailedLineMutation) { + m.oldValue = func(context.Context) (*BillingStandardInvoiceDetailedLine, 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 BillingStandardInvoiceDetailedLineMutation) 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 BillingStandardInvoiceDetailedLineMutation) 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 BillingStandardInvoiceDetailedLine entities. +func (m *BillingStandardInvoiceDetailedLineMutation) 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 *BillingStandardInvoiceDetailedLineMutation) 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 *BillingStandardInvoiceDetailedLineMutation) 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().BillingStandardInvoiceDetailedLine.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetCurrency sets the "currency" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetCurrency(c currencyx.Code) { + m.currency = &c +} + +// Currency returns the value of the "currency" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) Currency() (r currencyx.Code, exists bool) { + v := m.currency + if v == nil { + return + } + return *v, true +} + +// OldCurrency returns the old "currency" field's value of the BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) OldCurrency(ctx context.Context) (v currencyx.Code, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrency is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrency requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrency: %w", err) + } + return oldValue.Currency, nil +} + +// ResetCurrency resets all changes to the "currency" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetCurrency() { + m.currency = nil +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetServicePeriodStart(t time.Time) { + m.service_period_start = &t +} + +// ServicePeriodStart returns the value of the "service_period_start" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) ServicePeriodStart() (r time.Time, exists bool) { + v := m.service_period_start + if v == nil { + return + } + return *v, true +} + +// OldServicePeriodStart returns the old "service_period_start" field's value of the BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) OldServicePeriodStart(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldServicePeriodStart is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldServicePeriodStart requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldServicePeriodStart: %w", err) + } + return oldValue.ServicePeriodStart, nil +} + +// ResetServicePeriodStart resets all changes to the "service_period_start" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetServicePeriodStart() { + m.service_period_start = nil +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetServicePeriodEnd(t time.Time) { + m.service_period_end = &t +} + +// ServicePeriodEnd returns the value of the "service_period_end" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) ServicePeriodEnd() (r time.Time, exists bool) { + v := m.service_period_end + if v == nil { + return + } + return *v, true +} + +// OldServicePeriodEnd returns the old "service_period_end" field's value of the BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) OldServicePeriodEnd(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldServicePeriodEnd is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldServicePeriodEnd requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldServicePeriodEnd: %w", err) + } + return oldValue.ServicePeriodEnd, nil +} + +// ResetServicePeriodEnd resets all changes to the "service_period_end" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetServicePeriodEnd() { + m.service_period_end = nil +} + +// SetQuantity sets the "quantity" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetQuantity(a alpacadecimal.Decimal) { + m.quantity = &a +} + +// Quantity returns the value of the "quantity" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) Quantity() (r alpacadecimal.Decimal, exists bool) { + v := m.quantity + if v == nil { + return + } + return *v, true +} + +// OldQuantity returns the old "quantity" field's value of the BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) OldQuantity(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldQuantity is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldQuantity requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldQuantity: %w", err) + } + return oldValue.Quantity, nil +} + +// ResetQuantity resets all changes to the "quantity" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetQuantity() { + m.quantity = nil +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetInvoicingAppExternalID(s string) { + m.invoicing_app_external_id = &s +} + +// InvoicingAppExternalID returns the value of the "invoicing_app_external_id" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) InvoicingAppExternalID() (r string, exists bool) { + v := m.invoicing_app_external_id + if v == nil { + return + } + return *v, true +} + +// OldInvoicingAppExternalID returns the old "invoicing_app_external_id" field's value of the BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) OldInvoicingAppExternalID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoicingAppExternalID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoicingAppExternalID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoicingAppExternalID: %w", err) + } + return oldValue.InvoicingAppExternalID, nil +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ClearInvoicingAppExternalID() { + m.invoicing_app_external_id = nil + m.clearedFields[billingstandardinvoicedetailedline.FieldInvoicingAppExternalID] = struct{}{} +} + +// InvoicingAppExternalIDCleared returns if the "invoicing_app_external_id" field was cleared in this mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) InvoicingAppExternalIDCleared() bool { + _, ok := m.clearedFields[billingstandardinvoicedetailedline.FieldInvoicingAppExternalID] + return ok +} + +// ResetInvoicingAppExternalID resets all changes to the "invoicing_app_external_id" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetInvoicingAppExternalID() { + m.invoicing_app_external_id = nil + delete(m.clearedFields, billingstandardinvoicedetailedline.FieldInvoicingAppExternalID) +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetChildUniqueReferenceID(s string) { + m.child_unique_reference_id = &s +} + +// ChildUniqueReferenceID returns the value of the "child_unique_reference_id" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) ChildUniqueReferenceID() (r string, exists bool) { + v := m.child_unique_reference_id + if v == nil { + return + } + return *v, true +} + +// OldChildUniqueReferenceID returns the old "child_unique_reference_id" field's value of the BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) OldChildUniqueReferenceID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldChildUniqueReferenceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldChildUniqueReferenceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldChildUniqueReferenceID: %w", err) + } + return oldValue.ChildUniqueReferenceID, nil +} + +// ResetChildUniqueReferenceID resets all changes to the "child_unique_reference_id" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetChildUniqueReferenceID() { + m.child_unique_reference_id = nil +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetPerUnitAmount(a alpacadecimal.Decimal) { + m.per_unit_amount = &a +} + +// PerUnitAmount returns the value of the "per_unit_amount" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) PerUnitAmount() (r alpacadecimal.Decimal, exists bool) { + v := m.per_unit_amount + if v == nil { + return + } + return *v, true +} + +// OldPerUnitAmount returns the old "per_unit_amount" field's value of the BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) OldPerUnitAmount(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPerUnitAmount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPerUnitAmount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPerUnitAmount: %w", err) + } + return oldValue.PerUnitAmount, nil +} + +// ResetPerUnitAmount resets all changes to the "per_unit_amount" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetPerUnitAmount() { + m.per_unit_amount = nil +} + +// SetCategory sets the "category" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetCategory(s stddetailedline.Category) { + m.category = &s +} + +// Category returns the value of the "category" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) Category() (r stddetailedline.Category, exists bool) { + v := m.category + if v == nil { + return + } + return *v, true +} + +// OldCategory returns the old "category" field's value of the BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) OldCategory(ctx context.Context) (v stddetailedline.Category, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCategory is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCategory requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCategory: %w", err) + } + return oldValue.Category, nil +} + +// ResetCategory resets all changes to the "category" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetCategory() { + m.category = nil +} + +// SetPaymentTerm sets the "payment_term" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetPaymentTerm(ptt productcatalog.PaymentTermType) { + m.payment_term = &ptt +} + +// PaymentTerm returns the value of the "payment_term" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) PaymentTerm() (r productcatalog.PaymentTermType, exists bool) { + v := m.payment_term + if v == nil { + return + } + return *v, true +} + +// OldPaymentTerm returns the old "payment_term" field's value of the BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) OldPaymentTerm(ctx context.Context) (v productcatalog.PaymentTermType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPaymentTerm is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPaymentTerm requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPaymentTerm: %w", err) + } + return oldValue.PaymentTerm, nil +} + +// ResetPaymentTerm resets all changes to the "payment_term" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetPaymentTerm() { + m.payment_term = nil +} + +// SetIndex sets the "index" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetIndex(i int) { + m.index = &i + m.addindex = nil +} + +// Index returns the value of the "index" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) Index() (r int, exists bool) { + v := m.index + if v == nil { + return + } + return *v, true +} + +// OldIndex returns the old "index" field's value of the BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) OldIndex(ctx context.Context) (v *int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIndex is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIndex requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIndex: %w", err) + } + return oldValue.Index, nil +} + +// AddIndex adds i to the "index" field. +func (m *BillingStandardInvoiceDetailedLineMutation) AddIndex(i int) { + if m.addindex != nil { + *m.addindex += i + } else { + m.addindex = &i + } +} + +// AddedIndex returns the value that was added to the "index" field in this mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) AddedIndex() (r int, exists bool) { + v := m.addindex + if v == nil { + return + } + return *v, true +} + +// ClearIndex clears the value of the "index" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ClearIndex() { + m.index = nil + m.addindex = nil + m.clearedFields[billingstandardinvoicedetailedline.FieldIndex] = struct{}{} +} + +// IndexCleared returns if the "index" field was cleared in this mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) IndexCleared() bool { + _, ok := m.clearedFields[billingstandardinvoicedetailedline.FieldIndex] + return ok +} + +// ResetIndex resets all changes to the "index" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetIndex() { + m.index = nil + m.addindex = nil + delete(m.clearedFields, billingstandardinvoicedetailedline.FieldIndex) +} + +// SetCreditsApplied sets the "credits_applied" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetCreditsApplied(ca *creditsapplied.CreditsApplied) { + m.credits_applied = &ca +} + +// CreditsApplied returns the value of the "credits_applied" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) CreditsApplied() (r *creditsapplied.CreditsApplied, exists bool) { + v := m.credits_applied + if v == nil { + return + } + return *v, true +} + +// OldCreditsApplied returns the old "credits_applied" field's value of the BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) OldCreditsApplied(ctx context.Context) (v *creditsapplied.CreditsApplied, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreditsApplied is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreditsApplied requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreditsApplied: %w", err) + } + return oldValue.CreditsApplied, nil +} + +// ClearCreditsApplied clears the value of the "credits_applied" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ClearCreditsApplied() { + m.credits_applied = nil + m.clearedFields[billingstandardinvoicedetailedline.FieldCreditsApplied] = struct{}{} +} + +// CreditsAppliedCleared returns if the "credits_applied" field was cleared in this mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) CreditsAppliedCleared() bool { + _, ok := m.clearedFields[billingstandardinvoicedetailedline.FieldCreditsApplied] + return ok +} + +// ResetCreditsApplied resets all changes to the "credits_applied" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetCreditsApplied() { + m.credits_applied = nil + delete(m.clearedFields, billingstandardinvoicedetailedline.FieldCreditsApplied) +} + +// SetAnnotations sets the "annotations" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) 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 BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) 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 *BillingStandardInvoiceDetailedLineMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[billingstandardinvoicedetailedline.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[billingstandardinvoicedetailedline.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, billingstandardinvoicedetailedline.FieldAnnotations) +} + +// SetNamespace sets the "namespace" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) 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 BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) 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 *BillingStandardInvoiceDetailedLineMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[billingstandardinvoicedetailedline.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) MetadataCleared() bool { + _, ok := m.clearedFields[billingstandardinvoicedetailedline.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, billingstandardinvoicedetailedline.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) 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 BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) 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 *BillingStandardInvoiceDetailedLineMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) 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 BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) 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 *BillingStandardInvoiceDetailedLineMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) 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 BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) 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 *BillingStandardInvoiceDetailedLineMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[billingstandardinvoicedetailedline.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[billingstandardinvoicedetailedline.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, billingstandardinvoicedetailedline.FieldDeletedAt) +} + +// SetName sets the "name" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ClearDescription() { + m.description = nil + m.clearedFields[billingstandardinvoicedetailedline.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[billingstandardinvoicedetailedline.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, billingstandardinvoicedetailedline.FieldDescription) +} + +// SetAmount sets the "amount" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) 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 BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) 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 *BillingStandardInvoiceDetailedLineMutation) ResetAmount() { + m.amount = nil +} + +// SetTaxesTotal sets the "taxes_total" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetTaxesTotal(a alpacadecimal.Decimal) { + m.taxes_total = &a +} + +// TaxesTotal returns the value of the "taxes_total" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) 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 BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) 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 *BillingStandardInvoiceDetailedLineMutation) ResetTaxesTotal() { + m.taxes_total = nil +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetTaxesInclusiveTotal(a alpacadecimal.Decimal) { + m.taxes_inclusive_total = &a +} + +// TaxesInclusiveTotal returns the value of the "taxes_inclusive_total" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) 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 BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) 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 *BillingStandardInvoiceDetailedLineMutation) ResetTaxesInclusiveTotal() { + m.taxes_inclusive_total = nil +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetTaxesExclusiveTotal(a alpacadecimal.Decimal) { + m.taxes_exclusive_total = &a +} + +// TaxesExclusiveTotal returns the value of the "taxes_exclusive_total" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) 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 BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) 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 *BillingStandardInvoiceDetailedLineMutation) ResetTaxesExclusiveTotal() { + m.taxes_exclusive_total = nil +} + +// SetChargesTotal sets the "charges_total" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetChargesTotal(a alpacadecimal.Decimal) { + m.charges_total = &a +} + +// ChargesTotal returns the value of the "charges_total" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) 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 BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) 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 *BillingStandardInvoiceDetailedLineMutation) ResetChargesTotal() { + m.charges_total = nil +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetDiscountsTotal(a alpacadecimal.Decimal) { + m.discounts_total = &a +} + +// DiscountsTotal returns the value of the "discounts_total" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) 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 BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) 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 *BillingStandardInvoiceDetailedLineMutation) ResetDiscountsTotal() { + m.discounts_total = nil +} + +// SetCreditsTotal sets the "credits_total" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetCreditsTotal(a alpacadecimal.Decimal) { + m.credits_total = &a +} + +// CreditsTotal returns the value of the "credits_total" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) 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 BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) 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 *BillingStandardInvoiceDetailedLineMutation) ResetCreditsTotal() { + m.credits_total = nil +} + +// SetTotal sets the "total" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetTotal(a alpacadecimal.Decimal) { + m.total = &a +} + +// Total returns the value of the "total" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) 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 BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) 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 *BillingStandardInvoiceDetailedLineMutation) ResetTotal() { + m.total = nil +} + +// SetInvoiceID sets the "invoice_id" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetInvoiceID(s string) { + m.billing_invoice = &s +} + +// InvoiceID returns the value of the "invoice_id" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) InvoiceID() (r string, exists bool) { + v := m.billing_invoice + if v == nil { + return + } + return *v, true +} + +// OldInvoiceID returns the old "invoice_id" field's value of the BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) OldInvoiceID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceID: %w", err) + } + return oldValue.InvoiceID, nil +} + +// ResetInvoiceID resets all changes to the "invoice_id" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetInvoiceID() { + m.billing_invoice = nil +} + +// SetParentLineID sets the "parent_line_id" field. +func (m *BillingStandardInvoiceDetailedLineMutation) SetParentLineID(s string) { + m.billing_invoice_line = &s +} + +// ParentLineID returns the value of the "parent_line_id" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) ParentLineID() (r string, exists bool) { + v := m.billing_invoice_line + if v == nil { + return + } + return *v, true +} + +// OldParentLineID returns the old "parent_line_id" field's value of the BillingStandardInvoiceDetailedLine entity. +// If the BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) OldParentLineID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldParentLineID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldParentLineID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldParentLineID: %w", err) + } + return oldValue.ParentLineID, nil +} + +// ResetParentLineID resets all changes to the "parent_line_id" field. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetParentLineID() { + m.billing_invoice_line = nil +} + +// SetBillingInvoiceID sets the "billing_invoice" edge to the BillingInvoice entity by id. +func (m *BillingStandardInvoiceDetailedLineMutation) SetBillingInvoiceID(id string) { + m.billing_invoice = &id +} + +// ClearBillingInvoice clears the "billing_invoice" edge to the BillingInvoice entity. +func (m *BillingStandardInvoiceDetailedLineMutation) ClearBillingInvoice() { + m.clearedbilling_invoice = true + m.clearedFields[billingstandardinvoicedetailedline.FieldInvoiceID] = struct{}{} +} + +// BillingInvoiceCleared reports if the "billing_invoice" edge to the BillingInvoice entity was cleared. +func (m *BillingStandardInvoiceDetailedLineMutation) BillingInvoiceCleared() bool { + return m.clearedbilling_invoice +} + +// BillingInvoiceID returns the "billing_invoice" edge ID in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) BillingInvoiceID() (id string, exists bool) { + if m.billing_invoice != nil { + return *m.billing_invoice, true + } + return +} + +// BillingInvoiceIDs returns the "billing_invoice" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BillingInvoiceID instead. It exists only for internal usage by the builders. +func (m *BillingStandardInvoiceDetailedLineMutation) BillingInvoiceIDs() (ids []string) { + if id := m.billing_invoice; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBillingInvoice resets all changes to the "billing_invoice" edge. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetBillingInvoice() { + m.billing_invoice = nil + m.clearedbilling_invoice = false +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by id. +func (m *BillingStandardInvoiceDetailedLineMutation) SetBillingInvoiceLineID(id string) { + m.billing_invoice_line = &id +} + +// ClearBillingInvoiceLine clears the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (m *BillingStandardInvoiceDetailedLineMutation) ClearBillingInvoiceLine() { + m.clearedbilling_invoice_line = true + m.clearedFields[billingstandardinvoicedetailedline.FieldParentLineID] = struct{}{} +} + +// BillingInvoiceLineCleared reports if the "billing_invoice_line" edge to the BillingInvoiceLine entity was cleared. +func (m *BillingStandardInvoiceDetailedLineMutation) BillingInvoiceLineCleared() bool { + return m.clearedbilling_invoice_line +} + +// BillingInvoiceLineID returns the "billing_invoice_line" edge ID in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) BillingInvoiceLineID() (id string, exists bool) { + if m.billing_invoice_line != nil { + return *m.billing_invoice_line, true + } + return +} + +// BillingInvoiceLineIDs returns the "billing_invoice_line" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BillingInvoiceLineID instead. It exists only for internal usage by the builders. +func (m *BillingStandardInvoiceDetailedLineMutation) BillingInvoiceLineIDs() (ids []string) { + if id := m.billing_invoice_line; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBillingInvoiceLine resets all changes to the "billing_invoice_line" edge. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetBillingInvoiceLine() { + m.billing_invoice_line = nil + m.clearedbilling_invoice_line = false +} + +// AddAmountDiscountIDs adds the "amount_discounts" edge to the BillingStandardInvoiceDetailedLineAmountDiscount entity by ids. +func (m *BillingStandardInvoiceDetailedLineMutation) AddAmountDiscountIDs(ids ...string) { + if m.amount_discounts == nil { + m.amount_discounts = make(map[string]struct{}) + } + for i := range ids { + m.amount_discounts[ids[i]] = struct{}{} + } +} + +// ClearAmountDiscounts clears the "amount_discounts" edge to the BillingStandardInvoiceDetailedLineAmountDiscount entity. +func (m *BillingStandardInvoiceDetailedLineMutation) ClearAmountDiscounts() { + m.clearedamount_discounts = true +} + +// AmountDiscountsCleared reports if the "amount_discounts" edge to the BillingStandardInvoiceDetailedLineAmountDiscount entity was cleared. +func (m *BillingStandardInvoiceDetailedLineMutation) AmountDiscountsCleared() bool { + return m.clearedamount_discounts +} + +// RemoveAmountDiscountIDs removes the "amount_discounts" edge to the BillingStandardInvoiceDetailedLineAmountDiscount entity by IDs. +func (m *BillingStandardInvoiceDetailedLineMutation) RemoveAmountDiscountIDs(ids ...string) { + if m.removedamount_discounts == nil { + m.removedamount_discounts = make(map[string]struct{}) + } + for i := range ids { + delete(m.amount_discounts, ids[i]) + m.removedamount_discounts[ids[i]] = struct{}{} + } +} + +// RemovedAmountDiscounts returns the removed IDs of the "amount_discounts" edge to the BillingStandardInvoiceDetailedLineAmountDiscount entity. +func (m *BillingStandardInvoiceDetailedLineMutation) RemovedAmountDiscountsIDs() (ids []string) { + for id := range m.removedamount_discounts { + ids = append(ids, id) + } + return +} + +// AmountDiscountsIDs returns the "amount_discounts" edge IDs in the mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) AmountDiscountsIDs() (ids []string) { + for id := range m.amount_discounts { + ids = append(ids, id) + } + return +} + +// ResetAmountDiscounts resets all changes to the "amount_discounts" edge. +func (m *BillingStandardInvoiceDetailedLineMutation) ResetAmountDiscounts() { + m.amount_discounts = nil + m.clearedamount_discounts = false + m.removedamount_discounts = nil +} + +// Where appends a list predicates to the BillingStandardInvoiceDetailedLineMutation builder. +func (m *BillingStandardInvoiceDetailedLineMutation) Where(ps ...predicate.BillingStandardInvoiceDetailedLine) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BillingStandardInvoiceDetailedLineMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BillingStandardInvoiceDetailedLineMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillingStandardInvoiceDetailedLine, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BillingStandardInvoiceDetailedLineMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BillingStandardInvoiceDetailedLineMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BillingStandardInvoiceDetailedLine). +func (m *BillingStandardInvoiceDetailedLineMutation) 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 *BillingStandardInvoiceDetailedLineMutation) Fields() []string { + fields := make([]string, 0, 29) + if m.currency != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldCurrency) + } + if m.service_period_start != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldServicePeriodStart) + } + if m.service_period_end != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldServicePeriodEnd) + } + if m.quantity != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldQuantity) + } + if m.invoicing_app_external_id != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldInvoicingAppExternalID) + } + if m.child_unique_reference_id != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldChildUniqueReferenceID) + } + if m.per_unit_amount != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldPerUnitAmount) + } + if m.category != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldCategory) + } + if m.payment_term != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldPaymentTerm) + } + if m.index != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldIndex) + } + if m.credits_applied != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldCreditsApplied) + } + if m.annotations != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldAnnotations) + } + if m.namespace != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldDeletedAt) + } + if m.name != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldName) + } + if m.description != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldDescription) + } + if m.amount != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldAmount) + } + if m.taxes_total != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldTaxesTotal) + } + if m.taxes_inclusive_total != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldTaxesInclusiveTotal) + } + if m.taxes_exclusive_total != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldTaxesExclusiveTotal) + } + if m.charges_total != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldChargesTotal) + } + if m.discounts_total != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldDiscountsTotal) + } + if m.credits_total != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldCreditsTotal) + } + if m.total != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldTotal) + } + if m.billing_invoice != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldInvoiceID) + } + if m.billing_invoice_line != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldParentLineID) + } + 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 *BillingStandardInvoiceDetailedLineMutation) Field(name string) (ent.Value, bool) { + switch name { + case billingstandardinvoicedetailedline.FieldCurrency: + return m.Currency() + case billingstandardinvoicedetailedline.FieldServicePeriodStart: + return m.ServicePeriodStart() + case billingstandardinvoicedetailedline.FieldServicePeriodEnd: + return m.ServicePeriodEnd() + case billingstandardinvoicedetailedline.FieldQuantity: + return m.Quantity() + case billingstandardinvoicedetailedline.FieldInvoicingAppExternalID: + return m.InvoicingAppExternalID() + case billingstandardinvoicedetailedline.FieldChildUniqueReferenceID: + return m.ChildUniqueReferenceID() + case billingstandardinvoicedetailedline.FieldPerUnitAmount: + return m.PerUnitAmount() + case billingstandardinvoicedetailedline.FieldCategory: + return m.Category() + case billingstandardinvoicedetailedline.FieldPaymentTerm: + return m.PaymentTerm() + case billingstandardinvoicedetailedline.FieldIndex: + return m.Index() + case billingstandardinvoicedetailedline.FieldCreditsApplied: + return m.CreditsApplied() + case billingstandardinvoicedetailedline.FieldAnnotations: + return m.Annotations() + case billingstandardinvoicedetailedline.FieldNamespace: + return m.Namespace() + case billingstandardinvoicedetailedline.FieldMetadata: + return m.Metadata() + case billingstandardinvoicedetailedline.FieldCreatedAt: + return m.CreatedAt() + case billingstandardinvoicedetailedline.FieldUpdatedAt: + return m.UpdatedAt() + case billingstandardinvoicedetailedline.FieldDeletedAt: + return m.DeletedAt() + case billingstandardinvoicedetailedline.FieldName: + return m.Name() + case billingstandardinvoicedetailedline.FieldDescription: + return m.Description() + case billingstandardinvoicedetailedline.FieldAmount: + return m.Amount() + case billingstandardinvoicedetailedline.FieldTaxesTotal: + return m.TaxesTotal() + case billingstandardinvoicedetailedline.FieldTaxesInclusiveTotal: + return m.TaxesInclusiveTotal() + case billingstandardinvoicedetailedline.FieldTaxesExclusiveTotal: + return m.TaxesExclusiveTotal() + case billingstandardinvoicedetailedline.FieldChargesTotal: + return m.ChargesTotal() + case billingstandardinvoicedetailedline.FieldDiscountsTotal: + return m.DiscountsTotal() + case billingstandardinvoicedetailedline.FieldCreditsTotal: + return m.CreditsTotal() + case billingstandardinvoicedetailedline.FieldTotal: + return m.Total() + case billingstandardinvoicedetailedline.FieldInvoiceID: + return m.InvoiceID() + case billingstandardinvoicedetailedline.FieldParentLineID: + return m.ParentLineID() + } + 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 *BillingStandardInvoiceDetailedLineMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case billingstandardinvoicedetailedline.FieldCurrency: + return m.OldCurrency(ctx) + case billingstandardinvoicedetailedline.FieldServicePeriodStart: + return m.OldServicePeriodStart(ctx) + case billingstandardinvoicedetailedline.FieldServicePeriodEnd: + return m.OldServicePeriodEnd(ctx) + case billingstandardinvoicedetailedline.FieldQuantity: + return m.OldQuantity(ctx) + case billingstandardinvoicedetailedline.FieldInvoicingAppExternalID: + return m.OldInvoicingAppExternalID(ctx) + case billingstandardinvoicedetailedline.FieldChildUniqueReferenceID: + return m.OldChildUniqueReferenceID(ctx) + case billingstandardinvoicedetailedline.FieldPerUnitAmount: + return m.OldPerUnitAmount(ctx) + case billingstandardinvoicedetailedline.FieldCategory: + return m.OldCategory(ctx) + case billingstandardinvoicedetailedline.FieldPaymentTerm: + return m.OldPaymentTerm(ctx) + case billingstandardinvoicedetailedline.FieldIndex: + return m.OldIndex(ctx) + case billingstandardinvoicedetailedline.FieldCreditsApplied: + return m.OldCreditsApplied(ctx) + case billingstandardinvoicedetailedline.FieldAnnotations: + return m.OldAnnotations(ctx) + case billingstandardinvoicedetailedline.FieldNamespace: + return m.OldNamespace(ctx) + case billingstandardinvoicedetailedline.FieldMetadata: + return m.OldMetadata(ctx) + case billingstandardinvoicedetailedline.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case billingstandardinvoicedetailedline.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case billingstandardinvoicedetailedline.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case billingstandardinvoicedetailedline.FieldName: + return m.OldName(ctx) + case billingstandardinvoicedetailedline.FieldDescription: + return m.OldDescription(ctx) + case billingstandardinvoicedetailedline.FieldAmount: + return m.OldAmount(ctx) + case billingstandardinvoicedetailedline.FieldTaxesTotal: + return m.OldTaxesTotal(ctx) + case billingstandardinvoicedetailedline.FieldTaxesInclusiveTotal: + return m.OldTaxesInclusiveTotal(ctx) + case billingstandardinvoicedetailedline.FieldTaxesExclusiveTotal: + return m.OldTaxesExclusiveTotal(ctx) + case billingstandardinvoicedetailedline.FieldChargesTotal: + return m.OldChargesTotal(ctx) + case billingstandardinvoicedetailedline.FieldDiscountsTotal: + return m.OldDiscountsTotal(ctx) + case billingstandardinvoicedetailedline.FieldCreditsTotal: + return m.OldCreditsTotal(ctx) + case billingstandardinvoicedetailedline.FieldTotal: + return m.OldTotal(ctx) + case billingstandardinvoicedetailedline.FieldInvoiceID: + return m.OldInvoiceID(ctx) + case billingstandardinvoicedetailedline.FieldParentLineID: + return m.OldParentLineID(ctx) + } + return nil, fmt.Errorf("unknown BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) SetField(name string, value ent.Value) error { + switch name { + case billingstandardinvoicedetailedline.FieldCurrency: + v, ok := value.(currencyx.Code) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrency(v) + return nil + case billingstandardinvoicedetailedline.FieldServicePeriodStart: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetServicePeriodStart(v) + return nil + case billingstandardinvoicedetailedline.FieldServicePeriodEnd: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetServicePeriodEnd(v) + return nil + case billingstandardinvoicedetailedline.FieldQuantity: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetQuantity(v) + return nil + case billingstandardinvoicedetailedline.FieldInvoicingAppExternalID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoicingAppExternalID(v) + return nil + case billingstandardinvoicedetailedline.FieldChildUniqueReferenceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChildUniqueReferenceID(v) + return nil + case billingstandardinvoicedetailedline.FieldPerUnitAmount: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPerUnitAmount(v) + return nil + case billingstandardinvoicedetailedline.FieldCategory: + v, ok := value.(stddetailedline.Category) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCategory(v) + return nil + case billingstandardinvoicedetailedline.FieldPaymentTerm: + v, ok := value.(productcatalog.PaymentTermType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPaymentTerm(v) + return nil + case billingstandardinvoicedetailedline.FieldIndex: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIndex(v) + return nil + case billingstandardinvoicedetailedline.FieldCreditsApplied: + v, ok := value.(*creditsapplied.CreditsApplied) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreditsApplied(v) + return nil + case billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case billingstandardinvoicedetailedline.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case billingstandardinvoicedetailedline.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.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 billingstandardinvoicedetailedline.FieldInvoiceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceID(v) + return nil + case billingstandardinvoicedetailedline.FieldParentLineID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetParentLineID(v) + return nil + } + return fmt.Errorf("unknown BillingStandardInvoiceDetailedLine field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) AddedFields() []string { + var fields []string + if m.addindex != nil { + fields = append(fields, billingstandardinvoicedetailedline.FieldIndex) + } + return fields +} + +// 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 *BillingStandardInvoiceDetailedLineMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case billingstandardinvoicedetailedline.FieldIndex: + return m.AddedIndex() + } + 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 *BillingStandardInvoiceDetailedLineMutation) AddField(name string, value ent.Value) error { + switch name { + case billingstandardinvoicedetailedline.FieldIndex: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddIndex(v) + return nil + } + return fmt.Errorf("unknown BillingStandardInvoiceDetailedLine numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(billingstandardinvoicedetailedline.FieldInvoicingAppExternalID) { + fields = append(fields, billingstandardinvoicedetailedline.FieldInvoicingAppExternalID) + } + if m.FieldCleared(billingstandardinvoicedetailedline.FieldIndex) { + fields = append(fields, billingstandardinvoicedetailedline.FieldIndex) + } + if m.FieldCleared(billingstandardinvoicedetailedline.FieldCreditsApplied) { + fields = append(fields, billingstandardinvoicedetailedline.FieldCreditsApplied) + } + if m.FieldCleared(billingstandardinvoicedetailedline.FieldAnnotations) { + fields = append(fields, billingstandardinvoicedetailedline.FieldAnnotations) + } + if m.FieldCleared(billingstandardinvoicedetailedline.FieldMetadata) { + fields = append(fields, billingstandardinvoicedetailedline.FieldMetadata) + } + if m.FieldCleared(billingstandardinvoicedetailedline.FieldDeletedAt) { + fields = append(fields, billingstandardinvoicedetailedline.FieldDeletedAt) + } + if m.FieldCleared(billingstandardinvoicedetailedline.FieldDescription) { + fields = append(fields, billingstandardinvoicedetailedline.FieldDescription) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) 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 *BillingStandardInvoiceDetailedLineMutation) ClearField(name string) error { + switch name { + case billingstandardinvoicedetailedline.FieldInvoicingAppExternalID: + m.ClearInvoicingAppExternalID() + return nil + case billingstandardinvoicedetailedline.FieldIndex: + m.ClearIndex() + return nil + case billingstandardinvoicedetailedline.FieldCreditsApplied: + m.ClearCreditsApplied() + return nil + case billingstandardinvoicedetailedline.FieldAnnotations: + m.ClearAnnotations() + return nil + case billingstandardinvoicedetailedline.FieldMetadata: + m.ClearMetadata() + return nil + case billingstandardinvoicedetailedline.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case billingstandardinvoicedetailedline.FieldDescription: + m.ClearDescription() + return nil + } + return fmt.Errorf("unknown BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) ResetField(name string) error { + switch name { + case billingstandardinvoicedetailedline.FieldCurrency: + m.ResetCurrency() + return nil + case billingstandardinvoicedetailedline.FieldServicePeriodStart: + m.ResetServicePeriodStart() + return nil + case billingstandardinvoicedetailedline.FieldServicePeriodEnd: + m.ResetServicePeriodEnd() + return nil + case billingstandardinvoicedetailedline.FieldQuantity: + m.ResetQuantity() + return nil + case billingstandardinvoicedetailedline.FieldInvoicingAppExternalID: + m.ResetInvoicingAppExternalID() + return nil + case billingstandardinvoicedetailedline.FieldChildUniqueReferenceID: + m.ResetChildUniqueReferenceID() + return nil + case billingstandardinvoicedetailedline.FieldPerUnitAmount: + m.ResetPerUnitAmount() + return nil + case billingstandardinvoicedetailedline.FieldCategory: + m.ResetCategory() + return nil + case billingstandardinvoicedetailedline.FieldPaymentTerm: + m.ResetPaymentTerm() + return nil + case billingstandardinvoicedetailedline.FieldIndex: + m.ResetIndex() + return nil + case billingstandardinvoicedetailedline.FieldCreditsApplied: + m.ResetCreditsApplied() + return nil + case billingstandardinvoicedetailedline.FieldAnnotations: + m.ResetAnnotations() + return nil + case billingstandardinvoicedetailedline.FieldNamespace: + m.ResetNamespace() + return nil + case billingstandardinvoicedetailedline.FieldMetadata: + m.ResetMetadata() + return nil + case billingstandardinvoicedetailedline.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case billingstandardinvoicedetailedline.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case billingstandardinvoicedetailedline.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case billingstandardinvoicedetailedline.FieldName: + m.ResetName() + return nil + case billingstandardinvoicedetailedline.FieldDescription: + m.ResetDescription() + return nil + case billingstandardinvoicedetailedline.FieldAmount: + m.ResetAmount() + return nil + case billingstandardinvoicedetailedline.FieldTaxesTotal: + m.ResetTaxesTotal() + return nil + case billingstandardinvoicedetailedline.FieldTaxesInclusiveTotal: + m.ResetTaxesInclusiveTotal() + return nil + case billingstandardinvoicedetailedline.FieldTaxesExclusiveTotal: + m.ResetTaxesExclusiveTotal() + return nil + case billingstandardinvoicedetailedline.FieldChargesTotal: + m.ResetChargesTotal() + return nil + case billingstandardinvoicedetailedline.FieldDiscountsTotal: + m.ResetDiscountsTotal() + return nil + case billingstandardinvoicedetailedline.FieldCreditsTotal: + m.ResetCreditsTotal() + return nil + case billingstandardinvoicedetailedline.FieldTotal: + m.ResetTotal() + return nil + case billingstandardinvoicedetailedline.FieldInvoiceID: + m.ResetInvoiceID() + return nil + case billingstandardinvoicedetailedline.FieldParentLineID: + m.ResetParentLineID() + return nil + } + return fmt.Errorf("unknown BillingStandardInvoiceDetailedLine field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) AddedEdges() []string { + edges := make([]string, 0, 3) + if m.billing_invoice != nil { + edges = append(edges, billingstandardinvoicedetailedline.EdgeBillingInvoice) + } + if m.billing_invoice_line != nil { + edges = append(edges, billingstandardinvoicedetailedline.EdgeBillingInvoiceLine) + } + if m.amount_discounts != nil { + edges = append(edges, billingstandardinvoicedetailedline.EdgeAmountDiscounts) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) AddedIDs(name string) []ent.Value { + switch name { + case billingstandardinvoicedetailedline.EdgeBillingInvoice: + if id := m.billing_invoice; id != nil { + return []ent.Value{*id} + } + case billingstandardinvoicedetailedline.EdgeBillingInvoiceLine: + if id := m.billing_invoice_line; id != nil { + return []ent.Value{*id} + } + case billingstandardinvoicedetailedline.EdgeAmountDiscounts: + ids := make([]ent.Value, 0, len(m.amount_discounts)) + for id := range m.amount_discounts { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) RemovedEdges() []string { + edges := make([]string, 0, 3) + if m.removedamount_discounts != nil { + edges = append(edges, billingstandardinvoicedetailedline.EdgeAmountDiscounts) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) RemovedIDs(name string) []ent.Value { + switch name { + case billingstandardinvoicedetailedline.EdgeAmountDiscounts: + ids := make([]ent.Value, 0, len(m.removedamount_discounts)) + for id := range m.removedamount_discounts { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) + if m.clearedbilling_invoice { + edges = append(edges, billingstandardinvoicedetailedline.EdgeBillingInvoice) + } + if m.clearedbilling_invoice_line { + edges = append(edges, billingstandardinvoicedetailedline.EdgeBillingInvoiceLine) + } + if m.clearedamount_discounts { + edges = append(edges, billingstandardinvoicedetailedline.EdgeAmountDiscounts) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BillingStandardInvoiceDetailedLineMutation) EdgeCleared(name string) bool { + switch name { + case billingstandardinvoicedetailedline.EdgeBillingInvoice: + return m.clearedbilling_invoice + case billingstandardinvoicedetailedline.EdgeBillingInvoiceLine: + return m.clearedbilling_invoice_line + case billingstandardinvoicedetailedline.EdgeAmountDiscounts: + return m.clearedamount_discounts + } + 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 *BillingStandardInvoiceDetailedLineMutation) ClearEdge(name string) error { + switch name { + case billingstandardinvoicedetailedline.EdgeBillingInvoice: + m.ClearBillingInvoice() + return nil + case billingstandardinvoicedetailedline.EdgeBillingInvoiceLine: + m.ClearBillingInvoiceLine() + return nil + } + return fmt.Errorf("unknown BillingStandardInvoiceDetailedLine 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 *BillingStandardInvoiceDetailedLineMutation) ResetEdge(name string) error { + switch name { + case billingstandardinvoicedetailedline.EdgeBillingInvoice: + m.ResetBillingInvoice() + return nil + case billingstandardinvoicedetailedline.EdgeBillingInvoiceLine: + m.ResetBillingInvoiceLine() + return nil + case billingstandardinvoicedetailedline.EdgeAmountDiscounts: + m.ResetAmountDiscounts() + return nil + } + return fmt.Errorf("unknown BillingStandardInvoiceDetailedLine edge %s", name) +} + +// BillingStandardInvoiceDetailedLineAmountDiscountMutation represents an operation that mutates the BillingStandardInvoiceDetailedLineAmountDiscount nodes in the graph. +type BillingStandardInvoiceDetailedLineAmountDiscountMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + invoicing_app_external_id *string + child_unique_reference_id *string + description *string + reason *billing.DiscountReasonType + amount *alpacadecimal.Decimal + rounding_amount *alpacadecimal.Decimal + source_discount **billing.DiscountReason + clearedFields map[string]struct{} + detailed_line *string + cleareddetailed_line bool + done bool + oldValue func(context.Context) (*BillingStandardInvoiceDetailedLineAmountDiscount, error) + predicates []predicate.BillingStandardInvoiceDetailedLineAmountDiscount +} + +var _ ent.Mutation = (*BillingStandardInvoiceDetailedLineAmountDiscountMutation)(nil) + +// billingstandardinvoicedetailedlineamountdiscountOption allows management of the mutation configuration using functional options. +type billingstandardinvoicedetailedlineamountdiscountOption func(*BillingStandardInvoiceDetailedLineAmountDiscountMutation) + +// newBillingStandardInvoiceDetailedLineAmountDiscountMutation creates new mutation for the BillingStandardInvoiceDetailedLineAmountDiscount entity. +func newBillingStandardInvoiceDetailedLineAmountDiscountMutation(c config, op Op, opts ...billingstandardinvoicedetailedlineamountdiscountOption) *BillingStandardInvoiceDetailedLineAmountDiscountMutation { + m := &BillingStandardInvoiceDetailedLineAmountDiscountMutation{ + config: c, + op: op, + typ: TypeBillingStandardInvoiceDetailedLineAmountDiscount, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBillingStandardInvoiceDetailedLineAmountDiscountID sets the ID field of the mutation. +func withBillingStandardInvoiceDetailedLineAmountDiscountID(id string) billingstandardinvoicedetailedlineamountdiscountOption { + return func(m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) { + var ( + err error + once sync.Once + value *BillingStandardInvoiceDetailedLineAmountDiscount + ) + m.oldValue = func(ctx context.Context) (*BillingStandardInvoiceDetailedLineAmountDiscount, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().BillingStandardInvoiceDetailedLineAmountDiscount.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBillingStandardInvoiceDetailedLineAmountDiscount sets the old BillingStandardInvoiceDetailedLineAmountDiscount of the mutation. +func withBillingStandardInvoiceDetailedLineAmountDiscount(node *BillingStandardInvoiceDetailedLineAmountDiscount) billingstandardinvoicedetailedlineamountdiscountOption { + return func(m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) { + m.oldValue = func(context.Context) (*BillingStandardInvoiceDetailedLineAmountDiscount, 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 BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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 BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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 BillingStandardInvoiceDetailedLineAmountDiscount entities. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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().BillingStandardInvoiceDetailedLineAmountDiscount.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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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 BillingStandardInvoiceDetailedLineAmountDiscount entity. +// If the BillingStandardInvoiceDetailedLineAmountDiscount 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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 BillingStandardInvoiceDetailedLineAmountDiscount entity. +// If the BillingStandardInvoiceDetailedLineAmountDiscount 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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 BillingStandardInvoiceDetailedLineAmountDiscount entity. +// If the BillingStandardInvoiceDetailedLineAmountDiscount 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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 BillingStandardInvoiceDetailedLineAmountDiscount entity. +// If the BillingStandardInvoiceDetailedLineAmountDiscount 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[billingstandardinvoicedetailedlineamountdiscount.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[billingstandardinvoicedetailedlineamountdiscount.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, billingstandardinvoicedetailedlineamountdiscount.FieldDeletedAt) +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) SetInvoicingAppExternalID(s string) { + m.invoicing_app_external_id = &s +} + +// InvoicingAppExternalID returns the value of the "invoicing_app_external_id" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) InvoicingAppExternalID() (r string, exists bool) { + v := m.invoicing_app_external_id + if v == nil { + return + } + return *v, true +} + +// OldInvoicingAppExternalID returns the old "invoicing_app_external_id" field's value of the BillingStandardInvoiceDetailedLineAmountDiscount entity. +// If the BillingStandardInvoiceDetailedLineAmountDiscount 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) OldInvoicingAppExternalID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoicingAppExternalID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoicingAppExternalID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoicingAppExternalID: %w", err) + } + return oldValue.InvoicingAppExternalID, nil +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ClearInvoicingAppExternalID() { + m.invoicing_app_external_id = nil + m.clearedFields[billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID] = struct{}{} +} + +// InvoicingAppExternalIDCleared returns if the "invoicing_app_external_id" field was cleared in this mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) InvoicingAppExternalIDCleared() bool { + _, ok := m.clearedFields[billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID] + return ok +} + +// ResetInvoicingAppExternalID resets all changes to the "invoicing_app_external_id" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ResetInvoicingAppExternalID() { + m.invoicing_app_external_id = nil + delete(m.clearedFields, billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID) +} + +// SetLineID sets the "line_id" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) SetLineID(s string) { + m.detailed_line = &s +} + +// LineID returns the value of the "line_id" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) LineID() (r string, exists bool) { + v := m.detailed_line + if v == nil { + return + } + return *v, true +} + +// OldLineID returns the old "line_id" field's value of the BillingStandardInvoiceDetailedLineAmountDiscount entity. +// If the BillingStandardInvoiceDetailedLineAmountDiscount 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ResetLineID() { + m.detailed_line = nil +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) SetChildUniqueReferenceID(s string) { + m.child_unique_reference_id = &s +} + +// ChildUniqueReferenceID returns the value of the "child_unique_reference_id" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ChildUniqueReferenceID() (r string, exists bool) { + v := m.child_unique_reference_id + if v == nil { + return + } + return *v, true +} + +// OldChildUniqueReferenceID returns the old "child_unique_reference_id" field's value of the BillingStandardInvoiceDetailedLineAmountDiscount entity. +// If the BillingStandardInvoiceDetailedLineAmountDiscount 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) OldChildUniqueReferenceID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldChildUniqueReferenceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldChildUniqueReferenceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldChildUniqueReferenceID: %w", err) + } + return oldValue.ChildUniqueReferenceID, nil +} + +// ClearChildUniqueReferenceID clears the value of the "child_unique_reference_id" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ClearChildUniqueReferenceID() { + m.child_unique_reference_id = nil + m.clearedFields[billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID] = struct{}{} +} + +// ChildUniqueReferenceIDCleared returns if the "child_unique_reference_id" field was cleared in this mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ChildUniqueReferenceIDCleared() bool { + _, ok := m.clearedFields[billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID] + return ok +} + +// ResetChildUniqueReferenceID resets all changes to the "child_unique_reference_id" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ResetChildUniqueReferenceID() { + m.child_unique_reference_id = nil + delete(m.clearedFields, billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID) +} + +// SetDescription sets the "description" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the BillingStandardInvoiceDetailedLineAmountDiscount entity. +// If the BillingStandardInvoiceDetailedLineAmountDiscount 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ClearDescription() { + m.description = nil + m.clearedFields[billingstandardinvoicedetailedlineamountdiscount.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[billingstandardinvoicedetailedlineamountdiscount.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, billingstandardinvoicedetailedlineamountdiscount.FieldDescription) +} + +// SetReason sets the "reason" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) SetReason(brt billing.DiscountReasonType) { + m.reason = &brt +} + +// Reason returns the value of the "reason" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) Reason() (r billing.DiscountReasonType, exists bool) { + v := m.reason + if v == nil { + return + } + return *v, true +} + +// OldReason returns the old "reason" field's value of the BillingStandardInvoiceDetailedLineAmountDiscount entity. +// If the BillingStandardInvoiceDetailedLineAmountDiscount 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) OldReason(ctx context.Context) (v billing.DiscountReasonType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldReason is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldReason requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldReason: %w", err) + } + return oldValue.Reason, nil +} + +// ResetReason resets all changes to the "reason" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ResetReason() { + m.reason = nil +} + +// SetAmount sets the "amount" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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 BillingStandardInvoiceDetailedLineAmountDiscount entity. +// If the BillingStandardInvoiceDetailedLineAmountDiscount 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ResetAmount() { + m.amount = nil +} + +// SetRoundingAmount sets the "rounding_amount" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) SetRoundingAmount(a alpacadecimal.Decimal) { + m.rounding_amount = &a +} + +// RoundingAmount returns the value of the "rounding_amount" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) RoundingAmount() (r alpacadecimal.Decimal, exists bool) { + v := m.rounding_amount + if v == nil { + return + } + return *v, true +} + +// OldRoundingAmount returns the old "rounding_amount" field's value of the BillingStandardInvoiceDetailedLineAmountDiscount entity. +// If the BillingStandardInvoiceDetailedLineAmountDiscount 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) OldRoundingAmount(ctx context.Context) (v *alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRoundingAmount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRoundingAmount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRoundingAmount: %w", err) + } + return oldValue.RoundingAmount, nil +} + +// ClearRoundingAmount clears the value of the "rounding_amount" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ClearRoundingAmount() { + m.rounding_amount = nil + m.clearedFields[billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount] = struct{}{} +} + +// RoundingAmountCleared returns if the "rounding_amount" field was cleared in this mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) RoundingAmountCleared() bool { + _, ok := m.clearedFields[billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount] + return ok +} + +// ResetRoundingAmount resets all changes to the "rounding_amount" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ResetRoundingAmount() { + m.rounding_amount = nil + delete(m.clearedFields, billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount) +} + +// SetSourceDiscount sets the "source_discount" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) SetSourceDiscount(br *billing.DiscountReason) { + m.source_discount = &br +} + +// SourceDiscount returns the value of the "source_discount" field in the mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) SourceDiscount() (r *billing.DiscountReason, exists bool) { + v := m.source_discount + if v == nil { + return + } + return *v, true +} + +// OldSourceDiscount returns the old "source_discount" field's value of the BillingStandardInvoiceDetailedLineAmountDiscount entity. +// If the BillingStandardInvoiceDetailedLineAmountDiscount 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) OldSourceDiscount(ctx context.Context) (v *billing.DiscountReason, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSourceDiscount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSourceDiscount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSourceDiscount: %w", err) + } + return oldValue.SourceDiscount, nil +} + +// ClearSourceDiscount clears the value of the "source_discount" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ClearSourceDiscount() { + m.source_discount = nil + m.clearedFields[billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount] = struct{}{} +} + +// SourceDiscountCleared returns if the "source_discount" field was cleared in this mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) SourceDiscountCleared() bool { + _, ok := m.clearedFields[billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount] + return ok +} + +// ResetSourceDiscount resets all changes to the "source_discount" field. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ResetSourceDiscount() { + m.source_discount = nil + delete(m.clearedFields, billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount) +} + +// SetDetailedLineID sets the "detailed_line" edge to the BillingStandardInvoiceDetailedLine entity by id. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) SetDetailedLineID(id string) { + m.detailed_line = &id +} + +// ClearDetailedLine clears the "detailed_line" edge to the BillingStandardInvoiceDetailedLine entity. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ClearDetailedLine() { + m.cleareddetailed_line = true + m.clearedFields[billingstandardinvoicedetailedlineamountdiscount.FieldLineID] = struct{}{} +} + +// DetailedLineCleared reports if the "detailed_line" edge to the BillingStandardInvoiceDetailedLine entity was cleared. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) DetailedLineCleared() bool { + return m.cleareddetailed_line +} + +// DetailedLineID returns the "detailed_line" edge ID in the mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) DetailedLineID() (id string, exists bool) { + if m.detailed_line != nil { + return *m.detailed_line, true + } + return +} + +// DetailedLineIDs returns the "detailed_line" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// DetailedLineID instead. It exists only for internal usage by the builders. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) DetailedLineIDs() (ids []string) { + if id := m.detailed_line; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetDetailedLine resets all changes to the "detailed_line" edge. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ResetDetailedLine() { + m.detailed_line = nil + m.cleareddetailed_line = false +} + +// Where appends a list predicates to the BillingStandardInvoiceDetailedLineAmountDiscountMutation builder. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) Where(ps ...predicate.BillingStandardInvoiceDetailedLineAmountDiscount) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BillingStandardInvoiceDetailedLineAmountDiscountMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillingStandardInvoiceDetailedLineAmountDiscount, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BillingStandardInvoiceDetailedLineAmountDiscount). +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) Fields() []string { + fields := make([]string, 0, 12) + if m.namespace != nil { + fields = append(fields, billingstandardinvoicedetailedlineamountdiscount.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, billingstandardinvoicedetailedlineamountdiscount.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, billingstandardinvoicedetailedlineamountdiscount.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, billingstandardinvoicedetailedlineamountdiscount.FieldDeletedAt) + } + if m.invoicing_app_external_id != nil { + fields = append(fields, billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID) + } + if m.detailed_line != nil { + fields = append(fields, billingstandardinvoicedetailedlineamountdiscount.FieldLineID) + } + if m.child_unique_reference_id != nil { + fields = append(fields, billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID) + } + if m.description != nil { + fields = append(fields, billingstandardinvoicedetailedlineamountdiscount.FieldDescription) + } + if m.reason != nil { + fields = append(fields, billingstandardinvoicedetailedlineamountdiscount.FieldReason) + } + if m.amount != nil { + fields = append(fields, billingstandardinvoicedetailedlineamountdiscount.FieldAmount) + } + if m.rounding_amount != nil { + fields = append(fields, billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount) + } + if m.source_discount != nil { + fields = append(fields, billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount) + } + 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) Field(name string) (ent.Value, bool) { + switch name { + case billingstandardinvoicedetailedlineamountdiscount.FieldNamespace: + return m.Namespace() + case billingstandardinvoicedetailedlineamountdiscount.FieldCreatedAt: + return m.CreatedAt() + case billingstandardinvoicedetailedlineamountdiscount.FieldUpdatedAt: + return m.UpdatedAt() + case billingstandardinvoicedetailedlineamountdiscount.FieldDeletedAt: + return m.DeletedAt() + case billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID: + return m.InvoicingAppExternalID() + case billingstandardinvoicedetailedlineamountdiscount.FieldLineID: + return m.LineID() + case billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID: + return m.ChildUniqueReferenceID() + case billingstandardinvoicedetailedlineamountdiscount.FieldDescription: + return m.Description() + case billingstandardinvoicedetailedlineamountdiscount.FieldReason: + return m.Reason() + case billingstandardinvoicedetailedlineamountdiscount.FieldAmount: + return m.Amount() + case billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount: + return m.RoundingAmount() + case billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount: + return m.SourceDiscount() + } + 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case billingstandardinvoicedetailedlineamountdiscount.FieldNamespace: + return m.OldNamespace(ctx) + case billingstandardinvoicedetailedlineamountdiscount.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case billingstandardinvoicedetailedlineamountdiscount.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case billingstandardinvoicedetailedlineamountdiscount.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID: + return m.OldInvoicingAppExternalID(ctx) + case billingstandardinvoicedetailedlineamountdiscount.FieldLineID: + return m.OldLineID(ctx) + case billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID: + return m.OldChildUniqueReferenceID(ctx) + case billingstandardinvoicedetailedlineamountdiscount.FieldDescription: + return m.OldDescription(ctx) + case billingstandardinvoicedetailedlineamountdiscount.FieldReason: + return m.OldReason(ctx) + case billingstandardinvoicedetailedlineamountdiscount.FieldAmount: + return m.OldAmount(ctx) + case billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount: + return m.OldRoundingAmount(ctx) + case billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount: + return m.OldSourceDiscount(ctx) + } + return nil, fmt.Errorf("unknown BillingStandardInvoiceDetailedLineAmountDiscount 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) SetField(name string, value ent.Value) error { + switch name { + case billingstandardinvoicedetailedlineamountdiscount.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case billingstandardinvoicedetailedlineamountdiscount.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 billingstandardinvoicedetailedlineamountdiscount.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 billingstandardinvoicedetailedlineamountdiscount.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 billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoicingAppExternalID(v) + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldLineID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLineID(v) + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChildUniqueReferenceID(v) + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldReason: + v, ok := value.(billing.DiscountReasonType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetReason(v) + return nil + case billingstandardinvoicedetailedlineamountdiscount.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 billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRoundingAmount(v) + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount: + v, ok := value.(*billing.DiscountReason) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSourceDiscount(v) + return nil + } + return fmt.Errorf("unknown BillingStandardInvoiceDetailedLineAmountDiscount field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown BillingStandardInvoiceDetailedLineAmountDiscount numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(billingstandardinvoicedetailedlineamountdiscount.FieldDeletedAt) { + fields = append(fields, billingstandardinvoicedetailedlineamountdiscount.FieldDeletedAt) + } + if m.FieldCleared(billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID) { + fields = append(fields, billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID) + } + if m.FieldCleared(billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID) { + fields = append(fields, billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID) + } + if m.FieldCleared(billingstandardinvoicedetailedlineamountdiscount.FieldDescription) { + fields = append(fields, billingstandardinvoicedetailedlineamountdiscount.FieldDescription) + } + if m.FieldCleared(billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount) { + fields = append(fields, billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount) + } + if m.FieldCleared(billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount) { + fields = append(fields, billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ClearField(name string) error { + switch name { + case billingstandardinvoicedetailedlineamountdiscount.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID: + m.ClearInvoicingAppExternalID() + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID: + m.ClearChildUniqueReferenceID() + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldDescription: + m.ClearDescription() + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount: + m.ClearRoundingAmount() + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount: + m.ClearSourceDiscount() + return nil + } + return fmt.Errorf("unknown BillingStandardInvoiceDetailedLineAmountDiscount 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ResetField(name string) error { + switch name { + case billingstandardinvoicedetailedlineamountdiscount.FieldNamespace: + m.ResetNamespace() + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldInvoicingAppExternalID: + m.ResetInvoicingAppExternalID() + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldLineID: + m.ResetLineID() + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldChildUniqueReferenceID: + m.ResetChildUniqueReferenceID() + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldDescription: + m.ResetDescription() + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldReason: + m.ResetReason() + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldAmount: + m.ResetAmount() + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldRoundingAmount: + m.ResetRoundingAmount() + return nil + case billingstandardinvoicedetailedlineamountdiscount.FieldSourceDiscount: + m.ResetSourceDiscount() + return nil + } + return fmt.Errorf("unknown BillingStandardInvoiceDetailedLineAmountDiscount field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.detailed_line != nil { + edges = append(edges, billingstandardinvoicedetailedlineamountdiscount.EdgeDetailedLine) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) AddedIDs(name string) []ent.Value { + switch name { + case billingstandardinvoicedetailedlineamountdiscount.EdgeDetailedLine: + if id := m.detailed_line; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.cleareddetailed_line { + edges = append(edges, billingstandardinvoicedetailedlineamountdiscount.EdgeDetailedLine) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BillingStandardInvoiceDetailedLineAmountDiscountMutation) EdgeCleared(name string) bool { + switch name { + case billingstandardinvoicedetailedlineamountdiscount.EdgeDetailedLine: + return m.cleareddetailed_line + } + 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ClearEdge(name string) error { + switch name { + case billingstandardinvoicedetailedlineamountdiscount.EdgeDetailedLine: + m.ClearDetailedLine() + return nil + } + return fmt.Errorf("unknown BillingStandardInvoiceDetailedLineAmountDiscount 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 *BillingStandardInvoiceDetailedLineAmountDiscountMutation) ResetEdge(name string) error { + switch name { + case billingstandardinvoicedetailedlineamountdiscount.EdgeDetailedLine: + m.ResetDetailedLine() + return nil + } + return fmt.Errorf("unknown BillingStandardInvoiceDetailedLineAmountDiscount edge %s", name) +} + +// BillingWorkflowConfigMutation represents an operation that mutates the BillingWorkflowConfig nodes in the graph. +type BillingWorkflowConfigMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + tax_behavior *productcatalog.TaxBehavior + collection_alignment *billing.AlignmentKind + anchored_alignment_detail **billing.AnchoredAlignmentDetail + line_collection_period *datetime.ISODurationString + invoice_auto_advance *bool + invoice_draft_period *datetime.ISODurationString + invoice_due_after *datetime.ISODurationString + invoice_collection_method *billing.CollectionMethod + invoice_progressive_billing *bool + subscription_end_proration_mode *billing.SubscriptionEndProrationMode + invoice_default_tax_settings *productcatalog.TaxConfig + tax_enabled *bool + tax_enforced *bool + clearedFields map[string]struct{} + billing_invoices *string + clearedbilling_invoices bool + billing_profile *string + clearedbilling_profile bool + tax_code *string + clearedtax_code bool + done bool + oldValue func(context.Context) (*BillingWorkflowConfig, error) + predicates []predicate.BillingWorkflowConfig +} + +var _ ent.Mutation = (*BillingWorkflowConfigMutation)(nil) + +// billingworkflowconfigOption allows management of the mutation configuration using functional options. +type billingworkflowconfigOption func(*BillingWorkflowConfigMutation) + +// newBillingWorkflowConfigMutation creates new mutation for the BillingWorkflowConfig entity. +func newBillingWorkflowConfigMutation(c config, op Op, opts ...billingworkflowconfigOption) *BillingWorkflowConfigMutation { + m := &BillingWorkflowConfigMutation{ + config: c, + op: op, + typ: TypeBillingWorkflowConfig, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBillingWorkflowConfigID sets the ID field of the mutation. +func withBillingWorkflowConfigID(id string) billingworkflowconfigOption { + return func(m *BillingWorkflowConfigMutation) { + var ( + err error + once sync.Once + value *BillingWorkflowConfig + ) + m.oldValue = func(ctx context.Context) (*BillingWorkflowConfig, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().BillingWorkflowConfig.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBillingWorkflowConfig sets the old BillingWorkflowConfig of the mutation. +func withBillingWorkflowConfig(node *BillingWorkflowConfig) billingworkflowconfigOption { + return func(m *BillingWorkflowConfigMutation) { + m.oldValue = func(context.Context) (*BillingWorkflowConfig, 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 BillingWorkflowConfigMutation) 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 BillingWorkflowConfigMutation) 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 BillingWorkflowConfig entities. +func (m *BillingWorkflowConfigMutation) 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 *BillingWorkflowConfigMutation) 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 *BillingWorkflowConfigMutation) 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().BillingWorkflowConfig.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 *BillingWorkflowConfigMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *BillingWorkflowConfigMutation) 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 BillingWorkflowConfig entity. +// If the BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) 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 *BillingWorkflowConfigMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *BillingWorkflowConfigMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *BillingWorkflowConfigMutation) 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 BillingWorkflowConfig entity. +// If the BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) 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 *BillingWorkflowConfigMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *BillingWorkflowConfigMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *BillingWorkflowConfigMutation) 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 BillingWorkflowConfig entity. +// If the BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) 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 *BillingWorkflowConfigMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *BillingWorkflowConfigMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *BillingWorkflowConfigMutation) 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 BillingWorkflowConfig entity. +// If the BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) 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 *BillingWorkflowConfigMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[billingworkflowconfig.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *BillingWorkflowConfigMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[billingworkflowconfig.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *BillingWorkflowConfigMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, billingworkflowconfig.FieldDeletedAt) +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (m *BillingWorkflowConfigMutation) SetTaxCodeID(s string) { + m.tax_code = &s +} + +// TaxCodeID returns the value of the "tax_code_id" field in the mutation. +func (m *BillingWorkflowConfigMutation) TaxCodeID() (r string, exists bool) { + v := m.tax_code + if v == nil { + return + } + return *v, true +} + +// OldTaxCodeID returns the old "tax_code_id" field's value of the BillingWorkflowConfig entity. +// If the BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) OldTaxCodeID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxCodeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxCodeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxCodeID: %w", err) + } + return oldValue.TaxCodeID, nil +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (m *BillingWorkflowConfigMutation) ClearTaxCodeID() { + m.tax_code = nil + m.clearedFields[billingworkflowconfig.FieldTaxCodeID] = struct{}{} +} + +// TaxCodeIDCleared returns if the "tax_code_id" field was cleared in this mutation. +func (m *BillingWorkflowConfigMutation) TaxCodeIDCleared() bool { + _, ok := m.clearedFields[billingworkflowconfig.FieldTaxCodeID] + return ok +} + +// ResetTaxCodeID resets all changes to the "tax_code_id" field. +func (m *BillingWorkflowConfigMutation) ResetTaxCodeID() { + m.tax_code = nil + delete(m.clearedFields, billingworkflowconfig.FieldTaxCodeID) +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (m *BillingWorkflowConfigMutation) SetTaxBehavior(pb productcatalog.TaxBehavior) { + m.tax_behavior = &pb +} + +// TaxBehavior returns the value of the "tax_behavior" field in the mutation. +func (m *BillingWorkflowConfigMutation) TaxBehavior() (r productcatalog.TaxBehavior, exists bool) { + v := m.tax_behavior + if v == nil { + return + } + return *v, true +} + +// OldTaxBehavior returns the old "tax_behavior" field's value of the BillingWorkflowConfig entity. +// If the BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) OldTaxBehavior(ctx context.Context) (v *productcatalog.TaxBehavior, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxBehavior is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxBehavior requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxBehavior: %w", err) + } + return oldValue.TaxBehavior, nil +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (m *BillingWorkflowConfigMutation) ClearTaxBehavior() { + m.tax_behavior = nil + m.clearedFields[billingworkflowconfig.FieldTaxBehavior] = struct{}{} +} + +// TaxBehaviorCleared returns if the "tax_behavior" field was cleared in this mutation. +func (m *BillingWorkflowConfigMutation) TaxBehaviorCleared() bool { + _, ok := m.clearedFields[billingworkflowconfig.FieldTaxBehavior] + return ok +} + +// ResetTaxBehavior resets all changes to the "tax_behavior" field. +func (m *BillingWorkflowConfigMutation) ResetTaxBehavior() { + m.tax_behavior = nil + delete(m.clearedFields, billingworkflowconfig.FieldTaxBehavior) +} + +// SetCollectionAlignment sets the "collection_alignment" field. +func (m *BillingWorkflowConfigMutation) SetCollectionAlignment(bk billing.AlignmentKind) { + m.collection_alignment = &bk +} + +// CollectionAlignment returns the value of the "collection_alignment" field in the mutation. +func (m *BillingWorkflowConfigMutation) CollectionAlignment() (r billing.AlignmentKind, exists bool) { + v := m.collection_alignment + if v == nil { + return + } + return *v, true +} + +// OldCollectionAlignment returns the old "collection_alignment" field's value of the BillingWorkflowConfig entity. +// If the BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) OldCollectionAlignment(ctx context.Context) (v billing.AlignmentKind, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCollectionAlignment is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCollectionAlignment requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCollectionAlignment: %w", err) + } + return oldValue.CollectionAlignment, nil +} + +// ResetCollectionAlignment resets all changes to the "collection_alignment" field. +func (m *BillingWorkflowConfigMutation) ResetCollectionAlignment() { + m.collection_alignment = nil +} + +// SetAnchoredAlignmentDetail sets the "anchored_alignment_detail" field. +func (m *BillingWorkflowConfigMutation) SetAnchoredAlignmentDetail(bad *billing.AnchoredAlignmentDetail) { + m.anchored_alignment_detail = &bad +} + +// AnchoredAlignmentDetail returns the value of the "anchored_alignment_detail" field in the mutation. +func (m *BillingWorkflowConfigMutation) AnchoredAlignmentDetail() (r *billing.AnchoredAlignmentDetail, exists bool) { + v := m.anchored_alignment_detail + if v == nil { + return + } + return *v, true +} + +// OldAnchoredAlignmentDetail returns the old "anchored_alignment_detail" field's value of the BillingWorkflowConfig entity. +// If the BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) OldAnchoredAlignmentDetail(ctx context.Context) (v *billing.AnchoredAlignmentDetail, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAnchoredAlignmentDetail is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAnchoredAlignmentDetail requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAnchoredAlignmentDetail: %w", err) + } + return oldValue.AnchoredAlignmentDetail, nil +} + +// ClearAnchoredAlignmentDetail clears the value of the "anchored_alignment_detail" field. +func (m *BillingWorkflowConfigMutation) ClearAnchoredAlignmentDetail() { + m.anchored_alignment_detail = nil + m.clearedFields[billingworkflowconfig.FieldAnchoredAlignmentDetail] = struct{}{} +} + +// AnchoredAlignmentDetailCleared returns if the "anchored_alignment_detail" field was cleared in this mutation. +func (m *BillingWorkflowConfigMutation) AnchoredAlignmentDetailCleared() bool { + _, ok := m.clearedFields[billingworkflowconfig.FieldAnchoredAlignmentDetail] + return ok +} + +// ResetAnchoredAlignmentDetail resets all changes to the "anchored_alignment_detail" field. +func (m *BillingWorkflowConfigMutation) ResetAnchoredAlignmentDetail() { + m.anchored_alignment_detail = nil + delete(m.clearedFields, billingworkflowconfig.FieldAnchoredAlignmentDetail) +} + +// SetLineCollectionPeriod sets the "line_collection_period" field. +func (m *BillingWorkflowConfigMutation) SetLineCollectionPeriod(dds datetime.ISODurationString) { + m.line_collection_period = &dds +} + +// LineCollectionPeriod returns the value of the "line_collection_period" field in the mutation. +func (m *BillingWorkflowConfigMutation) LineCollectionPeriod() (r datetime.ISODurationString, exists bool) { + v := m.line_collection_period + if v == nil { + return + } + return *v, true +} + +// OldLineCollectionPeriod returns the old "line_collection_period" field's value of the BillingWorkflowConfig entity. +// If the BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) OldLineCollectionPeriod(ctx context.Context) (v datetime.ISODurationString, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLineCollectionPeriod is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLineCollectionPeriod requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLineCollectionPeriod: %w", err) + } + return oldValue.LineCollectionPeriod, nil +} + +// ResetLineCollectionPeriod resets all changes to the "line_collection_period" field. +func (m *BillingWorkflowConfigMutation) ResetLineCollectionPeriod() { + m.line_collection_period = nil +} + +// SetInvoiceAutoAdvance sets the "invoice_auto_advance" field. +func (m *BillingWorkflowConfigMutation) SetInvoiceAutoAdvance(b bool) { + m.invoice_auto_advance = &b +} + +// InvoiceAutoAdvance returns the value of the "invoice_auto_advance" field in the mutation. +func (m *BillingWorkflowConfigMutation) InvoiceAutoAdvance() (r bool, exists bool) { + v := m.invoice_auto_advance + if v == nil { + return + } + return *v, true +} + +// OldInvoiceAutoAdvance returns the old "invoice_auto_advance" field's value of the BillingWorkflowConfig entity. +// If the BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) OldInvoiceAutoAdvance(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceAutoAdvance is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceAutoAdvance requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceAutoAdvance: %w", err) + } + return oldValue.InvoiceAutoAdvance, nil +} + +// ResetInvoiceAutoAdvance resets all changes to the "invoice_auto_advance" field. +func (m *BillingWorkflowConfigMutation) ResetInvoiceAutoAdvance() { + m.invoice_auto_advance = nil +} + +// SetInvoiceDraftPeriod sets the "invoice_draft_period" field. +func (m *BillingWorkflowConfigMutation) SetInvoiceDraftPeriod(dds datetime.ISODurationString) { + m.invoice_draft_period = &dds +} + +// InvoiceDraftPeriod returns the value of the "invoice_draft_period" field in the mutation. +func (m *BillingWorkflowConfigMutation) InvoiceDraftPeriod() (r datetime.ISODurationString, exists bool) { + v := m.invoice_draft_period + if v == nil { + return + } + return *v, true +} + +// OldInvoiceDraftPeriod returns the old "invoice_draft_period" field's value of the BillingWorkflowConfig entity. +// If the BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) OldInvoiceDraftPeriod(ctx context.Context) (v datetime.ISODurationString, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceDraftPeriod is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceDraftPeriod requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceDraftPeriod: %w", err) + } + return oldValue.InvoiceDraftPeriod, nil +} + +// ResetInvoiceDraftPeriod resets all changes to the "invoice_draft_period" field. +func (m *BillingWorkflowConfigMutation) ResetInvoiceDraftPeriod() { + m.invoice_draft_period = nil +} + +// SetInvoiceDueAfter sets the "invoice_due_after" field. +func (m *BillingWorkflowConfigMutation) SetInvoiceDueAfter(dds datetime.ISODurationString) { + m.invoice_due_after = &dds +} + +// InvoiceDueAfter returns the value of the "invoice_due_after" field in the mutation. +func (m *BillingWorkflowConfigMutation) InvoiceDueAfter() (r datetime.ISODurationString, exists bool) { + v := m.invoice_due_after + if v == nil { + return + } + return *v, true +} + +// OldInvoiceDueAfter returns the old "invoice_due_after" field's value of the BillingWorkflowConfig entity. +// If the BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) OldInvoiceDueAfter(ctx context.Context) (v datetime.ISODurationString, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceDueAfter is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceDueAfter requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceDueAfter: %w", err) + } + return oldValue.InvoiceDueAfter, nil +} + +// ResetInvoiceDueAfter resets all changes to the "invoice_due_after" field. +func (m *BillingWorkflowConfigMutation) ResetInvoiceDueAfter() { + m.invoice_due_after = nil +} + +// SetInvoiceCollectionMethod sets the "invoice_collection_method" field. +func (m *BillingWorkflowConfigMutation) SetInvoiceCollectionMethod(bm billing.CollectionMethod) { + m.invoice_collection_method = &bm +} + +// InvoiceCollectionMethod returns the value of the "invoice_collection_method" field in the mutation. +func (m *BillingWorkflowConfigMutation) InvoiceCollectionMethod() (r billing.CollectionMethod, exists bool) { + v := m.invoice_collection_method + if v == nil { + return + } + return *v, true +} + +// OldInvoiceCollectionMethod returns the old "invoice_collection_method" field's value of the BillingWorkflowConfig entity. +// If the BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) OldInvoiceCollectionMethod(ctx context.Context) (v billing.CollectionMethod, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceCollectionMethod is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceCollectionMethod requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceCollectionMethod: %w", err) + } + return oldValue.InvoiceCollectionMethod, nil +} + +// ResetInvoiceCollectionMethod resets all changes to the "invoice_collection_method" field. +func (m *BillingWorkflowConfigMutation) ResetInvoiceCollectionMethod() { + m.invoice_collection_method = nil +} + +// SetInvoiceProgressiveBilling sets the "invoice_progressive_billing" field. +func (m *BillingWorkflowConfigMutation) SetInvoiceProgressiveBilling(b bool) { + m.invoice_progressive_billing = &b +} + +// InvoiceProgressiveBilling returns the value of the "invoice_progressive_billing" field in the mutation. +func (m *BillingWorkflowConfigMutation) InvoiceProgressiveBilling() (r bool, exists bool) { + v := m.invoice_progressive_billing + if v == nil { + return + } + return *v, true +} + +// OldInvoiceProgressiveBilling returns the old "invoice_progressive_billing" field's value of the BillingWorkflowConfig entity. +// If the BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) OldInvoiceProgressiveBilling(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceProgressiveBilling is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceProgressiveBilling requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceProgressiveBilling: %w", err) + } + return oldValue.InvoiceProgressiveBilling, nil +} + +// ResetInvoiceProgressiveBilling resets all changes to the "invoice_progressive_billing" field. +func (m *BillingWorkflowConfigMutation) ResetInvoiceProgressiveBilling() { + m.invoice_progressive_billing = nil +} + +// SetSubscriptionEndProrationMode sets the "subscription_end_proration_mode" field. +func (m *BillingWorkflowConfigMutation) SetSubscriptionEndProrationMode(bepm billing.SubscriptionEndProrationMode) { + m.subscription_end_proration_mode = &bepm +} + +// SubscriptionEndProrationMode returns the value of the "subscription_end_proration_mode" field in the mutation. +func (m *BillingWorkflowConfigMutation) SubscriptionEndProrationMode() (r billing.SubscriptionEndProrationMode, exists bool) { + v := m.subscription_end_proration_mode + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionEndProrationMode returns the old "subscription_end_proration_mode" field's value of the BillingWorkflowConfig entity. +// If the BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) OldSubscriptionEndProrationMode(ctx context.Context) (v billing.SubscriptionEndProrationMode, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionEndProrationMode is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionEndProrationMode requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionEndProrationMode: %w", err) + } + return oldValue.SubscriptionEndProrationMode, nil +} + +// ResetSubscriptionEndProrationMode resets all changes to the "subscription_end_proration_mode" field. +func (m *BillingWorkflowConfigMutation) ResetSubscriptionEndProrationMode() { + m.subscription_end_proration_mode = nil +} + +// SetInvoiceDefaultTaxSettings sets the "invoice_default_tax_settings" field. +func (m *BillingWorkflowConfigMutation) SetInvoiceDefaultTaxSettings(pc productcatalog.TaxConfig) { + m.invoice_default_tax_settings = &pc +} + +// InvoiceDefaultTaxSettings returns the value of the "invoice_default_tax_settings" field in the mutation. +func (m *BillingWorkflowConfigMutation) InvoiceDefaultTaxSettings() (r productcatalog.TaxConfig, exists bool) { + v := m.invoice_default_tax_settings + if v == nil { + return + } + return *v, true +} + +// OldInvoiceDefaultTaxSettings returns the old "invoice_default_tax_settings" field's value of the BillingWorkflowConfig entity. +// If the BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) OldInvoiceDefaultTaxSettings(ctx context.Context) (v productcatalog.TaxConfig, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceDefaultTaxSettings is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceDefaultTaxSettings requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceDefaultTaxSettings: %w", err) + } + return oldValue.InvoiceDefaultTaxSettings, nil +} + +// ClearInvoiceDefaultTaxSettings clears the value of the "invoice_default_tax_settings" field. +func (m *BillingWorkflowConfigMutation) ClearInvoiceDefaultTaxSettings() { + m.invoice_default_tax_settings = nil + m.clearedFields[billingworkflowconfig.FieldInvoiceDefaultTaxSettings] = struct{}{} +} + +// InvoiceDefaultTaxSettingsCleared returns if the "invoice_default_tax_settings" field was cleared in this mutation. +func (m *BillingWorkflowConfigMutation) InvoiceDefaultTaxSettingsCleared() bool { + _, ok := m.clearedFields[billingworkflowconfig.FieldInvoiceDefaultTaxSettings] + return ok +} + +// ResetInvoiceDefaultTaxSettings resets all changes to the "invoice_default_tax_settings" field. +func (m *BillingWorkflowConfigMutation) ResetInvoiceDefaultTaxSettings() { + m.invoice_default_tax_settings = nil + delete(m.clearedFields, billingworkflowconfig.FieldInvoiceDefaultTaxSettings) +} + +// SetTaxEnabled sets the "tax_enabled" field. +func (m *BillingWorkflowConfigMutation) SetTaxEnabled(b bool) { + m.tax_enabled = &b +} + +// TaxEnabled returns the value of the "tax_enabled" field in the mutation. +func (m *BillingWorkflowConfigMutation) TaxEnabled() (r bool, exists bool) { + v := m.tax_enabled + if v == nil { + return + } + return *v, true +} + +// OldTaxEnabled returns the old "tax_enabled" field's value of the BillingWorkflowConfig entity. +// If the BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) OldTaxEnabled(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxEnabled is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxEnabled requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxEnabled: %w", err) + } + return oldValue.TaxEnabled, nil +} + +// ResetTaxEnabled resets all changes to the "tax_enabled" field. +func (m *BillingWorkflowConfigMutation) ResetTaxEnabled() { + m.tax_enabled = nil +} + +// SetTaxEnforced sets the "tax_enforced" field. +func (m *BillingWorkflowConfigMutation) SetTaxEnforced(b bool) { + m.tax_enforced = &b +} + +// TaxEnforced returns the value of the "tax_enforced" field in the mutation. +func (m *BillingWorkflowConfigMutation) TaxEnforced() (r bool, exists bool) { + v := m.tax_enforced + if v == nil { + return + } + return *v, true +} + +// OldTaxEnforced returns the old "tax_enforced" field's value of the BillingWorkflowConfig entity. +// If the BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) OldTaxEnforced(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxEnforced is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxEnforced requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxEnforced: %w", err) + } + return oldValue.TaxEnforced, nil +} + +// ResetTaxEnforced resets all changes to the "tax_enforced" field. +func (m *BillingWorkflowConfigMutation) ResetTaxEnforced() { + m.tax_enforced = nil +} + +// SetBillingInvoicesID sets the "billing_invoices" edge to the BillingInvoice entity by id. +func (m *BillingWorkflowConfigMutation) SetBillingInvoicesID(id string) { + m.billing_invoices = &id +} + +// ClearBillingInvoices clears the "billing_invoices" edge to the BillingInvoice entity. +func (m *BillingWorkflowConfigMutation) ClearBillingInvoices() { + m.clearedbilling_invoices = true +} + +// BillingInvoicesCleared reports if the "billing_invoices" edge to the BillingInvoice entity was cleared. +func (m *BillingWorkflowConfigMutation) BillingInvoicesCleared() bool { + return m.clearedbilling_invoices +} + +// BillingInvoicesID returns the "billing_invoices" edge ID in the mutation. +func (m *BillingWorkflowConfigMutation) BillingInvoicesID() (id string, exists bool) { + if m.billing_invoices != nil { + return *m.billing_invoices, true + } + return +} + +// BillingInvoicesIDs returns the "billing_invoices" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BillingInvoicesID instead. It exists only for internal usage by the builders. +func (m *BillingWorkflowConfigMutation) BillingInvoicesIDs() (ids []string) { + if id := m.billing_invoices; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBillingInvoices resets all changes to the "billing_invoices" edge. +func (m *BillingWorkflowConfigMutation) ResetBillingInvoices() { + m.billing_invoices = nil + m.clearedbilling_invoices = false +} + +// SetBillingProfileID sets the "billing_profile" edge to the BillingProfile entity by id. +func (m *BillingWorkflowConfigMutation) SetBillingProfileID(id string) { + m.billing_profile = &id +} + +// ClearBillingProfile clears the "billing_profile" edge to the BillingProfile entity. +func (m *BillingWorkflowConfigMutation) ClearBillingProfile() { + m.clearedbilling_profile = true +} + +// BillingProfileCleared reports if the "billing_profile" edge to the BillingProfile entity was cleared. +func (m *BillingWorkflowConfigMutation) BillingProfileCleared() bool { + return m.clearedbilling_profile +} + +// BillingProfileID returns the "billing_profile" edge ID in the mutation. +func (m *BillingWorkflowConfigMutation) BillingProfileID() (id string, exists bool) { + if m.billing_profile != nil { + return *m.billing_profile, true + } + return +} + +// BillingProfileIDs returns the "billing_profile" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BillingProfileID instead. It exists only for internal usage by the builders. +func (m *BillingWorkflowConfigMutation) BillingProfileIDs() (ids []string) { + if id := m.billing_profile; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBillingProfile resets all changes to the "billing_profile" edge. +func (m *BillingWorkflowConfigMutation) ResetBillingProfile() { + m.billing_profile = nil + m.clearedbilling_profile = false +} + +// ClearTaxCode clears the "tax_code" edge to the TaxCode entity. +func (m *BillingWorkflowConfigMutation) ClearTaxCode() { + m.clearedtax_code = true + m.clearedFields[billingworkflowconfig.FieldTaxCodeID] = struct{}{} +} + +// TaxCodeCleared reports if the "tax_code" edge to the TaxCode entity was cleared. +func (m *BillingWorkflowConfigMutation) TaxCodeCleared() bool { + return m.TaxCodeIDCleared() || m.clearedtax_code +} + +// TaxCodeIDs returns the "tax_code" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TaxCodeID instead. It exists only for internal usage by the builders. +func (m *BillingWorkflowConfigMutation) TaxCodeIDs() (ids []string) { + if id := m.tax_code; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTaxCode resets all changes to the "tax_code" edge. +func (m *BillingWorkflowConfigMutation) ResetTaxCode() { + m.tax_code = nil + m.clearedtax_code = false +} + +// Where appends a list predicates to the BillingWorkflowConfigMutation builder. +func (m *BillingWorkflowConfigMutation) Where(ps ...predicate.BillingWorkflowConfig) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BillingWorkflowConfigMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BillingWorkflowConfigMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillingWorkflowConfig, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BillingWorkflowConfigMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BillingWorkflowConfigMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BillingWorkflowConfig). +func (m *BillingWorkflowConfigMutation) 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 *BillingWorkflowConfigMutation) Fields() []string { + fields := make([]string, 0, 18) + if m.namespace != nil { + fields = append(fields, billingworkflowconfig.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, billingworkflowconfig.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, billingworkflowconfig.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, billingworkflowconfig.FieldDeletedAt) + } + if m.tax_code != nil { + fields = append(fields, billingworkflowconfig.FieldTaxCodeID) + } + if m.tax_behavior != nil { + fields = append(fields, billingworkflowconfig.FieldTaxBehavior) + } + if m.collection_alignment != nil { + fields = append(fields, billingworkflowconfig.FieldCollectionAlignment) + } + if m.anchored_alignment_detail != nil { + fields = append(fields, billingworkflowconfig.FieldAnchoredAlignmentDetail) + } + if m.line_collection_period != nil { + fields = append(fields, billingworkflowconfig.FieldLineCollectionPeriod) + } + if m.invoice_auto_advance != nil { + fields = append(fields, billingworkflowconfig.FieldInvoiceAutoAdvance) + } + if m.invoice_draft_period != nil { + fields = append(fields, billingworkflowconfig.FieldInvoiceDraftPeriod) + } + if m.invoice_due_after != nil { + fields = append(fields, billingworkflowconfig.FieldInvoiceDueAfter) + } + if m.invoice_collection_method != nil { + fields = append(fields, billingworkflowconfig.FieldInvoiceCollectionMethod) + } + if m.invoice_progressive_billing != nil { + fields = append(fields, billingworkflowconfig.FieldInvoiceProgressiveBilling) + } + if m.subscription_end_proration_mode != nil { + fields = append(fields, billingworkflowconfig.FieldSubscriptionEndProrationMode) + } + if m.invoice_default_tax_settings != nil { + fields = append(fields, billingworkflowconfig.FieldInvoiceDefaultTaxSettings) + } + if m.tax_enabled != nil { + fields = append(fields, billingworkflowconfig.FieldTaxEnabled) + } + if m.tax_enforced != nil { + fields = append(fields, billingworkflowconfig.FieldTaxEnforced) + } + 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 *BillingWorkflowConfigMutation) Field(name string) (ent.Value, bool) { + switch name { + case billingworkflowconfig.FieldNamespace: + return m.Namespace() + case billingworkflowconfig.FieldCreatedAt: + return m.CreatedAt() + case billingworkflowconfig.FieldUpdatedAt: + return m.UpdatedAt() + case billingworkflowconfig.FieldDeletedAt: + return m.DeletedAt() + case billingworkflowconfig.FieldTaxCodeID: + return m.TaxCodeID() + case billingworkflowconfig.FieldTaxBehavior: + return m.TaxBehavior() + case billingworkflowconfig.FieldCollectionAlignment: + return m.CollectionAlignment() + case billingworkflowconfig.FieldAnchoredAlignmentDetail: + return m.AnchoredAlignmentDetail() + case billingworkflowconfig.FieldLineCollectionPeriod: + return m.LineCollectionPeriod() + case billingworkflowconfig.FieldInvoiceAutoAdvance: + return m.InvoiceAutoAdvance() + case billingworkflowconfig.FieldInvoiceDraftPeriod: + return m.InvoiceDraftPeriod() + case billingworkflowconfig.FieldInvoiceDueAfter: + return m.InvoiceDueAfter() + case billingworkflowconfig.FieldInvoiceCollectionMethod: + return m.InvoiceCollectionMethod() + case billingworkflowconfig.FieldInvoiceProgressiveBilling: + return m.InvoiceProgressiveBilling() + case billingworkflowconfig.FieldSubscriptionEndProrationMode: + return m.SubscriptionEndProrationMode() + case billingworkflowconfig.FieldInvoiceDefaultTaxSettings: + return m.InvoiceDefaultTaxSettings() + case billingworkflowconfig.FieldTaxEnabled: + return m.TaxEnabled() + case billingworkflowconfig.FieldTaxEnforced: + return m.TaxEnforced() + } + 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 *BillingWorkflowConfigMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case billingworkflowconfig.FieldNamespace: + return m.OldNamespace(ctx) + case billingworkflowconfig.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case billingworkflowconfig.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case billingworkflowconfig.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case billingworkflowconfig.FieldTaxCodeID: + return m.OldTaxCodeID(ctx) + case billingworkflowconfig.FieldTaxBehavior: + return m.OldTaxBehavior(ctx) + case billingworkflowconfig.FieldCollectionAlignment: + return m.OldCollectionAlignment(ctx) + case billingworkflowconfig.FieldAnchoredAlignmentDetail: + return m.OldAnchoredAlignmentDetail(ctx) + case billingworkflowconfig.FieldLineCollectionPeriod: + return m.OldLineCollectionPeriod(ctx) + case billingworkflowconfig.FieldInvoiceAutoAdvance: + return m.OldInvoiceAutoAdvance(ctx) + case billingworkflowconfig.FieldInvoiceDraftPeriod: + return m.OldInvoiceDraftPeriod(ctx) + case billingworkflowconfig.FieldInvoiceDueAfter: + return m.OldInvoiceDueAfter(ctx) + case billingworkflowconfig.FieldInvoiceCollectionMethod: + return m.OldInvoiceCollectionMethod(ctx) + case billingworkflowconfig.FieldInvoiceProgressiveBilling: + return m.OldInvoiceProgressiveBilling(ctx) + case billingworkflowconfig.FieldSubscriptionEndProrationMode: + return m.OldSubscriptionEndProrationMode(ctx) + case billingworkflowconfig.FieldInvoiceDefaultTaxSettings: + return m.OldInvoiceDefaultTaxSettings(ctx) + case billingworkflowconfig.FieldTaxEnabled: + return m.OldTaxEnabled(ctx) + case billingworkflowconfig.FieldTaxEnforced: + return m.OldTaxEnforced(ctx) + } + return nil, fmt.Errorf("unknown BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) SetField(name string, value ent.Value) error { + switch name { + case billingworkflowconfig.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case billingworkflowconfig.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 billingworkflowconfig.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 billingworkflowconfig.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 billingworkflowconfig.FieldTaxCodeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxCodeID(v) + return nil + case billingworkflowconfig.FieldTaxBehavior: + v, ok := value.(productcatalog.TaxBehavior) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxBehavior(v) + return nil + case billingworkflowconfig.FieldCollectionAlignment: + v, ok := value.(billing.AlignmentKind) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCollectionAlignment(v) + return nil + case billingworkflowconfig.FieldAnchoredAlignmentDetail: + v, ok := value.(*billing.AnchoredAlignmentDetail) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAnchoredAlignmentDetail(v) + return nil + case billingworkflowconfig.FieldLineCollectionPeriod: + v, ok := value.(datetime.ISODurationString) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLineCollectionPeriod(v) + return nil + case billingworkflowconfig.FieldInvoiceAutoAdvance: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceAutoAdvance(v) + return nil + case billingworkflowconfig.FieldInvoiceDraftPeriod: + v, ok := value.(datetime.ISODurationString) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceDraftPeriod(v) + return nil + case billingworkflowconfig.FieldInvoiceDueAfter: + v, ok := value.(datetime.ISODurationString) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceDueAfter(v) + return nil + case billingworkflowconfig.FieldInvoiceCollectionMethod: + v, ok := value.(billing.CollectionMethod) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceCollectionMethod(v) + return nil + case billingworkflowconfig.FieldInvoiceProgressiveBilling: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceProgressiveBilling(v) + return nil + case billingworkflowconfig.FieldSubscriptionEndProrationMode: + v, ok := value.(billing.SubscriptionEndProrationMode) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionEndProrationMode(v) + return nil + case billingworkflowconfig.FieldInvoiceDefaultTaxSettings: + v, ok := value.(productcatalog.TaxConfig) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceDefaultTaxSettings(v) + return nil + case billingworkflowconfig.FieldTaxEnabled: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxEnabled(v) + return nil + case billingworkflowconfig.FieldTaxEnforced: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxEnforced(v) + return nil + } + return fmt.Errorf("unknown BillingWorkflowConfig field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BillingWorkflowConfigMutation) 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 *BillingWorkflowConfigMutation) 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 *BillingWorkflowConfigMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown BillingWorkflowConfig numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BillingWorkflowConfigMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(billingworkflowconfig.FieldDeletedAt) { + fields = append(fields, billingworkflowconfig.FieldDeletedAt) + } + if m.FieldCleared(billingworkflowconfig.FieldTaxCodeID) { + fields = append(fields, billingworkflowconfig.FieldTaxCodeID) + } + if m.FieldCleared(billingworkflowconfig.FieldTaxBehavior) { + fields = append(fields, billingworkflowconfig.FieldTaxBehavior) + } + if m.FieldCleared(billingworkflowconfig.FieldAnchoredAlignmentDetail) { + fields = append(fields, billingworkflowconfig.FieldAnchoredAlignmentDetail) + } + if m.FieldCleared(billingworkflowconfig.FieldInvoiceDefaultTaxSettings) { + fields = append(fields, billingworkflowconfig.FieldInvoiceDefaultTaxSettings) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BillingWorkflowConfigMutation) 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 *BillingWorkflowConfigMutation) ClearField(name string) error { + switch name { + case billingworkflowconfig.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case billingworkflowconfig.FieldTaxCodeID: + m.ClearTaxCodeID() + return nil + case billingworkflowconfig.FieldTaxBehavior: + m.ClearTaxBehavior() + return nil + case billingworkflowconfig.FieldAnchoredAlignmentDetail: + m.ClearAnchoredAlignmentDetail() + return nil + case billingworkflowconfig.FieldInvoiceDefaultTaxSettings: + m.ClearInvoiceDefaultTaxSettings() + return nil + } + return fmt.Errorf("unknown BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) ResetField(name string) error { + switch name { + case billingworkflowconfig.FieldNamespace: + m.ResetNamespace() + return nil + case billingworkflowconfig.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case billingworkflowconfig.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case billingworkflowconfig.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case billingworkflowconfig.FieldTaxCodeID: + m.ResetTaxCodeID() + return nil + case billingworkflowconfig.FieldTaxBehavior: + m.ResetTaxBehavior() + return nil + case billingworkflowconfig.FieldCollectionAlignment: + m.ResetCollectionAlignment() + return nil + case billingworkflowconfig.FieldAnchoredAlignmentDetail: + m.ResetAnchoredAlignmentDetail() + return nil + case billingworkflowconfig.FieldLineCollectionPeriod: + m.ResetLineCollectionPeriod() + return nil + case billingworkflowconfig.FieldInvoiceAutoAdvance: + m.ResetInvoiceAutoAdvance() + return nil + case billingworkflowconfig.FieldInvoiceDraftPeriod: + m.ResetInvoiceDraftPeriod() + return nil + case billingworkflowconfig.FieldInvoiceDueAfter: + m.ResetInvoiceDueAfter() + return nil + case billingworkflowconfig.FieldInvoiceCollectionMethod: + m.ResetInvoiceCollectionMethod() + return nil + case billingworkflowconfig.FieldInvoiceProgressiveBilling: + m.ResetInvoiceProgressiveBilling() + return nil + case billingworkflowconfig.FieldSubscriptionEndProrationMode: + m.ResetSubscriptionEndProrationMode() + return nil + case billingworkflowconfig.FieldInvoiceDefaultTaxSettings: + m.ResetInvoiceDefaultTaxSettings() + return nil + case billingworkflowconfig.FieldTaxEnabled: + m.ResetTaxEnabled() + return nil + case billingworkflowconfig.FieldTaxEnforced: + m.ResetTaxEnforced() + return nil + } + return fmt.Errorf("unknown BillingWorkflowConfig field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BillingWorkflowConfigMutation) AddedEdges() []string { + edges := make([]string, 0, 3) + if m.billing_invoices != nil { + edges = append(edges, billingworkflowconfig.EdgeBillingInvoices) + } + if m.billing_profile != nil { + edges = append(edges, billingworkflowconfig.EdgeBillingProfile) + } + if m.tax_code != nil { + edges = append(edges, billingworkflowconfig.EdgeTaxCode) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BillingWorkflowConfigMutation) AddedIDs(name string) []ent.Value { + switch name { + case billingworkflowconfig.EdgeBillingInvoices: + if id := m.billing_invoices; id != nil { + return []ent.Value{*id} + } + case billingworkflowconfig.EdgeBillingProfile: + if id := m.billing_profile; id != nil { + return []ent.Value{*id} + } + case billingworkflowconfig.EdgeTaxCode: + if id := m.tax_code; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BillingWorkflowConfigMutation) RemovedEdges() []string { + edges := make([]string, 0, 3) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *BillingWorkflowConfigMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BillingWorkflowConfigMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) + if m.clearedbilling_invoices { + edges = append(edges, billingworkflowconfig.EdgeBillingInvoices) + } + if m.clearedbilling_profile { + edges = append(edges, billingworkflowconfig.EdgeBillingProfile) + } + if m.clearedtax_code { + edges = append(edges, billingworkflowconfig.EdgeTaxCode) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BillingWorkflowConfigMutation) EdgeCleared(name string) bool { + switch name { + case billingworkflowconfig.EdgeBillingInvoices: + return m.clearedbilling_invoices + case billingworkflowconfig.EdgeBillingProfile: + return m.clearedbilling_profile + case billingworkflowconfig.EdgeTaxCode: + return m.clearedtax_code + } + 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 *BillingWorkflowConfigMutation) ClearEdge(name string) error { + switch name { + case billingworkflowconfig.EdgeBillingInvoices: + m.ClearBillingInvoices() + return nil + case billingworkflowconfig.EdgeBillingProfile: + m.ClearBillingProfile() + return nil + case billingworkflowconfig.EdgeTaxCode: + m.ClearTaxCode() + return nil + } + return fmt.Errorf("unknown BillingWorkflowConfig 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 *BillingWorkflowConfigMutation) ResetEdge(name string) error { + switch name { + case billingworkflowconfig.EdgeBillingInvoices: + m.ResetBillingInvoices() + return nil + case billingworkflowconfig.EdgeBillingProfile: + m.ResetBillingProfile() + return nil + case billingworkflowconfig.EdgeTaxCode: + m.ResetTaxCode() + return nil + } + return fmt.Errorf("unknown BillingWorkflowConfig edge %s", name) +} + +// ChargeMutation represents an operation that mutates the Charge nodes in the graph. +type ChargeMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + deleted_at *time.Time + unique_reference_id *string + _type *meta.ChargeType + clearedFields map[string]struct{} + flat_fee *string + 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 + billing_split_line_groups map[string]struct{} + removedbilling_split_line_groups map[string]struct{} + clearedbilling_split_line_groups bool + credit_realization_lineages map[string]struct{} + removedcredit_realization_lineages map[string]struct{} + clearedcredit_realization_lineages bool + done bool + oldValue func(context.Context) (*Charge, error) + predicates []predicate.Charge +} + +var _ ent.Mutation = (*ChargeMutation)(nil) + +// chargeOption allows management of the mutation configuration using functional options. +type chargeOption func(*ChargeMutation) + +// newChargeMutation creates new mutation for the Charge entity. +func newChargeMutation(c config, op Op, opts ...chargeOption) *ChargeMutation { + m := &ChargeMutation{ + config: c, + op: op, + typ: TypeCharge, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withChargeID sets the ID field of the mutation. +func withChargeID(id string) chargeOption { + return func(m *ChargeMutation) { + var ( + err error + once sync.Once + value *Charge + ) + m.oldValue = func(ctx context.Context) (*Charge, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Charge.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withCharge sets the old Charge of the mutation. +func withCharge(node *Charge) chargeOption { + return func(m *ChargeMutation) { + m.oldValue = func(context.Context) (*Charge, 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 ChargeMutation) 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 ChargeMutation) 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 Charge entities. +func (m *ChargeMutation) 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 *ChargeMutation) 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 *ChargeMutation) 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().Charge.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 *ChargeMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *ChargeMutation) 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 Charge entity. +// If the Charge 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 *ChargeMutation) 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 *ChargeMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *ChargeMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ChargeMutation) 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 Charge entity. +// If the Charge 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 *ChargeMutation) 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 *ChargeMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *ChargeMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *ChargeMutation) 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 Charge entity. +// If the Charge 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 *ChargeMutation) 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 *ChargeMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[charge.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *ChargeMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[charge.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *ChargeMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, charge.FieldDeletedAt) +} + +// SetUniqueReferenceID sets the "unique_reference_id" field. +func (m *ChargeMutation) SetUniqueReferenceID(s string) { + m.unique_reference_id = &s +} + +// UniqueReferenceID returns the value of the "unique_reference_id" field in the mutation. +func (m *ChargeMutation) UniqueReferenceID() (r string, exists bool) { + v := m.unique_reference_id + if v == nil { + return + } + return *v, true +} + +// OldUniqueReferenceID returns the old "unique_reference_id" field's value of the Charge entity. +// If the Charge 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 *ChargeMutation) OldUniqueReferenceID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUniqueReferenceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUniqueReferenceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUniqueReferenceID: %w", err) + } + return oldValue.UniqueReferenceID, nil +} + +// ClearUniqueReferenceID clears the value of the "unique_reference_id" field. +func (m *ChargeMutation) ClearUniqueReferenceID() { + m.unique_reference_id = nil + m.clearedFields[charge.FieldUniqueReferenceID] = struct{}{} +} + +// UniqueReferenceIDCleared returns if the "unique_reference_id" field was cleared in this mutation. +func (m *ChargeMutation) UniqueReferenceIDCleared() bool { + _, ok := m.clearedFields[charge.FieldUniqueReferenceID] + return ok +} + +// ResetUniqueReferenceID resets all changes to the "unique_reference_id" field. +func (m *ChargeMutation) ResetUniqueReferenceID() { + m.unique_reference_id = nil + delete(m.clearedFields, charge.FieldUniqueReferenceID) +} + +// SetType sets the "type" field. +func (m *ChargeMutation) SetType(mt meta.ChargeType) { + m._type = &mt +} + +// GetType returns the value of the "type" field in the mutation. +func (m *ChargeMutation) GetType() (r meta.ChargeType, exists bool) { + v := m._type + if v == nil { + return + } + return *v, true +} + +// OldType returns the old "type" field's value of the Charge entity. +// If the Charge 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 *ChargeMutation) OldType(ctx context.Context) (v meta.ChargeType, 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 *ChargeMutation) ResetType() { + m._type = nil +} + +// SetChargeFlatFeeID sets the "charge_flat_fee_id" field. +func (m *ChargeMutation) SetChargeFlatFeeID(s string) { + m.flat_fee = &s +} + +// ChargeFlatFeeID returns the value of the "charge_flat_fee_id" field in the mutation. +func (m *ChargeMutation) ChargeFlatFeeID() (r string, exists bool) { + v := m.flat_fee + if v == nil { + return + } + return *v, true +} + +// OldChargeFlatFeeID returns the old "charge_flat_fee_id" field's value of the Charge entity. +// If the Charge 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 *ChargeMutation) OldChargeFlatFeeID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldChargeFlatFeeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldChargeFlatFeeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldChargeFlatFeeID: %w", err) + } + return oldValue.ChargeFlatFeeID, nil +} + +// ClearChargeFlatFeeID clears the value of the "charge_flat_fee_id" field. +func (m *ChargeMutation) ClearChargeFlatFeeID() { + m.flat_fee = nil + m.clearedFields[charge.FieldChargeFlatFeeID] = struct{}{} +} + +// ChargeFlatFeeIDCleared returns if the "charge_flat_fee_id" field was cleared in this mutation. +func (m *ChargeMutation) ChargeFlatFeeIDCleared() bool { + _, ok := m.clearedFields[charge.FieldChargeFlatFeeID] + return ok +} + +// ResetChargeFlatFeeID resets all changes to the "charge_flat_fee_id" field. +func (m *ChargeMutation) ResetChargeFlatFeeID() { + m.flat_fee = nil + delete(m.clearedFields, charge.FieldChargeFlatFeeID) +} + +// SetChargeCreditPurchaseID sets the "charge_credit_purchase_id" field. +func (m *ChargeMutation) SetChargeCreditPurchaseID(s string) { + m.credit_purchase = &s +} + +// ChargeCreditPurchaseID returns the value of the "charge_credit_purchase_id" field in the mutation. +func (m *ChargeMutation) ChargeCreditPurchaseID() (r string, exists bool) { + v := m.credit_purchase + if v == nil { + return + } + return *v, true +} + +// OldChargeCreditPurchaseID returns the old "charge_credit_purchase_id" field's value of the Charge entity. +// If the Charge 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 *ChargeMutation) OldChargeCreditPurchaseID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldChargeCreditPurchaseID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldChargeCreditPurchaseID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldChargeCreditPurchaseID: %w", err) + } + return oldValue.ChargeCreditPurchaseID, nil +} + +// ClearChargeCreditPurchaseID clears the value of the "charge_credit_purchase_id" field. +func (m *ChargeMutation) ClearChargeCreditPurchaseID() { + m.credit_purchase = nil + m.clearedFields[charge.FieldChargeCreditPurchaseID] = struct{}{} +} + +// ChargeCreditPurchaseIDCleared returns if the "charge_credit_purchase_id" field was cleared in this mutation. +func (m *ChargeMutation) ChargeCreditPurchaseIDCleared() bool { + _, ok := m.clearedFields[charge.FieldChargeCreditPurchaseID] + return ok +} + +// ResetChargeCreditPurchaseID resets all changes to the "charge_credit_purchase_id" field. +func (m *ChargeMutation) ResetChargeCreditPurchaseID() { + m.credit_purchase = nil + delete(m.clearedFields, charge.FieldChargeCreditPurchaseID) +} + +// SetChargeUsageBasedID sets the "charge_usage_based_id" field. +func (m *ChargeMutation) SetChargeUsageBasedID(s string) { + m.usage_based = &s +} + +// ChargeUsageBasedID returns the value of the "charge_usage_based_id" field in the mutation. +func (m *ChargeMutation) ChargeUsageBasedID() (r string, exists bool) { + v := m.usage_based + if v == nil { + return + } + return *v, true +} + +// OldChargeUsageBasedID returns the old "charge_usage_based_id" field's value of the Charge entity. +// If the Charge 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 *ChargeMutation) OldChargeUsageBasedID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldChargeUsageBasedID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldChargeUsageBasedID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldChargeUsageBasedID: %w", err) + } + return oldValue.ChargeUsageBasedID, nil +} + +// ClearChargeUsageBasedID clears the value of the "charge_usage_based_id" field. +func (m *ChargeMutation) ClearChargeUsageBasedID() { + m.usage_based = nil + m.clearedFields[charge.FieldChargeUsageBasedID] = struct{}{} +} + +// ChargeUsageBasedIDCleared returns if the "charge_usage_based_id" field was cleared in this mutation. +func (m *ChargeMutation) ChargeUsageBasedIDCleared() bool { + _, ok := m.clearedFields[charge.FieldChargeUsageBasedID] + return ok +} + +// ResetChargeUsageBasedID resets all changes to the "charge_usage_based_id" field. +func (m *ChargeMutation) ResetChargeUsageBasedID() { + m.usage_based = nil + delete(m.clearedFields, charge.FieldChargeUsageBasedID) +} + +// SetFlatFeeID sets the "flat_fee" edge to the ChargeFlatFee entity by id. +func (m *ChargeMutation) SetFlatFeeID(id string) { + m.flat_fee = &id +} + +// ClearFlatFee clears the "flat_fee" edge to the ChargeFlatFee entity. +func (m *ChargeMutation) ClearFlatFee() { + m.clearedflat_fee = true + m.clearedFields[charge.FieldChargeFlatFeeID] = struct{}{} +} + +// FlatFeeCleared reports if the "flat_fee" edge to the ChargeFlatFee entity was cleared. +func (m *ChargeMutation) FlatFeeCleared() bool { + return m.ChargeFlatFeeIDCleared() || m.clearedflat_fee +} + +// FlatFeeID returns the "flat_fee" edge ID in the mutation. +func (m *ChargeMutation) FlatFeeID() (id string, exists bool) { + if m.flat_fee != nil { + return *m.flat_fee, true + } + return +} + +// FlatFeeIDs returns the "flat_fee" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// FlatFeeID instead. It exists only for internal usage by the builders. +func (m *ChargeMutation) FlatFeeIDs() (ids []string) { + if id := m.flat_fee; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetFlatFee resets all changes to the "flat_fee" edge. +func (m *ChargeMutation) ResetFlatFee() { + m.flat_fee = nil + m.clearedflat_fee = false +} + +// SetCreditPurchaseID sets the "credit_purchase" edge to the ChargeCreditPurchase entity by id. +func (m *ChargeMutation) SetCreditPurchaseID(id string) { + m.credit_purchase = &id +} + +// ClearCreditPurchase clears the "credit_purchase" edge to the ChargeCreditPurchase entity. +func (m *ChargeMutation) ClearCreditPurchase() { + m.clearedcredit_purchase = true + m.clearedFields[charge.FieldChargeCreditPurchaseID] = struct{}{} +} + +// CreditPurchaseCleared reports if the "credit_purchase" edge to the ChargeCreditPurchase entity was cleared. +func (m *ChargeMutation) CreditPurchaseCleared() bool { + return m.ChargeCreditPurchaseIDCleared() || m.clearedcredit_purchase +} + +// CreditPurchaseID returns the "credit_purchase" edge ID in the mutation. +func (m *ChargeMutation) CreditPurchaseID() (id string, exists bool) { + if m.credit_purchase != nil { + return *m.credit_purchase, true + } + return +} + +// CreditPurchaseIDs returns the "credit_purchase" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CreditPurchaseID instead. It exists only for internal usage by the builders. +func (m *ChargeMutation) CreditPurchaseIDs() (ids []string) { + if id := m.credit_purchase; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCreditPurchase resets all changes to the "credit_purchase" edge. +func (m *ChargeMutation) ResetCreditPurchase() { + m.credit_purchase = nil + 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 + m.clearedFields[charge.FieldChargeUsageBasedID] = struct{}{} +} + +// UsageBasedCleared reports if the "usage_based" edge to the ChargeUsageBased entity was cleared. +func (m *ChargeMutation) UsageBasedCleared() bool { + return m.ChargeUsageBasedIDCleared() || 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 { + m.billing_invoice_lines = make(map[string]struct{}) + } + for i := range ids { + m.billing_invoice_lines[ids[i]] = struct{}{} + } +} + +// ClearBillingInvoiceLines clears the "billing_invoice_lines" edge to the BillingInvoiceLine entity. +func (m *ChargeMutation) ClearBillingInvoiceLines() { + m.clearedbilling_invoice_lines = true +} + +// BillingInvoiceLinesCleared reports if the "billing_invoice_lines" edge to the BillingInvoiceLine entity was cleared. +func (m *ChargeMutation) BillingInvoiceLinesCleared() bool { + return m.clearedbilling_invoice_lines +} + +// RemoveBillingInvoiceLineIDs removes the "billing_invoice_lines" edge to the BillingInvoiceLine entity by IDs. +func (m *ChargeMutation) RemoveBillingInvoiceLineIDs(ids ...string) { + if m.removedbilling_invoice_lines == nil { + m.removedbilling_invoice_lines = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_invoice_lines, ids[i]) + m.removedbilling_invoice_lines[ids[i]] = struct{}{} + } +} + +// RemovedBillingInvoiceLines returns the removed IDs of the "billing_invoice_lines" edge to the BillingInvoiceLine entity. +func (m *ChargeMutation) RemovedBillingInvoiceLinesIDs() (ids []string) { + for id := range m.removedbilling_invoice_lines { + ids = append(ids, id) + } + return +} + +// BillingInvoiceLinesIDs returns the "billing_invoice_lines" edge IDs in the mutation. +func (m *ChargeMutation) BillingInvoiceLinesIDs() (ids []string) { + for id := range m.billing_invoice_lines { + ids = append(ids, id) + } + return +} + +// ResetBillingInvoiceLines resets all changes to the "billing_invoice_lines" edge. +func (m *ChargeMutation) ResetBillingInvoiceLines() { + m.billing_invoice_lines = nil + m.clearedbilling_invoice_lines = false + m.removedbilling_invoice_lines = nil +} + +// AddBillingSplitLineGroupIDs adds the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity by ids. +func (m *ChargeMutation) AddBillingSplitLineGroupIDs(ids ...string) { + if m.billing_split_line_groups == nil { + m.billing_split_line_groups = make(map[string]struct{}) + } + for i := range ids { + m.billing_split_line_groups[ids[i]] = struct{}{} + } +} + +// ClearBillingSplitLineGroups clears the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity. +func (m *ChargeMutation) ClearBillingSplitLineGroups() { + m.clearedbilling_split_line_groups = true +} + +// BillingSplitLineGroupsCleared reports if the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity was cleared. +func (m *ChargeMutation) BillingSplitLineGroupsCleared() bool { + return m.clearedbilling_split_line_groups +} + +// RemoveBillingSplitLineGroupIDs removes the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity by IDs. +func (m *ChargeMutation) RemoveBillingSplitLineGroupIDs(ids ...string) { + if m.removedbilling_split_line_groups == nil { + m.removedbilling_split_line_groups = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_split_line_groups, ids[i]) + m.removedbilling_split_line_groups[ids[i]] = struct{}{} + } +} + +// RemovedBillingSplitLineGroups returns the removed IDs of the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity. +func (m *ChargeMutation) RemovedBillingSplitLineGroupsIDs() (ids []string) { + for id := range m.removedbilling_split_line_groups { + ids = append(ids, id) + } + return +} + +// BillingSplitLineGroupsIDs returns the "billing_split_line_groups" edge IDs in the mutation. +func (m *ChargeMutation) BillingSplitLineGroupsIDs() (ids []string) { + for id := range m.billing_split_line_groups { + ids = append(ids, id) + } + return +} + +// ResetBillingSplitLineGroups resets all changes to the "billing_split_line_groups" edge. +func (m *ChargeMutation) ResetBillingSplitLineGroups() { + m.billing_split_line_groups = nil + m.clearedbilling_split_line_groups = false + m.removedbilling_split_line_groups = nil +} + +// AddCreditRealizationLineageIDs adds the "credit_realization_lineages" edge to the CreditRealizationLineage entity by ids. +func (m *ChargeMutation) AddCreditRealizationLineageIDs(ids ...string) { + if m.credit_realization_lineages == nil { + m.credit_realization_lineages = make(map[string]struct{}) + } + for i := range ids { + m.credit_realization_lineages[ids[i]] = struct{}{} + } +} + +// ClearCreditRealizationLineages clears the "credit_realization_lineages" edge to the CreditRealizationLineage entity. +func (m *ChargeMutation) ClearCreditRealizationLineages() { + m.clearedcredit_realization_lineages = true +} + +// CreditRealizationLineagesCleared reports if the "credit_realization_lineages" edge to the CreditRealizationLineage entity was cleared. +func (m *ChargeMutation) CreditRealizationLineagesCleared() bool { + return m.clearedcredit_realization_lineages +} + +// RemoveCreditRealizationLineageIDs removes the "credit_realization_lineages" edge to the CreditRealizationLineage entity by IDs. +func (m *ChargeMutation) RemoveCreditRealizationLineageIDs(ids ...string) { + if m.removedcredit_realization_lineages == nil { + m.removedcredit_realization_lineages = make(map[string]struct{}) + } + for i := range ids { + delete(m.credit_realization_lineages, ids[i]) + m.removedcredit_realization_lineages[ids[i]] = struct{}{} + } +} + +// RemovedCreditRealizationLineages returns the removed IDs of the "credit_realization_lineages" edge to the CreditRealizationLineage entity. +func (m *ChargeMutation) RemovedCreditRealizationLineagesIDs() (ids []string) { + for id := range m.removedcredit_realization_lineages { + ids = append(ids, id) + } + return +} + +// CreditRealizationLineagesIDs returns the "credit_realization_lineages" edge IDs in the mutation. +func (m *ChargeMutation) CreditRealizationLineagesIDs() (ids []string) { + for id := range m.credit_realization_lineages { + ids = append(ids, id) + } + return +} + +// ResetCreditRealizationLineages resets all changes to the "credit_realization_lineages" edge. +func (m *ChargeMutation) ResetCreditRealizationLineages() { + m.credit_realization_lineages = nil + m.clearedcredit_realization_lineages = false + m.removedcredit_realization_lineages = nil +} + +// Where appends a list predicates to the ChargeMutation builder. +func (m *ChargeMutation) Where(ps ...predicate.Charge) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ChargeMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ChargeMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Charge, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ChargeMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ChargeMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Charge). +func (m *ChargeMutation) 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 *ChargeMutation) Fields() []string { + fields := make([]string, 0, 8) + if m.namespace != nil { + fields = append(fields, charge.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, charge.FieldCreatedAt) + } + if m.deleted_at != nil { + fields = append(fields, charge.FieldDeletedAt) + } + if m.unique_reference_id != nil { + fields = append(fields, charge.FieldUniqueReferenceID) + } + if m._type != nil { + fields = append(fields, charge.FieldType) + } + if m.flat_fee != nil { + fields = append(fields, charge.FieldChargeFlatFeeID) + } + if m.credit_purchase != nil { + fields = append(fields, charge.FieldChargeCreditPurchaseID) + } + if m.usage_based != nil { + fields = append(fields, charge.FieldChargeUsageBasedID) + } + 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 *ChargeMutation) Field(name string) (ent.Value, bool) { + switch name { + case charge.FieldNamespace: + return m.Namespace() + case charge.FieldCreatedAt: + return m.CreatedAt() + case charge.FieldDeletedAt: + return m.DeletedAt() + case charge.FieldUniqueReferenceID: + return m.UniqueReferenceID() + case charge.FieldType: + return m.GetType() + case charge.FieldChargeFlatFeeID: + return m.ChargeFlatFeeID() + case charge.FieldChargeCreditPurchaseID: + return m.ChargeCreditPurchaseID() + case charge.FieldChargeUsageBasedID: + return m.ChargeUsageBasedID() + } + 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 *ChargeMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case charge.FieldNamespace: + return m.OldNamespace(ctx) + case charge.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case charge.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case charge.FieldUniqueReferenceID: + return m.OldUniqueReferenceID(ctx) + case charge.FieldType: + return m.OldType(ctx) + case charge.FieldChargeFlatFeeID: + return m.OldChargeFlatFeeID(ctx) + case charge.FieldChargeCreditPurchaseID: + return m.OldChargeCreditPurchaseID(ctx) + case charge.FieldChargeUsageBasedID: + return m.OldChargeUsageBasedID(ctx) + } + return nil, fmt.Errorf("unknown Charge 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 *ChargeMutation) SetField(name string, value ent.Value) error { + switch name { + case charge.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case charge.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 charge.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 charge.FieldUniqueReferenceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUniqueReferenceID(v) + return nil + case charge.FieldType: + v, ok := value.(meta.ChargeType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case charge.FieldChargeFlatFeeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChargeFlatFeeID(v) + return nil + case charge.FieldChargeCreditPurchaseID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChargeCreditPurchaseID(v) + return nil + case charge.FieldChargeUsageBasedID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChargeUsageBasedID(v) + return nil + } + return fmt.Errorf("unknown Charge field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ChargeMutation) 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 *ChargeMutation) 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 *ChargeMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Charge numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ChargeMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(charge.FieldDeletedAt) { + fields = append(fields, charge.FieldDeletedAt) + } + if m.FieldCleared(charge.FieldUniqueReferenceID) { + fields = append(fields, charge.FieldUniqueReferenceID) + } + if m.FieldCleared(charge.FieldChargeFlatFeeID) { + fields = append(fields, charge.FieldChargeFlatFeeID) + } + if m.FieldCleared(charge.FieldChargeCreditPurchaseID) { + fields = append(fields, charge.FieldChargeCreditPurchaseID) + } + if m.FieldCleared(charge.FieldChargeUsageBasedID) { + fields = append(fields, charge.FieldChargeUsageBasedID) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ChargeMutation) 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 *ChargeMutation) ClearField(name string) error { + switch name { + case charge.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case charge.FieldUniqueReferenceID: + m.ClearUniqueReferenceID() + return nil + case charge.FieldChargeFlatFeeID: + m.ClearChargeFlatFeeID() + return nil + case charge.FieldChargeCreditPurchaseID: + m.ClearChargeCreditPurchaseID() + return nil + case charge.FieldChargeUsageBasedID: + m.ClearChargeUsageBasedID() + return nil + } + return fmt.Errorf("unknown Charge 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 *ChargeMutation) ResetField(name string) error { + switch name { + case charge.FieldNamespace: + m.ResetNamespace() + return nil + case charge.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case charge.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case charge.FieldUniqueReferenceID: + m.ResetUniqueReferenceID() + return nil + case charge.FieldType: + m.ResetType() + return nil + case charge.FieldChargeFlatFeeID: + m.ResetChargeFlatFeeID() + return nil + case charge.FieldChargeCreditPurchaseID: + m.ResetChargeCreditPurchaseID() + return nil + case charge.FieldChargeUsageBasedID: + m.ResetChargeUsageBasedID() + return nil + } + return fmt.Errorf("unknown Charge field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ChargeMutation) AddedEdges() []string { + edges := make([]string, 0, 6) + 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) + } + if m.billing_split_line_groups != nil { + edges = append(edges, charge.EdgeBillingSplitLineGroups) + } + if m.credit_realization_lineages != nil { + edges = append(edges, charge.EdgeCreditRealizationLineages) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ChargeMutation) AddedIDs(name string) []ent.Value { + switch name { + case charge.EdgeFlatFee: + if id := m.flat_fee; id != nil { + return []ent.Value{*id} + } + case charge.EdgeCreditPurchase: + 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 { + ids = append(ids, id) + } + return ids + case charge.EdgeBillingSplitLineGroups: + ids := make([]ent.Value, 0, len(m.billing_split_line_groups)) + for id := range m.billing_split_line_groups { + ids = append(ids, id) + } + return ids + case charge.EdgeCreditRealizationLineages: + ids := make([]ent.Value, 0, len(m.credit_realization_lineages)) + for id := range m.credit_realization_lineages { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ChargeMutation) RemovedEdges() []string { + edges := make([]string, 0, 6) + if m.removedbilling_invoice_lines != nil { + edges = append(edges, charge.EdgeBillingInvoiceLines) + } + if m.removedbilling_split_line_groups != nil { + edges = append(edges, charge.EdgeBillingSplitLineGroups) + } + if m.removedcredit_realization_lineages != nil { + edges = append(edges, charge.EdgeCreditRealizationLineages) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ChargeMutation) RemovedIDs(name string) []ent.Value { + switch name { + case charge.EdgeBillingInvoiceLines: + ids := make([]ent.Value, 0, len(m.removedbilling_invoice_lines)) + for id := range m.removedbilling_invoice_lines { + ids = append(ids, id) + } + return ids + case charge.EdgeBillingSplitLineGroups: + ids := make([]ent.Value, 0, len(m.removedbilling_split_line_groups)) + for id := range m.removedbilling_split_line_groups { + ids = append(ids, id) + } + return ids + case charge.EdgeCreditRealizationLineages: + ids := make([]ent.Value, 0, len(m.removedcredit_realization_lineages)) + for id := range m.removedcredit_realization_lineages { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ChargeMutation) ClearedEdges() []string { + edges := make([]string, 0, 6) + 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) + } + if m.clearedbilling_split_line_groups { + edges = append(edges, charge.EdgeBillingSplitLineGroups) + } + if m.clearedcredit_realization_lineages { + edges = append(edges, charge.EdgeCreditRealizationLineages) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ChargeMutation) EdgeCleared(name string) bool { + switch name { + case charge.EdgeFlatFee: + 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: + return m.clearedbilling_split_line_groups + case charge.EdgeCreditRealizationLineages: + return m.clearedcredit_realization_lineages + } + 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 *ChargeMutation) ClearEdge(name string) error { + switch name { + case charge.EdgeFlatFee: + m.ClearFlatFee() + return nil + case charge.EdgeCreditPurchase: + m.ClearCreditPurchase() + return nil + case charge.EdgeUsageBased: + m.ClearUsageBased() + return nil + } + return fmt.Errorf("unknown Charge 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 *ChargeMutation) ResetEdge(name string) error { + switch name { + case charge.EdgeFlatFee: + m.ResetFlatFee() + return nil + case charge.EdgeCreditPurchase: + m.ResetCreditPurchase() + return nil + case charge.EdgeUsageBased: + m.ResetUsageBased() + return nil + case charge.EdgeBillingInvoiceLines: + m.ResetBillingInvoiceLines() + return nil + case charge.EdgeBillingSplitLineGroups: + m.ResetBillingSplitLineGroups() + return nil + case charge.EdgeCreditRealizationLineages: + m.ResetCreditRealizationLineages() + return nil + } + return fmt.Errorf("unknown Charge edge %s", name) +} + +// ChargeCreditPurchaseMutation represents an operation that mutates the ChargeCreditPurchase nodes in the graph. +type ChargeCreditPurchaseMutation struct { + config + op Op + typ string + id *string + service_period_from *time.Time + service_period_to *time.Time + billing_period_from *time.Time + billing_period_to *time.Time + full_service_period_from *time.Time + full_service_period_to *time.Time + status *meta.ChargeStatus + unique_reference_id *string + currency *currencyx.Code + managed_by *billing.InvoiceLineManagedBy + advance_after *time.Time + tax_behavior *productcatalog.TaxBehavior + annotations *models.Annotations + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + name *string + description *string + credit_amount *alpacadecimal.Decimal + effective_at *time.Time + expires_at *time.Time + priority *int + addpriority *int + feature_filters *pq.StringArray + settlement *creditpurchase.Settlement + status_detailed *creditpurchase.Status + key *string + voided_at *time.Time + clearedFields map[string]struct{} + external_payment *string + clearedexternal_payment bool + invoiced_payment *string + clearedinvoiced_payment bool + credit_grant *string + clearedcredit_grant bool + charge *string + clearedcharge bool + subscription *string + clearedsubscription bool + subscription_phase *string + clearedsubscription_phase bool + subscription_item *string + clearedsubscription_item bool + customer *string + clearedcustomer bool + tax_code *string + clearedtax_code bool + done bool + oldValue func(context.Context) (*ChargeCreditPurchase, error) + predicates []predicate.ChargeCreditPurchase +} + +var _ ent.Mutation = (*ChargeCreditPurchaseMutation)(nil) + +// chargecreditpurchaseOption allows management of the mutation configuration using functional options. +type chargecreditpurchaseOption func(*ChargeCreditPurchaseMutation) + +// newChargeCreditPurchaseMutation creates new mutation for the ChargeCreditPurchase entity. +func newChargeCreditPurchaseMutation(c config, op Op, opts ...chargecreditpurchaseOption) *ChargeCreditPurchaseMutation { + m := &ChargeCreditPurchaseMutation{ + config: c, + op: op, + typ: TypeChargeCreditPurchase, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withChargeCreditPurchaseID sets the ID field of the mutation. +func withChargeCreditPurchaseID(id string) chargecreditpurchaseOption { + return func(m *ChargeCreditPurchaseMutation) { + var ( + err error + once sync.Once + value *ChargeCreditPurchase + ) + m.oldValue = func(ctx context.Context) (*ChargeCreditPurchase, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ChargeCreditPurchase.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withChargeCreditPurchase sets the old ChargeCreditPurchase of the mutation. +func withChargeCreditPurchase(node *ChargeCreditPurchase) chargecreditpurchaseOption { + return func(m *ChargeCreditPurchaseMutation) { + m.oldValue = func(context.Context) (*ChargeCreditPurchase, 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 ChargeCreditPurchaseMutation) 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 ChargeCreditPurchaseMutation) 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 ChargeCreditPurchase entities. +func (m *ChargeCreditPurchaseMutation) 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 *ChargeCreditPurchaseMutation) 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 *ChargeCreditPurchaseMutation) 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().ChargeCreditPurchase.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetCustomerID sets the "customer_id" field. +func (m *ChargeCreditPurchaseMutation) SetCustomerID(s string) { + m.customer = &s +} + +// CustomerID returns the value of the "customer_id" field in the mutation. +func (m *ChargeCreditPurchaseMutation) CustomerID() (r string, exists bool) { + v := m.customer + if v == nil { + return + } + return *v, true +} + +// OldCustomerID returns the old "customer_id" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldCustomerID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerID: %w", err) + } + return oldValue.CustomerID, nil +} + +// ResetCustomerID resets all changes to the "customer_id" field. +func (m *ChargeCreditPurchaseMutation) ResetCustomerID() { + m.customer = nil +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (m *ChargeCreditPurchaseMutation) SetServicePeriodFrom(t time.Time) { + m.service_period_from = &t +} + +// ServicePeriodFrom returns the value of the "service_period_from" field in the mutation. +func (m *ChargeCreditPurchaseMutation) 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 ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) 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 *ChargeCreditPurchaseMutation) ResetServicePeriodFrom() { + m.service_period_from = nil +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (m *ChargeCreditPurchaseMutation) SetServicePeriodTo(t time.Time) { + m.service_period_to = &t +} + +// ServicePeriodTo returns the value of the "service_period_to" field in the mutation. +func (m *ChargeCreditPurchaseMutation) 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 ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) 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 *ChargeCreditPurchaseMutation) ResetServicePeriodTo() { + m.service_period_to = nil +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (m *ChargeCreditPurchaseMutation) SetBillingPeriodFrom(t time.Time) { + m.billing_period_from = &t +} + +// BillingPeriodFrom returns the value of the "billing_period_from" field in the mutation. +func (m *ChargeCreditPurchaseMutation) BillingPeriodFrom() (r time.Time, exists bool) { + v := m.billing_period_from + if v == nil { + return + } + return *v, true +} + +// OldBillingPeriodFrom returns the old "billing_period_from" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldBillingPeriodFrom(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingPeriodFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingPeriodFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingPeriodFrom: %w", err) + } + return oldValue.BillingPeriodFrom, nil +} + +// ResetBillingPeriodFrom resets all changes to the "billing_period_from" field. +func (m *ChargeCreditPurchaseMutation) ResetBillingPeriodFrom() { + m.billing_period_from = nil +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (m *ChargeCreditPurchaseMutation) SetBillingPeriodTo(t time.Time) { + m.billing_period_to = &t +} + +// BillingPeriodTo returns the value of the "billing_period_to" field in the mutation. +func (m *ChargeCreditPurchaseMutation) BillingPeriodTo() (r time.Time, exists bool) { + v := m.billing_period_to + if v == nil { + return + } + return *v, true +} + +// OldBillingPeriodTo returns the old "billing_period_to" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldBillingPeriodTo(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingPeriodTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingPeriodTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingPeriodTo: %w", err) + } + return oldValue.BillingPeriodTo, nil +} + +// ResetBillingPeriodTo resets all changes to the "billing_period_to" field. +func (m *ChargeCreditPurchaseMutation) ResetBillingPeriodTo() { + m.billing_period_to = nil +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (m *ChargeCreditPurchaseMutation) SetFullServicePeriodFrom(t time.Time) { + m.full_service_period_from = &t +} + +// FullServicePeriodFrom returns the value of the "full_service_period_from" field in the mutation. +func (m *ChargeCreditPurchaseMutation) FullServicePeriodFrom() (r time.Time, exists bool) { + v := m.full_service_period_from + if v == nil { + return + } + return *v, true +} + +// OldFullServicePeriodFrom returns the old "full_service_period_from" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldFullServicePeriodFrom(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFullServicePeriodFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFullServicePeriodFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFullServicePeriodFrom: %w", err) + } + return oldValue.FullServicePeriodFrom, nil +} + +// ResetFullServicePeriodFrom resets all changes to the "full_service_period_from" field. +func (m *ChargeCreditPurchaseMutation) ResetFullServicePeriodFrom() { + m.full_service_period_from = nil +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (m *ChargeCreditPurchaseMutation) SetFullServicePeriodTo(t time.Time) { + m.full_service_period_to = &t +} + +// FullServicePeriodTo returns the value of the "full_service_period_to" field in the mutation. +func (m *ChargeCreditPurchaseMutation) FullServicePeriodTo() (r time.Time, exists bool) { + v := m.full_service_period_to + if v == nil { + return + } + return *v, true +} + +// OldFullServicePeriodTo returns the old "full_service_period_to" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldFullServicePeriodTo(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFullServicePeriodTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFullServicePeriodTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFullServicePeriodTo: %w", err) + } + return oldValue.FullServicePeriodTo, nil +} + +// ResetFullServicePeriodTo resets all changes to the "full_service_period_to" field. +func (m *ChargeCreditPurchaseMutation) ResetFullServicePeriodTo() { + m.full_service_period_to = nil +} + +// SetStatus sets the "status" field. +func (m *ChargeCreditPurchaseMutation) SetStatus(ms meta.ChargeStatus) { + m.status = &ms +} + +// Status returns the value of the "status" field in the mutation. +func (m *ChargeCreditPurchaseMutation) Status() (r meta.ChargeStatus, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true +} + +// OldStatus returns the old "status" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldStatus(ctx context.Context) (v meta.ChargeStatus, 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 *ChargeCreditPurchaseMutation) ResetStatus() { + m.status = nil +} + +// SetUniqueReferenceID sets the "unique_reference_id" field. +func (m *ChargeCreditPurchaseMutation) SetUniqueReferenceID(s string) { + m.unique_reference_id = &s +} + +// UniqueReferenceID returns the value of the "unique_reference_id" field in the mutation. +func (m *ChargeCreditPurchaseMutation) UniqueReferenceID() (r string, exists bool) { + v := m.unique_reference_id + if v == nil { + return + } + return *v, true +} + +// OldUniqueReferenceID returns the old "unique_reference_id" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldUniqueReferenceID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUniqueReferenceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUniqueReferenceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUniqueReferenceID: %w", err) + } + return oldValue.UniqueReferenceID, nil +} + +// ClearUniqueReferenceID clears the value of the "unique_reference_id" field. +func (m *ChargeCreditPurchaseMutation) ClearUniqueReferenceID() { + m.unique_reference_id = nil + m.clearedFields[chargecreditpurchase.FieldUniqueReferenceID] = struct{}{} +} + +// UniqueReferenceIDCleared returns if the "unique_reference_id" field was cleared in this mutation. +func (m *ChargeCreditPurchaseMutation) UniqueReferenceIDCleared() bool { + _, ok := m.clearedFields[chargecreditpurchase.FieldUniqueReferenceID] + return ok +} + +// ResetUniqueReferenceID resets all changes to the "unique_reference_id" field. +func (m *ChargeCreditPurchaseMutation) ResetUniqueReferenceID() { + m.unique_reference_id = nil + delete(m.clearedFields, chargecreditpurchase.FieldUniqueReferenceID) +} + +// SetCurrency sets the "currency" field. +func (m *ChargeCreditPurchaseMutation) SetCurrency(c currencyx.Code) { + m.currency = &c +} + +// Currency returns the value of the "currency" field in the mutation. +func (m *ChargeCreditPurchaseMutation) Currency() (r currencyx.Code, exists bool) { + v := m.currency + if v == nil { + return + } + return *v, true +} + +// OldCurrency returns the old "currency" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldCurrency(ctx context.Context) (v currencyx.Code, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrency is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrency requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrency: %w", err) + } + return oldValue.Currency, nil +} + +// ResetCurrency resets all changes to the "currency" field. +func (m *ChargeCreditPurchaseMutation) ResetCurrency() { + m.currency = nil +} + +// SetManagedBy sets the "managed_by" field. +func (m *ChargeCreditPurchaseMutation) SetManagedBy(blmb billing.InvoiceLineManagedBy) { + m.managed_by = &blmb +} + +// ManagedBy returns the value of the "managed_by" field in the mutation. +func (m *ChargeCreditPurchaseMutation) ManagedBy() (r billing.InvoiceLineManagedBy, exists bool) { + v := m.managed_by + if v == nil { + return + } + return *v, true +} + +// OldManagedBy returns the old "managed_by" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldManagedBy(ctx context.Context) (v billing.InvoiceLineManagedBy, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldManagedBy is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldManagedBy requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldManagedBy: %w", err) + } + return oldValue.ManagedBy, nil +} + +// ResetManagedBy resets all changes to the "managed_by" field. +func (m *ChargeCreditPurchaseMutation) ResetManagedBy() { + m.managed_by = nil +} + +// SetSubscriptionID sets the "subscription_id" field. +func (m *ChargeCreditPurchaseMutation) SetSubscriptionID(s string) { + m.subscription = &s +} + +// SubscriptionID returns the value of the "subscription_id" field in the mutation. +func (m *ChargeCreditPurchaseMutation) SubscriptionID() (r string, exists bool) { + v := m.subscription + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionID returns the old "subscription_id" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldSubscriptionID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionID: %w", err) + } + return oldValue.SubscriptionID, nil +} + +// ClearSubscriptionID clears the value of the "subscription_id" field. +func (m *ChargeCreditPurchaseMutation) ClearSubscriptionID() { + m.subscription = nil + m.clearedFields[chargecreditpurchase.FieldSubscriptionID] = struct{}{} +} + +// SubscriptionIDCleared returns if the "subscription_id" field was cleared in this mutation. +func (m *ChargeCreditPurchaseMutation) SubscriptionIDCleared() bool { + _, ok := m.clearedFields[chargecreditpurchase.FieldSubscriptionID] + return ok +} + +// ResetSubscriptionID resets all changes to the "subscription_id" field. +func (m *ChargeCreditPurchaseMutation) ResetSubscriptionID() { + m.subscription = nil + delete(m.clearedFields, chargecreditpurchase.FieldSubscriptionID) +} + +// SetSubscriptionPhaseID sets the "subscription_phase_id" field. +func (m *ChargeCreditPurchaseMutation) SetSubscriptionPhaseID(s string) { + m.subscription_phase = &s +} + +// SubscriptionPhaseID returns the value of the "subscription_phase_id" field in the mutation. +func (m *ChargeCreditPurchaseMutation) SubscriptionPhaseID() (r string, exists bool) { + v := m.subscription_phase + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionPhaseID returns the old "subscription_phase_id" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldSubscriptionPhaseID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionPhaseID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionPhaseID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionPhaseID: %w", err) + } + return oldValue.SubscriptionPhaseID, nil +} + +// ClearSubscriptionPhaseID clears the value of the "subscription_phase_id" field. +func (m *ChargeCreditPurchaseMutation) ClearSubscriptionPhaseID() { + m.subscription_phase = nil + m.clearedFields[chargecreditpurchase.FieldSubscriptionPhaseID] = struct{}{} +} + +// SubscriptionPhaseIDCleared returns if the "subscription_phase_id" field was cleared in this mutation. +func (m *ChargeCreditPurchaseMutation) SubscriptionPhaseIDCleared() bool { + _, ok := m.clearedFields[chargecreditpurchase.FieldSubscriptionPhaseID] + return ok +} + +// ResetSubscriptionPhaseID resets all changes to the "subscription_phase_id" field. +func (m *ChargeCreditPurchaseMutation) ResetSubscriptionPhaseID() { + m.subscription_phase = nil + delete(m.clearedFields, chargecreditpurchase.FieldSubscriptionPhaseID) +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (m *ChargeCreditPurchaseMutation) SetSubscriptionItemID(s string) { + m.subscription_item = &s +} + +// SubscriptionItemID returns the value of the "subscription_item_id" field in the mutation. +func (m *ChargeCreditPurchaseMutation) SubscriptionItemID() (r string, exists bool) { + v := m.subscription_item + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionItemID returns the old "subscription_item_id" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldSubscriptionItemID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionItemID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionItemID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionItemID: %w", err) + } + return oldValue.SubscriptionItemID, nil +} + +// ClearSubscriptionItemID clears the value of the "subscription_item_id" field. +func (m *ChargeCreditPurchaseMutation) ClearSubscriptionItemID() { + m.subscription_item = nil + m.clearedFields[chargecreditpurchase.FieldSubscriptionItemID] = struct{}{} +} + +// SubscriptionItemIDCleared returns if the "subscription_item_id" field was cleared in this mutation. +func (m *ChargeCreditPurchaseMutation) SubscriptionItemIDCleared() bool { + _, ok := m.clearedFields[chargecreditpurchase.FieldSubscriptionItemID] + return ok +} + +// ResetSubscriptionItemID resets all changes to the "subscription_item_id" field. +func (m *ChargeCreditPurchaseMutation) ResetSubscriptionItemID() { + m.subscription_item = nil + delete(m.clearedFields, chargecreditpurchase.FieldSubscriptionItemID) +} + +// SetAdvanceAfter sets the "advance_after" field. +func (m *ChargeCreditPurchaseMutation) SetAdvanceAfter(t time.Time) { + m.advance_after = &t +} + +// AdvanceAfter returns the value of the "advance_after" field in the mutation. +func (m *ChargeCreditPurchaseMutation) AdvanceAfter() (r time.Time, exists bool) { + v := m.advance_after + if v == nil { + return + } + return *v, true +} + +// OldAdvanceAfter returns the old "advance_after" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldAdvanceAfter(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAdvanceAfter is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAdvanceAfter requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAdvanceAfter: %w", err) + } + return oldValue.AdvanceAfter, nil +} + +// ClearAdvanceAfter clears the value of the "advance_after" field. +func (m *ChargeCreditPurchaseMutation) ClearAdvanceAfter() { + m.advance_after = nil + m.clearedFields[chargecreditpurchase.FieldAdvanceAfter] = struct{}{} +} + +// AdvanceAfterCleared returns if the "advance_after" field was cleared in this mutation. +func (m *ChargeCreditPurchaseMutation) AdvanceAfterCleared() bool { + _, ok := m.clearedFields[chargecreditpurchase.FieldAdvanceAfter] + return ok +} + +// ResetAdvanceAfter resets all changes to the "advance_after" field. +func (m *ChargeCreditPurchaseMutation) ResetAdvanceAfter() { + m.advance_after = nil + delete(m.clearedFields, chargecreditpurchase.FieldAdvanceAfter) +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (m *ChargeCreditPurchaseMutation) SetTaxCodeID(s string) { + m.tax_code = &s +} + +// TaxCodeID returns the value of the "tax_code_id" field in the mutation. +func (m *ChargeCreditPurchaseMutation) TaxCodeID() (r string, exists bool) { + v := m.tax_code + if v == nil { + return + } + return *v, true +} + +// OldTaxCodeID returns the old "tax_code_id" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldTaxCodeID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxCodeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxCodeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxCodeID: %w", err) + } + return oldValue.TaxCodeID, nil +} + +// ResetTaxCodeID resets all changes to the "tax_code_id" field. +func (m *ChargeCreditPurchaseMutation) ResetTaxCodeID() { + m.tax_code = nil +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (m *ChargeCreditPurchaseMutation) SetTaxBehavior(pb productcatalog.TaxBehavior) { + m.tax_behavior = &pb +} + +// TaxBehavior returns the value of the "tax_behavior" field in the mutation. +func (m *ChargeCreditPurchaseMutation) TaxBehavior() (r productcatalog.TaxBehavior, exists bool) { + v := m.tax_behavior + if v == nil { + return + } + return *v, true +} + +// OldTaxBehavior returns the old "tax_behavior" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldTaxBehavior(ctx context.Context) (v *productcatalog.TaxBehavior, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxBehavior is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxBehavior requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxBehavior: %w", err) + } + return oldValue.TaxBehavior, nil +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (m *ChargeCreditPurchaseMutation) ClearTaxBehavior() { + m.tax_behavior = nil + m.clearedFields[chargecreditpurchase.FieldTaxBehavior] = struct{}{} +} + +// TaxBehaviorCleared returns if the "tax_behavior" field was cleared in this mutation. +func (m *ChargeCreditPurchaseMutation) TaxBehaviorCleared() bool { + _, ok := m.clearedFields[chargecreditpurchase.FieldTaxBehavior] + return ok +} + +// ResetTaxBehavior resets all changes to the "tax_behavior" field. +func (m *ChargeCreditPurchaseMutation) ResetTaxBehavior() { + m.tax_behavior = nil + delete(m.clearedFields, chargecreditpurchase.FieldTaxBehavior) +} + +// SetAnnotations sets the "annotations" field. +func (m *ChargeCreditPurchaseMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *ChargeCreditPurchaseMutation) 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 ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) 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 *ChargeCreditPurchaseMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[chargecreditpurchase.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *ChargeCreditPurchaseMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[chargecreditpurchase.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *ChargeCreditPurchaseMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, chargecreditpurchase.FieldAnnotations) +} + +// SetNamespace sets the "namespace" field. +func (m *ChargeCreditPurchaseMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *ChargeCreditPurchaseMutation) 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 ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) 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 *ChargeCreditPurchaseMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *ChargeCreditPurchaseMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *ChargeCreditPurchaseMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *ChargeCreditPurchaseMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[chargecreditpurchase.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *ChargeCreditPurchaseMutation) MetadataCleared() bool { + _, ok := m.clearedFields[chargecreditpurchase.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *ChargeCreditPurchaseMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, chargecreditpurchase.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *ChargeCreditPurchaseMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ChargeCreditPurchaseMutation) 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 ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) 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 *ChargeCreditPurchaseMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *ChargeCreditPurchaseMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ChargeCreditPurchaseMutation) 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 ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) 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 *ChargeCreditPurchaseMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *ChargeCreditPurchaseMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *ChargeCreditPurchaseMutation) 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 ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) 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 *ChargeCreditPurchaseMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[chargecreditpurchase.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *ChargeCreditPurchaseMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[chargecreditpurchase.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *ChargeCreditPurchaseMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, chargecreditpurchase.FieldDeletedAt) +} + +// SetName sets the "name" field. +func (m *ChargeCreditPurchaseMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *ChargeCreditPurchaseMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *ChargeCreditPurchaseMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *ChargeCreditPurchaseMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *ChargeCreditPurchaseMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *ChargeCreditPurchaseMutation) ClearDescription() { + m.description = nil + m.clearedFields[chargecreditpurchase.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *ChargeCreditPurchaseMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[chargecreditpurchase.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *ChargeCreditPurchaseMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, chargecreditpurchase.FieldDescription) +} + +// SetCreditAmount sets the "credit_amount" field. +func (m *ChargeCreditPurchaseMutation) SetCreditAmount(a alpacadecimal.Decimal) { + m.credit_amount = &a +} + +// CreditAmount returns the value of the "credit_amount" field in the mutation. +func (m *ChargeCreditPurchaseMutation) CreditAmount() (r alpacadecimal.Decimal, exists bool) { + v := m.credit_amount + if v == nil { + return + } + return *v, true +} + +// OldCreditAmount returns the old "credit_amount" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldCreditAmount(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreditAmount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreditAmount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreditAmount: %w", err) + } + return oldValue.CreditAmount, nil +} + +// ResetCreditAmount resets all changes to the "credit_amount" field. +func (m *ChargeCreditPurchaseMutation) ResetCreditAmount() { + m.credit_amount = nil +} + +// SetEffectiveAt sets the "effective_at" field. +func (m *ChargeCreditPurchaseMutation) SetEffectiveAt(t time.Time) { + m.effective_at = &t +} + +// EffectiveAt returns the value of the "effective_at" field in the mutation. +func (m *ChargeCreditPurchaseMutation) EffectiveAt() (r time.Time, exists bool) { + v := m.effective_at + if v == nil { + return + } + return *v, true +} + +// OldEffectiveAt returns the old "effective_at" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldEffectiveAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEffectiveAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEffectiveAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEffectiveAt: %w", err) + } + return oldValue.EffectiveAt, nil +} + +// ClearEffectiveAt clears the value of the "effective_at" field. +func (m *ChargeCreditPurchaseMutation) ClearEffectiveAt() { + m.effective_at = nil + m.clearedFields[chargecreditpurchase.FieldEffectiveAt] = struct{}{} +} + +// EffectiveAtCleared returns if the "effective_at" field was cleared in this mutation. +func (m *ChargeCreditPurchaseMutation) EffectiveAtCleared() bool { + _, ok := m.clearedFields[chargecreditpurchase.FieldEffectiveAt] + return ok +} + +// ResetEffectiveAt resets all changes to the "effective_at" field. +func (m *ChargeCreditPurchaseMutation) ResetEffectiveAt() { + m.effective_at = nil + delete(m.clearedFields, chargecreditpurchase.FieldEffectiveAt) +} + +// SetExpiresAt sets the "expires_at" field. +func (m *ChargeCreditPurchaseMutation) SetExpiresAt(t time.Time) { + m.expires_at = &t +} + +// ExpiresAt returns the value of the "expires_at" field in the mutation. +func (m *ChargeCreditPurchaseMutation) ExpiresAt() (r time.Time, exists bool) { + v := m.expires_at + if v == nil { + return + } + return *v, true +} + +// OldExpiresAt returns the old "expires_at" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldExpiresAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldExpiresAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldExpiresAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldExpiresAt: %w", err) + } + return oldValue.ExpiresAt, nil +} + +// ClearExpiresAt clears the value of the "expires_at" field. +func (m *ChargeCreditPurchaseMutation) ClearExpiresAt() { + m.expires_at = nil + m.clearedFields[chargecreditpurchase.FieldExpiresAt] = struct{}{} +} + +// ExpiresAtCleared returns if the "expires_at" field was cleared in this mutation. +func (m *ChargeCreditPurchaseMutation) ExpiresAtCleared() bool { + _, ok := m.clearedFields[chargecreditpurchase.FieldExpiresAt] + return ok +} + +// ResetExpiresAt resets all changes to the "expires_at" field. +func (m *ChargeCreditPurchaseMutation) ResetExpiresAt() { + m.expires_at = nil + delete(m.clearedFields, chargecreditpurchase.FieldExpiresAt) +} + +// SetPriority sets the "priority" field. +func (m *ChargeCreditPurchaseMutation) SetPriority(i int) { + m.priority = &i + m.addpriority = nil +} + +// Priority returns the value of the "priority" field in the mutation. +func (m *ChargeCreditPurchaseMutation) Priority() (r int, exists bool) { + v := m.priority + if v == nil { + return + } + return *v, true +} + +// OldPriority returns the old "priority" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldPriority(ctx context.Context) (v *int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPriority is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPriority requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPriority: %w", err) + } + return oldValue.Priority, nil +} + +// AddPriority adds i to the "priority" field. +func (m *ChargeCreditPurchaseMutation) AddPriority(i int) { + if m.addpriority != nil { + *m.addpriority += i + } else { + m.addpriority = &i + } +} + +// AddedPriority returns the value that was added to the "priority" field in this mutation. +func (m *ChargeCreditPurchaseMutation) AddedPriority() (r int, exists bool) { + v := m.addpriority + if v == nil { + return + } + return *v, true +} + +// ClearPriority clears the value of the "priority" field. +func (m *ChargeCreditPurchaseMutation) ClearPriority() { + m.priority = nil + m.addpriority = nil + m.clearedFields[chargecreditpurchase.FieldPriority] = struct{}{} +} + +// PriorityCleared returns if the "priority" field was cleared in this mutation. +func (m *ChargeCreditPurchaseMutation) PriorityCleared() bool { + _, ok := m.clearedFields[chargecreditpurchase.FieldPriority] + return ok +} + +// ResetPriority resets all changes to the "priority" field. +func (m *ChargeCreditPurchaseMutation) ResetPriority() { + m.priority = nil + m.addpriority = nil + delete(m.clearedFields, chargecreditpurchase.FieldPriority) +} + +// SetFeatureFilters sets the "feature_filters" field. +func (m *ChargeCreditPurchaseMutation) SetFeatureFilters(pa pq.StringArray) { + m.feature_filters = &pa +} + +// FeatureFilters returns the value of the "feature_filters" field in the mutation. +func (m *ChargeCreditPurchaseMutation) FeatureFilters() (r pq.StringArray, exists bool) { + v := m.feature_filters + if v == nil { + return + } + return *v, true +} + +// OldFeatureFilters returns the old "feature_filters" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldFeatureFilters(ctx context.Context) (v pq.StringArray, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFeatureFilters is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFeatureFilters requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFeatureFilters: %w", err) + } + return oldValue.FeatureFilters, nil +} + +// ClearFeatureFilters clears the value of the "feature_filters" field. +func (m *ChargeCreditPurchaseMutation) ClearFeatureFilters() { + m.feature_filters = nil + m.clearedFields[chargecreditpurchase.FieldFeatureFilters] = struct{}{} +} + +// FeatureFiltersCleared returns if the "feature_filters" field was cleared in this mutation. +func (m *ChargeCreditPurchaseMutation) FeatureFiltersCleared() bool { + _, ok := m.clearedFields[chargecreditpurchase.FieldFeatureFilters] + return ok +} + +// ResetFeatureFilters resets all changes to the "feature_filters" field. +func (m *ChargeCreditPurchaseMutation) ResetFeatureFilters() { + m.feature_filters = nil + delete(m.clearedFields, chargecreditpurchase.FieldFeatureFilters) +} + +// SetSettlement sets the "settlement" field. +func (m *ChargeCreditPurchaseMutation) SetSettlement(c creditpurchase.Settlement) { + m.settlement = &c +} + +// Settlement returns the value of the "settlement" field in the mutation. +func (m *ChargeCreditPurchaseMutation) Settlement() (r creditpurchase.Settlement, exists bool) { + v := m.settlement + if v == nil { + return + } + return *v, true +} + +// OldSettlement returns the old "settlement" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldSettlement(ctx context.Context) (v creditpurchase.Settlement, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSettlement is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSettlement requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSettlement: %w", err) + } + return oldValue.Settlement, nil +} + +// ResetSettlement resets all changes to the "settlement" field. +func (m *ChargeCreditPurchaseMutation) ResetSettlement() { + m.settlement = nil +} + +// SetStatusDetailed sets the "status_detailed" field. +func (m *ChargeCreditPurchaseMutation) SetStatusDetailed(c creditpurchase.Status) { + m.status_detailed = &c +} + +// StatusDetailed returns the value of the "status_detailed" field in the mutation. +func (m *ChargeCreditPurchaseMutation) StatusDetailed() (r creditpurchase.Status, exists bool) { + v := m.status_detailed + if v == nil { + return + } + return *v, true +} + +// OldStatusDetailed returns the old "status_detailed" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldStatusDetailed(ctx context.Context) (v creditpurchase.Status, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStatusDetailed is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStatusDetailed requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStatusDetailed: %w", err) + } + return oldValue.StatusDetailed, nil +} + +// ResetStatusDetailed resets all changes to the "status_detailed" field. +func (m *ChargeCreditPurchaseMutation) ResetStatusDetailed() { + m.status_detailed = nil +} + +// SetKey sets the "key" field. +func (m *ChargeCreditPurchaseMutation) SetKey(s string) { + m.key = &s +} + +// Key returns the value of the "key" field in the mutation. +func (m *ChargeCreditPurchaseMutation) Key() (r string, exists bool) { + v := m.key + if v == nil { + return + } + return *v, true +} + +// OldKey returns the old "key" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldKey(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldKey: %w", err) + } + return oldValue.Key, nil +} + +// ClearKey clears the value of the "key" field. +func (m *ChargeCreditPurchaseMutation) ClearKey() { + m.key = nil + m.clearedFields[chargecreditpurchase.FieldKey] = struct{}{} +} + +// KeyCleared returns if the "key" field was cleared in this mutation. +func (m *ChargeCreditPurchaseMutation) KeyCleared() bool { + _, ok := m.clearedFields[chargecreditpurchase.FieldKey] + return ok +} + +// ResetKey resets all changes to the "key" field. +func (m *ChargeCreditPurchaseMutation) ResetKey() { + m.key = nil + delete(m.clearedFields, chargecreditpurchase.FieldKey) +} + +// SetVoidedAt sets the "voided_at" field. +func (m *ChargeCreditPurchaseMutation) SetVoidedAt(t time.Time) { + m.voided_at = &t +} + +// VoidedAt returns the value of the "voided_at" field in the mutation. +func (m *ChargeCreditPurchaseMutation) VoidedAt() (r time.Time, exists bool) { + v := m.voided_at + if v == nil { + return + } + return *v, true +} + +// OldVoidedAt returns the old "voided_at" field's value of the ChargeCreditPurchase entity. +// If the ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) OldVoidedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldVoidedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldVoidedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldVoidedAt: %w", err) + } + return oldValue.VoidedAt, nil +} + +// ClearVoidedAt clears the value of the "voided_at" field. +func (m *ChargeCreditPurchaseMutation) ClearVoidedAt() { + m.voided_at = nil + m.clearedFields[chargecreditpurchase.FieldVoidedAt] = struct{}{} +} + +// VoidedAtCleared returns if the "voided_at" field was cleared in this mutation. +func (m *ChargeCreditPurchaseMutation) VoidedAtCleared() bool { + _, ok := m.clearedFields[chargecreditpurchase.FieldVoidedAt] + return ok +} + +// ResetVoidedAt resets all changes to the "voided_at" field. +func (m *ChargeCreditPurchaseMutation) ResetVoidedAt() { + m.voided_at = nil + delete(m.clearedFields, chargecreditpurchase.FieldVoidedAt) +} + +// SetExternalPaymentID sets the "external_payment" edge to the ChargeCreditPurchaseExternalPayment entity by id. +func (m *ChargeCreditPurchaseMutation) SetExternalPaymentID(id string) { + m.external_payment = &id +} + +// ClearExternalPayment clears the "external_payment" edge to the ChargeCreditPurchaseExternalPayment entity. +func (m *ChargeCreditPurchaseMutation) ClearExternalPayment() { + m.clearedexternal_payment = true +} + +// ExternalPaymentCleared reports if the "external_payment" edge to the ChargeCreditPurchaseExternalPayment entity was cleared. +func (m *ChargeCreditPurchaseMutation) ExternalPaymentCleared() bool { + return m.clearedexternal_payment +} + +// ExternalPaymentID returns the "external_payment" edge ID in the mutation. +func (m *ChargeCreditPurchaseMutation) ExternalPaymentID() (id string, exists bool) { + if m.external_payment != nil { + return *m.external_payment, true + } + return +} + +// ExternalPaymentIDs returns the "external_payment" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ExternalPaymentID instead. It exists only for internal usage by the builders. +func (m *ChargeCreditPurchaseMutation) ExternalPaymentIDs() (ids []string) { + if id := m.external_payment; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetExternalPayment resets all changes to the "external_payment" edge. +func (m *ChargeCreditPurchaseMutation) ResetExternalPayment() { + m.external_payment = nil + m.clearedexternal_payment = false +} + +// SetInvoicedPaymentID sets the "invoiced_payment" edge to the ChargeCreditPurchaseInvoicedPayment entity by id. +func (m *ChargeCreditPurchaseMutation) SetInvoicedPaymentID(id string) { + m.invoiced_payment = &id +} + +// ClearInvoicedPayment clears the "invoiced_payment" edge to the ChargeCreditPurchaseInvoicedPayment entity. +func (m *ChargeCreditPurchaseMutation) ClearInvoicedPayment() { + m.clearedinvoiced_payment = true +} + +// InvoicedPaymentCleared reports if the "invoiced_payment" edge to the ChargeCreditPurchaseInvoicedPayment entity was cleared. +func (m *ChargeCreditPurchaseMutation) InvoicedPaymentCleared() bool { + return m.clearedinvoiced_payment +} + +// InvoicedPaymentID returns the "invoiced_payment" edge ID in the mutation. +func (m *ChargeCreditPurchaseMutation) InvoicedPaymentID() (id string, exists bool) { + if m.invoiced_payment != nil { + return *m.invoiced_payment, true + } + return +} + +// InvoicedPaymentIDs returns the "invoiced_payment" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// InvoicedPaymentID instead. It exists only for internal usage by the builders. +func (m *ChargeCreditPurchaseMutation) InvoicedPaymentIDs() (ids []string) { + if id := m.invoiced_payment; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetInvoicedPayment resets all changes to the "invoiced_payment" edge. +func (m *ChargeCreditPurchaseMutation) ResetInvoicedPayment() { + m.invoiced_payment = nil + m.clearedinvoiced_payment = false +} + +// SetCreditGrantID sets the "credit_grant" edge to the ChargeCreditPurchaseCreditGrant entity by id. +func (m *ChargeCreditPurchaseMutation) SetCreditGrantID(id string) { + m.credit_grant = &id +} + +// ClearCreditGrant clears the "credit_grant" edge to the ChargeCreditPurchaseCreditGrant entity. +func (m *ChargeCreditPurchaseMutation) ClearCreditGrant() { + m.clearedcredit_grant = true +} + +// CreditGrantCleared reports if the "credit_grant" edge to the ChargeCreditPurchaseCreditGrant entity was cleared. +func (m *ChargeCreditPurchaseMutation) CreditGrantCleared() bool { + return m.clearedcredit_grant +} + +// CreditGrantID returns the "credit_grant" edge ID in the mutation. +func (m *ChargeCreditPurchaseMutation) CreditGrantID() (id string, exists bool) { + if m.credit_grant != nil { + return *m.credit_grant, true + } + return +} + +// CreditGrantIDs returns the "credit_grant" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CreditGrantID instead. It exists only for internal usage by the builders. +func (m *ChargeCreditPurchaseMutation) CreditGrantIDs() (ids []string) { + if id := m.credit_grant; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCreditGrant resets all changes to the "credit_grant" edge. +func (m *ChargeCreditPurchaseMutation) ResetCreditGrant() { + m.credit_grant = nil + m.clearedcredit_grant = false +} + +// SetChargeID sets the "charge" edge to the Charge entity by id. +func (m *ChargeCreditPurchaseMutation) SetChargeID(id string) { + m.charge = &id +} + +// ClearCharge clears the "charge" edge to the Charge entity. +func (m *ChargeCreditPurchaseMutation) ClearCharge() { + m.clearedcharge = true +} + +// ChargeCleared reports if the "charge" edge to the Charge entity was cleared. +func (m *ChargeCreditPurchaseMutation) ChargeCleared() bool { + return m.clearedcharge +} + +// ChargeID returns the "charge" edge ID in the mutation. +func (m *ChargeCreditPurchaseMutation) 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 *ChargeCreditPurchaseMutation) ChargeIDs() (ids []string) { + if id := m.charge; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCharge resets all changes to the "charge" edge. +func (m *ChargeCreditPurchaseMutation) ResetCharge() { + m.charge = nil + m.clearedcharge = false +} + +// ClearSubscription clears the "subscription" edge to the Subscription entity. +func (m *ChargeCreditPurchaseMutation) ClearSubscription() { + m.clearedsubscription = true + m.clearedFields[chargecreditpurchase.FieldSubscriptionID] = struct{}{} +} + +// SubscriptionCleared reports if the "subscription" edge to the Subscription entity was cleared. +func (m *ChargeCreditPurchaseMutation) SubscriptionCleared() bool { + return m.SubscriptionIDCleared() || m.clearedsubscription +} + +// SubscriptionIDs returns the "subscription" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubscriptionID instead. It exists only for internal usage by the builders. +func (m *ChargeCreditPurchaseMutation) SubscriptionIDs() (ids []string) { + if id := m.subscription; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSubscription resets all changes to the "subscription" edge. +func (m *ChargeCreditPurchaseMutation) ResetSubscription() { + m.subscription = nil + m.clearedsubscription = false +} + +// ClearSubscriptionPhase clears the "subscription_phase" edge to the SubscriptionPhase entity. +func (m *ChargeCreditPurchaseMutation) ClearSubscriptionPhase() { + m.clearedsubscription_phase = true + m.clearedFields[chargecreditpurchase.FieldSubscriptionPhaseID] = struct{}{} +} + +// SubscriptionPhaseCleared reports if the "subscription_phase" edge to the SubscriptionPhase entity was cleared. +func (m *ChargeCreditPurchaseMutation) SubscriptionPhaseCleared() bool { + return m.SubscriptionPhaseIDCleared() || m.clearedsubscription_phase +} + +// SubscriptionPhaseIDs returns the "subscription_phase" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubscriptionPhaseID instead. It exists only for internal usage by the builders. +func (m *ChargeCreditPurchaseMutation) SubscriptionPhaseIDs() (ids []string) { + if id := m.subscription_phase; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSubscriptionPhase resets all changes to the "subscription_phase" edge. +func (m *ChargeCreditPurchaseMutation) ResetSubscriptionPhase() { + m.subscription_phase = nil + m.clearedsubscription_phase = false +} + +// ClearSubscriptionItem clears the "subscription_item" edge to the SubscriptionItem entity. +func (m *ChargeCreditPurchaseMutation) ClearSubscriptionItem() { + m.clearedsubscription_item = true + m.clearedFields[chargecreditpurchase.FieldSubscriptionItemID] = struct{}{} +} + +// SubscriptionItemCleared reports if the "subscription_item" edge to the SubscriptionItem entity was cleared. +func (m *ChargeCreditPurchaseMutation) SubscriptionItemCleared() bool { + return m.SubscriptionItemIDCleared() || m.clearedsubscription_item +} + +// SubscriptionItemIDs returns the "subscription_item" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubscriptionItemID instead. It exists only for internal usage by the builders. +func (m *ChargeCreditPurchaseMutation) SubscriptionItemIDs() (ids []string) { + if id := m.subscription_item; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSubscriptionItem resets all changes to the "subscription_item" edge. +func (m *ChargeCreditPurchaseMutation) ResetSubscriptionItem() { + m.subscription_item = nil + m.clearedsubscription_item = false +} + +// ClearCustomer clears the "customer" edge to the Customer entity. +func (m *ChargeCreditPurchaseMutation) ClearCustomer() { + m.clearedcustomer = true + m.clearedFields[chargecreditpurchase.FieldCustomerID] = struct{}{} +} + +// CustomerCleared reports if the "customer" edge to the Customer entity was cleared. +func (m *ChargeCreditPurchaseMutation) CustomerCleared() bool { + return m.clearedcustomer +} + +// CustomerIDs returns the "customer" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CustomerID instead. It exists only for internal usage by the builders. +func (m *ChargeCreditPurchaseMutation) CustomerIDs() (ids []string) { + if id := m.customer; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCustomer resets all changes to the "customer" edge. +func (m *ChargeCreditPurchaseMutation) ResetCustomer() { + m.customer = nil + m.clearedcustomer = false +} + +// ClearTaxCode clears the "tax_code" edge to the TaxCode entity. +func (m *ChargeCreditPurchaseMutation) ClearTaxCode() { + m.clearedtax_code = true + m.clearedFields[chargecreditpurchase.FieldTaxCodeID] = struct{}{} +} + +// TaxCodeCleared reports if the "tax_code" edge to the TaxCode entity was cleared. +func (m *ChargeCreditPurchaseMutation) TaxCodeCleared() bool { + return m.clearedtax_code +} + +// TaxCodeIDs returns the "tax_code" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TaxCodeID instead. It exists only for internal usage by the builders. +func (m *ChargeCreditPurchaseMutation) TaxCodeIDs() (ids []string) { + if id := m.tax_code; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTaxCode resets all changes to the "tax_code" edge. +func (m *ChargeCreditPurchaseMutation) ResetTaxCode() { + m.tax_code = nil + m.clearedtax_code = false +} + +// Where appends a list predicates to the ChargeCreditPurchaseMutation builder. +func (m *ChargeCreditPurchaseMutation) Where(ps ...predicate.ChargeCreditPurchase) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ChargeCreditPurchaseMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ChargeCreditPurchaseMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ChargeCreditPurchase, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ChargeCreditPurchaseMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ChargeCreditPurchaseMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ChargeCreditPurchase). +func (m *ChargeCreditPurchaseMutation) 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 *ChargeCreditPurchaseMutation) Fields() []string { + fields := make([]string, 0, 34) + if m.customer != nil { + fields = append(fields, chargecreditpurchase.FieldCustomerID) + } + if m.service_period_from != nil { + fields = append(fields, chargecreditpurchase.FieldServicePeriodFrom) + } + if m.service_period_to != nil { + fields = append(fields, chargecreditpurchase.FieldServicePeriodTo) + } + if m.billing_period_from != nil { + fields = append(fields, chargecreditpurchase.FieldBillingPeriodFrom) + } + if m.billing_period_to != nil { + fields = append(fields, chargecreditpurchase.FieldBillingPeriodTo) + } + if m.full_service_period_from != nil { + fields = append(fields, chargecreditpurchase.FieldFullServicePeriodFrom) + } + if m.full_service_period_to != nil { + fields = append(fields, chargecreditpurchase.FieldFullServicePeriodTo) + } + if m.status != nil { + fields = append(fields, chargecreditpurchase.FieldStatus) + } + if m.unique_reference_id != nil { + fields = append(fields, chargecreditpurchase.FieldUniqueReferenceID) + } + if m.currency != nil { + fields = append(fields, chargecreditpurchase.FieldCurrency) + } + if m.managed_by != nil { + fields = append(fields, chargecreditpurchase.FieldManagedBy) + } + if m.subscription != nil { + fields = append(fields, chargecreditpurchase.FieldSubscriptionID) + } + if m.subscription_phase != nil { + fields = append(fields, chargecreditpurchase.FieldSubscriptionPhaseID) + } + if m.subscription_item != nil { + fields = append(fields, chargecreditpurchase.FieldSubscriptionItemID) + } + if m.advance_after != nil { + fields = append(fields, chargecreditpurchase.FieldAdvanceAfter) + } + if m.tax_code != nil { + fields = append(fields, chargecreditpurchase.FieldTaxCodeID) + } + if m.tax_behavior != nil { + fields = append(fields, chargecreditpurchase.FieldTaxBehavior) + } + if m.annotations != nil { + fields = append(fields, chargecreditpurchase.FieldAnnotations) + } + if m.namespace != nil { + fields = append(fields, chargecreditpurchase.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, chargecreditpurchase.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, chargecreditpurchase.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, chargecreditpurchase.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, chargecreditpurchase.FieldDeletedAt) + } + if m.name != nil { + fields = append(fields, chargecreditpurchase.FieldName) + } + if m.description != nil { + fields = append(fields, chargecreditpurchase.FieldDescription) + } + if m.credit_amount != nil { + fields = append(fields, chargecreditpurchase.FieldCreditAmount) + } + if m.effective_at != nil { + fields = append(fields, chargecreditpurchase.FieldEffectiveAt) + } + if m.expires_at != nil { + fields = append(fields, chargecreditpurchase.FieldExpiresAt) + } + if m.priority != nil { + fields = append(fields, chargecreditpurchase.FieldPriority) + } + if m.feature_filters != nil { + fields = append(fields, chargecreditpurchase.FieldFeatureFilters) + } + if m.settlement != nil { + fields = append(fields, chargecreditpurchase.FieldSettlement) + } + if m.status_detailed != nil { + fields = append(fields, chargecreditpurchase.FieldStatusDetailed) + } + if m.key != nil { + fields = append(fields, chargecreditpurchase.FieldKey) + } + if m.voided_at != nil { + fields = append(fields, chargecreditpurchase.FieldVoidedAt) + } + 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 *ChargeCreditPurchaseMutation) Field(name string) (ent.Value, bool) { + switch name { + case chargecreditpurchase.FieldCustomerID: + return m.CustomerID() + case chargecreditpurchase.FieldServicePeriodFrom: + return m.ServicePeriodFrom() + case chargecreditpurchase.FieldServicePeriodTo: + return m.ServicePeriodTo() + case chargecreditpurchase.FieldBillingPeriodFrom: + return m.BillingPeriodFrom() + case chargecreditpurchase.FieldBillingPeriodTo: + return m.BillingPeriodTo() + case chargecreditpurchase.FieldFullServicePeriodFrom: + return m.FullServicePeriodFrom() + case chargecreditpurchase.FieldFullServicePeriodTo: + return m.FullServicePeriodTo() + case chargecreditpurchase.FieldStatus: + return m.Status() + case chargecreditpurchase.FieldUniqueReferenceID: + return m.UniqueReferenceID() + case chargecreditpurchase.FieldCurrency: + return m.Currency() + case chargecreditpurchase.FieldManagedBy: + return m.ManagedBy() + case chargecreditpurchase.FieldSubscriptionID: + return m.SubscriptionID() + case chargecreditpurchase.FieldSubscriptionPhaseID: + return m.SubscriptionPhaseID() + case chargecreditpurchase.FieldSubscriptionItemID: + return m.SubscriptionItemID() + case chargecreditpurchase.FieldAdvanceAfter: + return m.AdvanceAfter() + case chargecreditpurchase.FieldTaxCodeID: + return m.TaxCodeID() + case chargecreditpurchase.FieldTaxBehavior: + return m.TaxBehavior() + case chargecreditpurchase.FieldAnnotations: + return m.Annotations() + case chargecreditpurchase.FieldNamespace: + return m.Namespace() + case chargecreditpurchase.FieldMetadata: + return m.Metadata() + case chargecreditpurchase.FieldCreatedAt: + return m.CreatedAt() + case chargecreditpurchase.FieldUpdatedAt: + return m.UpdatedAt() + case chargecreditpurchase.FieldDeletedAt: + return m.DeletedAt() + case chargecreditpurchase.FieldName: + return m.Name() + case chargecreditpurchase.FieldDescription: + return m.Description() + case chargecreditpurchase.FieldCreditAmount: + return m.CreditAmount() + case chargecreditpurchase.FieldEffectiveAt: + return m.EffectiveAt() + case chargecreditpurchase.FieldExpiresAt: + return m.ExpiresAt() + case chargecreditpurchase.FieldPriority: + return m.Priority() + case chargecreditpurchase.FieldFeatureFilters: + return m.FeatureFilters() + case chargecreditpurchase.FieldSettlement: + return m.Settlement() + case chargecreditpurchase.FieldStatusDetailed: + return m.StatusDetailed() + case chargecreditpurchase.FieldKey: + return m.Key() + case chargecreditpurchase.FieldVoidedAt: + return m.VoidedAt() + } + 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 *ChargeCreditPurchaseMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case chargecreditpurchase.FieldCustomerID: + return m.OldCustomerID(ctx) + case chargecreditpurchase.FieldServicePeriodFrom: + return m.OldServicePeriodFrom(ctx) + case chargecreditpurchase.FieldServicePeriodTo: + return m.OldServicePeriodTo(ctx) + case chargecreditpurchase.FieldBillingPeriodFrom: + return m.OldBillingPeriodFrom(ctx) + case chargecreditpurchase.FieldBillingPeriodTo: + return m.OldBillingPeriodTo(ctx) + case chargecreditpurchase.FieldFullServicePeriodFrom: + return m.OldFullServicePeriodFrom(ctx) + case chargecreditpurchase.FieldFullServicePeriodTo: + return m.OldFullServicePeriodTo(ctx) + case chargecreditpurchase.FieldStatus: + return m.OldStatus(ctx) + case chargecreditpurchase.FieldUniqueReferenceID: + return m.OldUniqueReferenceID(ctx) + case chargecreditpurchase.FieldCurrency: + return m.OldCurrency(ctx) + case chargecreditpurchase.FieldManagedBy: + return m.OldManagedBy(ctx) + case chargecreditpurchase.FieldSubscriptionID: + return m.OldSubscriptionID(ctx) + case chargecreditpurchase.FieldSubscriptionPhaseID: + return m.OldSubscriptionPhaseID(ctx) + case chargecreditpurchase.FieldSubscriptionItemID: + return m.OldSubscriptionItemID(ctx) + case chargecreditpurchase.FieldAdvanceAfter: + return m.OldAdvanceAfter(ctx) + case chargecreditpurchase.FieldTaxCodeID: + return m.OldTaxCodeID(ctx) + case chargecreditpurchase.FieldTaxBehavior: + return m.OldTaxBehavior(ctx) + case chargecreditpurchase.FieldAnnotations: + return m.OldAnnotations(ctx) + case chargecreditpurchase.FieldNamespace: + return m.OldNamespace(ctx) + case chargecreditpurchase.FieldMetadata: + return m.OldMetadata(ctx) + case chargecreditpurchase.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case chargecreditpurchase.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case chargecreditpurchase.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case chargecreditpurchase.FieldName: + return m.OldName(ctx) + case chargecreditpurchase.FieldDescription: + return m.OldDescription(ctx) + case chargecreditpurchase.FieldCreditAmount: + return m.OldCreditAmount(ctx) + case chargecreditpurchase.FieldEffectiveAt: + return m.OldEffectiveAt(ctx) + case chargecreditpurchase.FieldExpiresAt: + return m.OldExpiresAt(ctx) + case chargecreditpurchase.FieldPriority: + return m.OldPriority(ctx) + case chargecreditpurchase.FieldFeatureFilters: + return m.OldFeatureFilters(ctx) + case chargecreditpurchase.FieldSettlement: + return m.OldSettlement(ctx) + case chargecreditpurchase.FieldStatusDetailed: + return m.OldStatusDetailed(ctx) + case chargecreditpurchase.FieldKey: + return m.OldKey(ctx) + case chargecreditpurchase.FieldVoidedAt: + return m.OldVoidedAt(ctx) + } + return nil, fmt.Errorf("unknown ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) SetField(name string, value ent.Value) error { + switch name { + case chargecreditpurchase.FieldCustomerID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerID(v) + return nil + case chargecreditpurchase.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 chargecreditpurchase.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 chargecreditpurchase.FieldBillingPeriodFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingPeriodFrom(v) + return nil + case chargecreditpurchase.FieldBillingPeriodTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingPeriodTo(v) + return nil + case chargecreditpurchase.FieldFullServicePeriodFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFullServicePeriodFrom(v) + return nil + case chargecreditpurchase.FieldFullServicePeriodTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFullServicePeriodTo(v) + return nil + case chargecreditpurchase.FieldStatus: + v, ok := value.(meta.ChargeStatus) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case chargecreditpurchase.FieldUniqueReferenceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUniqueReferenceID(v) + return nil + case chargecreditpurchase.FieldCurrency: + v, ok := value.(currencyx.Code) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrency(v) + return nil + case chargecreditpurchase.FieldManagedBy: + v, ok := value.(billing.InvoiceLineManagedBy) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetManagedBy(v) + return nil + case chargecreditpurchase.FieldSubscriptionID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionID(v) + return nil + case chargecreditpurchase.FieldSubscriptionPhaseID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionPhaseID(v) + return nil + case chargecreditpurchase.FieldSubscriptionItemID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionItemID(v) + return nil + case chargecreditpurchase.FieldAdvanceAfter: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAdvanceAfter(v) + return nil + case chargecreditpurchase.FieldTaxCodeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxCodeID(v) + return nil + case chargecreditpurchase.FieldTaxBehavior: + v, ok := value.(productcatalog.TaxBehavior) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxBehavior(v) + return nil + case chargecreditpurchase.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 chargecreditpurchase.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case chargecreditpurchase.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case chargecreditpurchase.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 chargecreditpurchase.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 chargecreditpurchase.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 chargecreditpurchase.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case chargecreditpurchase.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case chargecreditpurchase.FieldCreditAmount: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreditAmount(v) + return nil + case chargecreditpurchase.FieldEffectiveAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEffectiveAt(v) + return nil + case chargecreditpurchase.FieldExpiresAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetExpiresAt(v) + return nil + case chargecreditpurchase.FieldPriority: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPriority(v) + return nil + case chargecreditpurchase.FieldFeatureFilters: + v, ok := value.(pq.StringArray) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFeatureFilters(v) + return nil + case chargecreditpurchase.FieldSettlement: + v, ok := value.(creditpurchase.Settlement) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSettlement(v) + return nil + case chargecreditpurchase.FieldStatusDetailed: + v, ok := value.(creditpurchase.Status) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatusDetailed(v) + return nil + case chargecreditpurchase.FieldKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKey(v) + return nil + case chargecreditpurchase.FieldVoidedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVoidedAt(v) + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchase field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ChargeCreditPurchaseMutation) AddedFields() []string { + var fields []string + if m.addpriority != nil { + fields = append(fields, chargecreditpurchase.FieldPriority) + } + return fields +} + +// 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 *ChargeCreditPurchaseMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case chargecreditpurchase.FieldPriority: + return m.AddedPriority() + } + 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 *ChargeCreditPurchaseMutation) AddField(name string, value ent.Value) error { + switch name { + case chargecreditpurchase.FieldPriority: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddPriority(v) + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchase numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ChargeCreditPurchaseMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(chargecreditpurchase.FieldUniqueReferenceID) { + fields = append(fields, chargecreditpurchase.FieldUniqueReferenceID) + } + if m.FieldCleared(chargecreditpurchase.FieldSubscriptionID) { + fields = append(fields, chargecreditpurchase.FieldSubscriptionID) + } + if m.FieldCleared(chargecreditpurchase.FieldSubscriptionPhaseID) { + fields = append(fields, chargecreditpurchase.FieldSubscriptionPhaseID) + } + if m.FieldCleared(chargecreditpurchase.FieldSubscriptionItemID) { + fields = append(fields, chargecreditpurchase.FieldSubscriptionItemID) + } + if m.FieldCleared(chargecreditpurchase.FieldAdvanceAfter) { + fields = append(fields, chargecreditpurchase.FieldAdvanceAfter) + } + if m.FieldCleared(chargecreditpurchase.FieldTaxBehavior) { + fields = append(fields, chargecreditpurchase.FieldTaxBehavior) + } + if m.FieldCleared(chargecreditpurchase.FieldAnnotations) { + fields = append(fields, chargecreditpurchase.FieldAnnotations) + } + if m.FieldCleared(chargecreditpurchase.FieldMetadata) { + fields = append(fields, chargecreditpurchase.FieldMetadata) + } + if m.FieldCleared(chargecreditpurchase.FieldDeletedAt) { + fields = append(fields, chargecreditpurchase.FieldDeletedAt) + } + if m.FieldCleared(chargecreditpurchase.FieldDescription) { + fields = append(fields, chargecreditpurchase.FieldDescription) + } + if m.FieldCleared(chargecreditpurchase.FieldEffectiveAt) { + fields = append(fields, chargecreditpurchase.FieldEffectiveAt) + } + if m.FieldCleared(chargecreditpurchase.FieldExpiresAt) { + fields = append(fields, chargecreditpurchase.FieldExpiresAt) + } + if m.FieldCleared(chargecreditpurchase.FieldPriority) { + fields = append(fields, chargecreditpurchase.FieldPriority) + } + if m.FieldCleared(chargecreditpurchase.FieldFeatureFilters) { + fields = append(fields, chargecreditpurchase.FieldFeatureFilters) + } + if m.FieldCleared(chargecreditpurchase.FieldKey) { + fields = append(fields, chargecreditpurchase.FieldKey) + } + if m.FieldCleared(chargecreditpurchase.FieldVoidedAt) { + fields = append(fields, chargecreditpurchase.FieldVoidedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ChargeCreditPurchaseMutation) 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 *ChargeCreditPurchaseMutation) ClearField(name string) error { + switch name { + case chargecreditpurchase.FieldUniqueReferenceID: + m.ClearUniqueReferenceID() + return nil + case chargecreditpurchase.FieldSubscriptionID: + m.ClearSubscriptionID() + return nil + case chargecreditpurchase.FieldSubscriptionPhaseID: + m.ClearSubscriptionPhaseID() + return nil + case chargecreditpurchase.FieldSubscriptionItemID: + m.ClearSubscriptionItemID() + return nil + case chargecreditpurchase.FieldAdvanceAfter: + m.ClearAdvanceAfter() + return nil + case chargecreditpurchase.FieldTaxBehavior: + m.ClearTaxBehavior() + return nil + case chargecreditpurchase.FieldAnnotations: + m.ClearAnnotations() + return nil + case chargecreditpurchase.FieldMetadata: + m.ClearMetadata() + return nil + case chargecreditpurchase.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case chargecreditpurchase.FieldDescription: + m.ClearDescription() + return nil + case chargecreditpurchase.FieldEffectiveAt: + m.ClearEffectiveAt() + return nil + case chargecreditpurchase.FieldExpiresAt: + m.ClearExpiresAt() + return nil + case chargecreditpurchase.FieldPriority: + m.ClearPriority() + return nil + case chargecreditpurchase.FieldFeatureFilters: + m.ClearFeatureFilters() + return nil + case chargecreditpurchase.FieldKey: + m.ClearKey() + return nil + case chargecreditpurchase.FieldVoidedAt: + m.ClearVoidedAt() + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) ResetField(name string) error { + switch name { + case chargecreditpurchase.FieldCustomerID: + m.ResetCustomerID() + return nil + case chargecreditpurchase.FieldServicePeriodFrom: + m.ResetServicePeriodFrom() + return nil + case chargecreditpurchase.FieldServicePeriodTo: + m.ResetServicePeriodTo() + return nil + case chargecreditpurchase.FieldBillingPeriodFrom: + m.ResetBillingPeriodFrom() + return nil + case chargecreditpurchase.FieldBillingPeriodTo: + m.ResetBillingPeriodTo() + return nil + case chargecreditpurchase.FieldFullServicePeriodFrom: + m.ResetFullServicePeriodFrom() + return nil + case chargecreditpurchase.FieldFullServicePeriodTo: + m.ResetFullServicePeriodTo() + return nil + case chargecreditpurchase.FieldStatus: + m.ResetStatus() + return nil + case chargecreditpurchase.FieldUniqueReferenceID: + m.ResetUniqueReferenceID() + return nil + case chargecreditpurchase.FieldCurrency: + m.ResetCurrency() + return nil + case chargecreditpurchase.FieldManagedBy: + m.ResetManagedBy() + return nil + case chargecreditpurchase.FieldSubscriptionID: + m.ResetSubscriptionID() + return nil + case chargecreditpurchase.FieldSubscriptionPhaseID: + m.ResetSubscriptionPhaseID() + return nil + case chargecreditpurchase.FieldSubscriptionItemID: + m.ResetSubscriptionItemID() + return nil + case chargecreditpurchase.FieldAdvanceAfter: + m.ResetAdvanceAfter() + return nil + case chargecreditpurchase.FieldTaxCodeID: + m.ResetTaxCodeID() + return nil + case chargecreditpurchase.FieldTaxBehavior: + m.ResetTaxBehavior() + return nil + case chargecreditpurchase.FieldAnnotations: + m.ResetAnnotations() + return nil + case chargecreditpurchase.FieldNamespace: + m.ResetNamespace() + return nil + case chargecreditpurchase.FieldMetadata: + m.ResetMetadata() + return nil + case chargecreditpurchase.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case chargecreditpurchase.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case chargecreditpurchase.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case chargecreditpurchase.FieldName: + m.ResetName() + return nil + case chargecreditpurchase.FieldDescription: + m.ResetDescription() + return nil + case chargecreditpurchase.FieldCreditAmount: + m.ResetCreditAmount() + return nil + case chargecreditpurchase.FieldEffectiveAt: + m.ResetEffectiveAt() + return nil + case chargecreditpurchase.FieldExpiresAt: + m.ResetExpiresAt() + return nil + case chargecreditpurchase.FieldPriority: + m.ResetPriority() + return nil + case chargecreditpurchase.FieldFeatureFilters: + m.ResetFeatureFilters() + return nil + case chargecreditpurchase.FieldSettlement: + m.ResetSettlement() + return nil + case chargecreditpurchase.FieldStatusDetailed: + m.ResetStatusDetailed() + return nil + case chargecreditpurchase.FieldKey: + m.ResetKey() + return nil + case chargecreditpurchase.FieldVoidedAt: + m.ResetVoidedAt() + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchase field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ChargeCreditPurchaseMutation) AddedEdges() []string { + edges := make([]string, 0, 9) + if m.external_payment != nil { + edges = append(edges, chargecreditpurchase.EdgeExternalPayment) + } + if m.invoiced_payment != nil { + edges = append(edges, chargecreditpurchase.EdgeInvoicedPayment) + } + if m.credit_grant != nil { + edges = append(edges, chargecreditpurchase.EdgeCreditGrant) + } + if m.charge != nil { + edges = append(edges, chargecreditpurchase.EdgeCharge) + } + if m.subscription != nil { + edges = append(edges, chargecreditpurchase.EdgeSubscription) + } + if m.subscription_phase != nil { + edges = append(edges, chargecreditpurchase.EdgeSubscriptionPhase) + } + if m.subscription_item != nil { + edges = append(edges, chargecreditpurchase.EdgeSubscriptionItem) + } + if m.customer != nil { + edges = append(edges, chargecreditpurchase.EdgeCustomer) + } + if m.tax_code != nil { + edges = append(edges, chargecreditpurchase.EdgeTaxCode) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ChargeCreditPurchaseMutation) AddedIDs(name string) []ent.Value { + switch name { + case chargecreditpurchase.EdgeExternalPayment: + if id := m.external_payment; id != nil { + return []ent.Value{*id} + } + case chargecreditpurchase.EdgeInvoicedPayment: + if id := m.invoiced_payment; id != nil { + return []ent.Value{*id} + } + case chargecreditpurchase.EdgeCreditGrant: + if id := m.credit_grant; id != nil { + return []ent.Value{*id} + } + case chargecreditpurchase.EdgeCharge: + if id := m.charge; id != nil { + return []ent.Value{*id} + } + case chargecreditpurchase.EdgeSubscription: + if id := m.subscription; id != nil { + return []ent.Value{*id} + } + case chargecreditpurchase.EdgeSubscriptionPhase: + if id := m.subscription_phase; id != nil { + return []ent.Value{*id} + } + case chargecreditpurchase.EdgeSubscriptionItem: + if id := m.subscription_item; id != nil { + return []ent.Value{*id} + } + case chargecreditpurchase.EdgeCustomer: + if id := m.customer; id != nil { + return []ent.Value{*id} + } + case chargecreditpurchase.EdgeTaxCode: + if id := m.tax_code; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ChargeCreditPurchaseMutation) RemovedEdges() []string { + edges := make([]string, 0, 9) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ChargeCreditPurchaseMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ChargeCreditPurchaseMutation) ClearedEdges() []string { + edges := make([]string, 0, 9) + if m.clearedexternal_payment { + edges = append(edges, chargecreditpurchase.EdgeExternalPayment) + } + if m.clearedinvoiced_payment { + edges = append(edges, chargecreditpurchase.EdgeInvoicedPayment) + } + if m.clearedcredit_grant { + edges = append(edges, chargecreditpurchase.EdgeCreditGrant) + } + if m.clearedcharge { + edges = append(edges, chargecreditpurchase.EdgeCharge) + } + if m.clearedsubscription { + edges = append(edges, chargecreditpurchase.EdgeSubscription) + } + if m.clearedsubscription_phase { + edges = append(edges, chargecreditpurchase.EdgeSubscriptionPhase) + } + if m.clearedsubscription_item { + edges = append(edges, chargecreditpurchase.EdgeSubscriptionItem) + } + if m.clearedcustomer { + edges = append(edges, chargecreditpurchase.EdgeCustomer) + } + if m.clearedtax_code { + edges = append(edges, chargecreditpurchase.EdgeTaxCode) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ChargeCreditPurchaseMutation) EdgeCleared(name string) bool { + switch name { + case chargecreditpurchase.EdgeExternalPayment: + return m.clearedexternal_payment + case chargecreditpurchase.EdgeInvoicedPayment: + return m.clearedinvoiced_payment + case chargecreditpurchase.EdgeCreditGrant: + return m.clearedcredit_grant + case chargecreditpurchase.EdgeCharge: + return m.clearedcharge + case chargecreditpurchase.EdgeSubscription: + return m.clearedsubscription + case chargecreditpurchase.EdgeSubscriptionPhase: + return m.clearedsubscription_phase + case chargecreditpurchase.EdgeSubscriptionItem: + return m.clearedsubscription_item + case chargecreditpurchase.EdgeCustomer: + return m.clearedcustomer + case chargecreditpurchase.EdgeTaxCode: + return m.clearedtax_code + } + 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 *ChargeCreditPurchaseMutation) ClearEdge(name string) error { + switch name { + case chargecreditpurchase.EdgeExternalPayment: + m.ClearExternalPayment() + return nil + case chargecreditpurchase.EdgeInvoicedPayment: + m.ClearInvoicedPayment() + return nil + case chargecreditpurchase.EdgeCreditGrant: + m.ClearCreditGrant() + return nil + case chargecreditpurchase.EdgeCharge: + m.ClearCharge() + return nil + case chargecreditpurchase.EdgeSubscription: + m.ClearSubscription() + return nil + case chargecreditpurchase.EdgeSubscriptionPhase: + m.ClearSubscriptionPhase() + return nil + case chargecreditpurchase.EdgeSubscriptionItem: + m.ClearSubscriptionItem() + return nil + case chargecreditpurchase.EdgeCustomer: + m.ClearCustomer() + return nil + case chargecreditpurchase.EdgeTaxCode: + m.ClearTaxCode() + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchase 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 *ChargeCreditPurchaseMutation) ResetEdge(name string) error { + switch name { + case chargecreditpurchase.EdgeExternalPayment: + m.ResetExternalPayment() + return nil + case chargecreditpurchase.EdgeInvoicedPayment: + m.ResetInvoicedPayment() + return nil + case chargecreditpurchase.EdgeCreditGrant: + m.ResetCreditGrant() + return nil + case chargecreditpurchase.EdgeCharge: + m.ResetCharge() + return nil + case chargecreditpurchase.EdgeSubscription: + m.ResetSubscription() + return nil + case chargecreditpurchase.EdgeSubscriptionPhase: + m.ResetSubscriptionPhase() + return nil + case chargecreditpurchase.EdgeSubscriptionItem: + m.ResetSubscriptionItem() + return nil + case chargecreditpurchase.EdgeCustomer: + m.ResetCustomer() + return nil + case chargecreditpurchase.EdgeTaxCode: + m.ResetTaxCode() + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchase edge %s", name) +} + +// ChargeCreditPurchaseCreditGrantMutation represents an operation that mutates the ChargeCreditPurchaseCreditGrant nodes in the graph. +type ChargeCreditPurchaseCreditGrantMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + transaction_group_id *string + granted_at *time.Time + clearedFields map[string]struct{} + credit_purchase *string + clearedcredit_purchase bool + done bool + oldValue func(context.Context) (*ChargeCreditPurchaseCreditGrant, error) + predicates []predicate.ChargeCreditPurchaseCreditGrant +} + +var _ ent.Mutation = (*ChargeCreditPurchaseCreditGrantMutation)(nil) + +// chargecreditpurchasecreditgrantOption allows management of the mutation configuration using functional options. +type chargecreditpurchasecreditgrantOption func(*ChargeCreditPurchaseCreditGrantMutation) + +// newChargeCreditPurchaseCreditGrantMutation creates new mutation for the ChargeCreditPurchaseCreditGrant entity. +func newChargeCreditPurchaseCreditGrantMutation(c config, op Op, opts ...chargecreditpurchasecreditgrantOption) *ChargeCreditPurchaseCreditGrantMutation { + m := &ChargeCreditPurchaseCreditGrantMutation{ + config: c, + op: op, + typ: TypeChargeCreditPurchaseCreditGrant, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withChargeCreditPurchaseCreditGrantID sets the ID field of the mutation. +func withChargeCreditPurchaseCreditGrantID(id string) chargecreditpurchasecreditgrantOption { + return func(m *ChargeCreditPurchaseCreditGrantMutation) { + var ( + err error + once sync.Once + value *ChargeCreditPurchaseCreditGrant + ) + m.oldValue = func(ctx context.Context) (*ChargeCreditPurchaseCreditGrant, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ChargeCreditPurchaseCreditGrant.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withChargeCreditPurchaseCreditGrant sets the old ChargeCreditPurchaseCreditGrant of the mutation. +func withChargeCreditPurchaseCreditGrant(node *ChargeCreditPurchaseCreditGrant) chargecreditpurchasecreditgrantOption { + return func(m *ChargeCreditPurchaseCreditGrantMutation) { + m.oldValue = func(context.Context) (*ChargeCreditPurchaseCreditGrant, 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 ChargeCreditPurchaseCreditGrantMutation) 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 ChargeCreditPurchaseCreditGrantMutation) 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 ChargeCreditPurchaseCreditGrant entities. +func (m *ChargeCreditPurchaseCreditGrantMutation) 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 *ChargeCreditPurchaseCreditGrantMutation) 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 *ChargeCreditPurchaseCreditGrantMutation) 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().ChargeCreditPurchaseCreditGrant.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 *ChargeCreditPurchaseCreditGrantMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *ChargeCreditPurchaseCreditGrantMutation) 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 ChargeCreditPurchaseCreditGrant entity. +// If the ChargeCreditPurchaseCreditGrant 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 *ChargeCreditPurchaseCreditGrantMutation) 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 *ChargeCreditPurchaseCreditGrantMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *ChargeCreditPurchaseCreditGrantMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ChargeCreditPurchaseCreditGrantMutation) 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 ChargeCreditPurchaseCreditGrant entity. +// If the ChargeCreditPurchaseCreditGrant 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 *ChargeCreditPurchaseCreditGrantMutation) 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 *ChargeCreditPurchaseCreditGrantMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *ChargeCreditPurchaseCreditGrantMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ChargeCreditPurchaseCreditGrantMutation) 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 ChargeCreditPurchaseCreditGrant entity. +// If the ChargeCreditPurchaseCreditGrant 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 *ChargeCreditPurchaseCreditGrantMutation) 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 *ChargeCreditPurchaseCreditGrantMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *ChargeCreditPurchaseCreditGrantMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *ChargeCreditPurchaseCreditGrantMutation) 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 ChargeCreditPurchaseCreditGrant entity. +// If the ChargeCreditPurchaseCreditGrant 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 *ChargeCreditPurchaseCreditGrantMutation) 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 *ChargeCreditPurchaseCreditGrantMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[chargecreditpurchasecreditgrant.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *ChargeCreditPurchaseCreditGrantMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[chargecreditpurchasecreditgrant.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *ChargeCreditPurchaseCreditGrantMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, chargecreditpurchasecreditgrant.FieldDeletedAt) +} + +// SetChargeID sets the "charge_id" field. +func (m *ChargeCreditPurchaseCreditGrantMutation) SetChargeID(s string) { + m.credit_purchase = &s +} + +// ChargeID returns the value of the "charge_id" field in the mutation. +func (m *ChargeCreditPurchaseCreditGrantMutation) ChargeID() (r string, exists bool) { + v := m.credit_purchase + if v == nil { + return + } + return *v, true +} + +// OldChargeID returns the old "charge_id" field's value of the ChargeCreditPurchaseCreditGrant entity. +// If the ChargeCreditPurchaseCreditGrant 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 *ChargeCreditPurchaseCreditGrantMutation) 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 *ChargeCreditPurchaseCreditGrantMutation) ResetChargeID() { + m.credit_purchase = nil +} + +// SetTransactionGroupID sets the "transaction_group_id" field. +func (m *ChargeCreditPurchaseCreditGrantMutation) SetTransactionGroupID(s string) { + m.transaction_group_id = &s +} + +// TransactionGroupID returns the value of the "transaction_group_id" field in the mutation. +func (m *ChargeCreditPurchaseCreditGrantMutation) TransactionGroupID() (r string, exists bool) { + v := m.transaction_group_id + if v == nil { + return + } + return *v, true +} + +// OldTransactionGroupID returns the old "transaction_group_id" field's value of the ChargeCreditPurchaseCreditGrant entity. +// If the ChargeCreditPurchaseCreditGrant 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 *ChargeCreditPurchaseCreditGrantMutation) OldTransactionGroupID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTransactionGroupID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTransactionGroupID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTransactionGroupID: %w", err) + } + return oldValue.TransactionGroupID, nil +} + +// ResetTransactionGroupID resets all changes to the "transaction_group_id" field. +func (m *ChargeCreditPurchaseCreditGrantMutation) ResetTransactionGroupID() { + m.transaction_group_id = nil +} + +// SetGrantedAt sets the "granted_at" field. +func (m *ChargeCreditPurchaseCreditGrantMutation) SetGrantedAt(t time.Time) { + m.granted_at = &t +} + +// GrantedAt returns the value of the "granted_at" field in the mutation. +func (m *ChargeCreditPurchaseCreditGrantMutation) GrantedAt() (r time.Time, exists bool) { + v := m.granted_at + if v == nil { + return + } + return *v, true +} + +// OldGrantedAt returns the old "granted_at" field's value of the ChargeCreditPurchaseCreditGrant entity. +// If the ChargeCreditPurchaseCreditGrant 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 *ChargeCreditPurchaseCreditGrantMutation) OldGrantedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldGrantedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldGrantedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldGrantedAt: %w", err) + } + return oldValue.GrantedAt, nil +} + +// ResetGrantedAt resets all changes to the "granted_at" field. +func (m *ChargeCreditPurchaseCreditGrantMutation) ResetGrantedAt() { + m.granted_at = nil +} + +// SetCreditPurchaseID sets the "credit_purchase" edge to the ChargeCreditPurchase entity by id. +func (m *ChargeCreditPurchaseCreditGrantMutation) SetCreditPurchaseID(id string) { + m.credit_purchase = &id +} + +// ClearCreditPurchase clears the "credit_purchase" edge to the ChargeCreditPurchase entity. +func (m *ChargeCreditPurchaseCreditGrantMutation) ClearCreditPurchase() { + m.clearedcredit_purchase = true + m.clearedFields[chargecreditpurchasecreditgrant.FieldChargeID] = struct{}{} +} + +// CreditPurchaseCleared reports if the "credit_purchase" edge to the ChargeCreditPurchase entity was cleared. +func (m *ChargeCreditPurchaseCreditGrantMutation) CreditPurchaseCleared() bool { + return m.clearedcredit_purchase +} + +// CreditPurchaseID returns the "credit_purchase" edge ID in the mutation. +func (m *ChargeCreditPurchaseCreditGrantMutation) CreditPurchaseID() (id string, exists bool) { + if m.credit_purchase != nil { + return *m.credit_purchase, true + } + return +} + +// CreditPurchaseIDs returns the "credit_purchase" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CreditPurchaseID instead. It exists only for internal usage by the builders. +func (m *ChargeCreditPurchaseCreditGrantMutation) CreditPurchaseIDs() (ids []string) { + if id := m.credit_purchase; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCreditPurchase resets all changes to the "credit_purchase" edge. +func (m *ChargeCreditPurchaseCreditGrantMutation) ResetCreditPurchase() { + m.credit_purchase = nil + m.clearedcredit_purchase = false +} + +// Where appends a list predicates to the ChargeCreditPurchaseCreditGrantMutation builder. +func (m *ChargeCreditPurchaseCreditGrantMutation) Where(ps ...predicate.ChargeCreditPurchaseCreditGrant) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ChargeCreditPurchaseCreditGrantMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ChargeCreditPurchaseCreditGrantMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ChargeCreditPurchaseCreditGrant, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ChargeCreditPurchaseCreditGrantMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ChargeCreditPurchaseCreditGrantMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ChargeCreditPurchaseCreditGrant). +func (m *ChargeCreditPurchaseCreditGrantMutation) 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 *ChargeCreditPurchaseCreditGrantMutation) Fields() []string { + fields := make([]string, 0, 7) + if m.namespace != nil { + fields = append(fields, chargecreditpurchasecreditgrant.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, chargecreditpurchasecreditgrant.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, chargecreditpurchasecreditgrant.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, chargecreditpurchasecreditgrant.FieldDeletedAt) + } + if m.credit_purchase != nil { + fields = append(fields, chargecreditpurchasecreditgrant.FieldChargeID) + } + if m.transaction_group_id != nil { + fields = append(fields, chargecreditpurchasecreditgrant.FieldTransactionGroupID) + } + if m.granted_at != nil { + fields = append(fields, chargecreditpurchasecreditgrant.FieldGrantedAt) + } + 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 *ChargeCreditPurchaseCreditGrantMutation) Field(name string) (ent.Value, bool) { + switch name { + case chargecreditpurchasecreditgrant.FieldNamespace: + return m.Namespace() + case chargecreditpurchasecreditgrant.FieldCreatedAt: + return m.CreatedAt() + case chargecreditpurchasecreditgrant.FieldUpdatedAt: + return m.UpdatedAt() + case chargecreditpurchasecreditgrant.FieldDeletedAt: + return m.DeletedAt() + case chargecreditpurchasecreditgrant.FieldChargeID: + return m.ChargeID() + case chargecreditpurchasecreditgrant.FieldTransactionGroupID: + return m.TransactionGroupID() + case chargecreditpurchasecreditgrant.FieldGrantedAt: + return m.GrantedAt() + } + 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 *ChargeCreditPurchaseCreditGrantMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case chargecreditpurchasecreditgrant.FieldNamespace: + return m.OldNamespace(ctx) + case chargecreditpurchasecreditgrant.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case chargecreditpurchasecreditgrant.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case chargecreditpurchasecreditgrant.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case chargecreditpurchasecreditgrant.FieldChargeID: + return m.OldChargeID(ctx) + case chargecreditpurchasecreditgrant.FieldTransactionGroupID: + return m.OldTransactionGroupID(ctx) + case chargecreditpurchasecreditgrant.FieldGrantedAt: + return m.OldGrantedAt(ctx) + } + return nil, fmt.Errorf("unknown ChargeCreditPurchaseCreditGrant 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 *ChargeCreditPurchaseCreditGrantMutation) SetField(name string, value ent.Value) error { + switch name { + case chargecreditpurchasecreditgrant.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case chargecreditpurchasecreditgrant.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 chargecreditpurchasecreditgrant.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 chargecreditpurchasecreditgrant.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 chargecreditpurchasecreditgrant.FieldChargeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChargeID(v) + return nil + case chargecreditpurchasecreditgrant.FieldTransactionGroupID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTransactionGroupID(v) + return nil + case chargecreditpurchasecreditgrant.FieldGrantedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetGrantedAt(v) + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchaseCreditGrant field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ChargeCreditPurchaseCreditGrantMutation) 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 *ChargeCreditPurchaseCreditGrantMutation) 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 *ChargeCreditPurchaseCreditGrantMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown ChargeCreditPurchaseCreditGrant numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ChargeCreditPurchaseCreditGrantMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(chargecreditpurchasecreditgrant.FieldDeletedAt) { + fields = append(fields, chargecreditpurchasecreditgrant.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ChargeCreditPurchaseCreditGrantMutation) 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 *ChargeCreditPurchaseCreditGrantMutation) ClearField(name string) error { + switch name { + case chargecreditpurchasecreditgrant.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchaseCreditGrant 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 *ChargeCreditPurchaseCreditGrantMutation) ResetField(name string) error { + switch name { + case chargecreditpurchasecreditgrant.FieldNamespace: + m.ResetNamespace() + return nil + case chargecreditpurchasecreditgrant.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case chargecreditpurchasecreditgrant.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case chargecreditpurchasecreditgrant.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case chargecreditpurchasecreditgrant.FieldChargeID: + m.ResetChargeID() + return nil + case chargecreditpurchasecreditgrant.FieldTransactionGroupID: + m.ResetTransactionGroupID() + return nil + case chargecreditpurchasecreditgrant.FieldGrantedAt: + m.ResetGrantedAt() + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchaseCreditGrant field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ChargeCreditPurchaseCreditGrantMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.credit_purchase != nil { + edges = append(edges, chargecreditpurchasecreditgrant.EdgeCreditPurchase) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ChargeCreditPurchaseCreditGrantMutation) AddedIDs(name string) []ent.Value { + switch name { + case chargecreditpurchasecreditgrant.EdgeCreditPurchase: + if id := m.credit_purchase; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ChargeCreditPurchaseCreditGrantMutation) 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 *ChargeCreditPurchaseCreditGrantMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ChargeCreditPurchaseCreditGrantMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedcredit_purchase { + edges = append(edges, chargecreditpurchasecreditgrant.EdgeCreditPurchase) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ChargeCreditPurchaseCreditGrantMutation) EdgeCleared(name string) bool { + switch name { + case chargecreditpurchasecreditgrant.EdgeCreditPurchase: + return m.clearedcredit_purchase + } + 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 *ChargeCreditPurchaseCreditGrantMutation) ClearEdge(name string) error { + switch name { + case chargecreditpurchasecreditgrant.EdgeCreditPurchase: + m.ClearCreditPurchase() + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchaseCreditGrant 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 *ChargeCreditPurchaseCreditGrantMutation) ResetEdge(name string) error { + switch name { + case chargecreditpurchasecreditgrant.EdgeCreditPurchase: + m.ResetCreditPurchase() + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchaseCreditGrant edge %s", name) +} + +// ChargeCreditPurchaseExternalPaymentMutation represents an operation that mutates the ChargeCreditPurchaseExternalPayment nodes in the graph. +type ChargeCreditPurchaseExternalPaymentMutation struct { + config + op Op + typ string + 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{} + credit_purchase *string + clearedcredit_purchase bool + done bool + oldValue func(context.Context) (*ChargeCreditPurchaseExternalPayment, error) + predicates []predicate.ChargeCreditPurchaseExternalPayment +} + +var _ ent.Mutation = (*ChargeCreditPurchaseExternalPaymentMutation)(nil) + +// chargecreditpurchaseexternalpaymentOption allows management of the mutation configuration using functional options. +type chargecreditpurchaseexternalpaymentOption func(*ChargeCreditPurchaseExternalPaymentMutation) + +// newChargeCreditPurchaseExternalPaymentMutation creates new mutation for the ChargeCreditPurchaseExternalPayment entity. +func newChargeCreditPurchaseExternalPaymentMutation(c config, op Op, opts ...chargecreditpurchaseexternalpaymentOption) *ChargeCreditPurchaseExternalPaymentMutation { + m := &ChargeCreditPurchaseExternalPaymentMutation{ + config: c, + op: op, + typ: TypeChargeCreditPurchaseExternalPayment, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withChargeCreditPurchaseExternalPaymentID sets the ID field of the mutation. +func withChargeCreditPurchaseExternalPaymentID(id string) chargecreditpurchaseexternalpaymentOption { + return func(m *ChargeCreditPurchaseExternalPaymentMutation) { + var ( + err error + once sync.Once + value *ChargeCreditPurchaseExternalPayment + ) + m.oldValue = func(ctx context.Context) (*ChargeCreditPurchaseExternalPayment, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ChargeCreditPurchaseExternalPayment.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withChargeCreditPurchaseExternalPayment sets the old ChargeCreditPurchaseExternalPayment of the mutation. +func withChargeCreditPurchaseExternalPayment(node *ChargeCreditPurchaseExternalPayment) chargecreditpurchaseexternalpaymentOption { + return func(m *ChargeCreditPurchaseExternalPaymentMutation) { + m.oldValue = func(context.Context) (*ChargeCreditPurchaseExternalPayment, 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 ChargeCreditPurchaseExternalPaymentMutation) 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 ChargeCreditPurchaseExternalPaymentMutation) 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 ChargeCreditPurchaseExternalPayment entities. +func (m *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) 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().ChargeCreditPurchaseExternalPayment.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (m *ChargeCreditPurchaseExternalPaymentMutation) SetServicePeriodFrom(t time.Time) { + m.service_period_from = &t +} + +// ServicePeriodFrom returns the value of the "service_period_from" field in the mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) 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 ChargeCreditPurchaseExternalPayment entity. +// If the ChargeCreditPurchaseExternalPayment 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 *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) ResetServicePeriodFrom() { + m.service_period_from = nil +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (m *ChargeCreditPurchaseExternalPaymentMutation) SetServicePeriodTo(t time.Time) { + m.service_period_to = &t +} + +// ServicePeriodTo returns the value of the "service_period_to" field in the mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) 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 ChargeCreditPurchaseExternalPayment entity. +// If the ChargeCreditPurchaseExternalPayment 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 *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) ResetServicePeriodTo() { + m.service_period_to = nil +} + +// SetStatus sets the "status" field. +func (m *ChargeCreditPurchaseExternalPaymentMutation) SetStatus(pa payment.Status) { + m.status = &pa +} + +// Status returns the value of the "status" field in the mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) 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 ChargeCreditPurchaseExternalPayment entity. +// If the ChargeCreditPurchaseExternalPayment 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 *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) ResetStatus() { + m.status = nil +} + +// SetAmount sets the "amount" field. +func (m *ChargeCreditPurchaseExternalPaymentMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) 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 ChargeCreditPurchaseExternalPayment entity. +// If the ChargeCreditPurchaseExternalPayment 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 *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) ResetAmount() { + m.amount = nil +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (m *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) 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 ChargeCreditPurchaseExternalPayment entity. +// If the ChargeCreditPurchaseExternalPayment 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 *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) ClearAuthorizedTransactionGroupID() { + m.authorized_transaction_group_id = nil + m.clearedFields[chargecreditpurchaseexternalpayment.FieldAuthorizedTransactionGroupID] = struct{}{} +} + +// AuthorizedTransactionGroupIDCleared returns if the "authorized_transaction_group_id" field was cleared in this mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) AuthorizedTransactionGroupIDCleared() bool { + _, ok := m.clearedFields[chargecreditpurchaseexternalpayment.FieldAuthorizedTransactionGroupID] + return ok +} + +// ResetAuthorizedTransactionGroupID resets all changes to the "authorized_transaction_group_id" field. +func (m *ChargeCreditPurchaseExternalPaymentMutation) ResetAuthorizedTransactionGroupID() { + m.authorized_transaction_group_id = nil + delete(m.clearedFields, chargecreditpurchaseexternalpayment.FieldAuthorizedTransactionGroupID) +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (m *ChargeCreditPurchaseExternalPaymentMutation) SetAuthorizedAt(t time.Time) { + m.authorized_at = &t +} + +// AuthorizedAt returns the value of the "authorized_at" field in the mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) 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 ChargeCreditPurchaseExternalPayment entity. +// If the ChargeCreditPurchaseExternalPayment 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 *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) ClearAuthorizedAt() { + m.authorized_at = nil + m.clearedFields[chargecreditpurchaseexternalpayment.FieldAuthorizedAt] = struct{}{} +} + +// AuthorizedAtCleared returns if the "authorized_at" field was cleared in this mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) AuthorizedAtCleared() bool { + _, ok := m.clearedFields[chargecreditpurchaseexternalpayment.FieldAuthorizedAt] + return ok +} + +// ResetAuthorizedAt resets all changes to the "authorized_at" field. +func (m *ChargeCreditPurchaseExternalPaymentMutation) ResetAuthorizedAt() { + m.authorized_at = nil + delete(m.clearedFields, chargecreditpurchaseexternalpayment.FieldAuthorizedAt) +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (m *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) 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 ChargeCreditPurchaseExternalPayment entity. +// If the ChargeCreditPurchaseExternalPayment 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 *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) ClearSettledTransactionGroupID() { + m.settled_transaction_group_id = nil + m.clearedFields[chargecreditpurchaseexternalpayment.FieldSettledTransactionGroupID] = struct{}{} +} + +// SettledTransactionGroupIDCleared returns if the "settled_transaction_group_id" field was cleared in this mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) SettledTransactionGroupIDCleared() bool { + _, ok := m.clearedFields[chargecreditpurchaseexternalpayment.FieldSettledTransactionGroupID] + return ok +} + +// ResetSettledTransactionGroupID resets all changes to the "settled_transaction_group_id" field. +func (m *ChargeCreditPurchaseExternalPaymentMutation) ResetSettledTransactionGroupID() { + m.settled_transaction_group_id = nil + delete(m.clearedFields, chargecreditpurchaseexternalpayment.FieldSettledTransactionGroupID) +} + +// SetSettledAt sets the "settled_at" field. +func (m *ChargeCreditPurchaseExternalPaymentMutation) SetSettledAt(t time.Time) { + m.settled_at = &t +} + +// SettledAt returns the value of the "settled_at" field in the mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) 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 ChargeCreditPurchaseExternalPayment entity. +// If the ChargeCreditPurchaseExternalPayment 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 *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) ClearSettledAt() { + m.settled_at = nil + m.clearedFields[chargecreditpurchaseexternalpayment.FieldSettledAt] = struct{}{} +} + +// SettledAtCleared returns if the "settled_at" field was cleared in this mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) SettledAtCleared() bool { + _, ok := m.clearedFields[chargecreditpurchaseexternalpayment.FieldSettledAt] + return ok +} + +// ResetSettledAt resets all changes to the "settled_at" field. +func (m *ChargeCreditPurchaseExternalPaymentMutation) ResetSettledAt() { + m.settled_at = nil + delete(m.clearedFields, chargecreditpurchaseexternalpayment.FieldSettledAt) +} + +// SetNamespace sets the "namespace" field. +func (m *ChargeCreditPurchaseExternalPaymentMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) 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 ChargeCreditPurchaseExternalPayment entity. +// If the ChargeCreditPurchaseExternalPayment 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 *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *ChargeCreditPurchaseExternalPaymentMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) 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 ChargeCreditPurchaseExternalPayment entity. +// If the ChargeCreditPurchaseExternalPayment 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 *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *ChargeCreditPurchaseExternalPaymentMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) 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 ChargeCreditPurchaseExternalPayment entity. +// If the ChargeCreditPurchaseExternalPayment 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 *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *ChargeCreditPurchaseExternalPaymentMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) 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 ChargeCreditPurchaseExternalPayment entity. +// If the ChargeCreditPurchaseExternalPayment 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 *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[chargecreditpurchaseexternalpayment.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[chargecreditpurchaseexternalpayment.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *ChargeCreditPurchaseExternalPaymentMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, chargecreditpurchaseexternalpayment.FieldDeletedAt) +} + +// SetAnnotations sets the "annotations" field. +func (m *ChargeCreditPurchaseExternalPaymentMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) 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 ChargeCreditPurchaseExternalPayment entity. +// If the ChargeCreditPurchaseExternalPayment 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 *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[chargecreditpurchaseexternalpayment.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[chargecreditpurchaseexternalpayment.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *ChargeCreditPurchaseExternalPaymentMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, chargecreditpurchaseexternalpayment.FieldAnnotations) +} + +// SetChargeID sets the "charge_id" field. +func (m *ChargeCreditPurchaseExternalPaymentMutation) SetChargeID(s string) { + m.credit_purchase = &s +} + +// ChargeID returns the value of the "charge_id" field in the mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) ChargeID() (r string, exists bool) { + v := m.credit_purchase + if v == nil { + return + } + return *v, true +} + +// OldChargeID returns the old "charge_id" field's value of the ChargeCreditPurchaseExternalPayment entity. +// If the ChargeCreditPurchaseExternalPayment 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 *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) ResetChargeID() { + m.credit_purchase = nil +} + +// SetCreditPurchaseID sets the "credit_purchase" edge to the ChargeCreditPurchase entity by id. +func (m *ChargeCreditPurchaseExternalPaymentMutation) SetCreditPurchaseID(id string) { + m.credit_purchase = &id +} + +// ClearCreditPurchase clears the "credit_purchase" edge to the ChargeCreditPurchase entity. +func (m *ChargeCreditPurchaseExternalPaymentMutation) ClearCreditPurchase() { + m.clearedcredit_purchase = true + m.clearedFields[chargecreditpurchaseexternalpayment.FieldChargeID] = struct{}{} +} + +// CreditPurchaseCleared reports if the "credit_purchase" edge to the ChargeCreditPurchase entity was cleared. +func (m *ChargeCreditPurchaseExternalPaymentMutation) CreditPurchaseCleared() bool { + return m.clearedcredit_purchase +} + +// CreditPurchaseID returns the "credit_purchase" edge ID in the mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) CreditPurchaseID() (id string, exists bool) { + if m.credit_purchase != nil { + return *m.credit_purchase, true + } + return +} + +// CreditPurchaseIDs returns the "credit_purchase" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CreditPurchaseID instead. It exists only for internal usage by the builders. +func (m *ChargeCreditPurchaseExternalPaymentMutation) CreditPurchaseIDs() (ids []string) { + if id := m.credit_purchase; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCreditPurchase resets all changes to the "credit_purchase" edge. +func (m *ChargeCreditPurchaseExternalPaymentMutation) ResetCreditPurchase() { + m.credit_purchase = nil + m.clearedcredit_purchase = false +} + +// Where appends a list predicates to the ChargeCreditPurchaseExternalPaymentMutation builder. +func (m *ChargeCreditPurchaseExternalPaymentMutation) Where(ps ...predicate.ChargeCreditPurchaseExternalPayment) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ChargeCreditPurchaseExternalPaymentMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ChargeCreditPurchaseExternalPaymentMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ChargeCreditPurchaseExternalPayment, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ChargeCreditPurchaseExternalPaymentMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ChargeCreditPurchaseExternalPayment). +func (m *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) Fields() []string { + fields := make([]string, 0, 14) + if m.service_period_from != nil { + fields = append(fields, chargecreditpurchaseexternalpayment.FieldServicePeriodFrom) + } + if m.service_period_to != nil { + fields = append(fields, chargecreditpurchaseexternalpayment.FieldServicePeriodTo) + } + if m.status != nil { + fields = append(fields, chargecreditpurchaseexternalpayment.FieldStatus) + } + if m.amount != nil { + fields = append(fields, chargecreditpurchaseexternalpayment.FieldAmount) + } + if m.authorized_transaction_group_id != nil { + fields = append(fields, chargecreditpurchaseexternalpayment.FieldAuthorizedTransactionGroupID) + } + if m.authorized_at != nil { + fields = append(fields, chargecreditpurchaseexternalpayment.FieldAuthorizedAt) + } + if m.settled_transaction_group_id != nil { + fields = append(fields, chargecreditpurchaseexternalpayment.FieldSettledTransactionGroupID) + } + if m.settled_at != nil { + fields = append(fields, chargecreditpurchaseexternalpayment.FieldSettledAt) + } + if m.namespace != nil { + fields = append(fields, chargecreditpurchaseexternalpayment.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, chargecreditpurchaseexternalpayment.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, chargecreditpurchaseexternalpayment.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, chargecreditpurchaseexternalpayment.FieldDeletedAt) + } + if m.annotations != nil { + fields = append(fields, chargecreditpurchaseexternalpayment.FieldAnnotations) + } + if m.credit_purchase != nil { + fields = append(fields, chargecreditpurchaseexternalpayment.FieldChargeID) + } + 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 *ChargeCreditPurchaseExternalPaymentMutation) Field(name string) (ent.Value, bool) { + switch name { + case chargecreditpurchaseexternalpayment.FieldServicePeriodFrom: + return m.ServicePeriodFrom() + case chargecreditpurchaseexternalpayment.FieldServicePeriodTo: + return m.ServicePeriodTo() + case chargecreditpurchaseexternalpayment.FieldStatus: + return m.Status() + case chargecreditpurchaseexternalpayment.FieldAmount: + return m.Amount() + case chargecreditpurchaseexternalpayment.FieldAuthorizedTransactionGroupID: + return m.AuthorizedTransactionGroupID() + case chargecreditpurchaseexternalpayment.FieldAuthorizedAt: + return m.AuthorizedAt() + case chargecreditpurchaseexternalpayment.FieldSettledTransactionGroupID: + return m.SettledTransactionGroupID() + case chargecreditpurchaseexternalpayment.FieldSettledAt: + return m.SettledAt() + case chargecreditpurchaseexternalpayment.FieldNamespace: + return m.Namespace() + case chargecreditpurchaseexternalpayment.FieldCreatedAt: + return m.CreatedAt() + case chargecreditpurchaseexternalpayment.FieldUpdatedAt: + return m.UpdatedAt() + case chargecreditpurchaseexternalpayment.FieldDeletedAt: + return m.DeletedAt() + case chargecreditpurchaseexternalpayment.FieldAnnotations: + return m.Annotations() + case chargecreditpurchaseexternalpayment.FieldChargeID: + return m.ChargeID() + } + 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 *ChargeCreditPurchaseExternalPaymentMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case chargecreditpurchaseexternalpayment.FieldServicePeriodFrom: + return m.OldServicePeriodFrom(ctx) + case chargecreditpurchaseexternalpayment.FieldServicePeriodTo: + return m.OldServicePeriodTo(ctx) + case chargecreditpurchaseexternalpayment.FieldStatus: + return m.OldStatus(ctx) + case chargecreditpurchaseexternalpayment.FieldAmount: + return m.OldAmount(ctx) + case chargecreditpurchaseexternalpayment.FieldAuthorizedTransactionGroupID: + return m.OldAuthorizedTransactionGroupID(ctx) + case chargecreditpurchaseexternalpayment.FieldAuthorizedAt: + return m.OldAuthorizedAt(ctx) + case chargecreditpurchaseexternalpayment.FieldSettledTransactionGroupID: + return m.OldSettledTransactionGroupID(ctx) + case chargecreditpurchaseexternalpayment.FieldSettledAt: + return m.OldSettledAt(ctx) + case chargecreditpurchaseexternalpayment.FieldNamespace: + return m.OldNamespace(ctx) + case chargecreditpurchaseexternalpayment.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case chargecreditpurchaseexternalpayment.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case chargecreditpurchaseexternalpayment.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case chargecreditpurchaseexternalpayment.FieldAnnotations: + return m.OldAnnotations(ctx) + case chargecreditpurchaseexternalpayment.FieldChargeID: + return m.OldChargeID(ctx) + } + return nil, fmt.Errorf("unknown ChargeCreditPurchaseExternalPayment 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 *ChargeCreditPurchaseExternalPaymentMutation) SetField(name string, value ent.Value) error { + switch name { + case chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.FieldAuthorizedTransactionGroupID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAuthorizedTransactionGroupID(v) + return nil + case chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.FieldSettledTransactionGroupID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSettledTransactionGroupID(v) + return nil + case chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.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 chargecreditpurchaseexternalpayment.FieldChargeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChargeID(v) + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchaseExternalPayment field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown ChargeCreditPurchaseExternalPayment numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(chargecreditpurchaseexternalpayment.FieldAuthorizedTransactionGroupID) { + fields = append(fields, chargecreditpurchaseexternalpayment.FieldAuthorizedTransactionGroupID) + } + if m.FieldCleared(chargecreditpurchaseexternalpayment.FieldAuthorizedAt) { + fields = append(fields, chargecreditpurchaseexternalpayment.FieldAuthorizedAt) + } + if m.FieldCleared(chargecreditpurchaseexternalpayment.FieldSettledTransactionGroupID) { + fields = append(fields, chargecreditpurchaseexternalpayment.FieldSettledTransactionGroupID) + } + if m.FieldCleared(chargecreditpurchaseexternalpayment.FieldSettledAt) { + fields = append(fields, chargecreditpurchaseexternalpayment.FieldSettledAt) + } + if m.FieldCleared(chargecreditpurchaseexternalpayment.FieldDeletedAt) { + fields = append(fields, chargecreditpurchaseexternalpayment.FieldDeletedAt) + } + if m.FieldCleared(chargecreditpurchaseexternalpayment.FieldAnnotations) { + fields = append(fields, chargecreditpurchaseexternalpayment.FieldAnnotations) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) ClearField(name string) error { + switch name { + case chargecreditpurchaseexternalpayment.FieldAuthorizedTransactionGroupID: + m.ClearAuthorizedTransactionGroupID() + return nil + case chargecreditpurchaseexternalpayment.FieldAuthorizedAt: + m.ClearAuthorizedAt() + return nil + case chargecreditpurchaseexternalpayment.FieldSettledTransactionGroupID: + m.ClearSettledTransactionGroupID() + return nil + case chargecreditpurchaseexternalpayment.FieldSettledAt: + m.ClearSettledAt() + return nil + case chargecreditpurchaseexternalpayment.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case chargecreditpurchaseexternalpayment.FieldAnnotations: + m.ClearAnnotations() + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchaseExternalPayment 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 *ChargeCreditPurchaseExternalPaymentMutation) ResetField(name string) error { + switch name { + case chargecreditpurchaseexternalpayment.FieldServicePeriodFrom: + m.ResetServicePeriodFrom() + return nil + case chargecreditpurchaseexternalpayment.FieldServicePeriodTo: + m.ResetServicePeriodTo() + return nil + case chargecreditpurchaseexternalpayment.FieldStatus: + m.ResetStatus() + return nil + case chargecreditpurchaseexternalpayment.FieldAmount: + m.ResetAmount() + return nil + case chargecreditpurchaseexternalpayment.FieldAuthorizedTransactionGroupID: + m.ResetAuthorizedTransactionGroupID() + return nil + case chargecreditpurchaseexternalpayment.FieldAuthorizedAt: + m.ResetAuthorizedAt() + return nil + case chargecreditpurchaseexternalpayment.FieldSettledTransactionGroupID: + m.ResetSettledTransactionGroupID() + return nil + case chargecreditpurchaseexternalpayment.FieldSettledAt: + m.ResetSettledAt() + return nil + case chargecreditpurchaseexternalpayment.FieldNamespace: + m.ResetNamespace() + return nil + case chargecreditpurchaseexternalpayment.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case chargecreditpurchaseexternalpayment.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case chargecreditpurchaseexternalpayment.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case chargecreditpurchaseexternalpayment.FieldAnnotations: + m.ResetAnnotations() + return nil + case chargecreditpurchaseexternalpayment.FieldChargeID: + m.ResetChargeID() + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchaseExternalPayment field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.credit_purchase != nil { + edges = append(edges, chargecreditpurchaseexternalpayment.EdgeCreditPurchase) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) AddedIDs(name string) []ent.Value { + switch name { + case chargecreditpurchaseexternalpayment.EdgeCreditPurchase: + if id := m.credit_purchase; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) 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 *ChargeCreditPurchaseExternalPaymentMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedcredit_purchase { + edges = append(edges, chargecreditpurchaseexternalpayment.EdgeCreditPurchase) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ChargeCreditPurchaseExternalPaymentMutation) EdgeCleared(name string) bool { + switch name { + case chargecreditpurchaseexternalpayment.EdgeCreditPurchase: + return m.clearedcredit_purchase + } + 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 *ChargeCreditPurchaseExternalPaymentMutation) ClearEdge(name string) error { + switch name { + case chargecreditpurchaseexternalpayment.EdgeCreditPurchase: + m.ClearCreditPurchase() + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchaseExternalPayment 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 *ChargeCreditPurchaseExternalPaymentMutation) ResetEdge(name string) error { + switch name { + case chargecreditpurchaseexternalpayment.EdgeCreditPurchase: + m.ResetCreditPurchase() + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchaseExternalPayment edge %s", name) +} + +// ChargeCreditPurchaseInvoicedPaymentMutation represents an operation that mutates the ChargeCreditPurchaseInvoicedPayment nodes in the graph. +type ChargeCreditPurchaseInvoicedPaymentMutation struct { + config + op Op + typ string + id *string + invoice_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{} + billing_invoice_line *string + clearedbilling_invoice_line bool + credit_purchase *string + clearedcredit_purchase bool + done bool + oldValue func(context.Context) (*ChargeCreditPurchaseInvoicedPayment, error) + predicates []predicate.ChargeCreditPurchaseInvoicedPayment +} + +var _ ent.Mutation = (*ChargeCreditPurchaseInvoicedPaymentMutation)(nil) + +// chargecreditpurchaseinvoicedpaymentOption allows management of the mutation configuration using functional options. +type chargecreditpurchaseinvoicedpaymentOption func(*ChargeCreditPurchaseInvoicedPaymentMutation) + +// newChargeCreditPurchaseInvoicedPaymentMutation creates new mutation for the ChargeCreditPurchaseInvoicedPayment entity. +func newChargeCreditPurchaseInvoicedPaymentMutation(c config, op Op, opts ...chargecreditpurchaseinvoicedpaymentOption) *ChargeCreditPurchaseInvoicedPaymentMutation { + m := &ChargeCreditPurchaseInvoicedPaymentMutation{ + config: c, + op: op, + typ: TypeChargeCreditPurchaseInvoicedPayment, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withChargeCreditPurchaseInvoicedPaymentID sets the ID field of the mutation. +func withChargeCreditPurchaseInvoicedPaymentID(id string) chargecreditpurchaseinvoicedpaymentOption { + return func(m *ChargeCreditPurchaseInvoicedPaymentMutation) { + var ( + err error + once sync.Once + value *ChargeCreditPurchaseInvoicedPayment + ) + m.oldValue = func(ctx context.Context) (*ChargeCreditPurchaseInvoicedPayment, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ChargeCreditPurchaseInvoicedPayment.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withChargeCreditPurchaseInvoicedPayment sets the old ChargeCreditPurchaseInvoicedPayment of the mutation. +func withChargeCreditPurchaseInvoicedPayment(node *ChargeCreditPurchaseInvoicedPayment) chargecreditpurchaseinvoicedpaymentOption { + return func(m *ChargeCreditPurchaseInvoicedPaymentMutation) { + m.oldValue = func(context.Context) (*ChargeCreditPurchaseInvoicedPayment, 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 ChargeCreditPurchaseInvoicedPaymentMutation) 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 ChargeCreditPurchaseInvoicedPaymentMutation) 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 ChargeCreditPurchaseInvoicedPayment entities. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) 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().ChargeCreditPurchaseInvoicedPayment.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 *ChargeCreditPurchaseInvoicedPaymentMutation) SetLineID(s string) { + m.billing_invoice_line = &s +} + +// LineID returns the value of the "line_id" field in the mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) LineID() (r string, exists bool) { + v := m.billing_invoice_line + if v == nil { + return + } + return *v, true +} + +// OldLineID returns the old "line_id" field's value of the ChargeCreditPurchaseInvoicedPayment entity. +// If the ChargeCreditPurchaseInvoicedPayment 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 *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) ResetLineID() { + m.billing_invoice_line = nil +} + +// SetInvoiceID sets the "invoice_id" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) SetInvoiceID(s string) { + m.invoice_id = &s +} + +// InvoiceID returns the value of the "invoice_id" field in the mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) InvoiceID() (r string, exists bool) { + v := m.invoice_id + if v == nil { + return + } + return *v, true +} + +// OldInvoiceID returns the old "invoice_id" field's value of the ChargeCreditPurchaseInvoicedPayment entity. +// If the ChargeCreditPurchaseInvoicedPayment 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 *ChargeCreditPurchaseInvoicedPaymentMutation) OldInvoiceID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceID: %w", err) + } + return oldValue.InvoiceID, nil +} + +// ResetInvoiceID resets all changes to the "invoice_id" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) ResetInvoiceID() { + m.invoice_id = nil +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) SetServicePeriodFrom(t time.Time) { + m.service_period_from = &t +} + +// ServicePeriodFrom returns the value of the "service_period_from" field in the mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) 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 ChargeCreditPurchaseInvoicedPayment entity. +// If the ChargeCreditPurchaseInvoicedPayment 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 *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) ResetServicePeriodFrom() { + m.service_period_from = nil +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) SetServicePeriodTo(t time.Time) { + m.service_period_to = &t +} + +// ServicePeriodTo returns the value of the "service_period_to" field in the mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) 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 ChargeCreditPurchaseInvoicedPayment entity. +// If the ChargeCreditPurchaseInvoicedPayment 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 *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) ResetServicePeriodTo() { + m.service_period_to = nil +} + +// SetStatus sets the "status" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) SetStatus(pa payment.Status) { + m.status = &pa +} + +// Status returns the value of the "status" field in the mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) 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 ChargeCreditPurchaseInvoicedPayment entity. +// If the ChargeCreditPurchaseInvoicedPayment 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 *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) ResetStatus() { + m.status = nil +} + +// SetAmount sets the "amount" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) 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 ChargeCreditPurchaseInvoicedPayment entity. +// If the ChargeCreditPurchaseInvoicedPayment 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 *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) ResetAmount() { + m.amount = nil +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) 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 ChargeCreditPurchaseInvoicedPayment entity. +// If the ChargeCreditPurchaseInvoicedPayment 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 *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) ClearAuthorizedTransactionGroupID() { + m.authorized_transaction_group_id = nil + m.clearedFields[chargecreditpurchaseinvoicedpayment.FieldAuthorizedTransactionGroupID] = struct{}{} +} + +// AuthorizedTransactionGroupIDCleared returns if the "authorized_transaction_group_id" field was cleared in this mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) AuthorizedTransactionGroupIDCleared() bool { + _, ok := m.clearedFields[chargecreditpurchaseinvoicedpayment.FieldAuthorizedTransactionGroupID] + return ok +} + +// ResetAuthorizedTransactionGroupID resets all changes to the "authorized_transaction_group_id" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) ResetAuthorizedTransactionGroupID() { + m.authorized_transaction_group_id = nil + delete(m.clearedFields, chargecreditpurchaseinvoicedpayment.FieldAuthorizedTransactionGroupID) +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) SetAuthorizedAt(t time.Time) { + m.authorized_at = &t +} + +// AuthorizedAt returns the value of the "authorized_at" field in the mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) 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 ChargeCreditPurchaseInvoicedPayment entity. +// If the ChargeCreditPurchaseInvoicedPayment 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 *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) ClearAuthorizedAt() { + m.authorized_at = nil + m.clearedFields[chargecreditpurchaseinvoicedpayment.FieldAuthorizedAt] = struct{}{} +} + +// AuthorizedAtCleared returns if the "authorized_at" field was cleared in this mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) AuthorizedAtCleared() bool { + _, ok := m.clearedFields[chargecreditpurchaseinvoicedpayment.FieldAuthorizedAt] + return ok +} + +// ResetAuthorizedAt resets all changes to the "authorized_at" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) ResetAuthorizedAt() { + m.authorized_at = nil + delete(m.clearedFields, chargecreditpurchaseinvoicedpayment.FieldAuthorizedAt) +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) 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 ChargeCreditPurchaseInvoicedPayment entity. +// If the ChargeCreditPurchaseInvoicedPayment 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 *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) ClearSettledTransactionGroupID() { + m.settled_transaction_group_id = nil + m.clearedFields[chargecreditpurchaseinvoicedpayment.FieldSettledTransactionGroupID] = struct{}{} +} + +// SettledTransactionGroupIDCleared returns if the "settled_transaction_group_id" field was cleared in this mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) SettledTransactionGroupIDCleared() bool { + _, ok := m.clearedFields[chargecreditpurchaseinvoicedpayment.FieldSettledTransactionGroupID] + return ok +} + +// ResetSettledTransactionGroupID resets all changes to the "settled_transaction_group_id" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) ResetSettledTransactionGroupID() { + m.settled_transaction_group_id = nil + delete(m.clearedFields, chargecreditpurchaseinvoicedpayment.FieldSettledTransactionGroupID) +} + +// SetSettledAt sets the "settled_at" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) SetSettledAt(t time.Time) { + m.settled_at = &t +} + +// SettledAt returns the value of the "settled_at" field in the mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) 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 ChargeCreditPurchaseInvoicedPayment entity. +// If the ChargeCreditPurchaseInvoicedPayment 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 *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) ClearSettledAt() { + m.settled_at = nil + m.clearedFields[chargecreditpurchaseinvoicedpayment.FieldSettledAt] = struct{}{} +} + +// SettledAtCleared returns if the "settled_at" field was cleared in this mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) SettledAtCleared() bool { + _, ok := m.clearedFields[chargecreditpurchaseinvoicedpayment.FieldSettledAt] + return ok +} + +// ResetSettledAt resets all changes to the "settled_at" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) ResetSettledAt() { + m.settled_at = nil + delete(m.clearedFields, chargecreditpurchaseinvoicedpayment.FieldSettledAt) +} + +// SetNamespace sets the "namespace" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) 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 ChargeCreditPurchaseInvoicedPayment entity. +// If the ChargeCreditPurchaseInvoicedPayment 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 *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) 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 ChargeCreditPurchaseInvoicedPayment entity. +// If the ChargeCreditPurchaseInvoicedPayment 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 *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) 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 ChargeCreditPurchaseInvoicedPayment entity. +// If the ChargeCreditPurchaseInvoicedPayment 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 *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) 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 ChargeCreditPurchaseInvoicedPayment entity. +// If the ChargeCreditPurchaseInvoicedPayment 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 *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[chargecreditpurchaseinvoicedpayment.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[chargecreditpurchaseinvoicedpayment.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, chargecreditpurchaseinvoicedpayment.FieldDeletedAt) +} + +// SetAnnotations sets the "annotations" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) 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 ChargeCreditPurchaseInvoicedPayment entity. +// If the ChargeCreditPurchaseInvoicedPayment 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 *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[chargecreditpurchaseinvoicedpayment.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[chargecreditpurchaseinvoicedpayment.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, chargecreditpurchaseinvoicedpayment.FieldAnnotations) +} + +// SetChargeID sets the "charge_id" field. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) SetChargeID(s string) { + m.credit_purchase = &s +} + +// ChargeID returns the value of the "charge_id" field in the mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) ChargeID() (r string, exists bool) { + v := m.credit_purchase + if v == nil { + return + } + return *v, true +} + +// OldChargeID returns the old "charge_id" field's value of the ChargeCreditPurchaseInvoicedPayment entity. +// If the ChargeCreditPurchaseInvoicedPayment 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 *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) ResetChargeID() { + m.credit_purchase = nil +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by id. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) SetBillingInvoiceLineID(id string) { + m.billing_invoice_line = &id +} + +// ClearBillingInvoiceLine clears the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) ClearBillingInvoiceLine() { + m.clearedbilling_invoice_line = true + m.clearedFields[chargecreditpurchaseinvoicedpayment.FieldLineID] = struct{}{} +} + +// BillingInvoiceLineCleared reports if the "billing_invoice_line" edge to the BillingInvoiceLine entity was cleared. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) BillingInvoiceLineCleared() bool { + return m.clearedbilling_invoice_line +} + +// BillingInvoiceLineID returns the "billing_invoice_line" edge ID in the mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) BillingInvoiceLineID() (id string, exists bool) { + if m.billing_invoice_line != nil { + return *m.billing_invoice_line, true + } + return +} + +// BillingInvoiceLineIDs returns the "billing_invoice_line" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BillingInvoiceLineID instead. It exists only for internal usage by the builders. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) BillingInvoiceLineIDs() (ids []string) { + if id := m.billing_invoice_line; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBillingInvoiceLine resets all changes to the "billing_invoice_line" edge. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) ResetBillingInvoiceLine() { + m.billing_invoice_line = nil + m.clearedbilling_invoice_line = false +} + +// SetCreditPurchaseID sets the "credit_purchase" edge to the ChargeCreditPurchase entity by id. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) SetCreditPurchaseID(id string) { + m.credit_purchase = &id +} + +// ClearCreditPurchase clears the "credit_purchase" edge to the ChargeCreditPurchase entity. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) ClearCreditPurchase() { + m.clearedcredit_purchase = true + m.clearedFields[chargecreditpurchaseinvoicedpayment.FieldChargeID] = struct{}{} +} + +// CreditPurchaseCleared reports if the "credit_purchase" edge to the ChargeCreditPurchase entity was cleared. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) CreditPurchaseCleared() bool { + return m.clearedcredit_purchase +} + +// CreditPurchaseID returns the "credit_purchase" edge ID in the mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) CreditPurchaseID() (id string, exists bool) { + if m.credit_purchase != nil { + return *m.credit_purchase, true + } + return +} + +// CreditPurchaseIDs returns the "credit_purchase" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CreditPurchaseID instead. It exists only for internal usage by the builders. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) CreditPurchaseIDs() (ids []string) { + if id := m.credit_purchase; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCreditPurchase resets all changes to the "credit_purchase" edge. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) ResetCreditPurchase() { + m.credit_purchase = nil + m.clearedcredit_purchase = false +} + +// Where appends a list predicates to the ChargeCreditPurchaseInvoicedPaymentMutation builder. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) Where(ps ...predicate.ChargeCreditPurchaseInvoicedPayment) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ChargeCreditPurchaseInvoicedPaymentMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ChargeCreditPurchaseInvoicedPayment, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ChargeCreditPurchaseInvoicedPayment). +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) Fields() []string { + fields := make([]string, 0, 16) + if m.billing_invoice_line != nil { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldLineID) + } + if m.invoice_id != nil { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldInvoiceID) + } + if m.service_period_from != nil { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldServicePeriodFrom) + } + if m.service_period_to != nil { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldServicePeriodTo) + } + if m.status != nil { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldStatus) + } + if m.amount != nil { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldAmount) + } + if m.authorized_transaction_group_id != nil { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldAuthorizedTransactionGroupID) + } + if m.authorized_at != nil { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldAuthorizedAt) + } + if m.settled_transaction_group_id != nil { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldSettledTransactionGroupID) + } + if m.settled_at != nil { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldSettledAt) + } + if m.namespace != nil { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldDeletedAt) + } + if m.annotations != nil { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldAnnotations) + } + if m.credit_purchase != nil { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldChargeID) + } + 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 *ChargeCreditPurchaseInvoicedPaymentMutation) Field(name string) (ent.Value, bool) { + switch name { + case chargecreditpurchaseinvoicedpayment.FieldLineID: + return m.LineID() + case chargecreditpurchaseinvoicedpayment.FieldInvoiceID: + return m.InvoiceID() + case chargecreditpurchaseinvoicedpayment.FieldServicePeriodFrom: + return m.ServicePeriodFrom() + case chargecreditpurchaseinvoicedpayment.FieldServicePeriodTo: + return m.ServicePeriodTo() + case chargecreditpurchaseinvoicedpayment.FieldStatus: + return m.Status() + case chargecreditpurchaseinvoicedpayment.FieldAmount: + return m.Amount() + case chargecreditpurchaseinvoicedpayment.FieldAuthorizedTransactionGroupID: + return m.AuthorizedTransactionGroupID() + case chargecreditpurchaseinvoicedpayment.FieldAuthorizedAt: + return m.AuthorizedAt() + case chargecreditpurchaseinvoicedpayment.FieldSettledTransactionGroupID: + return m.SettledTransactionGroupID() + case chargecreditpurchaseinvoicedpayment.FieldSettledAt: + return m.SettledAt() + case chargecreditpurchaseinvoicedpayment.FieldNamespace: + return m.Namespace() + case chargecreditpurchaseinvoicedpayment.FieldCreatedAt: + return m.CreatedAt() + case chargecreditpurchaseinvoicedpayment.FieldUpdatedAt: + return m.UpdatedAt() + case chargecreditpurchaseinvoicedpayment.FieldDeletedAt: + return m.DeletedAt() + case chargecreditpurchaseinvoicedpayment.FieldAnnotations: + return m.Annotations() + case chargecreditpurchaseinvoicedpayment.FieldChargeID: + return m.ChargeID() + } + 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 *ChargeCreditPurchaseInvoicedPaymentMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case chargecreditpurchaseinvoicedpayment.FieldLineID: + return m.OldLineID(ctx) + case chargecreditpurchaseinvoicedpayment.FieldInvoiceID: + return m.OldInvoiceID(ctx) + case chargecreditpurchaseinvoicedpayment.FieldServicePeriodFrom: + return m.OldServicePeriodFrom(ctx) + case chargecreditpurchaseinvoicedpayment.FieldServicePeriodTo: + return m.OldServicePeriodTo(ctx) + case chargecreditpurchaseinvoicedpayment.FieldStatus: + return m.OldStatus(ctx) + case chargecreditpurchaseinvoicedpayment.FieldAmount: + return m.OldAmount(ctx) + case chargecreditpurchaseinvoicedpayment.FieldAuthorizedTransactionGroupID: + return m.OldAuthorizedTransactionGroupID(ctx) + case chargecreditpurchaseinvoicedpayment.FieldAuthorizedAt: + return m.OldAuthorizedAt(ctx) + case chargecreditpurchaseinvoicedpayment.FieldSettledTransactionGroupID: + return m.OldSettledTransactionGroupID(ctx) + case chargecreditpurchaseinvoicedpayment.FieldSettledAt: + return m.OldSettledAt(ctx) + case chargecreditpurchaseinvoicedpayment.FieldNamespace: + return m.OldNamespace(ctx) + case chargecreditpurchaseinvoicedpayment.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case chargecreditpurchaseinvoicedpayment.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case chargecreditpurchaseinvoicedpayment.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case chargecreditpurchaseinvoicedpayment.FieldAnnotations: + return m.OldAnnotations(ctx) + case chargecreditpurchaseinvoicedpayment.FieldChargeID: + return m.OldChargeID(ctx) + } + return nil, fmt.Errorf("unknown ChargeCreditPurchaseInvoicedPayment 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 *ChargeCreditPurchaseInvoicedPaymentMutation) SetField(name string, value ent.Value) error { + switch name { + case chargecreditpurchaseinvoicedpayment.FieldLineID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLineID(v) + return nil + case chargecreditpurchaseinvoicedpayment.FieldInvoiceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceID(v) + return nil + case chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.FieldAuthorizedTransactionGroupID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAuthorizedTransactionGroupID(v) + return nil + case chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.FieldSettledTransactionGroupID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSettledTransactionGroupID(v) + return nil + case chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.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 chargecreditpurchaseinvoicedpayment.FieldChargeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChargeID(v) + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchaseInvoicedPayment field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown ChargeCreditPurchaseInvoicedPayment numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(chargecreditpurchaseinvoicedpayment.FieldAuthorizedTransactionGroupID) { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldAuthorizedTransactionGroupID) + } + if m.FieldCleared(chargecreditpurchaseinvoicedpayment.FieldAuthorizedAt) { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldAuthorizedAt) + } + if m.FieldCleared(chargecreditpurchaseinvoicedpayment.FieldSettledTransactionGroupID) { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldSettledTransactionGroupID) + } + if m.FieldCleared(chargecreditpurchaseinvoicedpayment.FieldSettledAt) { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldSettledAt) + } + if m.FieldCleared(chargecreditpurchaseinvoicedpayment.FieldDeletedAt) { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldDeletedAt) + } + if m.FieldCleared(chargecreditpurchaseinvoicedpayment.FieldAnnotations) { + fields = append(fields, chargecreditpurchaseinvoicedpayment.FieldAnnotations) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) 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 *ChargeCreditPurchaseInvoicedPaymentMutation) ClearField(name string) error { + switch name { + case chargecreditpurchaseinvoicedpayment.FieldAuthorizedTransactionGroupID: + m.ClearAuthorizedTransactionGroupID() + return nil + case chargecreditpurchaseinvoicedpayment.FieldAuthorizedAt: + m.ClearAuthorizedAt() + return nil + case chargecreditpurchaseinvoicedpayment.FieldSettledTransactionGroupID: + m.ClearSettledTransactionGroupID() + return nil + case chargecreditpurchaseinvoicedpayment.FieldSettledAt: + m.ClearSettledAt() + return nil + case chargecreditpurchaseinvoicedpayment.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case chargecreditpurchaseinvoicedpayment.FieldAnnotations: + m.ClearAnnotations() + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchaseInvoicedPayment 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 *ChargeCreditPurchaseInvoicedPaymentMutation) ResetField(name string) error { + switch name { + case chargecreditpurchaseinvoicedpayment.FieldLineID: + m.ResetLineID() + return nil + case chargecreditpurchaseinvoicedpayment.FieldInvoiceID: + m.ResetInvoiceID() + return nil + case chargecreditpurchaseinvoicedpayment.FieldServicePeriodFrom: + m.ResetServicePeriodFrom() + return nil + case chargecreditpurchaseinvoicedpayment.FieldServicePeriodTo: + m.ResetServicePeriodTo() + return nil + case chargecreditpurchaseinvoicedpayment.FieldStatus: + m.ResetStatus() + return nil + case chargecreditpurchaseinvoicedpayment.FieldAmount: + m.ResetAmount() + return nil + case chargecreditpurchaseinvoicedpayment.FieldAuthorizedTransactionGroupID: + m.ResetAuthorizedTransactionGroupID() + return nil + case chargecreditpurchaseinvoicedpayment.FieldAuthorizedAt: + m.ResetAuthorizedAt() + return nil + case chargecreditpurchaseinvoicedpayment.FieldSettledTransactionGroupID: + m.ResetSettledTransactionGroupID() + return nil + case chargecreditpurchaseinvoicedpayment.FieldSettledAt: + m.ResetSettledAt() + return nil + case chargecreditpurchaseinvoicedpayment.FieldNamespace: + m.ResetNamespace() + return nil + case chargecreditpurchaseinvoicedpayment.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case chargecreditpurchaseinvoicedpayment.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case chargecreditpurchaseinvoicedpayment.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case chargecreditpurchaseinvoicedpayment.FieldAnnotations: + m.ResetAnnotations() + return nil + case chargecreditpurchaseinvoicedpayment.FieldChargeID: + m.ResetChargeID() + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchaseInvoicedPayment field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.billing_invoice_line != nil { + edges = append(edges, chargecreditpurchaseinvoicedpayment.EdgeBillingInvoiceLine) + } + if m.credit_purchase != nil { + edges = append(edges, chargecreditpurchaseinvoicedpayment.EdgeCreditPurchase) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) AddedIDs(name string) []ent.Value { + switch name { + case chargecreditpurchaseinvoicedpayment.EdgeBillingInvoiceLine: + if id := m.billing_invoice_line; id != nil { + return []ent.Value{*id} + } + case chargecreditpurchaseinvoicedpayment.EdgeCreditPurchase: + if id := m.credit_purchase; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedbilling_invoice_line { + edges = append(edges, chargecreditpurchaseinvoicedpayment.EdgeBillingInvoiceLine) + } + if m.clearedcredit_purchase { + edges = append(edges, chargecreditpurchaseinvoicedpayment.EdgeCreditPurchase) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ChargeCreditPurchaseInvoicedPaymentMutation) EdgeCleared(name string) bool { + switch name { + case chargecreditpurchaseinvoicedpayment.EdgeBillingInvoiceLine: + return m.clearedbilling_invoice_line + case chargecreditpurchaseinvoicedpayment.EdgeCreditPurchase: + return m.clearedcredit_purchase + } + 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 *ChargeCreditPurchaseInvoicedPaymentMutation) ClearEdge(name string) error { + switch name { + case chargecreditpurchaseinvoicedpayment.EdgeBillingInvoiceLine: + m.ClearBillingInvoiceLine() + return nil + case chargecreditpurchaseinvoicedpayment.EdgeCreditPurchase: + m.ClearCreditPurchase() + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchaseInvoicedPayment 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 *ChargeCreditPurchaseInvoicedPaymentMutation) ResetEdge(name string) error { + switch name { + case chargecreditpurchaseinvoicedpayment.EdgeBillingInvoiceLine: + m.ResetBillingInvoiceLine() + return nil + case chargecreditpurchaseinvoicedpayment.EdgeCreditPurchase: + m.ResetCreditPurchase() + return nil + } + return fmt.Errorf("unknown ChargeCreditPurchaseInvoicedPayment edge %s", name) +} + +// ChargeFlatFeeMutation represents an operation that mutates the ChargeFlatFee nodes in the graph. +type ChargeFlatFeeMutation struct { + config + op Op + typ string + id *string + service_period_from *time.Time + service_period_to *time.Time + billing_period_from *time.Time + billing_period_to *time.Time + full_service_period_from *time.Time + full_service_period_to *time.Time + status *meta.ChargeStatus + unique_reference_id *string + currency *currencyx.Code + managed_by *billing.InvoiceLineManagedBy + advance_after *time.Time + tax_behavior *productcatalog.TaxBehavior + annotations *models.Annotations + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + name *string + description *string + payment_term *productcatalog.PaymentTermType + invoice_at *time.Time + settlement_mode *productcatalog.SettlementMode + intent_deleted_at *time.Time + discounts **billing.Discounts + pro_rating *flatfee.ProRatingModeAdapterEnum + feature_key *string + amount_before_proration *alpacadecimal.Decimal + amount_after_proration *alpacadecimal.Decimal + status_detailed *flatfee.Status + clearedFields map[string]struct{} + runs map[string]struct{} + removedruns map[string]struct{} + clearedruns bool + current_run *string + clearedcurrent_run bool + charge *string + clearedcharge bool + intent_override *string + clearedintent_override bool + subscription *string + clearedsubscription bool + subscription_phase *string + clearedsubscription_phase bool + subscription_item *string + clearedsubscription_item bool + customer *string + clearedcustomer bool + feature *string + clearedfeature bool + tax_code *string + clearedtax_code bool + done bool + oldValue func(context.Context) (*ChargeFlatFee, error) + predicates []predicate.ChargeFlatFee +} + +var _ ent.Mutation = (*ChargeFlatFeeMutation)(nil) + +// chargeflatfeeOption allows management of the mutation configuration using functional options. +type chargeflatfeeOption func(*ChargeFlatFeeMutation) + +// newChargeFlatFeeMutation creates new mutation for the ChargeFlatFee entity. +func newChargeFlatFeeMutation(c config, op Op, opts ...chargeflatfeeOption) *ChargeFlatFeeMutation { + m := &ChargeFlatFeeMutation{ + config: c, + op: op, + typ: TypeChargeFlatFee, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withChargeFlatFeeID sets the ID field of the mutation. +func withChargeFlatFeeID(id string) chargeflatfeeOption { + return func(m *ChargeFlatFeeMutation) { + var ( + err error + once sync.Once + value *ChargeFlatFee + ) + m.oldValue = func(ctx context.Context) (*ChargeFlatFee, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ChargeFlatFee.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withChargeFlatFee sets the old ChargeFlatFee of the mutation. +func withChargeFlatFee(node *ChargeFlatFee) chargeflatfeeOption { + return func(m *ChargeFlatFeeMutation) { + m.oldValue = func(context.Context) (*ChargeFlatFee, 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 ChargeFlatFeeMutation) 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 ChargeFlatFeeMutation) 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 ChargeFlatFee entities. +func (m *ChargeFlatFeeMutation) 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 *ChargeFlatFeeMutation) 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 *ChargeFlatFeeMutation) 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().ChargeFlatFee.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetCustomerID sets the "customer_id" field. +func (m *ChargeFlatFeeMutation) SetCustomerID(s string) { + m.customer = &s +} + +// CustomerID returns the value of the "customer_id" field in the mutation. +func (m *ChargeFlatFeeMutation) CustomerID() (r string, exists bool) { + v := m.customer + if v == nil { + return + } + return *v, true +} + +// OldCustomerID returns the old "customer_id" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldCustomerID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerID: %w", err) + } + return oldValue.CustomerID, nil +} + +// ResetCustomerID resets all changes to the "customer_id" field. +func (m *ChargeFlatFeeMutation) ResetCustomerID() { + m.customer = nil +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (m *ChargeFlatFeeMutation) SetServicePeriodFrom(t time.Time) { + m.service_period_from = &t +} + +// ServicePeriodFrom returns the value of the "service_period_from" field in the mutation. +func (m *ChargeFlatFeeMutation) 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 ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) 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 *ChargeFlatFeeMutation) ResetServicePeriodFrom() { + m.service_period_from = nil +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (m *ChargeFlatFeeMutation) SetServicePeriodTo(t time.Time) { + m.service_period_to = &t +} + +// ServicePeriodTo returns the value of the "service_period_to" field in the mutation. +func (m *ChargeFlatFeeMutation) 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 ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) 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 *ChargeFlatFeeMutation) ResetServicePeriodTo() { + m.service_period_to = nil +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (m *ChargeFlatFeeMutation) SetBillingPeriodFrom(t time.Time) { + m.billing_period_from = &t +} + +// BillingPeriodFrom returns the value of the "billing_period_from" field in the mutation. +func (m *ChargeFlatFeeMutation) BillingPeriodFrom() (r time.Time, exists bool) { + v := m.billing_period_from + if v == nil { + return + } + return *v, true +} + +// OldBillingPeriodFrom returns the old "billing_period_from" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldBillingPeriodFrom(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingPeriodFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingPeriodFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingPeriodFrom: %w", err) + } + return oldValue.BillingPeriodFrom, nil +} + +// ResetBillingPeriodFrom resets all changes to the "billing_period_from" field. +func (m *ChargeFlatFeeMutation) ResetBillingPeriodFrom() { + m.billing_period_from = nil +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (m *ChargeFlatFeeMutation) SetBillingPeriodTo(t time.Time) { + m.billing_period_to = &t +} + +// BillingPeriodTo returns the value of the "billing_period_to" field in the mutation. +func (m *ChargeFlatFeeMutation) BillingPeriodTo() (r time.Time, exists bool) { + v := m.billing_period_to + if v == nil { + return + } + return *v, true +} + +// OldBillingPeriodTo returns the old "billing_period_to" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldBillingPeriodTo(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingPeriodTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingPeriodTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingPeriodTo: %w", err) + } + return oldValue.BillingPeriodTo, nil +} + +// ResetBillingPeriodTo resets all changes to the "billing_period_to" field. +func (m *ChargeFlatFeeMutation) ResetBillingPeriodTo() { + m.billing_period_to = nil +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (m *ChargeFlatFeeMutation) SetFullServicePeriodFrom(t time.Time) { + m.full_service_period_from = &t +} + +// FullServicePeriodFrom returns the value of the "full_service_period_from" field in the mutation. +func (m *ChargeFlatFeeMutation) FullServicePeriodFrom() (r time.Time, exists bool) { + v := m.full_service_period_from + if v == nil { + return + } + return *v, true +} + +// OldFullServicePeriodFrom returns the old "full_service_period_from" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldFullServicePeriodFrom(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFullServicePeriodFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFullServicePeriodFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFullServicePeriodFrom: %w", err) + } + return oldValue.FullServicePeriodFrom, nil +} + +// ResetFullServicePeriodFrom resets all changes to the "full_service_period_from" field. +func (m *ChargeFlatFeeMutation) ResetFullServicePeriodFrom() { + m.full_service_period_from = nil +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (m *ChargeFlatFeeMutation) SetFullServicePeriodTo(t time.Time) { + m.full_service_period_to = &t +} + +// FullServicePeriodTo returns the value of the "full_service_period_to" field in the mutation. +func (m *ChargeFlatFeeMutation) FullServicePeriodTo() (r time.Time, exists bool) { + v := m.full_service_period_to + if v == nil { + return + } + return *v, true +} + +// OldFullServicePeriodTo returns the old "full_service_period_to" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldFullServicePeriodTo(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFullServicePeriodTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFullServicePeriodTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFullServicePeriodTo: %w", err) + } + return oldValue.FullServicePeriodTo, nil +} + +// ResetFullServicePeriodTo resets all changes to the "full_service_period_to" field. +func (m *ChargeFlatFeeMutation) ResetFullServicePeriodTo() { + m.full_service_period_to = nil +} + +// SetStatus sets the "status" field. +func (m *ChargeFlatFeeMutation) SetStatus(ms meta.ChargeStatus) { + m.status = &ms +} + +// Status returns the value of the "status" field in the mutation. +func (m *ChargeFlatFeeMutation) Status() (r meta.ChargeStatus, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true +} + +// OldStatus returns the old "status" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldStatus(ctx context.Context) (v meta.ChargeStatus, 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 *ChargeFlatFeeMutation) ResetStatus() { + m.status = nil +} + +// SetUniqueReferenceID sets the "unique_reference_id" field. +func (m *ChargeFlatFeeMutation) SetUniqueReferenceID(s string) { + m.unique_reference_id = &s +} + +// UniqueReferenceID returns the value of the "unique_reference_id" field in the mutation. +func (m *ChargeFlatFeeMutation) UniqueReferenceID() (r string, exists bool) { + v := m.unique_reference_id + if v == nil { + return + } + return *v, true +} + +// OldUniqueReferenceID returns the old "unique_reference_id" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldUniqueReferenceID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUniqueReferenceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUniqueReferenceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUniqueReferenceID: %w", err) + } + return oldValue.UniqueReferenceID, nil +} + +// ClearUniqueReferenceID clears the value of the "unique_reference_id" field. +func (m *ChargeFlatFeeMutation) ClearUniqueReferenceID() { + m.unique_reference_id = nil + m.clearedFields[chargeflatfee.FieldUniqueReferenceID] = struct{}{} +} + +// UniqueReferenceIDCleared returns if the "unique_reference_id" field was cleared in this mutation. +func (m *ChargeFlatFeeMutation) UniqueReferenceIDCleared() bool { + _, ok := m.clearedFields[chargeflatfee.FieldUniqueReferenceID] + return ok +} + +// ResetUniqueReferenceID resets all changes to the "unique_reference_id" field. +func (m *ChargeFlatFeeMutation) ResetUniqueReferenceID() { + m.unique_reference_id = nil + delete(m.clearedFields, chargeflatfee.FieldUniqueReferenceID) +} + +// SetCurrency sets the "currency" field. +func (m *ChargeFlatFeeMutation) SetCurrency(c currencyx.Code) { + m.currency = &c +} + +// Currency returns the value of the "currency" field in the mutation. +func (m *ChargeFlatFeeMutation) Currency() (r currencyx.Code, exists bool) { + v := m.currency + if v == nil { + return + } + return *v, true +} + +// OldCurrency returns the old "currency" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldCurrency(ctx context.Context) (v currencyx.Code, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrency is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrency requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrency: %w", err) + } + return oldValue.Currency, nil +} + +// ResetCurrency resets all changes to the "currency" field. +func (m *ChargeFlatFeeMutation) ResetCurrency() { + m.currency = nil +} + +// SetManagedBy sets the "managed_by" field. +func (m *ChargeFlatFeeMutation) SetManagedBy(blmb billing.InvoiceLineManagedBy) { + m.managed_by = &blmb +} + +// ManagedBy returns the value of the "managed_by" field in the mutation. +func (m *ChargeFlatFeeMutation) ManagedBy() (r billing.InvoiceLineManagedBy, exists bool) { + v := m.managed_by + if v == nil { + return + } + return *v, true +} + +// OldManagedBy returns the old "managed_by" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldManagedBy(ctx context.Context) (v billing.InvoiceLineManagedBy, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldManagedBy is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldManagedBy requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldManagedBy: %w", err) + } + return oldValue.ManagedBy, nil +} + +// ResetManagedBy resets all changes to the "managed_by" field. +func (m *ChargeFlatFeeMutation) ResetManagedBy() { + m.managed_by = nil +} + +// SetSubscriptionID sets the "subscription_id" field. +func (m *ChargeFlatFeeMutation) SetSubscriptionID(s string) { + m.subscription = &s +} + +// SubscriptionID returns the value of the "subscription_id" field in the mutation. +func (m *ChargeFlatFeeMutation) SubscriptionID() (r string, exists bool) { + v := m.subscription + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionID returns the old "subscription_id" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldSubscriptionID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionID: %w", err) + } + return oldValue.SubscriptionID, nil +} + +// ClearSubscriptionID clears the value of the "subscription_id" field. +func (m *ChargeFlatFeeMutation) ClearSubscriptionID() { + m.subscription = nil + m.clearedFields[chargeflatfee.FieldSubscriptionID] = struct{}{} +} + +// SubscriptionIDCleared returns if the "subscription_id" field was cleared in this mutation. +func (m *ChargeFlatFeeMutation) SubscriptionIDCleared() bool { + _, ok := m.clearedFields[chargeflatfee.FieldSubscriptionID] + return ok +} + +// ResetSubscriptionID resets all changes to the "subscription_id" field. +func (m *ChargeFlatFeeMutation) ResetSubscriptionID() { + m.subscription = nil + delete(m.clearedFields, chargeflatfee.FieldSubscriptionID) +} + +// SetSubscriptionPhaseID sets the "subscription_phase_id" field. +func (m *ChargeFlatFeeMutation) SetSubscriptionPhaseID(s string) { + m.subscription_phase = &s +} + +// SubscriptionPhaseID returns the value of the "subscription_phase_id" field in the mutation. +func (m *ChargeFlatFeeMutation) SubscriptionPhaseID() (r string, exists bool) { + v := m.subscription_phase + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionPhaseID returns the old "subscription_phase_id" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldSubscriptionPhaseID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionPhaseID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionPhaseID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionPhaseID: %w", err) + } + return oldValue.SubscriptionPhaseID, nil +} + +// ClearSubscriptionPhaseID clears the value of the "subscription_phase_id" field. +func (m *ChargeFlatFeeMutation) ClearSubscriptionPhaseID() { + m.subscription_phase = nil + m.clearedFields[chargeflatfee.FieldSubscriptionPhaseID] = struct{}{} +} + +// SubscriptionPhaseIDCleared returns if the "subscription_phase_id" field was cleared in this mutation. +func (m *ChargeFlatFeeMutation) SubscriptionPhaseIDCleared() bool { + _, ok := m.clearedFields[chargeflatfee.FieldSubscriptionPhaseID] + return ok +} + +// ResetSubscriptionPhaseID resets all changes to the "subscription_phase_id" field. +func (m *ChargeFlatFeeMutation) ResetSubscriptionPhaseID() { + m.subscription_phase = nil + delete(m.clearedFields, chargeflatfee.FieldSubscriptionPhaseID) +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (m *ChargeFlatFeeMutation) SetSubscriptionItemID(s string) { + m.subscription_item = &s +} + +// SubscriptionItemID returns the value of the "subscription_item_id" field in the mutation. +func (m *ChargeFlatFeeMutation) SubscriptionItemID() (r string, exists bool) { + v := m.subscription_item + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionItemID returns the old "subscription_item_id" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldSubscriptionItemID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionItemID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionItemID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionItemID: %w", err) + } + return oldValue.SubscriptionItemID, nil +} + +// ClearSubscriptionItemID clears the value of the "subscription_item_id" field. +func (m *ChargeFlatFeeMutation) ClearSubscriptionItemID() { + m.subscription_item = nil + m.clearedFields[chargeflatfee.FieldSubscriptionItemID] = struct{}{} +} + +// SubscriptionItemIDCleared returns if the "subscription_item_id" field was cleared in this mutation. +func (m *ChargeFlatFeeMutation) SubscriptionItemIDCleared() bool { + _, ok := m.clearedFields[chargeflatfee.FieldSubscriptionItemID] + return ok +} + +// ResetSubscriptionItemID resets all changes to the "subscription_item_id" field. +func (m *ChargeFlatFeeMutation) ResetSubscriptionItemID() { + m.subscription_item = nil + delete(m.clearedFields, chargeflatfee.FieldSubscriptionItemID) +} + +// SetAdvanceAfter sets the "advance_after" field. +func (m *ChargeFlatFeeMutation) SetAdvanceAfter(t time.Time) { + m.advance_after = &t +} + +// AdvanceAfter returns the value of the "advance_after" field in the mutation. +func (m *ChargeFlatFeeMutation) AdvanceAfter() (r time.Time, exists bool) { + v := m.advance_after + if v == nil { + return + } + return *v, true +} + +// OldAdvanceAfter returns the old "advance_after" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldAdvanceAfter(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAdvanceAfter is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAdvanceAfter requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAdvanceAfter: %w", err) + } + return oldValue.AdvanceAfter, nil +} + +// ClearAdvanceAfter clears the value of the "advance_after" field. +func (m *ChargeFlatFeeMutation) ClearAdvanceAfter() { + m.advance_after = nil + m.clearedFields[chargeflatfee.FieldAdvanceAfter] = struct{}{} +} + +// AdvanceAfterCleared returns if the "advance_after" field was cleared in this mutation. +func (m *ChargeFlatFeeMutation) AdvanceAfterCleared() bool { + _, ok := m.clearedFields[chargeflatfee.FieldAdvanceAfter] + return ok +} + +// ResetAdvanceAfter resets all changes to the "advance_after" field. +func (m *ChargeFlatFeeMutation) ResetAdvanceAfter() { + m.advance_after = nil + delete(m.clearedFields, chargeflatfee.FieldAdvanceAfter) +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (m *ChargeFlatFeeMutation) SetTaxCodeID(s string) { + m.tax_code = &s +} + +// TaxCodeID returns the value of the "tax_code_id" field in the mutation. +func (m *ChargeFlatFeeMutation) TaxCodeID() (r string, exists bool) { + v := m.tax_code + if v == nil { + return + } + return *v, true +} + +// OldTaxCodeID returns the old "tax_code_id" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldTaxCodeID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxCodeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxCodeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxCodeID: %w", err) + } + return oldValue.TaxCodeID, nil +} + +// ResetTaxCodeID resets all changes to the "tax_code_id" field. +func (m *ChargeFlatFeeMutation) ResetTaxCodeID() { + m.tax_code = nil +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (m *ChargeFlatFeeMutation) SetTaxBehavior(pb productcatalog.TaxBehavior) { + m.tax_behavior = &pb +} + +// TaxBehavior returns the value of the "tax_behavior" field in the mutation. +func (m *ChargeFlatFeeMutation) TaxBehavior() (r productcatalog.TaxBehavior, exists bool) { + v := m.tax_behavior + if v == nil { + return + } + return *v, true +} + +// OldTaxBehavior returns the old "tax_behavior" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldTaxBehavior(ctx context.Context) (v *productcatalog.TaxBehavior, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxBehavior is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxBehavior requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxBehavior: %w", err) + } + return oldValue.TaxBehavior, nil +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (m *ChargeFlatFeeMutation) ClearTaxBehavior() { + m.tax_behavior = nil + m.clearedFields[chargeflatfee.FieldTaxBehavior] = struct{}{} +} + +// TaxBehaviorCleared returns if the "tax_behavior" field was cleared in this mutation. +func (m *ChargeFlatFeeMutation) TaxBehaviorCleared() bool { + _, ok := m.clearedFields[chargeflatfee.FieldTaxBehavior] + return ok +} + +// ResetTaxBehavior resets all changes to the "tax_behavior" field. +func (m *ChargeFlatFeeMutation) ResetTaxBehavior() { + m.tax_behavior = nil + delete(m.clearedFields, chargeflatfee.FieldTaxBehavior) +} + +// SetAnnotations sets the "annotations" field. +func (m *ChargeFlatFeeMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *ChargeFlatFeeMutation) 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 ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) 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 *ChargeFlatFeeMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[chargeflatfee.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *ChargeFlatFeeMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[chargeflatfee.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *ChargeFlatFeeMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, chargeflatfee.FieldAnnotations) +} + +// SetNamespace sets the "namespace" field. +func (m *ChargeFlatFeeMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *ChargeFlatFeeMutation) 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 ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) 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 *ChargeFlatFeeMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *ChargeFlatFeeMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *ChargeFlatFeeMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *ChargeFlatFeeMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[chargeflatfee.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *ChargeFlatFeeMutation) MetadataCleared() bool { + _, ok := m.clearedFields[chargeflatfee.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *ChargeFlatFeeMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, chargeflatfee.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *ChargeFlatFeeMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ChargeFlatFeeMutation) 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 ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) 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 *ChargeFlatFeeMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *ChargeFlatFeeMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ChargeFlatFeeMutation) 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 ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) 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 *ChargeFlatFeeMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *ChargeFlatFeeMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *ChargeFlatFeeMutation) 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 ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) 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 *ChargeFlatFeeMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[chargeflatfee.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *ChargeFlatFeeMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[chargeflatfee.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *ChargeFlatFeeMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, chargeflatfee.FieldDeletedAt) +} + +// SetName sets the "name" field. +func (m *ChargeFlatFeeMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *ChargeFlatFeeMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *ChargeFlatFeeMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *ChargeFlatFeeMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *ChargeFlatFeeMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *ChargeFlatFeeMutation) ClearDescription() { + m.description = nil + m.clearedFields[chargeflatfee.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *ChargeFlatFeeMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[chargeflatfee.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *ChargeFlatFeeMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, chargeflatfee.FieldDescription) +} + +// SetPaymentTerm sets the "payment_term" field. +func (m *ChargeFlatFeeMutation) SetPaymentTerm(ptt productcatalog.PaymentTermType) { + m.payment_term = &ptt +} + +// PaymentTerm returns the value of the "payment_term" field in the mutation. +func (m *ChargeFlatFeeMutation) PaymentTerm() (r productcatalog.PaymentTermType, exists bool) { + v := m.payment_term + if v == nil { + return + } + return *v, true +} + +// OldPaymentTerm returns the old "payment_term" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldPaymentTerm(ctx context.Context) (v productcatalog.PaymentTermType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPaymentTerm is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPaymentTerm requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPaymentTerm: %w", err) + } + return oldValue.PaymentTerm, nil +} + +// ResetPaymentTerm resets all changes to the "payment_term" field. +func (m *ChargeFlatFeeMutation) ResetPaymentTerm() { + m.payment_term = nil +} + +// SetInvoiceAt sets the "invoice_at" field. +func (m *ChargeFlatFeeMutation) SetInvoiceAt(t time.Time) { + m.invoice_at = &t +} + +// InvoiceAt returns the value of the "invoice_at" field in the mutation. +func (m *ChargeFlatFeeMutation) 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 ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) 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 *ChargeFlatFeeMutation) ResetInvoiceAt() { + m.invoice_at = nil +} + +// SetSettlementMode sets the "settlement_mode" field. +func (m *ChargeFlatFeeMutation) SetSettlementMode(pm productcatalog.SettlementMode) { + m.settlement_mode = &pm +} + +// SettlementMode returns the value of the "settlement_mode" field in the mutation. +func (m *ChargeFlatFeeMutation) 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 ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) 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 *ChargeFlatFeeMutation) ResetSettlementMode() { + m.settlement_mode = nil +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (m *ChargeFlatFeeMutation) SetIntentDeletedAt(t time.Time) { + m.intent_deleted_at = &t +} + +// IntentDeletedAt returns the value of the "intent_deleted_at" field in the mutation. +func (m *ChargeFlatFeeMutation) IntentDeletedAt() (r time.Time, exists bool) { + v := m.intent_deleted_at + if v == nil { + return + } + return *v, true +} + +// OldIntentDeletedAt returns the old "intent_deleted_at" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldIntentDeletedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIntentDeletedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIntentDeletedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIntentDeletedAt: %w", err) + } + return oldValue.IntentDeletedAt, nil +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (m *ChargeFlatFeeMutation) ClearIntentDeletedAt() { + m.intent_deleted_at = nil + m.clearedFields[chargeflatfee.FieldIntentDeletedAt] = struct{}{} +} + +// IntentDeletedAtCleared returns if the "intent_deleted_at" field was cleared in this mutation. +func (m *ChargeFlatFeeMutation) IntentDeletedAtCleared() bool { + _, ok := m.clearedFields[chargeflatfee.FieldIntentDeletedAt] + return ok +} + +// ResetIntentDeletedAt resets all changes to the "intent_deleted_at" field. +func (m *ChargeFlatFeeMutation) ResetIntentDeletedAt() { + m.intent_deleted_at = nil + delete(m.clearedFields, chargeflatfee.FieldIntentDeletedAt) +} + +// SetDiscounts sets the "discounts" field. +func (m *ChargeFlatFeeMutation) SetDiscounts(b *billing.Discounts) { + m.discounts = &b +} + +// Discounts returns the value of the "discounts" field in the mutation. +func (m *ChargeFlatFeeMutation) Discounts() (r *billing.Discounts, exists bool) { + v := m.discounts + if v == nil { + return + } + return *v, true +} + +// OldDiscounts returns the old "discounts" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldDiscounts(ctx context.Context) (v *billing.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 *ChargeFlatFeeMutation) ClearDiscounts() { + m.discounts = nil + m.clearedFields[chargeflatfee.FieldDiscounts] = struct{}{} +} + +// DiscountsCleared returns if the "discounts" field was cleared in this mutation. +func (m *ChargeFlatFeeMutation) DiscountsCleared() bool { + _, ok := m.clearedFields[chargeflatfee.FieldDiscounts] + return ok +} + +// ResetDiscounts resets all changes to the "discounts" field. +func (m *ChargeFlatFeeMutation) ResetDiscounts() { + m.discounts = nil + delete(m.clearedFields, chargeflatfee.FieldDiscounts) +} + +// SetProRating sets the "pro_rating" field. +func (m *ChargeFlatFeeMutation) SetProRating(frmae flatfee.ProRatingModeAdapterEnum) { + m.pro_rating = &frmae +} + +// ProRating returns the value of the "pro_rating" field in the mutation. +func (m *ChargeFlatFeeMutation) ProRating() (r flatfee.ProRatingModeAdapterEnum, exists bool) { + v := m.pro_rating + if v == nil { + return + } + return *v, true +} + +// OldProRating returns the old "pro_rating" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldProRating(ctx context.Context) (v flatfee.ProRatingModeAdapterEnum, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldProRating is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldProRating requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldProRating: %w", err) + } + return oldValue.ProRating, nil +} + +// ResetProRating resets all changes to the "pro_rating" field. +func (m *ChargeFlatFeeMutation) ResetProRating() { + m.pro_rating = nil +} + +// SetFeatureKey sets the "feature_key" field. +func (m *ChargeFlatFeeMutation) SetFeatureKey(s string) { + m.feature_key = &s +} + +// FeatureKey returns the value of the "feature_key" field in the mutation. +func (m *ChargeFlatFeeMutation) 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 ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) 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 +} + +// ClearFeatureKey clears the value of the "feature_key" field. +func (m *ChargeFlatFeeMutation) ClearFeatureKey() { + m.feature_key = nil + m.clearedFields[chargeflatfee.FieldFeatureKey] = struct{}{} +} + +// FeatureKeyCleared returns if the "feature_key" field was cleared in this mutation. +func (m *ChargeFlatFeeMutation) FeatureKeyCleared() bool { + _, ok := m.clearedFields[chargeflatfee.FieldFeatureKey] + return ok +} + +// ResetFeatureKey resets all changes to the "feature_key" field. +func (m *ChargeFlatFeeMutation) ResetFeatureKey() { + m.feature_key = nil + delete(m.clearedFields, chargeflatfee.FieldFeatureKey) +} + +// SetFeatureID sets the "feature_id" field. +func (m *ChargeFlatFeeMutation) SetFeatureID(s string) { + m.feature = &s +} + +// FeatureID returns the value of the "feature_id" field in the mutation. +func (m *ChargeFlatFeeMutation) FeatureID() (r string, exists bool) { + v := m.feature + if v == nil { + return + } + return *v, true +} + +// OldFeatureID returns the old "feature_id" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldFeatureID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFeatureID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFeatureID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFeatureID: %w", err) + } + return oldValue.FeatureID, nil +} + +// ClearFeatureID clears the value of the "feature_id" field. +func (m *ChargeFlatFeeMutation) ClearFeatureID() { + m.feature = nil + m.clearedFields[chargeflatfee.FieldFeatureID] = struct{}{} +} + +// FeatureIDCleared returns if the "feature_id" field was cleared in this mutation. +func (m *ChargeFlatFeeMutation) FeatureIDCleared() bool { + _, ok := m.clearedFields[chargeflatfee.FieldFeatureID] + return ok +} + +// ResetFeatureID resets all changes to the "feature_id" field. +func (m *ChargeFlatFeeMutation) ResetFeatureID() { + m.feature = nil + delete(m.clearedFields, chargeflatfee.FieldFeatureID) +} + +// SetAmountBeforeProration sets the "amount_before_proration" field. +func (m *ChargeFlatFeeMutation) SetAmountBeforeProration(a alpacadecimal.Decimal) { + m.amount_before_proration = &a +} + +// AmountBeforeProration returns the value of the "amount_before_proration" field in the mutation. +func (m *ChargeFlatFeeMutation) AmountBeforeProration() (r alpacadecimal.Decimal, exists bool) { + v := m.amount_before_proration + if v == nil { + return + } + return *v, true +} + +// OldAmountBeforeProration returns the old "amount_before_proration" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldAmountBeforeProration(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAmountBeforeProration is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAmountBeforeProration requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAmountBeforeProration: %w", err) + } + return oldValue.AmountBeforeProration, nil +} + +// ResetAmountBeforeProration resets all changes to the "amount_before_proration" field. +func (m *ChargeFlatFeeMutation) ResetAmountBeforeProration() { + m.amount_before_proration = nil +} + +// SetAmountAfterProration sets the "amount_after_proration" field. +func (m *ChargeFlatFeeMutation) SetAmountAfterProration(a alpacadecimal.Decimal) { + m.amount_after_proration = &a +} + +// AmountAfterProration returns the value of the "amount_after_proration" field in the mutation. +func (m *ChargeFlatFeeMutation) AmountAfterProration() (r alpacadecimal.Decimal, exists bool) { + v := m.amount_after_proration + if v == nil { + return + } + return *v, true +} + +// OldAmountAfterProration returns the old "amount_after_proration" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldAmountAfterProration(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAmountAfterProration is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAmountAfterProration requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAmountAfterProration: %w", err) + } + return oldValue.AmountAfterProration, nil +} + +// ResetAmountAfterProration resets all changes to the "amount_after_proration" field. +func (m *ChargeFlatFeeMutation) ResetAmountAfterProration() { + m.amount_after_proration = nil +} + +// SetCurrentRealizationRunID sets the "current_realization_run_id" field. +func (m *ChargeFlatFeeMutation) SetCurrentRealizationRunID(s string) { + m.current_run = &s +} + +// CurrentRealizationRunID returns the value of the "current_realization_run_id" field in the mutation. +func (m *ChargeFlatFeeMutation) CurrentRealizationRunID() (r string, exists bool) { + v := m.current_run + if v == nil { + return + } + return *v, true +} + +// OldCurrentRealizationRunID returns the old "current_realization_run_id" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldCurrentRealizationRunID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrentRealizationRunID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrentRealizationRunID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrentRealizationRunID: %w", err) + } + return oldValue.CurrentRealizationRunID, nil +} + +// ClearCurrentRealizationRunID clears the value of the "current_realization_run_id" field. +func (m *ChargeFlatFeeMutation) ClearCurrentRealizationRunID() { + m.current_run = nil + m.clearedFields[chargeflatfee.FieldCurrentRealizationRunID] = struct{}{} +} + +// CurrentRealizationRunIDCleared returns if the "current_realization_run_id" field was cleared in this mutation. +func (m *ChargeFlatFeeMutation) CurrentRealizationRunIDCleared() bool { + _, ok := m.clearedFields[chargeflatfee.FieldCurrentRealizationRunID] + return ok +} + +// ResetCurrentRealizationRunID resets all changes to the "current_realization_run_id" field. +func (m *ChargeFlatFeeMutation) ResetCurrentRealizationRunID() { + m.current_run = nil + delete(m.clearedFields, chargeflatfee.FieldCurrentRealizationRunID) +} + +// SetStatusDetailed sets the "status_detailed" field. +func (m *ChargeFlatFeeMutation) SetStatusDetailed(f flatfee.Status) { + m.status_detailed = &f +} + +// StatusDetailed returns the value of the "status_detailed" field in the mutation. +func (m *ChargeFlatFeeMutation) StatusDetailed() (r flatfee.Status, exists bool) { + v := m.status_detailed + if v == nil { + return + } + return *v, true +} + +// OldStatusDetailed returns the old "status_detailed" field's value of the ChargeFlatFee entity. +// If the ChargeFlatFee 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 *ChargeFlatFeeMutation) OldStatusDetailed(ctx context.Context) (v flatfee.Status, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStatusDetailed is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStatusDetailed requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStatusDetailed: %w", err) + } + return oldValue.StatusDetailed, nil +} + +// ResetStatusDetailed resets all changes to the "status_detailed" field. +func (m *ChargeFlatFeeMutation) ResetStatusDetailed() { + m.status_detailed = nil +} + +// AddRunIDs adds the "runs" edge to the ChargeFlatFeeRun entity by ids. +func (m *ChargeFlatFeeMutation) 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 ChargeFlatFeeRun entity. +func (m *ChargeFlatFeeMutation) ClearRuns() { + m.clearedruns = true +} + +// RunsCleared reports if the "runs" edge to the ChargeFlatFeeRun entity was cleared. +func (m *ChargeFlatFeeMutation) RunsCleared() bool { + return m.clearedruns +} + +// RemoveRunIDs removes the "runs" edge to the ChargeFlatFeeRun entity by IDs. +func (m *ChargeFlatFeeMutation) 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 ChargeFlatFeeRun entity. +func (m *ChargeFlatFeeMutation) RemovedRunsIDs() (ids []string) { + for id := range m.removedruns { + ids = append(ids, id) + } + return +} + +// RunsIDs returns the "runs" edge IDs in the mutation. +func (m *ChargeFlatFeeMutation) RunsIDs() (ids []string) { + for id := range m.runs { + ids = append(ids, id) + } + return +} + +// ResetRuns resets all changes to the "runs" edge. +func (m *ChargeFlatFeeMutation) ResetRuns() { + m.runs = nil + m.clearedruns = false + m.removedruns = nil +} + +// SetCurrentRunID sets the "current_run" edge to the ChargeFlatFeeRun entity by id. +func (m *ChargeFlatFeeMutation) SetCurrentRunID(id string) { + m.current_run = &id +} + +// ClearCurrentRun clears the "current_run" edge to the ChargeFlatFeeRun entity. +func (m *ChargeFlatFeeMutation) ClearCurrentRun() { + m.clearedcurrent_run = true + m.clearedFields[chargeflatfee.FieldCurrentRealizationRunID] = struct{}{} +} + +// CurrentRunCleared reports if the "current_run" edge to the ChargeFlatFeeRun entity was cleared. +func (m *ChargeFlatFeeMutation) CurrentRunCleared() bool { + return m.CurrentRealizationRunIDCleared() || m.clearedcurrent_run +} + +// CurrentRunID returns the "current_run" edge ID in the mutation. +func (m *ChargeFlatFeeMutation) CurrentRunID() (id string, exists bool) { + if m.current_run != nil { + return *m.current_run, true + } + return +} + +// CurrentRunIDs returns the "current_run" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CurrentRunID instead. It exists only for internal usage by the builders. +func (m *ChargeFlatFeeMutation) CurrentRunIDs() (ids []string) { + if id := m.current_run; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCurrentRun resets all changes to the "current_run" edge. +func (m *ChargeFlatFeeMutation) ResetCurrentRun() { + m.current_run = nil + m.clearedcurrent_run = false +} + +// SetChargeID sets the "charge" edge to the Charge entity by id. +func (m *ChargeFlatFeeMutation) SetChargeID(id string) { + m.charge = &id +} + +// ClearCharge clears the "charge" edge to the Charge entity. +func (m *ChargeFlatFeeMutation) ClearCharge() { + m.clearedcharge = true +} + +// ChargeCleared reports if the "charge" edge to the Charge entity was cleared. +func (m *ChargeFlatFeeMutation) ChargeCleared() bool { + return m.clearedcharge +} + +// ChargeID returns the "charge" edge ID in the mutation. +func (m *ChargeFlatFeeMutation) 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 *ChargeFlatFeeMutation) ChargeIDs() (ids []string) { + if id := m.charge; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCharge resets all changes to the "charge" edge. +func (m *ChargeFlatFeeMutation) ResetCharge() { + m.charge = nil + m.clearedcharge = false +} + +// SetIntentOverrideID sets the "intent_override" edge to the ChargeFlatFeeOverride entity by id. +func (m *ChargeFlatFeeMutation) SetIntentOverrideID(id string) { + m.intent_override = &id +} + +// ClearIntentOverride clears the "intent_override" edge to the ChargeFlatFeeOverride entity. +func (m *ChargeFlatFeeMutation) ClearIntentOverride() { + m.clearedintent_override = true +} + +// IntentOverrideCleared reports if the "intent_override" edge to the ChargeFlatFeeOverride entity was cleared. +func (m *ChargeFlatFeeMutation) IntentOverrideCleared() bool { + return m.clearedintent_override +} + +// IntentOverrideID returns the "intent_override" edge ID in the mutation. +func (m *ChargeFlatFeeMutation) IntentOverrideID() (id string, exists bool) { + if m.intent_override != nil { + return *m.intent_override, true + } + return +} + +// IntentOverrideIDs returns the "intent_override" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// IntentOverrideID instead. It exists only for internal usage by the builders. +func (m *ChargeFlatFeeMutation) IntentOverrideIDs() (ids []string) { + if id := m.intent_override; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetIntentOverride resets all changes to the "intent_override" edge. +func (m *ChargeFlatFeeMutation) ResetIntentOverride() { + m.intent_override = nil + m.clearedintent_override = false +} + +// ClearSubscription clears the "subscription" edge to the Subscription entity. +func (m *ChargeFlatFeeMutation) ClearSubscription() { + m.clearedsubscription = true + m.clearedFields[chargeflatfee.FieldSubscriptionID] = struct{}{} +} + +// SubscriptionCleared reports if the "subscription" edge to the Subscription entity was cleared. +func (m *ChargeFlatFeeMutation) SubscriptionCleared() bool { + return m.SubscriptionIDCleared() || m.clearedsubscription +} + +// SubscriptionIDs returns the "subscription" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubscriptionID instead. It exists only for internal usage by the builders. +func (m *ChargeFlatFeeMutation) SubscriptionIDs() (ids []string) { + if id := m.subscription; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSubscription resets all changes to the "subscription" edge. +func (m *ChargeFlatFeeMutation) ResetSubscription() { + m.subscription = nil + m.clearedsubscription = false +} + +// ClearSubscriptionPhase clears the "subscription_phase" edge to the SubscriptionPhase entity. +func (m *ChargeFlatFeeMutation) ClearSubscriptionPhase() { + m.clearedsubscription_phase = true + m.clearedFields[chargeflatfee.FieldSubscriptionPhaseID] = struct{}{} +} + +// SubscriptionPhaseCleared reports if the "subscription_phase" edge to the SubscriptionPhase entity was cleared. +func (m *ChargeFlatFeeMutation) SubscriptionPhaseCleared() bool { + return m.SubscriptionPhaseIDCleared() || m.clearedsubscription_phase +} + +// SubscriptionPhaseIDs returns the "subscription_phase" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubscriptionPhaseID instead. It exists only for internal usage by the builders. +func (m *ChargeFlatFeeMutation) SubscriptionPhaseIDs() (ids []string) { + if id := m.subscription_phase; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSubscriptionPhase resets all changes to the "subscription_phase" edge. +func (m *ChargeFlatFeeMutation) ResetSubscriptionPhase() { + m.subscription_phase = nil + m.clearedsubscription_phase = false +} + +// ClearSubscriptionItem clears the "subscription_item" edge to the SubscriptionItem entity. +func (m *ChargeFlatFeeMutation) ClearSubscriptionItem() { + m.clearedsubscription_item = true + m.clearedFields[chargeflatfee.FieldSubscriptionItemID] = struct{}{} +} + +// SubscriptionItemCleared reports if the "subscription_item" edge to the SubscriptionItem entity was cleared. +func (m *ChargeFlatFeeMutation) SubscriptionItemCleared() bool { + return m.SubscriptionItemIDCleared() || m.clearedsubscription_item +} + +// SubscriptionItemIDs returns the "subscription_item" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubscriptionItemID instead. It exists only for internal usage by the builders. +func (m *ChargeFlatFeeMutation) SubscriptionItemIDs() (ids []string) { + if id := m.subscription_item; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSubscriptionItem resets all changes to the "subscription_item" edge. +func (m *ChargeFlatFeeMutation) ResetSubscriptionItem() { + m.subscription_item = nil + m.clearedsubscription_item = false +} + +// ClearCustomer clears the "customer" edge to the Customer entity. +func (m *ChargeFlatFeeMutation) ClearCustomer() { + m.clearedcustomer = true + m.clearedFields[chargeflatfee.FieldCustomerID] = struct{}{} +} + +// CustomerCleared reports if the "customer" edge to the Customer entity was cleared. +func (m *ChargeFlatFeeMutation) CustomerCleared() bool { + return m.clearedcustomer +} + +// CustomerIDs returns the "customer" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CustomerID instead. It exists only for internal usage by the builders. +func (m *ChargeFlatFeeMutation) CustomerIDs() (ids []string) { + if id := m.customer; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCustomer resets all changes to the "customer" edge. +func (m *ChargeFlatFeeMutation) ResetCustomer() { + m.customer = nil + m.clearedcustomer = false +} + +// ClearFeature clears the "feature" edge to the Feature entity. +func (m *ChargeFlatFeeMutation) ClearFeature() { + m.clearedfeature = true + m.clearedFields[chargeflatfee.FieldFeatureID] = struct{}{} +} + +// FeatureCleared reports if the "feature" edge to the Feature entity was cleared. +func (m *ChargeFlatFeeMutation) FeatureCleared() bool { + return m.FeatureIDCleared() || m.clearedfeature +} + +// FeatureIDs returns the "feature" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// FeatureID instead. It exists only for internal usage by the builders. +func (m *ChargeFlatFeeMutation) FeatureIDs() (ids []string) { + if id := m.feature; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetFeature resets all changes to the "feature" edge. +func (m *ChargeFlatFeeMutation) ResetFeature() { + m.feature = nil + m.clearedfeature = false +} + +// ClearTaxCode clears the "tax_code" edge to the TaxCode entity. +func (m *ChargeFlatFeeMutation) ClearTaxCode() { + m.clearedtax_code = true + m.clearedFields[chargeflatfee.FieldTaxCodeID] = struct{}{} +} + +// TaxCodeCleared reports if the "tax_code" edge to the TaxCode entity was cleared. +func (m *ChargeFlatFeeMutation) TaxCodeCleared() bool { + return m.clearedtax_code +} + +// TaxCodeIDs returns the "tax_code" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TaxCodeID instead. It exists only for internal usage by the builders. +func (m *ChargeFlatFeeMutation) TaxCodeIDs() (ids []string) { + if id := m.tax_code; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTaxCode resets all changes to the "tax_code" edge. +func (m *ChargeFlatFeeMutation) ResetTaxCode() { + m.tax_code = nil + m.clearedtax_code = false +} + +// Where appends a list predicates to the ChargeFlatFeeMutation builder. +func (m *ChargeFlatFeeMutation) Where(ps ...predicate.ChargeFlatFee) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ChargeFlatFeeMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ChargeFlatFeeMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ChargeFlatFee, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ChargeFlatFeeMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ChargeFlatFeeMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ChargeFlatFee). +func (m *ChargeFlatFeeMutation) 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 *ChargeFlatFeeMutation) Fields() []string { + fields := make([]string, 0, 37) + if m.customer != nil { + fields = append(fields, chargeflatfee.FieldCustomerID) + } + if m.service_period_from != nil { + fields = append(fields, chargeflatfee.FieldServicePeriodFrom) + } + if m.service_period_to != nil { + fields = append(fields, chargeflatfee.FieldServicePeriodTo) + } + if m.billing_period_from != nil { + fields = append(fields, chargeflatfee.FieldBillingPeriodFrom) + } + if m.billing_period_to != nil { + fields = append(fields, chargeflatfee.FieldBillingPeriodTo) + } + if m.full_service_period_from != nil { + fields = append(fields, chargeflatfee.FieldFullServicePeriodFrom) + } + if m.full_service_period_to != nil { + fields = append(fields, chargeflatfee.FieldFullServicePeriodTo) + } + if m.status != nil { + fields = append(fields, chargeflatfee.FieldStatus) + } + if m.unique_reference_id != nil { + fields = append(fields, chargeflatfee.FieldUniqueReferenceID) + } + if m.currency != nil { + fields = append(fields, chargeflatfee.FieldCurrency) + } + if m.managed_by != nil { + fields = append(fields, chargeflatfee.FieldManagedBy) + } + if m.subscription != nil { + fields = append(fields, chargeflatfee.FieldSubscriptionID) + } + if m.subscription_phase != nil { + fields = append(fields, chargeflatfee.FieldSubscriptionPhaseID) + } + if m.subscription_item != nil { + fields = append(fields, chargeflatfee.FieldSubscriptionItemID) + } + if m.advance_after != nil { + fields = append(fields, chargeflatfee.FieldAdvanceAfter) + } + if m.tax_code != nil { + fields = append(fields, chargeflatfee.FieldTaxCodeID) + } + if m.tax_behavior != nil { + fields = append(fields, chargeflatfee.FieldTaxBehavior) + } + if m.annotations != nil { + fields = append(fields, chargeflatfee.FieldAnnotations) + } + if m.namespace != nil { + fields = append(fields, chargeflatfee.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, chargeflatfee.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, chargeflatfee.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, chargeflatfee.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, chargeflatfee.FieldDeletedAt) + } + if m.name != nil { + fields = append(fields, chargeflatfee.FieldName) + } + if m.description != nil { + fields = append(fields, chargeflatfee.FieldDescription) + } + if m.payment_term != nil { + fields = append(fields, chargeflatfee.FieldPaymentTerm) + } + if m.invoice_at != nil { + fields = append(fields, chargeflatfee.FieldInvoiceAt) + } + if m.settlement_mode != nil { + fields = append(fields, chargeflatfee.FieldSettlementMode) + } + if m.intent_deleted_at != nil { + fields = append(fields, chargeflatfee.FieldIntentDeletedAt) + } + if m.discounts != nil { + fields = append(fields, chargeflatfee.FieldDiscounts) + } + if m.pro_rating != nil { + fields = append(fields, chargeflatfee.FieldProRating) + } + if m.feature_key != nil { + fields = append(fields, chargeflatfee.FieldFeatureKey) + } + if m.feature != nil { + fields = append(fields, chargeflatfee.FieldFeatureID) + } + if m.amount_before_proration != nil { + fields = append(fields, chargeflatfee.FieldAmountBeforeProration) + } + if m.amount_after_proration != nil { + fields = append(fields, chargeflatfee.FieldAmountAfterProration) + } + if m.current_run != nil { + fields = append(fields, chargeflatfee.FieldCurrentRealizationRunID) + } + if m.status_detailed != nil { + fields = append(fields, chargeflatfee.FieldStatusDetailed) + } + 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 *ChargeFlatFeeMutation) Field(name string) (ent.Value, bool) { + switch name { + case chargeflatfee.FieldCustomerID: + return m.CustomerID() + case chargeflatfee.FieldServicePeriodFrom: + return m.ServicePeriodFrom() + case chargeflatfee.FieldServicePeriodTo: + return m.ServicePeriodTo() + case chargeflatfee.FieldBillingPeriodFrom: + return m.BillingPeriodFrom() + case chargeflatfee.FieldBillingPeriodTo: + return m.BillingPeriodTo() + case chargeflatfee.FieldFullServicePeriodFrom: + return m.FullServicePeriodFrom() + case chargeflatfee.FieldFullServicePeriodTo: + return m.FullServicePeriodTo() + case chargeflatfee.FieldStatus: + return m.Status() + case chargeflatfee.FieldUniqueReferenceID: + return m.UniqueReferenceID() + case chargeflatfee.FieldCurrency: + return m.Currency() + case chargeflatfee.FieldManagedBy: + return m.ManagedBy() + case chargeflatfee.FieldSubscriptionID: + return m.SubscriptionID() + case chargeflatfee.FieldSubscriptionPhaseID: + return m.SubscriptionPhaseID() + case chargeflatfee.FieldSubscriptionItemID: + return m.SubscriptionItemID() + case chargeflatfee.FieldAdvanceAfter: + return m.AdvanceAfter() + case chargeflatfee.FieldTaxCodeID: + return m.TaxCodeID() + case chargeflatfee.FieldTaxBehavior: + return m.TaxBehavior() + case chargeflatfee.FieldAnnotations: + return m.Annotations() + case chargeflatfee.FieldNamespace: + return m.Namespace() + case chargeflatfee.FieldMetadata: + return m.Metadata() + case chargeflatfee.FieldCreatedAt: + return m.CreatedAt() + case chargeflatfee.FieldUpdatedAt: + return m.UpdatedAt() + case chargeflatfee.FieldDeletedAt: + return m.DeletedAt() + case chargeflatfee.FieldName: + return m.Name() + case chargeflatfee.FieldDescription: + return m.Description() + case chargeflatfee.FieldPaymentTerm: + return m.PaymentTerm() + case chargeflatfee.FieldInvoiceAt: + return m.InvoiceAt() + case chargeflatfee.FieldSettlementMode: + return m.SettlementMode() + case chargeflatfee.FieldIntentDeletedAt: + return m.IntentDeletedAt() + case chargeflatfee.FieldDiscounts: + return m.Discounts() + case chargeflatfee.FieldProRating: + return m.ProRating() + case chargeflatfee.FieldFeatureKey: + return m.FeatureKey() + case chargeflatfee.FieldFeatureID: + return m.FeatureID() + case chargeflatfee.FieldAmountBeforeProration: + return m.AmountBeforeProration() + case chargeflatfee.FieldAmountAfterProration: + return m.AmountAfterProration() + case chargeflatfee.FieldCurrentRealizationRunID: + return m.CurrentRealizationRunID() + case chargeflatfee.FieldStatusDetailed: + return m.StatusDetailed() + } + 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 *ChargeFlatFeeMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case chargeflatfee.FieldCustomerID: + return m.OldCustomerID(ctx) + case chargeflatfee.FieldServicePeriodFrom: + return m.OldServicePeriodFrom(ctx) + case chargeflatfee.FieldServicePeriodTo: + return m.OldServicePeriodTo(ctx) + case chargeflatfee.FieldBillingPeriodFrom: + return m.OldBillingPeriodFrom(ctx) + case chargeflatfee.FieldBillingPeriodTo: + return m.OldBillingPeriodTo(ctx) + case chargeflatfee.FieldFullServicePeriodFrom: + return m.OldFullServicePeriodFrom(ctx) + case chargeflatfee.FieldFullServicePeriodTo: + return m.OldFullServicePeriodTo(ctx) + case chargeflatfee.FieldStatus: + return m.OldStatus(ctx) + case chargeflatfee.FieldUniqueReferenceID: + return m.OldUniqueReferenceID(ctx) + case chargeflatfee.FieldCurrency: + return m.OldCurrency(ctx) + case chargeflatfee.FieldManagedBy: + return m.OldManagedBy(ctx) + case chargeflatfee.FieldSubscriptionID: + return m.OldSubscriptionID(ctx) + case chargeflatfee.FieldSubscriptionPhaseID: + return m.OldSubscriptionPhaseID(ctx) + case chargeflatfee.FieldSubscriptionItemID: + return m.OldSubscriptionItemID(ctx) + case chargeflatfee.FieldAdvanceAfter: + return m.OldAdvanceAfter(ctx) + case chargeflatfee.FieldTaxCodeID: + return m.OldTaxCodeID(ctx) + case chargeflatfee.FieldTaxBehavior: + return m.OldTaxBehavior(ctx) + case chargeflatfee.FieldAnnotations: + return m.OldAnnotations(ctx) + case chargeflatfee.FieldNamespace: + return m.OldNamespace(ctx) + case chargeflatfee.FieldMetadata: + return m.OldMetadata(ctx) + case chargeflatfee.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case chargeflatfee.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case chargeflatfee.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case chargeflatfee.FieldName: + return m.OldName(ctx) + case chargeflatfee.FieldDescription: + return m.OldDescription(ctx) + case chargeflatfee.FieldPaymentTerm: + return m.OldPaymentTerm(ctx) + case chargeflatfee.FieldInvoiceAt: + return m.OldInvoiceAt(ctx) + case chargeflatfee.FieldSettlementMode: + return m.OldSettlementMode(ctx) + case chargeflatfee.FieldIntentDeletedAt: + return m.OldIntentDeletedAt(ctx) + case chargeflatfee.FieldDiscounts: + return m.OldDiscounts(ctx) + case chargeflatfee.FieldProRating: + return m.OldProRating(ctx) + case chargeflatfee.FieldFeatureKey: + return m.OldFeatureKey(ctx) + case chargeflatfee.FieldFeatureID: + return m.OldFeatureID(ctx) + case chargeflatfee.FieldAmountBeforeProration: + return m.OldAmountBeforeProration(ctx) + case chargeflatfee.FieldAmountAfterProration: + return m.OldAmountAfterProration(ctx) + case chargeflatfee.FieldCurrentRealizationRunID: + return m.OldCurrentRealizationRunID(ctx) + case chargeflatfee.FieldStatusDetailed: + return m.OldStatusDetailed(ctx) + } + return nil, fmt.Errorf("unknown ChargeFlatFee 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 *ChargeFlatFeeMutation) SetField(name string, value ent.Value) error { + switch name { + case chargeflatfee.FieldCustomerID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerID(v) + return nil + case chargeflatfee.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 chargeflatfee.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 chargeflatfee.FieldBillingPeriodFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingPeriodFrom(v) + return nil + case chargeflatfee.FieldBillingPeriodTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingPeriodTo(v) + return nil + case chargeflatfee.FieldFullServicePeriodFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFullServicePeriodFrom(v) + return nil + case chargeflatfee.FieldFullServicePeriodTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFullServicePeriodTo(v) + return nil + case chargeflatfee.FieldStatus: + v, ok := value.(meta.ChargeStatus) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case chargeflatfee.FieldUniqueReferenceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUniqueReferenceID(v) + return nil + case chargeflatfee.FieldCurrency: + v, ok := value.(currencyx.Code) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrency(v) + return nil + case chargeflatfee.FieldManagedBy: + v, ok := value.(billing.InvoiceLineManagedBy) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetManagedBy(v) + return nil + case chargeflatfee.FieldSubscriptionID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionID(v) + return nil + case chargeflatfee.FieldSubscriptionPhaseID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionPhaseID(v) + return nil + case chargeflatfee.FieldSubscriptionItemID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionItemID(v) + return nil + case chargeflatfee.FieldAdvanceAfter: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAdvanceAfter(v) + return nil + case chargeflatfee.FieldTaxCodeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxCodeID(v) + return nil + case chargeflatfee.FieldTaxBehavior: + v, ok := value.(productcatalog.TaxBehavior) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxBehavior(v) + return nil + case chargeflatfee.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 chargeflatfee.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case chargeflatfee.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case chargeflatfee.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 chargeflatfee.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 chargeflatfee.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 chargeflatfee.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case chargeflatfee.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case chargeflatfee.FieldPaymentTerm: + v, ok := value.(productcatalog.PaymentTermType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPaymentTerm(v) + return nil + case chargeflatfee.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 chargeflatfee.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 chargeflatfee.FieldIntentDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIntentDeletedAt(v) + return nil + case chargeflatfee.FieldDiscounts: + v, ok := value.(*billing.Discounts) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDiscounts(v) + return nil + case chargeflatfee.FieldProRating: + v, ok := value.(flatfee.ProRatingModeAdapterEnum) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetProRating(v) + return nil + case chargeflatfee.FieldFeatureKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFeatureKey(v) + return nil + case chargeflatfee.FieldFeatureID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFeatureID(v) + return nil + case chargeflatfee.FieldAmountBeforeProration: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAmountBeforeProration(v) + return nil + case chargeflatfee.FieldAmountAfterProration: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAmountAfterProration(v) + return nil + case chargeflatfee.FieldCurrentRealizationRunID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrentRealizationRunID(v) + return nil + case chargeflatfee.FieldStatusDetailed: + v, ok := value.(flatfee.Status) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatusDetailed(v) + return nil + } + return fmt.Errorf("unknown ChargeFlatFee field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ChargeFlatFeeMutation) 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 *ChargeFlatFeeMutation) 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 *ChargeFlatFeeMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown ChargeFlatFee numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ChargeFlatFeeMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(chargeflatfee.FieldUniqueReferenceID) { + fields = append(fields, chargeflatfee.FieldUniqueReferenceID) + } + if m.FieldCleared(chargeflatfee.FieldSubscriptionID) { + fields = append(fields, chargeflatfee.FieldSubscriptionID) + } + if m.FieldCleared(chargeflatfee.FieldSubscriptionPhaseID) { + fields = append(fields, chargeflatfee.FieldSubscriptionPhaseID) + } + if m.FieldCleared(chargeflatfee.FieldSubscriptionItemID) { + fields = append(fields, chargeflatfee.FieldSubscriptionItemID) + } + if m.FieldCleared(chargeflatfee.FieldAdvanceAfter) { + fields = append(fields, chargeflatfee.FieldAdvanceAfter) + } + if m.FieldCleared(chargeflatfee.FieldTaxBehavior) { + fields = append(fields, chargeflatfee.FieldTaxBehavior) + } + if m.FieldCleared(chargeflatfee.FieldAnnotations) { + fields = append(fields, chargeflatfee.FieldAnnotations) + } + if m.FieldCleared(chargeflatfee.FieldMetadata) { + fields = append(fields, chargeflatfee.FieldMetadata) + } + if m.FieldCleared(chargeflatfee.FieldDeletedAt) { + fields = append(fields, chargeflatfee.FieldDeletedAt) + } + if m.FieldCleared(chargeflatfee.FieldDescription) { + fields = append(fields, chargeflatfee.FieldDescription) + } + if m.FieldCleared(chargeflatfee.FieldIntentDeletedAt) { + fields = append(fields, chargeflatfee.FieldIntentDeletedAt) + } + if m.FieldCleared(chargeflatfee.FieldDiscounts) { + fields = append(fields, chargeflatfee.FieldDiscounts) + } + if m.FieldCleared(chargeflatfee.FieldFeatureKey) { + fields = append(fields, chargeflatfee.FieldFeatureKey) + } + if m.FieldCleared(chargeflatfee.FieldFeatureID) { + fields = append(fields, chargeflatfee.FieldFeatureID) + } + if m.FieldCleared(chargeflatfee.FieldCurrentRealizationRunID) { + fields = append(fields, chargeflatfee.FieldCurrentRealizationRunID) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ChargeFlatFeeMutation) 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 *ChargeFlatFeeMutation) ClearField(name string) error { + switch name { + case chargeflatfee.FieldUniqueReferenceID: + m.ClearUniqueReferenceID() + return nil + case chargeflatfee.FieldSubscriptionID: + m.ClearSubscriptionID() + return nil + case chargeflatfee.FieldSubscriptionPhaseID: + m.ClearSubscriptionPhaseID() + return nil + case chargeflatfee.FieldSubscriptionItemID: + m.ClearSubscriptionItemID() + return nil + case chargeflatfee.FieldAdvanceAfter: + m.ClearAdvanceAfter() + return nil + case chargeflatfee.FieldTaxBehavior: + m.ClearTaxBehavior() + return nil + case chargeflatfee.FieldAnnotations: + m.ClearAnnotations() + return nil + case chargeflatfee.FieldMetadata: + m.ClearMetadata() + return nil + case chargeflatfee.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case chargeflatfee.FieldDescription: + m.ClearDescription() + return nil + case chargeflatfee.FieldIntentDeletedAt: + m.ClearIntentDeletedAt() + return nil + case chargeflatfee.FieldDiscounts: + m.ClearDiscounts() + return nil + case chargeflatfee.FieldFeatureKey: + m.ClearFeatureKey() + return nil + case chargeflatfee.FieldFeatureID: + m.ClearFeatureID() + return nil + case chargeflatfee.FieldCurrentRealizationRunID: + m.ClearCurrentRealizationRunID() + return nil + } + return fmt.Errorf("unknown ChargeFlatFee 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 *ChargeFlatFeeMutation) ResetField(name string) error { + switch name { + case chargeflatfee.FieldCustomerID: + m.ResetCustomerID() + return nil + case chargeflatfee.FieldServicePeriodFrom: + m.ResetServicePeriodFrom() + return nil + case chargeflatfee.FieldServicePeriodTo: + m.ResetServicePeriodTo() + return nil + case chargeflatfee.FieldBillingPeriodFrom: + m.ResetBillingPeriodFrom() + return nil + case chargeflatfee.FieldBillingPeriodTo: + m.ResetBillingPeriodTo() + return nil + case chargeflatfee.FieldFullServicePeriodFrom: + m.ResetFullServicePeriodFrom() + return nil + case chargeflatfee.FieldFullServicePeriodTo: + m.ResetFullServicePeriodTo() + return nil + case chargeflatfee.FieldStatus: + m.ResetStatus() + return nil + case chargeflatfee.FieldUniqueReferenceID: + m.ResetUniqueReferenceID() + return nil + case chargeflatfee.FieldCurrency: + m.ResetCurrency() + return nil + case chargeflatfee.FieldManagedBy: + m.ResetManagedBy() + return nil + case chargeflatfee.FieldSubscriptionID: + m.ResetSubscriptionID() + return nil + case chargeflatfee.FieldSubscriptionPhaseID: + m.ResetSubscriptionPhaseID() + return nil + case chargeflatfee.FieldSubscriptionItemID: + m.ResetSubscriptionItemID() + return nil + case chargeflatfee.FieldAdvanceAfter: + m.ResetAdvanceAfter() + return nil + case chargeflatfee.FieldTaxCodeID: + m.ResetTaxCodeID() + return nil + case chargeflatfee.FieldTaxBehavior: + m.ResetTaxBehavior() + return nil + case chargeflatfee.FieldAnnotations: + m.ResetAnnotations() + return nil + case chargeflatfee.FieldNamespace: + m.ResetNamespace() + return nil + case chargeflatfee.FieldMetadata: + m.ResetMetadata() + return nil + case chargeflatfee.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case chargeflatfee.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case chargeflatfee.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case chargeflatfee.FieldName: + m.ResetName() + return nil + case chargeflatfee.FieldDescription: + m.ResetDescription() + return nil + case chargeflatfee.FieldPaymentTerm: + m.ResetPaymentTerm() + return nil + case chargeflatfee.FieldInvoiceAt: + m.ResetInvoiceAt() + return nil + case chargeflatfee.FieldSettlementMode: + m.ResetSettlementMode() + return nil + case chargeflatfee.FieldIntentDeletedAt: + m.ResetIntentDeletedAt() + return nil + case chargeflatfee.FieldDiscounts: + m.ResetDiscounts() + return nil + case chargeflatfee.FieldProRating: + m.ResetProRating() + return nil + case chargeflatfee.FieldFeatureKey: + m.ResetFeatureKey() + return nil + case chargeflatfee.FieldFeatureID: + m.ResetFeatureID() + return nil + case chargeflatfee.FieldAmountBeforeProration: + m.ResetAmountBeforeProration() + return nil + case chargeflatfee.FieldAmountAfterProration: + m.ResetAmountAfterProration() + return nil + case chargeflatfee.FieldCurrentRealizationRunID: + m.ResetCurrentRealizationRunID() + return nil + case chargeflatfee.FieldStatusDetailed: + m.ResetStatusDetailed() + return nil + } + return fmt.Errorf("unknown ChargeFlatFee field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ChargeFlatFeeMutation) AddedEdges() []string { + edges := make([]string, 0, 10) + if m.runs != nil { + edges = append(edges, chargeflatfee.EdgeRuns) + } + if m.current_run != nil { + edges = append(edges, chargeflatfee.EdgeCurrentRun) + } + if m.charge != nil { + edges = append(edges, chargeflatfee.EdgeCharge) + } + if m.intent_override != nil { + edges = append(edges, chargeflatfee.EdgeIntentOverride) + } + if m.subscription != nil { + edges = append(edges, chargeflatfee.EdgeSubscription) + } + if m.subscription_phase != nil { + edges = append(edges, chargeflatfee.EdgeSubscriptionPhase) + } + if m.subscription_item != nil { + edges = append(edges, chargeflatfee.EdgeSubscriptionItem) + } + if m.customer != nil { + edges = append(edges, chargeflatfee.EdgeCustomer) + } + if m.feature != nil { + edges = append(edges, chargeflatfee.EdgeFeature) + } + if m.tax_code != nil { + edges = append(edges, chargeflatfee.EdgeTaxCode) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ChargeFlatFeeMutation) AddedIDs(name string) []ent.Value { + switch name { + case chargeflatfee.EdgeRuns: + ids := make([]ent.Value, 0, len(m.runs)) + for id := range m.runs { + ids = append(ids, id) + } + return ids + case chargeflatfee.EdgeCurrentRun: + if id := m.current_run; id != nil { + return []ent.Value{*id} + } + case chargeflatfee.EdgeCharge: + if id := m.charge; id != nil { + return []ent.Value{*id} + } + case chargeflatfee.EdgeIntentOverride: + if id := m.intent_override; id != nil { + return []ent.Value{*id} + } + case chargeflatfee.EdgeSubscription: + if id := m.subscription; id != nil { + return []ent.Value{*id} + } + case chargeflatfee.EdgeSubscriptionPhase: + if id := m.subscription_phase; id != nil { + return []ent.Value{*id} + } + case chargeflatfee.EdgeSubscriptionItem: + if id := m.subscription_item; id != nil { + return []ent.Value{*id} + } + case chargeflatfee.EdgeCustomer: + if id := m.customer; id != nil { + return []ent.Value{*id} + } + case chargeflatfee.EdgeFeature: + if id := m.feature; id != nil { + return []ent.Value{*id} + } + case chargeflatfee.EdgeTaxCode: + if id := m.tax_code; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ChargeFlatFeeMutation) RemovedEdges() []string { + edges := make([]string, 0, 10) + if m.removedruns != nil { + edges = append(edges, chargeflatfee.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 *ChargeFlatFeeMutation) RemovedIDs(name string) []ent.Value { + switch name { + case chargeflatfee.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 *ChargeFlatFeeMutation) ClearedEdges() []string { + edges := make([]string, 0, 10) + if m.clearedruns { + edges = append(edges, chargeflatfee.EdgeRuns) + } + if m.clearedcurrent_run { + edges = append(edges, chargeflatfee.EdgeCurrentRun) + } + if m.clearedcharge { + edges = append(edges, chargeflatfee.EdgeCharge) + } + if m.clearedintent_override { + edges = append(edges, chargeflatfee.EdgeIntentOverride) + } + if m.clearedsubscription { + edges = append(edges, chargeflatfee.EdgeSubscription) + } + if m.clearedsubscription_phase { + edges = append(edges, chargeflatfee.EdgeSubscriptionPhase) + } + if m.clearedsubscription_item { + edges = append(edges, chargeflatfee.EdgeSubscriptionItem) + } + if m.clearedcustomer { + edges = append(edges, chargeflatfee.EdgeCustomer) + } + if m.clearedfeature { + edges = append(edges, chargeflatfee.EdgeFeature) + } + if m.clearedtax_code { + edges = append(edges, chargeflatfee.EdgeTaxCode) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ChargeFlatFeeMutation) EdgeCleared(name string) bool { + switch name { + case chargeflatfee.EdgeRuns: + return m.clearedruns + case chargeflatfee.EdgeCurrentRun: + return m.clearedcurrent_run + case chargeflatfee.EdgeCharge: + return m.clearedcharge + case chargeflatfee.EdgeIntentOverride: + return m.clearedintent_override + case chargeflatfee.EdgeSubscription: + return m.clearedsubscription + case chargeflatfee.EdgeSubscriptionPhase: + return m.clearedsubscription_phase + case chargeflatfee.EdgeSubscriptionItem: + return m.clearedsubscription_item + case chargeflatfee.EdgeCustomer: + return m.clearedcustomer + case chargeflatfee.EdgeFeature: + return m.clearedfeature + case chargeflatfee.EdgeTaxCode: + return m.clearedtax_code + } + 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 *ChargeFlatFeeMutation) ClearEdge(name string) error { + switch name { + case chargeflatfee.EdgeCurrentRun: + m.ClearCurrentRun() + return nil + case chargeflatfee.EdgeCharge: + m.ClearCharge() + return nil + case chargeflatfee.EdgeIntentOverride: + m.ClearIntentOverride() + return nil + case chargeflatfee.EdgeSubscription: + m.ClearSubscription() + return nil + case chargeflatfee.EdgeSubscriptionPhase: + m.ClearSubscriptionPhase() + return nil + case chargeflatfee.EdgeSubscriptionItem: + m.ClearSubscriptionItem() + return nil + case chargeflatfee.EdgeCustomer: + m.ClearCustomer() + return nil + case chargeflatfee.EdgeFeature: + m.ClearFeature() + return nil + case chargeflatfee.EdgeTaxCode: + m.ClearTaxCode() + return nil + } + return fmt.Errorf("unknown ChargeFlatFee 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 *ChargeFlatFeeMutation) ResetEdge(name string) error { + switch name { + case chargeflatfee.EdgeRuns: + m.ResetRuns() + return nil + case chargeflatfee.EdgeCurrentRun: + m.ResetCurrentRun() + return nil + case chargeflatfee.EdgeCharge: + m.ResetCharge() + return nil + case chargeflatfee.EdgeIntentOverride: + m.ResetIntentOverride() + return nil + case chargeflatfee.EdgeSubscription: + m.ResetSubscription() + return nil + case chargeflatfee.EdgeSubscriptionPhase: + m.ResetSubscriptionPhase() + return nil + case chargeflatfee.EdgeSubscriptionItem: + m.ResetSubscriptionItem() + return nil + case chargeflatfee.EdgeCustomer: + m.ResetCustomer() + return nil + case chargeflatfee.EdgeFeature: + m.ResetFeature() + return nil + case chargeflatfee.EdgeTaxCode: + m.ResetTaxCode() + return nil + } + return fmt.Errorf("unknown ChargeFlatFee edge %s", name) +} + +// ChargeFlatFeeOverrideMutation represents an operation that mutates the ChargeFlatFeeOverride nodes in the graph. +type ChargeFlatFeeOverrideMutation struct { + config + op Op + typ string + id *string + namespace *string + name *string + description *string + metadata **models.Metadata + tax_behavior *productcatalog.TaxBehavior + intent_deleted_at *time.Time + service_period_from *time.Time + service_period_to *time.Time + full_service_period_from *time.Time + full_service_period_to *time.Time + billing_period_from *time.Time + billing_period_to *time.Time + invoice_at *time.Time + feature_key *string + payment_term *productcatalog.PaymentTermType + pro_rating **productcatalog.ProRatingConfig + amount_before_proration *alpacadecimal.Decimal + discounts **billing.Discounts + percentage_discounts **billing.PercentageDiscount + clearedFields map[string]struct{} + flat_fee *string + clearedflat_fee bool + tax_code *string + clearedtax_code bool + done bool + oldValue func(context.Context) (*ChargeFlatFeeOverride, error) + predicates []predicate.ChargeFlatFeeOverride +} + +var _ ent.Mutation = (*ChargeFlatFeeOverrideMutation)(nil) + +// chargeflatfeeoverrideOption allows management of the mutation configuration using functional options. +type chargeflatfeeoverrideOption func(*ChargeFlatFeeOverrideMutation) + +// newChargeFlatFeeOverrideMutation creates new mutation for the ChargeFlatFeeOverride entity. +func newChargeFlatFeeOverrideMutation(c config, op Op, opts ...chargeflatfeeoverrideOption) *ChargeFlatFeeOverrideMutation { + m := &ChargeFlatFeeOverrideMutation{ + config: c, + op: op, + typ: TypeChargeFlatFeeOverride, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withChargeFlatFeeOverrideID sets the ID field of the mutation. +func withChargeFlatFeeOverrideID(id string) chargeflatfeeoverrideOption { + return func(m *ChargeFlatFeeOverrideMutation) { + var ( + err error + once sync.Once + value *ChargeFlatFeeOverride + ) + m.oldValue = func(ctx context.Context) (*ChargeFlatFeeOverride, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ChargeFlatFeeOverride.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withChargeFlatFeeOverride sets the old ChargeFlatFeeOverride of the mutation. +func withChargeFlatFeeOverride(node *ChargeFlatFeeOverride) chargeflatfeeoverrideOption { + return func(m *ChargeFlatFeeOverrideMutation) { + m.oldValue = func(context.Context) (*ChargeFlatFeeOverride, 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 ChargeFlatFeeOverrideMutation) 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 ChargeFlatFeeOverrideMutation) 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 ChargeFlatFeeOverride entities. +func (m *ChargeFlatFeeOverrideMutation) 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 *ChargeFlatFeeOverrideMutation) 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 *ChargeFlatFeeOverrideMutation) 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().ChargeFlatFeeOverride.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 *ChargeFlatFeeOverrideMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) 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 ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) 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 *ChargeFlatFeeOverrideMutation) ResetNamespace() { + m.namespace = nil +} + +// SetChargeID sets the "charge_id" field. +func (m *ChargeFlatFeeOverrideMutation) SetChargeID(s string) { + m.flat_fee = &s +} + +// ChargeID returns the value of the "charge_id" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) ChargeID() (r string, exists bool) { + v := m.flat_fee + if v == nil { + return + } + return *v, true +} + +// OldChargeID returns the old "charge_id" field's value of the ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) 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 *ChargeFlatFeeOverrideMutation) ResetChargeID() { + m.flat_fee = nil +} + +// SetName sets the "name" field. +func (m *ChargeFlatFeeOverrideMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *ChargeFlatFeeOverrideMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *ChargeFlatFeeOverrideMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *ChargeFlatFeeOverrideMutation) ClearDescription() { + m.description = nil + m.clearedFields[chargeflatfeeoverride.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *ChargeFlatFeeOverrideMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[chargeflatfeeoverride.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *ChargeFlatFeeOverrideMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, chargeflatfeeoverride.FieldDescription) +} + +// SetMetadata sets the "metadata" field. +func (m *ChargeFlatFeeOverrideMutation) SetMetadata(value *models.Metadata) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) Metadata() (r *models.Metadata, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) OldMetadata(ctx context.Context) (v *models.Metadata, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *ChargeFlatFeeOverrideMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[chargeflatfeeoverride.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *ChargeFlatFeeOverrideMutation) MetadataCleared() bool { + _, ok := m.clearedFields[chargeflatfeeoverride.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *ChargeFlatFeeOverrideMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, chargeflatfeeoverride.FieldMetadata) +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (m *ChargeFlatFeeOverrideMutation) SetTaxBehavior(pb productcatalog.TaxBehavior) { + m.tax_behavior = &pb +} + +// TaxBehavior returns the value of the "tax_behavior" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) TaxBehavior() (r productcatalog.TaxBehavior, exists bool) { + v := m.tax_behavior + if v == nil { + return + } + return *v, true +} + +// OldTaxBehavior returns the old "tax_behavior" field's value of the ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) OldTaxBehavior(ctx context.Context) (v *productcatalog.TaxBehavior, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxBehavior is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxBehavior requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxBehavior: %w", err) + } + return oldValue.TaxBehavior, nil +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (m *ChargeFlatFeeOverrideMutation) ClearTaxBehavior() { + m.tax_behavior = nil + m.clearedFields[chargeflatfeeoverride.FieldTaxBehavior] = struct{}{} +} + +// TaxBehaviorCleared returns if the "tax_behavior" field was cleared in this mutation. +func (m *ChargeFlatFeeOverrideMutation) TaxBehaviorCleared() bool { + _, ok := m.clearedFields[chargeflatfeeoverride.FieldTaxBehavior] + return ok +} + +// ResetTaxBehavior resets all changes to the "tax_behavior" field. +func (m *ChargeFlatFeeOverrideMutation) ResetTaxBehavior() { + m.tax_behavior = nil + delete(m.clearedFields, chargeflatfeeoverride.FieldTaxBehavior) +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (m *ChargeFlatFeeOverrideMutation) SetTaxCodeID(s string) { + m.tax_code = &s +} + +// TaxCodeID returns the value of the "tax_code_id" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) TaxCodeID() (r string, exists bool) { + v := m.tax_code + if v == nil { + return + } + return *v, true +} + +// OldTaxCodeID returns the old "tax_code_id" field's value of the ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) OldTaxCodeID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxCodeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxCodeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxCodeID: %w", err) + } + return oldValue.TaxCodeID, nil +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (m *ChargeFlatFeeOverrideMutation) ClearTaxCodeID() { + m.tax_code = nil + m.clearedFields[chargeflatfeeoverride.FieldTaxCodeID] = struct{}{} +} + +// TaxCodeIDCleared returns if the "tax_code_id" field was cleared in this mutation. +func (m *ChargeFlatFeeOverrideMutation) TaxCodeIDCleared() bool { + _, ok := m.clearedFields[chargeflatfeeoverride.FieldTaxCodeID] + return ok +} + +// ResetTaxCodeID resets all changes to the "tax_code_id" field. +func (m *ChargeFlatFeeOverrideMutation) ResetTaxCodeID() { + m.tax_code = nil + delete(m.clearedFields, chargeflatfeeoverride.FieldTaxCodeID) +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (m *ChargeFlatFeeOverrideMutation) SetIntentDeletedAt(t time.Time) { + m.intent_deleted_at = &t +} + +// IntentDeletedAt returns the value of the "intent_deleted_at" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) IntentDeletedAt() (r time.Time, exists bool) { + v := m.intent_deleted_at + if v == nil { + return + } + return *v, true +} + +// OldIntentDeletedAt returns the old "intent_deleted_at" field's value of the ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) OldIntentDeletedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIntentDeletedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIntentDeletedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIntentDeletedAt: %w", err) + } + return oldValue.IntentDeletedAt, nil +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (m *ChargeFlatFeeOverrideMutation) ClearIntentDeletedAt() { + m.intent_deleted_at = nil + m.clearedFields[chargeflatfeeoverride.FieldIntentDeletedAt] = struct{}{} +} + +// IntentDeletedAtCleared returns if the "intent_deleted_at" field was cleared in this mutation. +func (m *ChargeFlatFeeOverrideMutation) IntentDeletedAtCleared() bool { + _, ok := m.clearedFields[chargeflatfeeoverride.FieldIntentDeletedAt] + return ok +} + +// ResetIntentDeletedAt resets all changes to the "intent_deleted_at" field. +func (m *ChargeFlatFeeOverrideMutation) ResetIntentDeletedAt() { + m.intent_deleted_at = nil + delete(m.clearedFields, chargeflatfeeoverride.FieldIntentDeletedAt) +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (m *ChargeFlatFeeOverrideMutation) SetServicePeriodFrom(t time.Time) { + m.service_period_from = &t +} + +// ServicePeriodFrom returns the value of the "service_period_from" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) 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 ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) 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 *ChargeFlatFeeOverrideMutation) ResetServicePeriodFrom() { + m.service_period_from = nil +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (m *ChargeFlatFeeOverrideMutation) SetServicePeriodTo(t time.Time) { + m.service_period_to = &t +} + +// ServicePeriodTo returns the value of the "service_period_to" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) 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 ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) 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 *ChargeFlatFeeOverrideMutation) ResetServicePeriodTo() { + m.service_period_to = nil +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (m *ChargeFlatFeeOverrideMutation) SetFullServicePeriodFrom(t time.Time) { + m.full_service_period_from = &t +} + +// FullServicePeriodFrom returns the value of the "full_service_period_from" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) FullServicePeriodFrom() (r time.Time, exists bool) { + v := m.full_service_period_from + if v == nil { + return + } + return *v, true +} + +// OldFullServicePeriodFrom returns the old "full_service_period_from" field's value of the ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) OldFullServicePeriodFrom(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFullServicePeriodFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFullServicePeriodFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFullServicePeriodFrom: %w", err) + } + return oldValue.FullServicePeriodFrom, nil +} + +// ResetFullServicePeriodFrom resets all changes to the "full_service_period_from" field. +func (m *ChargeFlatFeeOverrideMutation) ResetFullServicePeriodFrom() { + m.full_service_period_from = nil +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (m *ChargeFlatFeeOverrideMutation) SetFullServicePeriodTo(t time.Time) { + m.full_service_period_to = &t +} + +// FullServicePeriodTo returns the value of the "full_service_period_to" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) FullServicePeriodTo() (r time.Time, exists bool) { + v := m.full_service_period_to + if v == nil { + return + } + return *v, true +} + +// OldFullServicePeriodTo returns the old "full_service_period_to" field's value of the ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) OldFullServicePeriodTo(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFullServicePeriodTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFullServicePeriodTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFullServicePeriodTo: %w", err) + } + return oldValue.FullServicePeriodTo, nil +} + +// ResetFullServicePeriodTo resets all changes to the "full_service_period_to" field. +func (m *ChargeFlatFeeOverrideMutation) ResetFullServicePeriodTo() { + m.full_service_period_to = nil +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (m *ChargeFlatFeeOverrideMutation) SetBillingPeriodFrom(t time.Time) { + m.billing_period_from = &t +} + +// BillingPeriodFrom returns the value of the "billing_period_from" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) BillingPeriodFrom() (r time.Time, exists bool) { + v := m.billing_period_from + if v == nil { + return + } + return *v, true +} + +// OldBillingPeriodFrom returns the old "billing_period_from" field's value of the ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) OldBillingPeriodFrom(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingPeriodFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingPeriodFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingPeriodFrom: %w", err) + } + return oldValue.BillingPeriodFrom, nil +} + +// ResetBillingPeriodFrom resets all changes to the "billing_period_from" field. +func (m *ChargeFlatFeeOverrideMutation) ResetBillingPeriodFrom() { + m.billing_period_from = nil +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (m *ChargeFlatFeeOverrideMutation) SetBillingPeriodTo(t time.Time) { + m.billing_period_to = &t +} + +// BillingPeriodTo returns the value of the "billing_period_to" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) BillingPeriodTo() (r time.Time, exists bool) { + v := m.billing_period_to + if v == nil { + return + } + return *v, true +} + +// OldBillingPeriodTo returns the old "billing_period_to" field's value of the ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) OldBillingPeriodTo(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingPeriodTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingPeriodTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingPeriodTo: %w", err) + } + return oldValue.BillingPeriodTo, nil +} + +// ResetBillingPeriodTo resets all changes to the "billing_period_to" field. +func (m *ChargeFlatFeeOverrideMutation) ResetBillingPeriodTo() { + m.billing_period_to = nil +} + +// SetInvoiceAt sets the "invoice_at" field. +func (m *ChargeFlatFeeOverrideMutation) SetInvoiceAt(t time.Time) { + m.invoice_at = &t +} + +// InvoiceAt returns the value of the "invoice_at" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) 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 ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) 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 *ChargeFlatFeeOverrideMutation) ResetInvoiceAt() { + m.invoice_at = nil +} + +// SetFeatureKey sets the "feature_key" field. +func (m *ChargeFlatFeeOverrideMutation) SetFeatureKey(s string) { + m.feature_key = &s +} + +// FeatureKey returns the value of the "feature_key" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) 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 ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) 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 +} + +// ClearFeatureKey clears the value of the "feature_key" field. +func (m *ChargeFlatFeeOverrideMutation) ClearFeatureKey() { + m.feature_key = nil + m.clearedFields[chargeflatfeeoverride.FieldFeatureKey] = struct{}{} +} + +// FeatureKeyCleared returns if the "feature_key" field was cleared in this mutation. +func (m *ChargeFlatFeeOverrideMutation) FeatureKeyCleared() bool { + _, ok := m.clearedFields[chargeflatfeeoverride.FieldFeatureKey] + return ok +} + +// ResetFeatureKey resets all changes to the "feature_key" field. +func (m *ChargeFlatFeeOverrideMutation) ResetFeatureKey() { + m.feature_key = nil + delete(m.clearedFields, chargeflatfeeoverride.FieldFeatureKey) +} + +// SetPaymentTerm sets the "payment_term" field. +func (m *ChargeFlatFeeOverrideMutation) SetPaymentTerm(ptt productcatalog.PaymentTermType) { + m.payment_term = &ptt +} + +// PaymentTerm returns the value of the "payment_term" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) PaymentTerm() (r productcatalog.PaymentTermType, exists bool) { + v := m.payment_term + if v == nil { + return + } + return *v, true +} + +// OldPaymentTerm returns the old "payment_term" field's value of the ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) OldPaymentTerm(ctx context.Context) (v productcatalog.PaymentTermType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPaymentTerm is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPaymentTerm requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPaymentTerm: %w", err) + } + return oldValue.PaymentTerm, nil +} + +// ResetPaymentTerm resets all changes to the "payment_term" field. +func (m *ChargeFlatFeeOverrideMutation) ResetPaymentTerm() { + m.payment_term = nil +} + +// SetProRating sets the "pro_rating" field. +func (m *ChargeFlatFeeOverrideMutation) SetProRating(prc *productcatalog.ProRatingConfig) { + m.pro_rating = &prc +} + +// ProRating returns the value of the "pro_rating" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) ProRating() (r *productcatalog.ProRatingConfig, exists bool) { + v := m.pro_rating + if v == nil { + return + } + return *v, true +} + +// OldProRating returns the old "pro_rating" field's value of the ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) OldProRating(ctx context.Context) (v *productcatalog.ProRatingConfig, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldProRating is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldProRating requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldProRating: %w", err) + } + return oldValue.ProRating, nil +} + +// ResetProRating resets all changes to the "pro_rating" field. +func (m *ChargeFlatFeeOverrideMutation) ResetProRating() { + m.pro_rating = nil +} + +// SetAmountBeforeProration sets the "amount_before_proration" field. +func (m *ChargeFlatFeeOverrideMutation) SetAmountBeforeProration(a alpacadecimal.Decimal) { + m.amount_before_proration = &a +} + +// AmountBeforeProration returns the value of the "amount_before_proration" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) AmountBeforeProration() (r alpacadecimal.Decimal, exists bool) { + v := m.amount_before_proration + if v == nil { + return + } + return *v, true +} + +// OldAmountBeforeProration returns the old "amount_before_proration" field's value of the ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) OldAmountBeforeProration(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAmountBeforeProration is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAmountBeforeProration requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAmountBeforeProration: %w", err) + } + return oldValue.AmountBeforeProration, nil +} + +// ResetAmountBeforeProration resets all changes to the "amount_before_proration" field. +func (m *ChargeFlatFeeOverrideMutation) ResetAmountBeforeProration() { + m.amount_before_proration = nil +} + +// SetDiscounts sets the "discounts" field. +func (m *ChargeFlatFeeOverrideMutation) SetDiscounts(b *billing.Discounts) { + m.discounts = &b +} + +// Discounts returns the value of the "discounts" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) Discounts() (r *billing.Discounts, exists bool) { + v := m.discounts + if v == nil { + return + } + return *v, true +} + +// OldDiscounts returns the old "discounts" field's value of the ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) OldDiscounts(ctx context.Context) (v *billing.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 *ChargeFlatFeeOverrideMutation) ClearDiscounts() { + m.discounts = nil + m.clearedFields[chargeflatfeeoverride.FieldDiscounts] = struct{}{} +} + +// DiscountsCleared returns if the "discounts" field was cleared in this mutation. +func (m *ChargeFlatFeeOverrideMutation) DiscountsCleared() bool { + _, ok := m.clearedFields[chargeflatfeeoverride.FieldDiscounts] + return ok +} + +// ResetDiscounts resets all changes to the "discounts" field. +func (m *ChargeFlatFeeOverrideMutation) ResetDiscounts() { + m.discounts = nil + delete(m.clearedFields, chargeflatfeeoverride.FieldDiscounts) +} + +// SetPercentageDiscounts sets the "percentage_discounts" field. +func (m *ChargeFlatFeeOverrideMutation) SetPercentageDiscounts(bd *billing.PercentageDiscount) { + m.percentage_discounts = &bd +} + +// PercentageDiscounts returns the value of the "percentage_discounts" field in the mutation. +func (m *ChargeFlatFeeOverrideMutation) PercentageDiscounts() (r *billing.PercentageDiscount, exists bool) { + v := m.percentage_discounts + if v == nil { + return + } + return *v, true +} + +// OldPercentageDiscounts returns the old "percentage_discounts" field's value of the ChargeFlatFeeOverride entity. +// If the ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) OldPercentageDiscounts(ctx context.Context) (v *billing.PercentageDiscount, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPercentageDiscounts is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPercentageDiscounts requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPercentageDiscounts: %w", err) + } + return oldValue.PercentageDiscounts, nil +} + +// ClearPercentageDiscounts clears the value of the "percentage_discounts" field. +func (m *ChargeFlatFeeOverrideMutation) ClearPercentageDiscounts() { + m.percentage_discounts = nil + m.clearedFields[chargeflatfeeoverride.FieldPercentageDiscounts] = struct{}{} +} + +// PercentageDiscountsCleared returns if the "percentage_discounts" field was cleared in this mutation. +func (m *ChargeFlatFeeOverrideMutation) PercentageDiscountsCleared() bool { + _, ok := m.clearedFields[chargeflatfeeoverride.FieldPercentageDiscounts] + return ok +} + +// ResetPercentageDiscounts resets all changes to the "percentage_discounts" field. +func (m *ChargeFlatFeeOverrideMutation) ResetPercentageDiscounts() { + m.percentage_discounts = nil + delete(m.clearedFields, chargeflatfeeoverride.FieldPercentageDiscounts) +} + +// SetFlatFeeID sets the "flat_fee" edge to the ChargeFlatFee entity by id. +func (m *ChargeFlatFeeOverrideMutation) SetFlatFeeID(id string) { + m.flat_fee = &id +} + +// ClearFlatFee clears the "flat_fee" edge to the ChargeFlatFee entity. +func (m *ChargeFlatFeeOverrideMutation) ClearFlatFee() { + m.clearedflat_fee = true + m.clearedFields[chargeflatfeeoverride.FieldChargeID] = struct{}{} +} + +// FlatFeeCleared reports if the "flat_fee" edge to the ChargeFlatFee entity was cleared. +func (m *ChargeFlatFeeOverrideMutation) FlatFeeCleared() bool { + return m.clearedflat_fee +} + +// FlatFeeID returns the "flat_fee" edge ID in the mutation. +func (m *ChargeFlatFeeOverrideMutation) FlatFeeID() (id string, exists bool) { + if m.flat_fee != nil { + return *m.flat_fee, true + } + return +} + +// FlatFeeIDs returns the "flat_fee" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// FlatFeeID instead. It exists only for internal usage by the builders. +func (m *ChargeFlatFeeOverrideMutation) FlatFeeIDs() (ids []string) { + if id := m.flat_fee; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetFlatFee resets all changes to the "flat_fee" edge. +func (m *ChargeFlatFeeOverrideMutation) ResetFlatFee() { + m.flat_fee = nil + m.clearedflat_fee = false +} + +// ClearTaxCode clears the "tax_code" edge to the TaxCode entity. +func (m *ChargeFlatFeeOverrideMutation) ClearTaxCode() { + m.clearedtax_code = true + m.clearedFields[chargeflatfeeoverride.FieldTaxCodeID] = struct{}{} +} + +// TaxCodeCleared reports if the "tax_code" edge to the TaxCode entity was cleared. +func (m *ChargeFlatFeeOverrideMutation) TaxCodeCleared() bool { + return m.TaxCodeIDCleared() || m.clearedtax_code +} + +// TaxCodeIDs returns the "tax_code" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TaxCodeID instead. It exists only for internal usage by the builders. +func (m *ChargeFlatFeeOverrideMutation) TaxCodeIDs() (ids []string) { + if id := m.tax_code; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTaxCode resets all changes to the "tax_code" edge. +func (m *ChargeFlatFeeOverrideMutation) ResetTaxCode() { + m.tax_code = nil + m.clearedtax_code = false +} + +// Where appends a list predicates to the ChargeFlatFeeOverrideMutation builder. +func (m *ChargeFlatFeeOverrideMutation) Where(ps ...predicate.ChargeFlatFeeOverride) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ChargeFlatFeeOverrideMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ChargeFlatFeeOverrideMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ChargeFlatFeeOverride, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ChargeFlatFeeOverrideMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ChargeFlatFeeOverrideMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ChargeFlatFeeOverride). +func (m *ChargeFlatFeeOverrideMutation) 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 *ChargeFlatFeeOverrideMutation) Fields() []string { + fields := make([]string, 0, 21) + if m.namespace != nil { + fields = append(fields, chargeflatfeeoverride.FieldNamespace) + } + if m.flat_fee != nil { + fields = append(fields, chargeflatfeeoverride.FieldChargeID) + } + if m.name != nil { + fields = append(fields, chargeflatfeeoverride.FieldName) + } + if m.description != nil { + fields = append(fields, chargeflatfeeoverride.FieldDescription) + } + if m.metadata != nil { + fields = append(fields, chargeflatfeeoverride.FieldMetadata) + } + if m.tax_behavior != nil { + fields = append(fields, chargeflatfeeoverride.FieldTaxBehavior) + } + if m.tax_code != nil { + fields = append(fields, chargeflatfeeoverride.FieldTaxCodeID) + } + if m.intent_deleted_at != nil { + fields = append(fields, chargeflatfeeoverride.FieldIntentDeletedAt) + } + if m.service_period_from != nil { + fields = append(fields, chargeflatfeeoverride.FieldServicePeriodFrom) + } + if m.service_period_to != nil { + fields = append(fields, chargeflatfeeoverride.FieldServicePeriodTo) + } + if m.full_service_period_from != nil { + fields = append(fields, chargeflatfeeoverride.FieldFullServicePeriodFrom) + } + if m.full_service_period_to != nil { + fields = append(fields, chargeflatfeeoverride.FieldFullServicePeriodTo) + } + if m.billing_period_from != nil { + fields = append(fields, chargeflatfeeoverride.FieldBillingPeriodFrom) + } + if m.billing_period_to != nil { + fields = append(fields, chargeflatfeeoverride.FieldBillingPeriodTo) + } + if m.invoice_at != nil { + fields = append(fields, chargeflatfeeoverride.FieldInvoiceAt) + } + if m.feature_key != nil { + fields = append(fields, chargeflatfeeoverride.FieldFeatureKey) + } + if m.payment_term != nil { + fields = append(fields, chargeflatfeeoverride.FieldPaymentTerm) + } + if m.pro_rating != nil { + fields = append(fields, chargeflatfeeoverride.FieldProRating) + } + if m.amount_before_proration != nil { + fields = append(fields, chargeflatfeeoverride.FieldAmountBeforeProration) + } + if m.discounts != nil { + fields = append(fields, chargeflatfeeoverride.FieldDiscounts) + } + if m.percentage_discounts != nil { + fields = append(fields, chargeflatfeeoverride.FieldPercentageDiscounts) + } + 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 *ChargeFlatFeeOverrideMutation) Field(name string) (ent.Value, bool) { + switch name { + case chargeflatfeeoverride.FieldNamespace: + return m.Namespace() + case chargeflatfeeoverride.FieldChargeID: + return m.ChargeID() + case chargeflatfeeoverride.FieldName: + return m.Name() + case chargeflatfeeoverride.FieldDescription: + return m.Description() + case chargeflatfeeoverride.FieldMetadata: + return m.Metadata() + case chargeflatfeeoverride.FieldTaxBehavior: + return m.TaxBehavior() + case chargeflatfeeoverride.FieldTaxCodeID: + return m.TaxCodeID() + case chargeflatfeeoverride.FieldIntentDeletedAt: + return m.IntentDeletedAt() + case chargeflatfeeoverride.FieldServicePeriodFrom: + return m.ServicePeriodFrom() + case chargeflatfeeoverride.FieldServicePeriodTo: + return m.ServicePeriodTo() + case chargeflatfeeoverride.FieldFullServicePeriodFrom: + return m.FullServicePeriodFrom() + case chargeflatfeeoverride.FieldFullServicePeriodTo: + return m.FullServicePeriodTo() + case chargeflatfeeoverride.FieldBillingPeriodFrom: + return m.BillingPeriodFrom() + case chargeflatfeeoverride.FieldBillingPeriodTo: + return m.BillingPeriodTo() + case chargeflatfeeoverride.FieldInvoiceAt: + return m.InvoiceAt() + case chargeflatfeeoverride.FieldFeatureKey: + return m.FeatureKey() + case chargeflatfeeoverride.FieldPaymentTerm: + return m.PaymentTerm() + case chargeflatfeeoverride.FieldProRating: + return m.ProRating() + case chargeflatfeeoverride.FieldAmountBeforeProration: + return m.AmountBeforeProration() + case chargeflatfeeoverride.FieldDiscounts: + return m.Discounts() + case chargeflatfeeoverride.FieldPercentageDiscounts: + return m.PercentageDiscounts() + } + 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 *ChargeFlatFeeOverrideMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case chargeflatfeeoverride.FieldNamespace: + return m.OldNamespace(ctx) + case chargeflatfeeoverride.FieldChargeID: + return m.OldChargeID(ctx) + case chargeflatfeeoverride.FieldName: + return m.OldName(ctx) + case chargeflatfeeoverride.FieldDescription: + return m.OldDescription(ctx) + case chargeflatfeeoverride.FieldMetadata: + return m.OldMetadata(ctx) + case chargeflatfeeoverride.FieldTaxBehavior: + return m.OldTaxBehavior(ctx) + case chargeflatfeeoverride.FieldTaxCodeID: + return m.OldTaxCodeID(ctx) + case chargeflatfeeoverride.FieldIntentDeletedAt: + return m.OldIntentDeletedAt(ctx) + case chargeflatfeeoverride.FieldServicePeriodFrom: + return m.OldServicePeriodFrom(ctx) + case chargeflatfeeoverride.FieldServicePeriodTo: + return m.OldServicePeriodTo(ctx) + case chargeflatfeeoverride.FieldFullServicePeriodFrom: + return m.OldFullServicePeriodFrom(ctx) + case chargeflatfeeoverride.FieldFullServicePeriodTo: + return m.OldFullServicePeriodTo(ctx) + case chargeflatfeeoverride.FieldBillingPeriodFrom: + return m.OldBillingPeriodFrom(ctx) + case chargeflatfeeoverride.FieldBillingPeriodTo: + return m.OldBillingPeriodTo(ctx) + case chargeflatfeeoverride.FieldInvoiceAt: + return m.OldInvoiceAt(ctx) + case chargeflatfeeoverride.FieldFeatureKey: + return m.OldFeatureKey(ctx) + case chargeflatfeeoverride.FieldPaymentTerm: + return m.OldPaymentTerm(ctx) + case chargeflatfeeoverride.FieldProRating: + return m.OldProRating(ctx) + case chargeflatfeeoverride.FieldAmountBeforeProration: + return m.OldAmountBeforeProration(ctx) + case chargeflatfeeoverride.FieldDiscounts: + return m.OldDiscounts(ctx) + case chargeflatfeeoverride.FieldPercentageDiscounts: + return m.OldPercentageDiscounts(ctx) + } + return nil, fmt.Errorf("unknown ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) SetField(name string, value ent.Value) error { + switch name { + case chargeflatfeeoverride.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case chargeflatfeeoverride.FieldChargeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChargeID(v) + return nil + case chargeflatfeeoverride.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case chargeflatfeeoverride.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case chargeflatfeeoverride.FieldMetadata: + v, ok := value.(*models.Metadata) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case chargeflatfeeoverride.FieldTaxBehavior: + v, ok := value.(productcatalog.TaxBehavior) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxBehavior(v) + return nil + case chargeflatfeeoverride.FieldTaxCodeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxCodeID(v) + return nil + case chargeflatfeeoverride.FieldIntentDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIntentDeletedAt(v) + return nil + case chargeflatfeeoverride.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 chargeflatfeeoverride.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 chargeflatfeeoverride.FieldFullServicePeriodFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFullServicePeriodFrom(v) + return nil + case chargeflatfeeoverride.FieldFullServicePeriodTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFullServicePeriodTo(v) + return nil + case chargeflatfeeoverride.FieldBillingPeriodFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingPeriodFrom(v) + return nil + case chargeflatfeeoverride.FieldBillingPeriodTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingPeriodTo(v) + return nil + case chargeflatfeeoverride.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 chargeflatfeeoverride.FieldFeatureKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFeatureKey(v) + return nil + case chargeflatfeeoverride.FieldPaymentTerm: + v, ok := value.(productcatalog.PaymentTermType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPaymentTerm(v) + return nil + case chargeflatfeeoverride.FieldProRating: + v, ok := value.(*productcatalog.ProRatingConfig) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetProRating(v) + return nil + case chargeflatfeeoverride.FieldAmountBeforeProration: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAmountBeforeProration(v) + return nil + case chargeflatfeeoverride.FieldDiscounts: + v, ok := value.(*billing.Discounts) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDiscounts(v) + return nil + case chargeflatfeeoverride.FieldPercentageDiscounts: + v, ok := value.(*billing.PercentageDiscount) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPercentageDiscounts(v) + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeOverride field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ChargeFlatFeeOverrideMutation) 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 *ChargeFlatFeeOverrideMutation) 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 *ChargeFlatFeeOverrideMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown ChargeFlatFeeOverride numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ChargeFlatFeeOverrideMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(chargeflatfeeoverride.FieldDescription) { + fields = append(fields, chargeflatfeeoverride.FieldDescription) + } + if m.FieldCleared(chargeflatfeeoverride.FieldMetadata) { + fields = append(fields, chargeflatfeeoverride.FieldMetadata) + } + if m.FieldCleared(chargeflatfeeoverride.FieldTaxBehavior) { + fields = append(fields, chargeflatfeeoverride.FieldTaxBehavior) + } + if m.FieldCleared(chargeflatfeeoverride.FieldTaxCodeID) { + fields = append(fields, chargeflatfeeoverride.FieldTaxCodeID) + } + if m.FieldCleared(chargeflatfeeoverride.FieldIntentDeletedAt) { + fields = append(fields, chargeflatfeeoverride.FieldIntentDeletedAt) + } + if m.FieldCleared(chargeflatfeeoverride.FieldFeatureKey) { + fields = append(fields, chargeflatfeeoverride.FieldFeatureKey) + } + if m.FieldCleared(chargeflatfeeoverride.FieldDiscounts) { + fields = append(fields, chargeflatfeeoverride.FieldDiscounts) + } + if m.FieldCleared(chargeflatfeeoverride.FieldPercentageDiscounts) { + fields = append(fields, chargeflatfeeoverride.FieldPercentageDiscounts) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ChargeFlatFeeOverrideMutation) 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 *ChargeFlatFeeOverrideMutation) ClearField(name string) error { + switch name { + case chargeflatfeeoverride.FieldDescription: + m.ClearDescription() + return nil + case chargeflatfeeoverride.FieldMetadata: + m.ClearMetadata() + return nil + case chargeflatfeeoverride.FieldTaxBehavior: + m.ClearTaxBehavior() + return nil + case chargeflatfeeoverride.FieldTaxCodeID: + m.ClearTaxCodeID() + return nil + case chargeflatfeeoverride.FieldIntentDeletedAt: + m.ClearIntentDeletedAt() + return nil + case chargeflatfeeoverride.FieldFeatureKey: + m.ClearFeatureKey() + return nil + case chargeflatfeeoverride.FieldDiscounts: + m.ClearDiscounts() + return nil + case chargeflatfeeoverride.FieldPercentageDiscounts: + m.ClearPercentageDiscounts() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) ResetField(name string) error { + switch name { + case chargeflatfeeoverride.FieldNamespace: + m.ResetNamespace() + return nil + case chargeflatfeeoverride.FieldChargeID: + m.ResetChargeID() + return nil + case chargeflatfeeoverride.FieldName: + m.ResetName() + return nil + case chargeflatfeeoverride.FieldDescription: + m.ResetDescription() + return nil + case chargeflatfeeoverride.FieldMetadata: + m.ResetMetadata() + return nil + case chargeflatfeeoverride.FieldTaxBehavior: + m.ResetTaxBehavior() + return nil + case chargeflatfeeoverride.FieldTaxCodeID: + m.ResetTaxCodeID() + return nil + case chargeflatfeeoverride.FieldIntentDeletedAt: + m.ResetIntentDeletedAt() + return nil + case chargeflatfeeoverride.FieldServicePeriodFrom: + m.ResetServicePeriodFrom() + return nil + case chargeflatfeeoverride.FieldServicePeriodTo: + m.ResetServicePeriodTo() + return nil + case chargeflatfeeoverride.FieldFullServicePeriodFrom: + m.ResetFullServicePeriodFrom() + return nil + case chargeflatfeeoverride.FieldFullServicePeriodTo: + m.ResetFullServicePeriodTo() + return nil + case chargeflatfeeoverride.FieldBillingPeriodFrom: + m.ResetBillingPeriodFrom() + return nil + case chargeflatfeeoverride.FieldBillingPeriodTo: + m.ResetBillingPeriodTo() + return nil + case chargeflatfeeoverride.FieldInvoiceAt: + m.ResetInvoiceAt() + return nil + case chargeflatfeeoverride.FieldFeatureKey: + m.ResetFeatureKey() + return nil + case chargeflatfeeoverride.FieldPaymentTerm: + m.ResetPaymentTerm() + return nil + case chargeflatfeeoverride.FieldProRating: + m.ResetProRating() + return nil + case chargeflatfeeoverride.FieldAmountBeforeProration: + m.ResetAmountBeforeProration() + return nil + case chargeflatfeeoverride.FieldDiscounts: + m.ResetDiscounts() + return nil + case chargeflatfeeoverride.FieldPercentageDiscounts: + m.ResetPercentageDiscounts() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeOverride field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ChargeFlatFeeOverrideMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.flat_fee != nil { + edges = append(edges, chargeflatfeeoverride.EdgeFlatFee) + } + if m.tax_code != nil { + edges = append(edges, chargeflatfeeoverride.EdgeTaxCode) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ChargeFlatFeeOverrideMutation) AddedIDs(name string) []ent.Value { + switch name { + case chargeflatfeeoverride.EdgeFlatFee: + if id := m.flat_fee; id != nil { + return []ent.Value{*id} + } + case chargeflatfeeoverride.EdgeTaxCode: + if id := m.tax_code; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ChargeFlatFeeOverrideMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ChargeFlatFeeOverrideMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ChargeFlatFeeOverrideMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedflat_fee { + edges = append(edges, chargeflatfeeoverride.EdgeFlatFee) + } + if m.clearedtax_code { + edges = append(edges, chargeflatfeeoverride.EdgeTaxCode) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ChargeFlatFeeOverrideMutation) EdgeCleared(name string) bool { + switch name { + case chargeflatfeeoverride.EdgeFlatFee: + return m.clearedflat_fee + case chargeflatfeeoverride.EdgeTaxCode: + return m.clearedtax_code + } + 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 *ChargeFlatFeeOverrideMutation) ClearEdge(name string) error { + switch name { + case chargeflatfeeoverride.EdgeFlatFee: + m.ClearFlatFee() + return nil + case chargeflatfeeoverride.EdgeTaxCode: + m.ClearTaxCode() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeOverride 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 *ChargeFlatFeeOverrideMutation) ResetEdge(name string) error { + switch name { + case chargeflatfeeoverride.EdgeFlatFee: + m.ResetFlatFee() + return nil + case chargeflatfeeoverride.EdgeTaxCode: + m.ResetTaxCode() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeOverride edge %s", name) +} + +// ChargeFlatFeeRunMutation represents an operation that mutates the ChargeFlatFeeRun nodes in the graph. +type ChargeFlatFeeRunMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + 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 + _type *flatfee.RealizationRunType + initial_type *flatfee.RealizationRunType + service_period_from *time.Time + service_period_to *time.Time + amount_after_proration *alpacadecimal.Decimal + no_fiat_transaction_required *bool + immutable *bool + clearedFields map[string]struct{} + flat_fee *string + clearedflat_fee bool + billing_invoice_line *string + clearedbilling_invoice_line bool + billing_invoice *string + clearedbilling_invoice bool + credit_allocations map[string]struct{} + removedcredit_allocations map[string]struct{} + clearedcredit_allocations bool + detailed_lines map[string]struct{} + removeddetailed_lines map[string]struct{} + cleareddetailed_lines bool + invoiced_usage *string + clearedinvoiced_usage bool + payment *string + clearedpayment bool + done bool + oldValue func(context.Context) (*ChargeFlatFeeRun, error) + predicates []predicate.ChargeFlatFeeRun +} + +var _ ent.Mutation = (*ChargeFlatFeeRunMutation)(nil) + +// chargeflatfeerunOption allows management of the mutation configuration using functional options. +type chargeflatfeerunOption func(*ChargeFlatFeeRunMutation) + +// newChargeFlatFeeRunMutation creates new mutation for the ChargeFlatFeeRun entity. +func newChargeFlatFeeRunMutation(c config, op Op, opts ...chargeflatfeerunOption) *ChargeFlatFeeRunMutation { + m := &ChargeFlatFeeRunMutation{ + config: c, + op: op, + typ: TypeChargeFlatFeeRun, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withChargeFlatFeeRunID sets the ID field of the mutation. +func withChargeFlatFeeRunID(id string) chargeflatfeerunOption { + return func(m *ChargeFlatFeeRunMutation) { + var ( + err error + once sync.Once + value *ChargeFlatFeeRun + ) + m.oldValue = func(ctx context.Context) (*ChargeFlatFeeRun, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ChargeFlatFeeRun.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withChargeFlatFeeRun sets the old ChargeFlatFeeRun of the mutation. +func withChargeFlatFeeRun(node *ChargeFlatFeeRun) chargeflatfeerunOption { + return func(m *ChargeFlatFeeRunMutation) { + m.oldValue = func(context.Context) (*ChargeFlatFeeRun, 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 ChargeFlatFeeRunMutation) 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 ChargeFlatFeeRunMutation) 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 ChargeFlatFeeRun entities. +func (m *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) 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().ChargeFlatFeeRun.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 *ChargeFlatFeeRunMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *ChargeFlatFeeRunMutation) 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 ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *ChargeFlatFeeRunMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ChargeFlatFeeRunMutation) 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 ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *ChargeFlatFeeRunMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ChargeFlatFeeRunMutation) 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 ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *ChargeFlatFeeRunMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *ChargeFlatFeeRunMutation) 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 ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[chargeflatfeerun.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *ChargeFlatFeeRunMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[chargeflatfeerun.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *ChargeFlatFeeRunMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, chargeflatfeerun.FieldDeletedAt) +} + +// SetAmount sets the "amount" field. +func (m *ChargeFlatFeeRunMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *ChargeFlatFeeRunMutation) 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 ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) ResetAmount() { + m.amount = nil +} + +// SetTaxesTotal sets the "taxes_total" field. +func (m *ChargeFlatFeeRunMutation) SetTaxesTotal(a alpacadecimal.Decimal) { + m.taxes_total = &a +} + +// TaxesTotal returns the value of the "taxes_total" field in the mutation. +func (m *ChargeFlatFeeRunMutation) 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 ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) ResetTaxesTotal() { + m.taxes_total = nil +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (m *ChargeFlatFeeRunMutation) SetTaxesInclusiveTotal(a alpacadecimal.Decimal) { + m.taxes_inclusive_total = &a +} + +// TaxesInclusiveTotal returns the value of the "taxes_inclusive_total" field in the mutation. +func (m *ChargeFlatFeeRunMutation) 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 ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) ResetTaxesInclusiveTotal() { + m.taxes_inclusive_total = nil +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (m *ChargeFlatFeeRunMutation) SetTaxesExclusiveTotal(a alpacadecimal.Decimal) { + m.taxes_exclusive_total = &a +} + +// TaxesExclusiveTotal returns the value of the "taxes_exclusive_total" field in the mutation. +func (m *ChargeFlatFeeRunMutation) 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 ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) ResetTaxesExclusiveTotal() { + m.taxes_exclusive_total = nil +} + +// SetChargesTotal sets the "charges_total" field. +func (m *ChargeFlatFeeRunMutation) SetChargesTotal(a alpacadecimal.Decimal) { + m.charges_total = &a +} + +// ChargesTotal returns the value of the "charges_total" field in the mutation. +func (m *ChargeFlatFeeRunMutation) 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 ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) ResetChargesTotal() { + m.charges_total = nil +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (m *ChargeFlatFeeRunMutation) SetDiscountsTotal(a alpacadecimal.Decimal) { + m.discounts_total = &a +} + +// DiscountsTotal returns the value of the "discounts_total" field in the mutation. +func (m *ChargeFlatFeeRunMutation) 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 ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) ResetDiscountsTotal() { + m.discounts_total = nil +} + +// SetCreditsTotal sets the "credits_total" field. +func (m *ChargeFlatFeeRunMutation) SetCreditsTotal(a alpacadecimal.Decimal) { + m.credits_total = &a +} + +// CreditsTotal returns the value of the "credits_total" field in the mutation. +func (m *ChargeFlatFeeRunMutation) 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 ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) ResetCreditsTotal() { + m.credits_total = nil +} + +// SetTotal sets the "total" field. +func (m *ChargeFlatFeeRunMutation) SetTotal(a alpacadecimal.Decimal) { + m.total = &a +} + +// Total returns the value of the "total" field in the mutation. +func (m *ChargeFlatFeeRunMutation) 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 ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) ResetTotal() { + m.total = nil +} + +// SetChargeID sets the "charge_id" field. +func (m *ChargeFlatFeeRunMutation) SetChargeID(s string) { + m.flat_fee = &s +} + +// ChargeID returns the value of the "charge_id" field in the mutation. +func (m *ChargeFlatFeeRunMutation) ChargeID() (r string, exists bool) { + v := m.flat_fee + if v == nil { + return + } + return *v, true +} + +// OldChargeID returns the old "charge_id" field's value of the ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) ResetChargeID() { + m.flat_fee = nil +} + +// SetType sets the "type" field. +func (m *ChargeFlatFeeRunMutation) SetType(frt flatfee.RealizationRunType) { + m._type = &frt +} + +// GetType returns the value of the "type" field in the mutation. +func (m *ChargeFlatFeeRunMutation) GetType() (r flatfee.RealizationRunType, exists bool) { + v := m._type + if v == nil { + return + } + return *v, true +} + +// OldType returns the old "type" field's value of the ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) OldType(ctx context.Context) (v flatfee.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 *ChargeFlatFeeRunMutation) ResetType() { + m._type = nil +} + +// SetInitialType sets the "initial_type" field. +func (m *ChargeFlatFeeRunMutation) SetInitialType(frt flatfee.RealizationRunType) { + m.initial_type = &frt +} + +// InitialType returns the value of the "initial_type" field in the mutation. +func (m *ChargeFlatFeeRunMutation) InitialType() (r flatfee.RealizationRunType, exists bool) { + v := m.initial_type + if v == nil { + return + } + return *v, true +} + +// OldInitialType returns the old "initial_type" field's value of the ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) OldInitialType(ctx context.Context) (v flatfee.RealizationRunType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInitialType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInitialType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInitialType: %w", err) + } + return oldValue.InitialType, nil +} + +// ResetInitialType resets all changes to the "initial_type" field. +func (m *ChargeFlatFeeRunMutation) ResetInitialType() { + m.initial_type = nil +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (m *ChargeFlatFeeRunMutation) SetServicePeriodFrom(t time.Time) { + m.service_period_from = &t +} + +// ServicePeriodFrom returns the value of the "service_period_from" field in the mutation. +func (m *ChargeFlatFeeRunMutation) 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 ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) ResetServicePeriodFrom() { + m.service_period_from = nil +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (m *ChargeFlatFeeRunMutation) SetServicePeriodTo(t time.Time) { + m.service_period_to = &t +} + +// ServicePeriodTo returns the value of the "service_period_to" field in the mutation. +func (m *ChargeFlatFeeRunMutation) 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 ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) ResetServicePeriodTo() { + m.service_period_to = nil +} + +// SetLineID sets the "line_id" field. +func (m *ChargeFlatFeeRunMutation) SetLineID(s string) { + m.billing_invoice_line = &s +} + +// LineID returns the value of the "line_id" field in the mutation. +func (m *ChargeFlatFeeRunMutation) LineID() (r string, exists bool) { + v := m.billing_invoice_line + if v == nil { + return + } + return *v, true +} + +// OldLineID returns the old "line_id" field's value of the ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) ClearLineID() { + m.billing_invoice_line = nil + m.clearedFields[chargeflatfeerun.FieldLineID] = struct{}{} +} + +// LineIDCleared returns if the "line_id" field was cleared in this mutation. +func (m *ChargeFlatFeeRunMutation) LineIDCleared() bool { + _, ok := m.clearedFields[chargeflatfeerun.FieldLineID] + return ok +} + +// ResetLineID resets all changes to the "line_id" field. +func (m *ChargeFlatFeeRunMutation) ResetLineID() { + m.billing_invoice_line = nil + delete(m.clearedFields, chargeflatfeerun.FieldLineID) +} + +// SetInvoiceID sets the "invoice_id" field. +func (m *ChargeFlatFeeRunMutation) SetInvoiceID(s string) { + m.billing_invoice = &s +} + +// InvoiceID returns the value of the "invoice_id" field in the mutation. +func (m *ChargeFlatFeeRunMutation) InvoiceID() (r string, exists bool) { + v := m.billing_invoice + if v == nil { + return + } + return *v, true +} + +// OldInvoiceID returns the old "invoice_id" field's value of the ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) OldInvoiceID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceID: %w", err) + } + return oldValue.InvoiceID, nil +} + +// ClearInvoiceID clears the value of the "invoice_id" field. +func (m *ChargeFlatFeeRunMutation) ClearInvoiceID() { + m.billing_invoice = nil + m.clearedFields[chargeflatfeerun.FieldInvoiceID] = struct{}{} +} + +// InvoiceIDCleared returns if the "invoice_id" field was cleared in this mutation. +func (m *ChargeFlatFeeRunMutation) InvoiceIDCleared() bool { + _, ok := m.clearedFields[chargeflatfeerun.FieldInvoiceID] + return ok +} + +// ResetInvoiceID resets all changes to the "invoice_id" field. +func (m *ChargeFlatFeeRunMutation) ResetInvoiceID() { + m.billing_invoice = nil + delete(m.clearedFields, chargeflatfeerun.FieldInvoiceID) +} + +// SetAmountAfterProration sets the "amount_after_proration" field. +func (m *ChargeFlatFeeRunMutation) SetAmountAfterProration(a alpacadecimal.Decimal) { + m.amount_after_proration = &a +} + +// AmountAfterProration returns the value of the "amount_after_proration" field in the mutation. +func (m *ChargeFlatFeeRunMutation) AmountAfterProration() (r alpacadecimal.Decimal, exists bool) { + v := m.amount_after_proration + if v == nil { + return + } + return *v, true +} + +// OldAmountAfterProration returns the old "amount_after_proration" field's value of the ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) OldAmountAfterProration(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAmountAfterProration is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAmountAfterProration requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAmountAfterProration: %w", err) + } + return oldValue.AmountAfterProration, nil +} + +// ResetAmountAfterProration resets all changes to the "amount_after_proration" field. +func (m *ChargeFlatFeeRunMutation) ResetAmountAfterProration() { + m.amount_after_proration = nil +} + +// SetNoFiatTransactionRequired sets the "no_fiat_transaction_required" field. +func (m *ChargeFlatFeeRunMutation) SetNoFiatTransactionRequired(b bool) { + m.no_fiat_transaction_required = &b +} + +// NoFiatTransactionRequired returns the value of the "no_fiat_transaction_required" field in the mutation. +func (m *ChargeFlatFeeRunMutation) NoFiatTransactionRequired() (r bool, exists bool) { + v := m.no_fiat_transaction_required + if v == nil { + return + } + return *v, true +} + +// OldNoFiatTransactionRequired returns the old "no_fiat_transaction_required" field's value of the ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) OldNoFiatTransactionRequired(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNoFiatTransactionRequired is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNoFiatTransactionRequired requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNoFiatTransactionRequired: %w", err) + } + return oldValue.NoFiatTransactionRequired, nil +} + +// ResetNoFiatTransactionRequired resets all changes to the "no_fiat_transaction_required" field. +func (m *ChargeFlatFeeRunMutation) ResetNoFiatTransactionRequired() { + m.no_fiat_transaction_required = nil +} + +// SetImmutable sets the "immutable" field. +func (m *ChargeFlatFeeRunMutation) SetImmutable(b bool) { + m.immutable = &b +} + +// Immutable returns the value of the "immutable" field in the mutation. +func (m *ChargeFlatFeeRunMutation) Immutable() (r bool, exists bool) { + v := m.immutable + if v == nil { + return + } + return *v, true +} + +// OldImmutable returns the old "immutable" field's value of the ChargeFlatFeeRun entity. +// If the ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) OldImmutable(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldImmutable is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldImmutable requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldImmutable: %w", err) + } + return oldValue.Immutable, nil +} + +// ResetImmutable resets all changes to the "immutable" field. +func (m *ChargeFlatFeeRunMutation) ResetImmutable() { + m.immutable = nil +} + +// SetFlatFeeID sets the "flat_fee" edge to the ChargeFlatFee entity by id. +func (m *ChargeFlatFeeRunMutation) SetFlatFeeID(id string) { + m.flat_fee = &id +} + +// ClearFlatFee clears the "flat_fee" edge to the ChargeFlatFee entity. +func (m *ChargeFlatFeeRunMutation) ClearFlatFee() { + m.clearedflat_fee = true + m.clearedFields[chargeflatfeerun.FieldChargeID] = struct{}{} +} + +// FlatFeeCleared reports if the "flat_fee" edge to the ChargeFlatFee entity was cleared. +func (m *ChargeFlatFeeRunMutation) FlatFeeCleared() bool { + return m.clearedflat_fee +} + +// FlatFeeID returns the "flat_fee" edge ID in the mutation. +func (m *ChargeFlatFeeRunMutation) FlatFeeID() (id string, exists bool) { + if m.flat_fee != nil { + return *m.flat_fee, true + } + return +} + +// FlatFeeIDs returns the "flat_fee" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// FlatFeeID instead. It exists only for internal usage by the builders. +func (m *ChargeFlatFeeRunMutation) FlatFeeIDs() (ids []string) { + if id := m.flat_fee; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetFlatFee resets all changes to the "flat_fee" edge. +func (m *ChargeFlatFeeRunMutation) ResetFlatFee() { + m.flat_fee = nil + m.clearedflat_fee = false +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by id. +func (m *ChargeFlatFeeRunMutation) SetBillingInvoiceLineID(id string) { + m.billing_invoice_line = &id +} + +// ClearBillingInvoiceLine clears the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (m *ChargeFlatFeeRunMutation) ClearBillingInvoiceLine() { + m.clearedbilling_invoice_line = true + m.clearedFields[chargeflatfeerun.FieldLineID] = struct{}{} +} + +// BillingInvoiceLineCleared reports if the "billing_invoice_line" edge to the BillingInvoiceLine entity was cleared. +func (m *ChargeFlatFeeRunMutation) BillingInvoiceLineCleared() bool { + return m.LineIDCleared() || m.clearedbilling_invoice_line +} + +// BillingInvoiceLineID returns the "billing_invoice_line" edge ID in the mutation. +func (m *ChargeFlatFeeRunMutation) BillingInvoiceLineID() (id string, exists bool) { + if m.billing_invoice_line != nil { + return *m.billing_invoice_line, true + } + return +} + +// BillingInvoiceLineIDs returns the "billing_invoice_line" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BillingInvoiceLineID instead. It exists only for internal usage by the builders. +func (m *ChargeFlatFeeRunMutation) BillingInvoiceLineIDs() (ids []string) { + if id := m.billing_invoice_line; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBillingInvoiceLine resets all changes to the "billing_invoice_line" edge. +func (m *ChargeFlatFeeRunMutation) ResetBillingInvoiceLine() { + m.billing_invoice_line = nil + m.clearedbilling_invoice_line = false +} + +// SetBillingInvoiceID sets the "billing_invoice" edge to the BillingInvoice entity by id. +func (m *ChargeFlatFeeRunMutation) SetBillingInvoiceID(id string) { + m.billing_invoice = &id +} + +// ClearBillingInvoice clears the "billing_invoice" edge to the BillingInvoice entity. +func (m *ChargeFlatFeeRunMutation) ClearBillingInvoice() { + m.clearedbilling_invoice = true + m.clearedFields[chargeflatfeerun.FieldInvoiceID] = struct{}{} +} + +// BillingInvoiceCleared reports if the "billing_invoice" edge to the BillingInvoice entity was cleared. +func (m *ChargeFlatFeeRunMutation) BillingInvoiceCleared() bool { + return m.InvoiceIDCleared() || m.clearedbilling_invoice +} + +// BillingInvoiceID returns the "billing_invoice" edge ID in the mutation. +func (m *ChargeFlatFeeRunMutation) BillingInvoiceID() (id string, exists bool) { + if m.billing_invoice != nil { + return *m.billing_invoice, true + } + return +} + +// BillingInvoiceIDs returns the "billing_invoice" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BillingInvoiceID instead. It exists only for internal usage by the builders. +func (m *ChargeFlatFeeRunMutation) BillingInvoiceIDs() (ids []string) { + if id := m.billing_invoice; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBillingInvoice resets all changes to the "billing_invoice" edge. +func (m *ChargeFlatFeeRunMutation) ResetBillingInvoice() { + m.billing_invoice = nil + m.clearedbilling_invoice = false +} + +// AddCreditAllocationIDs adds the "credit_allocations" edge to the ChargeFlatFeeRunCreditAllocations entity by ids. +func (m *ChargeFlatFeeRunMutation) 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 ChargeFlatFeeRunCreditAllocations entity. +func (m *ChargeFlatFeeRunMutation) ClearCreditAllocations() { + m.clearedcredit_allocations = true +} + +// CreditAllocationsCleared reports if the "credit_allocations" edge to the ChargeFlatFeeRunCreditAllocations entity was cleared. +func (m *ChargeFlatFeeRunMutation) CreditAllocationsCleared() bool { + return m.clearedcredit_allocations +} + +// RemoveCreditAllocationIDs removes the "credit_allocations" edge to the ChargeFlatFeeRunCreditAllocations entity by IDs. +func (m *ChargeFlatFeeRunMutation) 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 ChargeFlatFeeRunCreditAllocations entity. +func (m *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) ResetCreditAllocations() { + m.credit_allocations = nil + m.clearedcredit_allocations = false + m.removedcredit_allocations = nil +} + +// AddDetailedLineIDs adds the "detailed_lines" edge to the ChargeFlatFeeRunDetailedLine entity by ids. +func (m *ChargeFlatFeeRunMutation) AddDetailedLineIDs(ids ...string) { + if m.detailed_lines == nil { + m.detailed_lines = make(map[string]struct{}) + } + for i := range ids { + m.detailed_lines[ids[i]] = struct{}{} + } +} + +// ClearDetailedLines clears the "detailed_lines" edge to the ChargeFlatFeeRunDetailedLine entity. +func (m *ChargeFlatFeeRunMutation) ClearDetailedLines() { + m.cleareddetailed_lines = true +} + +// DetailedLinesCleared reports if the "detailed_lines" edge to the ChargeFlatFeeRunDetailedLine entity was cleared. +func (m *ChargeFlatFeeRunMutation) DetailedLinesCleared() bool { + return m.cleareddetailed_lines +} + +// RemoveDetailedLineIDs removes the "detailed_lines" edge to the ChargeFlatFeeRunDetailedLine entity by IDs. +func (m *ChargeFlatFeeRunMutation) RemoveDetailedLineIDs(ids ...string) { + if m.removeddetailed_lines == nil { + m.removeddetailed_lines = make(map[string]struct{}) + } + for i := range ids { + delete(m.detailed_lines, ids[i]) + m.removeddetailed_lines[ids[i]] = struct{}{} + } +} + +// RemovedDetailedLines returns the removed IDs of the "detailed_lines" edge to the ChargeFlatFeeRunDetailedLine entity. +func (m *ChargeFlatFeeRunMutation) RemovedDetailedLinesIDs() (ids []string) { + for id := range m.removeddetailed_lines { + ids = append(ids, id) + } + return +} + +// DetailedLinesIDs returns the "detailed_lines" edge IDs in the mutation. +func (m *ChargeFlatFeeRunMutation) DetailedLinesIDs() (ids []string) { + for id := range m.detailed_lines { + ids = append(ids, id) + } + return +} + +// ResetDetailedLines resets all changes to the "detailed_lines" edge. +func (m *ChargeFlatFeeRunMutation) ResetDetailedLines() { + m.detailed_lines = nil + m.cleareddetailed_lines = false + m.removeddetailed_lines = nil +} + +// SetInvoicedUsageID sets the "invoiced_usage" edge to the ChargeFlatFeeRunInvoicedUsage entity by id. +func (m *ChargeFlatFeeRunMutation) SetInvoicedUsageID(id string) { + m.invoiced_usage = &id +} + +// ClearInvoicedUsage clears the "invoiced_usage" edge to the ChargeFlatFeeRunInvoicedUsage entity. +func (m *ChargeFlatFeeRunMutation) ClearInvoicedUsage() { + m.clearedinvoiced_usage = true +} + +// InvoicedUsageCleared reports if the "invoiced_usage" edge to the ChargeFlatFeeRunInvoicedUsage entity was cleared. +func (m *ChargeFlatFeeRunMutation) InvoicedUsageCleared() bool { + return m.clearedinvoiced_usage +} + +// InvoicedUsageID returns the "invoiced_usage" edge ID in the mutation. +func (m *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) ResetInvoicedUsage() { + m.invoiced_usage = nil + m.clearedinvoiced_usage = false +} + +// SetPaymentID sets the "payment" edge to the ChargeFlatFeeRunPayment entity by id. +func (m *ChargeFlatFeeRunMutation) SetPaymentID(id string) { + m.payment = &id +} + +// ClearPayment clears the "payment" edge to the ChargeFlatFeeRunPayment entity. +func (m *ChargeFlatFeeRunMutation) ClearPayment() { + m.clearedpayment = true +} + +// PaymentCleared reports if the "payment" edge to the ChargeFlatFeeRunPayment entity was cleared. +func (m *ChargeFlatFeeRunMutation) PaymentCleared() bool { + return m.clearedpayment +} + +// PaymentID returns the "payment" edge ID in the mutation. +func (m *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) PaymentIDs() (ids []string) { + if id := m.payment; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetPayment resets all changes to the "payment" edge. +func (m *ChargeFlatFeeRunMutation) ResetPayment() { + m.payment = nil + m.clearedpayment = false +} + +// Where appends a list predicates to the ChargeFlatFeeRunMutation builder. +func (m *ChargeFlatFeeRunMutation) Where(ps ...predicate.ChargeFlatFeeRun) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ChargeFlatFeeRunMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ChargeFlatFeeRunMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ChargeFlatFeeRun, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ChargeFlatFeeRunMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ChargeFlatFeeRunMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ChargeFlatFeeRun). +func (m *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) Fields() []string { + fields := make([]string, 0, 22) + if m.namespace != nil { + fields = append(fields, chargeflatfeerun.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, chargeflatfeerun.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, chargeflatfeerun.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, chargeflatfeerun.FieldDeletedAt) + } + if m.amount != nil { + fields = append(fields, chargeflatfeerun.FieldAmount) + } + if m.taxes_total != nil { + fields = append(fields, chargeflatfeerun.FieldTaxesTotal) + } + if m.taxes_inclusive_total != nil { + fields = append(fields, chargeflatfeerun.FieldTaxesInclusiveTotal) + } + if m.taxes_exclusive_total != nil { + fields = append(fields, chargeflatfeerun.FieldTaxesExclusiveTotal) + } + if m.charges_total != nil { + fields = append(fields, chargeflatfeerun.FieldChargesTotal) + } + if m.discounts_total != nil { + fields = append(fields, chargeflatfeerun.FieldDiscountsTotal) + } + if m.credits_total != nil { + fields = append(fields, chargeflatfeerun.FieldCreditsTotal) + } + if m.total != nil { + fields = append(fields, chargeflatfeerun.FieldTotal) + } + if m.flat_fee != nil { + fields = append(fields, chargeflatfeerun.FieldChargeID) + } + if m._type != nil { + fields = append(fields, chargeflatfeerun.FieldType) + } + if m.initial_type != nil { + fields = append(fields, chargeflatfeerun.FieldInitialType) + } + if m.service_period_from != nil { + fields = append(fields, chargeflatfeerun.FieldServicePeriodFrom) + } + if m.service_period_to != nil { + fields = append(fields, chargeflatfeerun.FieldServicePeriodTo) + } + if m.billing_invoice_line != nil { + fields = append(fields, chargeflatfeerun.FieldLineID) + } + if m.billing_invoice != nil { + fields = append(fields, chargeflatfeerun.FieldInvoiceID) + } + if m.amount_after_proration != nil { + fields = append(fields, chargeflatfeerun.FieldAmountAfterProration) + } + if m.no_fiat_transaction_required != nil { + fields = append(fields, chargeflatfeerun.FieldNoFiatTransactionRequired) + } + if m.immutable != nil { + fields = append(fields, chargeflatfeerun.FieldImmutable) + } + 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 *ChargeFlatFeeRunMutation) Field(name string) (ent.Value, bool) { + switch name { + case chargeflatfeerun.FieldNamespace: + return m.Namespace() + case chargeflatfeerun.FieldCreatedAt: + return m.CreatedAt() + case chargeflatfeerun.FieldUpdatedAt: + return m.UpdatedAt() + case chargeflatfeerun.FieldDeletedAt: + return m.DeletedAt() + case chargeflatfeerun.FieldAmount: + return m.Amount() + case chargeflatfeerun.FieldTaxesTotal: + return m.TaxesTotal() + case chargeflatfeerun.FieldTaxesInclusiveTotal: + return m.TaxesInclusiveTotal() + case chargeflatfeerun.FieldTaxesExclusiveTotal: + return m.TaxesExclusiveTotal() + case chargeflatfeerun.FieldChargesTotal: + return m.ChargesTotal() + case chargeflatfeerun.FieldDiscountsTotal: + return m.DiscountsTotal() + case chargeflatfeerun.FieldCreditsTotal: + return m.CreditsTotal() + case chargeflatfeerun.FieldTotal: + return m.Total() + case chargeflatfeerun.FieldChargeID: + return m.ChargeID() + case chargeflatfeerun.FieldType: + return m.GetType() + case chargeflatfeerun.FieldInitialType: + return m.InitialType() + case chargeflatfeerun.FieldServicePeriodFrom: + return m.ServicePeriodFrom() + case chargeflatfeerun.FieldServicePeriodTo: + return m.ServicePeriodTo() + case chargeflatfeerun.FieldLineID: + return m.LineID() + case chargeflatfeerun.FieldInvoiceID: + return m.InvoiceID() + case chargeflatfeerun.FieldAmountAfterProration: + return m.AmountAfterProration() + case chargeflatfeerun.FieldNoFiatTransactionRequired: + return m.NoFiatTransactionRequired() + case chargeflatfeerun.FieldImmutable: + return m.Immutable() + } + 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 *ChargeFlatFeeRunMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case chargeflatfeerun.FieldNamespace: + return m.OldNamespace(ctx) + case chargeflatfeerun.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case chargeflatfeerun.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case chargeflatfeerun.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case chargeflatfeerun.FieldAmount: + return m.OldAmount(ctx) + case chargeflatfeerun.FieldTaxesTotal: + return m.OldTaxesTotal(ctx) + case chargeflatfeerun.FieldTaxesInclusiveTotal: + return m.OldTaxesInclusiveTotal(ctx) + case chargeflatfeerun.FieldTaxesExclusiveTotal: + return m.OldTaxesExclusiveTotal(ctx) + case chargeflatfeerun.FieldChargesTotal: + return m.OldChargesTotal(ctx) + case chargeflatfeerun.FieldDiscountsTotal: + return m.OldDiscountsTotal(ctx) + case chargeflatfeerun.FieldCreditsTotal: + return m.OldCreditsTotal(ctx) + case chargeflatfeerun.FieldTotal: + return m.OldTotal(ctx) + case chargeflatfeerun.FieldChargeID: + return m.OldChargeID(ctx) + case chargeflatfeerun.FieldType: + return m.OldType(ctx) + case chargeflatfeerun.FieldInitialType: + return m.OldInitialType(ctx) + case chargeflatfeerun.FieldServicePeriodFrom: + return m.OldServicePeriodFrom(ctx) + case chargeflatfeerun.FieldServicePeriodTo: + return m.OldServicePeriodTo(ctx) + case chargeflatfeerun.FieldLineID: + return m.OldLineID(ctx) + case chargeflatfeerun.FieldInvoiceID: + return m.OldInvoiceID(ctx) + case chargeflatfeerun.FieldAmountAfterProration: + return m.OldAmountAfterProration(ctx) + case chargeflatfeerun.FieldNoFiatTransactionRequired: + return m.OldNoFiatTransactionRequired(ctx) + case chargeflatfeerun.FieldImmutable: + return m.OldImmutable(ctx) + } + return nil, fmt.Errorf("unknown ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) SetField(name string, value ent.Value) error { + switch name { + case chargeflatfeerun.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.FieldChargeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChargeID(v) + return nil + case chargeflatfeerun.FieldType: + v, ok := value.(flatfee.RealizationRunType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case chargeflatfeerun.FieldInitialType: + v, ok := value.(flatfee.RealizationRunType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInitialType(v) + return nil + case chargeflatfeerun.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 chargeflatfeerun.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 chargeflatfeerun.FieldLineID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLineID(v) + return nil + case chargeflatfeerun.FieldInvoiceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceID(v) + return nil + case chargeflatfeerun.FieldAmountAfterProration: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAmountAfterProration(v) + return nil + case chargeflatfeerun.FieldNoFiatTransactionRequired: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNoFiatTransactionRequired(v) + return nil + case chargeflatfeerun.FieldImmutable: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetImmutable(v) + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRun field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown ChargeFlatFeeRun numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ChargeFlatFeeRunMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(chargeflatfeerun.FieldDeletedAt) { + fields = append(fields, chargeflatfeerun.FieldDeletedAt) + } + if m.FieldCleared(chargeflatfeerun.FieldLineID) { + fields = append(fields, chargeflatfeerun.FieldLineID) + } + if m.FieldCleared(chargeflatfeerun.FieldInvoiceID) { + fields = append(fields, chargeflatfeerun.FieldInvoiceID) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ChargeFlatFeeRunMutation) 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 *ChargeFlatFeeRunMutation) ClearField(name string) error { + switch name { + case chargeflatfeerun.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case chargeflatfeerun.FieldLineID: + m.ClearLineID() + return nil + case chargeflatfeerun.FieldInvoiceID: + m.ClearInvoiceID() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) ResetField(name string) error { + switch name { + case chargeflatfeerun.FieldNamespace: + m.ResetNamespace() + return nil + case chargeflatfeerun.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case chargeflatfeerun.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case chargeflatfeerun.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case chargeflatfeerun.FieldAmount: + m.ResetAmount() + return nil + case chargeflatfeerun.FieldTaxesTotal: + m.ResetTaxesTotal() + return nil + case chargeflatfeerun.FieldTaxesInclusiveTotal: + m.ResetTaxesInclusiveTotal() + return nil + case chargeflatfeerun.FieldTaxesExclusiveTotal: + m.ResetTaxesExclusiveTotal() + return nil + case chargeflatfeerun.FieldChargesTotal: + m.ResetChargesTotal() + return nil + case chargeflatfeerun.FieldDiscountsTotal: + m.ResetDiscountsTotal() + return nil + case chargeflatfeerun.FieldCreditsTotal: + m.ResetCreditsTotal() + return nil + case chargeflatfeerun.FieldTotal: + m.ResetTotal() + return nil + case chargeflatfeerun.FieldChargeID: + m.ResetChargeID() + return nil + case chargeflatfeerun.FieldType: + m.ResetType() + return nil + case chargeflatfeerun.FieldInitialType: + m.ResetInitialType() + return nil + case chargeflatfeerun.FieldServicePeriodFrom: + m.ResetServicePeriodFrom() + return nil + case chargeflatfeerun.FieldServicePeriodTo: + m.ResetServicePeriodTo() + return nil + case chargeflatfeerun.FieldLineID: + m.ResetLineID() + return nil + case chargeflatfeerun.FieldInvoiceID: + m.ResetInvoiceID() + return nil + case chargeflatfeerun.FieldAmountAfterProration: + m.ResetAmountAfterProration() + return nil + case chargeflatfeerun.FieldNoFiatTransactionRequired: + m.ResetNoFiatTransactionRequired() + return nil + case chargeflatfeerun.FieldImmutable: + m.ResetImmutable() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRun field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ChargeFlatFeeRunMutation) AddedEdges() []string { + edges := make([]string, 0, 7) + if m.flat_fee != nil { + edges = append(edges, chargeflatfeerun.EdgeFlatFee) + } + if m.billing_invoice_line != nil { + edges = append(edges, chargeflatfeerun.EdgeBillingInvoiceLine) + } + if m.billing_invoice != nil { + edges = append(edges, chargeflatfeerun.EdgeBillingInvoice) + } + if m.credit_allocations != nil { + edges = append(edges, chargeflatfeerun.EdgeCreditAllocations) + } + if m.detailed_lines != nil { + edges = append(edges, chargeflatfeerun.EdgeDetailedLines) + } + if m.invoiced_usage != nil { + edges = append(edges, chargeflatfeerun.EdgeInvoicedUsage) + } + if m.payment != nil { + edges = append(edges, chargeflatfeerun.EdgePayment) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ChargeFlatFeeRunMutation) AddedIDs(name string) []ent.Value { + switch name { + case chargeflatfeerun.EdgeFlatFee: + if id := m.flat_fee; id != nil { + return []ent.Value{*id} + } + case chargeflatfeerun.EdgeBillingInvoiceLine: + if id := m.billing_invoice_line; id != nil { + return []ent.Value{*id} + } + case chargeflatfeerun.EdgeBillingInvoice: + if id := m.billing_invoice; id != nil { + return []ent.Value{*id} + } + case chargeflatfeerun.EdgeCreditAllocations: + ids := make([]ent.Value, 0, len(m.credit_allocations)) + for id := range m.credit_allocations { + ids = append(ids, id) + } + return ids + case chargeflatfeerun.EdgeDetailedLines: + ids := make([]ent.Value, 0, len(m.detailed_lines)) + for id := range m.detailed_lines { + ids = append(ids, id) + } + return ids + case chargeflatfeerun.EdgeInvoicedUsage: + if id := m.invoiced_usage; id != nil { + return []ent.Value{*id} + } + case chargeflatfeerun.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 *ChargeFlatFeeRunMutation) RemovedEdges() []string { + edges := make([]string, 0, 7) + if m.removedcredit_allocations != nil { + edges = append(edges, chargeflatfeerun.EdgeCreditAllocations) + } + if m.removeddetailed_lines != nil { + edges = append(edges, chargeflatfeerun.EdgeDetailedLines) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ChargeFlatFeeRunMutation) RemovedIDs(name string) []ent.Value { + switch name { + case chargeflatfeerun.EdgeCreditAllocations: + ids := make([]ent.Value, 0, len(m.removedcredit_allocations)) + for id := range m.removedcredit_allocations { + ids = append(ids, id) + } + return ids + case chargeflatfeerun.EdgeDetailedLines: + ids := make([]ent.Value, 0, len(m.removeddetailed_lines)) + for id := range m.removeddetailed_lines { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ChargeFlatFeeRunMutation) ClearedEdges() []string { + edges := make([]string, 0, 7) + if m.clearedflat_fee { + edges = append(edges, chargeflatfeerun.EdgeFlatFee) + } + if m.clearedbilling_invoice_line { + edges = append(edges, chargeflatfeerun.EdgeBillingInvoiceLine) + } + if m.clearedbilling_invoice { + edges = append(edges, chargeflatfeerun.EdgeBillingInvoice) + } + if m.clearedcredit_allocations { + edges = append(edges, chargeflatfeerun.EdgeCreditAllocations) + } + if m.cleareddetailed_lines { + edges = append(edges, chargeflatfeerun.EdgeDetailedLines) + } + if m.clearedinvoiced_usage { + edges = append(edges, chargeflatfeerun.EdgeInvoicedUsage) + } + if m.clearedpayment { + edges = append(edges, chargeflatfeerun.EdgePayment) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ChargeFlatFeeRunMutation) EdgeCleared(name string) bool { + switch name { + case chargeflatfeerun.EdgeFlatFee: + return m.clearedflat_fee + case chargeflatfeerun.EdgeBillingInvoiceLine: + return m.clearedbilling_invoice_line + case chargeflatfeerun.EdgeBillingInvoice: + return m.clearedbilling_invoice + case chargeflatfeerun.EdgeCreditAllocations: + return m.clearedcredit_allocations + case chargeflatfeerun.EdgeDetailedLines: + return m.cleareddetailed_lines + case chargeflatfeerun.EdgeInvoicedUsage: + return m.clearedinvoiced_usage + case chargeflatfeerun.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 *ChargeFlatFeeRunMutation) ClearEdge(name string) error { + switch name { + case chargeflatfeerun.EdgeFlatFee: + m.ClearFlatFee() + return nil + case chargeflatfeerun.EdgeBillingInvoiceLine: + m.ClearBillingInvoiceLine() + return nil + case chargeflatfeerun.EdgeBillingInvoice: + m.ClearBillingInvoice() + return nil + case chargeflatfeerun.EdgeInvoicedUsage: + m.ClearInvoicedUsage() + return nil + case chargeflatfeerun.EdgePayment: + m.ClearPayment() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRun 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 *ChargeFlatFeeRunMutation) ResetEdge(name string) error { + switch name { + case chargeflatfeerun.EdgeFlatFee: + m.ResetFlatFee() + return nil + case chargeflatfeerun.EdgeBillingInvoiceLine: + m.ResetBillingInvoiceLine() + return nil + case chargeflatfeerun.EdgeBillingInvoice: + m.ResetBillingInvoice() + return nil + case chargeflatfeerun.EdgeCreditAllocations: + m.ResetCreditAllocations() + return nil + case chargeflatfeerun.EdgeDetailedLines: + m.ResetDetailedLines() + return nil + case chargeflatfeerun.EdgeInvoicedUsage: + m.ResetInvoicedUsage() + return nil + case chargeflatfeerun.EdgePayment: + m.ResetPayment() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRun edge %s", name) +} + +// ChargeFlatFeeRunCreditAllocationsMutation represents an operation that mutates the ChargeFlatFeeRunCreditAllocations nodes in the graph. +type ChargeFlatFeeRunCreditAllocationsMutation struct { + config + op Op + typ string + id *string + amount *alpacadecimal.Decimal + service_period_from *time.Time + service_period_to *time.Time + ledger_transaction_group_id *string + sort_hint *int + addsort_hint *int + _type *creditrealization.Type + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + annotations *models.Annotations + clearedFields map[string]struct{} + corrections map[string]struct{} + removedcorrections map[string]struct{} + clearedcorrections bool + allocation *string + clearedallocation bool + run *string + clearedrun bool + billing_invoice_line *string + clearedbilling_invoice_line bool + done bool + oldValue func(context.Context) (*ChargeFlatFeeRunCreditAllocations, error) + predicates []predicate.ChargeFlatFeeRunCreditAllocations +} + +var _ ent.Mutation = (*ChargeFlatFeeRunCreditAllocationsMutation)(nil) + +// chargeflatfeeruncreditallocationsOption allows management of the mutation configuration using functional options. +type chargeflatfeeruncreditallocationsOption func(*ChargeFlatFeeRunCreditAllocationsMutation) + +// newChargeFlatFeeRunCreditAllocationsMutation creates new mutation for the ChargeFlatFeeRunCreditAllocations entity. +func newChargeFlatFeeRunCreditAllocationsMutation(c config, op Op, opts ...chargeflatfeeruncreditallocationsOption) *ChargeFlatFeeRunCreditAllocationsMutation { + m := &ChargeFlatFeeRunCreditAllocationsMutation{ + config: c, + op: op, + typ: TypeChargeFlatFeeRunCreditAllocations, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withChargeFlatFeeRunCreditAllocationsID sets the ID field of the mutation. +func withChargeFlatFeeRunCreditAllocationsID(id string) chargeflatfeeruncreditallocationsOption { + return func(m *ChargeFlatFeeRunCreditAllocationsMutation) { + var ( + err error + once sync.Once + value *ChargeFlatFeeRunCreditAllocations + ) + m.oldValue = func(ctx context.Context) (*ChargeFlatFeeRunCreditAllocations, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ChargeFlatFeeRunCreditAllocations.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withChargeFlatFeeRunCreditAllocations sets the old ChargeFlatFeeRunCreditAllocations of the mutation. +func withChargeFlatFeeRunCreditAllocations(node *ChargeFlatFeeRunCreditAllocations) chargeflatfeeruncreditallocationsOption { + return func(m *ChargeFlatFeeRunCreditAllocationsMutation) { + m.oldValue = func(context.Context) (*ChargeFlatFeeRunCreditAllocations, 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 ChargeFlatFeeRunCreditAllocationsMutation) 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 ChargeFlatFeeRunCreditAllocationsMutation) 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 ChargeFlatFeeRunCreditAllocations entities. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) 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 *ChargeFlatFeeRunCreditAllocationsMutation) 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 *ChargeFlatFeeRunCreditAllocationsMutation) 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().ChargeFlatFeeRunCreditAllocations.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 *ChargeFlatFeeRunCreditAllocationsMutation) SetLineID(s string) { + m.billing_invoice_line = &s +} + +// LineID returns the value of the "line_id" field in the mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) LineID() (r string, exists bool) { + v := m.billing_invoice_line + if v == nil { + return + } + return *v, true +} + +// OldLineID returns the old "line_id" field's value of the ChargeFlatFeeRunCreditAllocations entity. +// If the ChargeFlatFeeRunCreditAllocations 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 *ChargeFlatFeeRunCreditAllocationsMutation) 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 *ChargeFlatFeeRunCreditAllocationsMutation) ClearLineID() { + m.billing_invoice_line = nil + m.clearedFields[chargeflatfeeruncreditallocations.FieldLineID] = struct{}{} +} + +// LineIDCleared returns if the "line_id" field was cleared in this mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) LineIDCleared() bool { + _, ok := m.clearedFields[chargeflatfeeruncreditallocations.FieldLineID] + return ok +} + +// ResetLineID resets all changes to the "line_id" field. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) ResetLineID() { + m.billing_invoice_line = nil + delete(m.clearedFields, chargeflatfeeruncreditallocations.FieldLineID) +} + +// SetAmount sets the "amount" field. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) 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 ChargeFlatFeeRunCreditAllocations entity. +// If the ChargeFlatFeeRunCreditAllocations 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 *ChargeFlatFeeRunCreditAllocationsMutation) 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 *ChargeFlatFeeRunCreditAllocationsMutation) ResetAmount() { + m.amount = nil +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) SetServicePeriodFrom(t time.Time) { + m.service_period_from = &t +} + +// ServicePeriodFrom returns the value of the "service_period_from" field in the mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) 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 ChargeFlatFeeRunCreditAllocations entity. +// If the ChargeFlatFeeRunCreditAllocations 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 *ChargeFlatFeeRunCreditAllocationsMutation) 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 *ChargeFlatFeeRunCreditAllocationsMutation) ResetServicePeriodFrom() { + m.service_period_from = nil +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) SetServicePeriodTo(t time.Time) { + m.service_period_to = &t +} + +// ServicePeriodTo returns the value of the "service_period_to" field in the mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) 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 ChargeFlatFeeRunCreditAllocations entity. +// If the ChargeFlatFeeRunCreditAllocations 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 *ChargeFlatFeeRunCreditAllocationsMutation) 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 *ChargeFlatFeeRunCreditAllocationsMutation) ResetServicePeriodTo() { + m.service_period_to = nil +} + +// SetLedgerTransactionGroupID sets the "ledger_transaction_group_id" field. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) 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 *ChargeFlatFeeRunCreditAllocationsMutation) 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 ChargeFlatFeeRunCreditAllocations entity. +// If the ChargeFlatFeeRunCreditAllocations 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 *ChargeFlatFeeRunCreditAllocationsMutation) 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 *ChargeFlatFeeRunCreditAllocationsMutation) ResetLedgerTransactionGroupID() { + m.ledger_transaction_group_id = nil +} + +// SetSortHint sets the "sort_hint" field. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) SetSortHint(i int) { + m.sort_hint = &i + m.addsort_hint = nil +} + +// SortHint returns the value of the "sort_hint" field in the mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) SortHint() (r int, exists bool) { + v := m.sort_hint + if v == nil { + return + } + return *v, true +} + +// OldSortHint returns the old "sort_hint" field's value of the ChargeFlatFeeRunCreditAllocations entity. +// If the ChargeFlatFeeRunCreditAllocations 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 *ChargeFlatFeeRunCreditAllocationsMutation) OldSortHint(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSortHint is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSortHint requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSortHint: %w", err) + } + return oldValue.SortHint, nil +} + +// AddSortHint adds i to the "sort_hint" field. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) AddSortHint(i int) { + if m.addsort_hint != nil { + *m.addsort_hint += i + } else { + m.addsort_hint = &i + } +} + +// AddedSortHint returns the value that was added to the "sort_hint" field in this mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) AddedSortHint() (r int, exists bool) { + v := m.addsort_hint + if v == nil { + return + } + return *v, true +} + +// ResetSortHint resets all changes to the "sort_hint" field. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) ResetSortHint() { + m.sort_hint = nil + m.addsort_hint = nil +} + +// SetType sets the "type" field. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) SetType(c creditrealization.Type) { + m._type = &c +} + +// GetType returns the value of the "type" field in the mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) GetType() (r creditrealization.Type, exists bool) { + v := m._type + if v == nil { + return + } + return *v, true +} + +// OldType returns the old "type" field's value of the ChargeFlatFeeRunCreditAllocations entity. +// If the ChargeFlatFeeRunCreditAllocations 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 *ChargeFlatFeeRunCreditAllocationsMutation) OldType(ctx context.Context) (v creditrealization.Type, 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 *ChargeFlatFeeRunCreditAllocationsMutation) ResetType() { + m._type = nil +} + +// SetCorrectsRealizationID sets the "corrects_realization_id" field. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) SetCorrectsRealizationID(s string) { + m.allocation = &s +} + +// CorrectsRealizationID returns the value of the "corrects_realization_id" field in the mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) CorrectsRealizationID() (r string, exists bool) { + v := m.allocation + if v == nil { + return + } + return *v, true +} + +// OldCorrectsRealizationID returns the old "corrects_realization_id" field's value of the ChargeFlatFeeRunCreditAllocations entity. +// If the ChargeFlatFeeRunCreditAllocations 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 *ChargeFlatFeeRunCreditAllocationsMutation) OldCorrectsRealizationID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCorrectsRealizationID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCorrectsRealizationID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCorrectsRealizationID: %w", err) + } + return oldValue.CorrectsRealizationID, nil +} + +// ClearCorrectsRealizationID clears the value of the "corrects_realization_id" field. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) ClearCorrectsRealizationID() { + m.allocation = nil + m.clearedFields[chargeflatfeeruncreditallocations.FieldCorrectsRealizationID] = struct{}{} +} + +// CorrectsRealizationIDCleared returns if the "corrects_realization_id" field was cleared in this mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) CorrectsRealizationIDCleared() bool { + _, ok := m.clearedFields[chargeflatfeeruncreditallocations.FieldCorrectsRealizationID] + return ok +} + +// ResetCorrectsRealizationID resets all changes to the "corrects_realization_id" field. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) ResetCorrectsRealizationID() { + m.allocation = nil + delete(m.clearedFields, chargeflatfeeruncreditallocations.FieldCorrectsRealizationID) +} + +// SetNamespace sets the "namespace" field. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) 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 ChargeFlatFeeRunCreditAllocations entity. +// If the ChargeFlatFeeRunCreditAllocations 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 *ChargeFlatFeeRunCreditAllocationsMutation) 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 *ChargeFlatFeeRunCreditAllocationsMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) 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 ChargeFlatFeeRunCreditAllocations entity. +// If the ChargeFlatFeeRunCreditAllocations 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 *ChargeFlatFeeRunCreditAllocationsMutation) 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 *ChargeFlatFeeRunCreditAllocationsMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) 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 ChargeFlatFeeRunCreditAllocations entity. +// If the ChargeFlatFeeRunCreditAllocations 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 *ChargeFlatFeeRunCreditAllocationsMutation) 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 *ChargeFlatFeeRunCreditAllocationsMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) 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 ChargeFlatFeeRunCreditAllocations entity. +// If the ChargeFlatFeeRunCreditAllocations 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 *ChargeFlatFeeRunCreditAllocationsMutation) 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 *ChargeFlatFeeRunCreditAllocationsMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[chargeflatfeeruncreditallocations.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[chargeflatfeeruncreditallocations.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, chargeflatfeeruncreditallocations.FieldDeletedAt) +} + +// SetAnnotations sets the "annotations" field. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) 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 ChargeFlatFeeRunCreditAllocations entity. +// If the ChargeFlatFeeRunCreditAllocations 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 *ChargeFlatFeeRunCreditAllocationsMutation) 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 *ChargeFlatFeeRunCreditAllocationsMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[chargeflatfeeruncreditallocations.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[chargeflatfeeruncreditallocations.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, chargeflatfeeruncreditallocations.FieldAnnotations) +} + +// SetRunID sets the "run_id" field. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) SetRunID(s string) { + m.run = &s +} + +// RunID returns the value of the "run_id" field in the mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) 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 ChargeFlatFeeRunCreditAllocations entity. +// If the ChargeFlatFeeRunCreditAllocations 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 *ChargeFlatFeeRunCreditAllocationsMutation) 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 *ChargeFlatFeeRunCreditAllocationsMutation) ResetRunID() { + m.run = nil +} + +// AddCorrectionIDs adds the "corrections" edge to the ChargeFlatFeeRunCreditAllocations entity by ids. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) AddCorrectionIDs(ids ...string) { + if m.corrections == nil { + m.corrections = make(map[string]struct{}) + } + for i := range ids { + m.corrections[ids[i]] = struct{}{} + } +} + +// ClearCorrections clears the "corrections" edge to the ChargeFlatFeeRunCreditAllocations entity. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) ClearCorrections() { + m.clearedcorrections = true +} + +// CorrectionsCleared reports if the "corrections" edge to the ChargeFlatFeeRunCreditAllocations entity was cleared. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) CorrectionsCleared() bool { + return m.clearedcorrections +} + +// RemoveCorrectionIDs removes the "corrections" edge to the ChargeFlatFeeRunCreditAllocations entity by IDs. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) RemoveCorrectionIDs(ids ...string) { + if m.removedcorrections == nil { + m.removedcorrections = make(map[string]struct{}) + } + for i := range ids { + delete(m.corrections, ids[i]) + m.removedcorrections[ids[i]] = struct{}{} + } +} + +// RemovedCorrections returns the removed IDs of the "corrections" edge to the ChargeFlatFeeRunCreditAllocations entity. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) RemovedCorrectionsIDs() (ids []string) { + for id := range m.removedcorrections { + ids = append(ids, id) + } + return +} + +// CorrectionsIDs returns the "corrections" edge IDs in the mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) CorrectionsIDs() (ids []string) { + for id := range m.corrections { + ids = append(ids, id) + } + return +} + +// ResetCorrections resets all changes to the "corrections" edge. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) ResetCorrections() { + m.corrections = nil + m.clearedcorrections = false + m.removedcorrections = nil +} + +// SetAllocationID sets the "allocation" edge to the ChargeFlatFeeRunCreditAllocations entity by id. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) SetAllocationID(id string) { + m.allocation = &id +} + +// ClearAllocation clears the "allocation" edge to the ChargeFlatFeeRunCreditAllocations entity. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) ClearAllocation() { + m.clearedallocation = true + m.clearedFields[chargeflatfeeruncreditallocations.FieldCorrectsRealizationID] = struct{}{} +} + +// AllocationCleared reports if the "allocation" edge to the ChargeFlatFeeRunCreditAllocations entity was cleared. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) AllocationCleared() bool { + return m.CorrectsRealizationIDCleared() || m.clearedallocation +} + +// AllocationID returns the "allocation" edge ID in the mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) AllocationID() (id string, exists bool) { + if m.allocation != nil { + return *m.allocation, true + } + return +} + +// AllocationIDs returns the "allocation" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// AllocationID instead. It exists only for internal usage by the builders. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) AllocationIDs() (ids []string) { + if id := m.allocation; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetAllocation resets all changes to the "allocation" edge. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) ResetAllocation() { + m.allocation = nil + m.clearedallocation = false +} + +// ClearRun clears the "run" edge to the ChargeFlatFeeRun entity. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) ClearRun() { + m.clearedrun = true + m.clearedFields[chargeflatfeeruncreditallocations.FieldRunID] = struct{}{} +} + +// RunCleared reports if the "run" edge to the ChargeFlatFeeRun entity was cleared. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) 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 *ChargeFlatFeeRunCreditAllocationsMutation) RunIDs() (ids []string) { + if id := m.run; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetRun resets all changes to the "run" edge. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) ResetRun() { + m.run = nil + m.clearedrun = false +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by id. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) SetBillingInvoiceLineID(id string) { + m.billing_invoice_line = &id +} + +// ClearBillingInvoiceLine clears the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) ClearBillingInvoiceLine() { + m.clearedbilling_invoice_line = true + m.clearedFields[chargeflatfeeruncreditallocations.FieldLineID] = struct{}{} +} + +// BillingInvoiceLineCleared reports if the "billing_invoice_line" edge to the BillingInvoiceLine entity was cleared. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) BillingInvoiceLineCleared() bool { + return m.LineIDCleared() || m.clearedbilling_invoice_line +} + +// BillingInvoiceLineID returns the "billing_invoice_line" edge ID in the mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) BillingInvoiceLineID() (id string, exists bool) { + if m.billing_invoice_line != nil { + return *m.billing_invoice_line, true + } + return +} + +// BillingInvoiceLineIDs returns the "billing_invoice_line" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BillingInvoiceLineID instead. It exists only for internal usage by the builders. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) BillingInvoiceLineIDs() (ids []string) { + if id := m.billing_invoice_line; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBillingInvoiceLine resets all changes to the "billing_invoice_line" edge. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) ResetBillingInvoiceLine() { + m.billing_invoice_line = nil + m.clearedbilling_invoice_line = false +} + +// Where appends a list predicates to the ChargeFlatFeeRunCreditAllocationsMutation builder. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) Where(ps ...predicate.ChargeFlatFeeRunCreditAllocations) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ChargeFlatFeeRunCreditAllocationsMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ChargeFlatFeeRunCreditAllocations, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ChargeFlatFeeRunCreditAllocations). +func (m *ChargeFlatFeeRunCreditAllocationsMutation) 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 *ChargeFlatFeeRunCreditAllocationsMutation) Fields() []string { + fields := make([]string, 0, 14) + if m.billing_invoice_line != nil { + fields = append(fields, chargeflatfeeruncreditallocations.FieldLineID) + } + if m.amount != nil { + fields = append(fields, chargeflatfeeruncreditallocations.FieldAmount) + } + if m.service_period_from != nil { + fields = append(fields, chargeflatfeeruncreditallocations.FieldServicePeriodFrom) + } + if m.service_period_to != nil { + fields = append(fields, chargeflatfeeruncreditallocations.FieldServicePeriodTo) + } + if m.ledger_transaction_group_id != nil { + fields = append(fields, chargeflatfeeruncreditallocations.FieldLedgerTransactionGroupID) + } + if m.sort_hint != nil { + fields = append(fields, chargeflatfeeruncreditallocations.FieldSortHint) + } + if m._type != nil { + fields = append(fields, chargeflatfeeruncreditallocations.FieldType) + } + if m.allocation != nil { + fields = append(fields, chargeflatfeeruncreditallocations.FieldCorrectsRealizationID) + } + if m.namespace != nil { + fields = append(fields, chargeflatfeeruncreditallocations.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, chargeflatfeeruncreditallocations.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, chargeflatfeeruncreditallocations.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, chargeflatfeeruncreditallocations.FieldDeletedAt) + } + if m.annotations != nil { + fields = append(fields, chargeflatfeeruncreditallocations.FieldAnnotations) + } + if m.run != nil { + fields = append(fields, chargeflatfeeruncreditallocations.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 *ChargeFlatFeeRunCreditAllocationsMutation) Field(name string) (ent.Value, bool) { + switch name { + case chargeflatfeeruncreditallocations.FieldLineID: + return m.LineID() + case chargeflatfeeruncreditallocations.FieldAmount: + return m.Amount() + case chargeflatfeeruncreditallocations.FieldServicePeriodFrom: + return m.ServicePeriodFrom() + case chargeflatfeeruncreditallocations.FieldServicePeriodTo: + return m.ServicePeriodTo() + case chargeflatfeeruncreditallocations.FieldLedgerTransactionGroupID: + return m.LedgerTransactionGroupID() + case chargeflatfeeruncreditallocations.FieldSortHint: + return m.SortHint() + case chargeflatfeeruncreditallocations.FieldType: + return m.GetType() + case chargeflatfeeruncreditallocations.FieldCorrectsRealizationID: + return m.CorrectsRealizationID() + case chargeflatfeeruncreditallocations.FieldNamespace: + return m.Namespace() + case chargeflatfeeruncreditallocations.FieldCreatedAt: + return m.CreatedAt() + case chargeflatfeeruncreditallocations.FieldUpdatedAt: + return m.UpdatedAt() + case chargeflatfeeruncreditallocations.FieldDeletedAt: + return m.DeletedAt() + case chargeflatfeeruncreditallocations.FieldAnnotations: + return m.Annotations() + case chargeflatfeeruncreditallocations.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 *ChargeFlatFeeRunCreditAllocationsMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case chargeflatfeeruncreditallocations.FieldLineID: + return m.OldLineID(ctx) + case chargeflatfeeruncreditallocations.FieldAmount: + return m.OldAmount(ctx) + case chargeflatfeeruncreditallocations.FieldServicePeriodFrom: + return m.OldServicePeriodFrom(ctx) + case chargeflatfeeruncreditallocations.FieldServicePeriodTo: + return m.OldServicePeriodTo(ctx) + case chargeflatfeeruncreditallocations.FieldLedgerTransactionGroupID: + return m.OldLedgerTransactionGroupID(ctx) + case chargeflatfeeruncreditallocations.FieldSortHint: + return m.OldSortHint(ctx) + case chargeflatfeeruncreditallocations.FieldType: + return m.OldType(ctx) + case chargeflatfeeruncreditallocations.FieldCorrectsRealizationID: + return m.OldCorrectsRealizationID(ctx) + case chargeflatfeeruncreditallocations.FieldNamespace: + return m.OldNamespace(ctx) + case chargeflatfeeruncreditallocations.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case chargeflatfeeruncreditallocations.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case chargeflatfeeruncreditallocations.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case chargeflatfeeruncreditallocations.FieldAnnotations: + return m.OldAnnotations(ctx) + case chargeflatfeeruncreditallocations.FieldRunID: + return m.OldRunID(ctx) + } + return nil, fmt.Errorf("unknown ChargeFlatFeeRunCreditAllocations 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 *ChargeFlatFeeRunCreditAllocationsMutation) SetField(name string, value ent.Value) error { + switch name { + case chargeflatfeeruncreditallocations.FieldLineID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLineID(v) + return nil + case chargeflatfeeruncreditallocations.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 chargeflatfeeruncreditallocations.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 chargeflatfeeruncreditallocations.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 chargeflatfeeruncreditallocations.FieldLedgerTransactionGroupID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLedgerTransactionGroupID(v) + return nil + case chargeflatfeeruncreditallocations.FieldSortHint: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSortHint(v) + return nil + case chargeflatfeeruncreditallocations.FieldType: + v, ok := value.(creditrealization.Type) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case chargeflatfeeruncreditallocations.FieldCorrectsRealizationID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCorrectsRealizationID(v) + return nil + case chargeflatfeeruncreditallocations.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case chargeflatfeeruncreditallocations.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 chargeflatfeeruncreditallocations.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 chargeflatfeeruncreditallocations.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 chargeflatfeeruncreditallocations.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 chargeflatfeeruncreditallocations.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 ChargeFlatFeeRunCreditAllocations field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) AddedFields() []string { + var fields []string + if m.addsort_hint != nil { + fields = append(fields, chargeflatfeeruncreditallocations.FieldSortHint) + } + return fields +} + +// 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 *ChargeFlatFeeRunCreditAllocationsMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case chargeflatfeeruncreditallocations.FieldSortHint: + return m.AddedSortHint() + } + 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 *ChargeFlatFeeRunCreditAllocationsMutation) AddField(name string, value ent.Value) error { + switch name { + case chargeflatfeeruncreditallocations.FieldSortHint: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddSortHint(v) + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRunCreditAllocations numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(chargeflatfeeruncreditallocations.FieldLineID) { + fields = append(fields, chargeflatfeeruncreditallocations.FieldLineID) + } + if m.FieldCleared(chargeflatfeeruncreditallocations.FieldCorrectsRealizationID) { + fields = append(fields, chargeflatfeeruncreditallocations.FieldCorrectsRealizationID) + } + if m.FieldCleared(chargeflatfeeruncreditallocations.FieldDeletedAt) { + fields = append(fields, chargeflatfeeruncreditallocations.FieldDeletedAt) + } + if m.FieldCleared(chargeflatfeeruncreditallocations.FieldAnnotations) { + fields = append(fields, chargeflatfeeruncreditallocations.FieldAnnotations) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) 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 *ChargeFlatFeeRunCreditAllocationsMutation) ClearField(name string) error { + switch name { + case chargeflatfeeruncreditallocations.FieldLineID: + m.ClearLineID() + return nil + case chargeflatfeeruncreditallocations.FieldCorrectsRealizationID: + m.ClearCorrectsRealizationID() + return nil + case chargeflatfeeruncreditallocations.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case chargeflatfeeruncreditallocations.FieldAnnotations: + m.ClearAnnotations() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRunCreditAllocations 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 *ChargeFlatFeeRunCreditAllocationsMutation) ResetField(name string) error { + switch name { + case chargeflatfeeruncreditallocations.FieldLineID: + m.ResetLineID() + return nil + case chargeflatfeeruncreditallocations.FieldAmount: + m.ResetAmount() + return nil + case chargeflatfeeruncreditallocations.FieldServicePeriodFrom: + m.ResetServicePeriodFrom() + return nil + case chargeflatfeeruncreditallocations.FieldServicePeriodTo: + m.ResetServicePeriodTo() + return nil + case chargeflatfeeruncreditallocations.FieldLedgerTransactionGroupID: + m.ResetLedgerTransactionGroupID() + return nil + case chargeflatfeeruncreditallocations.FieldSortHint: + m.ResetSortHint() + return nil + case chargeflatfeeruncreditallocations.FieldType: + m.ResetType() + return nil + case chargeflatfeeruncreditallocations.FieldCorrectsRealizationID: + m.ResetCorrectsRealizationID() + return nil + case chargeflatfeeruncreditallocations.FieldNamespace: + m.ResetNamespace() + return nil + case chargeflatfeeruncreditallocations.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case chargeflatfeeruncreditallocations.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case chargeflatfeeruncreditallocations.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case chargeflatfeeruncreditallocations.FieldAnnotations: + m.ResetAnnotations() + return nil + case chargeflatfeeruncreditallocations.FieldRunID: + m.ResetRunID() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRunCreditAllocations field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) AddedEdges() []string { + edges := make([]string, 0, 4) + if m.corrections != nil { + edges = append(edges, chargeflatfeeruncreditallocations.EdgeCorrections) + } + if m.allocation != nil { + edges = append(edges, chargeflatfeeruncreditallocations.EdgeAllocation) + } + if m.run != nil { + edges = append(edges, chargeflatfeeruncreditallocations.EdgeRun) + } + if m.billing_invoice_line != nil { + edges = append(edges, chargeflatfeeruncreditallocations.EdgeBillingInvoiceLine) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) AddedIDs(name string) []ent.Value { + switch name { + case chargeflatfeeruncreditallocations.EdgeCorrections: + ids := make([]ent.Value, 0, len(m.corrections)) + for id := range m.corrections { + ids = append(ids, id) + } + return ids + case chargeflatfeeruncreditallocations.EdgeAllocation: + if id := m.allocation; id != nil { + return []ent.Value{*id} + } + case chargeflatfeeruncreditallocations.EdgeRun: + if id := m.run; id != nil { + return []ent.Value{*id} + } + case chargeflatfeeruncreditallocations.EdgeBillingInvoiceLine: + if id := m.billing_invoice_line; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) RemovedEdges() []string { + edges := make([]string, 0, 4) + if m.removedcorrections != nil { + edges = append(edges, chargeflatfeeruncreditallocations.EdgeCorrections) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) RemovedIDs(name string) []ent.Value { + switch name { + case chargeflatfeeruncreditallocations.EdgeCorrections: + ids := make([]ent.Value, 0, len(m.removedcorrections)) + for id := range m.removedcorrections { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) ClearedEdges() []string { + edges := make([]string, 0, 4) + if m.clearedcorrections { + edges = append(edges, chargeflatfeeruncreditallocations.EdgeCorrections) + } + if m.clearedallocation { + edges = append(edges, chargeflatfeeruncreditallocations.EdgeAllocation) + } + if m.clearedrun { + edges = append(edges, chargeflatfeeruncreditallocations.EdgeRun) + } + if m.clearedbilling_invoice_line { + edges = append(edges, chargeflatfeeruncreditallocations.EdgeBillingInvoiceLine) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ChargeFlatFeeRunCreditAllocationsMutation) EdgeCleared(name string) bool { + switch name { + case chargeflatfeeruncreditallocations.EdgeCorrections: + return m.clearedcorrections + case chargeflatfeeruncreditallocations.EdgeAllocation: + return m.clearedallocation + case chargeflatfeeruncreditallocations.EdgeRun: + return m.clearedrun + case chargeflatfeeruncreditallocations.EdgeBillingInvoiceLine: + return m.clearedbilling_invoice_line + } + 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 *ChargeFlatFeeRunCreditAllocationsMutation) ClearEdge(name string) error { + switch name { + case chargeflatfeeruncreditallocations.EdgeAllocation: + m.ClearAllocation() + return nil + case chargeflatfeeruncreditallocations.EdgeRun: + m.ClearRun() + return nil + case chargeflatfeeruncreditallocations.EdgeBillingInvoiceLine: + m.ClearBillingInvoiceLine() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRunCreditAllocations 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 *ChargeFlatFeeRunCreditAllocationsMutation) ResetEdge(name string) error { + switch name { + case chargeflatfeeruncreditallocations.EdgeCorrections: + m.ResetCorrections() + return nil + case chargeflatfeeruncreditallocations.EdgeAllocation: + m.ResetAllocation() + return nil + case chargeflatfeeruncreditallocations.EdgeRun: + m.ResetRun() + return nil + case chargeflatfeeruncreditallocations.EdgeBillingInvoiceLine: + m.ResetBillingInvoiceLine() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRunCreditAllocations edge %s", name) +} + +// ChargeFlatFeeRunDetailedLineMutation represents an operation that mutates the ChargeFlatFeeRunDetailedLine nodes in the graph. +type ChargeFlatFeeRunDetailedLineMutation struct { + config + op Op + typ string + id *string + currency *currencyx.Code + service_period_start *time.Time + service_period_end *time.Time + quantity *alpacadecimal.Decimal + invoicing_app_external_id *string + child_unique_reference_id *string + per_unit_amount *alpacadecimal.Decimal + category *stddetailedline.Category + payment_term *productcatalog.PaymentTermType + index *int + addindex *int + credits_applied **creditsapplied.CreditsApplied + annotations *models.Annotations + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + name *string + description *string + 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 + pricer_reference_id *string + clearedFields map[string]struct{} + run *string + clearedrun bool + done bool + oldValue func(context.Context) (*ChargeFlatFeeRunDetailedLine, error) + predicates []predicate.ChargeFlatFeeRunDetailedLine +} + +var _ ent.Mutation = (*ChargeFlatFeeRunDetailedLineMutation)(nil) + +// chargeflatfeerundetailedlineOption allows management of the mutation configuration using functional options. +type chargeflatfeerundetailedlineOption func(*ChargeFlatFeeRunDetailedLineMutation) + +// newChargeFlatFeeRunDetailedLineMutation creates new mutation for the ChargeFlatFeeRunDetailedLine entity. +func newChargeFlatFeeRunDetailedLineMutation(c config, op Op, opts ...chargeflatfeerundetailedlineOption) *ChargeFlatFeeRunDetailedLineMutation { + m := &ChargeFlatFeeRunDetailedLineMutation{ + config: c, + op: op, + typ: TypeChargeFlatFeeRunDetailedLine, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withChargeFlatFeeRunDetailedLineID sets the ID field of the mutation. +func withChargeFlatFeeRunDetailedLineID(id string) chargeflatfeerundetailedlineOption { + return func(m *ChargeFlatFeeRunDetailedLineMutation) { + var ( + err error + once sync.Once + value *ChargeFlatFeeRunDetailedLine + ) + m.oldValue = func(ctx context.Context) (*ChargeFlatFeeRunDetailedLine, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ChargeFlatFeeRunDetailedLine.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withChargeFlatFeeRunDetailedLine sets the old ChargeFlatFeeRunDetailedLine of the mutation. +func withChargeFlatFeeRunDetailedLine(node *ChargeFlatFeeRunDetailedLine) chargeflatfeerundetailedlineOption { + return func(m *ChargeFlatFeeRunDetailedLineMutation) { + m.oldValue = func(context.Context) (*ChargeFlatFeeRunDetailedLine, 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 ChargeFlatFeeRunDetailedLineMutation) 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 ChargeFlatFeeRunDetailedLineMutation) 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 ChargeFlatFeeRunDetailedLine entities. +func (m *ChargeFlatFeeRunDetailedLineMutation) 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 *ChargeFlatFeeRunDetailedLineMutation) 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 *ChargeFlatFeeRunDetailedLineMutation) 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().ChargeFlatFeeRunDetailedLine.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetCurrency sets the "currency" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetCurrency(c currencyx.Code) { + m.currency = &c +} + +// Currency returns the value of the "currency" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) Currency() (r currencyx.Code, exists bool) { + v := m.currency + if v == nil { + return + } + return *v, true +} + +// OldCurrency returns the old "currency" field's value of the ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) OldCurrency(ctx context.Context) (v currencyx.Code, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrency is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrency requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrency: %w", err) + } + return oldValue.Currency, nil +} + +// ResetCurrency resets all changes to the "currency" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ResetCurrency() { + m.currency = nil +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetServicePeriodStart(t time.Time) { + m.service_period_start = &t +} + +// ServicePeriodStart returns the value of the "service_period_start" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) ServicePeriodStart() (r time.Time, exists bool) { + v := m.service_period_start + if v == nil { + return + } + return *v, true +} + +// OldServicePeriodStart returns the old "service_period_start" field's value of the ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) OldServicePeriodStart(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldServicePeriodStart is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldServicePeriodStart requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldServicePeriodStart: %w", err) + } + return oldValue.ServicePeriodStart, nil +} + +// ResetServicePeriodStart resets all changes to the "service_period_start" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ResetServicePeriodStart() { + m.service_period_start = nil +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetServicePeriodEnd(t time.Time) { + m.service_period_end = &t +} + +// ServicePeriodEnd returns the value of the "service_period_end" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) ServicePeriodEnd() (r time.Time, exists bool) { + v := m.service_period_end + if v == nil { + return + } + return *v, true +} + +// OldServicePeriodEnd returns the old "service_period_end" field's value of the ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) OldServicePeriodEnd(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldServicePeriodEnd is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldServicePeriodEnd requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldServicePeriodEnd: %w", err) + } + return oldValue.ServicePeriodEnd, nil +} + +// ResetServicePeriodEnd resets all changes to the "service_period_end" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ResetServicePeriodEnd() { + m.service_period_end = nil +} + +// SetQuantity sets the "quantity" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetQuantity(a alpacadecimal.Decimal) { + m.quantity = &a +} + +// Quantity returns the value of the "quantity" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) Quantity() (r alpacadecimal.Decimal, exists bool) { + v := m.quantity + if v == nil { + return + } + return *v, true +} + +// OldQuantity returns the old "quantity" field's value of the ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) OldQuantity(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldQuantity is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldQuantity requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldQuantity: %w", err) + } + return oldValue.Quantity, nil +} + +// ResetQuantity resets all changes to the "quantity" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ResetQuantity() { + m.quantity = nil +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetInvoicingAppExternalID(s string) { + m.invoicing_app_external_id = &s +} + +// InvoicingAppExternalID returns the value of the "invoicing_app_external_id" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) InvoicingAppExternalID() (r string, exists bool) { + v := m.invoicing_app_external_id + if v == nil { + return + } + return *v, true +} + +// OldInvoicingAppExternalID returns the old "invoicing_app_external_id" field's value of the ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) OldInvoicingAppExternalID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoicingAppExternalID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoicingAppExternalID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoicingAppExternalID: %w", err) + } + return oldValue.InvoicingAppExternalID, nil +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ClearInvoicingAppExternalID() { + m.invoicing_app_external_id = nil + m.clearedFields[chargeflatfeerundetailedline.FieldInvoicingAppExternalID] = struct{}{} +} + +// InvoicingAppExternalIDCleared returns if the "invoicing_app_external_id" field was cleared in this mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) InvoicingAppExternalIDCleared() bool { + _, ok := m.clearedFields[chargeflatfeerundetailedline.FieldInvoicingAppExternalID] + return ok +} + +// ResetInvoicingAppExternalID resets all changes to the "invoicing_app_external_id" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ResetInvoicingAppExternalID() { + m.invoicing_app_external_id = nil + delete(m.clearedFields, chargeflatfeerundetailedline.FieldInvoicingAppExternalID) +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetChildUniqueReferenceID(s string) { + m.child_unique_reference_id = &s +} + +// ChildUniqueReferenceID returns the value of the "child_unique_reference_id" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) ChildUniqueReferenceID() (r string, exists bool) { + v := m.child_unique_reference_id + if v == nil { + return + } + return *v, true +} + +// OldChildUniqueReferenceID returns the old "child_unique_reference_id" field's value of the ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) OldChildUniqueReferenceID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldChildUniqueReferenceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldChildUniqueReferenceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldChildUniqueReferenceID: %w", err) + } + return oldValue.ChildUniqueReferenceID, nil +} + +// ResetChildUniqueReferenceID resets all changes to the "child_unique_reference_id" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ResetChildUniqueReferenceID() { + m.child_unique_reference_id = nil +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetPerUnitAmount(a alpacadecimal.Decimal) { + m.per_unit_amount = &a +} + +// PerUnitAmount returns the value of the "per_unit_amount" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) PerUnitAmount() (r alpacadecimal.Decimal, exists bool) { + v := m.per_unit_amount + if v == nil { + return + } + return *v, true +} + +// OldPerUnitAmount returns the old "per_unit_amount" field's value of the ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) OldPerUnitAmount(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPerUnitAmount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPerUnitAmount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPerUnitAmount: %w", err) + } + return oldValue.PerUnitAmount, nil +} + +// ResetPerUnitAmount resets all changes to the "per_unit_amount" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ResetPerUnitAmount() { + m.per_unit_amount = nil +} + +// SetCategory sets the "category" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetCategory(s stddetailedline.Category) { + m.category = &s +} + +// Category returns the value of the "category" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) Category() (r stddetailedline.Category, exists bool) { + v := m.category + if v == nil { + return + } + return *v, true +} + +// OldCategory returns the old "category" field's value of the ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) OldCategory(ctx context.Context) (v stddetailedline.Category, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCategory is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCategory requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCategory: %w", err) + } + return oldValue.Category, nil +} + +// ResetCategory resets all changes to the "category" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ResetCategory() { + m.category = nil +} + +// SetPaymentTerm sets the "payment_term" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetPaymentTerm(ptt productcatalog.PaymentTermType) { + m.payment_term = &ptt +} + +// PaymentTerm returns the value of the "payment_term" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) PaymentTerm() (r productcatalog.PaymentTermType, exists bool) { + v := m.payment_term + if v == nil { + return + } + return *v, true +} + +// OldPaymentTerm returns the old "payment_term" field's value of the ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) OldPaymentTerm(ctx context.Context) (v productcatalog.PaymentTermType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPaymentTerm is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPaymentTerm requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPaymentTerm: %w", err) + } + return oldValue.PaymentTerm, nil +} + +// ResetPaymentTerm resets all changes to the "payment_term" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ResetPaymentTerm() { + m.payment_term = nil +} + +// SetIndex sets the "index" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetIndex(i int) { + m.index = &i + m.addindex = nil +} + +// Index returns the value of the "index" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) Index() (r int, exists bool) { + v := m.index + if v == nil { + return + } + return *v, true +} + +// OldIndex returns the old "index" field's value of the ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) OldIndex(ctx context.Context) (v *int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIndex is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIndex requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIndex: %w", err) + } + return oldValue.Index, nil +} + +// AddIndex adds i to the "index" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) AddIndex(i int) { + if m.addindex != nil { + *m.addindex += i + } else { + m.addindex = &i + } +} + +// AddedIndex returns the value that was added to the "index" field in this mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) AddedIndex() (r int, exists bool) { + v := m.addindex + if v == nil { + return + } + return *v, true +} + +// ClearIndex clears the value of the "index" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ClearIndex() { + m.index = nil + m.addindex = nil + m.clearedFields[chargeflatfeerundetailedline.FieldIndex] = struct{}{} +} + +// IndexCleared returns if the "index" field was cleared in this mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) IndexCleared() bool { + _, ok := m.clearedFields[chargeflatfeerundetailedline.FieldIndex] + return ok +} + +// ResetIndex resets all changes to the "index" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ResetIndex() { + m.index = nil + m.addindex = nil + delete(m.clearedFields, chargeflatfeerundetailedline.FieldIndex) +} + +// SetCreditsApplied sets the "credits_applied" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetCreditsApplied(ca *creditsapplied.CreditsApplied) { + m.credits_applied = &ca +} + +// CreditsApplied returns the value of the "credits_applied" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) CreditsApplied() (r *creditsapplied.CreditsApplied, exists bool) { + v := m.credits_applied + if v == nil { + return + } + return *v, true +} + +// OldCreditsApplied returns the old "credits_applied" field's value of the ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) OldCreditsApplied(ctx context.Context) (v *creditsapplied.CreditsApplied, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreditsApplied is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreditsApplied requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreditsApplied: %w", err) + } + return oldValue.CreditsApplied, nil +} + +// ClearCreditsApplied clears the value of the "credits_applied" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ClearCreditsApplied() { + m.credits_applied = nil + m.clearedFields[chargeflatfeerundetailedline.FieldCreditsApplied] = struct{}{} +} + +// CreditsAppliedCleared returns if the "credits_applied" field was cleared in this mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) CreditsAppliedCleared() bool { + _, ok := m.clearedFields[chargeflatfeerundetailedline.FieldCreditsApplied] + return ok +} + +// ResetCreditsApplied resets all changes to the "credits_applied" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ResetCreditsApplied() { + m.credits_applied = nil + delete(m.clearedFields, chargeflatfeerundetailedline.FieldCreditsApplied) +} + +// SetAnnotations sets the "annotations" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) 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 ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) 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 *ChargeFlatFeeRunDetailedLineMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[chargeflatfeerundetailedline.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[chargeflatfeerundetailedline.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, chargeflatfeerundetailedline.FieldAnnotations) +} + +// SetNamespace sets the "namespace" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) 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 ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) 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 *ChargeFlatFeeRunDetailedLineMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[chargeflatfeerundetailedline.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) MetadataCleared() bool { + _, ok := m.clearedFields[chargeflatfeerundetailedline.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, chargeflatfeerundetailedline.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) 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 ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) 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 *ChargeFlatFeeRunDetailedLineMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) 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 ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) 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 *ChargeFlatFeeRunDetailedLineMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) 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 ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) 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 *ChargeFlatFeeRunDetailedLineMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[chargeflatfeerundetailedline.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[chargeflatfeerundetailedline.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, chargeflatfeerundetailedline.FieldDeletedAt) +} + +// SetName sets the "name" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ClearDescription() { + m.description = nil + m.clearedFields[chargeflatfeerundetailedline.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[chargeflatfeerundetailedline.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, chargeflatfeerundetailedline.FieldDescription) +} + +// SetAmount sets the "amount" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) 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 ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) 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 *ChargeFlatFeeRunDetailedLineMutation) ResetAmount() { + m.amount = nil +} + +// SetTaxesTotal sets the "taxes_total" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetTaxesTotal(a alpacadecimal.Decimal) { + m.taxes_total = &a +} + +// TaxesTotal returns the value of the "taxes_total" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) 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 ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) 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 *ChargeFlatFeeRunDetailedLineMutation) ResetTaxesTotal() { + m.taxes_total = nil +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetTaxesInclusiveTotal(a alpacadecimal.Decimal) { + m.taxes_inclusive_total = &a +} + +// TaxesInclusiveTotal returns the value of the "taxes_inclusive_total" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) 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 ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) 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 *ChargeFlatFeeRunDetailedLineMutation) ResetTaxesInclusiveTotal() { + m.taxes_inclusive_total = nil +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetTaxesExclusiveTotal(a alpacadecimal.Decimal) { + m.taxes_exclusive_total = &a +} + +// TaxesExclusiveTotal returns the value of the "taxes_exclusive_total" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) 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 ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) 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 *ChargeFlatFeeRunDetailedLineMutation) ResetTaxesExclusiveTotal() { + m.taxes_exclusive_total = nil +} + +// SetChargesTotal sets the "charges_total" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetChargesTotal(a alpacadecimal.Decimal) { + m.charges_total = &a +} + +// ChargesTotal returns the value of the "charges_total" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) 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 ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) 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 *ChargeFlatFeeRunDetailedLineMutation) ResetChargesTotal() { + m.charges_total = nil +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetDiscountsTotal(a alpacadecimal.Decimal) { + m.discounts_total = &a +} + +// DiscountsTotal returns the value of the "discounts_total" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) 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 ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) 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 *ChargeFlatFeeRunDetailedLineMutation) ResetDiscountsTotal() { + m.discounts_total = nil +} + +// SetCreditsTotal sets the "credits_total" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetCreditsTotal(a alpacadecimal.Decimal) { + m.credits_total = &a +} + +// CreditsTotal returns the value of the "credits_total" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) 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 ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) 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 *ChargeFlatFeeRunDetailedLineMutation) ResetCreditsTotal() { + m.credits_total = nil +} + +// SetTotal sets the "total" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetTotal(a alpacadecimal.Decimal) { + m.total = &a +} + +// Total returns the value of the "total" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) 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 ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) 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 *ChargeFlatFeeRunDetailedLineMutation) ResetTotal() { + m.total = nil +} + +// SetRunID sets the "run_id" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetRunID(s string) { + m.run = &s +} + +// RunID returns the value of the "run_id" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) 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 ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) 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 *ChargeFlatFeeRunDetailedLineMutation) ResetRunID() { + m.run = nil +} + +// SetPricerReferenceID sets the "pricer_reference_id" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetPricerReferenceID(s string) { + m.pricer_reference_id = &s +} + +// PricerReferenceID returns the value of the "pricer_reference_id" field in the mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) PricerReferenceID() (r string, exists bool) { + v := m.pricer_reference_id + if v == nil { + return + } + return *v, true +} + +// OldPricerReferenceID returns the old "pricer_reference_id" field's value of the ChargeFlatFeeRunDetailedLine entity. +// If the ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) OldPricerReferenceID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPricerReferenceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPricerReferenceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPricerReferenceID: %w", err) + } + return oldValue.PricerReferenceID, nil +} + +// ResetPricerReferenceID resets all changes to the "pricer_reference_id" field. +func (m *ChargeFlatFeeRunDetailedLineMutation) ResetPricerReferenceID() { + m.pricer_reference_id = nil +} + +// ClearRun clears the "run" edge to the ChargeFlatFeeRun entity. +func (m *ChargeFlatFeeRunDetailedLineMutation) ClearRun() { + m.clearedrun = true + m.clearedFields[chargeflatfeerundetailedline.FieldRunID] = struct{}{} +} + +// RunCleared reports if the "run" edge to the ChargeFlatFeeRun entity was cleared. +func (m *ChargeFlatFeeRunDetailedLineMutation) 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 *ChargeFlatFeeRunDetailedLineMutation) RunIDs() (ids []string) { + if id := m.run; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetRun resets all changes to the "run" edge. +func (m *ChargeFlatFeeRunDetailedLineMutation) ResetRun() { + m.run = nil + m.clearedrun = false +} + +// Where appends a list predicates to the ChargeFlatFeeRunDetailedLineMutation builder. +func (m *ChargeFlatFeeRunDetailedLineMutation) Where(ps ...predicate.ChargeFlatFeeRunDetailedLine) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ChargeFlatFeeRunDetailedLineMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ChargeFlatFeeRunDetailedLineMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ChargeFlatFeeRunDetailedLine, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ChargeFlatFeeRunDetailedLineMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ChargeFlatFeeRunDetailedLineMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ChargeFlatFeeRunDetailedLine). +func (m *ChargeFlatFeeRunDetailedLineMutation) 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 *ChargeFlatFeeRunDetailedLineMutation) Fields() []string { + fields := make([]string, 0, 29) + if m.currency != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldCurrency) + } + if m.service_period_start != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldServicePeriodStart) + } + if m.service_period_end != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldServicePeriodEnd) + } + if m.quantity != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldQuantity) + } + if m.invoicing_app_external_id != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldInvoicingAppExternalID) + } + if m.child_unique_reference_id != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldChildUniqueReferenceID) + } + if m.per_unit_amount != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldPerUnitAmount) + } + if m.category != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldCategory) + } + if m.payment_term != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldPaymentTerm) + } + if m.index != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldIndex) + } + if m.credits_applied != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldCreditsApplied) + } + if m.annotations != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldAnnotations) + } + if m.namespace != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldDeletedAt) + } + if m.name != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldName) + } + if m.description != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldDescription) + } + if m.amount != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldAmount) + } + if m.taxes_total != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldTaxesTotal) + } + if m.taxes_inclusive_total != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldTaxesInclusiveTotal) + } + if m.taxes_exclusive_total != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldTaxesExclusiveTotal) + } + if m.charges_total != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldChargesTotal) + } + if m.discounts_total != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldDiscountsTotal) + } + if m.credits_total != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldCreditsTotal) + } + if m.total != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldTotal) + } + if m.run != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldRunID) + } + if m.pricer_reference_id != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldPricerReferenceID) + } + 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 *ChargeFlatFeeRunDetailedLineMutation) Field(name string) (ent.Value, bool) { + switch name { + case chargeflatfeerundetailedline.FieldCurrency: + return m.Currency() + case chargeflatfeerundetailedline.FieldServicePeriodStart: + return m.ServicePeriodStart() + case chargeflatfeerundetailedline.FieldServicePeriodEnd: + return m.ServicePeriodEnd() + case chargeflatfeerundetailedline.FieldQuantity: + return m.Quantity() + case chargeflatfeerundetailedline.FieldInvoicingAppExternalID: + return m.InvoicingAppExternalID() + case chargeflatfeerundetailedline.FieldChildUniqueReferenceID: + return m.ChildUniqueReferenceID() + case chargeflatfeerundetailedline.FieldPerUnitAmount: + return m.PerUnitAmount() + case chargeflatfeerundetailedline.FieldCategory: + return m.Category() + case chargeflatfeerundetailedline.FieldPaymentTerm: + return m.PaymentTerm() + case chargeflatfeerundetailedline.FieldIndex: + return m.Index() + case chargeflatfeerundetailedline.FieldCreditsApplied: + return m.CreditsApplied() + case chargeflatfeerundetailedline.FieldAnnotations: + return m.Annotations() + case chargeflatfeerundetailedline.FieldNamespace: + return m.Namespace() + case chargeflatfeerundetailedline.FieldMetadata: + return m.Metadata() + case chargeflatfeerundetailedline.FieldCreatedAt: + return m.CreatedAt() + case chargeflatfeerundetailedline.FieldUpdatedAt: + return m.UpdatedAt() + case chargeflatfeerundetailedline.FieldDeletedAt: + return m.DeletedAt() + case chargeflatfeerundetailedline.FieldName: + return m.Name() + case chargeflatfeerundetailedline.FieldDescription: + return m.Description() + case chargeflatfeerundetailedline.FieldAmount: + return m.Amount() + case chargeflatfeerundetailedline.FieldTaxesTotal: + return m.TaxesTotal() + case chargeflatfeerundetailedline.FieldTaxesInclusiveTotal: + return m.TaxesInclusiveTotal() + case chargeflatfeerundetailedline.FieldTaxesExclusiveTotal: + return m.TaxesExclusiveTotal() + case chargeflatfeerundetailedline.FieldChargesTotal: + return m.ChargesTotal() + case chargeflatfeerundetailedline.FieldDiscountsTotal: + return m.DiscountsTotal() + case chargeflatfeerundetailedline.FieldCreditsTotal: + return m.CreditsTotal() + case chargeflatfeerundetailedline.FieldTotal: + return m.Total() + case chargeflatfeerundetailedline.FieldRunID: + return m.RunID() + case chargeflatfeerundetailedline.FieldPricerReferenceID: + return m.PricerReferenceID() + } + 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 *ChargeFlatFeeRunDetailedLineMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case chargeflatfeerundetailedline.FieldCurrency: + return m.OldCurrency(ctx) + case chargeflatfeerundetailedline.FieldServicePeriodStart: + return m.OldServicePeriodStart(ctx) + case chargeflatfeerundetailedline.FieldServicePeriodEnd: + return m.OldServicePeriodEnd(ctx) + case chargeflatfeerundetailedline.FieldQuantity: + return m.OldQuantity(ctx) + case chargeflatfeerundetailedline.FieldInvoicingAppExternalID: + return m.OldInvoicingAppExternalID(ctx) + case chargeflatfeerundetailedline.FieldChildUniqueReferenceID: + return m.OldChildUniqueReferenceID(ctx) + case chargeflatfeerundetailedline.FieldPerUnitAmount: + return m.OldPerUnitAmount(ctx) + case chargeflatfeerundetailedline.FieldCategory: + return m.OldCategory(ctx) + case chargeflatfeerundetailedline.FieldPaymentTerm: + return m.OldPaymentTerm(ctx) + case chargeflatfeerundetailedline.FieldIndex: + return m.OldIndex(ctx) + case chargeflatfeerundetailedline.FieldCreditsApplied: + return m.OldCreditsApplied(ctx) + case chargeflatfeerundetailedline.FieldAnnotations: + return m.OldAnnotations(ctx) + case chargeflatfeerundetailedline.FieldNamespace: + return m.OldNamespace(ctx) + case chargeflatfeerundetailedline.FieldMetadata: + return m.OldMetadata(ctx) + case chargeflatfeerundetailedline.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case chargeflatfeerundetailedline.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case chargeflatfeerundetailedline.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case chargeflatfeerundetailedline.FieldName: + return m.OldName(ctx) + case chargeflatfeerundetailedline.FieldDescription: + return m.OldDescription(ctx) + case chargeflatfeerundetailedline.FieldAmount: + return m.OldAmount(ctx) + case chargeflatfeerundetailedline.FieldTaxesTotal: + return m.OldTaxesTotal(ctx) + case chargeflatfeerundetailedline.FieldTaxesInclusiveTotal: + return m.OldTaxesInclusiveTotal(ctx) + case chargeflatfeerundetailedline.FieldTaxesExclusiveTotal: + return m.OldTaxesExclusiveTotal(ctx) + case chargeflatfeerundetailedline.FieldChargesTotal: + return m.OldChargesTotal(ctx) + case chargeflatfeerundetailedline.FieldDiscountsTotal: + return m.OldDiscountsTotal(ctx) + case chargeflatfeerundetailedline.FieldCreditsTotal: + return m.OldCreditsTotal(ctx) + case chargeflatfeerundetailedline.FieldTotal: + return m.OldTotal(ctx) + case chargeflatfeerundetailedline.FieldRunID: + return m.OldRunID(ctx) + case chargeflatfeerundetailedline.FieldPricerReferenceID: + return m.OldPricerReferenceID(ctx) + } + return nil, fmt.Errorf("unknown ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) SetField(name string, value ent.Value) error { + switch name { + case chargeflatfeerundetailedline.FieldCurrency: + v, ok := value.(currencyx.Code) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrency(v) + return nil + case chargeflatfeerundetailedline.FieldServicePeriodStart: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetServicePeriodStart(v) + return nil + case chargeflatfeerundetailedline.FieldServicePeriodEnd: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetServicePeriodEnd(v) + return nil + case chargeflatfeerundetailedline.FieldQuantity: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetQuantity(v) + return nil + case chargeflatfeerundetailedline.FieldInvoicingAppExternalID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoicingAppExternalID(v) + return nil + case chargeflatfeerundetailedline.FieldChildUniqueReferenceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChildUniqueReferenceID(v) + return nil + case chargeflatfeerundetailedline.FieldPerUnitAmount: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPerUnitAmount(v) + return nil + case chargeflatfeerundetailedline.FieldCategory: + v, ok := value.(stddetailedline.Category) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCategory(v) + return nil + case chargeflatfeerundetailedline.FieldPaymentTerm: + v, ok := value.(productcatalog.PaymentTermType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPaymentTerm(v) + return nil + case chargeflatfeerundetailedline.FieldIndex: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIndex(v) + return nil + case chargeflatfeerundetailedline.FieldCreditsApplied: + v, ok := value.(*creditsapplied.CreditsApplied) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreditsApplied(v) + return nil + case chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case chargeflatfeerundetailedline.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case chargeflatfeerundetailedline.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.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 chargeflatfeerundetailedline.FieldRunID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRunID(v) + return nil + case chargeflatfeerundetailedline.FieldPricerReferenceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPricerReferenceID(v) + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRunDetailedLine field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) AddedFields() []string { + var fields []string + if m.addindex != nil { + fields = append(fields, chargeflatfeerundetailedline.FieldIndex) + } + return fields +} + +// 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 *ChargeFlatFeeRunDetailedLineMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case chargeflatfeerundetailedline.FieldIndex: + return m.AddedIndex() + } + 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 *ChargeFlatFeeRunDetailedLineMutation) AddField(name string, value ent.Value) error { + switch name { + case chargeflatfeerundetailedline.FieldIndex: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddIndex(v) + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRunDetailedLine numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(chargeflatfeerundetailedline.FieldInvoicingAppExternalID) { + fields = append(fields, chargeflatfeerundetailedline.FieldInvoicingAppExternalID) + } + if m.FieldCleared(chargeflatfeerundetailedline.FieldIndex) { + fields = append(fields, chargeflatfeerundetailedline.FieldIndex) + } + if m.FieldCleared(chargeflatfeerundetailedline.FieldCreditsApplied) { + fields = append(fields, chargeflatfeerundetailedline.FieldCreditsApplied) + } + if m.FieldCleared(chargeflatfeerundetailedline.FieldAnnotations) { + fields = append(fields, chargeflatfeerundetailedline.FieldAnnotations) + } + if m.FieldCleared(chargeflatfeerundetailedline.FieldMetadata) { + fields = append(fields, chargeflatfeerundetailedline.FieldMetadata) + } + if m.FieldCleared(chargeflatfeerundetailedline.FieldDeletedAt) { + fields = append(fields, chargeflatfeerundetailedline.FieldDeletedAt) + } + if m.FieldCleared(chargeflatfeerundetailedline.FieldDescription) { + fields = append(fields, chargeflatfeerundetailedline.FieldDescription) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) 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 *ChargeFlatFeeRunDetailedLineMutation) ClearField(name string) error { + switch name { + case chargeflatfeerundetailedline.FieldInvoicingAppExternalID: + m.ClearInvoicingAppExternalID() + return nil + case chargeflatfeerundetailedline.FieldIndex: + m.ClearIndex() + return nil + case chargeflatfeerundetailedline.FieldCreditsApplied: + m.ClearCreditsApplied() + return nil + case chargeflatfeerundetailedline.FieldAnnotations: + m.ClearAnnotations() + return nil + case chargeflatfeerundetailedline.FieldMetadata: + m.ClearMetadata() + return nil + case chargeflatfeerundetailedline.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case chargeflatfeerundetailedline.FieldDescription: + m.ClearDescription() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) ResetField(name string) error { + switch name { + case chargeflatfeerundetailedline.FieldCurrency: + m.ResetCurrency() + return nil + case chargeflatfeerundetailedline.FieldServicePeriodStart: + m.ResetServicePeriodStart() + return nil + case chargeflatfeerundetailedline.FieldServicePeriodEnd: + m.ResetServicePeriodEnd() + return nil + case chargeflatfeerundetailedline.FieldQuantity: + m.ResetQuantity() + return nil + case chargeflatfeerundetailedline.FieldInvoicingAppExternalID: + m.ResetInvoicingAppExternalID() + return nil + case chargeflatfeerundetailedline.FieldChildUniqueReferenceID: + m.ResetChildUniqueReferenceID() + return nil + case chargeflatfeerundetailedline.FieldPerUnitAmount: + m.ResetPerUnitAmount() + return nil + case chargeflatfeerundetailedline.FieldCategory: + m.ResetCategory() + return nil + case chargeflatfeerundetailedline.FieldPaymentTerm: + m.ResetPaymentTerm() + return nil + case chargeflatfeerundetailedline.FieldIndex: + m.ResetIndex() + return nil + case chargeflatfeerundetailedline.FieldCreditsApplied: + m.ResetCreditsApplied() + return nil + case chargeflatfeerundetailedline.FieldAnnotations: + m.ResetAnnotations() + return nil + case chargeflatfeerundetailedline.FieldNamespace: + m.ResetNamespace() + return nil + case chargeflatfeerundetailedline.FieldMetadata: + m.ResetMetadata() + return nil + case chargeflatfeerundetailedline.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case chargeflatfeerundetailedline.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case chargeflatfeerundetailedline.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case chargeflatfeerundetailedline.FieldName: + m.ResetName() + return nil + case chargeflatfeerundetailedline.FieldDescription: + m.ResetDescription() + return nil + case chargeflatfeerundetailedline.FieldAmount: + m.ResetAmount() + return nil + case chargeflatfeerundetailedline.FieldTaxesTotal: + m.ResetTaxesTotal() + return nil + case chargeflatfeerundetailedline.FieldTaxesInclusiveTotal: + m.ResetTaxesInclusiveTotal() + return nil + case chargeflatfeerundetailedline.FieldTaxesExclusiveTotal: + m.ResetTaxesExclusiveTotal() + return nil + case chargeflatfeerundetailedline.FieldChargesTotal: + m.ResetChargesTotal() + return nil + case chargeflatfeerundetailedline.FieldDiscountsTotal: + m.ResetDiscountsTotal() + return nil + case chargeflatfeerundetailedline.FieldCreditsTotal: + m.ResetCreditsTotal() + return nil + case chargeflatfeerundetailedline.FieldTotal: + m.ResetTotal() + return nil + case chargeflatfeerundetailedline.FieldRunID: + m.ResetRunID() + return nil + case chargeflatfeerundetailedline.FieldPricerReferenceID: + m.ResetPricerReferenceID() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRunDetailedLine field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.run != nil { + edges = append(edges, chargeflatfeerundetailedline.EdgeRun) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) AddedIDs(name string) []ent.Value { + switch name { + case chargeflatfeerundetailedline.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 *ChargeFlatFeeRunDetailedLineMutation) 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 *ChargeFlatFeeRunDetailedLineMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedrun { + edges = append(edges, chargeflatfeerundetailedline.EdgeRun) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ChargeFlatFeeRunDetailedLineMutation) EdgeCleared(name string) bool { + switch name { + case chargeflatfeerundetailedline.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 *ChargeFlatFeeRunDetailedLineMutation) ClearEdge(name string) error { + switch name { + case chargeflatfeerundetailedline.EdgeRun: + m.ClearRun() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRunDetailedLine 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 *ChargeFlatFeeRunDetailedLineMutation) ResetEdge(name string) error { + switch name { + case chargeflatfeerundetailedline.EdgeRun: + m.ResetRun() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRunDetailedLine edge %s", name) +} + +// ChargeFlatFeeRunInvoicedUsageMutation represents an operation that mutates the ChargeFlatFeeRunInvoicedUsage nodes in the graph. +type ChargeFlatFeeRunInvoicedUsageMutation struct { + config + op Op + typ string + id *string + 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 + 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) (*ChargeFlatFeeRunInvoicedUsage, error) + predicates []predicate.ChargeFlatFeeRunInvoicedUsage +} + +var _ ent.Mutation = (*ChargeFlatFeeRunInvoicedUsageMutation)(nil) + +// chargeflatfeeruninvoicedusageOption allows management of the mutation configuration using functional options. +type chargeflatfeeruninvoicedusageOption func(*ChargeFlatFeeRunInvoicedUsageMutation) + +// newChargeFlatFeeRunInvoicedUsageMutation creates new mutation for the ChargeFlatFeeRunInvoicedUsage entity. +func newChargeFlatFeeRunInvoicedUsageMutation(c config, op Op, opts ...chargeflatfeeruninvoicedusageOption) *ChargeFlatFeeRunInvoicedUsageMutation { + m := &ChargeFlatFeeRunInvoicedUsageMutation{ + config: c, + op: op, + typ: TypeChargeFlatFeeRunInvoicedUsage, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withChargeFlatFeeRunInvoicedUsageID sets the ID field of the mutation. +func withChargeFlatFeeRunInvoicedUsageID(id string) chargeflatfeeruninvoicedusageOption { + return func(m *ChargeFlatFeeRunInvoicedUsageMutation) { + var ( + err error + once sync.Once + value *ChargeFlatFeeRunInvoicedUsage + ) + m.oldValue = func(ctx context.Context) (*ChargeFlatFeeRunInvoicedUsage, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ChargeFlatFeeRunInvoicedUsage.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withChargeFlatFeeRunInvoicedUsage sets the old ChargeFlatFeeRunInvoicedUsage of the mutation. +func withChargeFlatFeeRunInvoicedUsage(node *ChargeFlatFeeRunInvoicedUsage) chargeflatfeeruninvoicedusageOption { + return func(m *ChargeFlatFeeRunInvoicedUsageMutation) { + m.oldValue = func(context.Context) (*ChargeFlatFeeRunInvoicedUsage, 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 ChargeFlatFeeRunInvoicedUsageMutation) 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 ChargeFlatFeeRunInvoicedUsageMutation) 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 ChargeFlatFeeRunInvoicedUsage entities. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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().ChargeFlatFeeRunInvoicedUsage.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) SetServicePeriodFrom(t time.Time) { + m.service_period_from = &t +} + +// ServicePeriodFrom returns the value of the "service_period_from" field in the mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 ChargeFlatFeeRunInvoicedUsage entity. +// If the ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) ResetServicePeriodFrom() { + m.service_period_from = nil +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) SetServicePeriodTo(t time.Time) { + m.service_period_to = &t +} + +// ServicePeriodTo returns the value of the "service_period_to" field in the mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 ChargeFlatFeeRunInvoicedUsage entity. +// If the ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) ResetServicePeriodTo() { + m.service_period_to = nil +} + +// SetLedgerTransactionGroupID sets the "ledger_transaction_group_id" field. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 ChargeFlatFeeRunInvoicedUsage entity. +// If the ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) ClearLedgerTransactionGroupID() { + m.ledger_transaction_group_id = nil + m.clearedFields[chargeflatfeeruninvoicedusage.FieldLedgerTransactionGroupID] = struct{}{} +} + +// LedgerTransactionGroupIDCleared returns if the "ledger_transaction_group_id" field was cleared in this mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) LedgerTransactionGroupIDCleared() bool { + _, ok := m.clearedFields[chargeflatfeeruninvoicedusage.FieldLedgerTransactionGroupID] + return ok +} + +// ResetLedgerTransactionGroupID resets all changes to the "ledger_transaction_group_id" field. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) ResetLedgerTransactionGroupID() { + m.ledger_transaction_group_id = nil + delete(m.clearedFields, chargeflatfeeruninvoicedusage.FieldLedgerTransactionGroupID) +} + +// SetNamespace sets the "namespace" field. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 ChargeFlatFeeRunInvoicedUsage entity. +// If the ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 ChargeFlatFeeRunInvoicedUsage entity. +// If the ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 ChargeFlatFeeRunInvoicedUsage entity. +// If the ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 ChargeFlatFeeRunInvoicedUsage entity. +// If the ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[chargeflatfeeruninvoicedusage.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[chargeflatfeeruninvoicedusage.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, chargeflatfeeruninvoicedusage.FieldDeletedAt) +} + +// SetAnnotations sets the "annotations" field. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 ChargeFlatFeeRunInvoicedUsage entity. +// If the ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[chargeflatfeeruninvoicedusage.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[chargeflatfeeruninvoicedusage.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, chargeflatfeeruninvoicedusage.FieldAnnotations) +} + +// SetAmount sets the "amount" field. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 ChargeFlatFeeRunInvoicedUsage entity. +// If the ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) ResetAmount() { + m.amount = nil +} + +// SetTaxesTotal sets the "taxes_total" field. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) SetTaxesTotal(a alpacadecimal.Decimal) { + m.taxes_total = &a +} + +// TaxesTotal returns the value of the "taxes_total" field in the mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 ChargeFlatFeeRunInvoicedUsage entity. +// If the ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) ResetTaxesTotal() { + m.taxes_total = nil +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) SetTaxesInclusiveTotal(a alpacadecimal.Decimal) { + m.taxes_inclusive_total = &a +} + +// TaxesInclusiveTotal returns the value of the "taxes_inclusive_total" field in the mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 ChargeFlatFeeRunInvoicedUsage entity. +// If the ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) ResetTaxesInclusiveTotal() { + m.taxes_inclusive_total = nil +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) SetTaxesExclusiveTotal(a alpacadecimal.Decimal) { + m.taxes_exclusive_total = &a +} + +// TaxesExclusiveTotal returns the value of the "taxes_exclusive_total" field in the mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 ChargeFlatFeeRunInvoicedUsage entity. +// If the ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) ResetTaxesExclusiveTotal() { + m.taxes_exclusive_total = nil +} + +// SetChargesTotal sets the "charges_total" field. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) SetChargesTotal(a alpacadecimal.Decimal) { + m.charges_total = &a +} + +// ChargesTotal returns the value of the "charges_total" field in the mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 ChargeFlatFeeRunInvoicedUsage entity. +// If the ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) ResetChargesTotal() { + m.charges_total = nil +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) SetDiscountsTotal(a alpacadecimal.Decimal) { + m.discounts_total = &a +} + +// DiscountsTotal returns the value of the "discounts_total" field in the mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 ChargeFlatFeeRunInvoicedUsage entity. +// If the ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) ResetDiscountsTotal() { + m.discounts_total = nil +} + +// SetCreditsTotal sets the "credits_total" field. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) SetCreditsTotal(a alpacadecimal.Decimal) { + m.credits_total = &a +} + +// CreditsTotal returns the value of the "credits_total" field in the mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 ChargeFlatFeeRunInvoicedUsage entity. +// If the ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) ResetCreditsTotal() { + m.credits_total = nil +} + +// SetTotal sets the "total" field. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) SetTotal(a alpacadecimal.Decimal) { + m.total = &a +} + +// Total returns the value of the "total" field in the mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 ChargeFlatFeeRunInvoicedUsage entity. +// If the ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) ResetTotal() { + m.total = nil +} + +// SetRunID sets the "run_id" field. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) SetRunID(s string) { + m.run = &s +} + +// RunID returns the value of the "run_id" field in the mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 ChargeFlatFeeRunInvoicedUsage entity. +// If the ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) ResetRunID() { + m.run = nil +} + +// ClearRun clears the "run" edge to the ChargeFlatFeeRun entity. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) ClearRun() { + m.clearedrun = true + m.clearedFields[chargeflatfeeruninvoicedusage.FieldRunID] = struct{}{} +} + +// RunCleared reports if the "run" edge to the ChargeFlatFeeRun entity was cleared. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) RunIDs() (ids []string) { + if id := m.run; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetRun resets all changes to the "run" edge. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) ResetRun() { + m.run = nil + m.clearedrun = false +} + +// Where appends a list predicates to the ChargeFlatFeeRunInvoicedUsageMutation builder. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) Where(ps ...predicate.ChargeFlatFeeRunInvoicedUsage) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ChargeFlatFeeRunInvoicedUsageMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ChargeFlatFeeRunInvoicedUsage, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ChargeFlatFeeRunInvoicedUsage). +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) Fields() []string { + fields := make([]string, 0, 17) + if m.service_period_from != nil { + fields = append(fields, chargeflatfeeruninvoicedusage.FieldServicePeriodFrom) + } + if m.service_period_to != nil { + fields = append(fields, chargeflatfeeruninvoicedusage.FieldServicePeriodTo) + } + if m.ledger_transaction_group_id != nil { + fields = append(fields, chargeflatfeeruninvoicedusage.FieldLedgerTransactionGroupID) + } + if m.namespace != nil { + fields = append(fields, chargeflatfeeruninvoicedusage.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, chargeflatfeeruninvoicedusage.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, chargeflatfeeruninvoicedusage.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, chargeflatfeeruninvoicedusage.FieldDeletedAt) + } + if m.annotations != nil { + fields = append(fields, chargeflatfeeruninvoicedusage.FieldAnnotations) + } + if m.amount != nil { + fields = append(fields, chargeflatfeeruninvoicedusage.FieldAmount) + } + if m.taxes_total != nil { + fields = append(fields, chargeflatfeeruninvoicedusage.FieldTaxesTotal) + } + if m.taxes_inclusive_total != nil { + fields = append(fields, chargeflatfeeruninvoicedusage.FieldTaxesInclusiveTotal) + } + if m.taxes_exclusive_total != nil { + fields = append(fields, chargeflatfeeruninvoicedusage.FieldTaxesExclusiveTotal) + } + if m.charges_total != nil { + fields = append(fields, chargeflatfeeruninvoicedusage.FieldChargesTotal) + } + if m.discounts_total != nil { + fields = append(fields, chargeflatfeeruninvoicedusage.FieldDiscountsTotal) + } + if m.credits_total != nil { + fields = append(fields, chargeflatfeeruninvoicedusage.FieldCreditsTotal) + } + if m.total != nil { + fields = append(fields, chargeflatfeeruninvoicedusage.FieldTotal) + } + if m.run != nil { + fields = append(fields, chargeflatfeeruninvoicedusage.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 *ChargeFlatFeeRunInvoicedUsageMutation) Field(name string) (ent.Value, bool) { + switch name { + case chargeflatfeeruninvoicedusage.FieldServicePeriodFrom: + return m.ServicePeriodFrom() + case chargeflatfeeruninvoicedusage.FieldServicePeriodTo: + return m.ServicePeriodTo() + case chargeflatfeeruninvoicedusage.FieldLedgerTransactionGroupID: + return m.LedgerTransactionGroupID() + case chargeflatfeeruninvoicedusage.FieldNamespace: + return m.Namespace() + case chargeflatfeeruninvoicedusage.FieldCreatedAt: + return m.CreatedAt() + case chargeflatfeeruninvoicedusage.FieldUpdatedAt: + return m.UpdatedAt() + case chargeflatfeeruninvoicedusage.FieldDeletedAt: + return m.DeletedAt() + case chargeflatfeeruninvoicedusage.FieldAnnotations: + return m.Annotations() + case chargeflatfeeruninvoicedusage.FieldAmount: + return m.Amount() + case chargeflatfeeruninvoicedusage.FieldTaxesTotal: + return m.TaxesTotal() + case chargeflatfeeruninvoicedusage.FieldTaxesInclusiveTotal: + return m.TaxesInclusiveTotal() + case chargeflatfeeruninvoicedusage.FieldTaxesExclusiveTotal: + return m.TaxesExclusiveTotal() + case chargeflatfeeruninvoicedusage.FieldChargesTotal: + return m.ChargesTotal() + case chargeflatfeeruninvoicedusage.FieldDiscountsTotal: + return m.DiscountsTotal() + case chargeflatfeeruninvoicedusage.FieldCreditsTotal: + return m.CreditsTotal() + case chargeflatfeeruninvoicedusage.FieldTotal: + return m.Total() + case chargeflatfeeruninvoicedusage.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 *ChargeFlatFeeRunInvoicedUsageMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case chargeflatfeeruninvoicedusage.FieldServicePeriodFrom: + return m.OldServicePeriodFrom(ctx) + case chargeflatfeeruninvoicedusage.FieldServicePeriodTo: + return m.OldServicePeriodTo(ctx) + case chargeflatfeeruninvoicedusage.FieldLedgerTransactionGroupID: + return m.OldLedgerTransactionGroupID(ctx) + case chargeflatfeeruninvoicedusage.FieldNamespace: + return m.OldNamespace(ctx) + case chargeflatfeeruninvoicedusage.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case chargeflatfeeruninvoicedusage.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case chargeflatfeeruninvoicedusage.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case chargeflatfeeruninvoicedusage.FieldAnnotations: + return m.OldAnnotations(ctx) + case chargeflatfeeruninvoicedusage.FieldAmount: + return m.OldAmount(ctx) + case chargeflatfeeruninvoicedusage.FieldTaxesTotal: + return m.OldTaxesTotal(ctx) + case chargeflatfeeruninvoicedusage.FieldTaxesInclusiveTotal: + return m.OldTaxesInclusiveTotal(ctx) + case chargeflatfeeruninvoicedusage.FieldTaxesExclusiveTotal: + return m.OldTaxesExclusiveTotal(ctx) + case chargeflatfeeruninvoicedusage.FieldChargesTotal: + return m.OldChargesTotal(ctx) + case chargeflatfeeruninvoicedusage.FieldDiscountsTotal: + return m.OldDiscountsTotal(ctx) + case chargeflatfeeruninvoicedusage.FieldCreditsTotal: + return m.OldCreditsTotal(ctx) + case chargeflatfeeruninvoicedusage.FieldTotal: + return m.OldTotal(ctx) + case chargeflatfeeruninvoicedusage.FieldRunID: + return m.OldRunID(ctx) + } + return nil, fmt.Errorf("unknown ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsageMutation) SetField(name string, value ent.Value) error { + switch name { + case chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.FieldLedgerTransactionGroupID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLedgerTransactionGroupID(v) + return nil + case chargeflatfeeruninvoicedusage.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 chargeflatfeeruninvoicedusage.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 ChargeFlatFeeRunInvoicedUsage field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown ChargeFlatFeeRunInvoicedUsage numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(chargeflatfeeruninvoicedusage.FieldLedgerTransactionGroupID) { + fields = append(fields, chargeflatfeeruninvoicedusage.FieldLedgerTransactionGroupID) + } + if m.FieldCleared(chargeflatfeeruninvoicedusage.FieldDeletedAt) { + fields = append(fields, chargeflatfeeruninvoicedusage.FieldDeletedAt) + } + if m.FieldCleared(chargeflatfeeruninvoicedusage.FieldAnnotations) { + fields = append(fields, chargeflatfeeruninvoicedusage.FieldAnnotations) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) ClearField(name string) error { + switch name { + case chargeflatfeeruninvoicedusage.FieldLedgerTransactionGroupID: + m.ClearLedgerTransactionGroupID() + return nil + case chargeflatfeeruninvoicedusage.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case chargeflatfeeruninvoicedusage.FieldAnnotations: + m.ClearAnnotations() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsageMutation) ResetField(name string) error { + switch name { + case chargeflatfeeruninvoicedusage.FieldServicePeriodFrom: + m.ResetServicePeriodFrom() + return nil + case chargeflatfeeruninvoicedusage.FieldServicePeriodTo: + m.ResetServicePeriodTo() + return nil + case chargeflatfeeruninvoicedusage.FieldLedgerTransactionGroupID: + m.ResetLedgerTransactionGroupID() + return nil + case chargeflatfeeruninvoicedusage.FieldNamespace: + m.ResetNamespace() + return nil + case chargeflatfeeruninvoicedusage.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case chargeflatfeeruninvoicedusage.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case chargeflatfeeruninvoicedusage.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case chargeflatfeeruninvoicedusage.FieldAnnotations: + m.ResetAnnotations() + return nil + case chargeflatfeeruninvoicedusage.FieldAmount: + m.ResetAmount() + return nil + case chargeflatfeeruninvoicedusage.FieldTaxesTotal: + m.ResetTaxesTotal() + return nil + case chargeflatfeeruninvoicedusage.FieldTaxesInclusiveTotal: + m.ResetTaxesInclusiveTotal() + return nil + case chargeflatfeeruninvoicedusage.FieldTaxesExclusiveTotal: + m.ResetTaxesExclusiveTotal() + return nil + case chargeflatfeeruninvoicedusage.FieldChargesTotal: + m.ResetChargesTotal() + return nil + case chargeflatfeeruninvoicedusage.FieldDiscountsTotal: + m.ResetDiscountsTotal() + return nil + case chargeflatfeeruninvoicedusage.FieldCreditsTotal: + m.ResetCreditsTotal() + return nil + case chargeflatfeeruninvoicedusage.FieldTotal: + m.ResetTotal() + return nil + case chargeflatfeeruninvoicedusage.FieldRunID: + m.ResetRunID() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRunInvoicedUsage field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.run != nil { + edges = append(edges, chargeflatfeeruninvoicedusage.EdgeRun) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) AddedIDs(name string) []ent.Value { + switch name { + case chargeflatfeeruninvoicedusage.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 *ChargeFlatFeeRunInvoicedUsageMutation) 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 *ChargeFlatFeeRunInvoicedUsageMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedrun { + edges = append(edges, chargeflatfeeruninvoicedusage.EdgeRun) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ChargeFlatFeeRunInvoicedUsageMutation) EdgeCleared(name string) bool { + switch name { + case chargeflatfeeruninvoicedusage.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 *ChargeFlatFeeRunInvoicedUsageMutation) ClearEdge(name string) error { + switch name { + case chargeflatfeeruninvoicedusage.EdgeRun: + m.ClearRun() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRunInvoicedUsage 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 *ChargeFlatFeeRunInvoicedUsageMutation) ResetEdge(name string) error { + switch name { + case chargeflatfeeruninvoicedusage.EdgeRun: + m.ResetRun() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRunInvoicedUsage edge %s", name) +} + +// ChargeFlatFeeRunPaymentMutation represents an operation that mutates the ChargeFlatFeeRunPayment nodes in the graph. +type ChargeFlatFeeRunPaymentMutation struct { + config + op Op + typ string + id *string + invoice_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{} + billing_invoice_line *string + clearedbilling_invoice_line bool + run *string + clearedrun bool + done bool + oldValue func(context.Context) (*ChargeFlatFeeRunPayment, error) + predicates []predicate.ChargeFlatFeeRunPayment +} + +var _ ent.Mutation = (*ChargeFlatFeeRunPaymentMutation)(nil) + +// chargeflatfeerunpaymentOption allows management of the mutation configuration using functional options. +type chargeflatfeerunpaymentOption func(*ChargeFlatFeeRunPaymentMutation) + +// newChargeFlatFeeRunPaymentMutation creates new mutation for the ChargeFlatFeeRunPayment entity. +func newChargeFlatFeeRunPaymentMutation(c config, op Op, opts ...chargeflatfeerunpaymentOption) *ChargeFlatFeeRunPaymentMutation { + m := &ChargeFlatFeeRunPaymentMutation{ + config: c, + op: op, + typ: TypeChargeFlatFeeRunPayment, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withChargeFlatFeeRunPaymentID sets the ID field of the mutation. +func withChargeFlatFeeRunPaymentID(id string) chargeflatfeerunpaymentOption { + return func(m *ChargeFlatFeeRunPaymentMutation) { + var ( + err error + once sync.Once + value *ChargeFlatFeeRunPayment + ) + m.oldValue = func(ctx context.Context) (*ChargeFlatFeeRunPayment, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ChargeFlatFeeRunPayment.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withChargeFlatFeeRunPayment sets the old ChargeFlatFeeRunPayment of the mutation. +func withChargeFlatFeeRunPayment(node *ChargeFlatFeeRunPayment) chargeflatfeerunpaymentOption { + return func(m *ChargeFlatFeeRunPaymentMutation) { + m.oldValue = func(context.Context) (*ChargeFlatFeeRunPayment, 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 ChargeFlatFeeRunPaymentMutation) 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 ChargeFlatFeeRunPaymentMutation) 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 ChargeFlatFeeRunPayment entities. +func (m *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) 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().ChargeFlatFeeRunPayment.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 *ChargeFlatFeeRunPaymentMutation) SetLineID(s string) { + m.billing_invoice_line = &s +} + +// LineID returns the value of the "line_id" field in the mutation. +func (m *ChargeFlatFeeRunPaymentMutation) LineID() (r string, exists bool) { + v := m.billing_invoice_line + if v == nil { + return + } + return *v, true +} + +// OldLineID returns the old "line_id" field's value of the ChargeFlatFeeRunPayment entity. +// If the ChargeFlatFeeRunPayment 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 *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) ResetLineID() { + m.billing_invoice_line = nil +} + +// SetInvoiceID sets the "invoice_id" field. +func (m *ChargeFlatFeeRunPaymentMutation) SetInvoiceID(s string) { + m.invoice_id = &s +} + +// InvoiceID returns the value of the "invoice_id" field in the mutation. +func (m *ChargeFlatFeeRunPaymentMutation) InvoiceID() (r string, exists bool) { + v := m.invoice_id + if v == nil { + return + } + return *v, true +} + +// OldInvoiceID returns the old "invoice_id" field's value of the ChargeFlatFeeRunPayment entity. +// If the ChargeFlatFeeRunPayment 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 *ChargeFlatFeeRunPaymentMutation) OldInvoiceID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceID: %w", err) + } + return oldValue.InvoiceID, nil +} + +// ResetInvoiceID resets all changes to the "invoice_id" field. +func (m *ChargeFlatFeeRunPaymentMutation) ResetInvoiceID() { + m.invoice_id = nil +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (m *ChargeFlatFeeRunPaymentMutation) SetServicePeriodFrom(t time.Time) { + m.service_period_from = &t +} + +// ServicePeriodFrom returns the value of the "service_period_from" field in the mutation. +func (m *ChargeFlatFeeRunPaymentMutation) 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 ChargeFlatFeeRunPayment entity. +// If the ChargeFlatFeeRunPayment 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 *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) ResetServicePeriodFrom() { + m.service_period_from = nil +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (m *ChargeFlatFeeRunPaymentMutation) SetServicePeriodTo(t time.Time) { + m.service_period_to = &t +} + +// ServicePeriodTo returns the value of the "service_period_to" field in the mutation. +func (m *ChargeFlatFeeRunPaymentMutation) 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 ChargeFlatFeeRunPayment entity. +// If the ChargeFlatFeeRunPayment 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 *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) ResetServicePeriodTo() { + m.service_period_to = nil +} + +// SetStatus sets the "status" field. +func (m *ChargeFlatFeeRunPaymentMutation) SetStatus(pa payment.Status) { + m.status = &pa +} + +// Status returns the value of the "status" field in the mutation. +func (m *ChargeFlatFeeRunPaymentMutation) 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 ChargeFlatFeeRunPayment entity. +// If the ChargeFlatFeeRunPayment 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 *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) ResetStatus() { + m.status = nil +} + +// SetAmount sets the "amount" field. +func (m *ChargeFlatFeeRunPaymentMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *ChargeFlatFeeRunPaymentMutation) 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 ChargeFlatFeeRunPayment entity. +// If the ChargeFlatFeeRunPayment 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 *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) ResetAmount() { + m.amount = nil +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (m *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) 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 ChargeFlatFeeRunPayment entity. +// If the ChargeFlatFeeRunPayment 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 *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) ClearAuthorizedTransactionGroupID() { + m.authorized_transaction_group_id = nil + m.clearedFields[chargeflatfeerunpayment.FieldAuthorizedTransactionGroupID] = struct{}{} +} + +// AuthorizedTransactionGroupIDCleared returns if the "authorized_transaction_group_id" field was cleared in this mutation. +func (m *ChargeFlatFeeRunPaymentMutation) AuthorizedTransactionGroupIDCleared() bool { + _, ok := m.clearedFields[chargeflatfeerunpayment.FieldAuthorizedTransactionGroupID] + return ok +} + +// ResetAuthorizedTransactionGroupID resets all changes to the "authorized_transaction_group_id" field. +func (m *ChargeFlatFeeRunPaymentMutation) ResetAuthorizedTransactionGroupID() { + m.authorized_transaction_group_id = nil + delete(m.clearedFields, chargeflatfeerunpayment.FieldAuthorizedTransactionGroupID) +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (m *ChargeFlatFeeRunPaymentMutation) SetAuthorizedAt(t time.Time) { + m.authorized_at = &t +} + +// AuthorizedAt returns the value of the "authorized_at" field in the mutation. +func (m *ChargeFlatFeeRunPaymentMutation) 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 ChargeFlatFeeRunPayment entity. +// If the ChargeFlatFeeRunPayment 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 *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) ClearAuthorizedAt() { + m.authorized_at = nil + m.clearedFields[chargeflatfeerunpayment.FieldAuthorizedAt] = struct{}{} +} + +// AuthorizedAtCleared returns if the "authorized_at" field was cleared in this mutation. +func (m *ChargeFlatFeeRunPaymentMutation) AuthorizedAtCleared() bool { + _, ok := m.clearedFields[chargeflatfeerunpayment.FieldAuthorizedAt] + return ok +} + +// ResetAuthorizedAt resets all changes to the "authorized_at" field. +func (m *ChargeFlatFeeRunPaymentMutation) ResetAuthorizedAt() { + m.authorized_at = nil + delete(m.clearedFields, chargeflatfeerunpayment.FieldAuthorizedAt) +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (m *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) 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 ChargeFlatFeeRunPayment entity. +// If the ChargeFlatFeeRunPayment 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 *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) ClearSettledTransactionGroupID() { + m.settled_transaction_group_id = nil + m.clearedFields[chargeflatfeerunpayment.FieldSettledTransactionGroupID] = struct{}{} +} + +// SettledTransactionGroupIDCleared returns if the "settled_transaction_group_id" field was cleared in this mutation. +func (m *ChargeFlatFeeRunPaymentMutation) SettledTransactionGroupIDCleared() bool { + _, ok := m.clearedFields[chargeflatfeerunpayment.FieldSettledTransactionGroupID] + return ok +} + +// ResetSettledTransactionGroupID resets all changes to the "settled_transaction_group_id" field. +func (m *ChargeFlatFeeRunPaymentMutation) ResetSettledTransactionGroupID() { + m.settled_transaction_group_id = nil + delete(m.clearedFields, chargeflatfeerunpayment.FieldSettledTransactionGroupID) +} + +// SetSettledAt sets the "settled_at" field. +func (m *ChargeFlatFeeRunPaymentMutation) SetSettledAt(t time.Time) { + m.settled_at = &t +} + +// SettledAt returns the value of the "settled_at" field in the mutation. +func (m *ChargeFlatFeeRunPaymentMutation) 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 ChargeFlatFeeRunPayment entity. +// If the ChargeFlatFeeRunPayment 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 *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) ClearSettledAt() { + m.settled_at = nil + m.clearedFields[chargeflatfeerunpayment.FieldSettledAt] = struct{}{} +} + +// SettledAtCleared returns if the "settled_at" field was cleared in this mutation. +func (m *ChargeFlatFeeRunPaymentMutation) SettledAtCleared() bool { + _, ok := m.clearedFields[chargeflatfeerunpayment.FieldSettledAt] + return ok +} + +// ResetSettledAt resets all changes to the "settled_at" field. +func (m *ChargeFlatFeeRunPaymentMutation) ResetSettledAt() { + m.settled_at = nil + delete(m.clearedFields, chargeflatfeerunpayment.FieldSettledAt) +} + +// SetNamespace sets the "namespace" field. +func (m *ChargeFlatFeeRunPaymentMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *ChargeFlatFeeRunPaymentMutation) 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 ChargeFlatFeeRunPayment entity. +// If the ChargeFlatFeeRunPayment 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 *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *ChargeFlatFeeRunPaymentMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ChargeFlatFeeRunPaymentMutation) 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 ChargeFlatFeeRunPayment entity. +// If the ChargeFlatFeeRunPayment 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 *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *ChargeFlatFeeRunPaymentMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ChargeFlatFeeRunPaymentMutation) 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 ChargeFlatFeeRunPayment entity. +// If the ChargeFlatFeeRunPayment 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 *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *ChargeFlatFeeRunPaymentMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *ChargeFlatFeeRunPaymentMutation) 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 ChargeFlatFeeRunPayment entity. +// If the ChargeFlatFeeRunPayment 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 *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[chargeflatfeerunpayment.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *ChargeFlatFeeRunPaymentMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[chargeflatfeerunpayment.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *ChargeFlatFeeRunPaymentMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, chargeflatfeerunpayment.FieldDeletedAt) +} + +// SetAnnotations sets the "annotations" field. +func (m *ChargeFlatFeeRunPaymentMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *ChargeFlatFeeRunPaymentMutation) 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 ChargeFlatFeeRunPayment entity. +// If the ChargeFlatFeeRunPayment 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 *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[chargeflatfeerunpayment.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *ChargeFlatFeeRunPaymentMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[chargeflatfeerunpayment.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *ChargeFlatFeeRunPaymentMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, chargeflatfeerunpayment.FieldAnnotations) +} + +// SetRunID sets the "run_id" field. +func (m *ChargeFlatFeeRunPaymentMutation) SetRunID(s string) { + m.run = &s +} + +// RunID returns the value of the "run_id" field in the mutation. +func (m *ChargeFlatFeeRunPaymentMutation) 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 ChargeFlatFeeRunPayment entity. +// If the ChargeFlatFeeRunPayment 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 *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) ResetRunID() { + m.run = nil +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by id. +func (m *ChargeFlatFeeRunPaymentMutation) SetBillingInvoiceLineID(id string) { + m.billing_invoice_line = &id +} + +// ClearBillingInvoiceLine clears the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (m *ChargeFlatFeeRunPaymentMutation) ClearBillingInvoiceLine() { + m.clearedbilling_invoice_line = true + m.clearedFields[chargeflatfeerunpayment.FieldLineID] = struct{}{} +} + +// BillingInvoiceLineCleared reports if the "billing_invoice_line" edge to the BillingInvoiceLine entity was cleared. +func (m *ChargeFlatFeeRunPaymentMutation) BillingInvoiceLineCleared() bool { + return m.clearedbilling_invoice_line +} + +// BillingInvoiceLineID returns the "billing_invoice_line" edge ID in the mutation. +func (m *ChargeFlatFeeRunPaymentMutation) BillingInvoiceLineID() (id string, exists bool) { + if m.billing_invoice_line != nil { + return *m.billing_invoice_line, true + } + return +} + +// BillingInvoiceLineIDs returns the "billing_invoice_line" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BillingInvoiceLineID instead. It exists only for internal usage by the builders. +func (m *ChargeFlatFeeRunPaymentMutation) BillingInvoiceLineIDs() (ids []string) { + if id := m.billing_invoice_line; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBillingInvoiceLine resets all changes to the "billing_invoice_line" edge. +func (m *ChargeFlatFeeRunPaymentMutation) ResetBillingInvoiceLine() { + m.billing_invoice_line = nil + m.clearedbilling_invoice_line = false +} + +// ClearRun clears the "run" edge to the ChargeFlatFeeRun entity. +func (m *ChargeFlatFeeRunPaymentMutation) ClearRun() { + m.clearedrun = true + m.clearedFields[chargeflatfeerunpayment.FieldRunID] = struct{}{} +} + +// RunCleared reports if the "run" edge to the ChargeFlatFeeRun entity was cleared. +func (m *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) RunIDs() (ids []string) { + if id := m.run; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetRun resets all changes to the "run" edge. +func (m *ChargeFlatFeeRunPaymentMutation) ResetRun() { + m.run = nil + m.clearedrun = false +} + +// Where appends a list predicates to the ChargeFlatFeeRunPaymentMutation builder. +func (m *ChargeFlatFeeRunPaymentMutation) Where(ps ...predicate.ChargeFlatFeeRunPayment) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ChargeFlatFeeRunPaymentMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ChargeFlatFeeRunPaymentMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ChargeFlatFeeRunPayment, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ChargeFlatFeeRunPaymentMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ChargeFlatFeeRunPaymentMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ChargeFlatFeeRunPayment). +func (m *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) Fields() []string { + fields := make([]string, 0, 16) + if m.billing_invoice_line != nil { + fields = append(fields, chargeflatfeerunpayment.FieldLineID) + } + if m.invoice_id != nil { + fields = append(fields, chargeflatfeerunpayment.FieldInvoiceID) + } + if m.service_period_from != nil { + fields = append(fields, chargeflatfeerunpayment.FieldServicePeriodFrom) + } + if m.service_period_to != nil { + fields = append(fields, chargeflatfeerunpayment.FieldServicePeriodTo) + } + if m.status != nil { + fields = append(fields, chargeflatfeerunpayment.FieldStatus) + } + if m.amount != nil { + fields = append(fields, chargeflatfeerunpayment.FieldAmount) + } + if m.authorized_transaction_group_id != nil { + fields = append(fields, chargeflatfeerunpayment.FieldAuthorizedTransactionGroupID) + } + if m.authorized_at != nil { + fields = append(fields, chargeflatfeerunpayment.FieldAuthorizedAt) + } + if m.settled_transaction_group_id != nil { + fields = append(fields, chargeflatfeerunpayment.FieldSettledTransactionGroupID) + } + if m.settled_at != nil { + fields = append(fields, chargeflatfeerunpayment.FieldSettledAt) + } + if m.namespace != nil { + fields = append(fields, chargeflatfeerunpayment.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, chargeflatfeerunpayment.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, chargeflatfeerunpayment.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, chargeflatfeerunpayment.FieldDeletedAt) + } + if m.annotations != nil { + fields = append(fields, chargeflatfeerunpayment.FieldAnnotations) + } + if m.run != nil { + fields = append(fields, chargeflatfeerunpayment.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 *ChargeFlatFeeRunPaymentMutation) Field(name string) (ent.Value, bool) { + switch name { + case chargeflatfeerunpayment.FieldLineID: + return m.LineID() + case chargeflatfeerunpayment.FieldInvoiceID: + return m.InvoiceID() + case chargeflatfeerunpayment.FieldServicePeriodFrom: + return m.ServicePeriodFrom() + case chargeflatfeerunpayment.FieldServicePeriodTo: + return m.ServicePeriodTo() + case chargeflatfeerunpayment.FieldStatus: + return m.Status() + case chargeflatfeerunpayment.FieldAmount: + return m.Amount() + case chargeflatfeerunpayment.FieldAuthorizedTransactionGroupID: + return m.AuthorizedTransactionGroupID() + case chargeflatfeerunpayment.FieldAuthorizedAt: + return m.AuthorizedAt() + case chargeflatfeerunpayment.FieldSettledTransactionGroupID: + return m.SettledTransactionGroupID() + case chargeflatfeerunpayment.FieldSettledAt: + return m.SettledAt() + case chargeflatfeerunpayment.FieldNamespace: + return m.Namespace() + case chargeflatfeerunpayment.FieldCreatedAt: + return m.CreatedAt() + case chargeflatfeerunpayment.FieldUpdatedAt: + return m.UpdatedAt() + case chargeflatfeerunpayment.FieldDeletedAt: + return m.DeletedAt() + case chargeflatfeerunpayment.FieldAnnotations: + return m.Annotations() + case chargeflatfeerunpayment.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 *ChargeFlatFeeRunPaymentMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case chargeflatfeerunpayment.FieldLineID: + return m.OldLineID(ctx) + case chargeflatfeerunpayment.FieldInvoiceID: + return m.OldInvoiceID(ctx) + case chargeflatfeerunpayment.FieldServicePeriodFrom: + return m.OldServicePeriodFrom(ctx) + case chargeflatfeerunpayment.FieldServicePeriodTo: + return m.OldServicePeriodTo(ctx) + case chargeflatfeerunpayment.FieldStatus: + return m.OldStatus(ctx) + case chargeflatfeerunpayment.FieldAmount: + return m.OldAmount(ctx) + case chargeflatfeerunpayment.FieldAuthorizedTransactionGroupID: + return m.OldAuthorizedTransactionGroupID(ctx) + case chargeflatfeerunpayment.FieldAuthorizedAt: + return m.OldAuthorizedAt(ctx) + case chargeflatfeerunpayment.FieldSettledTransactionGroupID: + return m.OldSettledTransactionGroupID(ctx) + case chargeflatfeerunpayment.FieldSettledAt: + return m.OldSettledAt(ctx) + case chargeflatfeerunpayment.FieldNamespace: + return m.OldNamespace(ctx) + case chargeflatfeerunpayment.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case chargeflatfeerunpayment.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case chargeflatfeerunpayment.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case chargeflatfeerunpayment.FieldAnnotations: + return m.OldAnnotations(ctx) + case chargeflatfeerunpayment.FieldRunID: + return m.OldRunID(ctx) + } + return nil, fmt.Errorf("unknown ChargeFlatFeeRunPayment 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 *ChargeFlatFeeRunPaymentMutation) SetField(name string, value ent.Value) error { + switch name { + case chargeflatfeerunpayment.FieldLineID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLineID(v) + return nil + case chargeflatfeerunpayment.FieldInvoiceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceID(v) + return nil + case chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 chargeflatfeerunpayment.FieldAuthorizedTransactionGroupID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAuthorizedTransactionGroupID(v) + return nil + case chargeflatfeerunpayment.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 chargeflatfeerunpayment.FieldSettledTransactionGroupID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSettledTransactionGroupID(v) + return nil + case chargeflatfeerunpayment.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 chargeflatfeerunpayment.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 chargeflatfeerunpayment.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 ChargeFlatFeeRunPayment field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown ChargeFlatFeeRunPayment numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ChargeFlatFeeRunPaymentMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(chargeflatfeerunpayment.FieldAuthorizedTransactionGroupID) { + fields = append(fields, chargeflatfeerunpayment.FieldAuthorizedTransactionGroupID) + } + if m.FieldCleared(chargeflatfeerunpayment.FieldAuthorizedAt) { + fields = append(fields, chargeflatfeerunpayment.FieldAuthorizedAt) + } + if m.FieldCleared(chargeflatfeerunpayment.FieldSettledTransactionGroupID) { + fields = append(fields, chargeflatfeerunpayment.FieldSettledTransactionGroupID) + } + if m.FieldCleared(chargeflatfeerunpayment.FieldSettledAt) { + fields = append(fields, chargeflatfeerunpayment.FieldSettledAt) + } + if m.FieldCleared(chargeflatfeerunpayment.FieldDeletedAt) { + fields = append(fields, chargeflatfeerunpayment.FieldDeletedAt) + } + if m.FieldCleared(chargeflatfeerunpayment.FieldAnnotations) { + fields = append(fields, chargeflatfeerunpayment.FieldAnnotations) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ChargeFlatFeeRunPaymentMutation) 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 *ChargeFlatFeeRunPaymentMutation) ClearField(name string) error { + switch name { + case chargeflatfeerunpayment.FieldAuthorizedTransactionGroupID: + m.ClearAuthorizedTransactionGroupID() + return nil + case chargeflatfeerunpayment.FieldAuthorizedAt: + m.ClearAuthorizedAt() + return nil + case chargeflatfeerunpayment.FieldSettledTransactionGroupID: + m.ClearSettledTransactionGroupID() + return nil + case chargeflatfeerunpayment.FieldSettledAt: + m.ClearSettledAt() + return nil + case chargeflatfeerunpayment.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case chargeflatfeerunpayment.FieldAnnotations: + m.ClearAnnotations() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRunPayment 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 *ChargeFlatFeeRunPaymentMutation) ResetField(name string) error { + switch name { + case chargeflatfeerunpayment.FieldLineID: + m.ResetLineID() + return nil + case chargeflatfeerunpayment.FieldInvoiceID: + m.ResetInvoiceID() + return nil + case chargeflatfeerunpayment.FieldServicePeriodFrom: + m.ResetServicePeriodFrom() + return nil + case chargeflatfeerunpayment.FieldServicePeriodTo: + m.ResetServicePeriodTo() + return nil + case chargeflatfeerunpayment.FieldStatus: + m.ResetStatus() + return nil + case chargeflatfeerunpayment.FieldAmount: + m.ResetAmount() + return nil + case chargeflatfeerunpayment.FieldAuthorizedTransactionGroupID: + m.ResetAuthorizedTransactionGroupID() + return nil + case chargeflatfeerunpayment.FieldAuthorizedAt: + m.ResetAuthorizedAt() + return nil + case chargeflatfeerunpayment.FieldSettledTransactionGroupID: + m.ResetSettledTransactionGroupID() + return nil + case chargeflatfeerunpayment.FieldSettledAt: + m.ResetSettledAt() + return nil + case chargeflatfeerunpayment.FieldNamespace: + m.ResetNamespace() + return nil + case chargeflatfeerunpayment.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case chargeflatfeerunpayment.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case chargeflatfeerunpayment.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case chargeflatfeerunpayment.FieldAnnotations: + m.ResetAnnotations() + return nil + case chargeflatfeerunpayment.FieldRunID: + m.ResetRunID() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRunPayment field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ChargeFlatFeeRunPaymentMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.billing_invoice_line != nil { + edges = append(edges, chargeflatfeerunpayment.EdgeBillingInvoiceLine) + } + if m.run != nil { + edges = append(edges, chargeflatfeerunpayment.EdgeRun) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ChargeFlatFeeRunPaymentMutation) AddedIDs(name string) []ent.Value { + switch name { + case chargeflatfeerunpayment.EdgeBillingInvoiceLine: + if id := m.billing_invoice_line; id != nil { + return []ent.Value{*id} + } + case chargeflatfeerunpayment.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 *ChargeFlatFeeRunPaymentMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ChargeFlatFeeRunPaymentMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ChargeFlatFeeRunPaymentMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedbilling_invoice_line { + edges = append(edges, chargeflatfeerunpayment.EdgeBillingInvoiceLine) + } + if m.clearedrun { + edges = append(edges, chargeflatfeerunpayment.EdgeRun) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ChargeFlatFeeRunPaymentMutation) EdgeCleared(name string) bool { + switch name { + case chargeflatfeerunpayment.EdgeBillingInvoiceLine: + return m.clearedbilling_invoice_line + case chargeflatfeerunpayment.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 *ChargeFlatFeeRunPaymentMutation) ClearEdge(name string) error { + switch name { + case chargeflatfeerunpayment.EdgeBillingInvoiceLine: + m.ClearBillingInvoiceLine() + return nil + case chargeflatfeerunpayment.EdgeRun: + m.ClearRun() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRunPayment 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 *ChargeFlatFeeRunPaymentMutation) ResetEdge(name string) error { + switch name { + case chargeflatfeerunpayment.EdgeBillingInvoiceLine: + m.ResetBillingInvoiceLine() + return nil + case chargeflatfeerunpayment.EdgeRun: + m.ResetRun() + return nil + } + return fmt.Errorf("unknown ChargeFlatFeeRunPayment 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 + service_period_from *time.Time + service_period_to *time.Time + billing_period_from *time.Time + billing_period_to *time.Time + full_service_period_from *time.Time + full_service_period_to *time.Time + status *meta.ChargeStatus + unique_reference_id *string + currency *currencyx.Code + managed_by *billing.InvoiceLineManagedBy + advance_after *time.Time + tax_behavior *productcatalog.TaxBehavior + annotations *models.Annotations + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + name *string + description *string + invoice_at *time.Time + settlement_mode *productcatalog.SettlementMode + intent_deleted_at *time.Time + discounts **billing.Discounts + feature_key *string + rating_engine *usagebased.RatingEngine + price **productcatalog.Price + unit_config **productcatalog.UnitConfig + status_detailed *usagebased.Status + clearedFields map[string]struct{} + runs map[string]struct{} + removedruns map[string]struct{} + clearedruns bool + detailed_lines map[string]struct{} + removeddetailed_lines map[string]struct{} + cleareddetailed_lines bool + current_run *string + clearedcurrent_run bool + charge *string + clearedcharge bool + intent_override *string + clearedintent_override bool + subscription *string + clearedsubscription bool + subscription_phase *string + clearedsubscription_phase bool + subscription_item *string + clearedsubscription_item bool + customer *string + clearedcustomer bool + feature *string + clearedfeature bool + tax_code *string + clearedtax_code 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) + } +} + +// SetCustomerID sets the "customer_id" field. +func (m *ChargeUsageBasedMutation) SetCustomerID(s string) { + m.customer = &s +} + +// CustomerID returns the value of the "customer_id" field in the mutation. +func (m *ChargeUsageBasedMutation) CustomerID() (r string, exists bool) { + v := m.customer + if v == nil { + return + } + return *v, true +} + +// OldCustomerID returns the old "customer_id" 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) OldCustomerID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerID: %w", err) + } + return oldValue.CustomerID, nil +} + +// ResetCustomerID resets all changes to the "customer_id" field. +func (m *ChargeUsageBasedMutation) ResetCustomerID() { + m.customer = nil +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (m *ChargeUsageBasedMutation) SetServicePeriodFrom(t time.Time) { + m.service_period_from = &t +} + +// ServicePeriodFrom returns the value of the "service_period_from" field in the mutation. +func (m *ChargeUsageBasedMutation) 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 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) 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 *ChargeUsageBasedMutation) ResetServicePeriodFrom() { + m.service_period_from = nil +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (m *ChargeUsageBasedMutation) SetServicePeriodTo(t time.Time) { + m.service_period_to = &t +} + +// ServicePeriodTo returns the value of the "service_period_to" field in the mutation. +func (m *ChargeUsageBasedMutation) 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 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) 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 *ChargeUsageBasedMutation) ResetServicePeriodTo() { + m.service_period_to = nil +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (m *ChargeUsageBasedMutation) SetBillingPeriodFrom(t time.Time) { + m.billing_period_from = &t +} + +// BillingPeriodFrom returns the value of the "billing_period_from" field in the mutation. +func (m *ChargeUsageBasedMutation) BillingPeriodFrom() (r time.Time, exists bool) { + v := m.billing_period_from + if v == nil { + return + } + return *v, true +} + +// OldBillingPeriodFrom returns the old "billing_period_from" 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) OldBillingPeriodFrom(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingPeriodFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingPeriodFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingPeriodFrom: %w", err) + } + return oldValue.BillingPeriodFrom, nil +} + +// ResetBillingPeriodFrom resets all changes to the "billing_period_from" field. +func (m *ChargeUsageBasedMutation) ResetBillingPeriodFrom() { + m.billing_period_from = nil +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (m *ChargeUsageBasedMutation) SetBillingPeriodTo(t time.Time) { + m.billing_period_to = &t +} + +// BillingPeriodTo returns the value of the "billing_period_to" field in the mutation. +func (m *ChargeUsageBasedMutation) BillingPeriodTo() (r time.Time, exists bool) { + v := m.billing_period_to + if v == nil { + return + } + return *v, true +} + +// OldBillingPeriodTo returns the old "billing_period_to" 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) OldBillingPeriodTo(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingPeriodTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingPeriodTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingPeriodTo: %w", err) + } + return oldValue.BillingPeriodTo, nil +} + +// ResetBillingPeriodTo resets all changes to the "billing_period_to" field. +func (m *ChargeUsageBasedMutation) ResetBillingPeriodTo() { + m.billing_period_to = nil +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (m *ChargeUsageBasedMutation) SetFullServicePeriodFrom(t time.Time) { + m.full_service_period_from = &t +} + +// FullServicePeriodFrom returns the value of the "full_service_period_from" field in the mutation. +func (m *ChargeUsageBasedMutation) FullServicePeriodFrom() (r time.Time, exists bool) { + v := m.full_service_period_from + if v == nil { + return + } + return *v, true +} + +// OldFullServicePeriodFrom returns the old "full_service_period_from" 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) OldFullServicePeriodFrom(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFullServicePeriodFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFullServicePeriodFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFullServicePeriodFrom: %w", err) + } + return oldValue.FullServicePeriodFrom, nil +} + +// ResetFullServicePeriodFrom resets all changes to the "full_service_period_from" field. +func (m *ChargeUsageBasedMutation) ResetFullServicePeriodFrom() { + m.full_service_period_from = nil +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (m *ChargeUsageBasedMutation) SetFullServicePeriodTo(t time.Time) { + m.full_service_period_to = &t +} + +// FullServicePeriodTo returns the value of the "full_service_period_to" field in the mutation. +func (m *ChargeUsageBasedMutation) FullServicePeriodTo() (r time.Time, exists bool) { + v := m.full_service_period_to + if v == nil { + return + } + return *v, true +} + +// OldFullServicePeriodTo returns the old "full_service_period_to" 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) OldFullServicePeriodTo(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFullServicePeriodTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFullServicePeriodTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFullServicePeriodTo: %w", err) + } + return oldValue.FullServicePeriodTo, nil +} + +// ResetFullServicePeriodTo resets all changes to the "full_service_period_to" field. +func (m *ChargeUsageBasedMutation) ResetFullServicePeriodTo() { + m.full_service_period_to = nil +} + +// SetStatus sets the "status" field. +func (m *ChargeUsageBasedMutation) SetStatus(ms meta.ChargeStatus) { + m.status = &ms +} + +// Status returns the value of the "status" field in the mutation. +func (m *ChargeUsageBasedMutation) Status() (r meta.ChargeStatus, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true +} + +// OldStatus returns the old "status" 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) OldStatus(ctx context.Context) (v meta.ChargeStatus, 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 *ChargeUsageBasedMutation) ResetStatus() { + m.status = nil +} + +// SetUniqueReferenceID sets the "unique_reference_id" field. +func (m *ChargeUsageBasedMutation) SetUniqueReferenceID(s string) { + m.unique_reference_id = &s +} + +// UniqueReferenceID returns the value of the "unique_reference_id" field in the mutation. +func (m *ChargeUsageBasedMutation) UniqueReferenceID() (r string, exists bool) { + v := m.unique_reference_id + if v == nil { + return + } + return *v, true +} + +// OldUniqueReferenceID returns the old "unique_reference_id" 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) OldUniqueReferenceID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUniqueReferenceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUniqueReferenceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUniqueReferenceID: %w", err) + } + return oldValue.UniqueReferenceID, nil +} + +// ClearUniqueReferenceID clears the value of the "unique_reference_id" field. +func (m *ChargeUsageBasedMutation) ClearUniqueReferenceID() { + m.unique_reference_id = nil + m.clearedFields[chargeusagebased.FieldUniqueReferenceID] = struct{}{} +} + +// UniqueReferenceIDCleared returns if the "unique_reference_id" field was cleared in this mutation. +func (m *ChargeUsageBasedMutation) UniqueReferenceIDCleared() bool { + _, ok := m.clearedFields[chargeusagebased.FieldUniqueReferenceID] + return ok +} + +// ResetUniqueReferenceID resets all changes to the "unique_reference_id" field. +func (m *ChargeUsageBasedMutation) ResetUniqueReferenceID() { + m.unique_reference_id = nil + delete(m.clearedFields, chargeusagebased.FieldUniqueReferenceID) +} + +// SetCurrency sets the "currency" field. +func (m *ChargeUsageBasedMutation) SetCurrency(c currencyx.Code) { + m.currency = &c +} + +// Currency returns the value of the "currency" field in the mutation. +func (m *ChargeUsageBasedMutation) Currency() (r currencyx.Code, exists bool) { + v := m.currency + if v == nil { + return + } + return *v, true +} + +// OldCurrency returns the old "currency" 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) OldCurrency(ctx context.Context) (v currencyx.Code, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrency is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrency requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrency: %w", err) + } + return oldValue.Currency, nil +} + +// ResetCurrency resets all changes to the "currency" field. +func (m *ChargeUsageBasedMutation) ResetCurrency() { + m.currency = nil +} + +// SetManagedBy sets the "managed_by" field. +func (m *ChargeUsageBasedMutation) SetManagedBy(blmb billing.InvoiceLineManagedBy) { + m.managed_by = &blmb +} + +// ManagedBy returns the value of the "managed_by" field in the mutation. +func (m *ChargeUsageBasedMutation) ManagedBy() (r billing.InvoiceLineManagedBy, exists bool) { + v := m.managed_by + if v == nil { + return + } + return *v, true +} + +// OldManagedBy returns the old "managed_by" 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) OldManagedBy(ctx context.Context) (v billing.InvoiceLineManagedBy, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldManagedBy is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldManagedBy requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldManagedBy: %w", err) + } + return oldValue.ManagedBy, nil +} + +// ResetManagedBy resets all changes to the "managed_by" field. +func (m *ChargeUsageBasedMutation) ResetManagedBy() { + m.managed_by = nil +} + +// SetSubscriptionID sets the "subscription_id" field. +func (m *ChargeUsageBasedMutation) SetSubscriptionID(s string) { + m.subscription = &s +} + +// SubscriptionID returns the value of the "subscription_id" field in the mutation. +func (m *ChargeUsageBasedMutation) SubscriptionID() (r string, exists bool) { + v := m.subscription + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionID returns the old "subscription_id" 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) OldSubscriptionID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionID: %w", err) + } + return oldValue.SubscriptionID, nil +} + +// ClearSubscriptionID clears the value of the "subscription_id" field. +func (m *ChargeUsageBasedMutation) ClearSubscriptionID() { + m.subscription = nil + m.clearedFields[chargeusagebased.FieldSubscriptionID] = struct{}{} +} + +// SubscriptionIDCleared returns if the "subscription_id" field was cleared in this mutation. +func (m *ChargeUsageBasedMutation) SubscriptionIDCleared() bool { + _, ok := m.clearedFields[chargeusagebased.FieldSubscriptionID] + return ok +} + +// ResetSubscriptionID resets all changes to the "subscription_id" field. +func (m *ChargeUsageBasedMutation) ResetSubscriptionID() { + m.subscription = nil + delete(m.clearedFields, chargeusagebased.FieldSubscriptionID) +} + +// SetSubscriptionPhaseID sets the "subscription_phase_id" field. +func (m *ChargeUsageBasedMutation) SetSubscriptionPhaseID(s string) { + m.subscription_phase = &s +} + +// SubscriptionPhaseID returns the value of the "subscription_phase_id" field in the mutation. +func (m *ChargeUsageBasedMutation) SubscriptionPhaseID() (r string, exists bool) { + v := m.subscription_phase + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionPhaseID returns the old "subscription_phase_id" 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) OldSubscriptionPhaseID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionPhaseID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionPhaseID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionPhaseID: %w", err) + } + return oldValue.SubscriptionPhaseID, nil +} + +// ClearSubscriptionPhaseID clears the value of the "subscription_phase_id" field. +func (m *ChargeUsageBasedMutation) ClearSubscriptionPhaseID() { + m.subscription_phase = nil + m.clearedFields[chargeusagebased.FieldSubscriptionPhaseID] = struct{}{} +} + +// SubscriptionPhaseIDCleared returns if the "subscription_phase_id" field was cleared in this mutation. +func (m *ChargeUsageBasedMutation) SubscriptionPhaseIDCleared() bool { + _, ok := m.clearedFields[chargeusagebased.FieldSubscriptionPhaseID] + return ok +} + +// ResetSubscriptionPhaseID resets all changes to the "subscription_phase_id" field. +func (m *ChargeUsageBasedMutation) ResetSubscriptionPhaseID() { + m.subscription_phase = nil + delete(m.clearedFields, chargeusagebased.FieldSubscriptionPhaseID) +} + +// SetSubscriptionItemID sets the "subscription_item_id" field. +func (m *ChargeUsageBasedMutation) SetSubscriptionItemID(s string) { + m.subscription_item = &s +} + +// SubscriptionItemID returns the value of the "subscription_item_id" field in the mutation. +func (m *ChargeUsageBasedMutation) SubscriptionItemID() (r string, exists bool) { + v := m.subscription_item + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionItemID returns the old "subscription_item_id" 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) OldSubscriptionItemID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionItemID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionItemID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionItemID: %w", err) + } + return oldValue.SubscriptionItemID, nil +} + +// ClearSubscriptionItemID clears the value of the "subscription_item_id" field. +func (m *ChargeUsageBasedMutation) ClearSubscriptionItemID() { + m.subscription_item = nil + m.clearedFields[chargeusagebased.FieldSubscriptionItemID] = struct{}{} +} + +// SubscriptionItemIDCleared returns if the "subscription_item_id" field was cleared in this mutation. +func (m *ChargeUsageBasedMutation) SubscriptionItemIDCleared() bool { + _, ok := m.clearedFields[chargeusagebased.FieldSubscriptionItemID] + return ok +} + +// ResetSubscriptionItemID resets all changes to the "subscription_item_id" field. +func (m *ChargeUsageBasedMutation) ResetSubscriptionItemID() { + m.subscription_item = nil + delete(m.clearedFields, chargeusagebased.FieldSubscriptionItemID) +} + +// SetAdvanceAfter sets the "advance_after" field. +func (m *ChargeUsageBasedMutation) SetAdvanceAfter(t time.Time) { + m.advance_after = &t +} + +// AdvanceAfter returns the value of the "advance_after" field in the mutation. +func (m *ChargeUsageBasedMutation) AdvanceAfter() (r time.Time, exists bool) { + v := m.advance_after + if v == nil { + return + } + return *v, true +} + +// OldAdvanceAfter returns the old "advance_after" 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) OldAdvanceAfter(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAdvanceAfter is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAdvanceAfter requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAdvanceAfter: %w", err) + } + return oldValue.AdvanceAfter, nil +} + +// ClearAdvanceAfter clears the value of the "advance_after" field. +func (m *ChargeUsageBasedMutation) ClearAdvanceAfter() { + m.advance_after = nil + m.clearedFields[chargeusagebased.FieldAdvanceAfter] = struct{}{} +} + +// AdvanceAfterCleared returns if the "advance_after" field was cleared in this mutation. +func (m *ChargeUsageBasedMutation) AdvanceAfterCleared() bool { + _, ok := m.clearedFields[chargeusagebased.FieldAdvanceAfter] + return ok +} + +// ResetAdvanceAfter resets all changes to the "advance_after" field. +func (m *ChargeUsageBasedMutation) ResetAdvanceAfter() { + m.advance_after = nil + delete(m.clearedFields, chargeusagebased.FieldAdvanceAfter) +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (m *ChargeUsageBasedMutation) SetTaxCodeID(s string) { + m.tax_code = &s +} + +// TaxCodeID returns the value of the "tax_code_id" field in the mutation. +func (m *ChargeUsageBasedMutation) TaxCodeID() (r string, exists bool) { + v := m.tax_code + if v == nil { + return + } + return *v, true +} + +// OldTaxCodeID returns the old "tax_code_id" 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) OldTaxCodeID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxCodeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxCodeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxCodeID: %w", err) + } + return oldValue.TaxCodeID, nil +} + +// ResetTaxCodeID resets all changes to the "tax_code_id" field. +func (m *ChargeUsageBasedMutation) ResetTaxCodeID() { + m.tax_code = nil +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (m *ChargeUsageBasedMutation) SetTaxBehavior(pb productcatalog.TaxBehavior) { + m.tax_behavior = &pb +} + +// TaxBehavior returns the value of the "tax_behavior" field in the mutation. +func (m *ChargeUsageBasedMutation) TaxBehavior() (r productcatalog.TaxBehavior, exists bool) { + v := m.tax_behavior + if v == nil { + return + } + return *v, true +} + +// OldTaxBehavior returns the old "tax_behavior" 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) OldTaxBehavior(ctx context.Context) (v *productcatalog.TaxBehavior, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxBehavior is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxBehavior requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxBehavior: %w", err) + } + return oldValue.TaxBehavior, nil +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (m *ChargeUsageBasedMutation) ClearTaxBehavior() { + m.tax_behavior = nil + m.clearedFields[chargeusagebased.FieldTaxBehavior] = struct{}{} +} + +// TaxBehaviorCleared returns if the "tax_behavior" field was cleared in this mutation. +func (m *ChargeUsageBasedMutation) TaxBehaviorCleared() bool { + _, ok := m.clearedFields[chargeusagebased.FieldTaxBehavior] + return ok +} + +// ResetTaxBehavior resets all changes to the "tax_behavior" field. +func (m *ChargeUsageBasedMutation) ResetTaxBehavior() { + m.tax_behavior = nil + delete(m.clearedFields, chargeusagebased.FieldTaxBehavior) +} + +// SetAnnotations sets the "annotations" field. +func (m *ChargeUsageBasedMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *ChargeUsageBasedMutation) 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 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) 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 *ChargeUsageBasedMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[chargeusagebased.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *ChargeUsageBasedMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[chargeusagebased.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *ChargeUsageBasedMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, chargeusagebased.FieldAnnotations) +} + +// 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 +} + +// SetMetadata sets the "metadata" field. +func (m *ChargeUsageBasedMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *ChargeUsageBasedMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" 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) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *ChargeUsageBasedMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[chargeusagebased.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *ChargeUsageBasedMutation) MetadataCleared() bool { + _, ok := m.clearedFields[chargeusagebased.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *ChargeUsageBasedMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, chargeusagebased.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *ChargeUsageBasedMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ChargeUsageBasedMutation) 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 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) 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 *ChargeUsageBasedMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *ChargeUsageBasedMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ChargeUsageBasedMutation) 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 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) 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 *ChargeUsageBasedMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *ChargeUsageBasedMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *ChargeUsageBasedMutation) 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 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) 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 *ChargeUsageBasedMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[chargeusagebased.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *ChargeUsageBasedMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[chargeusagebased.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *ChargeUsageBasedMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, chargeusagebased.FieldDeletedAt) +} + +// SetName sets the "name" field. +func (m *ChargeUsageBasedMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *ChargeUsageBasedMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" 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) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *ChargeUsageBasedMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *ChargeUsageBasedMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *ChargeUsageBasedMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" 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) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *ChargeUsageBasedMutation) ClearDescription() { + m.description = nil + m.clearedFields[chargeusagebased.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *ChargeUsageBasedMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[chargeusagebased.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *ChargeUsageBasedMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, chargeusagebased.FieldDescription) +} + +// 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 +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (m *ChargeUsageBasedMutation) SetIntentDeletedAt(t time.Time) { + m.intent_deleted_at = &t +} + +// IntentDeletedAt returns the value of the "intent_deleted_at" field in the mutation. +func (m *ChargeUsageBasedMutation) IntentDeletedAt() (r time.Time, exists bool) { + v := m.intent_deleted_at + if v == nil { + return + } + return *v, true +} + +// OldIntentDeletedAt returns the old "intent_deleted_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) OldIntentDeletedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIntentDeletedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIntentDeletedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIntentDeletedAt: %w", err) + } + return oldValue.IntentDeletedAt, nil +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (m *ChargeUsageBasedMutation) ClearIntentDeletedAt() { + m.intent_deleted_at = nil + m.clearedFields[chargeusagebased.FieldIntentDeletedAt] = struct{}{} +} + +// IntentDeletedAtCleared returns if the "intent_deleted_at" field was cleared in this mutation. +func (m *ChargeUsageBasedMutation) IntentDeletedAtCleared() bool { + _, ok := m.clearedFields[chargeusagebased.FieldIntentDeletedAt] + return ok +} + +// ResetIntentDeletedAt resets all changes to the "intent_deleted_at" field. +func (m *ChargeUsageBasedMutation) ResetIntentDeletedAt() { + m.intent_deleted_at = nil + delete(m.clearedFields, chargeusagebased.FieldIntentDeletedAt) +} + +// SetDiscounts sets the "discounts" field. +func (m *ChargeUsageBasedMutation) SetDiscounts(b *billing.Discounts) { + m.discounts = &b +} + +// Discounts returns the value of the "discounts" field in the mutation. +func (m *ChargeUsageBasedMutation) Discounts() (r *billing.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 *billing.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 +} + +// SetFeatureID sets the "feature_id" field. +func (m *ChargeUsageBasedMutation) SetFeatureID(s string) { + m.feature = &s +} + +// FeatureID returns the value of the "feature_id" field in the mutation. +func (m *ChargeUsageBasedMutation) FeatureID() (r string, exists bool) { + v := m.feature + if v == nil { + return + } + return *v, true +} + +// OldFeatureID returns the old "feature_id" 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) OldFeatureID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFeatureID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFeatureID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFeatureID: %w", err) + } + return oldValue.FeatureID, nil +} + +// ResetFeatureID resets all changes to the "feature_id" field. +func (m *ChargeUsageBasedMutation) ResetFeatureID() { + m.feature = nil +} + +// SetRatingEngine sets the "rating_engine" field. +func (m *ChargeUsageBasedMutation) SetRatingEngine(ue usagebased.RatingEngine) { + m.rating_engine = &ue +} + +// RatingEngine returns the value of the "rating_engine" field in the mutation. +func (m *ChargeUsageBasedMutation) RatingEngine() (r usagebased.RatingEngine, exists bool) { + v := m.rating_engine + if v == nil { + return + } + return *v, true +} + +// OldRatingEngine returns the old "rating_engine" 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) OldRatingEngine(ctx context.Context) (v usagebased.RatingEngine, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRatingEngine is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRatingEngine requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRatingEngine: %w", err) + } + return oldValue.RatingEngine, nil +} + +// ResetRatingEngine resets all changes to the "rating_engine" field. +func (m *ChargeUsageBasedMutation) ResetRatingEngine() { + m.rating_engine = 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 +} + +// SetUnitConfig sets the "unit_config" field. +func (m *ChargeUsageBasedMutation) SetUnitConfig(pc *productcatalog.UnitConfig) { + m.unit_config = &pc +} + +// UnitConfig returns the value of the "unit_config" field in the mutation. +func (m *ChargeUsageBasedMutation) UnitConfig() (r *productcatalog.UnitConfig, exists bool) { + v := m.unit_config + if v == nil { + return + } + return *v, true +} + +// OldUnitConfig returns the old "unit_config" 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) OldUnitConfig(ctx context.Context) (v *productcatalog.UnitConfig, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUnitConfig is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUnitConfig requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUnitConfig: %w", err) + } + return oldValue.UnitConfig, nil +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (m *ChargeUsageBasedMutation) ClearUnitConfig() { + m.unit_config = nil + m.clearedFields[chargeusagebased.FieldUnitConfig] = struct{}{} +} + +// UnitConfigCleared returns if the "unit_config" field was cleared in this mutation. +func (m *ChargeUsageBasedMutation) UnitConfigCleared() bool { + _, ok := m.clearedFields[chargeusagebased.FieldUnitConfig] + return ok +} + +// ResetUnitConfig resets all changes to the "unit_config" field. +func (m *ChargeUsageBasedMutation) ResetUnitConfig() { + m.unit_config = nil + delete(m.clearedFields, chargeusagebased.FieldUnitConfig) +} + +// SetCurrentRealizationRunID sets the "current_realization_run_id" field. +func (m *ChargeUsageBasedMutation) SetCurrentRealizationRunID(s string) { + m.current_run = &s +} + +// CurrentRealizationRunID returns the value of the "current_realization_run_id" field in the mutation. +func (m *ChargeUsageBasedMutation) CurrentRealizationRunID() (r string, exists bool) { + v := m.current_run + if v == nil { + return + } + return *v, true +} + +// OldCurrentRealizationRunID returns the old "current_realization_run_id" 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) OldCurrentRealizationRunID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrentRealizationRunID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrentRealizationRunID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrentRealizationRunID: %w", err) + } + return oldValue.CurrentRealizationRunID, nil +} + +// ClearCurrentRealizationRunID clears the value of the "current_realization_run_id" field. +func (m *ChargeUsageBasedMutation) ClearCurrentRealizationRunID() { + m.current_run = nil + m.clearedFields[chargeusagebased.FieldCurrentRealizationRunID] = struct{}{} +} + +// CurrentRealizationRunIDCleared returns if the "current_realization_run_id" field was cleared in this mutation. +func (m *ChargeUsageBasedMutation) CurrentRealizationRunIDCleared() bool { + _, ok := m.clearedFields[chargeusagebased.FieldCurrentRealizationRunID] + return ok +} + +// ResetCurrentRealizationRunID resets all changes to the "current_realization_run_id" field. +func (m *ChargeUsageBasedMutation) ResetCurrentRealizationRunID() { + m.current_run = nil + delete(m.clearedFields, chargeusagebased.FieldCurrentRealizationRunID) +} + +// SetStatusDetailed sets the "status_detailed" field. +func (m *ChargeUsageBasedMutation) SetStatusDetailed(u usagebased.Status) { + m.status_detailed = &u +} + +// StatusDetailed returns the value of the "status_detailed" field in the mutation. +func (m *ChargeUsageBasedMutation) StatusDetailed() (r usagebased.Status, exists bool) { + v := m.status_detailed + if v == nil { + return + } + return *v, true +} + +// OldStatusDetailed returns the old "status_detailed" 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) OldStatusDetailed(ctx context.Context) (v usagebased.Status, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStatusDetailed is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStatusDetailed requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStatusDetailed: %w", err) + } + return oldValue.StatusDetailed, nil +} + +// ResetStatusDetailed resets all changes to the "status_detailed" field. +func (m *ChargeUsageBasedMutation) ResetStatusDetailed() { + m.status_detailed = nil +} + +// 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 +} + +// AddDetailedLineIDs adds the "detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity by ids. +func (m *ChargeUsageBasedMutation) AddDetailedLineIDs(ids ...string) { + if m.detailed_lines == nil { + m.detailed_lines = make(map[string]struct{}) + } + for i := range ids { + m.detailed_lines[ids[i]] = struct{}{} + } +} + +// ClearDetailedLines clears the "detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity. +func (m *ChargeUsageBasedMutation) ClearDetailedLines() { + m.cleareddetailed_lines = true +} + +// DetailedLinesCleared reports if the "detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity was cleared. +func (m *ChargeUsageBasedMutation) DetailedLinesCleared() bool { + return m.cleareddetailed_lines +} + +// RemoveDetailedLineIDs removes the "detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity by IDs. +func (m *ChargeUsageBasedMutation) RemoveDetailedLineIDs(ids ...string) { + if m.removeddetailed_lines == nil { + m.removeddetailed_lines = make(map[string]struct{}) + } + for i := range ids { + delete(m.detailed_lines, ids[i]) + m.removeddetailed_lines[ids[i]] = struct{}{} + } +} + +// RemovedDetailedLines returns the removed IDs of the "detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity. +func (m *ChargeUsageBasedMutation) RemovedDetailedLinesIDs() (ids []string) { + for id := range m.removeddetailed_lines { + ids = append(ids, id) + } + return +} + +// DetailedLinesIDs returns the "detailed_lines" edge IDs in the mutation. +func (m *ChargeUsageBasedMutation) DetailedLinesIDs() (ids []string) { + for id := range m.detailed_lines { + ids = append(ids, id) + } + return +} + +// ResetDetailedLines resets all changes to the "detailed_lines" edge. +func (m *ChargeUsageBasedMutation) ResetDetailedLines() { + m.detailed_lines = nil + m.cleareddetailed_lines = false + m.removeddetailed_lines = nil +} + +// SetCurrentRunID sets the "current_run" edge to the ChargeUsageBasedRuns entity by id. +func (m *ChargeUsageBasedMutation) SetCurrentRunID(id string) { + m.current_run = &id +} + +// ClearCurrentRun clears the "current_run" edge to the ChargeUsageBasedRuns entity. +func (m *ChargeUsageBasedMutation) ClearCurrentRun() { + m.clearedcurrent_run = true + m.clearedFields[chargeusagebased.FieldCurrentRealizationRunID] = struct{}{} +} + +// CurrentRunCleared reports if the "current_run" edge to the ChargeUsageBasedRuns entity was cleared. +func (m *ChargeUsageBasedMutation) CurrentRunCleared() bool { + return m.CurrentRealizationRunIDCleared() || m.clearedcurrent_run +} + +// CurrentRunID returns the "current_run" edge ID in the mutation. +func (m *ChargeUsageBasedMutation) CurrentRunID() (id string, exists bool) { + if m.current_run != nil { + return *m.current_run, true + } + return +} + +// CurrentRunIDs returns the "current_run" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CurrentRunID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedMutation) CurrentRunIDs() (ids []string) { + if id := m.current_run; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCurrentRun resets all changes to the "current_run" edge. +func (m *ChargeUsageBasedMutation) ResetCurrentRun() { + m.current_run = nil + m.clearedcurrent_run = false +} + +// 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 +} + +// SetIntentOverrideID sets the "intent_override" edge to the ChargeUsageBasedOverride entity by id. +func (m *ChargeUsageBasedMutation) SetIntentOverrideID(id string) { + m.intent_override = &id +} + +// ClearIntentOverride clears the "intent_override" edge to the ChargeUsageBasedOverride entity. +func (m *ChargeUsageBasedMutation) ClearIntentOverride() { + m.clearedintent_override = true +} + +// IntentOverrideCleared reports if the "intent_override" edge to the ChargeUsageBasedOverride entity was cleared. +func (m *ChargeUsageBasedMutation) IntentOverrideCleared() bool { + return m.clearedintent_override +} + +// IntentOverrideID returns the "intent_override" edge ID in the mutation. +func (m *ChargeUsageBasedMutation) IntentOverrideID() (id string, exists bool) { + if m.intent_override != nil { + return *m.intent_override, true + } + return +} + +// IntentOverrideIDs returns the "intent_override" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// IntentOverrideID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedMutation) IntentOverrideIDs() (ids []string) { + if id := m.intent_override; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetIntentOverride resets all changes to the "intent_override" edge. +func (m *ChargeUsageBasedMutation) ResetIntentOverride() { + m.intent_override = nil + m.clearedintent_override = false +} + +// ClearSubscription clears the "subscription" edge to the Subscription entity. +func (m *ChargeUsageBasedMutation) ClearSubscription() { + m.clearedsubscription = true + m.clearedFields[chargeusagebased.FieldSubscriptionID] = struct{}{} +} + +// SubscriptionCleared reports if the "subscription" edge to the Subscription entity was cleared. +func (m *ChargeUsageBasedMutation) SubscriptionCleared() bool { + return m.SubscriptionIDCleared() || m.clearedsubscription +} + +// SubscriptionIDs returns the "subscription" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubscriptionID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedMutation) SubscriptionIDs() (ids []string) { + if id := m.subscription; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSubscription resets all changes to the "subscription" edge. +func (m *ChargeUsageBasedMutation) ResetSubscription() { + m.subscription = nil + m.clearedsubscription = false +} + +// ClearSubscriptionPhase clears the "subscription_phase" edge to the SubscriptionPhase entity. +func (m *ChargeUsageBasedMutation) ClearSubscriptionPhase() { + m.clearedsubscription_phase = true + m.clearedFields[chargeusagebased.FieldSubscriptionPhaseID] = struct{}{} +} + +// SubscriptionPhaseCleared reports if the "subscription_phase" edge to the SubscriptionPhase entity was cleared. +func (m *ChargeUsageBasedMutation) SubscriptionPhaseCleared() bool { + return m.SubscriptionPhaseIDCleared() || m.clearedsubscription_phase +} + +// SubscriptionPhaseIDs returns the "subscription_phase" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubscriptionPhaseID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedMutation) SubscriptionPhaseIDs() (ids []string) { + if id := m.subscription_phase; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSubscriptionPhase resets all changes to the "subscription_phase" edge. +func (m *ChargeUsageBasedMutation) ResetSubscriptionPhase() { + m.subscription_phase = nil + m.clearedsubscription_phase = false +} + +// ClearSubscriptionItem clears the "subscription_item" edge to the SubscriptionItem entity. +func (m *ChargeUsageBasedMutation) ClearSubscriptionItem() { + m.clearedsubscription_item = true + m.clearedFields[chargeusagebased.FieldSubscriptionItemID] = struct{}{} +} + +// SubscriptionItemCleared reports if the "subscription_item" edge to the SubscriptionItem entity was cleared. +func (m *ChargeUsageBasedMutation) SubscriptionItemCleared() bool { + return m.SubscriptionItemIDCleared() || m.clearedsubscription_item +} + +// SubscriptionItemIDs returns the "subscription_item" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubscriptionItemID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedMutation) SubscriptionItemIDs() (ids []string) { + if id := m.subscription_item; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSubscriptionItem resets all changes to the "subscription_item" edge. +func (m *ChargeUsageBasedMutation) ResetSubscriptionItem() { + m.subscription_item = nil + m.clearedsubscription_item = false +} + +// ClearCustomer clears the "customer" edge to the Customer entity. +func (m *ChargeUsageBasedMutation) ClearCustomer() { + m.clearedcustomer = true + m.clearedFields[chargeusagebased.FieldCustomerID] = struct{}{} +} + +// CustomerCleared reports if the "customer" edge to the Customer entity was cleared. +func (m *ChargeUsageBasedMutation) CustomerCleared() bool { + return m.clearedcustomer +} + +// CustomerIDs returns the "customer" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CustomerID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedMutation) CustomerIDs() (ids []string) { + if id := m.customer; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCustomer resets all changes to the "customer" edge. +func (m *ChargeUsageBasedMutation) ResetCustomer() { + m.customer = nil + m.clearedcustomer = false +} + +// ClearFeature clears the "feature" edge to the Feature entity. +func (m *ChargeUsageBasedMutation) ClearFeature() { + m.clearedfeature = true + m.clearedFields[chargeusagebased.FieldFeatureID] = struct{}{} +} + +// FeatureCleared reports if the "feature" edge to the Feature entity was cleared. +func (m *ChargeUsageBasedMutation) FeatureCleared() bool { + return m.clearedfeature +} + +// FeatureIDs returns the "feature" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// FeatureID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedMutation) FeatureIDs() (ids []string) { + if id := m.feature; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetFeature resets all changes to the "feature" edge. +func (m *ChargeUsageBasedMutation) ResetFeature() { + m.feature = nil + m.clearedfeature = false +} + +// ClearTaxCode clears the "tax_code" edge to the TaxCode entity. +func (m *ChargeUsageBasedMutation) ClearTaxCode() { + m.clearedtax_code = true + m.clearedFields[chargeusagebased.FieldTaxCodeID] = struct{}{} +} + +// TaxCodeCleared reports if the "tax_code" edge to the TaxCode entity was cleared. +func (m *ChargeUsageBasedMutation) TaxCodeCleared() bool { + return m.clearedtax_code +} + +// TaxCodeIDs returns the "tax_code" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TaxCodeID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedMutation) TaxCodeIDs() (ids []string) { + if id := m.tax_code; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTaxCode resets all changes to the "tax_code" edge. +func (m *ChargeUsageBasedMutation) ResetTaxCode() { + m.tax_code = nil + m.clearedtax_code = false +} + +// 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, 36) + if m.customer != nil { + fields = append(fields, chargeusagebased.FieldCustomerID) + } + if m.service_period_from != nil { + fields = append(fields, chargeusagebased.FieldServicePeriodFrom) + } + if m.service_period_to != nil { + fields = append(fields, chargeusagebased.FieldServicePeriodTo) + } + if m.billing_period_from != nil { + fields = append(fields, chargeusagebased.FieldBillingPeriodFrom) + } + if m.billing_period_to != nil { + fields = append(fields, chargeusagebased.FieldBillingPeriodTo) + } + if m.full_service_period_from != nil { + fields = append(fields, chargeusagebased.FieldFullServicePeriodFrom) + } + if m.full_service_period_to != nil { + fields = append(fields, chargeusagebased.FieldFullServicePeriodTo) + } + if m.status != nil { + fields = append(fields, chargeusagebased.FieldStatus) + } + if m.unique_reference_id != nil { + fields = append(fields, chargeusagebased.FieldUniqueReferenceID) + } + if m.currency != nil { + fields = append(fields, chargeusagebased.FieldCurrency) + } + if m.managed_by != nil { + fields = append(fields, chargeusagebased.FieldManagedBy) + } + if m.subscription != nil { + fields = append(fields, chargeusagebased.FieldSubscriptionID) + } + if m.subscription_phase != nil { + fields = append(fields, chargeusagebased.FieldSubscriptionPhaseID) + } + if m.subscription_item != nil { + fields = append(fields, chargeusagebased.FieldSubscriptionItemID) + } + if m.advance_after != nil { + fields = append(fields, chargeusagebased.FieldAdvanceAfter) + } + if m.tax_code != nil { + fields = append(fields, chargeusagebased.FieldTaxCodeID) + } + if m.tax_behavior != nil { + fields = append(fields, chargeusagebased.FieldTaxBehavior) + } + if m.annotations != nil { + fields = append(fields, chargeusagebased.FieldAnnotations) + } + if m.namespace != nil { + fields = append(fields, chargeusagebased.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, chargeusagebased.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, chargeusagebased.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, chargeusagebased.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, chargeusagebased.FieldDeletedAt) + } + if m.name != nil { + fields = append(fields, chargeusagebased.FieldName) + } + if m.description != nil { + fields = append(fields, chargeusagebased.FieldDescription) + } + if m.invoice_at != nil { + fields = append(fields, chargeusagebased.FieldInvoiceAt) + } + if m.settlement_mode != nil { + fields = append(fields, chargeusagebased.FieldSettlementMode) + } + if m.intent_deleted_at != nil { + fields = append(fields, chargeusagebased.FieldIntentDeletedAt) + } + if m.discounts != nil { + fields = append(fields, chargeusagebased.FieldDiscounts) + } + if m.feature_key != nil { + fields = append(fields, chargeusagebased.FieldFeatureKey) + } + if m.feature != nil { + fields = append(fields, chargeusagebased.FieldFeatureID) + } + if m.rating_engine != nil { + fields = append(fields, chargeusagebased.FieldRatingEngine) + } + if m.price != nil { + fields = append(fields, chargeusagebased.FieldPrice) + } + if m.unit_config != nil { + fields = append(fields, chargeusagebased.FieldUnitConfig) + } + if m.current_run != nil { + fields = append(fields, chargeusagebased.FieldCurrentRealizationRunID) + } + if m.status_detailed != nil { + fields = append(fields, chargeusagebased.FieldStatusDetailed) + } + 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.FieldCustomerID: + return m.CustomerID() + case chargeusagebased.FieldServicePeriodFrom: + return m.ServicePeriodFrom() + case chargeusagebased.FieldServicePeriodTo: + return m.ServicePeriodTo() + case chargeusagebased.FieldBillingPeriodFrom: + return m.BillingPeriodFrom() + case chargeusagebased.FieldBillingPeriodTo: + return m.BillingPeriodTo() + case chargeusagebased.FieldFullServicePeriodFrom: + return m.FullServicePeriodFrom() + case chargeusagebased.FieldFullServicePeriodTo: + return m.FullServicePeriodTo() + case chargeusagebased.FieldStatus: + return m.Status() + case chargeusagebased.FieldUniqueReferenceID: + return m.UniqueReferenceID() + case chargeusagebased.FieldCurrency: + return m.Currency() + case chargeusagebased.FieldManagedBy: + return m.ManagedBy() + case chargeusagebased.FieldSubscriptionID: + return m.SubscriptionID() + case chargeusagebased.FieldSubscriptionPhaseID: + return m.SubscriptionPhaseID() + case chargeusagebased.FieldSubscriptionItemID: + return m.SubscriptionItemID() + case chargeusagebased.FieldAdvanceAfter: + return m.AdvanceAfter() + case chargeusagebased.FieldTaxCodeID: + return m.TaxCodeID() + case chargeusagebased.FieldTaxBehavior: + return m.TaxBehavior() + case chargeusagebased.FieldAnnotations: + return m.Annotations() + case chargeusagebased.FieldNamespace: + return m.Namespace() + case chargeusagebased.FieldMetadata: + return m.Metadata() + case chargeusagebased.FieldCreatedAt: + return m.CreatedAt() + case chargeusagebased.FieldUpdatedAt: + return m.UpdatedAt() + case chargeusagebased.FieldDeletedAt: + return m.DeletedAt() + case chargeusagebased.FieldName: + return m.Name() + case chargeusagebased.FieldDescription: + return m.Description() + case chargeusagebased.FieldInvoiceAt: + return m.InvoiceAt() + case chargeusagebased.FieldSettlementMode: + return m.SettlementMode() + case chargeusagebased.FieldIntentDeletedAt: + return m.IntentDeletedAt() + case chargeusagebased.FieldDiscounts: + return m.Discounts() + case chargeusagebased.FieldFeatureKey: + return m.FeatureKey() + case chargeusagebased.FieldFeatureID: + return m.FeatureID() + case chargeusagebased.FieldRatingEngine: + return m.RatingEngine() + case chargeusagebased.FieldPrice: + return m.Price() + case chargeusagebased.FieldUnitConfig: + return m.UnitConfig() + case chargeusagebased.FieldCurrentRealizationRunID: + return m.CurrentRealizationRunID() + case chargeusagebased.FieldStatusDetailed: + return m.StatusDetailed() + } + 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.FieldCustomerID: + return m.OldCustomerID(ctx) + case chargeusagebased.FieldServicePeriodFrom: + return m.OldServicePeriodFrom(ctx) + case chargeusagebased.FieldServicePeriodTo: + return m.OldServicePeriodTo(ctx) + case chargeusagebased.FieldBillingPeriodFrom: + return m.OldBillingPeriodFrom(ctx) + case chargeusagebased.FieldBillingPeriodTo: + return m.OldBillingPeriodTo(ctx) + case chargeusagebased.FieldFullServicePeriodFrom: + return m.OldFullServicePeriodFrom(ctx) + case chargeusagebased.FieldFullServicePeriodTo: + return m.OldFullServicePeriodTo(ctx) + case chargeusagebased.FieldStatus: + return m.OldStatus(ctx) + case chargeusagebased.FieldUniqueReferenceID: + return m.OldUniqueReferenceID(ctx) + case chargeusagebased.FieldCurrency: + return m.OldCurrency(ctx) + case chargeusagebased.FieldManagedBy: + return m.OldManagedBy(ctx) + case chargeusagebased.FieldSubscriptionID: + return m.OldSubscriptionID(ctx) + case chargeusagebased.FieldSubscriptionPhaseID: + return m.OldSubscriptionPhaseID(ctx) + case chargeusagebased.FieldSubscriptionItemID: + return m.OldSubscriptionItemID(ctx) + case chargeusagebased.FieldAdvanceAfter: + return m.OldAdvanceAfter(ctx) + case chargeusagebased.FieldTaxCodeID: + return m.OldTaxCodeID(ctx) + case chargeusagebased.FieldTaxBehavior: + return m.OldTaxBehavior(ctx) + case chargeusagebased.FieldAnnotations: + return m.OldAnnotations(ctx) + case chargeusagebased.FieldNamespace: + return m.OldNamespace(ctx) + case chargeusagebased.FieldMetadata: + return m.OldMetadata(ctx) + case chargeusagebased.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case chargeusagebased.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case chargeusagebased.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case chargeusagebased.FieldName: + return m.OldName(ctx) + case chargeusagebased.FieldDescription: + return m.OldDescription(ctx) + case chargeusagebased.FieldInvoiceAt: + return m.OldInvoiceAt(ctx) + case chargeusagebased.FieldSettlementMode: + return m.OldSettlementMode(ctx) + case chargeusagebased.FieldIntentDeletedAt: + return m.OldIntentDeletedAt(ctx) + case chargeusagebased.FieldDiscounts: + return m.OldDiscounts(ctx) + case chargeusagebased.FieldFeatureKey: + return m.OldFeatureKey(ctx) + case chargeusagebased.FieldFeatureID: + return m.OldFeatureID(ctx) + case chargeusagebased.FieldRatingEngine: + return m.OldRatingEngine(ctx) + case chargeusagebased.FieldPrice: + return m.OldPrice(ctx) + case chargeusagebased.FieldUnitConfig: + return m.OldUnitConfig(ctx) + case chargeusagebased.FieldCurrentRealizationRunID: + return m.OldCurrentRealizationRunID(ctx) + case chargeusagebased.FieldStatusDetailed: + return m.OldStatusDetailed(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.FieldCustomerID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerID(v) + return nil + case chargeusagebased.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 chargeusagebased.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 chargeusagebased.FieldBillingPeriodFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingPeriodFrom(v) + return nil + case chargeusagebased.FieldBillingPeriodTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingPeriodTo(v) + return nil + case chargeusagebased.FieldFullServicePeriodFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFullServicePeriodFrom(v) + return nil + case chargeusagebased.FieldFullServicePeriodTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFullServicePeriodTo(v) + return nil + case chargeusagebased.FieldStatus: + v, ok := value.(meta.ChargeStatus) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case chargeusagebased.FieldUniqueReferenceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUniqueReferenceID(v) + return nil + case chargeusagebased.FieldCurrency: + v, ok := value.(currencyx.Code) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrency(v) + return nil + case chargeusagebased.FieldManagedBy: + v, ok := value.(billing.InvoiceLineManagedBy) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetManagedBy(v) + return nil + case chargeusagebased.FieldSubscriptionID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionID(v) + return nil + case chargeusagebased.FieldSubscriptionPhaseID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionPhaseID(v) + return nil + case chargeusagebased.FieldSubscriptionItemID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionItemID(v) + return nil + case chargeusagebased.FieldAdvanceAfter: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAdvanceAfter(v) + return nil + case chargeusagebased.FieldTaxCodeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxCodeID(v) + return nil + case chargeusagebased.FieldTaxBehavior: + v, ok := value.(productcatalog.TaxBehavior) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxBehavior(v) + return nil + case chargeusagebased.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 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.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case chargeusagebased.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 chargeusagebased.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 chargeusagebased.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 chargeusagebased.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case chargeusagebased.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(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.FieldIntentDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIntentDeletedAt(v) + return nil + case chargeusagebased.FieldDiscounts: + v, ok := value.(*billing.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.FieldFeatureID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFeatureID(v) + return nil + case chargeusagebased.FieldRatingEngine: + v, ok := value.(usagebased.RatingEngine) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRatingEngine(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 + case chargeusagebased.FieldUnitConfig: + v, ok := value.(*productcatalog.UnitConfig) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUnitConfig(v) + return nil + case chargeusagebased.FieldCurrentRealizationRunID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrentRealizationRunID(v) + return nil + case chargeusagebased.FieldStatusDetailed: + v, ok := value.(usagebased.Status) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatusDetailed(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.FieldUniqueReferenceID) { + fields = append(fields, chargeusagebased.FieldUniqueReferenceID) + } + if m.FieldCleared(chargeusagebased.FieldSubscriptionID) { + fields = append(fields, chargeusagebased.FieldSubscriptionID) + } + if m.FieldCleared(chargeusagebased.FieldSubscriptionPhaseID) { + fields = append(fields, chargeusagebased.FieldSubscriptionPhaseID) + } + if m.FieldCleared(chargeusagebased.FieldSubscriptionItemID) { + fields = append(fields, chargeusagebased.FieldSubscriptionItemID) + } + if m.FieldCleared(chargeusagebased.FieldAdvanceAfter) { + fields = append(fields, chargeusagebased.FieldAdvanceAfter) + } + if m.FieldCleared(chargeusagebased.FieldTaxBehavior) { + fields = append(fields, chargeusagebased.FieldTaxBehavior) + } + if m.FieldCleared(chargeusagebased.FieldAnnotations) { + fields = append(fields, chargeusagebased.FieldAnnotations) + } + if m.FieldCleared(chargeusagebased.FieldMetadata) { + fields = append(fields, chargeusagebased.FieldMetadata) + } + if m.FieldCleared(chargeusagebased.FieldDeletedAt) { + fields = append(fields, chargeusagebased.FieldDeletedAt) + } + if m.FieldCleared(chargeusagebased.FieldDescription) { + fields = append(fields, chargeusagebased.FieldDescription) + } + if m.FieldCleared(chargeusagebased.FieldIntentDeletedAt) { + fields = append(fields, chargeusagebased.FieldIntentDeletedAt) + } + if m.FieldCleared(chargeusagebased.FieldDiscounts) { + fields = append(fields, chargeusagebased.FieldDiscounts) + } + if m.FieldCleared(chargeusagebased.FieldUnitConfig) { + fields = append(fields, chargeusagebased.FieldUnitConfig) + } + if m.FieldCleared(chargeusagebased.FieldCurrentRealizationRunID) { + fields = append(fields, chargeusagebased.FieldCurrentRealizationRunID) + } + 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.FieldUniqueReferenceID: + m.ClearUniqueReferenceID() + return nil + case chargeusagebased.FieldSubscriptionID: + m.ClearSubscriptionID() + return nil + case chargeusagebased.FieldSubscriptionPhaseID: + m.ClearSubscriptionPhaseID() + return nil + case chargeusagebased.FieldSubscriptionItemID: + m.ClearSubscriptionItemID() + return nil + case chargeusagebased.FieldAdvanceAfter: + m.ClearAdvanceAfter() + return nil + case chargeusagebased.FieldTaxBehavior: + m.ClearTaxBehavior() + return nil + case chargeusagebased.FieldAnnotations: + m.ClearAnnotations() + return nil + case chargeusagebased.FieldMetadata: + m.ClearMetadata() + return nil + case chargeusagebased.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case chargeusagebased.FieldDescription: + m.ClearDescription() + return nil + case chargeusagebased.FieldIntentDeletedAt: + m.ClearIntentDeletedAt() + return nil + case chargeusagebased.FieldDiscounts: + m.ClearDiscounts() + return nil + case chargeusagebased.FieldUnitConfig: + m.ClearUnitConfig() + return nil + case chargeusagebased.FieldCurrentRealizationRunID: + m.ClearCurrentRealizationRunID() + 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.FieldCustomerID: + m.ResetCustomerID() + return nil + case chargeusagebased.FieldServicePeriodFrom: + m.ResetServicePeriodFrom() + return nil + case chargeusagebased.FieldServicePeriodTo: + m.ResetServicePeriodTo() + return nil + case chargeusagebased.FieldBillingPeriodFrom: + m.ResetBillingPeriodFrom() + return nil + case chargeusagebased.FieldBillingPeriodTo: + m.ResetBillingPeriodTo() + return nil + case chargeusagebased.FieldFullServicePeriodFrom: + m.ResetFullServicePeriodFrom() + return nil + case chargeusagebased.FieldFullServicePeriodTo: + m.ResetFullServicePeriodTo() + return nil + case chargeusagebased.FieldStatus: + m.ResetStatus() + return nil + case chargeusagebased.FieldUniqueReferenceID: + m.ResetUniqueReferenceID() + return nil + case chargeusagebased.FieldCurrency: + m.ResetCurrency() + return nil + case chargeusagebased.FieldManagedBy: + m.ResetManagedBy() + return nil + case chargeusagebased.FieldSubscriptionID: + m.ResetSubscriptionID() + return nil + case chargeusagebased.FieldSubscriptionPhaseID: + m.ResetSubscriptionPhaseID() + return nil + case chargeusagebased.FieldSubscriptionItemID: + m.ResetSubscriptionItemID() + return nil + case chargeusagebased.FieldAdvanceAfter: + m.ResetAdvanceAfter() + return nil + case chargeusagebased.FieldTaxCodeID: + m.ResetTaxCodeID() + return nil + case chargeusagebased.FieldTaxBehavior: + m.ResetTaxBehavior() + return nil + case chargeusagebased.FieldAnnotations: + m.ResetAnnotations() + return nil + case chargeusagebased.FieldNamespace: + m.ResetNamespace() + return nil + case chargeusagebased.FieldMetadata: + m.ResetMetadata() + return nil + case chargeusagebased.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case chargeusagebased.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case chargeusagebased.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case chargeusagebased.FieldName: + m.ResetName() + return nil + case chargeusagebased.FieldDescription: + m.ResetDescription() + return nil + case chargeusagebased.FieldInvoiceAt: + m.ResetInvoiceAt() + return nil + case chargeusagebased.FieldSettlementMode: + m.ResetSettlementMode() + return nil + case chargeusagebased.FieldIntentDeletedAt: + m.ResetIntentDeletedAt() + return nil + case chargeusagebased.FieldDiscounts: + m.ResetDiscounts() + return nil + case chargeusagebased.FieldFeatureKey: + m.ResetFeatureKey() + return nil + case chargeusagebased.FieldFeatureID: + m.ResetFeatureID() + return nil + case chargeusagebased.FieldRatingEngine: + m.ResetRatingEngine() + return nil + case chargeusagebased.FieldPrice: + m.ResetPrice() + return nil + case chargeusagebased.FieldUnitConfig: + m.ResetUnitConfig() + return nil + case chargeusagebased.FieldCurrentRealizationRunID: + m.ResetCurrentRealizationRunID() + return nil + case chargeusagebased.FieldStatusDetailed: + m.ResetStatusDetailed() + 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, 11) + if m.runs != nil { + edges = append(edges, chargeusagebased.EdgeRuns) + } + if m.detailed_lines != nil { + edges = append(edges, chargeusagebased.EdgeDetailedLines) + } + if m.current_run != nil { + edges = append(edges, chargeusagebased.EdgeCurrentRun) + } + if m.charge != nil { + edges = append(edges, chargeusagebased.EdgeCharge) + } + if m.intent_override != nil { + edges = append(edges, chargeusagebased.EdgeIntentOverride) + } + if m.subscription != nil { + edges = append(edges, chargeusagebased.EdgeSubscription) + } + if m.subscription_phase != nil { + edges = append(edges, chargeusagebased.EdgeSubscriptionPhase) + } + if m.subscription_item != nil { + edges = append(edges, chargeusagebased.EdgeSubscriptionItem) + } + if m.customer != nil { + edges = append(edges, chargeusagebased.EdgeCustomer) + } + if m.feature != nil { + edges = append(edges, chargeusagebased.EdgeFeature) + } + if m.tax_code != nil { + edges = append(edges, chargeusagebased.EdgeTaxCode) + } + 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.EdgeRuns: + ids := make([]ent.Value, 0, len(m.runs)) + for id := range m.runs { + ids = append(ids, id) + } + return ids + case chargeusagebased.EdgeDetailedLines: + ids := make([]ent.Value, 0, len(m.detailed_lines)) + for id := range m.detailed_lines { + ids = append(ids, id) + } + return ids + case chargeusagebased.EdgeCurrentRun: + if id := m.current_run; id != nil { + return []ent.Value{*id} + } + case chargeusagebased.EdgeCharge: + if id := m.charge; id != nil { + return []ent.Value{*id} + } + case chargeusagebased.EdgeIntentOverride: + if id := m.intent_override; id != nil { + return []ent.Value{*id} + } + case chargeusagebased.EdgeSubscription: + if id := m.subscription; id != nil { + return []ent.Value{*id} + } + case chargeusagebased.EdgeSubscriptionPhase: + if id := m.subscription_phase; id != nil { + return []ent.Value{*id} + } + case chargeusagebased.EdgeSubscriptionItem: + if id := m.subscription_item; id != nil { + return []ent.Value{*id} + } + case chargeusagebased.EdgeCustomer: + if id := m.customer; id != nil { + return []ent.Value{*id} + } + case chargeusagebased.EdgeFeature: + if id := m.feature; id != nil { + return []ent.Value{*id} + } + case chargeusagebased.EdgeTaxCode: + if id := m.tax_code; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ChargeUsageBasedMutation) RemovedEdges() []string { + edges := make([]string, 0, 11) + if m.removedruns != nil { + edges = append(edges, chargeusagebased.EdgeRuns) + } + if m.removeddetailed_lines != nil { + edges = append(edges, chargeusagebased.EdgeDetailedLines) + } + 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 + case chargeusagebased.EdgeDetailedLines: + ids := make([]ent.Value, 0, len(m.removeddetailed_lines)) + for id := range m.removeddetailed_lines { + 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, 11) + if m.clearedruns { + edges = append(edges, chargeusagebased.EdgeRuns) + } + if m.cleareddetailed_lines { + edges = append(edges, chargeusagebased.EdgeDetailedLines) + } + if m.clearedcurrent_run { + edges = append(edges, chargeusagebased.EdgeCurrentRun) + } + if m.clearedcharge { + edges = append(edges, chargeusagebased.EdgeCharge) + } + if m.clearedintent_override { + edges = append(edges, chargeusagebased.EdgeIntentOverride) + } + if m.clearedsubscription { + edges = append(edges, chargeusagebased.EdgeSubscription) + } + if m.clearedsubscription_phase { + edges = append(edges, chargeusagebased.EdgeSubscriptionPhase) + } + if m.clearedsubscription_item { + edges = append(edges, chargeusagebased.EdgeSubscriptionItem) + } + if m.clearedcustomer { + edges = append(edges, chargeusagebased.EdgeCustomer) + } + if m.clearedfeature { + edges = append(edges, chargeusagebased.EdgeFeature) + } + if m.clearedtax_code { + edges = append(edges, chargeusagebased.EdgeTaxCode) + } + 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.EdgeRuns: + return m.clearedruns + case chargeusagebased.EdgeDetailedLines: + return m.cleareddetailed_lines + case chargeusagebased.EdgeCurrentRun: + return m.clearedcurrent_run + case chargeusagebased.EdgeCharge: + return m.clearedcharge + case chargeusagebased.EdgeIntentOverride: + return m.clearedintent_override + case chargeusagebased.EdgeSubscription: + return m.clearedsubscription + case chargeusagebased.EdgeSubscriptionPhase: + return m.clearedsubscription_phase + case chargeusagebased.EdgeSubscriptionItem: + return m.clearedsubscription_item + case chargeusagebased.EdgeCustomer: + return m.clearedcustomer + case chargeusagebased.EdgeFeature: + return m.clearedfeature + case chargeusagebased.EdgeTaxCode: + return m.clearedtax_code + } + 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.EdgeCurrentRun: + m.ClearCurrentRun() + return nil + case chargeusagebased.EdgeCharge: + m.ClearCharge() + return nil + case chargeusagebased.EdgeIntentOverride: + m.ClearIntentOverride() + return nil + case chargeusagebased.EdgeSubscription: + m.ClearSubscription() + return nil + case chargeusagebased.EdgeSubscriptionPhase: + m.ClearSubscriptionPhase() + return nil + case chargeusagebased.EdgeSubscriptionItem: + m.ClearSubscriptionItem() + return nil + case chargeusagebased.EdgeCustomer: + m.ClearCustomer() + return nil + case chargeusagebased.EdgeFeature: + m.ClearFeature() + return nil + case chargeusagebased.EdgeTaxCode: + m.ClearTaxCode() + 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.EdgeRuns: + m.ResetRuns() + return nil + case chargeusagebased.EdgeDetailedLines: + m.ResetDetailedLines() + return nil + case chargeusagebased.EdgeCurrentRun: + m.ResetCurrentRun() + return nil + case chargeusagebased.EdgeCharge: + m.ResetCharge() + return nil + case chargeusagebased.EdgeIntentOverride: + m.ResetIntentOverride() + return nil + case chargeusagebased.EdgeSubscription: + m.ResetSubscription() + return nil + case chargeusagebased.EdgeSubscriptionPhase: + m.ResetSubscriptionPhase() + return nil + case chargeusagebased.EdgeSubscriptionItem: + m.ResetSubscriptionItem() + return nil + case chargeusagebased.EdgeCustomer: + m.ResetCustomer() + return nil + case chargeusagebased.EdgeFeature: + m.ResetFeature() + return nil + case chargeusagebased.EdgeTaxCode: + m.ResetTaxCode() + return nil + } + return fmt.Errorf("unknown ChargeUsageBased edge %s", name) +} + +// ChargeUsageBasedOverrideMutation represents an operation that mutates the ChargeUsageBasedOverride nodes in the graph. +type ChargeUsageBasedOverrideMutation struct { + config + op Op + typ string + id *string + namespace *string + name *string + description *string + metadata **models.Metadata + tax_behavior *productcatalog.TaxBehavior + intent_deleted_at *time.Time + service_period_from *time.Time + service_period_to *time.Time + full_service_period_from *time.Time + full_service_period_to *time.Time + billing_period_from *time.Time + billing_period_to *time.Time + invoice_at *time.Time + feature_key *string + price **productcatalog.Price + discounts **billing.Discounts + unit_config **productcatalog.UnitConfig + clearedFields map[string]struct{} + usage_based *string + clearedusage_based bool + tax_code *string + clearedtax_code bool + done bool + oldValue func(context.Context) (*ChargeUsageBasedOverride, error) + predicates []predicate.ChargeUsageBasedOverride +} + +var _ ent.Mutation = (*ChargeUsageBasedOverrideMutation)(nil) + +// chargeusagebasedoverrideOption allows management of the mutation configuration using functional options. +type chargeusagebasedoverrideOption func(*ChargeUsageBasedOverrideMutation) + +// newChargeUsageBasedOverrideMutation creates new mutation for the ChargeUsageBasedOverride entity. +func newChargeUsageBasedOverrideMutation(c config, op Op, opts ...chargeusagebasedoverrideOption) *ChargeUsageBasedOverrideMutation { + m := &ChargeUsageBasedOverrideMutation{ + config: c, + op: op, + typ: TypeChargeUsageBasedOverride, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withChargeUsageBasedOverrideID sets the ID field of the mutation. +func withChargeUsageBasedOverrideID(id string) chargeusagebasedoverrideOption { + return func(m *ChargeUsageBasedOverrideMutation) { + var ( + err error + once sync.Once + value *ChargeUsageBasedOverride + ) + m.oldValue = func(ctx context.Context) (*ChargeUsageBasedOverride, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ChargeUsageBasedOverride.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withChargeUsageBasedOverride sets the old ChargeUsageBasedOverride of the mutation. +func withChargeUsageBasedOverride(node *ChargeUsageBasedOverride) chargeusagebasedoverrideOption { + return func(m *ChargeUsageBasedOverrideMutation) { + m.oldValue = func(context.Context) (*ChargeUsageBasedOverride, 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 ChargeUsageBasedOverrideMutation) 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 ChargeUsageBasedOverrideMutation) 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 ChargeUsageBasedOverride entities. +func (m *ChargeUsageBasedOverrideMutation) 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 *ChargeUsageBasedOverrideMutation) 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 *ChargeUsageBasedOverrideMutation) 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().ChargeUsageBasedOverride.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 *ChargeUsageBasedOverrideMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *ChargeUsageBasedOverrideMutation) 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 ChargeUsageBasedOverride entity. +// If the ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) 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 *ChargeUsageBasedOverrideMutation) ResetNamespace() { + m.namespace = nil +} + +// SetChargeID sets the "charge_id" field. +func (m *ChargeUsageBasedOverrideMutation) SetChargeID(s string) { + m.usage_based = &s +} + +// ChargeID returns the value of the "charge_id" field in the mutation. +func (m *ChargeUsageBasedOverrideMutation) 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 ChargeUsageBasedOverride entity. +// If the ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) 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 *ChargeUsageBasedOverrideMutation) ResetChargeID() { + m.usage_based = nil +} + +// SetName sets the "name" field. +func (m *ChargeUsageBasedOverrideMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *ChargeUsageBasedOverrideMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the ChargeUsageBasedOverride entity. +// If the ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *ChargeUsageBasedOverrideMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *ChargeUsageBasedOverrideMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *ChargeUsageBasedOverrideMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the ChargeUsageBasedOverride entity. +// If the ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *ChargeUsageBasedOverrideMutation) ClearDescription() { + m.description = nil + m.clearedFields[chargeusagebasedoverride.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *ChargeUsageBasedOverrideMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[chargeusagebasedoverride.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *ChargeUsageBasedOverrideMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, chargeusagebasedoverride.FieldDescription) +} + +// SetMetadata sets the "metadata" field. +func (m *ChargeUsageBasedOverrideMutation) SetMetadata(value *models.Metadata) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *ChargeUsageBasedOverrideMutation) Metadata() (r *models.Metadata, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the ChargeUsageBasedOverride entity. +// If the ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) OldMetadata(ctx context.Context) (v *models.Metadata, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *ChargeUsageBasedOverrideMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[chargeusagebasedoverride.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *ChargeUsageBasedOverrideMutation) MetadataCleared() bool { + _, ok := m.clearedFields[chargeusagebasedoverride.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *ChargeUsageBasedOverrideMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, chargeusagebasedoverride.FieldMetadata) +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (m *ChargeUsageBasedOverrideMutation) SetTaxBehavior(pb productcatalog.TaxBehavior) { + m.tax_behavior = &pb +} + +// TaxBehavior returns the value of the "tax_behavior" field in the mutation. +func (m *ChargeUsageBasedOverrideMutation) TaxBehavior() (r productcatalog.TaxBehavior, exists bool) { + v := m.tax_behavior + if v == nil { + return + } + return *v, true +} + +// OldTaxBehavior returns the old "tax_behavior" field's value of the ChargeUsageBasedOverride entity. +// If the ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) OldTaxBehavior(ctx context.Context) (v *productcatalog.TaxBehavior, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxBehavior is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxBehavior requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxBehavior: %w", err) + } + return oldValue.TaxBehavior, nil +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (m *ChargeUsageBasedOverrideMutation) ClearTaxBehavior() { + m.tax_behavior = nil + m.clearedFields[chargeusagebasedoverride.FieldTaxBehavior] = struct{}{} +} + +// TaxBehaviorCleared returns if the "tax_behavior" field was cleared in this mutation. +func (m *ChargeUsageBasedOverrideMutation) TaxBehaviorCleared() bool { + _, ok := m.clearedFields[chargeusagebasedoverride.FieldTaxBehavior] + return ok +} + +// ResetTaxBehavior resets all changes to the "tax_behavior" field. +func (m *ChargeUsageBasedOverrideMutation) ResetTaxBehavior() { + m.tax_behavior = nil + delete(m.clearedFields, chargeusagebasedoverride.FieldTaxBehavior) +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (m *ChargeUsageBasedOverrideMutation) SetTaxCodeID(s string) { + m.tax_code = &s +} + +// TaxCodeID returns the value of the "tax_code_id" field in the mutation. +func (m *ChargeUsageBasedOverrideMutation) TaxCodeID() (r string, exists bool) { + v := m.tax_code + if v == nil { + return + } + return *v, true +} + +// OldTaxCodeID returns the old "tax_code_id" field's value of the ChargeUsageBasedOverride entity. +// If the ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) OldTaxCodeID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxCodeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxCodeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxCodeID: %w", err) + } + return oldValue.TaxCodeID, nil +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (m *ChargeUsageBasedOverrideMutation) ClearTaxCodeID() { + m.tax_code = nil + m.clearedFields[chargeusagebasedoverride.FieldTaxCodeID] = struct{}{} +} + +// TaxCodeIDCleared returns if the "tax_code_id" field was cleared in this mutation. +func (m *ChargeUsageBasedOverrideMutation) TaxCodeIDCleared() bool { + _, ok := m.clearedFields[chargeusagebasedoverride.FieldTaxCodeID] + return ok +} + +// ResetTaxCodeID resets all changes to the "tax_code_id" field. +func (m *ChargeUsageBasedOverrideMutation) ResetTaxCodeID() { + m.tax_code = nil + delete(m.clearedFields, chargeusagebasedoverride.FieldTaxCodeID) +} + +// SetIntentDeletedAt sets the "intent_deleted_at" field. +func (m *ChargeUsageBasedOverrideMutation) SetIntentDeletedAt(t time.Time) { + m.intent_deleted_at = &t +} + +// IntentDeletedAt returns the value of the "intent_deleted_at" field in the mutation. +func (m *ChargeUsageBasedOverrideMutation) IntentDeletedAt() (r time.Time, exists bool) { + v := m.intent_deleted_at + if v == nil { + return + } + return *v, true +} + +// OldIntentDeletedAt returns the old "intent_deleted_at" field's value of the ChargeUsageBasedOverride entity. +// If the ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) OldIntentDeletedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIntentDeletedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIntentDeletedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIntentDeletedAt: %w", err) + } + return oldValue.IntentDeletedAt, nil +} + +// ClearIntentDeletedAt clears the value of the "intent_deleted_at" field. +func (m *ChargeUsageBasedOverrideMutation) ClearIntentDeletedAt() { + m.intent_deleted_at = nil + m.clearedFields[chargeusagebasedoverride.FieldIntentDeletedAt] = struct{}{} +} + +// IntentDeletedAtCleared returns if the "intent_deleted_at" field was cleared in this mutation. +func (m *ChargeUsageBasedOverrideMutation) IntentDeletedAtCleared() bool { + _, ok := m.clearedFields[chargeusagebasedoverride.FieldIntentDeletedAt] + return ok +} + +// ResetIntentDeletedAt resets all changes to the "intent_deleted_at" field. +func (m *ChargeUsageBasedOverrideMutation) ResetIntentDeletedAt() { + m.intent_deleted_at = nil + delete(m.clearedFields, chargeusagebasedoverride.FieldIntentDeletedAt) +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (m *ChargeUsageBasedOverrideMutation) SetServicePeriodFrom(t time.Time) { + m.service_period_from = &t +} + +// ServicePeriodFrom returns the value of the "service_period_from" field in the mutation. +func (m *ChargeUsageBasedOverrideMutation) 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 ChargeUsageBasedOverride entity. +// If the ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) 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 *ChargeUsageBasedOverrideMutation) ResetServicePeriodFrom() { + m.service_period_from = nil +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (m *ChargeUsageBasedOverrideMutation) SetServicePeriodTo(t time.Time) { + m.service_period_to = &t +} + +// ServicePeriodTo returns the value of the "service_period_to" field in the mutation. +func (m *ChargeUsageBasedOverrideMutation) 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 ChargeUsageBasedOverride entity. +// If the ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) 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 *ChargeUsageBasedOverrideMutation) ResetServicePeriodTo() { + m.service_period_to = nil +} + +// SetFullServicePeriodFrom sets the "full_service_period_from" field. +func (m *ChargeUsageBasedOverrideMutation) SetFullServicePeriodFrom(t time.Time) { + m.full_service_period_from = &t +} + +// FullServicePeriodFrom returns the value of the "full_service_period_from" field in the mutation. +func (m *ChargeUsageBasedOverrideMutation) FullServicePeriodFrom() (r time.Time, exists bool) { + v := m.full_service_period_from + if v == nil { + return + } + return *v, true +} + +// OldFullServicePeriodFrom returns the old "full_service_period_from" field's value of the ChargeUsageBasedOverride entity. +// If the ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) OldFullServicePeriodFrom(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFullServicePeriodFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFullServicePeriodFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFullServicePeriodFrom: %w", err) + } + return oldValue.FullServicePeriodFrom, nil +} + +// ResetFullServicePeriodFrom resets all changes to the "full_service_period_from" field. +func (m *ChargeUsageBasedOverrideMutation) ResetFullServicePeriodFrom() { + m.full_service_period_from = nil +} + +// SetFullServicePeriodTo sets the "full_service_period_to" field. +func (m *ChargeUsageBasedOverrideMutation) SetFullServicePeriodTo(t time.Time) { + m.full_service_period_to = &t +} + +// FullServicePeriodTo returns the value of the "full_service_period_to" field in the mutation. +func (m *ChargeUsageBasedOverrideMutation) FullServicePeriodTo() (r time.Time, exists bool) { + v := m.full_service_period_to + if v == nil { + return + } + return *v, true +} + +// OldFullServicePeriodTo returns the old "full_service_period_to" field's value of the ChargeUsageBasedOverride entity. +// If the ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) OldFullServicePeriodTo(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFullServicePeriodTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFullServicePeriodTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFullServicePeriodTo: %w", err) + } + return oldValue.FullServicePeriodTo, nil +} + +// ResetFullServicePeriodTo resets all changes to the "full_service_period_to" field. +func (m *ChargeUsageBasedOverrideMutation) ResetFullServicePeriodTo() { + m.full_service_period_to = nil +} + +// SetBillingPeriodFrom sets the "billing_period_from" field. +func (m *ChargeUsageBasedOverrideMutation) SetBillingPeriodFrom(t time.Time) { + m.billing_period_from = &t +} + +// BillingPeriodFrom returns the value of the "billing_period_from" field in the mutation. +func (m *ChargeUsageBasedOverrideMutation) BillingPeriodFrom() (r time.Time, exists bool) { + v := m.billing_period_from + if v == nil { + return + } + return *v, true +} + +// OldBillingPeriodFrom returns the old "billing_period_from" field's value of the ChargeUsageBasedOverride entity. +// If the ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) OldBillingPeriodFrom(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingPeriodFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingPeriodFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingPeriodFrom: %w", err) + } + return oldValue.BillingPeriodFrom, nil +} + +// ResetBillingPeriodFrom resets all changes to the "billing_period_from" field. +func (m *ChargeUsageBasedOverrideMutation) ResetBillingPeriodFrom() { + m.billing_period_from = nil +} + +// SetBillingPeriodTo sets the "billing_period_to" field. +func (m *ChargeUsageBasedOverrideMutation) SetBillingPeriodTo(t time.Time) { + m.billing_period_to = &t +} + +// BillingPeriodTo returns the value of the "billing_period_to" field in the mutation. +func (m *ChargeUsageBasedOverrideMutation) BillingPeriodTo() (r time.Time, exists bool) { + v := m.billing_period_to + if v == nil { + return + } + return *v, true +} + +// OldBillingPeriodTo returns the old "billing_period_to" field's value of the ChargeUsageBasedOverride entity. +// If the ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) OldBillingPeriodTo(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingPeriodTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingPeriodTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingPeriodTo: %w", err) + } + return oldValue.BillingPeriodTo, nil +} + +// ResetBillingPeriodTo resets all changes to the "billing_period_to" field. +func (m *ChargeUsageBasedOverrideMutation) ResetBillingPeriodTo() { + m.billing_period_to = nil +} + +// SetInvoiceAt sets the "invoice_at" field. +func (m *ChargeUsageBasedOverrideMutation) SetInvoiceAt(t time.Time) { + m.invoice_at = &t +} + +// InvoiceAt returns the value of the "invoice_at" field in the mutation. +func (m *ChargeUsageBasedOverrideMutation) 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 ChargeUsageBasedOverride entity. +// If the ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) 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 *ChargeUsageBasedOverrideMutation) ResetInvoiceAt() { + m.invoice_at = nil +} + +// SetFeatureKey sets the "feature_key" field. +func (m *ChargeUsageBasedOverrideMutation) SetFeatureKey(s string) { + m.feature_key = &s +} + +// FeatureKey returns the value of the "feature_key" field in the mutation. +func (m *ChargeUsageBasedOverrideMutation) 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 ChargeUsageBasedOverride entity. +// If the ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) 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 +} + +// ClearFeatureKey clears the value of the "feature_key" field. +func (m *ChargeUsageBasedOverrideMutation) ClearFeatureKey() { + m.feature_key = nil + m.clearedFields[chargeusagebasedoverride.FieldFeatureKey] = struct{}{} +} + +// FeatureKeyCleared returns if the "feature_key" field was cleared in this mutation. +func (m *ChargeUsageBasedOverrideMutation) FeatureKeyCleared() bool { + _, ok := m.clearedFields[chargeusagebasedoverride.FieldFeatureKey] + return ok +} + +// ResetFeatureKey resets all changes to the "feature_key" field. +func (m *ChargeUsageBasedOverrideMutation) ResetFeatureKey() { + m.feature_key = nil + delete(m.clearedFields, chargeusagebasedoverride.FieldFeatureKey) +} + +// SetPrice sets the "price" field. +func (m *ChargeUsageBasedOverrideMutation) SetPrice(pr *productcatalog.Price) { + m.price = &pr +} + +// Price returns the value of the "price" field in the mutation. +func (m *ChargeUsageBasedOverrideMutation) 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 ChargeUsageBasedOverride entity. +// If the ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) 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 *ChargeUsageBasedOverrideMutation) ResetPrice() { + m.price = nil +} + +// SetDiscounts sets the "discounts" field. +func (m *ChargeUsageBasedOverrideMutation) SetDiscounts(b *billing.Discounts) { + m.discounts = &b +} + +// Discounts returns the value of the "discounts" field in the mutation. +func (m *ChargeUsageBasedOverrideMutation) Discounts() (r *billing.Discounts, exists bool) { + v := m.discounts + if v == nil { + return + } + return *v, true +} + +// OldDiscounts returns the old "discounts" field's value of the ChargeUsageBasedOverride entity. +// If the ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) OldDiscounts(ctx context.Context) (v *billing.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 +} + +// ResetDiscounts resets all changes to the "discounts" field. +func (m *ChargeUsageBasedOverrideMutation) ResetDiscounts() { + m.discounts = nil +} + +// SetUnitConfig sets the "unit_config" field. +func (m *ChargeUsageBasedOverrideMutation) SetUnitConfig(pc *productcatalog.UnitConfig) { + m.unit_config = &pc +} + +// UnitConfig returns the value of the "unit_config" field in the mutation. +func (m *ChargeUsageBasedOverrideMutation) UnitConfig() (r *productcatalog.UnitConfig, exists bool) { + v := m.unit_config + if v == nil { + return + } + return *v, true +} + +// OldUnitConfig returns the old "unit_config" field's value of the ChargeUsageBasedOverride entity. +// If the ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) OldUnitConfig(ctx context.Context) (v *productcatalog.UnitConfig, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUnitConfig is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUnitConfig requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUnitConfig: %w", err) + } + return oldValue.UnitConfig, nil +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (m *ChargeUsageBasedOverrideMutation) ClearUnitConfig() { + m.unit_config = nil + m.clearedFields[chargeusagebasedoverride.FieldUnitConfig] = struct{}{} +} + +// UnitConfigCleared returns if the "unit_config" field was cleared in this mutation. +func (m *ChargeUsageBasedOverrideMutation) UnitConfigCleared() bool { + _, ok := m.clearedFields[chargeusagebasedoverride.FieldUnitConfig] + return ok +} + +// ResetUnitConfig resets all changes to the "unit_config" field. +func (m *ChargeUsageBasedOverrideMutation) ResetUnitConfig() { + m.unit_config = nil + delete(m.clearedFields, chargeusagebasedoverride.FieldUnitConfig) +} + +// SetUsageBasedID sets the "usage_based" edge to the ChargeUsageBased entity by id. +func (m *ChargeUsageBasedOverrideMutation) SetUsageBasedID(id string) { + m.usage_based = &id +} + +// ClearUsageBased clears the "usage_based" edge to the ChargeUsageBased entity. +func (m *ChargeUsageBasedOverrideMutation) ClearUsageBased() { + m.clearedusage_based = true + m.clearedFields[chargeusagebasedoverride.FieldChargeID] = struct{}{} +} + +// UsageBasedCleared reports if the "usage_based" edge to the ChargeUsageBased entity was cleared. +func (m *ChargeUsageBasedOverrideMutation) UsageBasedCleared() bool { + return m.clearedusage_based +} + +// UsageBasedID returns the "usage_based" edge ID in the mutation. +func (m *ChargeUsageBasedOverrideMutation) 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 *ChargeUsageBasedOverrideMutation) 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 *ChargeUsageBasedOverrideMutation) ResetUsageBased() { + m.usage_based = nil + m.clearedusage_based = false +} + +// ClearTaxCode clears the "tax_code" edge to the TaxCode entity. +func (m *ChargeUsageBasedOverrideMutation) ClearTaxCode() { + m.clearedtax_code = true + m.clearedFields[chargeusagebasedoverride.FieldTaxCodeID] = struct{}{} +} + +// TaxCodeCleared reports if the "tax_code" edge to the TaxCode entity was cleared. +func (m *ChargeUsageBasedOverrideMutation) TaxCodeCleared() bool { + return m.TaxCodeIDCleared() || m.clearedtax_code +} + +// TaxCodeIDs returns the "tax_code" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TaxCodeID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedOverrideMutation) TaxCodeIDs() (ids []string) { + if id := m.tax_code; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTaxCode resets all changes to the "tax_code" edge. +func (m *ChargeUsageBasedOverrideMutation) ResetTaxCode() { + m.tax_code = nil + m.clearedtax_code = false +} + +// Where appends a list predicates to the ChargeUsageBasedOverrideMutation builder. +func (m *ChargeUsageBasedOverrideMutation) Where(ps ...predicate.ChargeUsageBasedOverride) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ChargeUsageBasedOverrideMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ChargeUsageBasedOverrideMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ChargeUsageBasedOverride, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ChargeUsageBasedOverrideMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ChargeUsageBasedOverrideMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ChargeUsageBasedOverride). +func (m *ChargeUsageBasedOverrideMutation) 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 *ChargeUsageBasedOverrideMutation) Fields() []string { + fields := make([]string, 0, 19) + if m.namespace != nil { + fields = append(fields, chargeusagebasedoverride.FieldNamespace) + } + if m.usage_based != nil { + fields = append(fields, chargeusagebasedoverride.FieldChargeID) + } + if m.name != nil { + fields = append(fields, chargeusagebasedoverride.FieldName) + } + if m.description != nil { + fields = append(fields, chargeusagebasedoverride.FieldDescription) + } + if m.metadata != nil { + fields = append(fields, chargeusagebasedoverride.FieldMetadata) + } + if m.tax_behavior != nil { + fields = append(fields, chargeusagebasedoverride.FieldTaxBehavior) + } + if m.tax_code != nil { + fields = append(fields, chargeusagebasedoverride.FieldTaxCodeID) + } + if m.intent_deleted_at != nil { + fields = append(fields, chargeusagebasedoverride.FieldIntentDeletedAt) + } + if m.service_period_from != nil { + fields = append(fields, chargeusagebasedoverride.FieldServicePeriodFrom) + } + if m.service_period_to != nil { + fields = append(fields, chargeusagebasedoverride.FieldServicePeriodTo) + } + if m.full_service_period_from != nil { + fields = append(fields, chargeusagebasedoverride.FieldFullServicePeriodFrom) + } + if m.full_service_period_to != nil { + fields = append(fields, chargeusagebasedoverride.FieldFullServicePeriodTo) + } + if m.billing_period_from != nil { + fields = append(fields, chargeusagebasedoverride.FieldBillingPeriodFrom) + } + if m.billing_period_to != nil { + fields = append(fields, chargeusagebasedoverride.FieldBillingPeriodTo) + } + if m.invoice_at != nil { + fields = append(fields, chargeusagebasedoverride.FieldInvoiceAt) + } + if m.feature_key != nil { + fields = append(fields, chargeusagebasedoverride.FieldFeatureKey) + } + if m.price != nil { + fields = append(fields, chargeusagebasedoverride.FieldPrice) + } + if m.discounts != nil { + fields = append(fields, chargeusagebasedoverride.FieldDiscounts) + } + if m.unit_config != nil { + fields = append(fields, chargeusagebasedoverride.FieldUnitConfig) + } + 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 *ChargeUsageBasedOverrideMutation) Field(name string) (ent.Value, bool) { + switch name { + case chargeusagebasedoverride.FieldNamespace: + return m.Namespace() + case chargeusagebasedoverride.FieldChargeID: + return m.ChargeID() + case chargeusagebasedoverride.FieldName: + return m.Name() + case chargeusagebasedoverride.FieldDescription: + return m.Description() + case chargeusagebasedoverride.FieldMetadata: + return m.Metadata() + case chargeusagebasedoverride.FieldTaxBehavior: + return m.TaxBehavior() + case chargeusagebasedoverride.FieldTaxCodeID: + return m.TaxCodeID() + case chargeusagebasedoverride.FieldIntentDeletedAt: + return m.IntentDeletedAt() + case chargeusagebasedoverride.FieldServicePeriodFrom: + return m.ServicePeriodFrom() + case chargeusagebasedoverride.FieldServicePeriodTo: + return m.ServicePeriodTo() + case chargeusagebasedoverride.FieldFullServicePeriodFrom: + return m.FullServicePeriodFrom() + case chargeusagebasedoverride.FieldFullServicePeriodTo: + return m.FullServicePeriodTo() + case chargeusagebasedoverride.FieldBillingPeriodFrom: + return m.BillingPeriodFrom() + case chargeusagebasedoverride.FieldBillingPeriodTo: + return m.BillingPeriodTo() + case chargeusagebasedoverride.FieldInvoiceAt: + return m.InvoiceAt() + case chargeusagebasedoverride.FieldFeatureKey: + return m.FeatureKey() + case chargeusagebasedoverride.FieldPrice: + return m.Price() + case chargeusagebasedoverride.FieldDiscounts: + return m.Discounts() + case chargeusagebasedoverride.FieldUnitConfig: + return m.UnitConfig() + } + 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 *ChargeUsageBasedOverrideMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case chargeusagebasedoverride.FieldNamespace: + return m.OldNamespace(ctx) + case chargeusagebasedoverride.FieldChargeID: + return m.OldChargeID(ctx) + case chargeusagebasedoverride.FieldName: + return m.OldName(ctx) + case chargeusagebasedoverride.FieldDescription: + return m.OldDescription(ctx) + case chargeusagebasedoverride.FieldMetadata: + return m.OldMetadata(ctx) + case chargeusagebasedoverride.FieldTaxBehavior: + return m.OldTaxBehavior(ctx) + case chargeusagebasedoverride.FieldTaxCodeID: + return m.OldTaxCodeID(ctx) + case chargeusagebasedoverride.FieldIntentDeletedAt: + return m.OldIntentDeletedAt(ctx) + case chargeusagebasedoverride.FieldServicePeriodFrom: + return m.OldServicePeriodFrom(ctx) + case chargeusagebasedoverride.FieldServicePeriodTo: + return m.OldServicePeriodTo(ctx) + case chargeusagebasedoverride.FieldFullServicePeriodFrom: + return m.OldFullServicePeriodFrom(ctx) + case chargeusagebasedoverride.FieldFullServicePeriodTo: + return m.OldFullServicePeriodTo(ctx) + case chargeusagebasedoverride.FieldBillingPeriodFrom: + return m.OldBillingPeriodFrom(ctx) + case chargeusagebasedoverride.FieldBillingPeriodTo: + return m.OldBillingPeriodTo(ctx) + case chargeusagebasedoverride.FieldInvoiceAt: + return m.OldInvoiceAt(ctx) + case chargeusagebasedoverride.FieldFeatureKey: + return m.OldFeatureKey(ctx) + case chargeusagebasedoverride.FieldPrice: + return m.OldPrice(ctx) + case chargeusagebasedoverride.FieldDiscounts: + return m.OldDiscounts(ctx) + case chargeusagebasedoverride.FieldUnitConfig: + return m.OldUnitConfig(ctx) + } + return nil, fmt.Errorf("unknown ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) SetField(name string, value ent.Value) error { + switch name { + case chargeusagebasedoverride.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case chargeusagebasedoverride.FieldChargeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChargeID(v) + return nil + case chargeusagebasedoverride.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case chargeusagebasedoverride.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case chargeusagebasedoverride.FieldMetadata: + v, ok := value.(*models.Metadata) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case chargeusagebasedoverride.FieldTaxBehavior: + v, ok := value.(productcatalog.TaxBehavior) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxBehavior(v) + return nil + case chargeusagebasedoverride.FieldTaxCodeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxCodeID(v) + return nil + case chargeusagebasedoverride.FieldIntentDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIntentDeletedAt(v) + return nil + case chargeusagebasedoverride.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 chargeusagebasedoverride.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 chargeusagebasedoverride.FieldFullServicePeriodFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFullServicePeriodFrom(v) + return nil + case chargeusagebasedoverride.FieldFullServicePeriodTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFullServicePeriodTo(v) + return nil + case chargeusagebasedoverride.FieldBillingPeriodFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingPeriodFrom(v) + return nil + case chargeusagebasedoverride.FieldBillingPeriodTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingPeriodTo(v) + return nil + case chargeusagebasedoverride.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 chargeusagebasedoverride.FieldFeatureKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFeatureKey(v) + return nil + case chargeusagebasedoverride.FieldPrice: + v, ok := value.(*productcatalog.Price) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPrice(v) + return nil + case chargeusagebasedoverride.FieldDiscounts: + v, ok := value.(*billing.Discounts) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDiscounts(v) + return nil + case chargeusagebasedoverride.FieldUnitConfig: + v, ok := value.(*productcatalog.UnitConfig) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUnitConfig(v) + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedOverride field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ChargeUsageBasedOverrideMutation) 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 *ChargeUsageBasedOverrideMutation) 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 *ChargeUsageBasedOverrideMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown ChargeUsageBasedOverride numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ChargeUsageBasedOverrideMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(chargeusagebasedoverride.FieldDescription) { + fields = append(fields, chargeusagebasedoverride.FieldDescription) + } + if m.FieldCleared(chargeusagebasedoverride.FieldMetadata) { + fields = append(fields, chargeusagebasedoverride.FieldMetadata) + } + if m.FieldCleared(chargeusagebasedoverride.FieldTaxBehavior) { + fields = append(fields, chargeusagebasedoverride.FieldTaxBehavior) + } + if m.FieldCleared(chargeusagebasedoverride.FieldTaxCodeID) { + fields = append(fields, chargeusagebasedoverride.FieldTaxCodeID) + } + if m.FieldCleared(chargeusagebasedoverride.FieldIntentDeletedAt) { + fields = append(fields, chargeusagebasedoverride.FieldIntentDeletedAt) + } + if m.FieldCleared(chargeusagebasedoverride.FieldFeatureKey) { + fields = append(fields, chargeusagebasedoverride.FieldFeatureKey) + } + if m.FieldCleared(chargeusagebasedoverride.FieldUnitConfig) { + fields = append(fields, chargeusagebasedoverride.FieldUnitConfig) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ChargeUsageBasedOverrideMutation) 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 *ChargeUsageBasedOverrideMutation) ClearField(name string) error { + switch name { + case chargeusagebasedoverride.FieldDescription: + m.ClearDescription() + return nil + case chargeusagebasedoverride.FieldMetadata: + m.ClearMetadata() + return nil + case chargeusagebasedoverride.FieldTaxBehavior: + m.ClearTaxBehavior() + return nil + case chargeusagebasedoverride.FieldTaxCodeID: + m.ClearTaxCodeID() + return nil + case chargeusagebasedoverride.FieldIntentDeletedAt: + m.ClearIntentDeletedAt() + return nil + case chargeusagebasedoverride.FieldFeatureKey: + m.ClearFeatureKey() + return nil + case chargeusagebasedoverride.FieldUnitConfig: + m.ClearUnitConfig() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) ResetField(name string) error { + switch name { + case chargeusagebasedoverride.FieldNamespace: + m.ResetNamespace() + return nil + case chargeusagebasedoverride.FieldChargeID: + m.ResetChargeID() + return nil + case chargeusagebasedoverride.FieldName: + m.ResetName() + return nil + case chargeusagebasedoverride.FieldDescription: + m.ResetDescription() + return nil + case chargeusagebasedoverride.FieldMetadata: + m.ResetMetadata() + return nil + case chargeusagebasedoverride.FieldTaxBehavior: + m.ResetTaxBehavior() + return nil + case chargeusagebasedoverride.FieldTaxCodeID: + m.ResetTaxCodeID() + return nil + case chargeusagebasedoverride.FieldIntentDeletedAt: + m.ResetIntentDeletedAt() + return nil + case chargeusagebasedoverride.FieldServicePeriodFrom: + m.ResetServicePeriodFrom() + return nil + case chargeusagebasedoverride.FieldServicePeriodTo: + m.ResetServicePeriodTo() + return nil + case chargeusagebasedoverride.FieldFullServicePeriodFrom: + m.ResetFullServicePeriodFrom() + return nil + case chargeusagebasedoverride.FieldFullServicePeriodTo: + m.ResetFullServicePeriodTo() + return nil + case chargeusagebasedoverride.FieldBillingPeriodFrom: + m.ResetBillingPeriodFrom() + return nil + case chargeusagebasedoverride.FieldBillingPeriodTo: + m.ResetBillingPeriodTo() + return nil + case chargeusagebasedoverride.FieldInvoiceAt: + m.ResetInvoiceAt() + return nil + case chargeusagebasedoverride.FieldFeatureKey: + m.ResetFeatureKey() + return nil + case chargeusagebasedoverride.FieldPrice: + m.ResetPrice() + return nil + case chargeusagebasedoverride.FieldDiscounts: + m.ResetDiscounts() + return nil + case chargeusagebasedoverride.FieldUnitConfig: + m.ResetUnitConfig() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedOverride field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ChargeUsageBasedOverrideMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.usage_based != nil { + edges = append(edges, chargeusagebasedoverride.EdgeUsageBased) + } + if m.tax_code != nil { + edges = append(edges, chargeusagebasedoverride.EdgeTaxCode) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ChargeUsageBasedOverrideMutation) AddedIDs(name string) []ent.Value { + switch name { + case chargeusagebasedoverride.EdgeUsageBased: + if id := m.usage_based; id != nil { + return []ent.Value{*id} + } + case chargeusagebasedoverride.EdgeTaxCode: + if id := m.tax_code; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ChargeUsageBasedOverrideMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ChargeUsageBasedOverrideMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ChargeUsageBasedOverrideMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedusage_based { + edges = append(edges, chargeusagebasedoverride.EdgeUsageBased) + } + if m.clearedtax_code { + edges = append(edges, chargeusagebasedoverride.EdgeTaxCode) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ChargeUsageBasedOverrideMutation) EdgeCleared(name string) bool { + switch name { + case chargeusagebasedoverride.EdgeUsageBased: + return m.clearedusage_based + case chargeusagebasedoverride.EdgeTaxCode: + return m.clearedtax_code + } + 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 *ChargeUsageBasedOverrideMutation) ClearEdge(name string) error { + switch name { + case chargeusagebasedoverride.EdgeUsageBased: + m.ClearUsageBased() + return nil + case chargeusagebasedoverride.EdgeTaxCode: + m.ClearTaxCode() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedOverride 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 *ChargeUsageBasedOverrideMutation) ResetEdge(name string) error { + switch name { + case chargeusagebasedoverride.EdgeUsageBased: + m.ResetUsageBased() + return nil + case chargeusagebasedoverride.EdgeTaxCode: + m.ResetTaxCode() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedOverride 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 + sort_hint *int + addsort_hint *int + _type *creditrealization.Type + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + annotations *models.Annotations + clearedFields map[string]struct{} + corrections map[string]struct{} + removedcorrections map[string]struct{} + clearedcorrections bool + allocation *string + clearedallocation bool + 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 +} + +// SetSortHint sets the "sort_hint" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) SetSortHint(i int) { + m.sort_hint = &i + m.addsort_hint = nil +} + +// SortHint returns the value of the "sort_hint" field in the mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) SortHint() (r int, exists bool) { + v := m.sort_hint + if v == nil { + return + } + return *v, true +} + +// OldSortHint returns the old "sort_hint" 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) OldSortHint(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSortHint is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSortHint requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSortHint: %w", err) + } + return oldValue.SortHint, nil +} + +// AddSortHint adds i to the "sort_hint" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) AddSortHint(i int) { + if m.addsort_hint != nil { + *m.addsort_hint += i + } else { + m.addsort_hint = &i + } +} + +// AddedSortHint returns the value that was added to the "sort_hint" field in this mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) AddedSortHint() (r int, exists bool) { + v := m.addsort_hint + if v == nil { + return + } + return *v, true +} + +// ResetSortHint resets all changes to the "sort_hint" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ResetSortHint() { + m.sort_hint = nil + m.addsort_hint = nil +} + +// SetType sets the "type" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) SetType(c creditrealization.Type) { + m._type = &c +} + +// GetType returns the value of the "type" field in the mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) GetType() (r creditrealization.Type, exists bool) { + v := m._type + if v == nil { + return + } + return *v, true +} + +// OldType returns the old "type" 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) OldType(ctx context.Context) (v creditrealization.Type, 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 *ChargeUsageBasedRunCreditAllocationsMutation) ResetType() { + m._type = nil +} + +// SetCorrectsRealizationID sets the "corrects_realization_id" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) SetCorrectsRealizationID(s string) { + m.allocation = &s +} + +// CorrectsRealizationID returns the value of the "corrects_realization_id" field in the mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) CorrectsRealizationID() (r string, exists bool) { + v := m.allocation + if v == nil { + return + } + return *v, true +} + +// OldCorrectsRealizationID returns the old "corrects_realization_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) OldCorrectsRealizationID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCorrectsRealizationID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCorrectsRealizationID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCorrectsRealizationID: %w", err) + } + return oldValue.CorrectsRealizationID, nil +} + +// ClearCorrectsRealizationID clears the value of the "corrects_realization_id" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ClearCorrectsRealizationID() { + m.allocation = nil + m.clearedFields[chargeusagebasedruncreditallocations.FieldCorrectsRealizationID] = struct{}{} +} + +// CorrectsRealizationIDCleared returns if the "corrects_realization_id" field was cleared in this mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) CorrectsRealizationIDCleared() bool { + _, ok := m.clearedFields[chargeusagebasedruncreditallocations.FieldCorrectsRealizationID] + return ok +} + +// ResetCorrectsRealizationID resets all changes to the "corrects_realization_id" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ResetCorrectsRealizationID() { + m.allocation = nil + delete(m.clearedFields, chargeusagebasedruncreditallocations.FieldCorrectsRealizationID) +} + +// 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 +} + +// AddCorrectionIDs adds the "corrections" edge to the ChargeUsageBasedRunCreditAllocations entity by ids. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) AddCorrectionIDs(ids ...string) { + if m.corrections == nil { + m.corrections = make(map[string]struct{}) + } + for i := range ids { + m.corrections[ids[i]] = struct{}{} + } +} + +// ClearCorrections clears the "corrections" edge to the ChargeUsageBasedRunCreditAllocations entity. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ClearCorrections() { + m.clearedcorrections = true +} + +// CorrectionsCleared reports if the "corrections" edge to the ChargeUsageBasedRunCreditAllocations entity was cleared. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) CorrectionsCleared() bool { + return m.clearedcorrections +} + +// RemoveCorrectionIDs removes the "corrections" edge to the ChargeUsageBasedRunCreditAllocations entity by IDs. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) RemoveCorrectionIDs(ids ...string) { + if m.removedcorrections == nil { + m.removedcorrections = make(map[string]struct{}) + } + for i := range ids { + delete(m.corrections, ids[i]) + m.removedcorrections[ids[i]] = struct{}{} + } +} + +// RemovedCorrections returns the removed IDs of the "corrections" edge to the ChargeUsageBasedRunCreditAllocations entity. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) RemovedCorrectionsIDs() (ids []string) { + for id := range m.removedcorrections { + ids = append(ids, id) + } + return +} + +// CorrectionsIDs returns the "corrections" edge IDs in the mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) CorrectionsIDs() (ids []string) { + for id := range m.corrections { + ids = append(ids, id) + } + return +} + +// ResetCorrections resets all changes to the "corrections" edge. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ResetCorrections() { + m.corrections = nil + m.clearedcorrections = false + m.removedcorrections = nil +} + +// SetAllocationID sets the "allocation" edge to the ChargeUsageBasedRunCreditAllocations entity by id. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) SetAllocationID(id string) { + m.allocation = &id +} + +// ClearAllocation clears the "allocation" edge to the ChargeUsageBasedRunCreditAllocations entity. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ClearAllocation() { + m.clearedallocation = true + m.clearedFields[chargeusagebasedruncreditallocations.FieldCorrectsRealizationID] = struct{}{} +} + +// AllocationCleared reports if the "allocation" edge to the ChargeUsageBasedRunCreditAllocations entity was cleared. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) AllocationCleared() bool { + return m.CorrectsRealizationIDCleared() || m.clearedallocation +} + +// AllocationID returns the "allocation" edge ID in the mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) AllocationID() (id string, exists bool) { + if m.allocation != nil { + return *m.allocation, true + } + return +} + +// AllocationIDs returns the "allocation" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// AllocationID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) AllocationIDs() (ids []string) { + if id := m.allocation; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetAllocation resets all changes to the "allocation" edge. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ResetAllocation() { + m.allocation = nil + m.clearedallocation = false +} + +// 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, 14) + 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.sort_hint != nil { + fields = append(fields, chargeusagebasedruncreditallocations.FieldSortHint) + } + if m._type != nil { + fields = append(fields, chargeusagebasedruncreditallocations.FieldType) + } + if m.allocation != nil { + fields = append(fields, chargeusagebasedruncreditallocations.FieldCorrectsRealizationID) + } + 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.FieldSortHint: + return m.SortHint() + case chargeusagebasedruncreditallocations.FieldType: + return m.GetType() + case chargeusagebasedruncreditallocations.FieldCorrectsRealizationID: + return m.CorrectsRealizationID() + 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.FieldSortHint: + return m.OldSortHint(ctx) + case chargeusagebasedruncreditallocations.FieldType: + return m.OldType(ctx) + case chargeusagebasedruncreditallocations.FieldCorrectsRealizationID: + return m.OldCorrectsRealizationID(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.FieldSortHint: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSortHint(v) + return nil + case chargeusagebasedruncreditallocations.FieldType: + v, ok := value.(creditrealization.Type) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case chargeusagebasedruncreditallocations.FieldCorrectsRealizationID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCorrectsRealizationID(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 { + var fields []string + if m.addsort_hint != nil { + fields = append(fields, chargeusagebasedruncreditallocations.FieldSortHint) + } + return fields +} + +// 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) { + switch name { + case chargeusagebasedruncreditallocations.FieldSortHint: + return m.AddedSortHint() + } + 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 { + case chargeusagebasedruncreditallocations.FieldSortHint: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddSortHint(v) + return nil + } + 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.FieldCorrectsRealizationID) { + fields = append(fields, chargeusagebasedruncreditallocations.FieldCorrectsRealizationID) + } + 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.FieldCorrectsRealizationID: + m.ClearCorrectsRealizationID() + 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.FieldSortHint: + m.ResetSortHint() + return nil + case chargeusagebasedruncreditallocations.FieldType: + m.ResetType() + return nil + case chargeusagebasedruncreditallocations.FieldCorrectsRealizationID: + m.ResetCorrectsRealizationID() + 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, 3) + if m.corrections != nil { + edges = append(edges, chargeusagebasedruncreditallocations.EdgeCorrections) + } + if m.allocation != nil { + edges = append(edges, chargeusagebasedruncreditallocations.EdgeAllocation) + } + 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.EdgeCorrections: + ids := make([]ent.Value, 0, len(m.corrections)) + for id := range m.corrections { + ids = append(ids, id) + } + return ids + case chargeusagebasedruncreditallocations.EdgeAllocation: + if id := m.allocation; id != nil { + return []ent.Value{*id} + } + 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, 3) + if m.removedcorrections != nil { + edges = append(edges, chargeusagebasedruncreditallocations.EdgeCorrections) + } + 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 { + switch name { + case chargeusagebasedruncreditallocations.EdgeCorrections: + ids := make([]ent.Value, 0, len(m.removedcorrections)) + for id := range m.removedcorrections { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) + if m.clearedcorrections { + edges = append(edges, chargeusagebasedruncreditallocations.EdgeCorrections) + } + if m.clearedallocation { + edges = append(edges, chargeusagebasedruncreditallocations.EdgeAllocation) + } + 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.EdgeCorrections: + return m.clearedcorrections + case chargeusagebasedruncreditallocations.EdgeAllocation: + return m.clearedallocation + 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.EdgeAllocation: + m.ClearAllocation() + return nil + 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.EdgeCorrections: + m.ResetCorrections() + return nil + case chargeusagebasedruncreditallocations.EdgeAllocation: + m.ResetAllocation() + return nil + case chargeusagebasedruncreditallocations.EdgeRun: + m.ResetRun() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunCreditAllocations edge %s", name) +} + +// ChargeUsageBasedRunDetailedLineMutation represents an operation that mutates the ChargeUsageBasedRunDetailedLine nodes in the graph. +type ChargeUsageBasedRunDetailedLineMutation struct { + config + op Op + typ string + id *string + currency *currencyx.Code + service_period_start *time.Time + service_period_end *time.Time + quantity *alpacadecimal.Decimal + invoicing_app_external_id *string + child_unique_reference_id *string + per_unit_amount *alpacadecimal.Decimal + category *stddetailedline.Category + payment_term *productcatalog.PaymentTermType + index *int + addindex *int + credits_applied **creditsapplied.CreditsApplied + annotations *models.Annotations + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + name *string + description *string + 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 + pricer_reference_id *string + clearedFields map[string]struct{} + charge *string + clearedcharge bool + run *string + clearedrun bool + corrects_run *string + clearedcorrects_run bool + done bool + oldValue func(context.Context) (*ChargeUsageBasedRunDetailedLine, error) + predicates []predicate.ChargeUsageBasedRunDetailedLine +} + +var _ ent.Mutation = (*ChargeUsageBasedRunDetailedLineMutation)(nil) + +// chargeusagebasedrundetailedlineOption allows management of the mutation configuration using functional options. +type chargeusagebasedrundetailedlineOption func(*ChargeUsageBasedRunDetailedLineMutation) + +// newChargeUsageBasedRunDetailedLineMutation creates new mutation for the ChargeUsageBasedRunDetailedLine entity. +func newChargeUsageBasedRunDetailedLineMutation(c config, op Op, opts ...chargeusagebasedrundetailedlineOption) *ChargeUsageBasedRunDetailedLineMutation { + m := &ChargeUsageBasedRunDetailedLineMutation{ + config: c, + op: op, + typ: TypeChargeUsageBasedRunDetailedLine, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withChargeUsageBasedRunDetailedLineID sets the ID field of the mutation. +func withChargeUsageBasedRunDetailedLineID(id string) chargeusagebasedrundetailedlineOption { + return func(m *ChargeUsageBasedRunDetailedLineMutation) { + var ( + err error + once sync.Once + value *ChargeUsageBasedRunDetailedLine + ) + m.oldValue = func(ctx context.Context) (*ChargeUsageBasedRunDetailedLine, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ChargeUsageBasedRunDetailedLine.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withChargeUsageBasedRunDetailedLine sets the old ChargeUsageBasedRunDetailedLine of the mutation. +func withChargeUsageBasedRunDetailedLine(node *ChargeUsageBasedRunDetailedLine) chargeusagebasedrundetailedlineOption { + return func(m *ChargeUsageBasedRunDetailedLineMutation) { + m.oldValue = func(context.Context) (*ChargeUsageBasedRunDetailedLine, 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 ChargeUsageBasedRunDetailedLineMutation) 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 ChargeUsageBasedRunDetailedLineMutation) 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 ChargeUsageBasedRunDetailedLine entities. +func (m *ChargeUsageBasedRunDetailedLineMutation) 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 *ChargeUsageBasedRunDetailedLineMutation) 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 *ChargeUsageBasedRunDetailedLineMutation) 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().ChargeUsageBasedRunDetailedLine.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetCurrency sets the "currency" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetCurrency(c currencyx.Code) { + m.currency = &c +} + +// Currency returns the value of the "currency" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) Currency() (r currencyx.Code, exists bool) { + v := m.currency + if v == nil { + return + } + return *v, true +} + +// OldCurrency returns the old "currency" field's value of the ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) OldCurrency(ctx context.Context) (v currencyx.Code, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrency is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrency requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrency: %w", err) + } + return oldValue.Currency, nil +} + +// ResetCurrency resets all changes to the "currency" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetCurrency() { + m.currency = nil +} + +// SetServicePeriodStart sets the "service_period_start" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetServicePeriodStart(t time.Time) { + m.service_period_start = &t +} + +// ServicePeriodStart returns the value of the "service_period_start" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) ServicePeriodStart() (r time.Time, exists bool) { + v := m.service_period_start + if v == nil { + return + } + return *v, true +} + +// OldServicePeriodStart returns the old "service_period_start" field's value of the ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) OldServicePeriodStart(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldServicePeriodStart is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldServicePeriodStart requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldServicePeriodStart: %w", err) + } + return oldValue.ServicePeriodStart, nil +} + +// ResetServicePeriodStart resets all changes to the "service_period_start" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetServicePeriodStart() { + m.service_period_start = nil +} + +// SetServicePeriodEnd sets the "service_period_end" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetServicePeriodEnd(t time.Time) { + m.service_period_end = &t +} + +// ServicePeriodEnd returns the value of the "service_period_end" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) ServicePeriodEnd() (r time.Time, exists bool) { + v := m.service_period_end + if v == nil { + return + } + return *v, true +} + +// OldServicePeriodEnd returns the old "service_period_end" field's value of the ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) OldServicePeriodEnd(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldServicePeriodEnd is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldServicePeriodEnd requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldServicePeriodEnd: %w", err) + } + return oldValue.ServicePeriodEnd, nil +} + +// ResetServicePeriodEnd resets all changes to the "service_period_end" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetServicePeriodEnd() { + m.service_period_end = nil +} + +// SetQuantity sets the "quantity" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetQuantity(a alpacadecimal.Decimal) { + m.quantity = &a +} + +// Quantity returns the value of the "quantity" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) Quantity() (r alpacadecimal.Decimal, exists bool) { + v := m.quantity + if v == nil { + return + } + return *v, true +} + +// OldQuantity returns the old "quantity" field's value of the ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) OldQuantity(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldQuantity is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldQuantity requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldQuantity: %w", err) + } + return oldValue.Quantity, nil +} + +// ResetQuantity resets all changes to the "quantity" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetQuantity() { + m.quantity = nil +} + +// SetInvoicingAppExternalID sets the "invoicing_app_external_id" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetInvoicingAppExternalID(s string) { + m.invoicing_app_external_id = &s +} + +// InvoicingAppExternalID returns the value of the "invoicing_app_external_id" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) InvoicingAppExternalID() (r string, exists bool) { + v := m.invoicing_app_external_id + if v == nil { + return + } + return *v, true +} + +// OldInvoicingAppExternalID returns the old "invoicing_app_external_id" field's value of the ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) OldInvoicingAppExternalID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoicingAppExternalID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoicingAppExternalID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoicingAppExternalID: %w", err) + } + return oldValue.InvoicingAppExternalID, nil +} + +// ClearInvoicingAppExternalID clears the value of the "invoicing_app_external_id" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ClearInvoicingAppExternalID() { + m.invoicing_app_external_id = nil + m.clearedFields[chargeusagebasedrundetailedline.FieldInvoicingAppExternalID] = struct{}{} +} + +// InvoicingAppExternalIDCleared returns if the "invoicing_app_external_id" field was cleared in this mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) InvoicingAppExternalIDCleared() bool { + _, ok := m.clearedFields[chargeusagebasedrundetailedline.FieldInvoicingAppExternalID] + return ok +} + +// ResetInvoicingAppExternalID resets all changes to the "invoicing_app_external_id" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetInvoicingAppExternalID() { + m.invoicing_app_external_id = nil + delete(m.clearedFields, chargeusagebasedrundetailedline.FieldInvoicingAppExternalID) +} + +// SetChildUniqueReferenceID sets the "child_unique_reference_id" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetChildUniqueReferenceID(s string) { + m.child_unique_reference_id = &s +} + +// ChildUniqueReferenceID returns the value of the "child_unique_reference_id" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) ChildUniqueReferenceID() (r string, exists bool) { + v := m.child_unique_reference_id + if v == nil { + return + } + return *v, true +} + +// OldChildUniqueReferenceID returns the old "child_unique_reference_id" field's value of the ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) OldChildUniqueReferenceID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldChildUniqueReferenceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldChildUniqueReferenceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldChildUniqueReferenceID: %w", err) + } + return oldValue.ChildUniqueReferenceID, nil +} + +// ResetChildUniqueReferenceID resets all changes to the "child_unique_reference_id" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetChildUniqueReferenceID() { + m.child_unique_reference_id = nil +} + +// SetPerUnitAmount sets the "per_unit_amount" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetPerUnitAmount(a alpacadecimal.Decimal) { + m.per_unit_amount = &a +} + +// PerUnitAmount returns the value of the "per_unit_amount" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) PerUnitAmount() (r alpacadecimal.Decimal, exists bool) { + v := m.per_unit_amount + if v == nil { + return + } + return *v, true +} + +// OldPerUnitAmount returns the old "per_unit_amount" field's value of the ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) OldPerUnitAmount(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPerUnitAmount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPerUnitAmount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPerUnitAmount: %w", err) + } + return oldValue.PerUnitAmount, nil +} + +// ResetPerUnitAmount resets all changes to the "per_unit_amount" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetPerUnitAmount() { + m.per_unit_amount = nil +} + +// SetCategory sets the "category" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetCategory(s stddetailedline.Category) { + m.category = &s +} + +// Category returns the value of the "category" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) Category() (r stddetailedline.Category, exists bool) { + v := m.category + if v == nil { + return + } + return *v, true +} + +// OldCategory returns the old "category" field's value of the ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) OldCategory(ctx context.Context) (v stddetailedline.Category, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCategory is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCategory requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCategory: %w", err) + } + return oldValue.Category, nil +} + +// ResetCategory resets all changes to the "category" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetCategory() { + m.category = nil +} + +// SetPaymentTerm sets the "payment_term" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetPaymentTerm(ptt productcatalog.PaymentTermType) { + m.payment_term = &ptt +} + +// PaymentTerm returns the value of the "payment_term" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) PaymentTerm() (r productcatalog.PaymentTermType, exists bool) { + v := m.payment_term + if v == nil { + return + } + return *v, true +} + +// OldPaymentTerm returns the old "payment_term" field's value of the ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) OldPaymentTerm(ctx context.Context) (v productcatalog.PaymentTermType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPaymentTerm is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPaymentTerm requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPaymentTerm: %w", err) + } + return oldValue.PaymentTerm, nil +} + +// ResetPaymentTerm resets all changes to the "payment_term" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetPaymentTerm() { + m.payment_term = nil +} + +// SetIndex sets the "index" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetIndex(i int) { + m.index = &i + m.addindex = nil +} + +// Index returns the value of the "index" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) Index() (r int, exists bool) { + v := m.index + if v == nil { + return + } + return *v, true +} + +// OldIndex returns the old "index" field's value of the ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) OldIndex(ctx context.Context) (v *int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIndex is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIndex requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIndex: %w", err) + } + return oldValue.Index, nil +} + +// AddIndex adds i to the "index" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) AddIndex(i int) { + if m.addindex != nil { + *m.addindex += i + } else { + m.addindex = &i + } +} + +// AddedIndex returns the value that was added to the "index" field in this mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) AddedIndex() (r int, exists bool) { + v := m.addindex + if v == nil { + return + } + return *v, true +} + +// ClearIndex clears the value of the "index" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ClearIndex() { + m.index = nil + m.addindex = nil + m.clearedFields[chargeusagebasedrundetailedline.FieldIndex] = struct{}{} +} + +// IndexCleared returns if the "index" field was cleared in this mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) IndexCleared() bool { + _, ok := m.clearedFields[chargeusagebasedrundetailedline.FieldIndex] + return ok +} + +// ResetIndex resets all changes to the "index" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetIndex() { + m.index = nil + m.addindex = nil + delete(m.clearedFields, chargeusagebasedrundetailedline.FieldIndex) +} + +// SetCreditsApplied sets the "credits_applied" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetCreditsApplied(ca *creditsapplied.CreditsApplied) { + m.credits_applied = &ca +} + +// CreditsApplied returns the value of the "credits_applied" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) CreditsApplied() (r *creditsapplied.CreditsApplied, exists bool) { + v := m.credits_applied + if v == nil { + return + } + return *v, true +} + +// OldCreditsApplied returns the old "credits_applied" field's value of the ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) OldCreditsApplied(ctx context.Context) (v *creditsapplied.CreditsApplied, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreditsApplied is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreditsApplied requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreditsApplied: %w", err) + } + return oldValue.CreditsApplied, nil +} + +// ClearCreditsApplied clears the value of the "credits_applied" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ClearCreditsApplied() { + m.credits_applied = nil + m.clearedFields[chargeusagebasedrundetailedline.FieldCreditsApplied] = struct{}{} +} + +// CreditsAppliedCleared returns if the "credits_applied" field was cleared in this mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) CreditsAppliedCleared() bool { + _, ok := m.clearedFields[chargeusagebasedrundetailedline.FieldCreditsApplied] + return ok +} + +// ResetCreditsApplied resets all changes to the "credits_applied" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetCreditsApplied() { + m.credits_applied = nil + delete(m.clearedFields, chargeusagebasedrundetailedline.FieldCreditsApplied) +} + +// SetAnnotations sets the "annotations" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) 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 ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) 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 *ChargeUsageBasedRunDetailedLineMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[chargeusagebasedrundetailedline.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[chargeusagebasedrundetailedline.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, chargeusagebasedrundetailedline.FieldAnnotations) +} + +// SetNamespace sets the "namespace" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) 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 ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) 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 *ChargeUsageBasedRunDetailedLineMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[chargeusagebasedrundetailedline.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) MetadataCleared() bool { + _, ok := m.clearedFields[chargeusagebasedrundetailedline.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, chargeusagebasedrundetailedline.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) 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 ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) 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 *ChargeUsageBasedRunDetailedLineMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) 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 ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) 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 *ChargeUsageBasedRunDetailedLineMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) 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 ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) 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 *ChargeUsageBasedRunDetailedLineMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[chargeusagebasedrundetailedline.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[chargeusagebasedrundetailedline.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, chargeusagebasedrundetailedline.FieldDeletedAt) +} + +// SetName sets the "name" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ClearDescription() { + m.description = nil + m.clearedFields[chargeusagebasedrundetailedline.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[chargeusagebasedrundetailedline.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, chargeusagebasedrundetailedline.FieldDescription) +} + +// SetAmount sets the "amount" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) 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 ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) 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 *ChargeUsageBasedRunDetailedLineMutation) ResetAmount() { + m.amount = nil +} + +// SetTaxesTotal sets the "taxes_total" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetTaxesTotal(a alpacadecimal.Decimal) { + m.taxes_total = &a +} + +// TaxesTotal returns the value of the "taxes_total" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) 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 ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) 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 *ChargeUsageBasedRunDetailedLineMutation) ResetTaxesTotal() { + m.taxes_total = nil +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetTaxesInclusiveTotal(a alpacadecimal.Decimal) { + m.taxes_inclusive_total = &a +} + +// TaxesInclusiveTotal returns the value of the "taxes_inclusive_total" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) 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 ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) 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 *ChargeUsageBasedRunDetailedLineMutation) ResetTaxesInclusiveTotal() { + m.taxes_inclusive_total = nil +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetTaxesExclusiveTotal(a alpacadecimal.Decimal) { + m.taxes_exclusive_total = &a +} + +// TaxesExclusiveTotal returns the value of the "taxes_exclusive_total" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) 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 ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) 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 *ChargeUsageBasedRunDetailedLineMutation) ResetTaxesExclusiveTotal() { + m.taxes_exclusive_total = nil +} + +// SetChargesTotal sets the "charges_total" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetChargesTotal(a alpacadecimal.Decimal) { + m.charges_total = &a +} + +// ChargesTotal returns the value of the "charges_total" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) 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 ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) 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 *ChargeUsageBasedRunDetailedLineMutation) ResetChargesTotal() { + m.charges_total = nil +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetDiscountsTotal(a alpacadecimal.Decimal) { + m.discounts_total = &a +} + +// DiscountsTotal returns the value of the "discounts_total" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) 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 ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) 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 *ChargeUsageBasedRunDetailedLineMutation) ResetDiscountsTotal() { + m.discounts_total = nil +} + +// SetCreditsTotal sets the "credits_total" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetCreditsTotal(a alpacadecimal.Decimal) { + m.credits_total = &a +} + +// CreditsTotal returns the value of the "credits_total" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) 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 ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) 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 *ChargeUsageBasedRunDetailedLineMutation) ResetCreditsTotal() { + m.credits_total = nil +} + +// SetTotal sets the "total" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetTotal(a alpacadecimal.Decimal) { + m.total = &a +} + +// Total returns the value of the "total" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) 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 ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) 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 *ChargeUsageBasedRunDetailedLineMutation) ResetTotal() { + m.total = nil +} + +// SetChargeID sets the "charge_id" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetChargeID(s string) { + m.charge = &s +} + +// ChargeID returns the value of the "charge_id" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) ChargeID() (r string, exists bool) { + v := m.charge + if v == nil { + return + } + return *v, true +} + +// OldChargeID returns the old "charge_id" field's value of the ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) 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 *ChargeUsageBasedRunDetailedLineMutation) ResetChargeID() { + m.charge = nil +} + +// SetRunID sets the "run_id" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetRunID(s string) { + m.run = &s +} + +// RunID returns the value of the "run_id" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) 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 ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) 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 *ChargeUsageBasedRunDetailedLineMutation) ResetRunID() { + m.run = nil +} + +// SetPricerReferenceID sets the "pricer_reference_id" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetPricerReferenceID(s string) { + m.pricer_reference_id = &s +} + +// PricerReferenceID returns the value of the "pricer_reference_id" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) PricerReferenceID() (r string, exists bool) { + v := m.pricer_reference_id + if v == nil { + return + } + return *v, true +} + +// OldPricerReferenceID returns the old "pricer_reference_id" field's value of the ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) OldPricerReferenceID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPricerReferenceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPricerReferenceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPricerReferenceID: %w", err) + } + return oldValue.PricerReferenceID, nil +} + +// ResetPricerReferenceID resets all changes to the "pricer_reference_id" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetPricerReferenceID() { + m.pricer_reference_id = nil +} + +// SetCorrectsRunID sets the "corrects_run_id" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetCorrectsRunID(s string) { + m.corrects_run = &s +} + +// CorrectsRunID returns the value of the "corrects_run_id" field in the mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) CorrectsRunID() (r string, exists bool) { + v := m.corrects_run + if v == nil { + return + } + return *v, true +} + +// OldCorrectsRunID returns the old "corrects_run_id" field's value of the ChargeUsageBasedRunDetailedLine entity. +// If the ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) OldCorrectsRunID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCorrectsRunID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCorrectsRunID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCorrectsRunID: %w", err) + } + return oldValue.CorrectsRunID, nil +} + +// ClearCorrectsRunID clears the value of the "corrects_run_id" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ClearCorrectsRunID() { + m.corrects_run = nil + m.clearedFields[chargeusagebasedrundetailedline.FieldCorrectsRunID] = struct{}{} +} + +// CorrectsRunIDCleared returns if the "corrects_run_id" field was cleared in this mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) CorrectsRunIDCleared() bool { + _, ok := m.clearedFields[chargeusagebasedrundetailedline.FieldCorrectsRunID] + return ok +} + +// ResetCorrectsRunID resets all changes to the "corrects_run_id" field. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetCorrectsRunID() { + m.corrects_run = nil + delete(m.clearedFields, chargeusagebasedrundetailedline.FieldCorrectsRunID) +} + +// ClearCharge clears the "charge" edge to the ChargeUsageBased entity. +func (m *ChargeUsageBasedRunDetailedLineMutation) ClearCharge() { + m.clearedcharge = true + m.clearedFields[chargeusagebasedrundetailedline.FieldChargeID] = struct{}{} +} + +// ChargeCleared reports if the "charge" edge to the ChargeUsageBased entity was cleared. +func (m *ChargeUsageBasedRunDetailedLineMutation) ChargeCleared() bool { + return m.clearedcharge +} + +// 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 *ChargeUsageBasedRunDetailedLineMutation) ChargeIDs() (ids []string) { + if id := m.charge; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCharge resets all changes to the "charge" edge. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetCharge() { + m.charge = nil + m.clearedcharge = false +} + +// ClearRun clears the "run" edge to the ChargeUsageBasedRuns entity. +func (m *ChargeUsageBasedRunDetailedLineMutation) ClearRun() { + m.clearedrun = true + m.clearedFields[chargeusagebasedrundetailedline.FieldRunID] = struct{}{} +} + +// RunCleared reports if the "run" edge to the ChargeUsageBasedRuns entity was cleared. +func (m *ChargeUsageBasedRunDetailedLineMutation) 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 *ChargeUsageBasedRunDetailedLineMutation) RunIDs() (ids []string) { + if id := m.run; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetRun resets all changes to the "run" edge. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetRun() { + m.run = nil + m.clearedrun = false +} + +// ClearCorrectsRun clears the "corrects_run" edge to the ChargeUsageBasedRuns entity. +func (m *ChargeUsageBasedRunDetailedLineMutation) ClearCorrectsRun() { + m.clearedcorrects_run = true + m.clearedFields[chargeusagebasedrundetailedline.FieldCorrectsRunID] = struct{}{} +} + +// CorrectsRunCleared reports if the "corrects_run" edge to the ChargeUsageBasedRuns entity was cleared. +func (m *ChargeUsageBasedRunDetailedLineMutation) CorrectsRunCleared() bool { + return m.CorrectsRunIDCleared() || m.clearedcorrects_run +} + +// CorrectsRunIDs returns the "corrects_run" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CorrectsRunID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedRunDetailedLineMutation) CorrectsRunIDs() (ids []string) { + if id := m.corrects_run; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCorrectsRun resets all changes to the "corrects_run" edge. +func (m *ChargeUsageBasedRunDetailedLineMutation) ResetCorrectsRun() { + m.corrects_run = nil + m.clearedcorrects_run = false +} + +// Where appends a list predicates to the ChargeUsageBasedRunDetailedLineMutation builder. +func (m *ChargeUsageBasedRunDetailedLineMutation) Where(ps ...predicate.ChargeUsageBasedRunDetailedLine) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ChargeUsageBasedRunDetailedLineMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ChargeUsageBasedRunDetailedLineMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ChargeUsageBasedRunDetailedLine, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ChargeUsageBasedRunDetailedLineMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ChargeUsageBasedRunDetailedLineMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ChargeUsageBasedRunDetailedLine). +func (m *ChargeUsageBasedRunDetailedLineMutation) 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 *ChargeUsageBasedRunDetailedLineMutation) Fields() []string { + fields := make([]string, 0, 31) + if m.currency != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldCurrency) + } + if m.service_period_start != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldServicePeriodStart) + } + if m.service_period_end != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldServicePeriodEnd) + } + if m.quantity != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldQuantity) + } + if m.invoicing_app_external_id != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldInvoicingAppExternalID) + } + if m.child_unique_reference_id != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldChildUniqueReferenceID) + } + if m.per_unit_amount != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldPerUnitAmount) + } + if m.category != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldCategory) + } + if m.payment_term != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldPaymentTerm) + } + if m.index != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldIndex) + } + if m.credits_applied != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldCreditsApplied) + } + if m.annotations != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldAnnotations) + } + if m.namespace != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldDeletedAt) + } + if m.name != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldName) + } + if m.description != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldDescription) + } + if m.amount != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldAmount) + } + if m.taxes_total != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldTaxesTotal) + } + if m.taxes_inclusive_total != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldTaxesInclusiveTotal) + } + if m.taxes_exclusive_total != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldTaxesExclusiveTotal) + } + if m.charges_total != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldChargesTotal) + } + if m.discounts_total != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldDiscountsTotal) + } + if m.credits_total != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldCreditsTotal) + } + if m.total != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldTotal) + } + if m.charge != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldChargeID) + } + if m.run != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldRunID) + } + if m.pricer_reference_id != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldPricerReferenceID) + } + if m.corrects_run != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldCorrectsRunID) + } + 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 *ChargeUsageBasedRunDetailedLineMutation) Field(name string) (ent.Value, bool) { + switch name { + case chargeusagebasedrundetailedline.FieldCurrency: + return m.Currency() + case chargeusagebasedrundetailedline.FieldServicePeriodStart: + return m.ServicePeriodStart() + case chargeusagebasedrundetailedline.FieldServicePeriodEnd: + return m.ServicePeriodEnd() + case chargeusagebasedrundetailedline.FieldQuantity: + return m.Quantity() + case chargeusagebasedrundetailedline.FieldInvoicingAppExternalID: + return m.InvoicingAppExternalID() + case chargeusagebasedrundetailedline.FieldChildUniqueReferenceID: + return m.ChildUniqueReferenceID() + case chargeusagebasedrundetailedline.FieldPerUnitAmount: + return m.PerUnitAmount() + case chargeusagebasedrundetailedline.FieldCategory: + return m.Category() + case chargeusagebasedrundetailedline.FieldPaymentTerm: + return m.PaymentTerm() + case chargeusagebasedrundetailedline.FieldIndex: + return m.Index() + case chargeusagebasedrundetailedline.FieldCreditsApplied: + return m.CreditsApplied() + case chargeusagebasedrundetailedline.FieldAnnotations: + return m.Annotations() + case chargeusagebasedrundetailedline.FieldNamespace: + return m.Namespace() + case chargeusagebasedrundetailedline.FieldMetadata: + return m.Metadata() + case chargeusagebasedrundetailedline.FieldCreatedAt: + return m.CreatedAt() + case chargeusagebasedrundetailedline.FieldUpdatedAt: + return m.UpdatedAt() + case chargeusagebasedrundetailedline.FieldDeletedAt: + return m.DeletedAt() + case chargeusagebasedrundetailedline.FieldName: + return m.Name() + case chargeusagebasedrundetailedline.FieldDescription: + return m.Description() + case chargeusagebasedrundetailedline.FieldAmount: + return m.Amount() + case chargeusagebasedrundetailedline.FieldTaxesTotal: + return m.TaxesTotal() + case chargeusagebasedrundetailedline.FieldTaxesInclusiveTotal: + return m.TaxesInclusiveTotal() + case chargeusagebasedrundetailedline.FieldTaxesExclusiveTotal: + return m.TaxesExclusiveTotal() + case chargeusagebasedrundetailedline.FieldChargesTotal: + return m.ChargesTotal() + case chargeusagebasedrundetailedline.FieldDiscountsTotal: + return m.DiscountsTotal() + case chargeusagebasedrundetailedline.FieldCreditsTotal: + return m.CreditsTotal() + case chargeusagebasedrundetailedline.FieldTotal: + return m.Total() + case chargeusagebasedrundetailedline.FieldChargeID: + return m.ChargeID() + case chargeusagebasedrundetailedline.FieldRunID: + return m.RunID() + case chargeusagebasedrundetailedline.FieldPricerReferenceID: + return m.PricerReferenceID() + case chargeusagebasedrundetailedline.FieldCorrectsRunID: + return m.CorrectsRunID() + } + 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 *ChargeUsageBasedRunDetailedLineMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case chargeusagebasedrundetailedline.FieldCurrency: + return m.OldCurrency(ctx) + case chargeusagebasedrundetailedline.FieldServicePeriodStart: + return m.OldServicePeriodStart(ctx) + case chargeusagebasedrundetailedline.FieldServicePeriodEnd: + return m.OldServicePeriodEnd(ctx) + case chargeusagebasedrundetailedline.FieldQuantity: + return m.OldQuantity(ctx) + case chargeusagebasedrundetailedline.FieldInvoicingAppExternalID: + return m.OldInvoicingAppExternalID(ctx) + case chargeusagebasedrundetailedline.FieldChildUniqueReferenceID: + return m.OldChildUniqueReferenceID(ctx) + case chargeusagebasedrundetailedline.FieldPerUnitAmount: + return m.OldPerUnitAmount(ctx) + case chargeusagebasedrundetailedline.FieldCategory: + return m.OldCategory(ctx) + case chargeusagebasedrundetailedline.FieldPaymentTerm: + return m.OldPaymentTerm(ctx) + case chargeusagebasedrundetailedline.FieldIndex: + return m.OldIndex(ctx) + case chargeusagebasedrundetailedline.FieldCreditsApplied: + return m.OldCreditsApplied(ctx) + case chargeusagebasedrundetailedline.FieldAnnotations: + return m.OldAnnotations(ctx) + case chargeusagebasedrundetailedline.FieldNamespace: + return m.OldNamespace(ctx) + case chargeusagebasedrundetailedline.FieldMetadata: + return m.OldMetadata(ctx) + case chargeusagebasedrundetailedline.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case chargeusagebasedrundetailedline.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case chargeusagebasedrundetailedline.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case chargeusagebasedrundetailedline.FieldName: + return m.OldName(ctx) + case chargeusagebasedrundetailedline.FieldDescription: + return m.OldDescription(ctx) + case chargeusagebasedrundetailedline.FieldAmount: + return m.OldAmount(ctx) + case chargeusagebasedrundetailedline.FieldTaxesTotal: + return m.OldTaxesTotal(ctx) + case chargeusagebasedrundetailedline.FieldTaxesInclusiveTotal: + return m.OldTaxesInclusiveTotal(ctx) + case chargeusagebasedrundetailedline.FieldTaxesExclusiveTotal: + return m.OldTaxesExclusiveTotal(ctx) + case chargeusagebasedrundetailedline.FieldChargesTotal: + return m.OldChargesTotal(ctx) + case chargeusagebasedrundetailedline.FieldDiscountsTotal: + return m.OldDiscountsTotal(ctx) + case chargeusagebasedrundetailedline.FieldCreditsTotal: + return m.OldCreditsTotal(ctx) + case chargeusagebasedrundetailedline.FieldTotal: + return m.OldTotal(ctx) + case chargeusagebasedrundetailedline.FieldChargeID: + return m.OldChargeID(ctx) + case chargeusagebasedrundetailedline.FieldRunID: + return m.OldRunID(ctx) + case chargeusagebasedrundetailedline.FieldPricerReferenceID: + return m.OldPricerReferenceID(ctx) + case chargeusagebasedrundetailedline.FieldCorrectsRunID: + return m.OldCorrectsRunID(ctx) + } + return nil, fmt.Errorf("unknown ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) SetField(name string, value ent.Value) error { + switch name { + case chargeusagebasedrundetailedline.FieldCurrency: + v, ok := value.(currencyx.Code) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrency(v) + return nil + case chargeusagebasedrundetailedline.FieldServicePeriodStart: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetServicePeriodStart(v) + return nil + case chargeusagebasedrundetailedline.FieldServicePeriodEnd: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetServicePeriodEnd(v) + return nil + case chargeusagebasedrundetailedline.FieldQuantity: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetQuantity(v) + return nil + case chargeusagebasedrundetailedline.FieldInvoicingAppExternalID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoicingAppExternalID(v) + return nil + case chargeusagebasedrundetailedline.FieldChildUniqueReferenceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChildUniqueReferenceID(v) + return nil + case chargeusagebasedrundetailedline.FieldPerUnitAmount: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPerUnitAmount(v) + return nil + case chargeusagebasedrundetailedline.FieldCategory: + v, ok := value.(stddetailedline.Category) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCategory(v) + return nil + case chargeusagebasedrundetailedline.FieldPaymentTerm: + v, ok := value.(productcatalog.PaymentTermType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPaymentTerm(v) + return nil + case chargeusagebasedrundetailedline.FieldIndex: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIndex(v) + return nil + case chargeusagebasedrundetailedline.FieldCreditsApplied: + v, ok := value.(*creditsapplied.CreditsApplied) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreditsApplied(v) + return nil + case chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case chargeusagebasedrundetailedline.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case chargeusagebasedrundetailedline.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.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 chargeusagebasedrundetailedline.FieldChargeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChargeID(v) + return nil + case chargeusagebasedrundetailedline.FieldRunID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRunID(v) + return nil + case chargeusagebasedrundetailedline.FieldPricerReferenceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPricerReferenceID(v) + return nil + case chargeusagebasedrundetailedline.FieldCorrectsRunID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCorrectsRunID(v) + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunDetailedLine field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) AddedFields() []string { + var fields []string + if m.addindex != nil { + fields = append(fields, chargeusagebasedrundetailedline.FieldIndex) + } + return fields +} + +// 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 *ChargeUsageBasedRunDetailedLineMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case chargeusagebasedrundetailedline.FieldIndex: + return m.AddedIndex() + } + 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 *ChargeUsageBasedRunDetailedLineMutation) AddField(name string, value ent.Value) error { + switch name { + case chargeusagebasedrundetailedline.FieldIndex: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddIndex(v) + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunDetailedLine numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(chargeusagebasedrundetailedline.FieldInvoicingAppExternalID) { + fields = append(fields, chargeusagebasedrundetailedline.FieldInvoicingAppExternalID) + } + if m.FieldCleared(chargeusagebasedrundetailedline.FieldIndex) { + fields = append(fields, chargeusagebasedrundetailedline.FieldIndex) + } + if m.FieldCleared(chargeusagebasedrundetailedline.FieldCreditsApplied) { + fields = append(fields, chargeusagebasedrundetailedline.FieldCreditsApplied) + } + if m.FieldCleared(chargeusagebasedrundetailedline.FieldAnnotations) { + fields = append(fields, chargeusagebasedrundetailedline.FieldAnnotations) + } + if m.FieldCleared(chargeusagebasedrundetailedline.FieldMetadata) { + fields = append(fields, chargeusagebasedrundetailedline.FieldMetadata) + } + if m.FieldCleared(chargeusagebasedrundetailedline.FieldDeletedAt) { + fields = append(fields, chargeusagebasedrundetailedline.FieldDeletedAt) + } + if m.FieldCleared(chargeusagebasedrundetailedline.FieldDescription) { + fields = append(fields, chargeusagebasedrundetailedline.FieldDescription) + } + if m.FieldCleared(chargeusagebasedrundetailedline.FieldCorrectsRunID) { + fields = append(fields, chargeusagebasedrundetailedline.FieldCorrectsRunID) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) 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 *ChargeUsageBasedRunDetailedLineMutation) ClearField(name string) error { + switch name { + case chargeusagebasedrundetailedline.FieldInvoicingAppExternalID: + m.ClearInvoicingAppExternalID() + return nil + case chargeusagebasedrundetailedline.FieldIndex: + m.ClearIndex() + return nil + case chargeusagebasedrundetailedline.FieldCreditsApplied: + m.ClearCreditsApplied() + return nil + case chargeusagebasedrundetailedline.FieldAnnotations: + m.ClearAnnotations() + return nil + case chargeusagebasedrundetailedline.FieldMetadata: + m.ClearMetadata() + return nil + case chargeusagebasedrundetailedline.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case chargeusagebasedrundetailedline.FieldDescription: + m.ClearDescription() + return nil + case chargeusagebasedrundetailedline.FieldCorrectsRunID: + m.ClearCorrectsRunID() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) ResetField(name string) error { + switch name { + case chargeusagebasedrundetailedline.FieldCurrency: + m.ResetCurrency() + return nil + case chargeusagebasedrundetailedline.FieldServicePeriodStart: + m.ResetServicePeriodStart() + return nil + case chargeusagebasedrundetailedline.FieldServicePeriodEnd: + m.ResetServicePeriodEnd() + return nil + case chargeusagebasedrundetailedline.FieldQuantity: + m.ResetQuantity() + return nil + case chargeusagebasedrundetailedline.FieldInvoicingAppExternalID: + m.ResetInvoicingAppExternalID() + return nil + case chargeusagebasedrundetailedline.FieldChildUniqueReferenceID: + m.ResetChildUniqueReferenceID() + return nil + case chargeusagebasedrundetailedline.FieldPerUnitAmount: + m.ResetPerUnitAmount() + return nil + case chargeusagebasedrundetailedline.FieldCategory: + m.ResetCategory() + return nil + case chargeusagebasedrundetailedline.FieldPaymentTerm: + m.ResetPaymentTerm() + return nil + case chargeusagebasedrundetailedline.FieldIndex: + m.ResetIndex() + return nil + case chargeusagebasedrundetailedline.FieldCreditsApplied: + m.ResetCreditsApplied() + return nil + case chargeusagebasedrundetailedline.FieldAnnotations: + m.ResetAnnotations() + return nil + case chargeusagebasedrundetailedline.FieldNamespace: + m.ResetNamespace() + return nil + case chargeusagebasedrundetailedline.FieldMetadata: + m.ResetMetadata() + return nil + case chargeusagebasedrundetailedline.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case chargeusagebasedrundetailedline.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case chargeusagebasedrundetailedline.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case chargeusagebasedrundetailedline.FieldName: + m.ResetName() + return nil + case chargeusagebasedrundetailedline.FieldDescription: + m.ResetDescription() + return nil + case chargeusagebasedrundetailedline.FieldAmount: + m.ResetAmount() + return nil + case chargeusagebasedrundetailedline.FieldTaxesTotal: + m.ResetTaxesTotal() + return nil + case chargeusagebasedrundetailedline.FieldTaxesInclusiveTotal: + m.ResetTaxesInclusiveTotal() + return nil + case chargeusagebasedrundetailedline.FieldTaxesExclusiveTotal: + m.ResetTaxesExclusiveTotal() + return nil + case chargeusagebasedrundetailedline.FieldChargesTotal: + m.ResetChargesTotal() + return nil + case chargeusagebasedrundetailedline.FieldDiscountsTotal: + m.ResetDiscountsTotal() + return nil + case chargeusagebasedrundetailedline.FieldCreditsTotal: + m.ResetCreditsTotal() + return nil + case chargeusagebasedrundetailedline.FieldTotal: + m.ResetTotal() + return nil + case chargeusagebasedrundetailedline.FieldChargeID: + m.ResetChargeID() + return nil + case chargeusagebasedrundetailedline.FieldRunID: + m.ResetRunID() + return nil + case chargeusagebasedrundetailedline.FieldPricerReferenceID: + m.ResetPricerReferenceID() + return nil + case chargeusagebasedrundetailedline.FieldCorrectsRunID: + m.ResetCorrectsRunID() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunDetailedLine field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) AddedEdges() []string { + edges := make([]string, 0, 3) + if m.charge != nil { + edges = append(edges, chargeusagebasedrundetailedline.EdgeCharge) + } + if m.run != nil { + edges = append(edges, chargeusagebasedrundetailedline.EdgeRun) + } + if m.corrects_run != nil { + edges = append(edges, chargeusagebasedrundetailedline.EdgeCorrectsRun) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) AddedIDs(name string) []ent.Value { + switch name { + case chargeusagebasedrundetailedline.EdgeCharge: + if id := m.charge; id != nil { + return []ent.Value{*id} + } + case chargeusagebasedrundetailedline.EdgeRun: + if id := m.run; id != nil { + return []ent.Value{*id} + } + case chargeusagebasedrundetailedline.EdgeCorrectsRun: + if id := m.corrects_run; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) RemovedEdges() []string { + edges := make([]string, 0, 3) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) + if m.clearedcharge { + edges = append(edges, chargeusagebasedrundetailedline.EdgeCharge) + } + if m.clearedrun { + edges = append(edges, chargeusagebasedrundetailedline.EdgeRun) + } + if m.clearedcorrects_run { + edges = append(edges, chargeusagebasedrundetailedline.EdgeCorrectsRun) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ChargeUsageBasedRunDetailedLineMutation) EdgeCleared(name string) bool { + switch name { + case chargeusagebasedrundetailedline.EdgeCharge: + return m.clearedcharge + case chargeusagebasedrundetailedline.EdgeRun: + return m.clearedrun + case chargeusagebasedrundetailedline.EdgeCorrectsRun: + return m.clearedcorrects_run + } + 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 *ChargeUsageBasedRunDetailedLineMutation) ClearEdge(name string) error { + switch name { + case chargeusagebasedrundetailedline.EdgeCharge: + m.ClearCharge() + return nil + case chargeusagebasedrundetailedline.EdgeRun: + m.ClearRun() + return nil + case chargeusagebasedrundetailedline.EdgeCorrectsRun: + m.ClearCorrectsRun() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunDetailedLine 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 *ChargeUsageBasedRunDetailedLineMutation) ResetEdge(name string) error { + switch name { + case chargeusagebasedrundetailedline.EdgeCharge: + m.ResetCharge() + return nil + case chargeusagebasedrundetailedline.EdgeRun: + m.ResetRun() + return nil + case chargeusagebasedrundetailedline.EdgeCorrectsRun: + m.ResetCorrectsRun() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunDetailedLine 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 + 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 + 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) + } +} + +// 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 +} + +// 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, 17) + if m.service_period_from != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldServicePeriodFrom) + } + if m.service_period_to != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldServicePeriodTo) + } + 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.FieldServicePeriodFrom: + return m.ServicePeriodFrom() + case chargeusagebasedruninvoicedusage.FieldServicePeriodTo: + return m.ServicePeriodTo() + 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.FieldServicePeriodFrom: + return m.OldServicePeriodFrom(ctx) + case chargeusagebasedruninvoicedusage.FieldServicePeriodTo: + return m.OldServicePeriodTo(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.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.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.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.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.FieldServicePeriodFrom: + m.ResetServicePeriodFrom() + return nil + case chargeusagebasedruninvoicedusage.FieldServicePeriodTo: + m.ResetServicePeriodTo() + 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 + invoice_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 +} + +// SetInvoiceID sets the "invoice_id" field. +func (m *ChargeUsageBasedRunPaymentMutation) SetInvoiceID(s string) { + m.invoice_id = &s +} + +// InvoiceID returns the value of the "invoice_id" field in the mutation. +func (m *ChargeUsageBasedRunPaymentMutation) InvoiceID() (r string, exists bool) { + v := m.invoice_id + if v == nil { + return + } + return *v, true +} + +// OldInvoiceID returns the old "invoice_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) OldInvoiceID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceID: %w", err) + } + return oldValue.InvoiceID, nil +} + +// ResetInvoiceID resets all changes to the "invoice_id" field. +func (m *ChargeUsageBasedRunPaymentMutation) ResetInvoiceID() { + m.invoice_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, 16) + if m.line_id != nil { + fields = append(fields, chargeusagebasedrunpayment.FieldLineID) + } + if m.invoice_id != nil { + fields = append(fields, chargeusagebasedrunpayment.FieldInvoiceID) + } + 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.FieldInvoiceID: + return m.InvoiceID() + 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.FieldInvoiceID: + return m.OldInvoiceID(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.FieldInvoiceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceID(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.FieldInvoiceID: + m.ResetInvoiceID() + 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 + 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 + _type *usagebased.RealizationRunType + initial_type *usagebased.RealizationRunType + stored_at_lt *time.Time + service_period_to *time.Time + detailed_lines_present *bool + metered_quantity *alpacadecimal.Decimal + no_fiat_transaction_required *bool + clearedFields map[string]struct{} + usage_based *string + clearedusage_based bool + feature *string + clearedfeature bool + billing_invoice_line *string + clearedbilling_invoice_line bool + billing_invoice *string + clearedbilling_invoice bool + credit_allocations map[string]struct{} + removedcredit_allocations map[string]struct{} + clearedcredit_allocations bool + detailed_lines map[string]struct{} + removeddetailed_lines map[string]struct{} + cleareddetailed_lines bool + corrected_detailed_lines map[string]struct{} + removedcorrected_detailed_lines map[string]struct{} + clearedcorrected_detailed_lines 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) +} + +// SetAmount sets the "amount" field. +func (m *ChargeUsageBasedRunsMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) 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 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) 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 *ChargeUsageBasedRunsMutation) ResetAmount() { + m.amount = nil +} + +// SetTaxesTotal sets the "taxes_total" field. +func (m *ChargeUsageBasedRunsMutation) SetTaxesTotal(a alpacadecimal.Decimal) { + m.taxes_total = &a +} + +// TaxesTotal returns the value of the "taxes_total" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) 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 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) 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 *ChargeUsageBasedRunsMutation) ResetTaxesTotal() { + m.taxes_total = nil +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (m *ChargeUsageBasedRunsMutation) SetTaxesInclusiveTotal(a alpacadecimal.Decimal) { + m.taxes_inclusive_total = &a +} + +// TaxesInclusiveTotal returns the value of the "taxes_inclusive_total" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) 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 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) 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 *ChargeUsageBasedRunsMutation) ResetTaxesInclusiveTotal() { + m.taxes_inclusive_total = nil +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (m *ChargeUsageBasedRunsMutation) SetTaxesExclusiveTotal(a alpacadecimal.Decimal) { + m.taxes_exclusive_total = &a +} + +// TaxesExclusiveTotal returns the value of the "taxes_exclusive_total" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) 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 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) 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 *ChargeUsageBasedRunsMutation) ResetTaxesExclusiveTotal() { + m.taxes_exclusive_total = nil +} + +// SetChargesTotal sets the "charges_total" field. +func (m *ChargeUsageBasedRunsMutation) SetChargesTotal(a alpacadecimal.Decimal) { + m.charges_total = &a +} + +// ChargesTotal returns the value of the "charges_total" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) 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 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) 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 *ChargeUsageBasedRunsMutation) ResetChargesTotal() { + m.charges_total = nil +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (m *ChargeUsageBasedRunsMutation) SetDiscountsTotal(a alpacadecimal.Decimal) { + m.discounts_total = &a +} + +// DiscountsTotal returns the value of the "discounts_total" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) 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 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) 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 *ChargeUsageBasedRunsMutation) ResetDiscountsTotal() { + m.discounts_total = nil +} + +// SetCreditsTotal sets the "credits_total" field. +func (m *ChargeUsageBasedRunsMutation) SetCreditsTotal(a alpacadecimal.Decimal) { + m.credits_total = &a +} + +// CreditsTotal returns the value of the "credits_total" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) 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 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) 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 *ChargeUsageBasedRunsMutation) ResetCreditsTotal() { + m.credits_total = nil +} + +// SetTotal sets the "total" field. +func (m *ChargeUsageBasedRunsMutation) SetTotal(a alpacadecimal.Decimal) { + m.total = &a +} + +// Total returns the value of the "total" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) 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 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) 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 *ChargeUsageBasedRunsMutation) ResetTotal() { + m.total = nil +} + +// 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 +} + +// SetFeatureID sets the "feature_id" field. +func (m *ChargeUsageBasedRunsMutation) SetFeatureID(s string) { + m.feature = &s +} + +// FeatureID returns the value of the "feature_id" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) FeatureID() (r string, exists bool) { + v := m.feature + if v == nil { + return + } + return *v, true +} + +// OldFeatureID returns the old "feature_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) OldFeatureID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFeatureID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFeatureID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFeatureID: %w", err) + } + return oldValue.FeatureID, nil +} + +// ResetFeatureID resets all changes to the "feature_id" field. +func (m *ChargeUsageBasedRunsMutation) ResetFeatureID() { + m.feature = 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 +} + +// SetInitialType sets the "initial_type" field. +func (m *ChargeUsageBasedRunsMutation) SetInitialType(urt usagebased.RealizationRunType) { + m.initial_type = &urt +} + +// InitialType returns the value of the "initial_type" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) InitialType() (r usagebased.RealizationRunType, exists bool) { + v := m.initial_type + if v == nil { + return + } + return *v, true +} + +// OldInitialType returns the old "initial_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) OldInitialType(ctx context.Context) (v usagebased.RealizationRunType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInitialType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInitialType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInitialType: %w", err) + } + return oldValue.InitialType, nil +} + +// ResetInitialType resets all changes to the "initial_type" field. +func (m *ChargeUsageBasedRunsMutation) ResetInitialType() { + m.initial_type = nil +} + +// SetStoredAtLt sets the "stored_at_lt" field. +func (m *ChargeUsageBasedRunsMutation) SetStoredAtLt(t time.Time) { + m.stored_at_lt = &t +} + +// StoredAtLt returns the value of the "stored_at_lt" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) StoredAtLt() (r time.Time, exists bool) { + v := m.stored_at_lt + if v == nil { + return + } + return *v, true +} + +// OldStoredAtLt returns the old "stored_at_lt" 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) OldStoredAtLt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStoredAtLt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStoredAtLt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStoredAtLt: %w", err) + } + return oldValue.StoredAtLt, nil +} + +// ResetStoredAtLt resets all changes to the "stored_at_lt" field. +func (m *ChargeUsageBasedRunsMutation) ResetStoredAtLt() { + m.stored_at_lt = nil +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (m *ChargeUsageBasedRunsMutation) SetServicePeriodTo(t time.Time) { + m.service_period_to = &t +} + +// ServicePeriodTo returns the value of the "service_period_to" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) 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 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) 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 *ChargeUsageBasedRunsMutation) ResetServicePeriodTo() { + m.service_period_to = nil +} + +// SetDetailedLinesPresent sets the "detailed_lines_present" field. +func (m *ChargeUsageBasedRunsMutation) SetDetailedLinesPresent(b bool) { + m.detailed_lines_present = &b +} + +// DetailedLinesPresent returns the value of the "detailed_lines_present" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) DetailedLinesPresent() (r bool, exists bool) { + v := m.detailed_lines_present + if v == nil { + return + } + return *v, true +} + +// OldDetailedLinesPresent returns the old "detailed_lines_present" 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) OldDetailedLinesPresent(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDetailedLinesPresent is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDetailedLinesPresent requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDetailedLinesPresent: %w", err) + } + return oldValue.DetailedLinesPresent, nil +} + +// ResetDetailedLinesPresent resets all changes to the "detailed_lines_present" field. +func (m *ChargeUsageBasedRunsMutation) ResetDetailedLinesPresent() { + m.detailed_lines_present = nil +} + +// SetLineID sets the "line_id" field. +func (m *ChargeUsageBasedRunsMutation) SetLineID(s string) { + m.billing_invoice_line = &s +} + +// LineID returns the value of the "line_id" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) LineID() (r string, exists bool) { + v := m.billing_invoice_line + if v == nil { + return + } + return *v, true +} + +// OldLineID returns the old "line_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) 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 *ChargeUsageBasedRunsMutation) ClearLineID() { + m.billing_invoice_line = nil + m.clearedFields[chargeusagebasedruns.FieldLineID] = struct{}{} +} + +// LineIDCleared returns if the "line_id" field was cleared in this mutation. +func (m *ChargeUsageBasedRunsMutation) LineIDCleared() bool { + _, ok := m.clearedFields[chargeusagebasedruns.FieldLineID] + return ok +} + +// ResetLineID resets all changes to the "line_id" field. +func (m *ChargeUsageBasedRunsMutation) ResetLineID() { + m.billing_invoice_line = nil + delete(m.clearedFields, chargeusagebasedruns.FieldLineID) +} + +// SetInvoiceID sets the "invoice_id" field. +func (m *ChargeUsageBasedRunsMutation) SetInvoiceID(s string) { + m.billing_invoice = &s +} + +// InvoiceID returns the value of the "invoice_id" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) InvoiceID() (r string, exists bool) { + v := m.billing_invoice + if v == nil { + return + } + return *v, true +} + +// OldInvoiceID returns the old "invoice_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) OldInvoiceID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceID: %w", err) + } + return oldValue.InvoiceID, nil +} + +// ClearInvoiceID clears the value of the "invoice_id" field. +func (m *ChargeUsageBasedRunsMutation) ClearInvoiceID() { + m.billing_invoice = nil + m.clearedFields[chargeusagebasedruns.FieldInvoiceID] = struct{}{} +} + +// InvoiceIDCleared returns if the "invoice_id" field was cleared in this mutation. +func (m *ChargeUsageBasedRunsMutation) InvoiceIDCleared() bool { + _, ok := m.clearedFields[chargeusagebasedruns.FieldInvoiceID] + return ok +} + +// ResetInvoiceID resets all changes to the "invoice_id" field. +func (m *ChargeUsageBasedRunsMutation) ResetInvoiceID() { + m.billing_invoice = nil + delete(m.clearedFields, chargeusagebasedruns.FieldInvoiceID) +} + +// SetMeteredQuantity sets the "metered_quantity" field. +func (m *ChargeUsageBasedRunsMutation) SetMeteredQuantity(a alpacadecimal.Decimal) { + m.metered_quantity = &a +} + +// MeteredQuantity returns the value of the "metered_quantity" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) MeteredQuantity() (r alpacadecimal.Decimal, exists bool) { + v := m.metered_quantity + if v == nil { + return + } + return *v, true +} + +// OldMeteredQuantity returns the old "metered_quantity" 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) OldMeteredQuantity(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMeteredQuantity is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMeteredQuantity requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMeteredQuantity: %w", err) + } + return oldValue.MeteredQuantity, nil +} + +// ResetMeteredQuantity resets all changes to the "metered_quantity" field. +func (m *ChargeUsageBasedRunsMutation) ResetMeteredQuantity() { + m.metered_quantity = nil +} + +// SetNoFiatTransactionRequired sets the "no_fiat_transaction_required" field. +func (m *ChargeUsageBasedRunsMutation) SetNoFiatTransactionRequired(b bool) { + m.no_fiat_transaction_required = &b +} + +// NoFiatTransactionRequired returns the value of the "no_fiat_transaction_required" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) NoFiatTransactionRequired() (r bool, exists bool) { + v := m.no_fiat_transaction_required + if v == nil { + return + } + return *v, true +} + +// OldNoFiatTransactionRequired returns the old "no_fiat_transaction_required" 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) OldNoFiatTransactionRequired(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNoFiatTransactionRequired is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNoFiatTransactionRequired requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNoFiatTransactionRequired: %w", err) + } + return oldValue.NoFiatTransactionRequired, nil +} + +// ResetNoFiatTransactionRequired resets all changes to the "no_fiat_transaction_required" field. +func (m *ChargeUsageBasedRunsMutation) ResetNoFiatTransactionRequired() { + m.no_fiat_transaction_required = 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 +} + +// ClearFeature clears the "feature" edge to the Feature entity. +func (m *ChargeUsageBasedRunsMutation) ClearFeature() { + m.clearedfeature = true + m.clearedFields[chargeusagebasedruns.FieldFeatureID] = struct{}{} +} + +// FeatureCleared reports if the "feature" edge to the Feature entity was cleared. +func (m *ChargeUsageBasedRunsMutation) FeatureCleared() bool { + return m.clearedfeature +} + +// FeatureIDs returns the "feature" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// FeatureID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedRunsMutation) FeatureIDs() (ids []string) { + if id := m.feature; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetFeature resets all changes to the "feature" edge. +func (m *ChargeUsageBasedRunsMutation) ResetFeature() { + m.feature = nil + m.clearedfeature = false +} + +// SetBillingInvoiceLineID sets the "billing_invoice_line" edge to the BillingInvoiceLine entity by id. +func (m *ChargeUsageBasedRunsMutation) SetBillingInvoiceLineID(id string) { + m.billing_invoice_line = &id +} + +// ClearBillingInvoiceLine clears the "billing_invoice_line" edge to the BillingInvoiceLine entity. +func (m *ChargeUsageBasedRunsMutation) ClearBillingInvoiceLine() { + m.clearedbilling_invoice_line = true + m.clearedFields[chargeusagebasedruns.FieldLineID] = struct{}{} +} + +// BillingInvoiceLineCleared reports if the "billing_invoice_line" edge to the BillingInvoiceLine entity was cleared. +func (m *ChargeUsageBasedRunsMutation) BillingInvoiceLineCleared() bool { + return m.LineIDCleared() || m.clearedbilling_invoice_line +} + +// BillingInvoiceLineID returns the "billing_invoice_line" edge ID in the mutation. +func (m *ChargeUsageBasedRunsMutation) BillingInvoiceLineID() (id string, exists bool) { + if m.billing_invoice_line != nil { + return *m.billing_invoice_line, true + } + return +} + +// BillingInvoiceLineIDs returns the "billing_invoice_line" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BillingInvoiceLineID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedRunsMutation) BillingInvoiceLineIDs() (ids []string) { + if id := m.billing_invoice_line; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBillingInvoiceLine resets all changes to the "billing_invoice_line" edge. +func (m *ChargeUsageBasedRunsMutation) ResetBillingInvoiceLine() { + m.billing_invoice_line = nil + m.clearedbilling_invoice_line = false +} + +// SetBillingInvoiceID sets the "billing_invoice" edge to the BillingInvoice entity by id. +func (m *ChargeUsageBasedRunsMutation) SetBillingInvoiceID(id string) { + m.billing_invoice = &id +} + +// ClearBillingInvoice clears the "billing_invoice" edge to the BillingInvoice entity. +func (m *ChargeUsageBasedRunsMutation) ClearBillingInvoice() { + m.clearedbilling_invoice = true + m.clearedFields[chargeusagebasedruns.FieldInvoiceID] = struct{}{} +} + +// BillingInvoiceCleared reports if the "billing_invoice" edge to the BillingInvoice entity was cleared. +func (m *ChargeUsageBasedRunsMutation) BillingInvoiceCleared() bool { + return m.InvoiceIDCleared() || m.clearedbilling_invoice +} + +// BillingInvoiceID returns the "billing_invoice" edge ID in the mutation. +func (m *ChargeUsageBasedRunsMutation) BillingInvoiceID() (id string, exists bool) { + if m.billing_invoice != nil { + return *m.billing_invoice, true + } + return +} + +// BillingInvoiceIDs returns the "billing_invoice" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BillingInvoiceID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedRunsMutation) BillingInvoiceIDs() (ids []string) { + if id := m.billing_invoice; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBillingInvoice resets all changes to the "billing_invoice" edge. +func (m *ChargeUsageBasedRunsMutation) ResetBillingInvoice() { + m.billing_invoice = nil + m.clearedbilling_invoice = 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 +} + +// AddDetailedLineIDs adds the "detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity by ids. +func (m *ChargeUsageBasedRunsMutation) AddDetailedLineIDs(ids ...string) { + if m.detailed_lines == nil { + m.detailed_lines = make(map[string]struct{}) + } + for i := range ids { + m.detailed_lines[ids[i]] = struct{}{} + } +} + +// ClearDetailedLines clears the "detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity. +func (m *ChargeUsageBasedRunsMutation) ClearDetailedLines() { + m.cleareddetailed_lines = true +} + +// DetailedLinesCleared reports if the "detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity was cleared. +func (m *ChargeUsageBasedRunsMutation) DetailedLinesCleared() bool { + return m.cleareddetailed_lines +} + +// RemoveDetailedLineIDs removes the "detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity by IDs. +func (m *ChargeUsageBasedRunsMutation) RemoveDetailedLineIDs(ids ...string) { + if m.removeddetailed_lines == nil { + m.removeddetailed_lines = make(map[string]struct{}) + } + for i := range ids { + delete(m.detailed_lines, ids[i]) + m.removeddetailed_lines[ids[i]] = struct{}{} + } +} + +// RemovedDetailedLines returns the removed IDs of the "detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity. +func (m *ChargeUsageBasedRunsMutation) RemovedDetailedLinesIDs() (ids []string) { + for id := range m.removeddetailed_lines { + ids = append(ids, id) + } + return +} + +// DetailedLinesIDs returns the "detailed_lines" edge IDs in the mutation. +func (m *ChargeUsageBasedRunsMutation) DetailedLinesIDs() (ids []string) { + for id := range m.detailed_lines { + ids = append(ids, id) + } + return +} + +// ResetDetailedLines resets all changes to the "detailed_lines" edge. +func (m *ChargeUsageBasedRunsMutation) ResetDetailedLines() { + m.detailed_lines = nil + m.cleareddetailed_lines = false + m.removeddetailed_lines = nil +} + +// AddCorrectedDetailedLineIDs adds the "corrected_detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity by ids. +func (m *ChargeUsageBasedRunsMutation) AddCorrectedDetailedLineIDs(ids ...string) { + if m.corrected_detailed_lines == nil { + m.corrected_detailed_lines = make(map[string]struct{}) + } + for i := range ids { + m.corrected_detailed_lines[ids[i]] = struct{}{} + } +} + +// ClearCorrectedDetailedLines clears the "corrected_detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity. +func (m *ChargeUsageBasedRunsMutation) ClearCorrectedDetailedLines() { + m.clearedcorrected_detailed_lines = true +} + +// CorrectedDetailedLinesCleared reports if the "corrected_detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity was cleared. +func (m *ChargeUsageBasedRunsMutation) CorrectedDetailedLinesCleared() bool { + return m.clearedcorrected_detailed_lines +} + +// RemoveCorrectedDetailedLineIDs removes the "corrected_detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity by IDs. +func (m *ChargeUsageBasedRunsMutation) RemoveCorrectedDetailedLineIDs(ids ...string) { + if m.removedcorrected_detailed_lines == nil { + m.removedcorrected_detailed_lines = make(map[string]struct{}) + } + for i := range ids { + delete(m.corrected_detailed_lines, ids[i]) + m.removedcorrected_detailed_lines[ids[i]] = struct{}{} + } +} + +// RemovedCorrectedDetailedLines returns the removed IDs of the "corrected_detailed_lines" edge to the ChargeUsageBasedRunDetailedLine entity. +func (m *ChargeUsageBasedRunsMutation) RemovedCorrectedDetailedLinesIDs() (ids []string) { + for id := range m.removedcorrected_detailed_lines { + ids = append(ids, id) + } + return +} + +// CorrectedDetailedLinesIDs returns the "corrected_detailed_lines" edge IDs in the mutation. +func (m *ChargeUsageBasedRunsMutation) CorrectedDetailedLinesIDs() (ids []string) { + for id := range m.corrected_detailed_lines { + ids = append(ids, id) + } + return +} + +// ResetCorrectedDetailedLines resets all changes to the "corrected_detailed_lines" edge. +func (m *ChargeUsageBasedRunsMutation) ResetCorrectedDetailedLines() { + m.corrected_detailed_lines = nil + m.clearedcorrected_detailed_lines = false + m.removedcorrected_detailed_lines = 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, 23) + 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.amount != nil { + fields = append(fields, chargeusagebasedruns.FieldAmount) + } + if m.taxes_total != nil { + fields = append(fields, chargeusagebasedruns.FieldTaxesTotal) + } + if m.taxes_inclusive_total != nil { + fields = append(fields, chargeusagebasedruns.FieldTaxesInclusiveTotal) + } + if m.taxes_exclusive_total != nil { + fields = append(fields, chargeusagebasedruns.FieldTaxesExclusiveTotal) + } + if m.charges_total != nil { + fields = append(fields, chargeusagebasedruns.FieldChargesTotal) + } + if m.discounts_total != nil { + fields = append(fields, chargeusagebasedruns.FieldDiscountsTotal) + } + if m.credits_total != nil { + fields = append(fields, chargeusagebasedruns.FieldCreditsTotal) + } + if m.total != nil { + fields = append(fields, chargeusagebasedruns.FieldTotal) + } + if m.usage_based != nil { + fields = append(fields, chargeusagebasedruns.FieldChargeID) + } + if m.feature != nil { + fields = append(fields, chargeusagebasedruns.FieldFeatureID) + } + if m._type != nil { + fields = append(fields, chargeusagebasedruns.FieldType) + } + if m.initial_type != nil { + fields = append(fields, chargeusagebasedruns.FieldInitialType) + } + if m.stored_at_lt != nil { + fields = append(fields, chargeusagebasedruns.FieldStoredAtLt) + } + if m.service_period_to != nil { + fields = append(fields, chargeusagebasedruns.FieldServicePeriodTo) + } + if m.detailed_lines_present != nil { + fields = append(fields, chargeusagebasedruns.FieldDetailedLinesPresent) + } + if m.billing_invoice_line != nil { + fields = append(fields, chargeusagebasedruns.FieldLineID) + } + if m.billing_invoice != nil { + fields = append(fields, chargeusagebasedruns.FieldInvoiceID) + } + if m.metered_quantity != nil { + fields = append(fields, chargeusagebasedruns.FieldMeteredQuantity) + } + if m.no_fiat_transaction_required != nil { + fields = append(fields, chargeusagebasedruns.FieldNoFiatTransactionRequired) + } + 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.FieldAmount: + return m.Amount() + case chargeusagebasedruns.FieldTaxesTotal: + return m.TaxesTotal() + case chargeusagebasedruns.FieldTaxesInclusiveTotal: + return m.TaxesInclusiveTotal() + case chargeusagebasedruns.FieldTaxesExclusiveTotal: + return m.TaxesExclusiveTotal() + case chargeusagebasedruns.FieldChargesTotal: + return m.ChargesTotal() + case chargeusagebasedruns.FieldDiscountsTotal: + return m.DiscountsTotal() + case chargeusagebasedruns.FieldCreditsTotal: + return m.CreditsTotal() + case chargeusagebasedruns.FieldTotal: + return m.Total() + case chargeusagebasedruns.FieldChargeID: + return m.ChargeID() + case chargeusagebasedruns.FieldFeatureID: + return m.FeatureID() + case chargeusagebasedruns.FieldType: + return m.GetType() + case chargeusagebasedruns.FieldInitialType: + return m.InitialType() + case chargeusagebasedruns.FieldStoredAtLt: + return m.StoredAtLt() + case chargeusagebasedruns.FieldServicePeriodTo: + return m.ServicePeriodTo() + case chargeusagebasedruns.FieldDetailedLinesPresent: + return m.DetailedLinesPresent() + case chargeusagebasedruns.FieldLineID: + return m.LineID() + case chargeusagebasedruns.FieldInvoiceID: + return m.InvoiceID() + case chargeusagebasedruns.FieldMeteredQuantity: + return m.MeteredQuantity() + case chargeusagebasedruns.FieldNoFiatTransactionRequired: + return m.NoFiatTransactionRequired() + } + 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.FieldAmount: + return m.OldAmount(ctx) + case chargeusagebasedruns.FieldTaxesTotal: + return m.OldTaxesTotal(ctx) + case chargeusagebasedruns.FieldTaxesInclusiveTotal: + return m.OldTaxesInclusiveTotal(ctx) + case chargeusagebasedruns.FieldTaxesExclusiveTotal: + return m.OldTaxesExclusiveTotal(ctx) + case chargeusagebasedruns.FieldChargesTotal: + return m.OldChargesTotal(ctx) + case chargeusagebasedruns.FieldDiscountsTotal: + return m.OldDiscountsTotal(ctx) + case chargeusagebasedruns.FieldCreditsTotal: + return m.OldCreditsTotal(ctx) + case chargeusagebasedruns.FieldTotal: + return m.OldTotal(ctx) + case chargeusagebasedruns.FieldChargeID: + return m.OldChargeID(ctx) + case chargeusagebasedruns.FieldFeatureID: + return m.OldFeatureID(ctx) + case chargeusagebasedruns.FieldType: + return m.OldType(ctx) + case chargeusagebasedruns.FieldInitialType: + return m.OldInitialType(ctx) + case chargeusagebasedruns.FieldStoredAtLt: + return m.OldStoredAtLt(ctx) + case chargeusagebasedruns.FieldServicePeriodTo: + return m.OldServicePeriodTo(ctx) + case chargeusagebasedruns.FieldDetailedLinesPresent: + return m.OldDetailedLinesPresent(ctx) + case chargeusagebasedruns.FieldLineID: + return m.OldLineID(ctx) + case chargeusagebasedruns.FieldInvoiceID: + return m.OldInvoiceID(ctx) + case chargeusagebasedruns.FieldMeteredQuantity: + return m.OldMeteredQuantity(ctx) + case chargeusagebasedruns.FieldNoFiatTransactionRequired: + return m.OldNoFiatTransactionRequired(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.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 chargeusagebasedruns.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 chargeusagebasedruns.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 chargeusagebasedruns.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 chargeusagebasedruns.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 chargeusagebasedruns.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 chargeusagebasedruns.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 chargeusagebasedruns.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 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.FieldFeatureID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFeatureID(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.FieldInitialType: + v, ok := value.(usagebased.RealizationRunType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInitialType(v) + return nil + case chargeusagebasedruns.FieldStoredAtLt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStoredAtLt(v) + return nil + case chargeusagebasedruns.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 chargeusagebasedruns.FieldDetailedLinesPresent: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDetailedLinesPresent(v) + return nil + case chargeusagebasedruns.FieldLineID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLineID(v) + return nil + case chargeusagebasedruns.FieldInvoiceID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceID(v) + return nil + case chargeusagebasedruns.FieldMeteredQuantity: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMeteredQuantity(v) + return nil + case chargeusagebasedruns.FieldNoFiatTransactionRequired: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNoFiatTransactionRequired(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) + } + if m.FieldCleared(chargeusagebasedruns.FieldLineID) { + fields = append(fields, chargeusagebasedruns.FieldLineID) + } + if m.FieldCleared(chargeusagebasedruns.FieldInvoiceID) { + fields = append(fields, chargeusagebasedruns.FieldInvoiceID) + } + 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 + case chargeusagebasedruns.FieldLineID: + m.ClearLineID() + return nil + case chargeusagebasedruns.FieldInvoiceID: + m.ClearInvoiceID() + 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.FieldAmount: + m.ResetAmount() + return nil + case chargeusagebasedruns.FieldTaxesTotal: + m.ResetTaxesTotal() + return nil + case chargeusagebasedruns.FieldTaxesInclusiveTotal: + m.ResetTaxesInclusiveTotal() + return nil + case chargeusagebasedruns.FieldTaxesExclusiveTotal: + m.ResetTaxesExclusiveTotal() + return nil + case chargeusagebasedruns.FieldChargesTotal: + m.ResetChargesTotal() + return nil + case chargeusagebasedruns.FieldDiscountsTotal: + m.ResetDiscountsTotal() + return nil + case chargeusagebasedruns.FieldCreditsTotal: + m.ResetCreditsTotal() + return nil + case chargeusagebasedruns.FieldTotal: + m.ResetTotal() + return nil + case chargeusagebasedruns.FieldChargeID: + m.ResetChargeID() + return nil + case chargeusagebasedruns.FieldFeatureID: + m.ResetFeatureID() + return nil + case chargeusagebasedruns.FieldType: + m.ResetType() + return nil + case chargeusagebasedruns.FieldInitialType: + m.ResetInitialType() + return nil + case chargeusagebasedruns.FieldStoredAtLt: + m.ResetStoredAtLt() + return nil + case chargeusagebasedruns.FieldServicePeriodTo: + m.ResetServicePeriodTo() + return nil + case chargeusagebasedruns.FieldDetailedLinesPresent: + m.ResetDetailedLinesPresent() + return nil + case chargeusagebasedruns.FieldLineID: + m.ResetLineID() + return nil + case chargeusagebasedruns.FieldInvoiceID: + m.ResetInvoiceID() + return nil + case chargeusagebasedruns.FieldMeteredQuantity: + m.ResetMeteredQuantity() + return nil + case chargeusagebasedruns.FieldNoFiatTransactionRequired: + m.ResetNoFiatTransactionRequired() + 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, 9) + if m.usage_based != nil { + edges = append(edges, chargeusagebasedruns.EdgeUsageBased) + } + if m.feature != nil { + edges = append(edges, chargeusagebasedruns.EdgeFeature) + } + if m.billing_invoice_line != nil { + edges = append(edges, chargeusagebasedruns.EdgeBillingInvoiceLine) + } + if m.billing_invoice != nil { + edges = append(edges, chargeusagebasedruns.EdgeBillingInvoice) + } + if m.credit_allocations != nil { + edges = append(edges, chargeusagebasedruns.EdgeCreditAllocations) + } + if m.detailed_lines != nil { + edges = append(edges, chargeusagebasedruns.EdgeDetailedLines) + } + if m.corrected_detailed_lines != nil { + edges = append(edges, chargeusagebasedruns.EdgeCorrectedDetailedLines) + } + 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.EdgeFeature: + if id := m.feature; id != nil { + return []ent.Value{*id} + } + case chargeusagebasedruns.EdgeBillingInvoiceLine: + if id := m.billing_invoice_line; id != nil { + return []ent.Value{*id} + } + case chargeusagebasedruns.EdgeBillingInvoice: + if id := m.billing_invoice; 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.EdgeDetailedLines: + ids := make([]ent.Value, 0, len(m.detailed_lines)) + for id := range m.detailed_lines { + ids = append(ids, id) + } + return ids + case chargeusagebasedruns.EdgeCorrectedDetailedLines: + ids := make([]ent.Value, 0, len(m.corrected_detailed_lines)) + for id := range m.corrected_detailed_lines { + 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, 9) + if m.removedcredit_allocations != nil { + edges = append(edges, chargeusagebasedruns.EdgeCreditAllocations) + } + if m.removeddetailed_lines != nil { + edges = append(edges, chargeusagebasedruns.EdgeDetailedLines) + } + if m.removedcorrected_detailed_lines != nil { + edges = append(edges, chargeusagebasedruns.EdgeCorrectedDetailedLines) + } + 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 + case chargeusagebasedruns.EdgeDetailedLines: + ids := make([]ent.Value, 0, len(m.removeddetailed_lines)) + for id := range m.removeddetailed_lines { + ids = append(ids, id) + } + return ids + case chargeusagebasedruns.EdgeCorrectedDetailedLines: + ids := make([]ent.Value, 0, len(m.removedcorrected_detailed_lines)) + for id := range m.removedcorrected_detailed_lines { + 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, 9) + if m.clearedusage_based { + edges = append(edges, chargeusagebasedruns.EdgeUsageBased) + } + if m.clearedfeature { + edges = append(edges, chargeusagebasedruns.EdgeFeature) + } + if m.clearedbilling_invoice_line { + edges = append(edges, chargeusagebasedruns.EdgeBillingInvoiceLine) + } + if m.clearedbilling_invoice { + edges = append(edges, chargeusagebasedruns.EdgeBillingInvoice) + } + if m.clearedcredit_allocations { + edges = append(edges, chargeusagebasedruns.EdgeCreditAllocations) + } + if m.cleareddetailed_lines { + edges = append(edges, chargeusagebasedruns.EdgeDetailedLines) + } + if m.clearedcorrected_detailed_lines { + edges = append(edges, chargeusagebasedruns.EdgeCorrectedDetailedLines) + } + 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.EdgeFeature: + return m.clearedfeature + case chargeusagebasedruns.EdgeBillingInvoiceLine: + return m.clearedbilling_invoice_line + case chargeusagebasedruns.EdgeBillingInvoice: + return m.clearedbilling_invoice + case chargeusagebasedruns.EdgeCreditAllocations: + return m.clearedcredit_allocations + case chargeusagebasedruns.EdgeDetailedLines: + return m.cleareddetailed_lines + case chargeusagebasedruns.EdgeCorrectedDetailedLines: + return m.clearedcorrected_detailed_lines + 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.EdgeFeature: + m.ClearFeature() + return nil + case chargeusagebasedruns.EdgeBillingInvoiceLine: + m.ClearBillingInvoiceLine() + return nil + case chargeusagebasedruns.EdgeBillingInvoice: + m.ClearBillingInvoice() + 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.EdgeFeature: + m.ResetFeature() + return nil + case chargeusagebasedruns.EdgeBillingInvoiceLine: + m.ResetBillingInvoiceLine() + return nil + case chargeusagebasedruns.EdgeBillingInvoice: + m.ResetBillingInvoice() + return nil + case chargeusagebasedruns.EdgeCreditAllocations: + m.ResetCreditAllocations() + return nil + case chargeusagebasedruns.EdgeDetailedLines: + m.ResetDetailedLines() + return nil + case chargeusagebasedruns.EdgeCorrectedDetailedLines: + m.ResetCorrectedDetailedLines() + return nil + case chargeusagebasedruns.EdgeInvoicedUsage: + m.ResetInvoicedUsage() + return nil + case chargeusagebasedruns.EdgePayment: + m.ResetPayment() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRuns edge %s", name) +} + +// CreditRealizationLineageMutation represents an operation that mutates the CreditRealizationLineage nodes in the graph. +type CreditRealizationLineageMutation struct { + config + op Op + typ string + id *string + namespace *string + root_realization_id *string + customer_id *string + currency *currencyx.Code + origin_kind *creditrealization.LineageOriginKind + advance_features *pq.StringArray + created_at *time.Time + clearedFields map[string]struct{} + charge *string + clearedcharge bool + segments map[string]struct{} + removedsegments map[string]struct{} + clearedsegments bool + done bool + oldValue func(context.Context) (*CreditRealizationLineage, error) + predicates []predicate.CreditRealizationLineage +} + +var _ ent.Mutation = (*CreditRealizationLineageMutation)(nil) + +// creditrealizationlineageOption allows management of the mutation configuration using functional options. +type creditrealizationlineageOption func(*CreditRealizationLineageMutation) + +// newCreditRealizationLineageMutation creates new mutation for the CreditRealizationLineage entity. +func newCreditRealizationLineageMutation(c config, op Op, opts ...creditrealizationlineageOption) *CreditRealizationLineageMutation { + m := &CreditRealizationLineageMutation{ + config: c, + op: op, + typ: TypeCreditRealizationLineage, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withCreditRealizationLineageID sets the ID field of the mutation. +func withCreditRealizationLineageID(id string) creditrealizationlineageOption { + return func(m *CreditRealizationLineageMutation) { + var ( + err error + once sync.Once + value *CreditRealizationLineage + ) + m.oldValue = func(ctx context.Context) (*CreditRealizationLineage, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().CreditRealizationLineage.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withCreditRealizationLineage sets the old CreditRealizationLineage of the mutation. +func withCreditRealizationLineage(node *CreditRealizationLineage) creditrealizationlineageOption { + return func(m *CreditRealizationLineageMutation) { + m.oldValue = func(context.Context) (*CreditRealizationLineage, 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 CreditRealizationLineageMutation) 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 CreditRealizationLineageMutation) 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 CreditRealizationLineage entities. +func (m *CreditRealizationLineageMutation) 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 *CreditRealizationLineageMutation) 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 *CreditRealizationLineageMutation) 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().CreditRealizationLineage.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 *CreditRealizationLineageMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *CreditRealizationLineageMutation) 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 CreditRealizationLineage entity. +// If the CreditRealizationLineage 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 *CreditRealizationLineageMutation) 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 *CreditRealizationLineageMutation) ResetNamespace() { + m.namespace = nil +} + +// SetChargeID sets the "charge_id" field. +func (m *CreditRealizationLineageMutation) SetChargeID(s string) { + m.charge = &s +} + +// ChargeID returns the value of the "charge_id" field in the mutation. +func (m *CreditRealizationLineageMutation) ChargeID() (r string, exists bool) { + v := m.charge + if v == nil { + return + } + return *v, true +} + +// OldChargeID returns the old "charge_id" field's value of the CreditRealizationLineage entity. +// If the CreditRealizationLineage 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 *CreditRealizationLineageMutation) 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 *CreditRealizationLineageMutation) ResetChargeID() { + m.charge = nil +} + +// SetRootRealizationID sets the "root_realization_id" field. +func (m *CreditRealizationLineageMutation) SetRootRealizationID(s string) { + m.root_realization_id = &s +} + +// RootRealizationID returns the value of the "root_realization_id" field in the mutation. +func (m *CreditRealizationLineageMutation) RootRealizationID() (r string, exists bool) { + v := m.root_realization_id + if v == nil { + return + } + return *v, true +} + +// OldRootRealizationID returns the old "root_realization_id" field's value of the CreditRealizationLineage entity. +// If the CreditRealizationLineage 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 *CreditRealizationLineageMutation) OldRootRealizationID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRootRealizationID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRootRealizationID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRootRealizationID: %w", err) + } + return oldValue.RootRealizationID, nil +} + +// ResetRootRealizationID resets all changes to the "root_realization_id" field. +func (m *CreditRealizationLineageMutation) ResetRootRealizationID() { + m.root_realization_id = nil +} + +// SetCustomerID sets the "customer_id" field. +func (m *CreditRealizationLineageMutation) SetCustomerID(s string) { + m.customer_id = &s +} + +// CustomerID returns the value of the "customer_id" field in the mutation. +func (m *CreditRealizationLineageMutation) CustomerID() (r string, exists bool) { + v := m.customer_id + if v == nil { + return + } + return *v, true +} + +// OldCustomerID returns the old "customer_id" field's value of the CreditRealizationLineage entity. +// If the CreditRealizationLineage 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 *CreditRealizationLineageMutation) OldCustomerID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerID: %w", err) + } + return oldValue.CustomerID, nil +} + +// ResetCustomerID resets all changes to the "customer_id" field. +func (m *CreditRealizationLineageMutation) ResetCustomerID() { + m.customer_id = nil +} + +// SetCurrency sets the "currency" field. +func (m *CreditRealizationLineageMutation) SetCurrency(c currencyx.Code) { + m.currency = &c +} + +// Currency returns the value of the "currency" field in the mutation. +func (m *CreditRealizationLineageMutation) Currency() (r currencyx.Code, exists bool) { + v := m.currency + if v == nil { + return + } + return *v, true +} + +// OldCurrency returns the old "currency" field's value of the CreditRealizationLineage entity. +// If the CreditRealizationLineage 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 *CreditRealizationLineageMutation) OldCurrency(ctx context.Context) (v currencyx.Code, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrency is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrency requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrency: %w", err) + } + return oldValue.Currency, nil +} + +// ResetCurrency resets all changes to the "currency" field. +func (m *CreditRealizationLineageMutation) ResetCurrency() { + m.currency = nil +} + +// SetOriginKind sets the "origin_kind" field. +func (m *CreditRealizationLineageMutation) SetOriginKind(cok creditrealization.LineageOriginKind) { + m.origin_kind = &cok +} + +// OriginKind returns the value of the "origin_kind" field in the mutation. +func (m *CreditRealizationLineageMutation) OriginKind() (r creditrealization.LineageOriginKind, exists bool) { + v := m.origin_kind + if v == nil { + return + } + return *v, true +} + +// OldOriginKind returns the old "origin_kind" field's value of the CreditRealizationLineage entity. +// If the CreditRealizationLineage 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 *CreditRealizationLineageMutation) OldOriginKind(ctx context.Context) (v creditrealization.LineageOriginKind, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOriginKind is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOriginKind requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOriginKind: %w", err) + } + return oldValue.OriginKind, nil +} + +// ResetOriginKind resets all changes to the "origin_kind" field. +func (m *CreditRealizationLineageMutation) ResetOriginKind() { + m.origin_kind = nil +} + +// SetAdvanceFeatures sets the "advance_features" field. +func (m *CreditRealizationLineageMutation) SetAdvanceFeatures(pa pq.StringArray) { + m.advance_features = &pa +} + +// AdvanceFeatures returns the value of the "advance_features" field in the mutation. +func (m *CreditRealizationLineageMutation) AdvanceFeatures() (r pq.StringArray, exists bool) { + v := m.advance_features + if v == nil { + return + } + return *v, true +} + +// OldAdvanceFeatures returns the old "advance_features" field's value of the CreditRealizationLineage entity. +// If the CreditRealizationLineage 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 *CreditRealizationLineageMutation) OldAdvanceFeatures(ctx context.Context) (v pq.StringArray, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAdvanceFeatures is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAdvanceFeatures requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAdvanceFeatures: %w", err) + } + return oldValue.AdvanceFeatures, nil +} + +// ClearAdvanceFeatures clears the value of the "advance_features" field. +func (m *CreditRealizationLineageMutation) ClearAdvanceFeatures() { + m.advance_features = nil + m.clearedFields[creditrealizationlineage.FieldAdvanceFeatures] = struct{}{} +} + +// AdvanceFeaturesCleared returns if the "advance_features" field was cleared in this mutation. +func (m *CreditRealizationLineageMutation) AdvanceFeaturesCleared() bool { + _, ok := m.clearedFields[creditrealizationlineage.FieldAdvanceFeatures] + return ok +} + +// ResetAdvanceFeatures resets all changes to the "advance_features" field. +func (m *CreditRealizationLineageMutation) ResetAdvanceFeatures() { + m.advance_features = nil + delete(m.clearedFields, creditrealizationlineage.FieldAdvanceFeatures) +} + +// SetCreatedAt sets the "created_at" field. +func (m *CreditRealizationLineageMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *CreditRealizationLineageMutation) 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 CreditRealizationLineage entity. +// If the CreditRealizationLineage 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 *CreditRealizationLineageMutation) 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 *CreditRealizationLineageMutation) ResetCreatedAt() { + m.created_at = nil +} + +// ClearCharge clears the "charge" edge to the Charge entity. +func (m *CreditRealizationLineageMutation) ClearCharge() { + m.clearedcharge = true + m.clearedFields[creditrealizationlineage.FieldChargeID] = struct{}{} +} + +// ChargeCleared reports if the "charge" edge to the Charge entity was cleared. +func (m *CreditRealizationLineageMutation) ChargeCleared() bool { + return m.clearedcharge +} + +// 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 *CreditRealizationLineageMutation) ChargeIDs() (ids []string) { + if id := m.charge; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCharge resets all changes to the "charge" edge. +func (m *CreditRealizationLineageMutation) ResetCharge() { + m.charge = nil + m.clearedcharge = false +} + +// AddSegmentIDs adds the "segments" edge to the CreditRealizationLineageSegment entity by ids. +func (m *CreditRealizationLineageMutation) AddSegmentIDs(ids ...string) { + if m.segments == nil { + m.segments = make(map[string]struct{}) + } + for i := range ids { + m.segments[ids[i]] = struct{}{} + } +} + +// ClearSegments clears the "segments" edge to the CreditRealizationLineageSegment entity. +func (m *CreditRealizationLineageMutation) ClearSegments() { + m.clearedsegments = true +} + +// SegmentsCleared reports if the "segments" edge to the CreditRealizationLineageSegment entity was cleared. +func (m *CreditRealizationLineageMutation) SegmentsCleared() bool { + return m.clearedsegments +} + +// RemoveSegmentIDs removes the "segments" edge to the CreditRealizationLineageSegment entity by IDs. +func (m *CreditRealizationLineageMutation) RemoveSegmentIDs(ids ...string) { + if m.removedsegments == nil { + m.removedsegments = make(map[string]struct{}) + } + for i := range ids { + delete(m.segments, ids[i]) + m.removedsegments[ids[i]] = struct{}{} + } +} + +// RemovedSegments returns the removed IDs of the "segments" edge to the CreditRealizationLineageSegment entity. +func (m *CreditRealizationLineageMutation) RemovedSegmentsIDs() (ids []string) { + for id := range m.removedsegments { + ids = append(ids, id) + } + return +} + +// SegmentsIDs returns the "segments" edge IDs in the mutation. +func (m *CreditRealizationLineageMutation) SegmentsIDs() (ids []string) { + for id := range m.segments { + ids = append(ids, id) + } + return +} + +// ResetSegments resets all changes to the "segments" edge. +func (m *CreditRealizationLineageMutation) ResetSegments() { + m.segments = nil + m.clearedsegments = false + m.removedsegments = nil +} + +// Where appends a list predicates to the CreditRealizationLineageMutation builder. +func (m *CreditRealizationLineageMutation) Where(ps ...predicate.CreditRealizationLineage) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the CreditRealizationLineageMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *CreditRealizationLineageMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.CreditRealizationLineage, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *CreditRealizationLineageMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *CreditRealizationLineageMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (CreditRealizationLineage). +func (m *CreditRealizationLineageMutation) 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 *CreditRealizationLineageMutation) Fields() []string { + fields := make([]string, 0, 8) + if m.namespace != nil { + fields = append(fields, creditrealizationlineage.FieldNamespace) + } + if m.charge != nil { + fields = append(fields, creditrealizationlineage.FieldChargeID) + } + if m.root_realization_id != nil { + fields = append(fields, creditrealizationlineage.FieldRootRealizationID) + } + if m.customer_id != nil { + fields = append(fields, creditrealizationlineage.FieldCustomerID) + } + if m.currency != nil { + fields = append(fields, creditrealizationlineage.FieldCurrency) + } + if m.origin_kind != nil { + fields = append(fields, creditrealizationlineage.FieldOriginKind) + } + if m.advance_features != nil { + fields = append(fields, creditrealizationlineage.FieldAdvanceFeatures) + } + if m.created_at != nil { + fields = append(fields, creditrealizationlineage.FieldCreatedAt) + } + 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 *CreditRealizationLineageMutation) Field(name string) (ent.Value, bool) { + switch name { + case creditrealizationlineage.FieldNamespace: + return m.Namespace() + case creditrealizationlineage.FieldChargeID: + return m.ChargeID() + case creditrealizationlineage.FieldRootRealizationID: + return m.RootRealizationID() + case creditrealizationlineage.FieldCustomerID: + return m.CustomerID() + case creditrealizationlineage.FieldCurrency: + return m.Currency() + case creditrealizationlineage.FieldOriginKind: + return m.OriginKind() + case creditrealizationlineage.FieldAdvanceFeatures: + return m.AdvanceFeatures() + case creditrealizationlineage.FieldCreatedAt: + return m.CreatedAt() + } + 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 *CreditRealizationLineageMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case creditrealizationlineage.FieldNamespace: + return m.OldNamespace(ctx) + case creditrealizationlineage.FieldChargeID: + return m.OldChargeID(ctx) + case creditrealizationlineage.FieldRootRealizationID: + return m.OldRootRealizationID(ctx) + case creditrealizationlineage.FieldCustomerID: + return m.OldCustomerID(ctx) + case creditrealizationlineage.FieldCurrency: + return m.OldCurrency(ctx) + case creditrealizationlineage.FieldOriginKind: + return m.OldOriginKind(ctx) + case creditrealizationlineage.FieldAdvanceFeatures: + return m.OldAdvanceFeatures(ctx) + case creditrealizationlineage.FieldCreatedAt: + return m.OldCreatedAt(ctx) + } + return nil, fmt.Errorf("unknown CreditRealizationLineage 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 *CreditRealizationLineageMutation) SetField(name string, value ent.Value) error { + switch name { + case creditrealizationlineage.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case creditrealizationlineage.FieldChargeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChargeID(v) + return nil + case creditrealizationlineage.FieldRootRealizationID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRootRealizationID(v) + return nil + case creditrealizationlineage.FieldCustomerID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerID(v) + return nil + case creditrealizationlineage.FieldCurrency: + v, ok := value.(currencyx.Code) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrency(v) + return nil + case creditrealizationlineage.FieldOriginKind: + v, ok := value.(creditrealization.LineageOriginKind) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOriginKind(v) + return nil + case creditrealizationlineage.FieldAdvanceFeatures: + v, ok := value.(pq.StringArray) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAdvanceFeatures(v) + return nil + case creditrealizationlineage.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + } + return fmt.Errorf("unknown CreditRealizationLineage field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *CreditRealizationLineageMutation) 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 *CreditRealizationLineageMutation) 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 *CreditRealizationLineageMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown CreditRealizationLineage numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *CreditRealizationLineageMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(creditrealizationlineage.FieldAdvanceFeatures) { + fields = append(fields, creditrealizationlineage.FieldAdvanceFeatures) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *CreditRealizationLineageMutation) 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 *CreditRealizationLineageMutation) ClearField(name string) error { + switch name { + case creditrealizationlineage.FieldAdvanceFeatures: + m.ClearAdvanceFeatures() + return nil + } + return fmt.Errorf("unknown CreditRealizationLineage 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 *CreditRealizationLineageMutation) ResetField(name string) error { + switch name { + case creditrealizationlineage.FieldNamespace: + m.ResetNamespace() + return nil + case creditrealizationlineage.FieldChargeID: + m.ResetChargeID() + return nil + case creditrealizationlineage.FieldRootRealizationID: + m.ResetRootRealizationID() + return nil + case creditrealizationlineage.FieldCustomerID: + m.ResetCustomerID() + return nil + case creditrealizationlineage.FieldCurrency: + m.ResetCurrency() + return nil + case creditrealizationlineage.FieldOriginKind: + m.ResetOriginKind() + return nil + case creditrealizationlineage.FieldAdvanceFeatures: + m.ResetAdvanceFeatures() + return nil + case creditrealizationlineage.FieldCreatedAt: + m.ResetCreatedAt() + return nil + } + return fmt.Errorf("unknown CreditRealizationLineage field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *CreditRealizationLineageMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.charge != nil { + edges = append(edges, creditrealizationlineage.EdgeCharge) + } + if m.segments != nil { + edges = append(edges, creditrealizationlineage.EdgeSegments) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *CreditRealizationLineageMutation) AddedIDs(name string) []ent.Value { + switch name { + case creditrealizationlineage.EdgeCharge: + if id := m.charge; id != nil { + return []ent.Value{*id} + } + case creditrealizationlineage.EdgeSegments: + ids := make([]ent.Value, 0, len(m.segments)) + for id := range m.segments { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *CreditRealizationLineageMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedsegments != nil { + edges = append(edges, creditrealizationlineage.EdgeSegments) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *CreditRealizationLineageMutation) RemovedIDs(name string) []ent.Value { + switch name { + case creditrealizationlineage.EdgeSegments: + ids := make([]ent.Value, 0, len(m.removedsegments)) + for id := range m.removedsegments { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *CreditRealizationLineageMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedcharge { + edges = append(edges, creditrealizationlineage.EdgeCharge) + } + if m.clearedsegments { + edges = append(edges, creditrealizationlineage.EdgeSegments) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *CreditRealizationLineageMutation) EdgeCleared(name string) bool { + switch name { + case creditrealizationlineage.EdgeCharge: + return m.clearedcharge + case creditrealizationlineage.EdgeSegments: + return m.clearedsegments + } + 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 *CreditRealizationLineageMutation) ClearEdge(name string) error { + switch name { + case creditrealizationlineage.EdgeCharge: + m.ClearCharge() + return nil + } + return fmt.Errorf("unknown CreditRealizationLineage 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 *CreditRealizationLineageMutation) ResetEdge(name string) error { + switch name { + case creditrealizationlineage.EdgeCharge: + m.ResetCharge() + return nil + case creditrealizationlineage.EdgeSegments: + m.ResetSegments() + return nil + } + return fmt.Errorf("unknown CreditRealizationLineage edge %s", name) +} + +// CreditRealizationLineageSegmentMutation represents an operation that mutates the CreditRealizationLineageSegment nodes in the graph. +type CreditRealizationLineageSegmentMutation struct { + config + op Op + typ string + id *string + amount *alpacadecimal.Decimal + state *creditrealization.LineageSegmentState + backing_transaction_group_id *string + source_state *creditrealization.LineageSegmentState + source_backing_transaction_group_id *string + closed_at *time.Time + created_at *time.Time + clearedFields map[string]struct{} + lineage *string + clearedlineage bool + done bool + oldValue func(context.Context) (*CreditRealizationLineageSegment, error) + predicates []predicate.CreditRealizationLineageSegment +} + +var _ ent.Mutation = (*CreditRealizationLineageSegmentMutation)(nil) + +// creditrealizationlineagesegmentOption allows management of the mutation configuration using functional options. +type creditrealizationlineagesegmentOption func(*CreditRealizationLineageSegmentMutation) + +// newCreditRealizationLineageSegmentMutation creates new mutation for the CreditRealizationLineageSegment entity. +func newCreditRealizationLineageSegmentMutation(c config, op Op, opts ...creditrealizationlineagesegmentOption) *CreditRealizationLineageSegmentMutation { + m := &CreditRealizationLineageSegmentMutation{ + config: c, + op: op, + typ: TypeCreditRealizationLineageSegment, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withCreditRealizationLineageSegmentID sets the ID field of the mutation. +func withCreditRealizationLineageSegmentID(id string) creditrealizationlineagesegmentOption { + return func(m *CreditRealizationLineageSegmentMutation) { + var ( + err error + once sync.Once + value *CreditRealizationLineageSegment + ) + m.oldValue = func(ctx context.Context) (*CreditRealizationLineageSegment, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().CreditRealizationLineageSegment.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withCreditRealizationLineageSegment sets the old CreditRealizationLineageSegment of the mutation. +func withCreditRealizationLineageSegment(node *CreditRealizationLineageSegment) creditrealizationlineagesegmentOption { + return func(m *CreditRealizationLineageSegmentMutation) { + m.oldValue = func(context.Context) (*CreditRealizationLineageSegment, 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 CreditRealizationLineageSegmentMutation) 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 CreditRealizationLineageSegmentMutation) 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 CreditRealizationLineageSegment entities. +func (m *CreditRealizationLineageSegmentMutation) 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 *CreditRealizationLineageSegmentMutation) 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 *CreditRealizationLineageSegmentMutation) 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().CreditRealizationLineageSegment.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetLineageID sets the "lineage_id" field. +func (m *CreditRealizationLineageSegmentMutation) SetLineageID(s string) { + m.lineage = &s +} + +// LineageID returns the value of the "lineage_id" field in the mutation. +func (m *CreditRealizationLineageSegmentMutation) LineageID() (r string, exists bool) { + v := m.lineage + if v == nil { + return + } + return *v, true +} + +// OldLineageID returns the old "lineage_id" field's value of the CreditRealizationLineageSegment entity. +// If the CreditRealizationLineageSegment 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 *CreditRealizationLineageSegmentMutation) OldLineageID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLineageID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLineageID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLineageID: %w", err) + } + return oldValue.LineageID, nil +} + +// ResetLineageID resets all changes to the "lineage_id" field. +func (m *CreditRealizationLineageSegmentMutation) ResetLineageID() { + m.lineage = nil +} + +// SetAmount sets the "amount" field. +func (m *CreditRealizationLineageSegmentMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *CreditRealizationLineageSegmentMutation) 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 CreditRealizationLineageSegment entity. +// If the CreditRealizationLineageSegment 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 *CreditRealizationLineageSegmentMutation) 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 *CreditRealizationLineageSegmentMutation) ResetAmount() { + m.amount = nil +} + +// SetState sets the "state" field. +func (m *CreditRealizationLineageSegmentMutation) SetState(css creditrealization.LineageSegmentState) { + m.state = &css +} + +// State returns the value of the "state" field in the mutation. +func (m *CreditRealizationLineageSegmentMutation) State() (r creditrealization.LineageSegmentState, exists bool) { + v := m.state + if v == nil { + return + } + return *v, true +} + +// OldState returns the old "state" field's value of the CreditRealizationLineageSegment entity. +// If the CreditRealizationLineageSegment 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 *CreditRealizationLineageSegmentMutation) OldState(ctx context.Context) (v creditrealization.LineageSegmentState, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldState is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldState requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldState: %w", err) + } + return oldValue.State, nil +} + +// ResetState resets all changes to the "state" field. +func (m *CreditRealizationLineageSegmentMutation) ResetState() { + m.state = nil +} + +// SetBackingTransactionGroupID sets the "backing_transaction_group_id" field. +func (m *CreditRealizationLineageSegmentMutation) SetBackingTransactionGroupID(s string) { + m.backing_transaction_group_id = &s +} + +// BackingTransactionGroupID returns the value of the "backing_transaction_group_id" field in the mutation. +func (m *CreditRealizationLineageSegmentMutation) BackingTransactionGroupID() (r string, exists bool) { + v := m.backing_transaction_group_id + if v == nil { + return + } + return *v, true +} + +// OldBackingTransactionGroupID returns the old "backing_transaction_group_id" field's value of the CreditRealizationLineageSegment entity. +// If the CreditRealizationLineageSegment 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 *CreditRealizationLineageSegmentMutation) OldBackingTransactionGroupID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBackingTransactionGroupID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBackingTransactionGroupID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBackingTransactionGroupID: %w", err) + } + return oldValue.BackingTransactionGroupID, nil +} + +// ClearBackingTransactionGroupID clears the value of the "backing_transaction_group_id" field. +func (m *CreditRealizationLineageSegmentMutation) ClearBackingTransactionGroupID() { + m.backing_transaction_group_id = nil + m.clearedFields[creditrealizationlineagesegment.FieldBackingTransactionGroupID] = struct{}{} +} + +// BackingTransactionGroupIDCleared returns if the "backing_transaction_group_id" field was cleared in this mutation. +func (m *CreditRealizationLineageSegmentMutation) BackingTransactionGroupIDCleared() bool { + _, ok := m.clearedFields[creditrealizationlineagesegment.FieldBackingTransactionGroupID] + return ok +} + +// ResetBackingTransactionGroupID resets all changes to the "backing_transaction_group_id" field. +func (m *CreditRealizationLineageSegmentMutation) ResetBackingTransactionGroupID() { + m.backing_transaction_group_id = nil + delete(m.clearedFields, creditrealizationlineagesegment.FieldBackingTransactionGroupID) +} + +// SetSourceState sets the "source_state" field. +func (m *CreditRealizationLineageSegmentMutation) SetSourceState(css creditrealization.LineageSegmentState) { + m.source_state = &css +} + +// SourceState returns the value of the "source_state" field in the mutation. +func (m *CreditRealizationLineageSegmentMutation) SourceState() (r creditrealization.LineageSegmentState, exists bool) { + v := m.source_state + if v == nil { + return + } + return *v, true +} + +// OldSourceState returns the old "source_state" field's value of the CreditRealizationLineageSegment entity. +// If the CreditRealizationLineageSegment 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 *CreditRealizationLineageSegmentMutation) OldSourceState(ctx context.Context) (v *creditrealization.LineageSegmentState, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSourceState is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSourceState requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSourceState: %w", err) + } + return oldValue.SourceState, nil +} + +// ClearSourceState clears the value of the "source_state" field. +func (m *CreditRealizationLineageSegmentMutation) ClearSourceState() { + m.source_state = nil + m.clearedFields[creditrealizationlineagesegment.FieldSourceState] = struct{}{} +} + +// SourceStateCleared returns if the "source_state" field was cleared in this mutation. +func (m *CreditRealizationLineageSegmentMutation) SourceStateCleared() bool { + _, ok := m.clearedFields[creditrealizationlineagesegment.FieldSourceState] + return ok +} + +// ResetSourceState resets all changes to the "source_state" field. +func (m *CreditRealizationLineageSegmentMutation) ResetSourceState() { + m.source_state = nil + delete(m.clearedFields, creditrealizationlineagesegment.FieldSourceState) +} + +// SetSourceBackingTransactionGroupID sets the "source_backing_transaction_group_id" field. +func (m *CreditRealizationLineageSegmentMutation) SetSourceBackingTransactionGroupID(s string) { + m.source_backing_transaction_group_id = &s +} + +// SourceBackingTransactionGroupID returns the value of the "source_backing_transaction_group_id" field in the mutation. +func (m *CreditRealizationLineageSegmentMutation) SourceBackingTransactionGroupID() (r string, exists bool) { + v := m.source_backing_transaction_group_id + if v == nil { + return + } + return *v, true +} + +// OldSourceBackingTransactionGroupID returns the old "source_backing_transaction_group_id" field's value of the CreditRealizationLineageSegment entity. +// If the CreditRealizationLineageSegment 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 *CreditRealizationLineageSegmentMutation) OldSourceBackingTransactionGroupID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSourceBackingTransactionGroupID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSourceBackingTransactionGroupID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSourceBackingTransactionGroupID: %w", err) + } + return oldValue.SourceBackingTransactionGroupID, nil +} + +// ClearSourceBackingTransactionGroupID clears the value of the "source_backing_transaction_group_id" field. +func (m *CreditRealizationLineageSegmentMutation) ClearSourceBackingTransactionGroupID() { + m.source_backing_transaction_group_id = nil + m.clearedFields[creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID] = struct{}{} +} + +// SourceBackingTransactionGroupIDCleared returns if the "source_backing_transaction_group_id" field was cleared in this mutation. +func (m *CreditRealizationLineageSegmentMutation) SourceBackingTransactionGroupIDCleared() bool { + _, ok := m.clearedFields[creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID] + return ok +} + +// ResetSourceBackingTransactionGroupID resets all changes to the "source_backing_transaction_group_id" field. +func (m *CreditRealizationLineageSegmentMutation) ResetSourceBackingTransactionGroupID() { + m.source_backing_transaction_group_id = nil + delete(m.clearedFields, creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID) +} + +// SetClosedAt sets the "closed_at" field. +func (m *CreditRealizationLineageSegmentMutation) SetClosedAt(t time.Time) { + m.closed_at = &t +} + +// ClosedAt returns the value of the "closed_at" field in the mutation. +func (m *CreditRealizationLineageSegmentMutation) ClosedAt() (r time.Time, exists bool) { + v := m.closed_at + if v == nil { + return + } + return *v, true +} + +// OldClosedAt returns the old "closed_at" field's value of the CreditRealizationLineageSegment entity. +// If the CreditRealizationLineageSegment 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 *CreditRealizationLineageSegmentMutation) OldClosedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldClosedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldClosedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldClosedAt: %w", err) + } + return oldValue.ClosedAt, nil +} + +// ClearClosedAt clears the value of the "closed_at" field. +func (m *CreditRealizationLineageSegmentMutation) ClearClosedAt() { + m.closed_at = nil + m.clearedFields[creditrealizationlineagesegment.FieldClosedAt] = struct{}{} +} + +// ClosedAtCleared returns if the "closed_at" field was cleared in this mutation. +func (m *CreditRealizationLineageSegmentMutation) ClosedAtCleared() bool { + _, ok := m.clearedFields[creditrealizationlineagesegment.FieldClosedAt] + return ok +} + +// ResetClosedAt resets all changes to the "closed_at" field. +func (m *CreditRealizationLineageSegmentMutation) ResetClosedAt() { + m.closed_at = nil + delete(m.clearedFields, creditrealizationlineagesegment.FieldClosedAt) +} + +// SetCreatedAt sets the "created_at" field. +func (m *CreditRealizationLineageSegmentMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *CreditRealizationLineageSegmentMutation) 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 CreditRealizationLineageSegment entity. +// If the CreditRealizationLineageSegment 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 *CreditRealizationLineageSegmentMutation) 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 *CreditRealizationLineageSegmentMutation) ResetCreatedAt() { + m.created_at = nil +} + +// ClearLineage clears the "lineage" edge to the CreditRealizationLineage entity. +func (m *CreditRealizationLineageSegmentMutation) ClearLineage() { + m.clearedlineage = true + m.clearedFields[creditrealizationlineagesegment.FieldLineageID] = struct{}{} +} + +// LineageCleared reports if the "lineage" edge to the CreditRealizationLineage entity was cleared. +func (m *CreditRealizationLineageSegmentMutation) LineageCleared() bool { + return m.clearedlineage +} + +// LineageIDs returns the "lineage" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// LineageID instead. It exists only for internal usage by the builders. +func (m *CreditRealizationLineageSegmentMutation) LineageIDs() (ids []string) { + if id := m.lineage; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetLineage resets all changes to the "lineage" edge. +func (m *CreditRealizationLineageSegmentMutation) ResetLineage() { + m.lineage = nil + m.clearedlineage = false +} + +// Where appends a list predicates to the CreditRealizationLineageSegmentMutation builder. +func (m *CreditRealizationLineageSegmentMutation) Where(ps ...predicate.CreditRealizationLineageSegment) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the CreditRealizationLineageSegmentMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *CreditRealizationLineageSegmentMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.CreditRealizationLineageSegment, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *CreditRealizationLineageSegmentMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *CreditRealizationLineageSegmentMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (CreditRealizationLineageSegment). +func (m *CreditRealizationLineageSegmentMutation) 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 *CreditRealizationLineageSegmentMutation) Fields() []string { + fields := make([]string, 0, 8) + if m.lineage != nil { + fields = append(fields, creditrealizationlineagesegment.FieldLineageID) + } + if m.amount != nil { + fields = append(fields, creditrealizationlineagesegment.FieldAmount) + } + if m.state != nil { + fields = append(fields, creditrealizationlineagesegment.FieldState) + } + if m.backing_transaction_group_id != nil { + fields = append(fields, creditrealizationlineagesegment.FieldBackingTransactionGroupID) + } + if m.source_state != nil { + fields = append(fields, creditrealizationlineagesegment.FieldSourceState) + } + if m.source_backing_transaction_group_id != nil { + fields = append(fields, creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID) + } + if m.closed_at != nil { + fields = append(fields, creditrealizationlineagesegment.FieldClosedAt) + } + if m.created_at != nil { + fields = append(fields, creditrealizationlineagesegment.FieldCreatedAt) + } + 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 *CreditRealizationLineageSegmentMutation) Field(name string) (ent.Value, bool) { + switch name { + case creditrealizationlineagesegment.FieldLineageID: + return m.LineageID() + case creditrealizationlineagesegment.FieldAmount: + return m.Amount() + case creditrealizationlineagesegment.FieldState: + return m.State() + case creditrealizationlineagesegment.FieldBackingTransactionGroupID: + return m.BackingTransactionGroupID() + case creditrealizationlineagesegment.FieldSourceState: + return m.SourceState() + case creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID: + return m.SourceBackingTransactionGroupID() + case creditrealizationlineagesegment.FieldClosedAt: + return m.ClosedAt() + case creditrealizationlineagesegment.FieldCreatedAt: + return m.CreatedAt() + } + 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 *CreditRealizationLineageSegmentMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case creditrealizationlineagesegment.FieldLineageID: + return m.OldLineageID(ctx) + case creditrealizationlineagesegment.FieldAmount: + return m.OldAmount(ctx) + case creditrealizationlineagesegment.FieldState: + return m.OldState(ctx) + case creditrealizationlineagesegment.FieldBackingTransactionGroupID: + return m.OldBackingTransactionGroupID(ctx) + case creditrealizationlineagesegment.FieldSourceState: + return m.OldSourceState(ctx) + case creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID: + return m.OldSourceBackingTransactionGroupID(ctx) + case creditrealizationlineagesegment.FieldClosedAt: + return m.OldClosedAt(ctx) + case creditrealizationlineagesegment.FieldCreatedAt: + return m.OldCreatedAt(ctx) + } + return nil, fmt.Errorf("unknown CreditRealizationLineageSegment 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 *CreditRealizationLineageSegmentMutation) SetField(name string, value ent.Value) error { + switch name { + case creditrealizationlineagesegment.FieldLineageID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLineageID(v) + return nil + case creditrealizationlineagesegment.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 creditrealizationlineagesegment.FieldState: + v, ok := value.(creditrealization.LineageSegmentState) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetState(v) + return nil + case creditrealizationlineagesegment.FieldBackingTransactionGroupID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBackingTransactionGroupID(v) + return nil + case creditrealizationlineagesegment.FieldSourceState: + v, ok := value.(creditrealization.LineageSegmentState) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSourceState(v) + return nil + case creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSourceBackingTransactionGroupID(v) + return nil + case creditrealizationlineagesegment.FieldClosedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetClosedAt(v) + return nil + case creditrealizationlineagesegment.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + } + return fmt.Errorf("unknown CreditRealizationLineageSegment field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *CreditRealizationLineageSegmentMutation) 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 *CreditRealizationLineageSegmentMutation) 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 *CreditRealizationLineageSegmentMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown CreditRealizationLineageSegment numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *CreditRealizationLineageSegmentMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(creditrealizationlineagesegment.FieldBackingTransactionGroupID) { + fields = append(fields, creditrealizationlineagesegment.FieldBackingTransactionGroupID) + } + if m.FieldCleared(creditrealizationlineagesegment.FieldSourceState) { + fields = append(fields, creditrealizationlineagesegment.FieldSourceState) + } + if m.FieldCleared(creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID) { + fields = append(fields, creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID) + } + if m.FieldCleared(creditrealizationlineagesegment.FieldClosedAt) { + fields = append(fields, creditrealizationlineagesegment.FieldClosedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *CreditRealizationLineageSegmentMutation) 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 *CreditRealizationLineageSegmentMutation) ClearField(name string) error { + switch name { + case creditrealizationlineagesegment.FieldBackingTransactionGroupID: + m.ClearBackingTransactionGroupID() + return nil + case creditrealizationlineagesegment.FieldSourceState: + m.ClearSourceState() + return nil + case creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID: + m.ClearSourceBackingTransactionGroupID() + return nil + case creditrealizationlineagesegment.FieldClosedAt: + m.ClearClosedAt() + return nil + } + return fmt.Errorf("unknown CreditRealizationLineageSegment 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 *CreditRealizationLineageSegmentMutation) ResetField(name string) error { + switch name { + case creditrealizationlineagesegment.FieldLineageID: + m.ResetLineageID() + return nil + case creditrealizationlineagesegment.FieldAmount: + m.ResetAmount() + return nil + case creditrealizationlineagesegment.FieldState: + m.ResetState() + return nil + case creditrealizationlineagesegment.FieldBackingTransactionGroupID: + m.ResetBackingTransactionGroupID() + return nil + case creditrealizationlineagesegment.FieldSourceState: + m.ResetSourceState() + return nil + case creditrealizationlineagesegment.FieldSourceBackingTransactionGroupID: + m.ResetSourceBackingTransactionGroupID() + return nil + case creditrealizationlineagesegment.FieldClosedAt: + m.ResetClosedAt() + return nil + case creditrealizationlineagesegment.FieldCreatedAt: + m.ResetCreatedAt() + return nil + } + return fmt.Errorf("unknown CreditRealizationLineageSegment field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *CreditRealizationLineageSegmentMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.lineage != nil { + edges = append(edges, creditrealizationlineagesegment.EdgeLineage) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *CreditRealizationLineageSegmentMutation) AddedIDs(name string) []ent.Value { + switch name { + case creditrealizationlineagesegment.EdgeLineage: + if id := m.lineage; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *CreditRealizationLineageSegmentMutation) 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 *CreditRealizationLineageSegmentMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *CreditRealizationLineageSegmentMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedlineage { + edges = append(edges, creditrealizationlineagesegment.EdgeLineage) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *CreditRealizationLineageSegmentMutation) EdgeCleared(name string) bool { + switch name { + case creditrealizationlineagesegment.EdgeLineage: + return m.clearedlineage + } + 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 *CreditRealizationLineageSegmentMutation) ClearEdge(name string) error { + switch name { + case creditrealizationlineagesegment.EdgeLineage: + m.ClearLineage() + return nil + } + return fmt.Errorf("unknown CreditRealizationLineageSegment 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 *CreditRealizationLineageSegmentMutation) ResetEdge(name string) error { + switch name { + case creditrealizationlineagesegment.EdgeLineage: + m.ResetLineage() + return nil + } + return fmt.Errorf("unknown CreditRealizationLineageSegment edge %s", name) +} + +// CurrencyCostBasisMutation represents an operation that mutates the CurrencyCostBasis nodes in the graph. +type CurrencyCostBasisMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + fiat_code *currencyx.Code + rate *alpacadecimal.Decimal + effective_from *time.Time + effective_to *time.Time + clearedFields map[string]struct{} + currency *string + clearedcurrency bool + done bool + oldValue func(context.Context) (*CurrencyCostBasis, error) + predicates []predicate.CurrencyCostBasis +} + +var _ ent.Mutation = (*CurrencyCostBasisMutation)(nil) + +// currencycostbasisOption allows management of the mutation configuration using functional options. +type currencycostbasisOption func(*CurrencyCostBasisMutation) + +// newCurrencyCostBasisMutation creates new mutation for the CurrencyCostBasis entity. +func newCurrencyCostBasisMutation(c config, op Op, opts ...currencycostbasisOption) *CurrencyCostBasisMutation { + m := &CurrencyCostBasisMutation{ + config: c, + op: op, + typ: TypeCurrencyCostBasis, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withCurrencyCostBasisID sets the ID field of the mutation. +func withCurrencyCostBasisID(id string) currencycostbasisOption { + return func(m *CurrencyCostBasisMutation) { + var ( + err error + once sync.Once + value *CurrencyCostBasis + ) + m.oldValue = func(ctx context.Context) (*CurrencyCostBasis, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().CurrencyCostBasis.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withCurrencyCostBasis sets the old CurrencyCostBasis of the mutation. +func withCurrencyCostBasis(node *CurrencyCostBasis) currencycostbasisOption { + return func(m *CurrencyCostBasisMutation) { + m.oldValue = func(context.Context) (*CurrencyCostBasis, 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 CurrencyCostBasisMutation) 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 CurrencyCostBasisMutation) 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 CurrencyCostBasis entities. +func (m *CurrencyCostBasisMutation) 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 *CurrencyCostBasisMutation) 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 *CurrencyCostBasisMutation) 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().CurrencyCostBasis.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 *CurrencyCostBasisMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *CurrencyCostBasisMutation) 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 CurrencyCostBasis entity. +// If the CurrencyCostBasis 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 *CurrencyCostBasisMutation) 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 *CurrencyCostBasisMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *CurrencyCostBasisMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *CurrencyCostBasisMutation) 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 CurrencyCostBasis entity. +// If the CurrencyCostBasis 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 *CurrencyCostBasisMutation) 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 *CurrencyCostBasisMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *CurrencyCostBasisMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *CurrencyCostBasisMutation) 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 CurrencyCostBasis entity. +// If the CurrencyCostBasis 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 *CurrencyCostBasisMutation) 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 *CurrencyCostBasisMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *CurrencyCostBasisMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *CurrencyCostBasisMutation) 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 CurrencyCostBasis entity. +// If the CurrencyCostBasis 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 *CurrencyCostBasisMutation) 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 *CurrencyCostBasisMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[currencycostbasis.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *CurrencyCostBasisMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[currencycostbasis.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *CurrencyCostBasisMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, currencycostbasis.FieldDeletedAt) +} + +// SetCurrencyID sets the "currency_id" field. +func (m *CurrencyCostBasisMutation) SetCurrencyID(s string) { + m.currency = &s +} + +// CurrencyID returns the value of the "currency_id" field in the mutation. +func (m *CurrencyCostBasisMutation) CurrencyID() (r string, exists bool) { + v := m.currency + if v == nil { + return + } + return *v, true +} + +// OldCurrencyID returns the old "currency_id" field's value of the CurrencyCostBasis entity. +// If the CurrencyCostBasis 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 *CurrencyCostBasisMutation) OldCurrencyID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrencyID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrencyID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrencyID: %w", err) + } + return oldValue.CurrencyID, nil +} + +// ResetCurrencyID resets all changes to the "currency_id" field. +func (m *CurrencyCostBasisMutation) ResetCurrencyID() { + m.currency = nil +} + +// SetFiatCode sets the "fiat_code" field. +func (m *CurrencyCostBasisMutation) SetFiatCode(c currencyx.Code) { + m.fiat_code = &c +} + +// FiatCode returns the value of the "fiat_code" field in the mutation. +func (m *CurrencyCostBasisMutation) FiatCode() (r currencyx.Code, exists bool) { + v := m.fiat_code + if v == nil { + return + } + return *v, true +} + +// OldFiatCode returns the old "fiat_code" field's value of the CurrencyCostBasis entity. +// If the CurrencyCostBasis 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 *CurrencyCostBasisMutation) OldFiatCode(ctx context.Context) (v currencyx.Code, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFiatCode is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFiatCode requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFiatCode: %w", err) + } + return oldValue.FiatCode, nil +} + +// ResetFiatCode resets all changes to the "fiat_code" field. +func (m *CurrencyCostBasisMutation) ResetFiatCode() { + m.fiat_code = nil +} + +// SetRate sets the "rate" field. +func (m *CurrencyCostBasisMutation) SetRate(a alpacadecimal.Decimal) { + m.rate = &a +} + +// Rate returns the value of the "rate" field in the mutation. +func (m *CurrencyCostBasisMutation) Rate() (r alpacadecimal.Decimal, exists bool) { + v := m.rate + if v == nil { + return + } + return *v, true +} + +// OldRate returns the old "rate" field's value of the CurrencyCostBasis entity. +// If the CurrencyCostBasis 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 *CurrencyCostBasisMutation) OldRate(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRate is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRate requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRate: %w", err) + } + return oldValue.Rate, nil +} + +// ResetRate resets all changes to the "rate" field. +func (m *CurrencyCostBasisMutation) ResetRate() { + m.rate = nil +} + +// SetEffectiveFrom sets the "effective_from" field. +func (m *CurrencyCostBasisMutation) SetEffectiveFrom(t time.Time) { + m.effective_from = &t +} + +// EffectiveFrom returns the value of the "effective_from" field in the mutation. +func (m *CurrencyCostBasisMutation) EffectiveFrom() (r time.Time, exists bool) { + v := m.effective_from + if v == nil { + return + } + return *v, true +} + +// OldEffectiveFrom returns the old "effective_from" field's value of the CurrencyCostBasis entity. +// If the CurrencyCostBasis 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 *CurrencyCostBasisMutation) OldEffectiveFrom(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEffectiveFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEffectiveFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEffectiveFrom: %w", err) + } + return oldValue.EffectiveFrom, nil +} + +// ResetEffectiveFrom resets all changes to the "effective_from" field. +func (m *CurrencyCostBasisMutation) ResetEffectiveFrom() { + m.effective_from = nil +} + +// SetEffectiveTo sets the "effective_to" field. +func (m *CurrencyCostBasisMutation) SetEffectiveTo(t time.Time) { + m.effective_to = &t +} + +// EffectiveTo returns the value of the "effective_to" field in the mutation. +func (m *CurrencyCostBasisMutation) EffectiveTo() (r time.Time, exists bool) { + v := m.effective_to + if v == nil { + return + } + return *v, true +} + +// OldEffectiveTo returns the old "effective_to" field's value of the CurrencyCostBasis entity. +// If the CurrencyCostBasis 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 *CurrencyCostBasisMutation) OldEffectiveTo(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEffectiveTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEffectiveTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEffectiveTo: %w", err) + } + return oldValue.EffectiveTo, nil +} + +// ClearEffectiveTo clears the value of the "effective_to" field. +func (m *CurrencyCostBasisMutation) ClearEffectiveTo() { + m.effective_to = nil + m.clearedFields[currencycostbasis.FieldEffectiveTo] = struct{}{} +} + +// EffectiveToCleared returns if the "effective_to" field was cleared in this mutation. +func (m *CurrencyCostBasisMutation) EffectiveToCleared() bool { + _, ok := m.clearedFields[currencycostbasis.FieldEffectiveTo] + return ok +} + +// ResetEffectiveTo resets all changes to the "effective_to" field. +func (m *CurrencyCostBasisMutation) ResetEffectiveTo() { + m.effective_to = nil + delete(m.clearedFields, currencycostbasis.FieldEffectiveTo) +} + +// ClearCurrency clears the "currency" edge to the CustomCurrency entity. +func (m *CurrencyCostBasisMutation) ClearCurrency() { + m.clearedcurrency = true + m.clearedFields[currencycostbasis.FieldCurrencyID] = struct{}{} +} + +// CurrencyCleared reports if the "currency" edge to the CustomCurrency entity was cleared. +func (m *CurrencyCostBasisMutation) CurrencyCleared() bool { + return m.clearedcurrency +} + +// CurrencyIDs returns the "currency" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CurrencyID instead. It exists only for internal usage by the builders. +func (m *CurrencyCostBasisMutation) CurrencyIDs() (ids []string) { + if id := m.currency; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCurrency resets all changes to the "currency" edge. +func (m *CurrencyCostBasisMutation) ResetCurrency() { + m.currency = nil + m.clearedcurrency = false +} + +// Where appends a list predicates to the CurrencyCostBasisMutation builder. +func (m *CurrencyCostBasisMutation) Where(ps ...predicate.CurrencyCostBasis) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the CurrencyCostBasisMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *CurrencyCostBasisMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.CurrencyCostBasis, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *CurrencyCostBasisMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *CurrencyCostBasisMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (CurrencyCostBasis). +func (m *CurrencyCostBasisMutation) 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 *CurrencyCostBasisMutation) Fields() []string { + fields := make([]string, 0, 9) + if m.namespace != nil { + fields = append(fields, currencycostbasis.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, currencycostbasis.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, currencycostbasis.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, currencycostbasis.FieldDeletedAt) + } + if m.currency != nil { + fields = append(fields, currencycostbasis.FieldCurrencyID) + } + if m.fiat_code != nil { + fields = append(fields, currencycostbasis.FieldFiatCode) + } + if m.rate != nil { + fields = append(fields, currencycostbasis.FieldRate) + } + if m.effective_from != nil { + fields = append(fields, currencycostbasis.FieldEffectiveFrom) + } + if m.effective_to != nil { + fields = append(fields, currencycostbasis.FieldEffectiveTo) + } + 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 *CurrencyCostBasisMutation) Field(name string) (ent.Value, bool) { + switch name { + case currencycostbasis.FieldNamespace: + return m.Namespace() + case currencycostbasis.FieldCreatedAt: + return m.CreatedAt() + case currencycostbasis.FieldUpdatedAt: + return m.UpdatedAt() + case currencycostbasis.FieldDeletedAt: + return m.DeletedAt() + case currencycostbasis.FieldCurrencyID: + return m.CurrencyID() + case currencycostbasis.FieldFiatCode: + return m.FiatCode() + case currencycostbasis.FieldRate: + return m.Rate() + case currencycostbasis.FieldEffectiveFrom: + return m.EffectiveFrom() + case currencycostbasis.FieldEffectiveTo: + return m.EffectiveTo() + } + 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 *CurrencyCostBasisMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case currencycostbasis.FieldNamespace: + return m.OldNamespace(ctx) + case currencycostbasis.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case currencycostbasis.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case currencycostbasis.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case currencycostbasis.FieldCurrencyID: + return m.OldCurrencyID(ctx) + case currencycostbasis.FieldFiatCode: + return m.OldFiatCode(ctx) + case currencycostbasis.FieldRate: + return m.OldRate(ctx) + case currencycostbasis.FieldEffectiveFrom: + return m.OldEffectiveFrom(ctx) + case currencycostbasis.FieldEffectiveTo: + return m.OldEffectiveTo(ctx) + } + return nil, fmt.Errorf("unknown CurrencyCostBasis 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 *CurrencyCostBasisMutation) SetField(name string, value ent.Value) error { + switch name { + case currencycostbasis.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case currencycostbasis.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 currencycostbasis.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 currencycostbasis.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 currencycostbasis.FieldCurrencyID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrencyID(v) + return nil + case currencycostbasis.FieldFiatCode: + v, ok := value.(currencyx.Code) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFiatCode(v) + return nil + case currencycostbasis.FieldRate: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRate(v) + return nil + case currencycostbasis.FieldEffectiveFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEffectiveFrom(v) + return nil + case currencycostbasis.FieldEffectiveTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEffectiveTo(v) + return nil + } + return fmt.Errorf("unknown CurrencyCostBasis field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *CurrencyCostBasisMutation) 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 *CurrencyCostBasisMutation) 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 *CurrencyCostBasisMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown CurrencyCostBasis numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *CurrencyCostBasisMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(currencycostbasis.FieldDeletedAt) { + fields = append(fields, currencycostbasis.FieldDeletedAt) + } + if m.FieldCleared(currencycostbasis.FieldEffectiveTo) { + fields = append(fields, currencycostbasis.FieldEffectiveTo) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *CurrencyCostBasisMutation) 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 *CurrencyCostBasisMutation) ClearField(name string) error { + switch name { + case currencycostbasis.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case currencycostbasis.FieldEffectiveTo: + m.ClearEffectiveTo() + return nil + } + return fmt.Errorf("unknown CurrencyCostBasis 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 *CurrencyCostBasisMutation) ResetField(name string) error { + switch name { + case currencycostbasis.FieldNamespace: + m.ResetNamespace() + return nil + case currencycostbasis.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case currencycostbasis.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case currencycostbasis.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case currencycostbasis.FieldCurrencyID: + m.ResetCurrencyID() + return nil + case currencycostbasis.FieldFiatCode: + m.ResetFiatCode() + return nil + case currencycostbasis.FieldRate: + m.ResetRate() + return nil + case currencycostbasis.FieldEffectiveFrom: + m.ResetEffectiveFrom() + return nil + case currencycostbasis.FieldEffectiveTo: + m.ResetEffectiveTo() + return nil + } + return fmt.Errorf("unknown CurrencyCostBasis field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *CurrencyCostBasisMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.currency != nil { + edges = append(edges, currencycostbasis.EdgeCurrency) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *CurrencyCostBasisMutation) AddedIDs(name string) []ent.Value { + switch name { + case currencycostbasis.EdgeCurrency: + if id := m.currency; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *CurrencyCostBasisMutation) 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 *CurrencyCostBasisMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *CurrencyCostBasisMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedcurrency { + edges = append(edges, currencycostbasis.EdgeCurrency) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *CurrencyCostBasisMutation) EdgeCleared(name string) bool { + switch name { + case currencycostbasis.EdgeCurrency: + return m.clearedcurrency + } + 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 *CurrencyCostBasisMutation) ClearEdge(name string) error { + switch name { + case currencycostbasis.EdgeCurrency: + m.ClearCurrency() + return nil + } + return fmt.Errorf("unknown CurrencyCostBasis 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 *CurrencyCostBasisMutation) ResetEdge(name string) error { + switch name { + case currencycostbasis.EdgeCurrency: + m.ResetCurrency() + return nil + } + return fmt.Errorf("unknown CurrencyCostBasis edge %s", name) +} + +// CustomCurrencyMutation represents an operation that mutates the CustomCurrency nodes in the graph. +type CustomCurrencyMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + code *string + name *string + symbol *string + clearedFields map[string]struct{} + cost_basis_history map[string]struct{} + removedcost_basis_history map[string]struct{} + clearedcost_basis_history bool + done bool + oldValue func(context.Context) (*CustomCurrency, error) + predicates []predicate.CustomCurrency +} + +var _ ent.Mutation = (*CustomCurrencyMutation)(nil) + +// customcurrencyOption allows management of the mutation configuration using functional options. +type customcurrencyOption func(*CustomCurrencyMutation) + +// newCustomCurrencyMutation creates new mutation for the CustomCurrency entity. +func newCustomCurrencyMutation(c config, op Op, opts ...customcurrencyOption) *CustomCurrencyMutation { + m := &CustomCurrencyMutation{ + config: c, + op: op, + typ: TypeCustomCurrency, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withCustomCurrencyID sets the ID field of the mutation. +func withCustomCurrencyID(id string) customcurrencyOption { + return func(m *CustomCurrencyMutation) { + var ( + err error + once sync.Once + value *CustomCurrency + ) + m.oldValue = func(ctx context.Context) (*CustomCurrency, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().CustomCurrency.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withCustomCurrency sets the old CustomCurrency of the mutation. +func withCustomCurrency(node *CustomCurrency) customcurrencyOption { + return func(m *CustomCurrencyMutation) { + m.oldValue = func(context.Context) (*CustomCurrency, 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 CustomCurrencyMutation) 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 CustomCurrencyMutation) 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 CustomCurrency entities. +func (m *CustomCurrencyMutation) 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 *CustomCurrencyMutation) 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 *CustomCurrencyMutation) 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().CustomCurrency.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 *CustomCurrencyMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *CustomCurrencyMutation) 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 CustomCurrency entity. +// If the CustomCurrency 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 *CustomCurrencyMutation) 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 *CustomCurrencyMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *CustomCurrencyMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *CustomCurrencyMutation) 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 CustomCurrency entity. +// If the CustomCurrency 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 *CustomCurrencyMutation) 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 *CustomCurrencyMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *CustomCurrencyMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *CustomCurrencyMutation) 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 CustomCurrency entity. +// If the CustomCurrency 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 *CustomCurrencyMutation) 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 *CustomCurrencyMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *CustomCurrencyMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *CustomCurrencyMutation) 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 CustomCurrency entity. +// If the CustomCurrency 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 *CustomCurrencyMutation) 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 *CustomCurrencyMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[customcurrency.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *CustomCurrencyMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[customcurrency.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *CustomCurrencyMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, customcurrency.FieldDeletedAt) +} + +// SetCode sets the "code" field. +func (m *CustomCurrencyMutation) SetCode(s string) { + m.code = &s +} + +// Code returns the value of the "code" field in the mutation. +func (m *CustomCurrencyMutation) Code() (r string, exists bool) { + v := m.code + if v == nil { + return + } + return *v, true +} + +// OldCode returns the old "code" field's value of the CustomCurrency entity. +// If the CustomCurrency 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 *CustomCurrencyMutation) OldCode(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCode is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCode requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCode: %w", err) + } + return oldValue.Code, nil +} + +// ResetCode resets all changes to the "code" field. +func (m *CustomCurrencyMutation) ResetCode() { + m.code = nil +} + +// SetName sets the "name" field. +func (m *CustomCurrencyMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *CustomCurrencyMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the CustomCurrency entity. +// If the CustomCurrency 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 *CustomCurrencyMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *CustomCurrencyMutation) ResetName() { + m.name = nil +} + +// SetSymbol sets the "symbol" field. +func (m *CustomCurrencyMutation) SetSymbol(s string) { + m.symbol = &s +} + +// Symbol returns the value of the "symbol" field in the mutation. +func (m *CustomCurrencyMutation) Symbol() (r string, exists bool) { + v := m.symbol + if v == nil { + return + } + return *v, true +} + +// OldSymbol returns the old "symbol" field's value of the CustomCurrency entity. +// If the CustomCurrency 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 *CustomCurrencyMutation) OldSymbol(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSymbol is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSymbol requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSymbol: %w", err) + } + return oldValue.Symbol, nil +} + +// ResetSymbol resets all changes to the "symbol" field. +func (m *CustomCurrencyMutation) ResetSymbol() { + m.symbol = nil +} + +// AddCostBasisHistoryIDs adds the "cost_basis_history" edge to the CurrencyCostBasis entity by ids. +func (m *CustomCurrencyMutation) AddCostBasisHistoryIDs(ids ...string) { + if m.cost_basis_history == nil { + m.cost_basis_history = make(map[string]struct{}) + } + for i := range ids { + m.cost_basis_history[ids[i]] = struct{}{} + } +} + +// ClearCostBasisHistory clears the "cost_basis_history" edge to the CurrencyCostBasis entity. +func (m *CustomCurrencyMutation) ClearCostBasisHistory() { + m.clearedcost_basis_history = true +} + +// CostBasisHistoryCleared reports if the "cost_basis_history" edge to the CurrencyCostBasis entity was cleared. +func (m *CustomCurrencyMutation) CostBasisHistoryCleared() bool { + return m.clearedcost_basis_history +} + +// RemoveCostBasisHistoryIDs removes the "cost_basis_history" edge to the CurrencyCostBasis entity by IDs. +func (m *CustomCurrencyMutation) RemoveCostBasisHistoryIDs(ids ...string) { + if m.removedcost_basis_history == nil { + m.removedcost_basis_history = make(map[string]struct{}) + } + for i := range ids { + delete(m.cost_basis_history, ids[i]) + m.removedcost_basis_history[ids[i]] = struct{}{} + } +} + +// RemovedCostBasisHistory returns the removed IDs of the "cost_basis_history" edge to the CurrencyCostBasis entity. +func (m *CustomCurrencyMutation) RemovedCostBasisHistoryIDs() (ids []string) { + for id := range m.removedcost_basis_history { + ids = append(ids, id) + } + return +} + +// CostBasisHistoryIDs returns the "cost_basis_history" edge IDs in the mutation. +func (m *CustomCurrencyMutation) CostBasisHistoryIDs() (ids []string) { + for id := range m.cost_basis_history { + ids = append(ids, id) + } + return +} + +// ResetCostBasisHistory resets all changes to the "cost_basis_history" edge. +func (m *CustomCurrencyMutation) ResetCostBasisHistory() { + m.cost_basis_history = nil + m.clearedcost_basis_history = false + m.removedcost_basis_history = nil +} + +// Where appends a list predicates to the CustomCurrencyMutation builder. +func (m *CustomCurrencyMutation) Where(ps ...predicate.CustomCurrency) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the CustomCurrencyMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *CustomCurrencyMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.CustomCurrency, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *CustomCurrencyMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *CustomCurrencyMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (CustomCurrency). +func (m *CustomCurrencyMutation) 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 *CustomCurrencyMutation) Fields() []string { + fields := make([]string, 0, 7) + if m.namespace != nil { + fields = append(fields, customcurrency.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, customcurrency.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, customcurrency.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, customcurrency.FieldDeletedAt) + } + if m.code != nil { + fields = append(fields, customcurrency.FieldCode) + } + if m.name != nil { + fields = append(fields, customcurrency.FieldName) + } + if m.symbol != nil { + fields = append(fields, customcurrency.FieldSymbol) + } + 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 *CustomCurrencyMutation) Field(name string) (ent.Value, bool) { + switch name { + case customcurrency.FieldNamespace: + return m.Namespace() + case customcurrency.FieldCreatedAt: + return m.CreatedAt() + case customcurrency.FieldUpdatedAt: + return m.UpdatedAt() + case customcurrency.FieldDeletedAt: + return m.DeletedAt() + case customcurrency.FieldCode: + return m.Code() + case customcurrency.FieldName: + return m.Name() + case customcurrency.FieldSymbol: + return m.Symbol() + } + 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 *CustomCurrencyMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case customcurrency.FieldNamespace: + return m.OldNamespace(ctx) + case customcurrency.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case customcurrency.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case customcurrency.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case customcurrency.FieldCode: + return m.OldCode(ctx) + case customcurrency.FieldName: + return m.OldName(ctx) + case customcurrency.FieldSymbol: + return m.OldSymbol(ctx) + } + return nil, fmt.Errorf("unknown CustomCurrency 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 *CustomCurrencyMutation) SetField(name string, value ent.Value) error { + switch name { + case customcurrency.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case customcurrency.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 customcurrency.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 customcurrency.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 customcurrency.FieldCode: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCode(v) + return nil + case customcurrency.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case customcurrency.FieldSymbol: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSymbol(v) + return nil + } + return fmt.Errorf("unknown CustomCurrency field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *CustomCurrencyMutation) 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 *CustomCurrencyMutation) 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 *CustomCurrencyMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown CustomCurrency numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *CustomCurrencyMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(customcurrency.FieldDeletedAt) { + fields = append(fields, customcurrency.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *CustomCurrencyMutation) 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 *CustomCurrencyMutation) ClearField(name string) error { + switch name { + case customcurrency.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown CustomCurrency 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 *CustomCurrencyMutation) ResetField(name string) error { + switch name { + case customcurrency.FieldNamespace: + m.ResetNamespace() + return nil + case customcurrency.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case customcurrency.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case customcurrency.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case customcurrency.FieldCode: + m.ResetCode() + return nil + case customcurrency.FieldName: + m.ResetName() + return nil + case customcurrency.FieldSymbol: + m.ResetSymbol() + return nil + } + return fmt.Errorf("unknown CustomCurrency field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *CustomCurrencyMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.cost_basis_history != nil { + edges = append(edges, customcurrency.EdgeCostBasisHistory) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *CustomCurrencyMutation) AddedIDs(name string) []ent.Value { + switch name { + case customcurrency.EdgeCostBasisHistory: + ids := make([]ent.Value, 0, len(m.cost_basis_history)) + for id := range m.cost_basis_history { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *CustomCurrencyMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + if m.removedcost_basis_history != nil { + edges = append(edges, customcurrency.EdgeCostBasisHistory) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *CustomCurrencyMutation) RemovedIDs(name string) []ent.Value { + switch name { + case customcurrency.EdgeCostBasisHistory: + ids := make([]ent.Value, 0, len(m.removedcost_basis_history)) + for id := range m.removedcost_basis_history { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *CustomCurrencyMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedcost_basis_history { + edges = append(edges, customcurrency.EdgeCostBasisHistory) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *CustomCurrencyMutation) EdgeCleared(name string) bool { + switch name { + case customcurrency.EdgeCostBasisHistory: + return m.clearedcost_basis_history + } + 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 *CustomCurrencyMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown CustomCurrency 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 *CustomCurrencyMutation) ResetEdge(name string) error { + switch name { + case customcurrency.EdgeCostBasisHistory: + m.ResetCostBasisHistory() + return nil + } + return fmt.Errorf("unknown CustomCurrency edge %s", name) +} + +// CustomerMutation represents an operation that mutates the Customer nodes in the graph. +type CustomerMutation struct { + config + op Op + typ string + id *string + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + name *string + description *string + billing_address_country *models.CountryCode + billing_address_postal_code *string + billing_address_state *string + billing_address_city *string + billing_address_line1 *string + billing_address_line2 *string + billing_address_phone_number *string + annotations *models.Annotations + key *string + primary_email *string + currency *currencyx.Code + clearedFields map[string]struct{} + apps map[int]struct{} + removedapps map[int]struct{} + clearedapps bool + subjects map[int]struct{} + removedsubjects map[int]struct{} + clearedsubjects bool + billing_customer_override *string + clearedbilling_customer_override bool + billing_invoice map[string]struct{} + removedbilling_invoice map[string]struct{} + clearedbilling_invoice bool + subscription map[string]struct{} + removedsubscription map[string]struct{} + clearedsubscription bool + entitlements map[string]struct{} + removedentitlements map[string]struct{} + clearedentitlements bool + charges_credit_purchase map[string]struct{} + removedcharges_credit_purchase map[string]struct{} + clearedcharges_credit_purchase bool + charges_flat_fee map[string]struct{} + removedcharges_flat_fee map[string]struct{} + clearedcharges_flat_fee bool + charges_usage_based map[string]struct{} + removedcharges_usage_based map[string]struct{} + clearedcharges_usage_based bool + done bool + oldValue func(context.Context) (*Customer, error) + predicates []predicate.Customer +} + +var _ ent.Mutation = (*CustomerMutation)(nil) + +// customerOption allows management of the mutation configuration using functional options. +type customerOption func(*CustomerMutation) + +// newCustomerMutation creates new mutation for the Customer entity. +func newCustomerMutation(c config, op Op, opts ...customerOption) *CustomerMutation { + m := &CustomerMutation{ + config: c, + op: op, + typ: TypeCustomer, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withCustomerID sets the ID field of the mutation. +func withCustomerID(id string) customerOption { + return func(m *CustomerMutation) { + var ( + err error + once sync.Once + value *Customer + ) + m.oldValue = func(ctx context.Context) (*Customer, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Customer.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withCustomer sets the old Customer of the mutation. +func withCustomer(node *Customer) customerOption { + return func(m *CustomerMutation) { + m.oldValue = func(context.Context) (*Customer, 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 CustomerMutation) 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 CustomerMutation) 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 Customer entities. +func (m *CustomerMutation) 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 *CustomerMutation) 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 *CustomerMutation) 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().Customer.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 *CustomerMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *CustomerMutation) 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 Customer entity. +// If the Customer 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 *CustomerMutation) 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 *CustomerMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *CustomerMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *CustomerMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the Customer entity. +// If the Customer 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 *CustomerMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *CustomerMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[customer.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *CustomerMutation) MetadataCleared() bool { + _, ok := m.clearedFields[customer.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *CustomerMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, customer.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *CustomerMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *CustomerMutation) 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 Customer entity. +// If the Customer 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 *CustomerMutation) 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 *CustomerMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *CustomerMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *CustomerMutation) 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 Customer entity. +// If the Customer 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 *CustomerMutation) 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 *CustomerMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *CustomerMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *CustomerMutation) 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 Customer entity. +// If the Customer 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 *CustomerMutation) 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 *CustomerMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[customer.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *CustomerMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[customer.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *CustomerMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, customer.FieldDeletedAt) +} + +// SetName sets the "name" field. +func (m *CustomerMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *CustomerMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the Customer entity. +// If the Customer 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 *CustomerMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *CustomerMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *CustomerMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *CustomerMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the Customer entity. +// If the Customer 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 *CustomerMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *CustomerMutation) ClearDescription() { + m.description = nil + m.clearedFields[customer.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *CustomerMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[customer.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *CustomerMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, customer.FieldDescription) +} + +// SetBillingAddressCountry sets the "billing_address_country" field. +func (m *CustomerMutation) SetBillingAddressCountry(mc models.CountryCode) { + m.billing_address_country = &mc +} + +// BillingAddressCountry returns the value of the "billing_address_country" field in the mutation. +func (m *CustomerMutation) BillingAddressCountry() (r models.CountryCode, exists bool) { + v := m.billing_address_country + if v == nil { + return + } + return *v, true +} + +// OldBillingAddressCountry returns the old "billing_address_country" field's value of the Customer entity. +// If the Customer 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 *CustomerMutation) OldBillingAddressCountry(ctx context.Context) (v *models.CountryCode, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingAddressCountry is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingAddressCountry requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingAddressCountry: %w", err) + } + return oldValue.BillingAddressCountry, nil +} + +// ClearBillingAddressCountry clears the value of the "billing_address_country" field. +func (m *CustomerMutation) ClearBillingAddressCountry() { + m.billing_address_country = nil + m.clearedFields[customer.FieldBillingAddressCountry] = struct{}{} +} + +// BillingAddressCountryCleared returns if the "billing_address_country" field was cleared in this mutation. +func (m *CustomerMutation) BillingAddressCountryCleared() bool { + _, ok := m.clearedFields[customer.FieldBillingAddressCountry] + return ok +} + +// ResetBillingAddressCountry resets all changes to the "billing_address_country" field. +func (m *CustomerMutation) ResetBillingAddressCountry() { + m.billing_address_country = nil + delete(m.clearedFields, customer.FieldBillingAddressCountry) +} + +// SetBillingAddressPostalCode sets the "billing_address_postal_code" field. +func (m *CustomerMutation) SetBillingAddressPostalCode(s string) { + m.billing_address_postal_code = &s +} + +// BillingAddressPostalCode returns the value of the "billing_address_postal_code" field in the mutation. +func (m *CustomerMutation) BillingAddressPostalCode() (r string, exists bool) { + v := m.billing_address_postal_code + if v == nil { + return + } + return *v, true +} + +// OldBillingAddressPostalCode returns the old "billing_address_postal_code" field's value of the Customer entity. +// If the Customer 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 *CustomerMutation) OldBillingAddressPostalCode(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingAddressPostalCode is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingAddressPostalCode requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingAddressPostalCode: %w", err) + } + return oldValue.BillingAddressPostalCode, nil +} + +// ClearBillingAddressPostalCode clears the value of the "billing_address_postal_code" field. +func (m *CustomerMutation) ClearBillingAddressPostalCode() { + m.billing_address_postal_code = nil + m.clearedFields[customer.FieldBillingAddressPostalCode] = struct{}{} +} + +// BillingAddressPostalCodeCleared returns if the "billing_address_postal_code" field was cleared in this mutation. +func (m *CustomerMutation) BillingAddressPostalCodeCleared() bool { + _, ok := m.clearedFields[customer.FieldBillingAddressPostalCode] + return ok +} + +// ResetBillingAddressPostalCode resets all changes to the "billing_address_postal_code" field. +func (m *CustomerMutation) ResetBillingAddressPostalCode() { + m.billing_address_postal_code = nil + delete(m.clearedFields, customer.FieldBillingAddressPostalCode) +} + +// SetBillingAddressState sets the "billing_address_state" field. +func (m *CustomerMutation) SetBillingAddressState(s string) { + m.billing_address_state = &s +} + +// BillingAddressState returns the value of the "billing_address_state" field in the mutation. +func (m *CustomerMutation) BillingAddressState() (r string, exists bool) { + v := m.billing_address_state + if v == nil { + return + } + return *v, true +} + +// OldBillingAddressState returns the old "billing_address_state" field's value of the Customer entity. +// If the Customer 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 *CustomerMutation) OldBillingAddressState(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingAddressState is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingAddressState requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingAddressState: %w", err) + } + return oldValue.BillingAddressState, nil +} + +// ClearBillingAddressState clears the value of the "billing_address_state" field. +func (m *CustomerMutation) ClearBillingAddressState() { + m.billing_address_state = nil + m.clearedFields[customer.FieldBillingAddressState] = struct{}{} +} + +// BillingAddressStateCleared returns if the "billing_address_state" field was cleared in this mutation. +func (m *CustomerMutation) BillingAddressStateCleared() bool { + _, ok := m.clearedFields[customer.FieldBillingAddressState] + return ok +} + +// ResetBillingAddressState resets all changes to the "billing_address_state" field. +func (m *CustomerMutation) ResetBillingAddressState() { + m.billing_address_state = nil + delete(m.clearedFields, customer.FieldBillingAddressState) +} + +// SetBillingAddressCity sets the "billing_address_city" field. +func (m *CustomerMutation) SetBillingAddressCity(s string) { + m.billing_address_city = &s +} + +// BillingAddressCity returns the value of the "billing_address_city" field in the mutation. +func (m *CustomerMutation) BillingAddressCity() (r string, exists bool) { + v := m.billing_address_city + if v == nil { + return + } + return *v, true +} + +// OldBillingAddressCity returns the old "billing_address_city" field's value of the Customer entity. +// If the Customer 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 *CustomerMutation) OldBillingAddressCity(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingAddressCity is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingAddressCity requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingAddressCity: %w", err) + } + return oldValue.BillingAddressCity, nil +} + +// ClearBillingAddressCity clears the value of the "billing_address_city" field. +func (m *CustomerMutation) ClearBillingAddressCity() { + m.billing_address_city = nil + m.clearedFields[customer.FieldBillingAddressCity] = struct{}{} +} + +// BillingAddressCityCleared returns if the "billing_address_city" field was cleared in this mutation. +func (m *CustomerMutation) BillingAddressCityCleared() bool { + _, ok := m.clearedFields[customer.FieldBillingAddressCity] + return ok +} + +// ResetBillingAddressCity resets all changes to the "billing_address_city" field. +func (m *CustomerMutation) ResetBillingAddressCity() { + m.billing_address_city = nil + delete(m.clearedFields, customer.FieldBillingAddressCity) +} + +// SetBillingAddressLine1 sets the "billing_address_line1" field. +func (m *CustomerMutation) SetBillingAddressLine1(s string) { + m.billing_address_line1 = &s +} + +// BillingAddressLine1 returns the value of the "billing_address_line1" field in the mutation. +func (m *CustomerMutation) BillingAddressLine1() (r string, exists bool) { + v := m.billing_address_line1 + if v == nil { + return + } + return *v, true +} + +// OldBillingAddressLine1 returns the old "billing_address_line1" field's value of the Customer entity. +// If the Customer 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 *CustomerMutation) OldBillingAddressLine1(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingAddressLine1 is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingAddressLine1 requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingAddressLine1: %w", err) + } + return oldValue.BillingAddressLine1, nil +} + +// ClearBillingAddressLine1 clears the value of the "billing_address_line1" field. +func (m *CustomerMutation) ClearBillingAddressLine1() { + m.billing_address_line1 = nil + m.clearedFields[customer.FieldBillingAddressLine1] = struct{}{} +} + +// BillingAddressLine1Cleared returns if the "billing_address_line1" field was cleared in this mutation. +func (m *CustomerMutation) BillingAddressLine1Cleared() bool { + _, ok := m.clearedFields[customer.FieldBillingAddressLine1] + return ok +} + +// ResetBillingAddressLine1 resets all changes to the "billing_address_line1" field. +func (m *CustomerMutation) ResetBillingAddressLine1() { + m.billing_address_line1 = nil + delete(m.clearedFields, customer.FieldBillingAddressLine1) +} + +// SetBillingAddressLine2 sets the "billing_address_line2" field. +func (m *CustomerMutation) SetBillingAddressLine2(s string) { + m.billing_address_line2 = &s +} + +// BillingAddressLine2 returns the value of the "billing_address_line2" field in the mutation. +func (m *CustomerMutation) BillingAddressLine2() (r string, exists bool) { + v := m.billing_address_line2 + if v == nil { + return + } + return *v, true +} + +// OldBillingAddressLine2 returns the old "billing_address_line2" field's value of the Customer entity. +// If the Customer 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 *CustomerMutation) OldBillingAddressLine2(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingAddressLine2 is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingAddressLine2 requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingAddressLine2: %w", err) + } + return oldValue.BillingAddressLine2, nil +} + +// ClearBillingAddressLine2 clears the value of the "billing_address_line2" field. +func (m *CustomerMutation) ClearBillingAddressLine2() { + m.billing_address_line2 = nil + m.clearedFields[customer.FieldBillingAddressLine2] = struct{}{} +} + +// BillingAddressLine2Cleared returns if the "billing_address_line2" field was cleared in this mutation. +func (m *CustomerMutation) BillingAddressLine2Cleared() bool { + _, ok := m.clearedFields[customer.FieldBillingAddressLine2] + return ok +} + +// ResetBillingAddressLine2 resets all changes to the "billing_address_line2" field. +func (m *CustomerMutation) ResetBillingAddressLine2() { + m.billing_address_line2 = nil + delete(m.clearedFields, customer.FieldBillingAddressLine2) +} + +// SetBillingAddressPhoneNumber sets the "billing_address_phone_number" field. +func (m *CustomerMutation) SetBillingAddressPhoneNumber(s string) { + m.billing_address_phone_number = &s +} + +// BillingAddressPhoneNumber returns the value of the "billing_address_phone_number" field in the mutation. +func (m *CustomerMutation) BillingAddressPhoneNumber() (r string, exists bool) { + v := m.billing_address_phone_number + if v == nil { + return + } + return *v, true +} + +// OldBillingAddressPhoneNumber returns the old "billing_address_phone_number" field's value of the Customer entity. +// If the Customer 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 *CustomerMutation) OldBillingAddressPhoneNumber(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingAddressPhoneNumber is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingAddressPhoneNumber requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingAddressPhoneNumber: %w", err) + } + return oldValue.BillingAddressPhoneNumber, nil +} + +// ClearBillingAddressPhoneNumber clears the value of the "billing_address_phone_number" field. +func (m *CustomerMutation) ClearBillingAddressPhoneNumber() { + m.billing_address_phone_number = nil + m.clearedFields[customer.FieldBillingAddressPhoneNumber] = struct{}{} +} + +// BillingAddressPhoneNumberCleared returns if the "billing_address_phone_number" field was cleared in this mutation. +func (m *CustomerMutation) BillingAddressPhoneNumberCleared() bool { + _, ok := m.clearedFields[customer.FieldBillingAddressPhoneNumber] + return ok +} + +// ResetBillingAddressPhoneNumber resets all changes to the "billing_address_phone_number" field. +func (m *CustomerMutation) ResetBillingAddressPhoneNumber() { + m.billing_address_phone_number = nil + delete(m.clearedFields, customer.FieldBillingAddressPhoneNumber) +} + +// SetAnnotations sets the "annotations" field. +func (m *CustomerMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *CustomerMutation) 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 Customer entity. +// If the Customer 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 *CustomerMutation) 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 *CustomerMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[customer.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *CustomerMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[customer.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *CustomerMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, customer.FieldAnnotations) +} + +// SetKey sets the "key" field. +func (m *CustomerMutation) SetKey(s string) { + m.key = &s +} + +// Key returns the value of the "key" field in the mutation. +func (m *CustomerMutation) Key() (r string, exists bool) { + v := m.key + if v == nil { + return + } + return *v, true +} + +// OldKey returns the old "key" field's value of the Customer entity. +// If the Customer 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 *CustomerMutation) OldKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldKey: %w", err) + } + return oldValue.Key, nil +} + +// ClearKey clears the value of the "key" field. +func (m *CustomerMutation) ClearKey() { + m.key = nil + m.clearedFields[customer.FieldKey] = struct{}{} +} + +// KeyCleared returns if the "key" field was cleared in this mutation. +func (m *CustomerMutation) KeyCleared() bool { + _, ok := m.clearedFields[customer.FieldKey] + return ok +} + +// ResetKey resets all changes to the "key" field. +func (m *CustomerMutation) ResetKey() { + m.key = nil + delete(m.clearedFields, customer.FieldKey) +} + +// SetPrimaryEmail sets the "primary_email" field. +func (m *CustomerMutation) SetPrimaryEmail(s string) { + m.primary_email = &s +} + +// PrimaryEmail returns the value of the "primary_email" field in the mutation. +func (m *CustomerMutation) PrimaryEmail() (r string, exists bool) { + v := m.primary_email + if v == nil { + return + } + return *v, true +} + +// OldPrimaryEmail returns the old "primary_email" field's value of the Customer entity. +// If the Customer 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 *CustomerMutation) OldPrimaryEmail(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPrimaryEmail is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPrimaryEmail requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPrimaryEmail: %w", err) + } + return oldValue.PrimaryEmail, nil +} + +// ClearPrimaryEmail clears the value of the "primary_email" field. +func (m *CustomerMutation) ClearPrimaryEmail() { + m.primary_email = nil + m.clearedFields[customer.FieldPrimaryEmail] = struct{}{} +} + +// PrimaryEmailCleared returns if the "primary_email" field was cleared in this mutation. +func (m *CustomerMutation) PrimaryEmailCleared() bool { + _, ok := m.clearedFields[customer.FieldPrimaryEmail] + return ok +} + +// ResetPrimaryEmail resets all changes to the "primary_email" field. +func (m *CustomerMutation) ResetPrimaryEmail() { + m.primary_email = nil + delete(m.clearedFields, customer.FieldPrimaryEmail) +} + +// SetCurrency sets the "currency" field. +func (m *CustomerMutation) SetCurrency(c currencyx.Code) { + m.currency = &c +} + +// Currency returns the value of the "currency" field in the mutation. +func (m *CustomerMutation) Currency() (r currencyx.Code, exists bool) { + v := m.currency + if v == nil { + return + } + return *v, true +} + +// OldCurrency returns the old "currency" field's value of the Customer entity. +// If the Customer 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 *CustomerMutation) OldCurrency(ctx context.Context) (v *currencyx.Code, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrency is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrency requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrency: %w", err) + } + return oldValue.Currency, nil +} + +// ClearCurrency clears the value of the "currency" field. +func (m *CustomerMutation) ClearCurrency() { + m.currency = nil + m.clearedFields[customer.FieldCurrency] = struct{}{} +} + +// CurrencyCleared returns if the "currency" field was cleared in this mutation. +func (m *CustomerMutation) CurrencyCleared() bool { + _, ok := m.clearedFields[customer.FieldCurrency] + return ok +} + +// ResetCurrency resets all changes to the "currency" field. +func (m *CustomerMutation) ResetCurrency() { + m.currency = nil + delete(m.clearedFields, customer.FieldCurrency) +} + +// AddAppIDs adds the "apps" edge to the AppCustomer entity by ids. +func (m *CustomerMutation) AddAppIDs(ids ...int) { + if m.apps == nil { + m.apps = make(map[int]struct{}) + } + for i := range ids { + m.apps[ids[i]] = struct{}{} + } +} + +// ClearApps clears the "apps" edge to the AppCustomer entity. +func (m *CustomerMutation) ClearApps() { + m.clearedapps = true +} + +// AppsCleared reports if the "apps" edge to the AppCustomer entity was cleared. +func (m *CustomerMutation) AppsCleared() bool { + return m.clearedapps +} + +// RemoveAppIDs removes the "apps" edge to the AppCustomer entity by IDs. +func (m *CustomerMutation) RemoveAppIDs(ids ...int) { + if m.removedapps == nil { + m.removedapps = make(map[int]struct{}) + } + for i := range ids { + delete(m.apps, ids[i]) + m.removedapps[ids[i]] = struct{}{} + } +} + +// RemovedApps returns the removed IDs of the "apps" edge to the AppCustomer entity. +func (m *CustomerMutation) RemovedAppsIDs() (ids []int) { + for id := range m.removedapps { + ids = append(ids, id) + } + return +} + +// AppsIDs returns the "apps" edge IDs in the mutation. +func (m *CustomerMutation) AppsIDs() (ids []int) { + for id := range m.apps { + ids = append(ids, id) + } + return +} + +// ResetApps resets all changes to the "apps" edge. +func (m *CustomerMutation) ResetApps() { + m.apps = nil + m.clearedapps = false + m.removedapps = nil +} + +// AddSubjectIDs adds the "subjects" edge to the CustomerSubjects entity by ids. +func (m *CustomerMutation) AddSubjectIDs(ids ...int) { + if m.subjects == nil { + m.subjects = make(map[int]struct{}) + } + for i := range ids { + m.subjects[ids[i]] = struct{}{} + } +} + +// ClearSubjects clears the "subjects" edge to the CustomerSubjects entity. +func (m *CustomerMutation) ClearSubjects() { + m.clearedsubjects = true +} + +// SubjectsCleared reports if the "subjects" edge to the CustomerSubjects entity was cleared. +func (m *CustomerMutation) SubjectsCleared() bool { + return m.clearedsubjects +} + +// RemoveSubjectIDs removes the "subjects" edge to the CustomerSubjects entity by IDs. +func (m *CustomerMutation) RemoveSubjectIDs(ids ...int) { + if m.removedsubjects == nil { + m.removedsubjects = make(map[int]struct{}) + } + for i := range ids { + delete(m.subjects, ids[i]) + m.removedsubjects[ids[i]] = struct{}{} + } +} + +// RemovedSubjects returns the removed IDs of the "subjects" edge to the CustomerSubjects entity. +func (m *CustomerMutation) RemovedSubjectsIDs() (ids []int) { + for id := range m.removedsubjects { + ids = append(ids, id) + } + return +} + +// SubjectsIDs returns the "subjects" edge IDs in the mutation. +func (m *CustomerMutation) SubjectsIDs() (ids []int) { + for id := range m.subjects { + ids = append(ids, id) + } + return +} + +// ResetSubjects resets all changes to the "subjects" edge. +func (m *CustomerMutation) ResetSubjects() { + m.subjects = nil + m.clearedsubjects = false + m.removedsubjects = nil +} + +// SetBillingCustomerOverrideID sets the "billing_customer_override" edge to the BillingCustomerOverride entity by id. +func (m *CustomerMutation) SetBillingCustomerOverrideID(id string) { + m.billing_customer_override = &id +} + +// ClearBillingCustomerOverride clears the "billing_customer_override" edge to the BillingCustomerOverride entity. +func (m *CustomerMutation) ClearBillingCustomerOverride() { + m.clearedbilling_customer_override = true +} + +// BillingCustomerOverrideCleared reports if the "billing_customer_override" edge to the BillingCustomerOverride entity was cleared. +func (m *CustomerMutation) BillingCustomerOverrideCleared() bool { + return m.clearedbilling_customer_override +} + +// BillingCustomerOverrideID returns the "billing_customer_override" edge ID in the mutation. +func (m *CustomerMutation) BillingCustomerOverrideID() (id string, exists bool) { + if m.billing_customer_override != nil { + return *m.billing_customer_override, true + } + return +} + +// BillingCustomerOverrideIDs returns the "billing_customer_override" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BillingCustomerOverrideID instead. It exists only for internal usage by the builders. +func (m *CustomerMutation) BillingCustomerOverrideIDs() (ids []string) { + if id := m.billing_customer_override; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBillingCustomerOverride resets all changes to the "billing_customer_override" edge. +func (m *CustomerMutation) ResetBillingCustomerOverride() { + m.billing_customer_override = nil + m.clearedbilling_customer_override = false +} + +// AddBillingInvoiceIDs adds the "billing_invoice" edge to the BillingInvoice entity by ids. +func (m *CustomerMutation) AddBillingInvoiceIDs(ids ...string) { + if m.billing_invoice == nil { + m.billing_invoice = make(map[string]struct{}) + } + for i := range ids { + m.billing_invoice[ids[i]] = struct{}{} + } +} + +// ClearBillingInvoice clears the "billing_invoice" edge to the BillingInvoice entity. +func (m *CustomerMutation) ClearBillingInvoice() { + m.clearedbilling_invoice = true +} + +// BillingInvoiceCleared reports if the "billing_invoice" edge to the BillingInvoice entity was cleared. +func (m *CustomerMutation) BillingInvoiceCleared() bool { + return m.clearedbilling_invoice +} + +// RemoveBillingInvoiceIDs removes the "billing_invoice" edge to the BillingInvoice entity by IDs. +func (m *CustomerMutation) RemoveBillingInvoiceIDs(ids ...string) { + if m.removedbilling_invoice == nil { + m.removedbilling_invoice = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_invoice, ids[i]) + m.removedbilling_invoice[ids[i]] = struct{}{} + } +} + +// RemovedBillingInvoice returns the removed IDs of the "billing_invoice" edge to the BillingInvoice entity. +func (m *CustomerMutation) RemovedBillingInvoiceIDs() (ids []string) { + for id := range m.removedbilling_invoice { + ids = append(ids, id) + } + return +} + +// BillingInvoiceIDs returns the "billing_invoice" edge IDs in the mutation. +func (m *CustomerMutation) BillingInvoiceIDs() (ids []string) { + for id := range m.billing_invoice { + ids = append(ids, id) + } + return +} + +// ResetBillingInvoice resets all changes to the "billing_invoice" edge. +func (m *CustomerMutation) ResetBillingInvoice() { + m.billing_invoice = nil + m.clearedbilling_invoice = false + m.removedbilling_invoice = nil +} + +// AddSubscriptionIDs adds the "subscription" edge to the Subscription entity by ids. +func (m *CustomerMutation) AddSubscriptionIDs(ids ...string) { + if m.subscription == nil { + m.subscription = make(map[string]struct{}) + } + for i := range ids { + m.subscription[ids[i]] = struct{}{} + } +} + +// ClearSubscription clears the "subscription" edge to the Subscription entity. +func (m *CustomerMutation) ClearSubscription() { + m.clearedsubscription = true +} + +// SubscriptionCleared reports if the "subscription" edge to the Subscription entity was cleared. +func (m *CustomerMutation) SubscriptionCleared() bool { + return m.clearedsubscription +} + +// RemoveSubscriptionIDs removes the "subscription" edge to the Subscription entity by IDs. +func (m *CustomerMutation) RemoveSubscriptionIDs(ids ...string) { + if m.removedsubscription == nil { + m.removedsubscription = make(map[string]struct{}) + } + for i := range ids { + delete(m.subscription, ids[i]) + m.removedsubscription[ids[i]] = struct{}{} + } +} + +// RemovedSubscription returns the removed IDs of the "subscription" edge to the Subscription entity. +func (m *CustomerMutation) RemovedSubscriptionIDs() (ids []string) { + for id := range m.removedsubscription { + ids = append(ids, id) + } + return +} + +// SubscriptionIDs returns the "subscription" edge IDs in the mutation. +func (m *CustomerMutation) SubscriptionIDs() (ids []string) { + for id := range m.subscription { + ids = append(ids, id) + } + return +} + +// ResetSubscription resets all changes to the "subscription" edge. +func (m *CustomerMutation) ResetSubscription() { + m.subscription = nil + m.clearedsubscription = false + m.removedsubscription = nil +} + +// AddEntitlementIDs adds the "entitlements" edge to the Entitlement entity by ids. +func (m *CustomerMutation) AddEntitlementIDs(ids ...string) { + if m.entitlements == nil { + m.entitlements = make(map[string]struct{}) + } + for i := range ids { + m.entitlements[ids[i]] = struct{}{} + } +} + +// ClearEntitlements clears the "entitlements" edge to the Entitlement entity. +func (m *CustomerMutation) ClearEntitlements() { + m.clearedentitlements = true +} + +// EntitlementsCleared reports if the "entitlements" edge to the Entitlement entity was cleared. +func (m *CustomerMutation) EntitlementsCleared() bool { + return m.clearedentitlements +} + +// RemoveEntitlementIDs removes the "entitlements" edge to the Entitlement entity by IDs. +func (m *CustomerMutation) RemoveEntitlementIDs(ids ...string) { + if m.removedentitlements == nil { + m.removedentitlements = make(map[string]struct{}) + } + for i := range ids { + delete(m.entitlements, ids[i]) + m.removedentitlements[ids[i]] = struct{}{} + } +} + +// RemovedEntitlements returns the removed IDs of the "entitlements" edge to the Entitlement entity. +func (m *CustomerMutation) RemovedEntitlementsIDs() (ids []string) { + for id := range m.removedentitlements { + ids = append(ids, id) + } + return +} + +// EntitlementsIDs returns the "entitlements" edge IDs in the mutation. +func (m *CustomerMutation) EntitlementsIDs() (ids []string) { + for id := range m.entitlements { + ids = append(ids, id) + } + return +} + +// ResetEntitlements resets all changes to the "entitlements" edge. +func (m *CustomerMutation) ResetEntitlements() { + m.entitlements = nil + m.clearedentitlements = false + m.removedentitlements = nil +} + +// AddChargesCreditPurchaseIDs adds the "charges_credit_purchase" edge to the ChargeCreditPurchase entity by ids. +func (m *CustomerMutation) AddChargesCreditPurchaseIDs(ids ...string) { + if m.charges_credit_purchase == nil { + m.charges_credit_purchase = make(map[string]struct{}) + } + for i := range ids { + m.charges_credit_purchase[ids[i]] = struct{}{} + } +} + +// ClearChargesCreditPurchase clears the "charges_credit_purchase" edge to the ChargeCreditPurchase entity. +func (m *CustomerMutation) ClearChargesCreditPurchase() { + m.clearedcharges_credit_purchase = true +} + +// ChargesCreditPurchaseCleared reports if the "charges_credit_purchase" edge to the ChargeCreditPurchase entity was cleared. +func (m *CustomerMutation) ChargesCreditPurchaseCleared() bool { + return m.clearedcharges_credit_purchase +} + +// RemoveChargesCreditPurchaseIDs removes the "charges_credit_purchase" edge to the ChargeCreditPurchase entity by IDs. +func (m *CustomerMutation) RemoveChargesCreditPurchaseIDs(ids ...string) { + if m.removedcharges_credit_purchase == nil { + m.removedcharges_credit_purchase = make(map[string]struct{}) + } + for i := range ids { + delete(m.charges_credit_purchase, ids[i]) + m.removedcharges_credit_purchase[ids[i]] = struct{}{} + } +} + +// RemovedChargesCreditPurchase returns the removed IDs of the "charges_credit_purchase" edge to the ChargeCreditPurchase entity. +func (m *CustomerMutation) RemovedChargesCreditPurchaseIDs() (ids []string) { + for id := range m.removedcharges_credit_purchase { + ids = append(ids, id) + } + return +} + +// ChargesCreditPurchaseIDs returns the "charges_credit_purchase" edge IDs in the mutation. +func (m *CustomerMutation) ChargesCreditPurchaseIDs() (ids []string) { + for id := range m.charges_credit_purchase { + ids = append(ids, id) + } + return +} + +// ResetChargesCreditPurchase resets all changes to the "charges_credit_purchase" edge. +func (m *CustomerMutation) ResetChargesCreditPurchase() { + m.charges_credit_purchase = nil + m.clearedcharges_credit_purchase = false + m.removedcharges_credit_purchase = nil +} + +// AddChargesFlatFeeIDs adds the "charges_flat_fee" edge to the ChargeFlatFee entity by ids. +func (m *CustomerMutation) AddChargesFlatFeeIDs(ids ...string) { + if m.charges_flat_fee == nil { + m.charges_flat_fee = make(map[string]struct{}) + } + for i := range ids { + m.charges_flat_fee[ids[i]] = struct{}{} + } +} + +// ClearChargesFlatFee clears the "charges_flat_fee" edge to the ChargeFlatFee entity. +func (m *CustomerMutation) ClearChargesFlatFee() { + m.clearedcharges_flat_fee = true +} + +// ChargesFlatFeeCleared reports if the "charges_flat_fee" edge to the ChargeFlatFee entity was cleared. +func (m *CustomerMutation) ChargesFlatFeeCleared() bool { + return m.clearedcharges_flat_fee +} + +// RemoveChargesFlatFeeIDs removes the "charges_flat_fee" edge to the ChargeFlatFee entity by IDs. +func (m *CustomerMutation) RemoveChargesFlatFeeIDs(ids ...string) { + if m.removedcharges_flat_fee == nil { + m.removedcharges_flat_fee = make(map[string]struct{}) + } + for i := range ids { + delete(m.charges_flat_fee, ids[i]) + m.removedcharges_flat_fee[ids[i]] = struct{}{} + } +} + +// RemovedChargesFlatFee returns the removed IDs of the "charges_flat_fee" edge to the ChargeFlatFee entity. +func (m *CustomerMutation) RemovedChargesFlatFeeIDs() (ids []string) { + for id := range m.removedcharges_flat_fee { + ids = append(ids, id) + } + return +} + +// ChargesFlatFeeIDs returns the "charges_flat_fee" edge IDs in the mutation. +func (m *CustomerMutation) ChargesFlatFeeIDs() (ids []string) { + for id := range m.charges_flat_fee { + ids = append(ids, id) + } + return +} + +// ResetChargesFlatFee resets all changes to the "charges_flat_fee" edge. +func (m *CustomerMutation) ResetChargesFlatFee() { + m.charges_flat_fee = nil + m.clearedcharges_flat_fee = false + m.removedcharges_flat_fee = nil +} + +// AddChargesUsageBasedIDs adds the "charges_usage_based" edge to the ChargeUsageBased entity by ids. +func (m *CustomerMutation) AddChargesUsageBasedIDs(ids ...string) { + if m.charges_usage_based == nil { + m.charges_usage_based = make(map[string]struct{}) + } + for i := range ids { + m.charges_usage_based[ids[i]] = struct{}{} + } +} + +// ClearChargesUsageBased clears the "charges_usage_based" edge to the ChargeUsageBased entity. +func (m *CustomerMutation) ClearChargesUsageBased() { + m.clearedcharges_usage_based = true +} + +// ChargesUsageBasedCleared reports if the "charges_usage_based" edge to the ChargeUsageBased entity was cleared. +func (m *CustomerMutation) ChargesUsageBasedCleared() bool { + return m.clearedcharges_usage_based +} + +// RemoveChargesUsageBasedIDs removes the "charges_usage_based" edge to the ChargeUsageBased entity by IDs. +func (m *CustomerMutation) RemoveChargesUsageBasedIDs(ids ...string) { + if m.removedcharges_usage_based == nil { + m.removedcharges_usage_based = make(map[string]struct{}) + } + for i := range ids { + delete(m.charges_usage_based, ids[i]) + m.removedcharges_usage_based[ids[i]] = struct{}{} + } +} + +// RemovedChargesUsageBased returns the removed IDs of the "charges_usage_based" edge to the ChargeUsageBased entity. +func (m *CustomerMutation) RemovedChargesUsageBasedIDs() (ids []string) { + for id := range m.removedcharges_usage_based { + ids = append(ids, id) + } + return +} + +// ChargesUsageBasedIDs returns the "charges_usage_based" edge IDs in the mutation. +func (m *CustomerMutation) ChargesUsageBasedIDs() (ids []string) { + for id := range m.charges_usage_based { + ids = append(ids, id) + } + return +} + +// ResetChargesUsageBased resets all changes to the "charges_usage_based" edge. +func (m *CustomerMutation) ResetChargesUsageBased() { + m.charges_usage_based = nil + m.clearedcharges_usage_based = false + m.removedcharges_usage_based = nil +} + +// Where appends a list predicates to the CustomerMutation builder. +func (m *CustomerMutation) Where(ps ...predicate.Customer) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the CustomerMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *CustomerMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Customer, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *CustomerMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *CustomerMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Customer). +func (m *CustomerMutation) 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 *CustomerMutation) Fields() []string { + fields := make([]string, 0, 18) + if m.namespace != nil { + fields = append(fields, customer.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, customer.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, customer.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, customer.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, customer.FieldDeletedAt) + } + if m.name != nil { + fields = append(fields, customer.FieldName) + } + if m.description != nil { + fields = append(fields, customer.FieldDescription) + } + if m.billing_address_country != nil { + fields = append(fields, customer.FieldBillingAddressCountry) + } + if m.billing_address_postal_code != nil { + fields = append(fields, customer.FieldBillingAddressPostalCode) + } + if m.billing_address_state != nil { + fields = append(fields, customer.FieldBillingAddressState) + } + if m.billing_address_city != nil { + fields = append(fields, customer.FieldBillingAddressCity) + } + if m.billing_address_line1 != nil { + fields = append(fields, customer.FieldBillingAddressLine1) + } + if m.billing_address_line2 != nil { + fields = append(fields, customer.FieldBillingAddressLine2) + } + if m.billing_address_phone_number != nil { + fields = append(fields, customer.FieldBillingAddressPhoneNumber) + } + if m.annotations != nil { + fields = append(fields, customer.FieldAnnotations) + } + if m.key != nil { + fields = append(fields, customer.FieldKey) + } + if m.primary_email != nil { + fields = append(fields, customer.FieldPrimaryEmail) + } + if m.currency != nil { + fields = append(fields, customer.FieldCurrency) + } + 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 *CustomerMutation) Field(name string) (ent.Value, bool) { + switch name { + case customer.FieldNamespace: + return m.Namespace() + case customer.FieldMetadata: + return m.Metadata() + case customer.FieldCreatedAt: + return m.CreatedAt() + case customer.FieldUpdatedAt: + return m.UpdatedAt() + case customer.FieldDeletedAt: + return m.DeletedAt() + case customer.FieldName: + return m.Name() + case customer.FieldDescription: + return m.Description() + case customer.FieldBillingAddressCountry: + return m.BillingAddressCountry() + case customer.FieldBillingAddressPostalCode: + return m.BillingAddressPostalCode() + case customer.FieldBillingAddressState: + return m.BillingAddressState() + case customer.FieldBillingAddressCity: + return m.BillingAddressCity() + case customer.FieldBillingAddressLine1: + return m.BillingAddressLine1() + case customer.FieldBillingAddressLine2: + return m.BillingAddressLine2() + case customer.FieldBillingAddressPhoneNumber: + return m.BillingAddressPhoneNumber() + case customer.FieldAnnotations: + return m.Annotations() + case customer.FieldKey: + return m.Key() + case customer.FieldPrimaryEmail: + return m.PrimaryEmail() + case customer.FieldCurrency: + return m.Currency() + } + 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 *CustomerMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case customer.FieldNamespace: + return m.OldNamespace(ctx) + case customer.FieldMetadata: + return m.OldMetadata(ctx) + case customer.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case customer.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case customer.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case customer.FieldName: + return m.OldName(ctx) + case customer.FieldDescription: + return m.OldDescription(ctx) + case customer.FieldBillingAddressCountry: + return m.OldBillingAddressCountry(ctx) + case customer.FieldBillingAddressPostalCode: + return m.OldBillingAddressPostalCode(ctx) + case customer.FieldBillingAddressState: + return m.OldBillingAddressState(ctx) + case customer.FieldBillingAddressCity: + return m.OldBillingAddressCity(ctx) + case customer.FieldBillingAddressLine1: + return m.OldBillingAddressLine1(ctx) + case customer.FieldBillingAddressLine2: + return m.OldBillingAddressLine2(ctx) + case customer.FieldBillingAddressPhoneNumber: + return m.OldBillingAddressPhoneNumber(ctx) + case customer.FieldAnnotations: + return m.OldAnnotations(ctx) + case customer.FieldKey: + return m.OldKey(ctx) + case customer.FieldPrimaryEmail: + return m.OldPrimaryEmail(ctx) + case customer.FieldCurrency: + return m.OldCurrency(ctx) + } + return nil, fmt.Errorf("unknown Customer 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 *CustomerMutation) SetField(name string, value ent.Value) error { + switch name { + case customer.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case customer.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case customer.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 customer.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 customer.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 customer.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case customer.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case customer.FieldBillingAddressCountry: + v, ok := value.(models.CountryCode) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingAddressCountry(v) + return nil + case customer.FieldBillingAddressPostalCode: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingAddressPostalCode(v) + return nil + case customer.FieldBillingAddressState: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingAddressState(v) + return nil + case customer.FieldBillingAddressCity: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingAddressCity(v) + return nil + case customer.FieldBillingAddressLine1: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingAddressLine1(v) + return nil + case customer.FieldBillingAddressLine2: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingAddressLine2(v) + return nil + case customer.FieldBillingAddressPhoneNumber: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingAddressPhoneNumber(v) + return nil + case customer.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 customer.FieldKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKey(v) + return nil + case customer.FieldPrimaryEmail: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPrimaryEmail(v) + return nil + case customer.FieldCurrency: + v, ok := value.(currencyx.Code) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrency(v) + return nil + } + return fmt.Errorf("unknown Customer field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *CustomerMutation) 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 *CustomerMutation) 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 *CustomerMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Customer numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *CustomerMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(customer.FieldMetadata) { + fields = append(fields, customer.FieldMetadata) + } + if m.FieldCleared(customer.FieldDeletedAt) { + fields = append(fields, customer.FieldDeletedAt) + } + if m.FieldCleared(customer.FieldDescription) { + fields = append(fields, customer.FieldDescription) + } + if m.FieldCleared(customer.FieldBillingAddressCountry) { + fields = append(fields, customer.FieldBillingAddressCountry) + } + if m.FieldCleared(customer.FieldBillingAddressPostalCode) { + fields = append(fields, customer.FieldBillingAddressPostalCode) + } + if m.FieldCleared(customer.FieldBillingAddressState) { + fields = append(fields, customer.FieldBillingAddressState) + } + if m.FieldCleared(customer.FieldBillingAddressCity) { + fields = append(fields, customer.FieldBillingAddressCity) + } + if m.FieldCleared(customer.FieldBillingAddressLine1) { + fields = append(fields, customer.FieldBillingAddressLine1) + } + if m.FieldCleared(customer.FieldBillingAddressLine2) { + fields = append(fields, customer.FieldBillingAddressLine2) + } + if m.FieldCleared(customer.FieldBillingAddressPhoneNumber) { + fields = append(fields, customer.FieldBillingAddressPhoneNumber) + } + if m.FieldCleared(customer.FieldAnnotations) { + fields = append(fields, customer.FieldAnnotations) + } + if m.FieldCleared(customer.FieldKey) { + fields = append(fields, customer.FieldKey) + } + if m.FieldCleared(customer.FieldPrimaryEmail) { + fields = append(fields, customer.FieldPrimaryEmail) + } + if m.FieldCleared(customer.FieldCurrency) { + fields = append(fields, customer.FieldCurrency) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *CustomerMutation) 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 *CustomerMutation) ClearField(name string) error { + switch name { + case customer.FieldMetadata: + m.ClearMetadata() + return nil + case customer.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case customer.FieldDescription: + m.ClearDescription() + return nil + case customer.FieldBillingAddressCountry: + m.ClearBillingAddressCountry() + return nil + case customer.FieldBillingAddressPostalCode: + m.ClearBillingAddressPostalCode() + return nil + case customer.FieldBillingAddressState: + m.ClearBillingAddressState() + return nil + case customer.FieldBillingAddressCity: + m.ClearBillingAddressCity() + return nil + case customer.FieldBillingAddressLine1: + m.ClearBillingAddressLine1() + return nil + case customer.FieldBillingAddressLine2: + m.ClearBillingAddressLine2() + return nil + case customer.FieldBillingAddressPhoneNumber: + m.ClearBillingAddressPhoneNumber() + return nil + case customer.FieldAnnotations: + m.ClearAnnotations() + return nil + case customer.FieldKey: + m.ClearKey() + return nil + case customer.FieldPrimaryEmail: + m.ClearPrimaryEmail() + return nil + case customer.FieldCurrency: + m.ClearCurrency() + return nil + } + return fmt.Errorf("unknown Customer 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 *CustomerMutation) ResetField(name string) error { + switch name { + case customer.FieldNamespace: + m.ResetNamespace() + return nil + case customer.FieldMetadata: + m.ResetMetadata() + return nil + case customer.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case customer.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case customer.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case customer.FieldName: + m.ResetName() + return nil + case customer.FieldDescription: + m.ResetDescription() + return nil + case customer.FieldBillingAddressCountry: + m.ResetBillingAddressCountry() + return nil + case customer.FieldBillingAddressPostalCode: + m.ResetBillingAddressPostalCode() + return nil + case customer.FieldBillingAddressState: + m.ResetBillingAddressState() + return nil + case customer.FieldBillingAddressCity: + m.ResetBillingAddressCity() + return nil + case customer.FieldBillingAddressLine1: + m.ResetBillingAddressLine1() + return nil + case customer.FieldBillingAddressLine2: + m.ResetBillingAddressLine2() + return nil + case customer.FieldBillingAddressPhoneNumber: + m.ResetBillingAddressPhoneNumber() + return nil + case customer.FieldAnnotations: + m.ResetAnnotations() + return nil + case customer.FieldKey: + m.ResetKey() + return nil + case customer.FieldPrimaryEmail: + m.ResetPrimaryEmail() + return nil + case customer.FieldCurrency: + m.ResetCurrency() + return nil + } + return fmt.Errorf("unknown Customer field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *CustomerMutation) AddedEdges() []string { + edges := make([]string, 0, 9) + if m.apps != nil { + edges = append(edges, customer.EdgeApps) + } + if m.subjects != nil { + edges = append(edges, customer.EdgeSubjects) + } + if m.billing_customer_override != nil { + edges = append(edges, customer.EdgeBillingCustomerOverride) + } + if m.billing_invoice != nil { + edges = append(edges, customer.EdgeBillingInvoice) + } + if m.subscription != nil { + edges = append(edges, customer.EdgeSubscription) + } + if m.entitlements != nil { + edges = append(edges, customer.EdgeEntitlements) + } + if m.charges_credit_purchase != nil { + edges = append(edges, customer.EdgeChargesCreditPurchase) + } + if m.charges_flat_fee != nil { + edges = append(edges, customer.EdgeChargesFlatFee) + } + if m.charges_usage_based != nil { + edges = append(edges, customer.EdgeChargesUsageBased) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *CustomerMutation) AddedIDs(name string) []ent.Value { + switch name { + case customer.EdgeApps: + ids := make([]ent.Value, 0, len(m.apps)) + for id := range m.apps { + ids = append(ids, id) + } + return ids + case customer.EdgeSubjects: + ids := make([]ent.Value, 0, len(m.subjects)) + for id := range m.subjects { + ids = append(ids, id) + } + return ids + case customer.EdgeBillingCustomerOverride: + if id := m.billing_customer_override; id != nil { + return []ent.Value{*id} + } + case customer.EdgeBillingInvoice: + ids := make([]ent.Value, 0, len(m.billing_invoice)) + for id := range m.billing_invoice { + ids = append(ids, id) + } + return ids + case customer.EdgeSubscription: + ids := make([]ent.Value, 0, len(m.subscription)) + for id := range m.subscription { + ids = append(ids, id) + } + return ids + case customer.EdgeEntitlements: + ids := make([]ent.Value, 0, len(m.entitlements)) + for id := range m.entitlements { + ids = append(ids, id) + } + return ids + case customer.EdgeChargesCreditPurchase: + ids := make([]ent.Value, 0, len(m.charges_credit_purchase)) + for id := range m.charges_credit_purchase { + ids = append(ids, id) + } + return ids + case customer.EdgeChargesFlatFee: + ids := make([]ent.Value, 0, len(m.charges_flat_fee)) + for id := range m.charges_flat_fee { + ids = append(ids, id) + } + return ids + case customer.EdgeChargesUsageBased: + ids := make([]ent.Value, 0, len(m.charges_usage_based)) + for id := range m.charges_usage_based { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *CustomerMutation) RemovedEdges() []string { + edges := make([]string, 0, 9) + if m.removedapps != nil { + edges = append(edges, customer.EdgeApps) + } + if m.removedsubjects != nil { + edges = append(edges, customer.EdgeSubjects) + } + if m.removedbilling_invoice != nil { + edges = append(edges, customer.EdgeBillingInvoice) + } + if m.removedsubscription != nil { + edges = append(edges, customer.EdgeSubscription) + } + if m.removedentitlements != nil { + edges = append(edges, customer.EdgeEntitlements) + } + if m.removedcharges_credit_purchase != nil { + edges = append(edges, customer.EdgeChargesCreditPurchase) + } + if m.removedcharges_flat_fee != nil { + edges = append(edges, customer.EdgeChargesFlatFee) + } + if m.removedcharges_usage_based != nil { + edges = append(edges, customer.EdgeChargesUsageBased) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *CustomerMutation) RemovedIDs(name string) []ent.Value { + switch name { + case customer.EdgeApps: + ids := make([]ent.Value, 0, len(m.removedapps)) + for id := range m.removedapps { + ids = append(ids, id) + } + return ids + case customer.EdgeSubjects: + ids := make([]ent.Value, 0, len(m.removedsubjects)) + for id := range m.removedsubjects { + ids = append(ids, id) + } + return ids + case customer.EdgeBillingInvoice: + ids := make([]ent.Value, 0, len(m.removedbilling_invoice)) + for id := range m.removedbilling_invoice { + ids = append(ids, id) + } + return ids + case customer.EdgeSubscription: + ids := make([]ent.Value, 0, len(m.removedsubscription)) + for id := range m.removedsubscription { + ids = append(ids, id) + } + return ids + case customer.EdgeEntitlements: + ids := make([]ent.Value, 0, len(m.removedentitlements)) + for id := range m.removedentitlements { + ids = append(ids, id) + } + return ids + case customer.EdgeChargesCreditPurchase: + ids := make([]ent.Value, 0, len(m.removedcharges_credit_purchase)) + for id := range m.removedcharges_credit_purchase { + ids = append(ids, id) + } + return ids + case customer.EdgeChargesFlatFee: + ids := make([]ent.Value, 0, len(m.removedcharges_flat_fee)) + for id := range m.removedcharges_flat_fee { + ids = append(ids, id) + } + return ids + case customer.EdgeChargesUsageBased: + ids := make([]ent.Value, 0, len(m.removedcharges_usage_based)) + for id := range m.removedcharges_usage_based { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *CustomerMutation) ClearedEdges() []string { + edges := make([]string, 0, 9) + if m.clearedapps { + edges = append(edges, customer.EdgeApps) + } + if m.clearedsubjects { + edges = append(edges, customer.EdgeSubjects) + } + if m.clearedbilling_customer_override { + edges = append(edges, customer.EdgeBillingCustomerOverride) + } + if m.clearedbilling_invoice { + edges = append(edges, customer.EdgeBillingInvoice) + } + if m.clearedsubscription { + edges = append(edges, customer.EdgeSubscription) + } + if m.clearedentitlements { + edges = append(edges, customer.EdgeEntitlements) + } + if m.clearedcharges_credit_purchase { + edges = append(edges, customer.EdgeChargesCreditPurchase) + } + if m.clearedcharges_flat_fee { + edges = append(edges, customer.EdgeChargesFlatFee) + } + if m.clearedcharges_usage_based { + edges = append(edges, customer.EdgeChargesUsageBased) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *CustomerMutation) EdgeCleared(name string) bool { + switch name { + case customer.EdgeApps: + return m.clearedapps + case customer.EdgeSubjects: + return m.clearedsubjects + case customer.EdgeBillingCustomerOverride: + return m.clearedbilling_customer_override + case customer.EdgeBillingInvoice: + return m.clearedbilling_invoice + case customer.EdgeSubscription: + return m.clearedsubscription + case customer.EdgeEntitlements: + return m.clearedentitlements + case customer.EdgeChargesCreditPurchase: + return m.clearedcharges_credit_purchase + case customer.EdgeChargesFlatFee: + return m.clearedcharges_flat_fee + case customer.EdgeChargesUsageBased: + return m.clearedcharges_usage_based + } + 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 *CustomerMutation) ClearEdge(name string) error { + switch name { + case customer.EdgeBillingCustomerOverride: + m.ClearBillingCustomerOverride() + return nil + } + return fmt.Errorf("unknown Customer 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 *CustomerMutation) ResetEdge(name string) error { + switch name { + case customer.EdgeApps: + m.ResetApps() + return nil + case customer.EdgeSubjects: + m.ResetSubjects() + return nil + case customer.EdgeBillingCustomerOverride: + m.ResetBillingCustomerOverride() + return nil + case customer.EdgeBillingInvoice: + m.ResetBillingInvoice() + return nil + case customer.EdgeSubscription: + m.ResetSubscription() + return nil + case customer.EdgeEntitlements: + m.ResetEntitlements() + return nil + case customer.EdgeChargesCreditPurchase: + m.ResetChargesCreditPurchase() + return nil + case customer.EdgeChargesFlatFee: + m.ResetChargesFlatFee() + return nil + case customer.EdgeChargesUsageBased: + m.ResetChargesUsageBased() + return nil + } + return fmt.Errorf("unknown Customer edge %s", name) +} + +// CustomerSubjectsMutation represents an operation that mutates the CustomerSubjects nodes in the graph. +type CustomerSubjectsMutation struct { + config + op Op + typ string + id *int + namespace *string + subject_key *string + created_at *time.Time + deleted_at *time.Time + clearedFields map[string]struct{} + customer *string + clearedcustomer bool + done bool + oldValue func(context.Context) (*CustomerSubjects, error) + predicates []predicate.CustomerSubjects +} + +var _ ent.Mutation = (*CustomerSubjectsMutation)(nil) + +// customersubjectsOption allows management of the mutation configuration using functional options. +type customersubjectsOption func(*CustomerSubjectsMutation) + +// newCustomerSubjectsMutation creates new mutation for the CustomerSubjects entity. +func newCustomerSubjectsMutation(c config, op Op, opts ...customersubjectsOption) *CustomerSubjectsMutation { + m := &CustomerSubjectsMutation{ + config: c, + op: op, + typ: TypeCustomerSubjects, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withCustomerSubjectsID sets the ID field of the mutation. +func withCustomerSubjectsID(id int) customersubjectsOption { + return func(m *CustomerSubjectsMutation) { + var ( + err error + once sync.Once + value *CustomerSubjects + ) + m.oldValue = func(ctx context.Context) (*CustomerSubjects, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().CustomerSubjects.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withCustomerSubjects sets the old CustomerSubjects of the mutation. +func withCustomerSubjects(node *CustomerSubjects) customersubjectsOption { + return func(m *CustomerSubjectsMutation) { + m.oldValue = func(context.Context) (*CustomerSubjects, 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 CustomerSubjectsMutation) 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 CustomerSubjectsMutation) 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 +} + +// 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 *CustomerSubjectsMutation) ID() (id int, 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 *CustomerSubjectsMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().CustomerSubjects.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 *CustomerSubjectsMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *CustomerSubjectsMutation) 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 CustomerSubjects entity. +// If the CustomerSubjects 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 *CustomerSubjectsMutation) 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 *CustomerSubjectsMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCustomerID sets the "customer_id" field. +func (m *CustomerSubjectsMutation) SetCustomerID(s string) { + m.customer = &s +} + +// CustomerID returns the value of the "customer_id" field in the mutation. +func (m *CustomerSubjectsMutation) CustomerID() (r string, exists bool) { + v := m.customer + if v == nil { + return + } + return *v, true +} + +// OldCustomerID returns the old "customer_id" field's value of the CustomerSubjects entity. +// If the CustomerSubjects 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 *CustomerSubjectsMutation) OldCustomerID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerID: %w", err) + } + return oldValue.CustomerID, nil +} + +// ResetCustomerID resets all changes to the "customer_id" field. +func (m *CustomerSubjectsMutation) ResetCustomerID() { + m.customer = nil +} + +// SetSubjectKey sets the "subject_key" field. +func (m *CustomerSubjectsMutation) SetSubjectKey(s string) { + m.subject_key = &s +} + +// SubjectKey returns the value of the "subject_key" field in the mutation. +func (m *CustomerSubjectsMutation) SubjectKey() (r string, exists bool) { + v := m.subject_key + if v == nil { + return + } + return *v, true +} + +// OldSubjectKey returns the old "subject_key" field's value of the CustomerSubjects entity. +// If the CustomerSubjects 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 *CustomerSubjectsMutation) OldSubjectKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubjectKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubjectKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubjectKey: %w", err) + } + return oldValue.SubjectKey, nil +} + +// ResetSubjectKey resets all changes to the "subject_key" field. +func (m *CustomerSubjectsMutation) ResetSubjectKey() { + m.subject_key = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *CustomerSubjectsMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *CustomerSubjectsMutation) 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 CustomerSubjects entity. +// If the CustomerSubjects 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 *CustomerSubjectsMutation) 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 *CustomerSubjectsMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *CustomerSubjectsMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *CustomerSubjectsMutation) 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 CustomerSubjects entity. +// If the CustomerSubjects 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 *CustomerSubjectsMutation) 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 *CustomerSubjectsMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[customersubjects.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *CustomerSubjectsMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[customersubjects.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *CustomerSubjectsMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, customersubjects.FieldDeletedAt) +} + +// ClearCustomer clears the "customer" edge to the Customer entity. +func (m *CustomerSubjectsMutation) ClearCustomer() { + m.clearedcustomer = true + m.clearedFields[customersubjects.FieldCustomerID] = struct{}{} +} + +// CustomerCleared reports if the "customer" edge to the Customer entity was cleared. +func (m *CustomerSubjectsMutation) CustomerCleared() bool { + return m.clearedcustomer +} + +// CustomerIDs returns the "customer" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CustomerID instead. It exists only for internal usage by the builders. +func (m *CustomerSubjectsMutation) CustomerIDs() (ids []string) { + if id := m.customer; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCustomer resets all changes to the "customer" edge. +func (m *CustomerSubjectsMutation) ResetCustomer() { + m.customer = nil + m.clearedcustomer = false +} + +// Where appends a list predicates to the CustomerSubjectsMutation builder. +func (m *CustomerSubjectsMutation) Where(ps ...predicate.CustomerSubjects) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the CustomerSubjectsMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *CustomerSubjectsMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.CustomerSubjects, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *CustomerSubjectsMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *CustomerSubjectsMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (CustomerSubjects). +func (m *CustomerSubjectsMutation) 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 *CustomerSubjectsMutation) Fields() []string { + fields := make([]string, 0, 5) + if m.namespace != nil { + fields = append(fields, customersubjects.FieldNamespace) + } + if m.customer != nil { + fields = append(fields, customersubjects.FieldCustomerID) + } + if m.subject_key != nil { + fields = append(fields, customersubjects.FieldSubjectKey) + } + if m.created_at != nil { + fields = append(fields, customersubjects.FieldCreatedAt) + } + if m.deleted_at != nil { + fields = append(fields, customersubjects.FieldDeletedAt) + } + 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 *CustomerSubjectsMutation) Field(name string) (ent.Value, bool) { + switch name { + case customersubjects.FieldNamespace: + return m.Namespace() + case customersubjects.FieldCustomerID: + return m.CustomerID() + case customersubjects.FieldSubjectKey: + return m.SubjectKey() + case customersubjects.FieldCreatedAt: + return m.CreatedAt() + case customersubjects.FieldDeletedAt: + return m.DeletedAt() + } + 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 *CustomerSubjectsMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case customersubjects.FieldNamespace: + return m.OldNamespace(ctx) + case customersubjects.FieldCustomerID: + return m.OldCustomerID(ctx) + case customersubjects.FieldSubjectKey: + return m.OldSubjectKey(ctx) + case customersubjects.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case customersubjects.FieldDeletedAt: + return m.OldDeletedAt(ctx) + } + return nil, fmt.Errorf("unknown CustomerSubjects 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 *CustomerSubjectsMutation) SetField(name string, value ent.Value) error { + switch name { + case customersubjects.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case customersubjects.FieldCustomerID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerID(v) + return nil + case customersubjects.FieldSubjectKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubjectKey(v) + return nil + case customersubjects.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 customersubjects.FieldDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeletedAt(v) + return nil + } + return fmt.Errorf("unknown CustomerSubjects field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *CustomerSubjectsMutation) 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 *CustomerSubjectsMutation) 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 *CustomerSubjectsMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown CustomerSubjects numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *CustomerSubjectsMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(customersubjects.FieldDeletedAt) { + fields = append(fields, customersubjects.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *CustomerSubjectsMutation) 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 *CustomerSubjectsMutation) ClearField(name string) error { + switch name { + case customersubjects.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown CustomerSubjects 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 *CustomerSubjectsMutation) ResetField(name string) error { + switch name { + case customersubjects.FieldNamespace: + m.ResetNamespace() + return nil + case customersubjects.FieldCustomerID: + m.ResetCustomerID() + return nil + case customersubjects.FieldSubjectKey: + m.ResetSubjectKey() + return nil + case customersubjects.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case customersubjects.FieldDeletedAt: + m.ResetDeletedAt() + return nil + } + return fmt.Errorf("unknown CustomerSubjects field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *CustomerSubjectsMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.customer != nil { + edges = append(edges, customersubjects.EdgeCustomer) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *CustomerSubjectsMutation) AddedIDs(name string) []ent.Value { + switch name { + case customersubjects.EdgeCustomer: + if id := m.customer; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *CustomerSubjectsMutation) 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 *CustomerSubjectsMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *CustomerSubjectsMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedcustomer { + edges = append(edges, customersubjects.EdgeCustomer) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *CustomerSubjectsMutation) EdgeCleared(name string) bool { + switch name { + case customersubjects.EdgeCustomer: + return m.clearedcustomer + } + 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 *CustomerSubjectsMutation) ClearEdge(name string) error { + switch name { + case customersubjects.EdgeCustomer: + m.ClearCustomer() + return nil + } + return fmt.Errorf("unknown CustomerSubjects 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 *CustomerSubjectsMutation) ResetEdge(name string) error { + switch name { + case customersubjects.EdgeCustomer: + m.ResetCustomer() + return nil + } + return fmt.Errorf("unknown CustomerSubjects edge %s", name) +} + +// EntitlementMutation represents an operation that mutates the Entitlement nodes in the graph. +type EntitlementMutation struct { + config + op Op + typ string + id *string + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + entitlement_type *entitlement.EntitlementType + active_from *time.Time + active_to *time.Time + feature_key *string + measure_usage_from *time.Time + issue_after_reset *float64 + addissue_after_reset *float64 + issue_after_reset_priority *uint8 + addissue_after_reset_priority *int8 + is_soft_limit *bool + preserve_overage_at_reset *bool + _config *string + usage_period_interval *datetime.ISODurationString + usage_period_anchor *time.Time + current_usage_period_start *time.Time + current_usage_period_end *time.Time + annotations *models.Annotations + clearedFields map[string]struct{} + usage_reset map[string]struct{} + removedusage_reset map[string]struct{} + clearedusage_reset bool + grant map[string]struct{} + removedgrant map[string]struct{} + clearedgrant bool + balance_snapshot map[int]struct{} + removedbalance_snapshot map[int]struct{} + clearedbalance_snapshot bool + subscription_item map[string]struct{} + removedsubscription_item map[string]struct{} + clearedsubscription_item bool + feature *string + clearedfeature bool + customer *string + clearedcustomer bool + done bool + oldValue func(context.Context) (*Entitlement, error) + predicates []predicate.Entitlement +} + +var _ ent.Mutation = (*EntitlementMutation)(nil) + +// entitlementOption allows management of the mutation configuration using functional options. +type entitlementOption func(*EntitlementMutation) + +// newEntitlementMutation creates new mutation for the Entitlement entity. +func newEntitlementMutation(c config, op Op, opts ...entitlementOption) *EntitlementMutation { + m := &EntitlementMutation{ + config: c, + op: op, + typ: TypeEntitlement, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withEntitlementID sets the ID field of the mutation. +func withEntitlementID(id string) entitlementOption { + return func(m *EntitlementMutation) { + var ( + err error + once sync.Once + value *Entitlement + ) + m.oldValue = func(ctx context.Context) (*Entitlement, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Entitlement.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withEntitlement sets the old Entitlement of the mutation. +func withEntitlement(node *Entitlement) entitlementOption { + return func(m *EntitlementMutation) { + m.oldValue = func(context.Context) (*Entitlement, 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 EntitlementMutation) 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 EntitlementMutation) 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 Entitlement entities. +func (m *EntitlementMutation) 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 *EntitlementMutation) 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 *EntitlementMutation) 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().Entitlement.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 *EntitlementMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *EntitlementMutation) 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 Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) 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 *EntitlementMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *EntitlementMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *EntitlementMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *EntitlementMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[entitlement.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *EntitlementMutation) MetadataCleared() bool { + _, ok := m.clearedFields[entitlement.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *EntitlementMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, entitlement.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *EntitlementMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *EntitlementMutation) 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 Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) 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 *EntitlementMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *EntitlementMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *EntitlementMutation) 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 Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) 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 *EntitlementMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *EntitlementMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *EntitlementMutation) 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 Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) 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 *EntitlementMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[entitlement.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *EntitlementMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[entitlement.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *EntitlementMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, entitlement.FieldDeletedAt) +} + +// SetEntitlementType sets the "entitlement_type" field. +func (m *EntitlementMutation) SetEntitlementType(et entitlement.EntitlementType) { + m.entitlement_type = &et +} + +// EntitlementType returns the value of the "entitlement_type" field in the mutation. +func (m *EntitlementMutation) EntitlementType() (r entitlement.EntitlementType, exists bool) { + v := m.entitlement_type + if v == nil { + return + } + return *v, true +} + +// OldEntitlementType returns the old "entitlement_type" field's value of the Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) OldEntitlementType(ctx context.Context) (v entitlement.EntitlementType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEntitlementType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEntitlementType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEntitlementType: %w", err) + } + return oldValue.EntitlementType, nil +} + +// ResetEntitlementType resets all changes to the "entitlement_type" field. +func (m *EntitlementMutation) ResetEntitlementType() { + m.entitlement_type = nil +} + +// SetFeatureID sets the "feature_id" field. +func (m *EntitlementMutation) SetFeatureID(s string) { + m.feature = &s +} + +// FeatureID returns the value of the "feature_id" field in the mutation. +func (m *EntitlementMutation) FeatureID() (r string, exists bool) { + v := m.feature + if v == nil { + return + } + return *v, true +} + +// OldFeatureID returns the old "feature_id" field's value of the Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) OldFeatureID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFeatureID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFeatureID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFeatureID: %w", err) + } + return oldValue.FeatureID, nil +} + +// ResetFeatureID resets all changes to the "feature_id" field. +func (m *EntitlementMutation) ResetFeatureID() { + m.feature = nil +} + +// SetActiveFrom sets the "active_from" field. +func (m *EntitlementMutation) SetActiveFrom(t time.Time) { + m.active_from = &t +} + +// ActiveFrom returns the value of the "active_from" field in the mutation. +func (m *EntitlementMutation) ActiveFrom() (r time.Time, exists bool) { + v := m.active_from + if v == nil { + return + } + return *v, true +} + +// OldActiveFrom returns the old "active_from" field's value of the Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) OldActiveFrom(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldActiveFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldActiveFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldActiveFrom: %w", err) + } + return oldValue.ActiveFrom, nil +} + +// ClearActiveFrom clears the value of the "active_from" field. +func (m *EntitlementMutation) ClearActiveFrom() { + m.active_from = nil + m.clearedFields[entitlement.FieldActiveFrom] = struct{}{} +} + +// ActiveFromCleared returns if the "active_from" field was cleared in this mutation. +func (m *EntitlementMutation) ActiveFromCleared() bool { + _, ok := m.clearedFields[entitlement.FieldActiveFrom] + return ok +} + +// ResetActiveFrom resets all changes to the "active_from" field. +func (m *EntitlementMutation) ResetActiveFrom() { + m.active_from = nil + delete(m.clearedFields, entitlement.FieldActiveFrom) +} + +// SetActiveTo sets the "active_to" field. +func (m *EntitlementMutation) SetActiveTo(t time.Time) { + m.active_to = &t +} + +// ActiveTo returns the value of the "active_to" field in the mutation. +func (m *EntitlementMutation) ActiveTo() (r time.Time, exists bool) { + v := m.active_to + if v == nil { + return + } + return *v, true +} + +// OldActiveTo returns the old "active_to" field's value of the Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) OldActiveTo(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldActiveTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldActiveTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldActiveTo: %w", err) + } + return oldValue.ActiveTo, nil +} + +// ClearActiveTo clears the value of the "active_to" field. +func (m *EntitlementMutation) ClearActiveTo() { + m.active_to = nil + m.clearedFields[entitlement.FieldActiveTo] = struct{}{} +} + +// ActiveToCleared returns if the "active_to" field was cleared in this mutation. +func (m *EntitlementMutation) ActiveToCleared() bool { + _, ok := m.clearedFields[entitlement.FieldActiveTo] + return ok +} + +// ResetActiveTo resets all changes to the "active_to" field. +func (m *EntitlementMutation) ResetActiveTo() { + m.active_to = nil + delete(m.clearedFields, entitlement.FieldActiveTo) +} + +// SetFeatureKey sets the "feature_key" field. +func (m *EntitlementMutation) SetFeatureKey(s string) { + m.feature_key = &s +} + +// FeatureKey returns the value of the "feature_key" field in the mutation. +func (m *EntitlementMutation) 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 Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) 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 *EntitlementMutation) ResetFeatureKey() { + m.feature_key = nil +} + +// SetCustomerID sets the "customer_id" field. +func (m *EntitlementMutation) SetCustomerID(s string) { + m.customer = &s +} + +// CustomerID returns the value of the "customer_id" field in the mutation. +func (m *EntitlementMutation) CustomerID() (r string, exists bool) { + v := m.customer + if v == nil { + return + } + return *v, true +} + +// OldCustomerID returns the old "customer_id" field's value of the Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) OldCustomerID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerID: %w", err) + } + return oldValue.CustomerID, nil +} + +// ResetCustomerID resets all changes to the "customer_id" field. +func (m *EntitlementMutation) ResetCustomerID() { + m.customer = nil +} + +// SetMeasureUsageFrom sets the "measure_usage_from" field. +func (m *EntitlementMutation) SetMeasureUsageFrom(t time.Time) { + m.measure_usage_from = &t +} + +// MeasureUsageFrom returns the value of the "measure_usage_from" field in the mutation. +func (m *EntitlementMutation) MeasureUsageFrom() (r time.Time, exists bool) { + v := m.measure_usage_from + if v == nil { + return + } + return *v, true +} + +// OldMeasureUsageFrom returns the old "measure_usage_from" field's value of the Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) OldMeasureUsageFrom(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMeasureUsageFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMeasureUsageFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMeasureUsageFrom: %w", err) + } + return oldValue.MeasureUsageFrom, nil +} + +// ClearMeasureUsageFrom clears the value of the "measure_usage_from" field. +func (m *EntitlementMutation) ClearMeasureUsageFrom() { + m.measure_usage_from = nil + m.clearedFields[entitlement.FieldMeasureUsageFrom] = struct{}{} +} + +// MeasureUsageFromCleared returns if the "measure_usage_from" field was cleared in this mutation. +func (m *EntitlementMutation) MeasureUsageFromCleared() bool { + _, ok := m.clearedFields[entitlement.FieldMeasureUsageFrom] + return ok +} + +// ResetMeasureUsageFrom resets all changes to the "measure_usage_from" field. +func (m *EntitlementMutation) ResetMeasureUsageFrom() { + m.measure_usage_from = nil + delete(m.clearedFields, entitlement.FieldMeasureUsageFrom) +} + +// SetIssueAfterReset sets the "issue_after_reset" field. +func (m *EntitlementMutation) SetIssueAfterReset(f float64) { + m.issue_after_reset = &f + m.addissue_after_reset = nil +} + +// IssueAfterReset returns the value of the "issue_after_reset" field in the mutation. +func (m *EntitlementMutation) IssueAfterReset() (r float64, exists bool) { + v := m.issue_after_reset + if v == nil { + return + } + return *v, true +} + +// OldIssueAfterReset returns the old "issue_after_reset" field's value of the Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) OldIssueAfterReset(ctx context.Context) (v *float64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIssueAfterReset is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIssueAfterReset requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIssueAfterReset: %w", err) + } + return oldValue.IssueAfterReset, nil +} + +// AddIssueAfterReset adds f to the "issue_after_reset" field. +func (m *EntitlementMutation) AddIssueAfterReset(f float64) { + if m.addissue_after_reset != nil { + *m.addissue_after_reset += f + } else { + m.addissue_after_reset = &f + } +} + +// AddedIssueAfterReset returns the value that was added to the "issue_after_reset" field in this mutation. +func (m *EntitlementMutation) AddedIssueAfterReset() (r float64, exists bool) { + v := m.addissue_after_reset + if v == nil { + return + } + return *v, true +} + +// ClearIssueAfterReset clears the value of the "issue_after_reset" field. +func (m *EntitlementMutation) ClearIssueAfterReset() { + m.issue_after_reset = nil + m.addissue_after_reset = nil + m.clearedFields[entitlement.FieldIssueAfterReset] = struct{}{} +} + +// IssueAfterResetCleared returns if the "issue_after_reset" field was cleared in this mutation. +func (m *EntitlementMutation) IssueAfterResetCleared() bool { + _, ok := m.clearedFields[entitlement.FieldIssueAfterReset] + return ok +} + +// ResetIssueAfterReset resets all changes to the "issue_after_reset" field. +func (m *EntitlementMutation) ResetIssueAfterReset() { + m.issue_after_reset = nil + m.addissue_after_reset = nil + delete(m.clearedFields, entitlement.FieldIssueAfterReset) +} + +// SetIssueAfterResetPriority sets the "issue_after_reset_priority" field. +func (m *EntitlementMutation) SetIssueAfterResetPriority(u uint8) { + m.issue_after_reset_priority = &u + m.addissue_after_reset_priority = nil +} + +// IssueAfterResetPriority returns the value of the "issue_after_reset_priority" field in the mutation. +func (m *EntitlementMutation) IssueAfterResetPriority() (r uint8, exists bool) { + v := m.issue_after_reset_priority + if v == nil { + return + } + return *v, true +} + +// OldIssueAfterResetPriority returns the old "issue_after_reset_priority" field's value of the Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) OldIssueAfterResetPriority(ctx context.Context) (v *uint8, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIssueAfterResetPriority is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIssueAfterResetPriority requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIssueAfterResetPriority: %w", err) + } + return oldValue.IssueAfterResetPriority, nil +} + +// AddIssueAfterResetPriority adds u to the "issue_after_reset_priority" field. +func (m *EntitlementMutation) AddIssueAfterResetPriority(u int8) { + if m.addissue_after_reset_priority != nil { + *m.addissue_after_reset_priority += u + } else { + m.addissue_after_reset_priority = &u + } +} + +// AddedIssueAfterResetPriority returns the value that was added to the "issue_after_reset_priority" field in this mutation. +func (m *EntitlementMutation) AddedIssueAfterResetPriority() (r int8, exists bool) { + v := m.addissue_after_reset_priority + if v == nil { + return + } + return *v, true +} + +// ClearIssueAfterResetPriority clears the value of the "issue_after_reset_priority" field. +func (m *EntitlementMutation) ClearIssueAfterResetPriority() { + m.issue_after_reset_priority = nil + m.addissue_after_reset_priority = nil + m.clearedFields[entitlement.FieldIssueAfterResetPriority] = struct{}{} +} + +// IssueAfterResetPriorityCleared returns if the "issue_after_reset_priority" field was cleared in this mutation. +func (m *EntitlementMutation) IssueAfterResetPriorityCleared() bool { + _, ok := m.clearedFields[entitlement.FieldIssueAfterResetPriority] + return ok +} + +// ResetIssueAfterResetPriority resets all changes to the "issue_after_reset_priority" field. +func (m *EntitlementMutation) ResetIssueAfterResetPriority() { + m.issue_after_reset_priority = nil + m.addissue_after_reset_priority = nil + delete(m.clearedFields, entitlement.FieldIssueAfterResetPriority) +} + +// SetIsSoftLimit sets the "is_soft_limit" field. +func (m *EntitlementMutation) SetIsSoftLimit(b bool) { + m.is_soft_limit = &b +} + +// IsSoftLimit returns the value of the "is_soft_limit" field in the mutation. +func (m *EntitlementMutation) IsSoftLimit() (r bool, exists bool) { + v := m.is_soft_limit + if v == nil { + return + } + return *v, true +} + +// OldIsSoftLimit returns the old "is_soft_limit" field's value of the Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) OldIsSoftLimit(ctx context.Context) (v *bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIsSoftLimit is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIsSoftLimit requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIsSoftLimit: %w", err) + } + return oldValue.IsSoftLimit, nil +} + +// ClearIsSoftLimit clears the value of the "is_soft_limit" field. +func (m *EntitlementMutation) ClearIsSoftLimit() { + m.is_soft_limit = nil + m.clearedFields[entitlement.FieldIsSoftLimit] = struct{}{} +} + +// IsSoftLimitCleared returns if the "is_soft_limit" field was cleared in this mutation. +func (m *EntitlementMutation) IsSoftLimitCleared() bool { + _, ok := m.clearedFields[entitlement.FieldIsSoftLimit] + return ok +} + +// ResetIsSoftLimit resets all changes to the "is_soft_limit" field. +func (m *EntitlementMutation) ResetIsSoftLimit() { + m.is_soft_limit = nil + delete(m.clearedFields, entitlement.FieldIsSoftLimit) +} + +// SetPreserveOverageAtReset sets the "preserve_overage_at_reset" field. +func (m *EntitlementMutation) SetPreserveOverageAtReset(b bool) { + m.preserve_overage_at_reset = &b +} + +// PreserveOverageAtReset returns the value of the "preserve_overage_at_reset" field in the mutation. +func (m *EntitlementMutation) PreserveOverageAtReset() (r bool, exists bool) { + v := m.preserve_overage_at_reset + if v == nil { + return + } + return *v, true +} + +// OldPreserveOverageAtReset returns the old "preserve_overage_at_reset" field's value of the Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) OldPreserveOverageAtReset(ctx context.Context) (v *bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPreserveOverageAtReset is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPreserveOverageAtReset requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPreserveOverageAtReset: %w", err) + } + return oldValue.PreserveOverageAtReset, nil +} + +// ClearPreserveOverageAtReset clears the value of the "preserve_overage_at_reset" field. +func (m *EntitlementMutation) ClearPreserveOverageAtReset() { + m.preserve_overage_at_reset = nil + m.clearedFields[entitlement.FieldPreserveOverageAtReset] = struct{}{} +} + +// PreserveOverageAtResetCleared returns if the "preserve_overage_at_reset" field was cleared in this mutation. +func (m *EntitlementMutation) PreserveOverageAtResetCleared() bool { + _, ok := m.clearedFields[entitlement.FieldPreserveOverageAtReset] + return ok +} + +// ResetPreserveOverageAtReset resets all changes to the "preserve_overage_at_reset" field. +func (m *EntitlementMutation) ResetPreserveOverageAtReset() { + m.preserve_overage_at_reset = nil + delete(m.clearedFields, entitlement.FieldPreserveOverageAtReset) +} + +// SetConfig sets the "config" field. +func (m *EntitlementMutation) SetConfig(s string) { + m._config = &s +} + +// Config returns the value of the "config" field in the mutation. +func (m *EntitlementMutation) Config() (r string, exists bool) { + v := m._config + if v == nil { + return + } + return *v, true +} + +// OldConfig returns the old "config" field's value of the Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) OldConfig(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldConfig is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldConfig requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldConfig: %w", err) + } + return oldValue.Config, nil +} + +// ClearConfig clears the value of the "config" field. +func (m *EntitlementMutation) ClearConfig() { + m._config = nil + m.clearedFields[entitlement.FieldConfig] = struct{}{} +} + +// ConfigCleared returns if the "config" field was cleared in this mutation. +func (m *EntitlementMutation) ConfigCleared() bool { + _, ok := m.clearedFields[entitlement.FieldConfig] + return ok +} + +// ResetConfig resets all changes to the "config" field. +func (m *EntitlementMutation) ResetConfig() { + m._config = nil + delete(m.clearedFields, entitlement.FieldConfig) +} + +// SetUsagePeriodInterval sets the "usage_period_interval" field. +func (m *EntitlementMutation) SetUsagePeriodInterval(dds datetime.ISODurationString) { + m.usage_period_interval = &dds +} + +// UsagePeriodInterval returns the value of the "usage_period_interval" field in the mutation. +func (m *EntitlementMutation) UsagePeriodInterval() (r datetime.ISODurationString, exists bool) { + v := m.usage_period_interval + if v == nil { + return + } + return *v, true +} + +// OldUsagePeriodInterval returns the old "usage_period_interval" field's value of the Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) OldUsagePeriodInterval(ctx context.Context) (v *datetime.ISODurationString, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUsagePeriodInterval is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUsagePeriodInterval requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUsagePeriodInterval: %w", err) + } + return oldValue.UsagePeriodInterval, nil +} + +// ClearUsagePeriodInterval clears the value of the "usage_period_interval" field. +func (m *EntitlementMutation) ClearUsagePeriodInterval() { + m.usage_period_interval = nil + m.clearedFields[entitlement.FieldUsagePeriodInterval] = struct{}{} +} + +// UsagePeriodIntervalCleared returns if the "usage_period_interval" field was cleared in this mutation. +func (m *EntitlementMutation) UsagePeriodIntervalCleared() bool { + _, ok := m.clearedFields[entitlement.FieldUsagePeriodInterval] + return ok +} + +// ResetUsagePeriodInterval resets all changes to the "usage_period_interval" field. +func (m *EntitlementMutation) ResetUsagePeriodInterval() { + m.usage_period_interval = nil + delete(m.clearedFields, entitlement.FieldUsagePeriodInterval) +} + +// SetUsagePeriodAnchor sets the "usage_period_anchor" field. +func (m *EntitlementMutation) SetUsagePeriodAnchor(t time.Time) { + m.usage_period_anchor = &t +} + +// UsagePeriodAnchor returns the value of the "usage_period_anchor" field in the mutation. +func (m *EntitlementMutation) UsagePeriodAnchor() (r time.Time, exists bool) { + v := m.usage_period_anchor + if v == nil { + return + } + return *v, true +} + +// OldUsagePeriodAnchor returns the old "usage_period_anchor" field's value of the Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) OldUsagePeriodAnchor(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUsagePeriodAnchor is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUsagePeriodAnchor requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUsagePeriodAnchor: %w", err) + } + return oldValue.UsagePeriodAnchor, nil +} + +// ClearUsagePeriodAnchor clears the value of the "usage_period_anchor" field. +func (m *EntitlementMutation) ClearUsagePeriodAnchor() { + m.usage_period_anchor = nil + m.clearedFields[entitlement.FieldUsagePeriodAnchor] = struct{}{} +} + +// UsagePeriodAnchorCleared returns if the "usage_period_anchor" field was cleared in this mutation. +func (m *EntitlementMutation) UsagePeriodAnchorCleared() bool { + _, ok := m.clearedFields[entitlement.FieldUsagePeriodAnchor] + return ok +} + +// ResetUsagePeriodAnchor resets all changes to the "usage_period_anchor" field. +func (m *EntitlementMutation) ResetUsagePeriodAnchor() { + m.usage_period_anchor = nil + delete(m.clearedFields, entitlement.FieldUsagePeriodAnchor) +} + +// SetCurrentUsagePeriodStart sets the "current_usage_period_start" field. +func (m *EntitlementMutation) SetCurrentUsagePeriodStart(t time.Time) { + m.current_usage_period_start = &t +} + +// CurrentUsagePeriodStart returns the value of the "current_usage_period_start" field in the mutation. +func (m *EntitlementMutation) CurrentUsagePeriodStart() (r time.Time, exists bool) { + v := m.current_usage_period_start + if v == nil { + return + } + return *v, true +} + +// OldCurrentUsagePeriodStart returns the old "current_usage_period_start" field's value of the Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) OldCurrentUsagePeriodStart(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrentUsagePeriodStart is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrentUsagePeriodStart requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrentUsagePeriodStart: %w", err) + } + return oldValue.CurrentUsagePeriodStart, nil +} + +// ClearCurrentUsagePeriodStart clears the value of the "current_usage_period_start" field. +func (m *EntitlementMutation) ClearCurrentUsagePeriodStart() { + m.current_usage_period_start = nil + m.clearedFields[entitlement.FieldCurrentUsagePeriodStart] = struct{}{} +} + +// CurrentUsagePeriodStartCleared returns if the "current_usage_period_start" field was cleared in this mutation. +func (m *EntitlementMutation) CurrentUsagePeriodStartCleared() bool { + _, ok := m.clearedFields[entitlement.FieldCurrentUsagePeriodStart] + return ok +} + +// ResetCurrentUsagePeriodStart resets all changes to the "current_usage_period_start" field. +func (m *EntitlementMutation) ResetCurrentUsagePeriodStart() { + m.current_usage_period_start = nil + delete(m.clearedFields, entitlement.FieldCurrentUsagePeriodStart) +} + +// SetCurrentUsagePeriodEnd sets the "current_usage_period_end" field. +func (m *EntitlementMutation) SetCurrentUsagePeriodEnd(t time.Time) { + m.current_usage_period_end = &t +} + +// CurrentUsagePeriodEnd returns the value of the "current_usage_period_end" field in the mutation. +func (m *EntitlementMutation) CurrentUsagePeriodEnd() (r time.Time, exists bool) { + v := m.current_usage_period_end + if v == nil { + return + } + return *v, true +} + +// OldCurrentUsagePeriodEnd returns the old "current_usage_period_end" field's value of the Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) OldCurrentUsagePeriodEnd(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrentUsagePeriodEnd is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrentUsagePeriodEnd requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrentUsagePeriodEnd: %w", err) + } + return oldValue.CurrentUsagePeriodEnd, nil +} + +// ClearCurrentUsagePeriodEnd clears the value of the "current_usage_period_end" field. +func (m *EntitlementMutation) ClearCurrentUsagePeriodEnd() { + m.current_usage_period_end = nil + m.clearedFields[entitlement.FieldCurrentUsagePeriodEnd] = struct{}{} +} + +// CurrentUsagePeriodEndCleared returns if the "current_usage_period_end" field was cleared in this mutation. +func (m *EntitlementMutation) CurrentUsagePeriodEndCleared() bool { + _, ok := m.clearedFields[entitlement.FieldCurrentUsagePeriodEnd] + return ok +} + +// ResetCurrentUsagePeriodEnd resets all changes to the "current_usage_period_end" field. +func (m *EntitlementMutation) ResetCurrentUsagePeriodEnd() { + m.current_usage_period_end = nil + delete(m.clearedFields, entitlement.FieldCurrentUsagePeriodEnd) +} + +// SetAnnotations sets the "annotations" field. +func (m *EntitlementMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *EntitlementMutation) 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 Entitlement entity. +// If the Entitlement 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 *EntitlementMutation) 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 *EntitlementMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[entitlement.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *EntitlementMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[entitlement.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *EntitlementMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, entitlement.FieldAnnotations) +} + +// AddUsageResetIDs adds the "usage_reset" edge to the UsageReset entity by ids. +func (m *EntitlementMutation) AddUsageResetIDs(ids ...string) { + if m.usage_reset == nil { + m.usage_reset = make(map[string]struct{}) + } + for i := range ids { + m.usage_reset[ids[i]] = struct{}{} + } +} + +// ClearUsageReset clears the "usage_reset" edge to the UsageReset entity. +func (m *EntitlementMutation) ClearUsageReset() { + m.clearedusage_reset = true +} + +// UsageResetCleared reports if the "usage_reset" edge to the UsageReset entity was cleared. +func (m *EntitlementMutation) UsageResetCleared() bool { + return m.clearedusage_reset +} + +// RemoveUsageResetIDs removes the "usage_reset" edge to the UsageReset entity by IDs. +func (m *EntitlementMutation) RemoveUsageResetIDs(ids ...string) { + if m.removedusage_reset == nil { + m.removedusage_reset = make(map[string]struct{}) + } + for i := range ids { + delete(m.usage_reset, ids[i]) + m.removedusage_reset[ids[i]] = struct{}{} + } +} + +// RemovedUsageReset returns the removed IDs of the "usage_reset" edge to the UsageReset entity. +func (m *EntitlementMutation) RemovedUsageResetIDs() (ids []string) { + for id := range m.removedusage_reset { + ids = append(ids, id) + } + return +} + +// UsageResetIDs returns the "usage_reset" edge IDs in the mutation. +func (m *EntitlementMutation) UsageResetIDs() (ids []string) { + for id := range m.usage_reset { + ids = append(ids, id) + } + return +} + +// ResetUsageReset resets all changes to the "usage_reset" edge. +func (m *EntitlementMutation) ResetUsageReset() { + m.usage_reset = nil + m.clearedusage_reset = false + m.removedusage_reset = nil +} + +// AddGrantIDs adds the "grant" edge to the Grant entity by ids. +func (m *EntitlementMutation) AddGrantIDs(ids ...string) { + if m.grant == nil { + m.grant = make(map[string]struct{}) + } + for i := range ids { + m.grant[ids[i]] = struct{}{} + } +} + +// ClearGrant clears the "grant" edge to the Grant entity. +func (m *EntitlementMutation) ClearGrant() { + m.clearedgrant = true +} + +// GrantCleared reports if the "grant" edge to the Grant entity was cleared. +func (m *EntitlementMutation) GrantCleared() bool { + return m.clearedgrant +} + +// RemoveGrantIDs removes the "grant" edge to the Grant entity by IDs. +func (m *EntitlementMutation) RemoveGrantIDs(ids ...string) { + if m.removedgrant == nil { + m.removedgrant = make(map[string]struct{}) + } + for i := range ids { + delete(m.grant, ids[i]) + m.removedgrant[ids[i]] = struct{}{} + } +} + +// RemovedGrant returns the removed IDs of the "grant" edge to the Grant entity. +func (m *EntitlementMutation) RemovedGrantIDs() (ids []string) { + for id := range m.removedgrant { + ids = append(ids, id) + } + return +} + +// GrantIDs returns the "grant" edge IDs in the mutation. +func (m *EntitlementMutation) GrantIDs() (ids []string) { + for id := range m.grant { + ids = append(ids, id) + } + return +} + +// ResetGrant resets all changes to the "grant" edge. +func (m *EntitlementMutation) ResetGrant() { + m.grant = nil + m.clearedgrant = false + m.removedgrant = nil +} + +// AddBalanceSnapshotIDs adds the "balance_snapshot" edge to the BalanceSnapshot entity by ids. +func (m *EntitlementMutation) AddBalanceSnapshotIDs(ids ...int) { + if m.balance_snapshot == nil { + m.balance_snapshot = make(map[int]struct{}) + } + for i := range ids { + m.balance_snapshot[ids[i]] = struct{}{} + } +} + +// ClearBalanceSnapshot clears the "balance_snapshot" edge to the BalanceSnapshot entity. +func (m *EntitlementMutation) ClearBalanceSnapshot() { + m.clearedbalance_snapshot = true +} + +// BalanceSnapshotCleared reports if the "balance_snapshot" edge to the BalanceSnapshot entity was cleared. +func (m *EntitlementMutation) BalanceSnapshotCleared() bool { + return m.clearedbalance_snapshot +} + +// RemoveBalanceSnapshotIDs removes the "balance_snapshot" edge to the BalanceSnapshot entity by IDs. +func (m *EntitlementMutation) RemoveBalanceSnapshotIDs(ids ...int) { + if m.removedbalance_snapshot == nil { + m.removedbalance_snapshot = make(map[int]struct{}) + } + for i := range ids { + delete(m.balance_snapshot, ids[i]) + m.removedbalance_snapshot[ids[i]] = struct{}{} + } +} + +// RemovedBalanceSnapshot returns the removed IDs of the "balance_snapshot" edge to the BalanceSnapshot entity. +func (m *EntitlementMutation) RemovedBalanceSnapshotIDs() (ids []int) { + for id := range m.removedbalance_snapshot { + ids = append(ids, id) + } + return +} + +// BalanceSnapshotIDs returns the "balance_snapshot" edge IDs in the mutation. +func (m *EntitlementMutation) BalanceSnapshotIDs() (ids []int) { + for id := range m.balance_snapshot { + ids = append(ids, id) + } + return +} + +// ResetBalanceSnapshot resets all changes to the "balance_snapshot" edge. +func (m *EntitlementMutation) ResetBalanceSnapshot() { + m.balance_snapshot = nil + m.clearedbalance_snapshot = false + m.removedbalance_snapshot = nil +} + +// AddSubscriptionItemIDs adds the "subscription_item" edge to the SubscriptionItem entity by ids. +func (m *EntitlementMutation) AddSubscriptionItemIDs(ids ...string) { + if m.subscription_item == nil { + m.subscription_item = make(map[string]struct{}) + } + for i := range ids { + m.subscription_item[ids[i]] = struct{}{} + } +} + +// ClearSubscriptionItem clears the "subscription_item" edge to the SubscriptionItem entity. +func (m *EntitlementMutation) ClearSubscriptionItem() { + m.clearedsubscription_item = true +} + +// SubscriptionItemCleared reports if the "subscription_item" edge to the SubscriptionItem entity was cleared. +func (m *EntitlementMutation) SubscriptionItemCleared() bool { + return m.clearedsubscription_item +} + +// RemoveSubscriptionItemIDs removes the "subscription_item" edge to the SubscriptionItem entity by IDs. +func (m *EntitlementMutation) RemoveSubscriptionItemIDs(ids ...string) { + if m.removedsubscription_item == nil { + m.removedsubscription_item = make(map[string]struct{}) + } + for i := range ids { + delete(m.subscription_item, ids[i]) + m.removedsubscription_item[ids[i]] = struct{}{} + } +} + +// RemovedSubscriptionItem returns the removed IDs of the "subscription_item" edge to the SubscriptionItem entity. +func (m *EntitlementMutation) RemovedSubscriptionItemIDs() (ids []string) { + for id := range m.removedsubscription_item { + ids = append(ids, id) + } + return +} + +// SubscriptionItemIDs returns the "subscription_item" edge IDs in the mutation. +func (m *EntitlementMutation) SubscriptionItemIDs() (ids []string) { + for id := range m.subscription_item { + ids = append(ids, id) + } + return +} + +// ResetSubscriptionItem resets all changes to the "subscription_item" edge. +func (m *EntitlementMutation) ResetSubscriptionItem() { + m.subscription_item = nil + m.clearedsubscription_item = false + m.removedsubscription_item = nil +} + +// ClearFeature clears the "feature" edge to the Feature entity. +func (m *EntitlementMutation) ClearFeature() { + m.clearedfeature = true + m.clearedFields[entitlement.FieldFeatureID] = struct{}{} +} + +// FeatureCleared reports if the "feature" edge to the Feature entity was cleared. +func (m *EntitlementMutation) FeatureCleared() bool { + return m.clearedfeature +} + +// FeatureIDs returns the "feature" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// FeatureID instead. It exists only for internal usage by the builders. +func (m *EntitlementMutation) FeatureIDs() (ids []string) { + if id := m.feature; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetFeature resets all changes to the "feature" edge. +func (m *EntitlementMutation) ResetFeature() { + m.feature = nil + m.clearedfeature = false +} + +// ClearCustomer clears the "customer" edge to the Customer entity. +func (m *EntitlementMutation) ClearCustomer() { + m.clearedcustomer = true + m.clearedFields[entitlement.FieldCustomerID] = struct{}{} +} + +// CustomerCleared reports if the "customer" edge to the Customer entity was cleared. +func (m *EntitlementMutation) CustomerCleared() bool { + return m.clearedcustomer +} + +// CustomerIDs returns the "customer" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CustomerID instead. It exists only for internal usage by the builders. +func (m *EntitlementMutation) CustomerIDs() (ids []string) { + if id := m.customer; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCustomer resets all changes to the "customer" edge. +func (m *EntitlementMutation) ResetCustomer() { + m.customer = nil + m.clearedcustomer = false +} + +// Where appends a list predicates to the EntitlementMutation builder. +func (m *EntitlementMutation) Where(ps ...predicate.Entitlement) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the EntitlementMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *EntitlementMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Entitlement, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *EntitlementMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *EntitlementMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Entitlement). +func (m *EntitlementMutation) 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 *EntitlementMutation) Fields() []string { + fields := make([]string, 0, 22) + if m.namespace != nil { + fields = append(fields, entitlement.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, entitlement.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, entitlement.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, entitlement.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, entitlement.FieldDeletedAt) + } + if m.entitlement_type != nil { + fields = append(fields, entitlement.FieldEntitlementType) + } + if m.feature != nil { + fields = append(fields, entitlement.FieldFeatureID) + } + if m.active_from != nil { + fields = append(fields, entitlement.FieldActiveFrom) + } + if m.active_to != nil { + fields = append(fields, entitlement.FieldActiveTo) + } + if m.feature_key != nil { + fields = append(fields, entitlement.FieldFeatureKey) + } + if m.customer != nil { + fields = append(fields, entitlement.FieldCustomerID) + } + if m.measure_usage_from != nil { + fields = append(fields, entitlement.FieldMeasureUsageFrom) + } + if m.issue_after_reset != nil { + fields = append(fields, entitlement.FieldIssueAfterReset) + } + if m.issue_after_reset_priority != nil { + fields = append(fields, entitlement.FieldIssueAfterResetPriority) + } + if m.is_soft_limit != nil { + fields = append(fields, entitlement.FieldIsSoftLimit) + } + if m.preserve_overage_at_reset != nil { + fields = append(fields, entitlement.FieldPreserveOverageAtReset) + } + if m._config != nil { + fields = append(fields, entitlement.FieldConfig) + } + if m.usage_period_interval != nil { + fields = append(fields, entitlement.FieldUsagePeriodInterval) + } + if m.usage_period_anchor != nil { + fields = append(fields, entitlement.FieldUsagePeriodAnchor) + } + if m.current_usage_period_start != nil { + fields = append(fields, entitlement.FieldCurrentUsagePeriodStart) + } + if m.current_usage_period_end != nil { + fields = append(fields, entitlement.FieldCurrentUsagePeriodEnd) + } + if m.annotations != nil { + fields = append(fields, entitlement.FieldAnnotations) + } + 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 *EntitlementMutation) Field(name string) (ent.Value, bool) { + switch name { + case entitlement.FieldNamespace: + return m.Namespace() + case entitlement.FieldMetadata: + return m.Metadata() + case entitlement.FieldCreatedAt: + return m.CreatedAt() + case entitlement.FieldUpdatedAt: + return m.UpdatedAt() + case entitlement.FieldDeletedAt: + return m.DeletedAt() + case entitlement.FieldEntitlementType: + return m.EntitlementType() + case entitlement.FieldFeatureID: + return m.FeatureID() + case entitlement.FieldActiveFrom: + return m.ActiveFrom() + case entitlement.FieldActiveTo: + return m.ActiveTo() + case entitlement.FieldFeatureKey: + return m.FeatureKey() + case entitlement.FieldCustomerID: + return m.CustomerID() + case entitlement.FieldMeasureUsageFrom: + return m.MeasureUsageFrom() + case entitlement.FieldIssueAfterReset: + return m.IssueAfterReset() + case entitlement.FieldIssueAfterResetPriority: + return m.IssueAfterResetPriority() + case entitlement.FieldIsSoftLimit: + return m.IsSoftLimit() + case entitlement.FieldPreserveOverageAtReset: + return m.PreserveOverageAtReset() + case entitlement.FieldConfig: + return m.Config() + case entitlement.FieldUsagePeriodInterval: + return m.UsagePeriodInterval() + case entitlement.FieldUsagePeriodAnchor: + return m.UsagePeriodAnchor() + case entitlement.FieldCurrentUsagePeriodStart: + return m.CurrentUsagePeriodStart() + case entitlement.FieldCurrentUsagePeriodEnd: + return m.CurrentUsagePeriodEnd() + case entitlement.FieldAnnotations: + return m.Annotations() + } + 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 *EntitlementMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case entitlement.FieldNamespace: + return m.OldNamespace(ctx) + case entitlement.FieldMetadata: + return m.OldMetadata(ctx) + case entitlement.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case entitlement.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case entitlement.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case entitlement.FieldEntitlementType: + return m.OldEntitlementType(ctx) + case entitlement.FieldFeatureID: + return m.OldFeatureID(ctx) + case entitlement.FieldActiveFrom: + return m.OldActiveFrom(ctx) + case entitlement.FieldActiveTo: + return m.OldActiveTo(ctx) + case entitlement.FieldFeatureKey: + return m.OldFeatureKey(ctx) + case entitlement.FieldCustomerID: + return m.OldCustomerID(ctx) + case entitlement.FieldMeasureUsageFrom: + return m.OldMeasureUsageFrom(ctx) + case entitlement.FieldIssueAfterReset: + return m.OldIssueAfterReset(ctx) + case entitlement.FieldIssueAfterResetPriority: + return m.OldIssueAfterResetPriority(ctx) + case entitlement.FieldIsSoftLimit: + return m.OldIsSoftLimit(ctx) + case entitlement.FieldPreserveOverageAtReset: + return m.OldPreserveOverageAtReset(ctx) + case entitlement.FieldConfig: + return m.OldConfig(ctx) + case entitlement.FieldUsagePeriodInterval: + return m.OldUsagePeriodInterval(ctx) + case entitlement.FieldUsagePeriodAnchor: + return m.OldUsagePeriodAnchor(ctx) + case entitlement.FieldCurrentUsagePeriodStart: + return m.OldCurrentUsagePeriodStart(ctx) + case entitlement.FieldCurrentUsagePeriodEnd: + return m.OldCurrentUsagePeriodEnd(ctx) + case entitlement.FieldAnnotations: + return m.OldAnnotations(ctx) + } + return nil, fmt.Errorf("unknown Entitlement 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 *EntitlementMutation) SetField(name string, value ent.Value) error { + switch name { + case entitlement.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case entitlement.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case entitlement.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 entitlement.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 entitlement.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 entitlement.FieldEntitlementType: + v, ok := value.(entitlement.EntitlementType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEntitlementType(v) + return nil + case entitlement.FieldFeatureID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFeatureID(v) + return nil + case entitlement.FieldActiveFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetActiveFrom(v) + return nil + case entitlement.FieldActiveTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetActiveTo(v) + return nil + case entitlement.FieldFeatureKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFeatureKey(v) + return nil + case entitlement.FieldCustomerID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerID(v) + return nil + case entitlement.FieldMeasureUsageFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMeasureUsageFrom(v) + return nil + case entitlement.FieldIssueAfterReset: + v, ok := value.(float64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIssueAfterReset(v) + return nil + case entitlement.FieldIssueAfterResetPriority: + v, ok := value.(uint8) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIssueAfterResetPriority(v) + return nil + case entitlement.FieldIsSoftLimit: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIsSoftLimit(v) + return nil + case entitlement.FieldPreserveOverageAtReset: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPreserveOverageAtReset(v) + return nil + case entitlement.FieldConfig: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetConfig(v) + return nil + case entitlement.FieldUsagePeriodInterval: + v, ok := value.(datetime.ISODurationString) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUsagePeriodInterval(v) + return nil + case entitlement.FieldUsagePeriodAnchor: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUsagePeriodAnchor(v) + return nil + case entitlement.FieldCurrentUsagePeriodStart: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrentUsagePeriodStart(v) + return nil + case entitlement.FieldCurrentUsagePeriodEnd: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrentUsagePeriodEnd(v) + return nil + case entitlement.FieldAnnotations: + v, ok := value.(models.Annotations) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAnnotations(v) + return nil + } + return fmt.Errorf("unknown Entitlement field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *EntitlementMutation) AddedFields() []string { + var fields []string + if m.addissue_after_reset != nil { + fields = append(fields, entitlement.FieldIssueAfterReset) + } + if m.addissue_after_reset_priority != nil { + fields = append(fields, entitlement.FieldIssueAfterResetPriority) + } + return fields +} + +// 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 *EntitlementMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case entitlement.FieldIssueAfterReset: + return m.AddedIssueAfterReset() + case entitlement.FieldIssueAfterResetPriority: + return m.AddedIssueAfterResetPriority() + } + 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 *EntitlementMutation) AddField(name string, value ent.Value) error { + switch name { + case entitlement.FieldIssueAfterReset: + v, ok := value.(float64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddIssueAfterReset(v) + return nil + case entitlement.FieldIssueAfterResetPriority: + v, ok := value.(int8) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddIssueAfterResetPriority(v) + return nil + } + return fmt.Errorf("unknown Entitlement numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *EntitlementMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(entitlement.FieldMetadata) { + fields = append(fields, entitlement.FieldMetadata) + } + if m.FieldCleared(entitlement.FieldDeletedAt) { + fields = append(fields, entitlement.FieldDeletedAt) + } + if m.FieldCleared(entitlement.FieldActiveFrom) { + fields = append(fields, entitlement.FieldActiveFrom) + } + if m.FieldCleared(entitlement.FieldActiveTo) { + fields = append(fields, entitlement.FieldActiveTo) + } + if m.FieldCleared(entitlement.FieldMeasureUsageFrom) { + fields = append(fields, entitlement.FieldMeasureUsageFrom) + } + if m.FieldCleared(entitlement.FieldIssueAfterReset) { + fields = append(fields, entitlement.FieldIssueAfterReset) + } + if m.FieldCleared(entitlement.FieldIssueAfterResetPriority) { + fields = append(fields, entitlement.FieldIssueAfterResetPriority) + } + if m.FieldCleared(entitlement.FieldIsSoftLimit) { + fields = append(fields, entitlement.FieldIsSoftLimit) + } + if m.FieldCleared(entitlement.FieldPreserveOverageAtReset) { + fields = append(fields, entitlement.FieldPreserveOverageAtReset) + } + if m.FieldCleared(entitlement.FieldConfig) { + fields = append(fields, entitlement.FieldConfig) + } + if m.FieldCleared(entitlement.FieldUsagePeriodInterval) { + fields = append(fields, entitlement.FieldUsagePeriodInterval) + } + if m.FieldCleared(entitlement.FieldUsagePeriodAnchor) { + fields = append(fields, entitlement.FieldUsagePeriodAnchor) + } + if m.FieldCleared(entitlement.FieldCurrentUsagePeriodStart) { + fields = append(fields, entitlement.FieldCurrentUsagePeriodStart) + } + if m.FieldCleared(entitlement.FieldCurrentUsagePeriodEnd) { + fields = append(fields, entitlement.FieldCurrentUsagePeriodEnd) + } + if m.FieldCleared(entitlement.FieldAnnotations) { + fields = append(fields, entitlement.FieldAnnotations) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *EntitlementMutation) 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 *EntitlementMutation) ClearField(name string) error { + switch name { + case entitlement.FieldMetadata: + m.ClearMetadata() + return nil + case entitlement.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case entitlement.FieldActiveFrom: + m.ClearActiveFrom() + return nil + case entitlement.FieldActiveTo: + m.ClearActiveTo() + return nil + case entitlement.FieldMeasureUsageFrom: + m.ClearMeasureUsageFrom() + return nil + case entitlement.FieldIssueAfterReset: + m.ClearIssueAfterReset() + return nil + case entitlement.FieldIssueAfterResetPriority: + m.ClearIssueAfterResetPriority() + return nil + case entitlement.FieldIsSoftLimit: + m.ClearIsSoftLimit() + return nil + case entitlement.FieldPreserveOverageAtReset: + m.ClearPreserveOverageAtReset() + return nil + case entitlement.FieldConfig: + m.ClearConfig() + return nil + case entitlement.FieldUsagePeriodInterval: + m.ClearUsagePeriodInterval() + return nil + case entitlement.FieldUsagePeriodAnchor: + m.ClearUsagePeriodAnchor() + return nil + case entitlement.FieldCurrentUsagePeriodStart: + m.ClearCurrentUsagePeriodStart() + return nil + case entitlement.FieldCurrentUsagePeriodEnd: + m.ClearCurrentUsagePeriodEnd() + return nil + case entitlement.FieldAnnotations: + m.ClearAnnotations() + return nil + } + return fmt.Errorf("unknown Entitlement 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 *EntitlementMutation) ResetField(name string) error { + switch name { + case entitlement.FieldNamespace: + m.ResetNamespace() + return nil + case entitlement.FieldMetadata: + m.ResetMetadata() + return nil + case entitlement.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case entitlement.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case entitlement.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case entitlement.FieldEntitlementType: + m.ResetEntitlementType() + return nil + case entitlement.FieldFeatureID: + m.ResetFeatureID() + return nil + case entitlement.FieldActiveFrom: + m.ResetActiveFrom() + return nil + case entitlement.FieldActiveTo: + m.ResetActiveTo() + return nil + case entitlement.FieldFeatureKey: + m.ResetFeatureKey() + return nil + case entitlement.FieldCustomerID: + m.ResetCustomerID() + return nil + case entitlement.FieldMeasureUsageFrom: + m.ResetMeasureUsageFrom() + return nil + case entitlement.FieldIssueAfterReset: + m.ResetIssueAfterReset() + return nil + case entitlement.FieldIssueAfterResetPriority: + m.ResetIssueAfterResetPriority() + return nil + case entitlement.FieldIsSoftLimit: + m.ResetIsSoftLimit() + return nil + case entitlement.FieldPreserveOverageAtReset: + m.ResetPreserveOverageAtReset() + return nil + case entitlement.FieldConfig: + m.ResetConfig() + return nil + case entitlement.FieldUsagePeriodInterval: + m.ResetUsagePeriodInterval() + return nil + case entitlement.FieldUsagePeriodAnchor: + m.ResetUsagePeriodAnchor() + return nil + case entitlement.FieldCurrentUsagePeriodStart: + m.ResetCurrentUsagePeriodStart() + return nil + case entitlement.FieldCurrentUsagePeriodEnd: + m.ResetCurrentUsagePeriodEnd() + return nil + case entitlement.FieldAnnotations: + m.ResetAnnotations() + return nil + } + return fmt.Errorf("unknown Entitlement field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *EntitlementMutation) AddedEdges() []string { + edges := make([]string, 0, 6) + if m.usage_reset != nil { + edges = append(edges, entitlement.EdgeUsageReset) + } + if m.grant != nil { + edges = append(edges, entitlement.EdgeGrant) + } + if m.balance_snapshot != nil { + edges = append(edges, entitlement.EdgeBalanceSnapshot) + } + if m.subscription_item != nil { + edges = append(edges, entitlement.EdgeSubscriptionItem) + } + if m.feature != nil { + edges = append(edges, entitlement.EdgeFeature) + } + if m.customer != nil { + edges = append(edges, entitlement.EdgeCustomer) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *EntitlementMutation) AddedIDs(name string) []ent.Value { + switch name { + case entitlement.EdgeUsageReset: + ids := make([]ent.Value, 0, len(m.usage_reset)) + for id := range m.usage_reset { + ids = append(ids, id) + } + return ids + case entitlement.EdgeGrant: + ids := make([]ent.Value, 0, len(m.grant)) + for id := range m.grant { + ids = append(ids, id) + } + return ids + case entitlement.EdgeBalanceSnapshot: + ids := make([]ent.Value, 0, len(m.balance_snapshot)) + for id := range m.balance_snapshot { + ids = append(ids, id) + } + return ids + case entitlement.EdgeSubscriptionItem: + ids := make([]ent.Value, 0, len(m.subscription_item)) + for id := range m.subscription_item { + ids = append(ids, id) + } + return ids + case entitlement.EdgeFeature: + if id := m.feature; id != nil { + return []ent.Value{*id} + } + case entitlement.EdgeCustomer: + if id := m.customer; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *EntitlementMutation) RemovedEdges() []string { + edges := make([]string, 0, 6) + if m.removedusage_reset != nil { + edges = append(edges, entitlement.EdgeUsageReset) + } + if m.removedgrant != nil { + edges = append(edges, entitlement.EdgeGrant) + } + if m.removedbalance_snapshot != nil { + edges = append(edges, entitlement.EdgeBalanceSnapshot) + } + if m.removedsubscription_item != nil { + edges = append(edges, entitlement.EdgeSubscriptionItem) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *EntitlementMutation) RemovedIDs(name string) []ent.Value { + switch name { + case entitlement.EdgeUsageReset: + ids := make([]ent.Value, 0, len(m.removedusage_reset)) + for id := range m.removedusage_reset { + ids = append(ids, id) + } + return ids + case entitlement.EdgeGrant: + ids := make([]ent.Value, 0, len(m.removedgrant)) + for id := range m.removedgrant { + ids = append(ids, id) + } + return ids + case entitlement.EdgeBalanceSnapshot: + ids := make([]ent.Value, 0, len(m.removedbalance_snapshot)) + for id := range m.removedbalance_snapshot { + ids = append(ids, id) + } + return ids + case entitlement.EdgeSubscriptionItem: + ids := make([]ent.Value, 0, len(m.removedsubscription_item)) + for id := range m.removedsubscription_item { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *EntitlementMutation) ClearedEdges() []string { + edges := make([]string, 0, 6) + if m.clearedusage_reset { + edges = append(edges, entitlement.EdgeUsageReset) + } + if m.clearedgrant { + edges = append(edges, entitlement.EdgeGrant) + } + if m.clearedbalance_snapshot { + edges = append(edges, entitlement.EdgeBalanceSnapshot) + } + if m.clearedsubscription_item { + edges = append(edges, entitlement.EdgeSubscriptionItem) + } + if m.clearedfeature { + edges = append(edges, entitlement.EdgeFeature) + } + if m.clearedcustomer { + edges = append(edges, entitlement.EdgeCustomer) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *EntitlementMutation) EdgeCleared(name string) bool { + switch name { + case entitlement.EdgeUsageReset: + return m.clearedusage_reset + case entitlement.EdgeGrant: + return m.clearedgrant + case entitlement.EdgeBalanceSnapshot: + return m.clearedbalance_snapshot + case entitlement.EdgeSubscriptionItem: + return m.clearedsubscription_item + case entitlement.EdgeFeature: + return m.clearedfeature + case entitlement.EdgeCustomer: + return m.clearedcustomer + } + 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 *EntitlementMutation) ClearEdge(name string) error { + switch name { + case entitlement.EdgeFeature: + m.ClearFeature() + return nil + case entitlement.EdgeCustomer: + m.ClearCustomer() + return nil + } + return fmt.Errorf("unknown Entitlement 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 *EntitlementMutation) ResetEdge(name string) error { + switch name { + case entitlement.EdgeUsageReset: + m.ResetUsageReset() + return nil + case entitlement.EdgeGrant: + m.ResetGrant() + return nil + case entitlement.EdgeBalanceSnapshot: + m.ResetBalanceSnapshot() + return nil + case entitlement.EdgeSubscriptionItem: + m.ResetSubscriptionItem() + return nil + case entitlement.EdgeFeature: + m.ResetFeature() + return nil + case entitlement.EdgeCustomer: + m.ResetCustomer() + return nil + } + return fmt.Errorf("unknown Entitlement edge %s", name) +} + +// FeatureMutation represents an operation that mutates the Feature nodes in the graph. +type FeatureMutation struct { + config + op Op + typ string + id *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + metadata *map[string]string + namespace *string + name *string + description *string + key *string + meter_slug *string + meter_group_by_filters *map[string]string + advanced_meter_group_by_filters *feature.MeterGroupByFilters + unit_cost_type *string + unit_cost_manual_amount *alpacadecimal.Decimal + unit_cost_llm_provider_property *string + unit_cost_llm_provider *string + unit_cost_llm_model_property *string + unit_cost_llm_model *string + unit_cost_llm_token_type_property *string + unit_cost_llm_token_type *string + archived_at *time.Time + clearedFields map[string]struct{} + entitlement map[string]struct{} + removedentitlement map[string]struct{} + clearedentitlement bool + ratecard map[string]struct{} + removedratecard map[string]struct{} + clearedratecard bool + addon_ratecard map[string]struct{} + removedaddon_ratecard map[string]struct{} + clearedaddon_ratecard bool + usage_based_charges map[string]struct{} + removedusage_based_charges map[string]struct{} + clearedusage_based_charges bool + usage_based_runs map[string]struct{} + removedusage_based_runs map[string]struct{} + clearedusage_based_runs bool + flat_fee_charges map[string]struct{} + removedflat_fee_charges map[string]struct{} + clearedflat_fee_charges bool + meter *string + clearedmeter bool + done bool + oldValue func(context.Context) (*Feature, error) + predicates []predicate.Feature +} + +var _ ent.Mutation = (*FeatureMutation)(nil) + +// featureOption allows management of the mutation configuration using functional options. +type featureOption func(*FeatureMutation) + +// newFeatureMutation creates new mutation for the Feature entity. +func newFeatureMutation(c config, op Op, opts ...featureOption) *FeatureMutation { + m := &FeatureMutation{ + config: c, + op: op, + typ: TypeFeature, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withFeatureID sets the ID field of the mutation. +func withFeatureID(id string) featureOption { + return func(m *FeatureMutation) { + var ( + err error + once sync.Once + value *Feature + ) + m.oldValue = func(ctx context.Context) (*Feature, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Feature.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withFeature sets the old Feature of the mutation. +func withFeature(node *Feature) featureOption { + return func(m *FeatureMutation) { + m.oldValue = func(context.Context) (*Feature, 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 FeatureMutation) 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 FeatureMutation) 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 Feature entities. +func (m *FeatureMutation) 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 *FeatureMutation) 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 *FeatureMutation) 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().Feature.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetCreatedAt sets the "created_at" field. +func (m *FeatureMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *FeatureMutation) 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 Feature entity. +// If the Feature 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 *FeatureMutation) 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 *FeatureMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *FeatureMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *FeatureMutation) 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 Feature entity. +// If the Feature 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 *FeatureMutation) 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 *FeatureMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *FeatureMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *FeatureMutation) 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 Feature entity. +// If the Feature 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 *FeatureMutation) 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 *FeatureMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[dbfeature.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *FeatureMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[dbfeature.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *FeatureMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, dbfeature.FieldDeletedAt) +} + +// SetMetadata sets the "metadata" field. +func (m *FeatureMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *FeatureMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the Feature entity. +// If the Feature 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 *FeatureMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *FeatureMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[dbfeature.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *FeatureMutation) MetadataCleared() bool { + _, ok := m.clearedFields[dbfeature.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *FeatureMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, dbfeature.FieldMetadata) +} + +// SetNamespace sets the "namespace" field. +func (m *FeatureMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *FeatureMutation) 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 Feature entity. +// If the Feature 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 *FeatureMutation) 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 *FeatureMutation) ResetNamespace() { + m.namespace = nil +} + +// SetName sets the "name" field. +func (m *FeatureMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *FeatureMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the Feature entity. +// If the Feature 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 *FeatureMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *FeatureMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *FeatureMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *FeatureMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the Feature entity. +// If the Feature 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 *FeatureMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *FeatureMutation) ClearDescription() { + m.description = nil + m.clearedFields[dbfeature.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *FeatureMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[dbfeature.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *FeatureMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, dbfeature.FieldDescription) +} + +// SetKey sets the "key" field. +func (m *FeatureMutation) SetKey(s string) { + m.key = &s +} + +// Key returns the value of the "key" field in the mutation. +func (m *FeatureMutation) Key() (r string, exists bool) { + v := m.key + if v == nil { + return + } + return *v, true +} + +// OldKey returns the old "key" field's value of the Feature entity. +// If the Feature 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 *FeatureMutation) OldKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldKey: %w", err) + } + return oldValue.Key, nil +} + +// ResetKey resets all changes to the "key" field. +func (m *FeatureMutation) ResetKey() { + m.key = nil +} + +// SetMeterSlug sets the "meter_slug" field. +func (m *FeatureMutation) SetMeterSlug(s string) { + m.meter_slug = &s +} + +// MeterSlug returns the value of the "meter_slug" field in the mutation. +func (m *FeatureMutation) MeterSlug() (r string, exists bool) { + v := m.meter_slug + if v == nil { + return + } + return *v, true +} + +// OldMeterSlug returns the old "meter_slug" field's value of the Feature entity. +// If the Feature 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 *FeatureMutation) OldMeterSlug(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMeterSlug is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMeterSlug requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMeterSlug: %w", err) + } + return oldValue.MeterSlug, nil +} + +// ClearMeterSlug clears the value of the "meter_slug" field. +func (m *FeatureMutation) ClearMeterSlug() { + m.meter_slug = nil + m.clearedFields[dbfeature.FieldMeterSlug] = struct{}{} +} + +// MeterSlugCleared returns if the "meter_slug" field was cleared in this mutation. +func (m *FeatureMutation) MeterSlugCleared() bool { + _, ok := m.clearedFields[dbfeature.FieldMeterSlug] + return ok +} + +// ResetMeterSlug resets all changes to the "meter_slug" field. +func (m *FeatureMutation) ResetMeterSlug() { + m.meter_slug = nil + delete(m.clearedFields, dbfeature.FieldMeterSlug) +} + +// SetMeterID sets the "meter_id" field. +func (m *FeatureMutation) SetMeterID(s string) { + m.meter = &s +} + +// MeterID returns the value of the "meter_id" field in the mutation. +func (m *FeatureMutation) MeterID() (r string, exists bool) { + v := m.meter + if v == nil { + return + } + return *v, true +} + +// OldMeterID returns the old "meter_id" field's value of the Feature entity. +// If the Feature 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 *FeatureMutation) OldMeterID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMeterID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMeterID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMeterID: %w", err) + } + return oldValue.MeterID, nil +} + +// ClearMeterID clears the value of the "meter_id" field. +func (m *FeatureMutation) ClearMeterID() { + m.meter = nil + m.clearedFields[dbfeature.FieldMeterID] = struct{}{} +} + +// MeterIDCleared returns if the "meter_id" field was cleared in this mutation. +func (m *FeatureMutation) MeterIDCleared() bool { + _, ok := m.clearedFields[dbfeature.FieldMeterID] + return ok +} + +// ResetMeterID resets all changes to the "meter_id" field. +func (m *FeatureMutation) ResetMeterID() { + m.meter = nil + delete(m.clearedFields, dbfeature.FieldMeterID) +} + +// SetMeterGroupByFilters sets the "meter_group_by_filters" field. +func (m *FeatureMutation) SetMeterGroupByFilters(value map[string]string) { + m.meter_group_by_filters = &value +} + +// MeterGroupByFilters returns the value of the "meter_group_by_filters" field in the mutation. +func (m *FeatureMutation) MeterGroupByFilters() (r map[string]string, exists bool) { + v := m.meter_group_by_filters + if v == nil { + return + } + return *v, true +} + +// OldMeterGroupByFilters returns the old "meter_group_by_filters" field's value of the Feature entity. +// If the Feature 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 *FeatureMutation) OldMeterGroupByFilters(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMeterGroupByFilters is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMeterGroupByFilters requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMeterGroupByFilters: %w", err) + } + return oldValue.MeterGroupByFilters, nil +} + +// ClearMeterGroupByFilters clears the value of the "meter_group_by_filters" field. +func (m *FeatureMutation) ClearMeterGroupByFilters() { + m.meter_group_by_filters = nil + m.clearedFields[dbfeature.FieldMeterGroupByFilters] = struct{}{} +} + +// MeterGroupByFiltersCleared returns if the "meter_group_by_filters" field was cleared in this mutation. +func (m *FeatureMutation) MeterGroupByFiltersCleared() bool { + _, ok := m.clearedFields[dbfeature.FieldMeterGroupByFilters] + return ok +} + +// ResetMeterGroupByFilters resets all changes to the "meter_group_by_filters" field. +func (m *FeatureMutation) ResetMeterGroupByFilters() { + m.meter_group_by_filters = nil + delete(m.clearedFields, dbfeature.FieldMeterGroupByFilters) +} + +// SetAdvancedMeterGroupByFilters sets the "advanced_meter_group_by_filters" field. +func (m *FeatureMutation) SetAdvancedMeterGroupByFilters(fgbf feature.MeterGroupByFilters) { + m.advanced_meter_group_by_filters = &fgbf +} + +// AdvancedMeterGroupByFilters returns the value of the "advanced_meter_group_by_filters" field in the mutation. +func (m *FeatureMutation) AdvancedMeterGroupByFilters() (r feature.MeterGroupByFilters, exists bool) { + v := m.advanced_meter_group_by_filters + if v == nil { + return + } + return *v, true +} + +// OldAdvancedMeterGroupByFilters returns the old "advanced_meter_group_by_filters" field's value of the Feature entity. +// If the Feature 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 *FeatureMutation) OldAdvancedMeterGroupByFilters(ctx context.Context) (v feature.MeterGroupByFilters, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAdvancedMeterGroupByFilters is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAdvancedMeterGroupByFilters requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAdvancedMeterGroupByFilters: %w", err) + } + return oldValue.AdvancedMeterGroupByFilters, nil +} + +// ClearAdvancedMeterGroupByFilters clears the value of the "advanced_meter_group_by_filters" field. +func (m *FeatureMutation) ClearAdvancedMeterGroupByFilters() { + m.advanced_meter_group_by_filters = nil + m.clearedFields[dbfeature.FieldAdvancedMeterGroupByFilters] = struct{}{} +} + +// AdvancedMeterGroupByFiltersCleared returns if the "advanced_meter_group_by_filters" field was cleared in this mutation. +func (m *FeatureMutation) AdvancedMeterGroupByFiltersCleared() bool { + _, ok := m.clearedFields[dbfeature.FieldAdvancedMeterGroupByFilters] + return ok +} + +// ResetAdvancedMeterGroupByFilters resets all changes to the "advanced_meter_group_by_filters" field. +func (m *FeatureMutation) ResetAdvancedMeterGroupByFilters() { + m.advanced_meter_group_by_filters = nil + delete(m.clearedFields, dbfeature.FieldAdvancedMeterGroupByFilters) +} + +// SetUnitCostType sets the "unit_cost_type" field. +func (m *FeatureMutation) SetUnitCostType(s string) { + m.unit_cost_type = &s +} + +// UnitCostType returns the value of the "unit_cost_type" field in the mutation. +func (m *FeatureMutation) UnitCostType() (r string, exists bool) { + v := m.unit_cost_type + if v == nil { + return + } + return *v, true +} + +// OldUnitCostType returns the old "unit_cost_type" field's value of the Feature entity. +// If the Feature 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 *FeatureMutation) OldUnitCostType(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUnitCostType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUnitCostType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUnitCostType: %w", err) + } + return oldValue.UnitCostType, nil +} + +// ClearUnitCostType clears the value of the "unit_cost_type" field. +func (m *FeatureMutation) ClearUnitCostType() { + m.unit_cost_type = nil + m.clearedFields[dbfeature.FieldUnitCostType] = struct{}{} +} + +// UnitCostTypeCleared returns if the "unit_cost_type" field was cleared in this mutation. +func (m *FeatureMutation) UnitCostTypeCleared() bool { + _, ok := m.clearedFields[dbfeature.FieldUnitCostType] + return ok +} + +// ResetUnitCostType resets all changes to the "unit_cost_type" field. +func (m *FeatureMutation) ResetUnitCostType() { + m.unit_cost_type = nil + delete(m.clearedFields, dbfeature.FieldUnitCostType) +} + +// SetUnitCostManualAmount sets the "unit_cost_manual_amount" field. +func (m *FeatureMutation) SetUnitCostManualAmount(a alpacadecimal.Decimal) { + m.unit_cost_manual_amount = &a +} + +// UnitCostManualAmount returns the value of the "unit_cost_manual_amount" field in the mutation. +func (m *FeatureMutation) UnitCostManualAmount() (r alpacadecimal.Decimal, exists bool) { + v := m.unit_cost_manual_amount + if v == nil { + return + } + return *v, true +} + +// OldUnitCostManualAmount returns the old "unit_cost_manual_amount" field's value of the Feature entity. +// If the Feature 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 *FeatureMutation) OldUnitCostManualAmount(ctx context.Context) (v *alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUnitCostManualAmount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUnitCostManualAmount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUnitCostManualAmount: %w", err) + } + return oldValue.UnitCostManualAmount, nil +} + +// ClearUnitCostManualAmount clears the value of the "unit_cost_manual_amount" field. +func (m *FeatureMutation) ClearUnitCostManualAmount() { + m.unit_cost_manual_amount = nil + m.clearedFields[dbfeature.FieldUnitCostManualAmount] = struct{}{} +} + +// UnitCostManualAmountCleared returns if the "unit_cost_manual_amount" field was cleared in this mutation. +func (m *FeatureMutation) UnitCostManualAmountCleared() bool { + _, ok := m.clearedFields[dbfeature.FieldUnitCostManualAmount] + return ok +} + +// ResetUnitCostManualAmount resets all changes to the "unit_cost_manual_amount" field. +func (m *FeatureMutation) ResetUnitCostManualAmount() { + m.unit_cost_manual_amount = nil + delete(m.clearedFields, dbfeature.FieldUnitCostManualAmount) +} + +// SetUnitCostLlmProviderProperty sets the "unit_cost_llm_provider_property" field. +func (m *FeatureMutation) SetUnitCostLlmProviderProperty(s string) { + m.unit_cost_llm_provider_property = &s +} + +// UnitCostLlmProviderProperty returns the value of the "unit_cost_llm_provider_property" field in the mutation. +func (m *FeatureMutation) UnitCostLlmProviderProperty() (r string, exists bool) { + v := m.unit_cost_llm_provider_property + if v == nil { + return + } + return *v, true +} + +// OldUnitCostLlmProviderProperty returns the old "unit_cost_llm_provider_property" field's value of the Feature entity. +// If the Feature 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 *FeatureMutation) OldUnitCostLlmProviderProperty(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUnitCostLlmProviderProperty is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUnitCostLlmProviderProperty requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUnitCostLlmProviderProperty: %w", err) + } + return oldValue.UnitCostLlmProviderProperty, nil +} + +// ClearUnitCostLlmProviderProperty clears the value of the "unit_cost_llm_provider_property" field. +func (m *FeatureMutation) ClearUnitCostLlmProviderProperty() { + m.unit_cost_llm_provider_property = nil + m.clearedFields[dbfeature.FieldUnitCostLlmProviderProperty] = struct{}{} +} + +// UnitCostLlmProviderPropertyCleared returns if the "unit_cost_llm_provider_property" field was cleared in this mutation. +func (m *FeatureMutation) UnitCostLlmProviderPropertyCleared() bool { + _, ok := m.clearedFields[dbfeature.FieldUnitCostLlmProviderProperty] + return ok +} + +// ResetUnitCostLlmProviderProperty resets all changes to the "unit_cost_llm_provider_property" field. +func (m *FeatureMutation) ResetUnitCostLlmProviderProperty() { + m.unit_cost_llm_provider_property = nil + delete(m.clearedFields, dbfeature.FieldUnitCostLlmProviderProperty) +} + +// SetUnitCostLlmProvider sets the "unit_cost_llm_provider" field. +func (m *FeatureMutation) SetUnitCostLlmProvider(s string) { + m.unit_cost_llm_provider = &s +} + +// UnitCostLlmProvider returns the value of the "unit_cost_llm_provider" field in the mutation. +func (m *FeatureMutation) UnitCostLlmProvider() (r string, exists bool) { + v := m.unit_cost_llm_provider + if v == nil { + return + } + return *v, true +} + +// OldUnitCostLlmProvider returns the old "unit_cost_llm_provider" field's value of the Feature entity. +// If the Feature 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 *FeatureMutation) OldUnitCostLlmProvider(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUnitCostLlmProvider is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUnitCostLlmProvider requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUnitCostLlmProvider: %w", err) + } + return oldValue.UnitCostLlmProvider, nil +} + +// ClearUnitCostLlmProvider clears the value of the "unit_cost_llm_provider" field. +func (m *FeatureMutation) ClearUnitCostLlmProvider() { + m.unit_cost_llm_provider = nil + m.clearedFields[dbfeature.FieldUnitCostLlmProvider] = struct{}{} +} + +// UnitCostLlmProviderCleared returns if the "unit_cost_llm_provider" field was cleared in this mutation. +func (m *FeatureMutation) UnitCostLlmProviderCleared() bool { + _, ok := m.clearedFields[dbfeature.FieldUnitCostLlmProvider] + return ok +} + +// ResetUnitCostLlmProvider resets all changes to the "unit_cost_llm_provider" field. +func (m *FeatureMutation) ResetUnitCostLlmProvider() { + m.unit_cost_llm_provider = nil + delete(m.clearedFields, dbfeature.FieldUnitCostLlmProvider) +} + +// SetUnitCostLlmModelProperty sets the "unit_cost_llm_model_property" field. +func (m *FeatureMutation) SetUnitCostLlmModelProperty(s string) { + m.unit_cost_llm_model_property = &s +} + +// UnitCostLlmModelProperty returns the value of the "unit_cost_llm_model_property" field in the mutation. +func (m *FeatureMutation) UnitCostLlmModelProperty() (r string, exists bool) { + v := m.unit_cost_llm_model_property + if v == nil { + return + } + return *v, true +} + +// OldUnitCostLlmModelProperty returns the old "unit_cost_llm_model_property" field's value of the Feature entity. +// If the Feature 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 *FeatureMutation) OldUnitCostLlmModelProperty(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUnitCostLlmModelProperty is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUnitCostLlmModelProperty requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUnitCostLlmModelProperty: %w", err) + } + return oldValue.UnitCostLlmModelProperty, nil +} + +// ClearUnitCostLlmModelProperty clears the value of the "unit_cost_llm_model_property" field. +func (m *FeatureMutation) ClearUnitCostLlmModelProperty() { + m.unit_cost_llm_model_property = nil + m.clearedFields[dbfeature.FieldUnitCostLlmModelProperty] = struct{}{} +} + +// UnitCostLlmModelPropertyCleared returns if the "unit_cost_llm_model_property" field was cleared in this mutation. +func (m *FeatureMutation) UnitCostLlmModelPropertyCleared() bool { + _, ok := m.clearedFields[dbfeature.FieldUnitCostLlmModelProperty] + return ok +} + +// ResetUnitCostLlmModelProperty resets all changes to the "unit_cost_llm_model_property" field. +func (m *FeatureMutation) ResetUnitCostLlmModelProperty() { + m.unit_cost_llm_model_property = nil + delete(m.clearedFields, dbfeature.FieldUnitCostLlmModelProperty) +} + +// SetUnitCostLlmModel sets the "unit_cost_llm_model" field. +func (m *FeatureMutation) SetUnitCostLlmModel(s string) { + m.unit_cost_llm_model = &s +} + +// UnitCostLlmModel returns the value of the "unit_cost_llm_model" field in the mutation. +func (m *FeatureMutation) UnitCostLlmModel() (r string, exists bool) { + v := m.unit_cost_llm_model + if v == nil { + return + } + return *v, true +} + +// OldUnitCostLlmModel returns the old "unit_cost_llm_model" field's value of the Feature entity. +// If the Feature 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 *FeatureMutation) OldUnitCostLlmModel(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUnitCostLlmModel is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUnitCostLlmModel requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUnitCostLlmModel: %w", err) + } + return oldValue.UnitCostLlmModel, nil +} + +// ClearUnitCostLlmModel clears the value of the "unit_cost_llm_model" field. +func (m *FeatureMutation) ClearUnitCostLlmModel() { + m.unit_cost_llm_model = nil + m.clearedFields[dbfeature.FieldUnitCostLlmModel] = struct{}{} +} + +// UnitCostLlmModelCleared returns if the "unit_cost_llm_model" field was cleared in this mutation. +func (m *FeatureMutation) UnitCostLlmModelCleared() bool { + _, ok := m.clearedFields[dbfeature.FieldUnitCostLlmModel] + return ok +} + +// ResetUnitCostLlmModel resets all changes to the "unit_cost_llm_model" field. +func (m *FeatureMutation) ResetUnitCostLlmModel() { + m.unit_cost_llm_model = nil + delete(m.clearedFields, dbfeature.FieldUnitCostLlmModel) +} + +// SetUnitCostLlmTokenTypeProperty sets the "unit_cost_llm_token_type_property" field. +func (m *FeatureMutation) SetUnitCostLlmTokenTypeProperty(s string) { + m.unit_cost_llm_token_type_property = &s +} + +// UnitCostLlmTokenTypeProperty returns the value of the "unit_cost_llm_token_type_property" field in the mutation. +func (m *FeatureMutation) UnitCostLlmTokenTypeProperty() (r string, exists bool) { + v := m.unit_cost_llm_token_type_property + if v == nil { + return + } + return *v, true +} + +// OldUnitCostLlmTokenTypeProperty returns the old "unit_cost_llm_token_type_property" field's value of the Feature entity. +// If the Feature 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 *FeatureMutation) OldUnitCostLlmTokenTypeProperty(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUnitCostLlmTokenTypeProperty is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUnitCostLlmTokenTypeProperty requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUnitCostLlmTokenTypeProperty: %w", err) + } + return oldValue.UnitCostLlmTokenTypeProperty, nil +} + +// ClearUnitCostLlmTokenTypeProperty clears the value of the "unit_cost_llm_token_type_property" field. +func (m *FeatureMutation) ClearUnitCostLlmTokenTypeProperty() { + m.unit_cost_llm_token_type_property = nil + m.clearedFields[dbfeature.FieldUnitCostLlmTokenTypeProperty] = struct{}{} +} + +// UnitCostLlmTokenTypePropertyCleared returns if the "unit_cost_llm_token_type_property" field was cleared in this mutation. +func (m *FeatureMutation) UnitCostLlmTokenTypePropertyCleared() bool { + _, ok := m.clearedFields[dbfeature.FieldUnitCostLlmTokenTypeProperty] + return ok +} + +// ResetUnitCostLlmTokenTypeProperty resets all changes to the "unit_cost_llm_token_type_property" field. +func (m *FeatureMutation) ResetUnitCostLlmTokenTypeProperty() { + m.unit_cost_llm_token_type_property = nil + delete(m.clearedFields, dbfeature.FieldUnitCostLlmTokenTypeProperty) +} + +// SetUnitCostLlmTokenType sets the "unit_cost_llm_token_type" field. +func (m *FeatureMutation) SetUnitCostLlmTokenType(s string) { + m.unit_cost_llm_token_type = &s +} + +// UnitCostLlmTokenType returns the value of the "unit_cost_llm_token_type" field in the mutation. +func (m *FeatureMutation) UnitCostLlmTokenType() (r string, exists bool) { + v := m.unit_cost_llm_token_type + if v == nil { + return + } + return *v, true +} + +// OldUnitCostLlmTokenType returns the old "unit_cost_llm_token_type" field's value of the Feature entity. +// If the Feature 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 *FeatureMutation) OldUnitCostLlmTokenType(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUnitCostLlmTokenType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUnitCostLlmTokenType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUnitCostLlmTokenType: %w", err) + } + return oldValue.UnitCostLlmTokenType, nil +} + +// ClearUnitCostLlmTokenType clears the value of the "unit_cost_llm_token_type" field. +func (m *FeatureMutation) ClearUnitCostLlmTokenType() { + m.unit_cost_llm_token_type = nil + m.clearedFields[dbfeature.FieldUnitCostLlmTokenType] = struct{}{} +} + +// UnitCostLlmTokenTypeCleared returns if the "unit_cost_llm_token_type" field was cleared in this mutation. +func (m *FeatureMutation) UnitCostLlmTokenTypeCleared() bool { + _, ok := m.clearedFields[dbfeature.FieldUnitCostLlmTokenType] + return ok +} + +// ResetUnitCostLlmTokenType resets all changes to the "unit_cost_llm_token_type" field. +func (m *FeatureMutation) ResetUnitCostLlmTokenType() { + m.unit_cost_llm_token_type = nil + delete(m.clearedFields, dbfeature.FieldUnitCostLlmTokenType) +} + +// SetArchivedAt sets the "archived_at" field. +func (m *FeatureMutation) SetArchivedAt(t time.Time) { + m.archived_at = &t +} + +// ArchivedAt returns the value of the "archived_at" field in the mutation. +func (m *FeatureMutation) ArchivedAt() (r time.Time, exists bool) { + v := m.archived_at + if v == nil { + return + } + return *v, true +} + +// OldArchivedAt returns the old "archived_at" field's value of the Feature entity. +// If the Feature 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 *FeatureMutation) OldArchivedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldArchivedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldArchivedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldArchivedAt: %w", err) + } + return oldValue.ArchivedAt, nil +} + +// ClearArchivedAt clears the value of the "archived_at" field. +func (m *FeatureMutation) ClearArchivedAt() { + m.archived_at = nil + m.clearedFields[dbfeature.FieldArchivedAt] = struct{}{} +} + +// ArchivedAtCleared returns if the "archived_at" field was cleared in this mutation. +func (m *FeatureMutation) ArchivedAtCleared() bool { + _, ok := m.clearedFields[dbfeature.FieldArchivedAt] + return ok +} + +// ResetArchivedAt resets all changes to the "archived_at" field. +func (m *FeatureMutation) ResetArchivedAt() { + m.archived_at = nil + delete(m.clearedFields, dbfeature.FieldArchivedAt) +} + +// AddEntitlementIDs adds the "entitlement" edge to the Entitlement entity by ids. +func (m *FeatureMutation) AddEntitlementIDs(ids ...string) { + if m.entitlement == nil { + m.entitlement = make(map[string]struct{}) + } + for i := range ids { + m.entitlement[ids[i]] = struct{}{} + } +} + +// ClearEntitlement clears the "entitlement" edge to the Entitlement entity. +func (m *FeatureMutation) ClearEntitlement() { + m.clearedentitlement = true +} + +// EntitlementCleared reports if the "entitlement" edge to the Entitlement entity was cleared. +func (m *FeatureMutation) EntitlementCleared() bool { + return m.clearedentitlement +} + +// RemoveEntitlementIDs removes the "entitlement" edge to the Entitlement entity by IDs. +func (m *FeatureMutation) RemoveEntitlementIDs(ids ...string) { + if m.removedentitlement == nil { + m.removedentitlement = make(map[string]struct{}) + } + for i := range ids { + delete(m.entitlement, ids[i]) + m.removedentitlement[ids[i]] = struct{}{} + } +} + +// RemovedEntitlement returns the removed IDs of the "entitlement" edge to the Entitlement entity. +func (m *FeatureMutation) RemovedEntitlementIDs() (ids []string) { + for id := range m.removedentitlement { + ids = append(ids, id) + } + return +} + +// EntitlementIDs returns the "entitlement" edge IDs in the mutation. +func (m *FeatureMutation) EntitlementIDs() (ids []string) { + for id := range m.entitlement { + ids = append(ids, id) + } + return +} + +// ResetEntitlement resets all changes to the "entitlement" edge. +func (m *FeatureMutation) ResetEntitlement() { + m.entitlement = nil + m.clearedentitlement = false + m.removedentitlement = nil +} + +// AddRatecardIDs adds the "ratecard" edge to the PlanRateCard entity by ids. +func (m *FeatureMutation) AddRatecardIDs(ids ...string) { + if m.ratecard == nil { + m.ratecard = make(map[string]struct{}) + } + for i := range ids { + m.ratecard[ids[i]] = struct{}{} + } +} + +// ClearRatecard clears the "ratecard" edge to the PlanRateCard entity. +func (m *FeatureMutation) ClearRatecard() { + m.clearedratecard = true +} + +// RatecardCleared reports if the "ratecard" edge to the PlanRateCard entity was cleared. +func (m *FeatureMutation) RatecardCleared() bool { + return m.clearedratecard +} + +// RemoveRatecardIDs removes the "ratecard" edge to the PlanRateCard entity by IDs. +func (m *FeatureMutation) RemoveRatecardIDs(ids ...string) { + if m.removedratecard == nil { + m.removedratecard = make(map[string]struct{}) + } + for i := range ids { + delete(m.ratecard, ids[i]) + m.removedratecard[ids[i]] = struct{}{} + } +} + +// RemovedRatecard returns the removed IDs of the "ratecard" edge to the PlanRateCard entity. +func (m *FeatureMutation) RemovedRatecardIDs() (ids []string) { + for id := range m.removedratecard { + ids = append(ids, id) + } + return +} + +// RatecardIDs returns the "ratecard" edge IDs in the mutation. +func (m *FeatureMutation) RatecardIDs() (ids []string) { + for id := range m.ratecard { + ids = append(ids, id) + } + return +} + +// ResetRatecard resets all changes to the "ratecard" edge. +func (m *FeatureMutation) ResetRatecard() { + m.ratecard = nil + m.clearedratecard = false + m.removedratecard = nil +} + +// AddAddonRatecardIDs adds the "addon_ratecard" edge to the AddonRateCard entity by ids. +func (m *FeatureMutation) AddAddonRatecardIDs(ids ...string) { + if m.addon_ratecard == nil { + m.addon_ratecard = make(map[string]struct{}) + } + for i := range ids { + m.addon_ratecard[ids[i]] = struct{}{} + } +} + +// ClearAddonRatecard clears the "addon_ratecard" edge to the AddonRateCard entity. +func (m *FeatureMutation) ClearAddonRatecard() { + m.clearedaddon_ratecard = true +} + +// AddonRatecardCleared reports if the "addon_ratecard" edge to the AddonRateCard entity was cleared. +func (m *FeatureMutation) AddonRatecardCleared() bool { + return m.clearedaddon_ratecard +} + +// RemoveAddonRatecardIDs removes the "addon_ratecard" edge to the AddonRateCard entity by IDs. +func (m *FeatureMutation) RemoveAddonRatecardIDs(ids ...string) { + if m.removedaddon_ratecard == nil { + m.removedaddon_ratecard = make(map[string]struct{}) + } + for i := range ids { + delete(m.addon_ratecard, ids[i]) + m.removedaddon_ratecard[ids[i]] = struct{}{} + } +} + +// RemovedAddonRatecard returns the removed IDs of the "addon_ratecard" edge to the AddonRateCard entity. +func (m *FeatureMutation) RemovedAddonRatecardIDs() (ids []string) { + for id := range m.removedaddon_ratecard { + ids = append(ids, id) + } + return +} + +// AddonRatecardIDs returns the "addon_ratecard" edge IDs in the mutation. +func (m *FeatureMutation) AddonRatecardIDs() (ids []string) { + for id := range m.addon_ratecard { + ids = append(ids, id) + } + return +} + +// ResetAddonRatecard resets all changes to the "addon_ratecard" edge. +func (m *FeatureMutation) ResetAddonRatecard() { + m.addon_ratecard = nil + m.clearedaddon_ratecard = false + m.removedaddon_ratecard = nil +} + +// AddUsageBasedChargeIDs adds the "usage_based_charges" edge to the ChargeUsageBased entity by ids. +func (m *FeatureMutation) AddUsageBasedChargeIDs(ids ...string) { + if m.usage_based_charges == nil { + m.usage_based_charges = make(map[string]struct{}) + } + for i := range ids { + m.usage_based_charges[ids[i]] = struct{}{} + } +} + +// ClearUsageBasedCharges clears the "usage_based_charges" edge to the ChargeUsageBased entity. +func (m *FeatureMutation) ClearUsageBasedCharges() { + m.clearedusage_based_charges = true +} + +// UsageBasedChargesCleared reports if the "usage_based_charges" edge to the ChargeUsageBased entity was cleared. +func (m *FeatureMutation) UsageBasedChargesCleared() bool { + return m.clearedusage_based_charges +} + +// RemoveUsageBasedChargeIDs removes the "usage_based_charges" edge to the ChargeUsageBased entity by IDs. +func (m *FeatureMutation) RemoveUsageBasedChargeIDs(ids ...string) { + if m.removedusage_based_charges == nil { + m.removedusage_based_charges = make(map[string]struct{}) + } + for i := range ids { + delete(m.usage_based_charges, ids[i]) + m.removedusage_based_charges[ids[i]] = struct{}{} + } +} + +// RemovedUsageBasedCharges returns the removed IDs of the "usage_based_charges" edge to the ChargeUsageBased entity. +func (m *FeatureMutation) RemovedUsageBasedChargesIDs() (ids []string) { + for id := range m.removedusage_based_charges { + ids = append(ids, id) + } + return +} + +// UsageBasedChargesIDs returns the "usage_based_charges" edge IDs in the mutation. +func (m *FeatureMutation) UsageBasedChargesIDs() (ids []string) { + for id := range m.usage_based_charges { + ids = append(ids, id) + } + return +} + +// ResetUsageBasedCharges resets all changes to the "usage_based_charges" edge. +func (m *FeatureMutation) ResetUsageBasedCharges() { + m.usage_based_charges = nil + m.clearedusage_based_charges = false + m.removedusage_based_charges = nil +} + +// AddUsageBasedRunIDs adds the "usage_based_runs" edge to the ChargeUsageBasedRuns entity by ids. +func (m *FeatureMutation) AddUsageBasedRunIDs(ids ...string) { + if m.usage_based_runs == nil { + m.usage_based_runs = make(map[string]struct{}) + } + for i := range ids { + m.usage_based_runs[ids[i]] = struct{}{} + } +} + +// ClearUsageBasedRuns clears the "usage_based_runs" edge to the ChargeUsageBasedRuns entity. +func (m *FeatureMutation) ClearUsageBasedRuns() { + m.clearedusage_based_runs = true +} + +// UsageBasedRunsCleared reports if the "usage_based_runs" edge to the ChargeUsageBasedRuns entity was cleared. +func (m *FeatureMutation) UsageBasedRunsCleared() bool { + return m.clearedusage_based_runs +} + +// RemoveUsageBasedRunIDs removes the "usage_based_runs" edge to the ChargeUsageBasedRuns entity by IDs. +func (m *FeatureMutation) RemoveUsageBasedRunIDs(ids ...string) { + if m.removedusage_based_runs == nil { + m.removedusage_based_runs = make(map[string]struct{}) + } + for i := range ids { + delete(m.usage_based_runs, ids[i]) + m.removedusage_based_runs[ids[i]] = struct{}{} + } +} + +// RemovedUsageBasedRuns returns the removed IDs of the "usage_based_runs" edge to the ChargeUsageBasedRuns entity. +func (m *FeatureMutation) RemovedUsageBasedRunsIDs() (ids []string) { + for id := range m.removedusage_based_runs { + ids = append(ids, id) + } + return +} + +// UsageBasedRunsIDs returns the "usage_based_runs" edge IDs in the mutation. +func (m *FeatureMutation) UsageBasedRunsIDs() (ids []string) { + for id := range m.usage_based_runs { + ids = append(ids, id) + } + return +} + +// ResetUsageBasedRuns resets all changes to the "usage_based_runs" edge. +func (m *FeatureMutation) ResetUsageBasedRuns() { + m.usage_based_runs = nil + m.clearedusage_based_runs = false + m.removedusage_based_runs = nil +} + +// AddFlatFeeChargeIDs adds the "flat_fee_charges" edge to the ChargeFlatFee entity by ids. +func (m *FeatureMutation) AddFlatFeeChargeIDs(ids ...string) { + if m.flat_fee_charges == nil { + m.flat_fee_charges = make(map[string]struct{}) + } + for i := range ids { + m.flat_fee_charges[ids[i]] = struct{}{} + } +} + +// ClearFlatFeeCharges clears the "flat_fee_charges" edge to the ChargeFlatFee entity. +func (m *FeatureMutation) ClearFlatFeeCharges() { + m.clearedflat_fee_charges = true +} + +// FlatFeeChargesCleared reports if the "flat_fee_charges" edge to the ChargeFlatFee entity was cleared. +func (m *FeatureMutation) FlatFeeChargesCleared() bool { + return m.clearedflat_fee_charges +} + +// RemoveFlatFeeChargeIDs removes the "flat_fee_charges" edge to the ChargeFlatFee entity by IDs. +func (m *FeatureMutation) RemoveFlatFeeChargeIDs(ids ...string) { + if m.removedflat_fee_charges == nil { + m.removedflat_fee_charges = make(map[string]struct{}) + } + for i := range ids { + delete(m.flat_fee_charges, ids[i]) + m.removedflat_fee_charges[ids[i]] = struct{}{} + } +} + +// RemovedFlatFeeCharges returns the removed IDs of the "flat_fee_charges" edge to the ChargeFlatFee entity. +func (m *FeatureMutation) RemovedFlatFeeChargesIDs() (ids []string) { + for id := range m.removedflat_fee_charges { + ids = append(ids, id) + } + return +} + +// FlatFeeChargesIDs returns the "flat_fee_charges" edge IDs in the mutation. +func (m *FeatureMutation) FlatFeeChargesIDs() (ids []string) { + for id := range m.flat_fee_charges { + ids = append(ids, id) + } + return +} + +// ResetFlatFeeCharges resets all changes to the "flat_fee_charges" edge. +func (m *FeatureMutation) ResetFlatFeeCharges() { + m.flat_fee_charges = nil + m.clearedflat_fee_charges = false + m.removedflat_fee_charges = nil +} + +// ClearMeter clears the "meter" edge to the Meter entity. +func (m *FeatureMutation) ClearMeter() { + m.clearedmeter = true + m.clearedFields[dbfeature.FieldMeterID] = struct{}{} +} + +// MeterCleared reports if the "meter" edge to the Meter entity was cleared. +func (m *FeatureMutation) MeterCleared() bool { + return m.MeterIDCleared() || m.clearedmeter +} + +// MeterIDs returns the "meter" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// MeterID instead. It exists only for internal usage by the builders. +func (m *FeatureMutation) MeterIDs() (ids []string) { + if id := m.meter; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetMeter resets all changes to the "meter" edge. +func (m *FeatureMutation) ResetMeter() { + m.meter = nil + m.clearedmeter = false +} + +// Where appends a list predicates to the FeatureMutation builder. +func (m *FeatureMutation) Where(ps ...predicate.Feature) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the FeatureMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *FeatureMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Feature, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *FeatureMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *FeatureMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Feature). +func (m *FeatureMutation) 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 *FeatureMutation) Fields() []string { + fields := make([]string, 0, 21) + if m.created_at != nil { + fields = append(fields, dbfeature.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, dbfeature.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, dbfeature.FieldDeletedAt) + } + if m.metadata != nil { + fields = append(fields, dbfeature.FieldMetadata) + } + if m.namespace != nil { + fields = append(fields, dbfeature.FieldNamespace) + } + if m.name != nil { + fields = append(fields, dbfeature.FieldName) + } + if m.description != nil { + fields = append(fields, dbfeature.FieldDescription) + } + if m.key != nil { + fields = append(fields, dbfeature.FieldKey) + } + if m.meter_slug != nil { + fields = append(fields, dbfeature.FieldMeterSlug) + } + if m.meter != nil { + fields = append(fields, dbfeature.FieldMeterID) + } + if m.meter_group_by_filters != nil { + fields = append(fields, dbfeature.FieldMeterGroupByFilters) + } + if m.advanced_meter_group_by_filters != nil { + fields = append(fields, dbfeature.FieldAdvancedMeterGroupByFilters) + } + if m.unit_cost_type != nil { + fields = append(fields, dbfeature.FieldUnitCostType) + } + if m.unit_cost_manual_amount != nil { + fields = append(fields, dbfeature.FieldUnitCostManualAmount) + } + if m.unit_cost_llm_provider_property != nil { + fields = append(fields, dbfeature.FieldUnitCostLlmProviderProperty) + } + if m.unit_cost_llm_provider != nil { + fields = append(fields, dbfeature.FieldUnitCostLlmProvider) + } + if m.unit_cost_llm_model_property != nil { + fields = append(fields, dbfeature.FieldUnitCostLlmModelProperty) + } + if m.unit_cost_llm_model != nil { + fields = append(fields, dbfeature.FieldUnitCostLlmModel) + } + if m.unit_cost_llm_token_type_property != nil { + fields = append(fields, dbfeature.FieldUnitCostLlmTokenTypeProperty) + } + if m.unit_cost_llm_token_type != nil { + fields = append(fields, dbfeature.FieldUnitCostLlmTokenType) + } + if m.archived_at != nil { + fields = append(fields, dbfeature.FieldArchivedAt) + } + 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 *FeatureMutation) Field(name string) (ent.Value, bool) { + switch name { + case dbfeature.FieldCreatedAt: + return m.CreatedAt() + case dbfeature.FieldUpdatedAt: + return m.UpdatedAt() + case dbfeature.FieldDeletedAt: + return m.DeletedAt() + case dbfeature.FieldMetadata: + return m.Metadata() + case dbfeature.FieldNamespace: + return m.Namespace() + case dbfeature.FieldName: + return m.Name() + case dbfeature.FieldDescription: + return m.Description() + case dbfeature.FieldKey: + return m.Key() + case dbfeature.FieldMeterSlug: + return m.MeterSlug() + case dbfeature.FieldMeterID: + return m.MeterID() + case dbfeature.FieldMeterGroupByFilters: + return m.MeterGroupByFilters() + case dbfeature.FieldAdvancedMeterGroupByFilters: + return m.AdvancedMeterGroupByFilters() + case dbfeature.FieldUnitCostType: + return m.UnitCostType() + case dbfeature.FieldUnitCostManualAmount: + return m.UnitCostManualAmount() + case dbfeature.FieldUnitCostLlmProviderProperty: + return m.UnitCostLlmProviderProperty() + case dbfeature.FieldUnitCostLlmProvider: + return m.UnitCostLlmProvider() + case dbfeature.FieldUnitCostLlmModelProperty: + return m.UnitCostLlmModelProperty() + case dbfeature.FieldUnitCostLlmModel: + return m.UnitCostLlmModel() + case dbfeature.FieldUnitCostLlmTokenTypeProperty: + return m.UnitCostLlmTokenTypeProperty() + case dbfeature.FieldUnitCostLlmTokenType: + return m.UnitCostLlmTokenType() + case dbfeature.FieldArchivedAt: + return m.ArchivedAt() + } + 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 *FeatureMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case dbfeature.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case dbfeature.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case dbfeature.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case dbfeature.FieldMetadata: + return m.OldMetadata(ctx) + case dbfeature.FieldNamespace: + return m.OldNamespace(ctx) + case dbfeature.FieldName: + return m.OldName(ctx) + case dbfeature.FieldDescription: + return m.OldDescription(ctx) + case dbfeature.FieldKey: + return m.OldKey(ctx) + case dbfeature.FieldMeterSlug: + return m.OldMeterSlug(ctx) + case dbfeature.FieldMeterID: + return m.OldMeterID(ctx) + case dbfeature.FieldMeterGroupByFilters: + return m.OldMeterGroupByFilters(ctx) + case dbfeature.FieldAdvancedMeterGroupByFilters: + return m.OldAdvancedMeterGroupByFilters(ctx) + case dbfeature.FieldUnitCostType: + return m.OldUnitCostType(ctx) + case dbfeature.FieldUnitCostManualAmount: + return m.OldUnitCostManualAmount(ctx) + case dbfeature.FieldUnitCostLlmProviderProperty: + return m.OldUnitCostLlmProviderProperty(ctx) + case dbfeature.FieldUnitCostLlmProvider: + return m.OldUnitCostLlmProvider(ctx) + case dbfeature.FieldUnitCostLlmModelProperty: + return m.OldUnitCostLlmModelProperty(ctx) + case dbfeature.FieldUnitCostLlmModel: + return m.OldUnitCostLlmModel(ctx) + case dbfeature.FieldUnitCostLlmTokenTypeProperty: + return m.OldUnitCostLlmTokenTypeProperty(ctx) + case dbfeature.FieldUnitCostLlmTokenType: + return m.OldUnitCostLlmTokenType(ctx) + case dbfeature.FieldArchivedAt: + return m.OldArchivedAt(ctx) + } + return nil, fmt.Errorf("unknown Feature 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 *FeatureMutation) SetField(name string, value ent.Value) error { + switch name { + case dbfeature.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 dbfeature.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 dbfeature.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 dbfeature.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case dbfeature.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case dbfeature.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case dbfeature.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case dbfeature.FieldKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKey(v) + return nil + case dbfeature.FieldMeterSlug: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMeterSlug(v) + return nil + case dbfeature.FieldMeterID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMeterID(v) + return nil + case dbfeature.FieldMeterGroupByFilters: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMeterGroupByFilters(v) + return nil + case dbfeature.FieldAdvancedMeterGroupByFilters: + v, ok := value.(feature.MeterGroupByFilters) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAdvancedMeterGroupByFilters(v) + return nil + case dbfeature.FieldUnitCostType: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUnitCostType(v) + return nil + case dbfeature.FieldUnitCostManualAmount: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUnitCostManualAmount(v) + return nil + case dbfeature.FieldUnitCostLlmProviderProperty: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUnitCostLlmProviderProperty(v) + return nil + case dbfeature.FieldUnitCostLlmProvider: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUnitCostLlmProvider(v) + return nil + case dbfeature.FieldUnitCostLlmModelProperty: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUnitCostLlmModelProperty(v) + return nil + case dbfeature.FieldUnitCostLlmModel: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUnitCostLlmModel(v) + return nil + case dbfeature.FieldUnitCostLlmTokenTypeProperty: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUnitCostLlmTokenTypeProperty(v) + return nil + case dbfeature.FieldUnitCostLlmTokenType: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUnitCostLlmTokenType(v) + return nil + case dbfeature.FieldArchivedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetArchivedAt(v) + return nil + } + return fmt.Errorf("unknown Feature field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *FeatureMutation) 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 *FeatureMutation) 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 *FeatureMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Feature numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *FeatureMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(dbfeature.FieldDeletedAt) { + fields = append(fields, dbfeature.FieldDeletedAt) + } + if m.FieldCleared(dbfeature.FieldMetadata) { + fields = append(fields, dbfeature.FieldMetadata) + } + if m.FieldCleared(dbfeature.FieldDescription) { + fields = append(fields, dbfeature.FieldDescription) + } + if m.FieldCleared(dbfeature.FieldMeterSlug) { + fields = append(fields, dbfeature.FieldMeterSlug) + } + if m.FieldCleared(dbfeature.FieldMeterID) { + fields = append(fields, dbfeature.FieldMeterID) + } + if m.FieldCleared(dbfeature.FieldMeterGroupByFilters) { + fields = append(fields, dbfeature.FieldMeterGroupByFilters) + } + if m.FieldCleared(dbfeature.FieldAdvancedMeterGroupByFilters) { + fields = append(fields, dbfeature.FieldAdvancedMeterGroupByFilters) + } + if m.FieldCleared(dbfeature.FieldUnitCostType) { + fields = append(fields, dbfeature.FieldUnitCostType) + } + if m.FieldCleared(dbfeature.FieldUnitCostManualAmount) { + fields = append(fields, dbfeature.FieldUnitCostManualAmount) + } + if m.FieldCleared(dbfeature.FieldUnitCostLlmProviderProperty) { + fields = append(fields, dbfeature.FieldUnitCostLlmProviderProperty) + } + if m.FieldCleared(dbfeature.FieldUnitCostLlmProvider) { + fields = append(fields, dbfeature.FieldUnitCostLlmProvider) + } + if m.FieldCleared(dbfeature.FieldUnitCostLlmModelProperty) { + fields = append(fields, dbfeature.FieldUnitCostLlmModelProperty) + } + if m.FieldCleared(dbfeature.FieldUnitCostLlmModel) { + fields = append(fields, dbfeature.FieldUnitCostLlmModel) + } + if m.FieldCleared(dbfeature.FieldUnitCostLlmTokenTypeProperty) { + fields = append(fields, dbfeature.FieldUnitCostLlmTokenTypeProperty) + } + if m.FieldCleared(dbfeature.FieldUnitCostLlmTokenType) { + fields = append(fields, dbfeature.FieldUnitCostLlmTokenType) + } + if m.FieldCleared(dbfeature.FieldArchivedAt) { + fields = append(fields, dbfeature.FieldArchivedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *FeatureMutation) 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 *FeatureMutation) ClearField(name string) error { + switch name { + case dbfeature.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case dbfeature.FieldMetadata: + m.ClearMetadata() + return nil + case dbfeature.FieldDescription: + m.ClearDescription() + return nil + case dbfeature.FieldMeterSlug: + m.ClearMeterSlug() + return nil + case dbfeature.FieldMeterID: + m.ClearMeterID() + return nil + case dbfeature.FieldMeterGroupByFilters: + m.ClearMeterGroupByFilters() + return nil + case dbfeature.FieldAdvancedMeterGroupByFilters: + m.ClearAdvancedMeterGroupByFilters() + return nil + case dbfeature.FieldUnitCostType: + m.ClearUnitCostType() + return nil + case dbfeature.FieldUnitCostManualAmount: + m.ClearUnitCostManualAmount() + return nil + case dbfeature.FieldUnitCostLlmProviderProperty: + m.ClearUnitCostLlmProviderProperty() + return nil + case dbfeature.FieldUnitCostLlmProvider: + m.ClearUnitCostLlmProvider() + return nil + case dbfeature.FieldUnitCostLlmModelProperty: + m.ClearUnitCostLlmModelProperty() + return nil + case dbfeature.FieldUnitCostLlmModel: + m.ClearUnitCostLlmModel() + return nil + case dbfeature.FieldUnitCostLlmTokenTypeProperty: + m.ClearUnitCostLlmTokenTypeProperty() + return nil + case dbfeature.FieldUnitCostLlmTokenType: + m.ClearUnitCostLlmTokenType() + return nil + case dbfeature.FieldArchivedAt: + m.ClearArchivedAt() + return nil + } + return fmt.Errorf("unknown Feature 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 *FeatureMutation) ResetField(name string) error { + switch name { + case dbfeature.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case dbfeature.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case dbfeature.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case dbfeature.FieldMetadata: + m.ResetMetadata() + return nil + case dbfeature.FieldNamespace: + m.ResetNamespace() + return nil + case dbfeature.FieldName: + m.ResetName() + return nil + case dbfeature.FieldDescription: + m.ResetDescription() + return nil + case dbfeature.FieldKey: + m.ResetKey() + return nil + case dbfeature.FieldMeterSlug: + m.ResetMeterSlug() + return nil + case dbfeature.FieldMeterID: + m.ResetMeterID() + return nil + case dbfeature.FieldMeterGroupByFilters: + m.ResetMeterGroupByFilters() + return nil + case dbfeature.FieldAdvancedMeterGroupByFilters: + m.ResetAdvancedMeterGroupByFilters() + return nil + case dbfeature.FieldUnitCostType: + m.ResetUnitCostType() + return nil + case dbfeature.FieldUnitCostManualAmount: + m.ResetUnitCostManualAmount() + return nil + case dbfeature.FieldUnitCostLlmProviderProperty: + m.ResetUnitCostLlmProviderProperty() + return nil + case dbfeature.FieldUnitCostLlmProvider: + m.ResetUnitCostLlmProvider() + return nil + case dbfeature.FieldUnitCostLlmModelProperty: + m.ResetUnitCostLlmModelProperty() + return nil + case dbfeature.FieldUnitCostLlmModel: + m.ResetUnitCostLlmModel() + return nil + case dbfeature.FieldUnitCostLlmTokenTypeProperty: + m.ResetUnitCostLlmTokenTypeProperty() + return nil + case dbfeature.FieldUnitCostLlmTokenType: + m.ResetUnitCostLlmTokenType() + return nil + case dbfeature.FieldArchivedAt: + m.ResetArchivedAt() + return nil + } + return fmt.Errorf("unknown Feature field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *FeatureMutation) AddedEdges() []string { + edges := make([]string, 0, 7) + if m.entitlement != nil { + edges = append(edges, dbfeature.EdgeEntitlement) + } + if m.ratecard != nil { + edges = append(edges, dbfeature.EdgeRatecard) + } + if m.addon_ratecard != nil { + edges = append(edges, dbfeature.EdgeAddonRatecard) + } + if m.usage_based_charges != nil { + edges = append(edges, dbfeature.EdgeUsageBasedCharges) + } + if m.usage_based_runs != nil { + edges = append(edges, dbfeature.EdgeUsageBasedRuns) + } + if m.flat_fee_charges != nil { + edges = append(edges, dbfeature.EdgeFlatFeeCharges) + } + if m.meter != nil { + edges = append(edges, dbfeature.EdgeMeter) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *FeatureMutation) AddedIDs(name string) []ent.Value { + switch name { + case dbfeature.EdgeEntitlement: + ids := make([]ent.Value, 0, len(m.entitlement)) + for id := range m.entitlement { + ids = append(ids, id) + } + return ids + case dbfeature.EdgeRatecard: + ids := make([]ent.Value, 0, len(m.ratecard)) + for id := range m.ratecard { + ids = append(ids, id) + } + return ids + case dbfeature.EdgeAddonRatecard: + ids := make([]ent.Value, 0, len(m.addon_ratecard)) + for id := range m.addon_ratecard { + ids = append(ids, id) + } + return ids + case dbfeature.EdgeUsageBasedCharges: + ids := make([]ent.Value, 0, len(m.usage_based_charges)) + for id := range m.usage_based_charges { + ids = append(ids, id) + } + return ids + case dbfeature.EdgeUsageBasedRuns: + ids := make([]ent.Value, 0, len(m.usage_based_runs)) + for id := range m.usage_based_runs { + ids = append(ids, id) + } + return ids + case dbfeature.EdgeFlatFeeCharges: + ids := make([]ent.Value, 0, len(m.flat_fee_charges)) + for id := range m.flat_fee_charges { + ids = append(ids, id) + } + return ids + case dbfeature.EdgeMeter: + if id := m.meter; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *FeatureMutation) RemovedEdges() []string { + edges := make([]string, 0, 7) + if m.removedentitlement != nil { + edges = append(edges, dbfeature.EdgeEntitlement) + } + if m.removedratecard != nil { + edges = append(edges, dbfeature.EdgeRatecard) + } + if m.removedaddon_ratecard != nil { + edges = append(edges, dbfeature.EdgeAddonRatecard) + } + if m.removedusage_based_charges != nil { + edges = append(edges, dbfeature.EdgeUsageBasedCharges) + } + if m.removedusage_based_runs != nil { + edges = append(edges, dbfeature.EdgeUsageBasedRuns) + } + if m.removedflat_fee_charges != nil { + edges = append(edges, dbfeature.EdgeFlatFeeCharges) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *FeatureMutation) RemovedIDs(name string) []ent.Value { + switch name { + case dbfeature.EdgeEntitlement: + ids := make([]ent.Value, 0, len(m.removedentitlement)) + for id := range m.removedentitlement { + ids = append(ids, id) + } + return ids + case dbfeature.EdgeRatecard: + ids := make([]ent.Value, 0, len(m.removedratecard)) + for id := range m.removedratecard { + ids = append(ids, id) + } + return ids + case dbfeature.EdgeAddonRatecard: + ids := make([]ent.Value, 0, len(m.removedaddon_ratecard)) + for id := range m.removedaddon_ratecard { + ids = append(ids, id) + } + return ids + case dbfeature.EdgeUsageBasedCharges: + ids := make([]ent.Value, 0, len(m.removedusage_based_charges)) + for id := range m.removedusage_based_charges { + ids = append(ids, id) + } + return ids + case dbfeature.EdgeUsageBasedRuns: + ids := make([]ent.Value, 0, len(m.removedusage_based_runs)) + for id := range m.removedusage_based_runs { + ids = append(ids, id) + } + return ids + case dbfeature.EdgeFlatFeeCharges: + ids := make([]ent.Value, 0, len(m.removedflat_fee_charges)) + for id := range m.removedflat_fee_charges { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *FeatureMutation) ClearedEdges() []string { + edges := make([]string, 0, 7) + if m.clearedentitlement { + edges = append(edges, dbfeature.EdgeEntitlement) + } + if m.clearedratecard { + edges = append(edges, dbfeature.EdgeRatecard) + } + if m.clearedaddon_ratecard { + edges = append(edges, dbfeature.EdgeAddonRatecard) + } + if m.clearedusage_based_charges { + edges = append(edges, dbfeature.EdgeUsageBasedCharges) + } + if m.clearedusage_based_runs { + edges = append(edges, dbfeature.EdgeUsageBasedRuns) + } + if m.clearedflat_fee_charges { + edges = append(edges, dbfeature.EdgeFlatFeeCharges) + } + if m.clearedmeter { + edges = append(edges, dbfeature.EdgeMeter) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *FeatureMutation) EdgeCleared(name string) bool { + switch name { + case dbfeature.EdgeEntitlement: + return m.clearedentitlement + case dbfeature.EdgeRatecard: + return m.clearedratecard + case dbfeature.EdgeAddonRatecard: + return m.clearedaddon_ratecard + case dbfeature.EdgeUsageBasedCharges: + return m.clearedusage_based_charges + case dbfeature.EdgeUsageBasedRuns: + return m.clearedusage_based_runs + case dbfeature.EdgeFlatFeeCharges: + return m.clearedflat_fee_charges + case dbfeature.EdgeMeter: + return m.clearedmeter + } + 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 *FeatureMutation) ClearEdge(name string) error { + switch name { + case dbfeature.EdgeMeter: + m.ClearMeter() + return nil + } + return fmt.Errorf("unknown Feature 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 *FeatureMutation) ResetEdge(name string) error { + switch name { + case dbfeature.EdgeEntitlement: + m.ResetEntitlement() + return nil + case dbfeature.EdgeRatecard: + m.ResetRatecard() + return nil + case dbfeature.EdgeAddonRatecard: + m.ResetAddonRatecard() + return nil + case dbfeature.EdgeUsageBasedCharges: + m.ResetUsageBasedCharges() + return nil + case dbfeature.EdgeUsageBasedRuns: + m.ResetUsageBasedRuns() + return nil + case dbfeature.EdgeFlatFeeCharges: + m.ResetFlatFeeCharges() + return nil + case dbfeature.EdgeMeter: + m.ResetMeter() + return nil + } + return fmt.Errorf("unknown Feature edge %s", name) +} + +// GrantMutation represents an operation that mutates the Grant nodes in the graph. +type GrantMutation struct { + config + op Op + typ string + id *string + namespace *string + annotations *models.Annotations + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + metadata *map[string]string + amount *float64 + addamount *float64 + priority *uint8 + addpriority *int8 + effective_at *time.Time + expiration **grant.ExpirationPeriod + expires_at *time.Time + voided_at *time.Time + reset_max_rollover *float64 + addreset_max_rollover *float64 + reset_min_rollover *float64 + addreset_min_rollover *float64 + recurrence_period *datetime.ISODurationString + recurrence_anchor *time.Time + clearedFields map[string]struct{} + entitlement *string + clearedentitlement bool + done bool + oldValue func(context.Context) (*Grant, error) + predicates []predicate.Grant +} + +var _ ent.Mutation = (*GrantMutation)(nil) + +// grantOption allows management of the mutation configuration using functional options. +type grantOption func(*GrantMutation) + +// newGrantMutation creates new mutation for the Grant entity. +func newGrantMutation(c config, op Op, opts ...grantOption) *GrantMutation { + m := &GrantMutation{ + config: c, + op: op, + typ: TypeGrant, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withGrantID sets the ID field of the mutation. +func withGrantID(id string) grantOption { + return func(m *GrantMutation) { + var ( + err error + once sync.Once + value *Grant + ) + m.oldValue = func(ctx context.Context) (*Grant, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Grant.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withGrant sets the old Grant of the mutation. +func withGrant(node *Grant) grantOption { + return func(m *GrantMutation) { + m.oldValue = func(context.Context) (*Grant, 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 GrantMutation) 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 GrantMutation) 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 Grant entities. +func (m *GrantMutation) 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 *GrantMutation) 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 *GrantMutation) 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().Grant.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 *GrantMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *GrantMutation) 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 Grant entity. +// If the Grant 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 *GrantMutation) 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 *GrantMutation) ResetNamespace() { + m.namespace = nil +} + +// SetAnnotations sets the "annotations" field. +func (m *GrantMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *GrantMutation) 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 Grant entity. +// If the Grant 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 *GrantMutation) 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 *GrantMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[dbgrant.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *GrantMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[dbgrant.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *GrantMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, dbgrant.FieldAnnotations) +} + +// SetCreatedAt sets the "created_at" field. +func (m *GrantMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *GrantMutation) 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 Grant entity. +// If the Grant 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 *GrantMutation) 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 *GrantMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *GrantMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *GrantMutation) 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 Grant entity. +// If the Grant 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 *GrantMutation) 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 *GrantMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *GrantMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *GrantMutation) 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 Grant entity. +// If the Grant 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 *GrantMutation) 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 *GrantMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[dbgrant.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *GrantMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[dbgrant.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *GrantMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, dbgrant.FieldDeletedAt) +} + +// SetMetadata sets the "metadata" field. +func (m *GrantMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *GrantMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the Grant entity. +// If the Grant 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 *GrantMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *GrantMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[dbgrant.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *GrantMutation) MetadataCleared() bool { + _, ok := m.clearedFields[dbgrant.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *GrantMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, dbgrant.FieldMetadata) +} + +// SetOwnerID sets the "owner_id" field. +func (m *GrantMutation) SetOwnerID(s string) { + m.entitlement = &s +} + +// OwnerID returns the value of the "owner_id" field in the mutation. +func (m *GrantMutation) OwnerID() (r string, exists bool) { + v := m.entitlement + if v == nil { + return + } + return *v, true +} + +// OldOwnerID returns the old "owner_id" field's value of the Grant entity. +// If the Grant 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 *GrantMutation) OldOwnerID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOwnerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOwnerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOwnerID: %w", err) + } + return oldValue.OwnerID, nil +} + +// ResetOwnerID resets all changes to the "owner_id" field. +func (m *GrantMutation) ResetOwnerID() { + m.entitlement = nil +} + +// SetAmount sets the "amount" field. +func (m *GrantMutation) SetAmount(f float64) { + m.amount = &f + m.addamount = nil +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *GrantMutation) Amount() (r float64, exists bool) { + v := m.amount + if v == nil { + return + } + return *v, true +} + +// OldAmount returns the old "amount" field's value of the Grant entity. +// If the Grant 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 *GrantMutation) OldAmount(ctx context.Context) (v float64, 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 +} + +// AddAmount adds f to the "amount" field. +func (m *GrantMutation) AddAmount(f float64) { + if m.addamount != nil { + *m.addamount += f + } else { + m.addamount = &f + } +} + +// AddedAmount returns the value that was added to the "amount" field in this mutation. +func (m *GrantMutation) AddedAmount() (r float64, exists bool) { + v := m.addamount + if v == nil { + return + } + return *v, true +} + +// ResetAmount resets all changes to the "amount" field. +func (m *GrantMutation) ResetAmount() { + m.amount = nil + m.addamount = nil +} + +// SetPriority sets the "priority" field. +func (m *GrantMutation) SetPriority(u uint8) { + m.priority = &u + m.addpriority = nil +} + +// Priority returns the value of the "priority" field in the mutation. +func (m *GrantMutation) Priority() (r uint8, exists bool) { + v := m.priority + if v == nil { + return + } + return *v, true +} + +// OldPriority returns the old "priority" field's value of the Grant entity. +// If the Grant 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 *GrantMutation) OldPriority(ctx context.Context) (v uint8, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPriority is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPriority requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPriority: %w", err) + } + return oldValue.Priority, nil +} + +// AddPriority adds u to the "priority" field. +func (m *GrantMutation) AddPriority(u int8) { + if m.addpriority != nil { + *m.addpriority += u + } else { + m.addpriority = &u + } +} + +// AddedPriority returns the value that was added to the "priority" field in this mutation. +func (m *GrantMutation) AddedPriority() (r int8, exists bool) { + v := m.addpriority + if v == nil { + return + } + return *v, true +} + +// ResetPriority resets all changes to the "priority" field. +func (m *GrantMutation) ResetPriority() { + m.priority = nil + m.addpriority = nil +} + +// SetEffectiveAt sets the "effective_at" field. +func (m *GrantMutation) SetEffectiveAt(t time.Time) { + m.effective_at = &t +} + +// EffectiveAt returns the value of the "effective_at" field in the mutation. +func (m *GrantMutation) EffectiveAt() (r time.Time, exists bool) { + v := m.effective_at + if v == nil { + return + } + return *v, true +} + +// OldEffectiveAt returns the old "effective_at" field's value of the Grant entity. +// If the Grant 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 *GrantMutation) OldEffectiveAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEffectiveAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEffectiveAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEffectiveAt: %w", err) + } + return oldValue.EffectiveAt, nil +} + +// ResetEffectiveAt resets all changes to the "effective_at" field. +func (m *GrantMutation) ResetEffectiveAt() { + m.effective_at = nil +} + +// SetExpiration sets the "expiration" field. +func (m *GrantMutation) SetExpiration(gp *grant.ExpirationPeriod) { + m.expiration = &gp +} + +// Expiration returns the value of the "expiration" field in the mutation. +func (m *GrantMutation) Expiration() (r *grant.ExpirationPeriod, exists bool) { + v := m.expiration + if v == nil { + return + } + return *v, true +} + +// OldExpiration returns the old "expiration" field's value of the Grant entity. +// If the Grant 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 *GrantMutation) OldExpiration(ctx context.Context) (v *grant.ExpirationPeriod, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldExpiration is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldExpiration requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldExpiration: %w", err) + } + return oldValue.Expiration, nil +} + +// ClearExpiration clears the value of the "expiration" field. +func (m *GrantMutation) ClearExpiration() { + m.expiration = nil + m.clearedFields[dbgrant.FieldExpiration] = struct{}{} +} + +// ExpirationCleared returns if the "expiration" field was cleared in this mutation. +func (m *GrantMutation) ExpirationCleared() bool { + _, ok := m.clearedFields[dbgrant.FieldExpiration] + return ok +} + +// ResetExpiration resets all changes to the "expiration" field. +func (m *GrantMutation) ResetExpiration() { + m.expiration = nil + delete(m.clearedFields, dbgrant.FieldExpiration) +} + +// SetExpiresAt sets the "expires_at" field. +func (m *GrantMutation) SetExpiresAt(t time.Time) { + m.expires_at = &t +} + +// ExpiresAt returns the value of the "expires_at" field in the mutation. +func (m *GrantMutation) ExpiresAt() (r time.Time, exists bool) { + v := m.expires_at + if v == nil { + return + } + return *v, true +} + +// OldExpiresAt returns the old "expires_at" field's value of the Grant entity. +// If the Grant 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 *GrantMutation) OldExpiresAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldExpiresAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldExpiresAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldExpiresAt: %w", err) + } + return oldValue.ExpiresAt, nil +} + +// ClearExpiresAt clears the value of the "expires_at" field. +func (m *GrantMutation) ClearExpiresAt() { + m.expires_at = nil + m.clearedFields[dbgrant.FieldExpiresAt] = struct{}{} +} + +// ExpiresAtCleared returns if the "expires_at" field was cleared in this mutation. +func (m *GrantMutation) ExpiresAtCleared() bool { + _, ok := m.clearedFields[dbgrant.FieldExpiresAt] + return ok +} + +// ResetExpiresAt resets all changes to the "expires_at" field. +func (m *GrantMutation) ResetExpiresAt() { + m.expires_at = nil + delete(m.clearedFields, dbgrant.FieldExpiresAt) +} + +// SetVoidedAt sets the "voided_at" field. +func (m *GrantMutation) SetVoidedAt(t time.Time) { + m.voided_at = &t +} + +// VoidedAt returns the value of the "voided_at" field in the mutation. +func (m *GrantMutation) VoidedAt() (r time.Time, exists bool) { + v := m.voided_at + if v == nil { + return + } + return *v, true +} + +// OldVoidedAt returns the old "voided_at" field's value of the Grant entity. +// If the Grant 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 *GrantMutation) OldVoidedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldVoidedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldVoidedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldVoidedAt: %w", err) + } + return oldValue.VoidedAt, nil +} + +// ClearVoidedAt clears the value of the "voided_at" field. +func (m *GrantMutation) ClearVoidedAt() { + m.voided_at = nil + m.clearedFields[dbgrant.FieldVoidedAt] = struct{}{} +} + +// VoidedAtCleared returns if the "voided_at" field was cleared in this mutation. +func (m *GrantMutation) VoidedAtCleared() bool { + _, ok := m.clearedFields[dbgrant.FieldVoidedAt] + return ok +} + +// ResetVoidedAt resets all changes to the "voided_at" field. +func (m *GrantMutation) ResetVoidedAt() { + m.voided_at = nil + delete(m.clearedFields, dbgrant.FieldVoidedAt) +} + +// SetResetMaxRollover sets the "reset_max_rollover" field. +func (m *GrantMutation) SetResetMaxRollover(f float64) { + m.reset_max_rollover = &f + m.addreset_max_rollover = nil +} + +// ResetMaxRollover returns the value of the "reset_max_rollover" field in the mutation. +func (m *GrantMutation) ResetMaxRollover() (r float64, exists bool) { + v := m.reset_max_rollover + if v == nil { + return + } + return *v, true +} + +// OldResetMaxRollover returns the old "reset_max_rollover" field's value of the Grant entity. +// If the Grant 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 *GrantMutation) OldResetMaxRollover(ctx context.Context) (v float64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldResetMaxRollover is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldResetMaxRollover requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldResetMaxRollover: %w", err) + } + return oldValue.ResetMaxRollover, nil +} + +// AddResetMaxRollover adds f to the "reset_max_rollover" field. +func (m *GrantMutation) AddResetMaxRollover(f float64) { + if m.addreset_max_rollover != nil { + *m.addreset_max_rollover += f + } else { + m.addreset_max_rollover = &f + } +} + +// AddedResetMaxRollover returns the value that was added to the "reset_max_rollover" field in this mutation. +func (m *GrantMutation) AddedResetMaxRollover() (r float64, exists bool) { + v := m.addreset_max_rollover + if v == nil { + return + } + return *v, true +} + +// ResetResetMaxRollover resets all changes to the "reset_max_rollover" field. +func (m *GrantMutation) ResetResetMaxRollover() { + m.reset_max_rollover = nil + m.addreset_max_rollover = nil +} + +// SetResetMinRollover sets the "reset_min_rollover" field. +func (m *GrantMutation) SetResetMinRollover(f float64) { + m.reset_min_rollover = &f + m.addreset_min_rollover = nil +} + +// ResetMinRollover returns the value of the "reset_min_rollover" field in the mutation. +func (m *GrantMutation) ResetMinRollover() (r float64, exists bool) { + v := m.reset_min_rollover + if v == nil { + return + } + return *v, true +} + +// OldResetMinRollover returns the old "reset_min_rollover" field's value of the Grant entity. +// If the Grant 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 *GrantMutation) OldResetMinRollover(ctx context.Context) (v float64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldResetMinRollover is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldResetMinRollover requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldResetMinRollover: %w", err) + } + return oldValue.ResetMinRollover, nil +} + +// AddResetMinRollover adds f to the "reset_min_rollover" field. +func (m *GrantMutation) AddResetMinRollover(f float64) { + if m.addreset_min_rollover != nil { + *m.addreset_min_rollover += f + } else { + m.addreset_min_rollover = &f + } +} + +// AddedResetMinRollover returns the value that was added to the "reset_min_rollover" field in this mutation. +func (m *GrantMutation) AddedResetMinRollover() (r float64, exists bool) { + v := m.addreset_min_rollover + if v == nil { + return + } + return *v, true +} + +// ResetResetMinRollover resets all changes to the "reset_min_rollover" field. +func (m *GrantMutation) ResetResetMinRollover() { + m.reset_min_rollover = nil + m.addreset_min_rollover = nil +} + +// SetRecurrencePeriod sets the "recurrence_period" field. +func (m *GrantMutation) SetRecurrencePeriod(dds datetime.ISODurationString) { + m.recurrence_period = &dds +} + +// RecurrencePeriod returns the value of the "recurrence_period" field in the mutation. +func (m *GrantMutation) RecurrencePeriod() (r datetime.ISODurationString, exists bool) { + v := m.recurrence_period + if v == nil { + return + } + return *v, true +} + +// OldRecurrencePeriod returns the old "recurrence_period" field's value of the Grant entity. +// If the Grant 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 *GrantMutation) OldRecurrencePeriod(ctx context.Context) (v *datetime.ISODurationString, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRecurrencePeriod is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRecurrencePeriod requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRecurrencePeriod: %w", err) + } + return oldValue.RecurrencePeriod, nil +} + +// ClearRecurrencePeriod clears the value of the "recurrence_period" field. +func (m *GrantMutation) ClearRecurrencePeriod() { + m.recurrence_period = nil + m.clearedFields[dbgrant.FieldRecurrencePeriod] = struct{}{} +} + +// RecurrencePeriodCleared returns if the "recurrence_period" field was cleared in this mutation. +func (m *GrantMutation) RecurrencePeriodCleared() bool { + _, ok := m.clearedFields[dbgrant.FieldRecurrencePeriod] + return ok +} + +// ResetRecurrencePeriod resets all changes to the "recurrence_period" field. +func (m *GrantMutation) ResetRecurrencePeriod() { + m.recurrence_period = nil + delete(m.clearedFields, dbgrant.FieldRecurrencePeriod) +} + +// SetRecurrenceAnchor sets the "recurrence_anchor" field. +func (m *GrantMutation) SetRecurrenceAnchor(t time.Time) { + m.recurrence_anchor = &t +} + +// RecurrenceAnchor returns the value of the "recurrence_anchor" field in the mutation. +func (m *GrantMutation) RecurrenceAnchor() (r time.Time, exists bool) { + v := m.recurrence_anchor + if v == nil { + return + } + return *v, true +} + +// OldRecurrenceAnchor returns the old "recurrence_anchor" field's value of the Grant entity. +// If the Grant 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 *GrantMutation) OldRecurrenceAnchor(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRecurrenceAnchor is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRecurrenceAnchor requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRecurrenceAnchor: %w", err) + } + return oldValue.RecurrenceAnchor, nil +} + +// ClearRecurrenceAnchor clears the value of the "recurrence_anchor" field. +func (m *GrantMutation) ClearRecurrenceAnchor() { + m.recurrence_anchor = nil + m.clearedFields[dbgrant.FieldRecurrenceAnchor] = struct{}{} +} + +// RecurrenceAnchorCleared returns if the "recurrence_anchor" field was cleared in this mutation. +func (m *GrantMutation) RecurrenceAnchorCleared() bool { + _, ok := m.clearedFields[dbgrant.FieldRecurrenceAnchor] + return ok +} + +// ResetRecurrenceAnchor resets all changes to the "recurrence_anchor" field. +func (m *GrantMutation) ResetRecurrenceAnchor() { + m.recurrence_anchor = nil + delete(m.clearedFields, dbgrant.FieldRecurrenceAnchor) +} + +// SetEntitlementID sets the "entitlement" edge to the Entitlement entity by id. +func (m *GrantMutation) SetEntitlementID(id string) { + m.entitlement = &id +} + +// ClearEntitlement clears the "entitlement" edge to the Entitlement entity. +func (m *GrantMutation) ClearEntitlement() { + m.clearedentitlement = true + m.clearedFields[dbgrant.FieldOwnerID] = struct{}{} +} + +// EntitlementCleared reports if the "entitlement" edge to the Entitlement entity was cleared. +func (m *GrantMutation) EntitlementCleared() bool { + return m.clearedentitlement +} + +// EntitlementID returns the "entitlement" edge ID in the mutation. +func (m *GrantMutation) EntitlementID() (id string, exists bool) { + if m.entitlement != nil { + return *m.entitlement, true + } + return +} + +// EntitlementIDs returns the "entitlement" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// EntitlementID instead. It exists only for internal usage by the builders. +func (m *GrantMutation) EntitlementIDs() (ids []string) { + if id := m.entitlement; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetEntitlement resets all changes to the "entitlement" edge. +func (m *GrantMutation) ResetEntitlement() { + m.entitlement = nil + m.clearedentitlement = false +} + +// Where appends a list predicates to the GrantMutation builder. +func (m *GrantMutation) Where(ps ...predicate.Grant) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the GrantMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *GrantMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Grant, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *GrantMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *GrantMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Grant). +func (m *GrantMutation) 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 *GrantMutation) Fields() []string { + fields := make([]string, 0, 17) + if m.namespace != nil { + fields = append(fields, dbgrant.FieldNamespace) + } + if m.annotations != nil { + fields = append(fields, dbgrant.FieldAnnotations) + } + if m.created_at != nil { + fields = append(fields, dbgrant.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, dbgrant.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, dbgrant.FieldDeletedAt) + } + if m.metadata != nil { + fields = append(fields, dbgrant.FieldMetadata) + } + if m.entitlement != nil { + fields = append(fields, dbgrant.FieldOwnerID) + } + if m.amount != nil { + fields = append(fields, dbgrant.FieldAmount) + } + if m.priority != nil { + fields = append(fields, dbgrant.FieldPriority) + } + if m.effective_at != nil { + fields = append(fields, dbgrant.FieldEffectiveAt) + } + if m.expiration != nil { + fields = append(fields, dbgrant.FieldExpiration) + } + if m.expires_at != nil { + fields = append(fields, dbgrant.FieldExpiresAt) + } + if m.voided_at != nil { + fields = append(fields, dbgrant.FieldVoidedAt) + } + if m.reset_max_rollover != nil { + fields = append(fields, dbgrant.FieldResetMaxRollover) + } + if m.reset_min_rollover != nil { + fields = append(fields, dbgrant.FieldResetMinRollover) + } + if m.recurrence_period != nil { + fields = append(fields, dbgrant.FieldRecurrencePeriod) + } + if m.recurrence_anchor != nil { + fields = append(fields, dbgrant.FieldRecurrenceAnchor) + } + 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 *GrantMutation) Field(name string) (ent.Value, bool) { + switch name { + case dbgrant.FieldNamespace: + return m.Namespace() + case dbgrant.FieldAnnotations: + return m.Annotations() + case dbgrant.FieldCreatedAt: + return m.CreatedAt() + case dbgrant.FieldUpdatedAt: + return m.UpdatedAt() + case dbgrant.FieldDeletedAt: + return m.DeletedAt() + case dbgrant.FieldMetadata: + return m.Metadata() + case dbgrant.FieldOwnerID: + return m.OwnerID() + case dbgrant.FieldAmount: + return m.Amount() + case dbgrant.FieldPriority: + return m.Priority() + case dbgrant.FieldEffectiveAt: + return m.EffectiveAt() + case dbgrant.FieldExpiration: + return m.Expiration() + case dbgrant.FieldExpiresAt: + return m.ExpiresAt() + case dbgrant.FieldVoidedAt: + return m.VoidedAt() + case dbgrant.FieldResetMaxRollover: + return m.ResetMaxRollover() + case dbgrant.FieldResetMinRollover: + return m.ResetMinRollover() + case dbgrant.FieldRecurrencePeriod: + return m.RecurrencePeriod() + case dbgrant.FieldRecurrenceAnchor: + return m.RecurrenceAnchor() + } + 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 *GrantMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case dbgrant.FieldNamespace: + return m.OldNamespace(ctx) + case dbgrant.FieldAnnotations: + return m.OldAnnotations(ctx) + case dbgrant.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case dbgrant.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case dbgrant.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case dbgrant.FieldMetadata: + return m.OldMetadata(ctx) + case dbgrant.FieldOwnerID: + return m.OldOwnerID(ctx) + case dbgrant.FieldAmount: + return m.OldAmount(ctx) + case dbgrant.FieldPriority: + return m.OldPriority(ctx) + case dbgrant.FieldEffectiveAt: + return m.OldEffectiveAt(ctx) + case dbgrant.FieldExpiration: + return m.OldExpiration(ctx) + case dbgrant.FieldExpiresAt: + return m.OldExpiresAt(ctx) + case dbgrant.FieldVoidedAt: + return m.OldVoidedAt(ctx) + case dbgrant.FieldResetMaxRollover: + return m.OldResetMaxRollover(ctx) + case dbgrant.FieldResetMinRollover: + return m.OldResetMinRollover(ctx) + case dbgrant.FieldRecurrencePeriod: + return m.OldRecurrencePeriod(ctx) + case dbgrant.FieldRecurrenceAnchor: + return m.OldRecurrenceAnchor(ctx) + } + return nil, fmt.Errorf("unknown Grant 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 *GrantMutation) SetField(name string, value ent.Value) error { + switch name { + case dbgrant.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case dbgrant.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 dbgrant.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 dbgrant.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 dbgrant.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 dbgrant.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case dbgrant.FieldOwnerID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOwnerID(v) + return nil + case dbgrant.FieldAmount: + v, ok := value.(float64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAmount(v) + return nil + case dbgrant.FieldPriority: + v, ok := value.(uint8) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPriority(v) + return nil + case dbgrant.FieldEffectiveAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEffectiveAt(v) + return nil + case dbgrant.FieldExpiration: + v, ok := value.(*grant.ExpirationPeriod) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetExpiration(v) + return nil + case dbgrant.FieldExpiresAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetExpiresAt(v) + return nil + case dbgrant.FieldVoidedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVoidedAt(v) + return nil + case dbgrant.FieldResetMaxRollover: + v, ok := value.(float64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetResetMaxRollover(v) + return nil + case dbgrant.FieldResetMinRollover: + v, ok := value.(float64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetResetMinRollover(v) + return nil + case dbgrant.FieldRecurrencePeriod: + v, ok := value.(datetime.ISODurationString) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRecurrencePeriod(v) + return nil + case dbgrant.FieldRecurrenceAnchor: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRecurrenceAnchor(v) + return nil + } + return fmt.Errorf("unknown Grant field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *GrantMutation) AddedFields() []string { + var fields []string + if m.addamount != nil { + fields = append(fields, dbgrant.FieldAmount) + } + if m.addpriority != nil { + fields = append(fields, dbgrant.FieldPriority) + } + if m.addreset_max_rollover != nil { + fields = append(fields, dbgrant.FieldResetMaxRollover) + } + if m.addreset_min_rollover != nil { + fields = append(fields, dbgrant.FieldResetMinRollover) + } + return fields +} + +// 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 *GrantMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case dbgrant.FieldAmount: + return m.AddedAmount() + case dbgrant.FieldPriority: + return m.AddedPriority() + case dbgrant.FieldResetMaxRollover: + return m.AddedResetMaxRollover() + case dbgrant.FieldResetMinRollover: + return m.AddedResetMinRollover() + } + 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 *GrantMutation) AddField(name string, value ent.Value) error { + switch name { + case dbgrant.FieldAmount: + v, ok := value.(float64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddAmount(v) + return nil + case dbgrant.FieldPriority: + v, ok := value.(int8) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddPriority(v) + return nil + case dbgrant.FieldResetMaxRollover: + v, ok := value.(float64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddResetMaxRollover(v) + return nil + case dbgrant.FieldResetMinRollover: + v, ok := value.(float64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddResetMinRollover(v) + return nil + } + return fmt.Errorf("unknown Grant numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *GrantMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(dbgrant.FieldAnnotations) { + fields = append(fields, dbgrant.FieldAnnotations) + } + if m.FieldCleared(dbgrant.FieldDeletedAt) { + fields = append(fields, dbgrant.FieldDeletedAt) + } + if m.FieldCleared(dbgrant.FieldMetadata) { + fields = append(fields, dbgrant.FieldMetadata) + } + if m.FieldCleared(dbgrant.FieldExpiration) { + fields = append(fields, dbgrant.FieldExpiration) + } + if m.FieldCleared(dbgrant.FieldExpiresAt) { + fields = append(fields, dbgrant.FieldExpiresAt) + } + if m.FieldCleared(dbgrant.FieldVoidedAt) { + fields = append(fields, dbgrant.FieldVoidedAt) + } + if m.FieldCleared(dbgrant.FieldRecurrencePeriod) { + fields = append(fields, dbgrant.FieldRecurrencePeriod) + } + if m.FieldCleared(dbgrant.FieldRecurrenceAnchor) { + fields = append(fields, dbgrant.FieldRecurrenceAnchor) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *GrantMutation) 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 *GrantMutation) ClearField(name string) error { + switch name { + case dbgrant.FieldAnnotations: + m.ClearAnnotations() + return nil + case dbgrant.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case dbgrant.FieldMetadata: + m.ClearMetadata() + return nil + case dbgrant.FieldExpiration: + m.ClearExpiration() + return nil + case dbgrant.FieldExpiresAt: + m.ClearExpiresAt() + return nil + case dbgrant.FieldVoidedAt: + m.ClearVoidedAt() + return nil + case dbgrant.FieldRecurrencePeriod: + m.ClearRecurrencePeriod() + return nil + case dbgrant.FieldRecurrenceAnchor: + m.ClearRecurrenceAnchor() + return nil + } + return fmt.Errorf("unknown Grant 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 *GrantMutation) ResetField(name string) error { + switch name { + case dbgrant.FieldNamespace: + m.ResetNamespace() + return nil + case dbgrant.FieldAnnotations: + m.ResetAnnotations() + return nil + case dbgrant.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case dbgrant.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case dbgrant.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case dbgrant.FieldMetadata: + m.ResetMetadata() + return nil + case dbgrant.FieldOwnerID: + m.ResetOwnerID() + return nil + case dbgrant.FieldAmount: + m.ResetAmount() + return nil + case dbgrant.FieldPriority: + m.ResetPriority() + return nil + case dbgrant.FieldEffectiveAt: + m.ResetEffectiveAt() + return nil + case dbgrant.FieldExpiration: + m.ResetExpiration() + return nil + case dbgrant.FieldExpiresAt: + m.ResetExpiresAt() + return nil + case dbgrant.FieldVoidedAt: + m.ResetVoidedAt() + return nil + case dbgrant.FieldResetMaxRollover: + m.ResetResetMaxRollover() + return nil + case dbgrant.FieldResetMinRollover: + m.ResetResetMinRollover() + return nil + case dbgrant.FieldRecurrencePeriod: + m.ResetRecurrencePeriod() + return nil + case dbgrant.FieldRecurrenceAnchor: + m.ResetRecurrenceAnchor() + return nil + } + return fmt.Errorf("unknown Grant field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *GrantMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.entitlement != nil { + edges = append(edges, dbgrant.EdgeEntitlement) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *GrantMutation) AddedIDs(name string) []ent.Value { + switch name { + case dbgrant.EdgeEntitlement: + if id := m.entitlement; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *GrantMutation) 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 *GrantMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *GrantMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedentitlement { + edges = append(edges, dbgrant.EdgeEntitlement) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *GrantMutation) EdgeCleared(name string) bool { + switch name { + case dbgrant.EdgeEntitlement: + return m.clearedentitlement + } + 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 *GrantMutation) ClearEdge(name string) error { + switch name { + case dbgrant.EdgeEntitlement: + m.ClearEntitlement() + return nil + } + return fmt.Errorf("unknown Grant 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 *GrantMutation) ResetEdge(name string) error { + switch name { + case dbgrant.EdgeEntitlement: + m.ResetEntitlement() + return nil + } + return fmt.Errorf("unknown Grant edge %s", name) +} + +// LLMCostPriceMutation represents an operation that mutates the LLMCostPrice nodes in the graph. +type LLMCostPriceMutation struct { + config + op Op + typ string + id *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + namespace *string + provider *string + model_id *string + model_name *string + input_per_token *alpacadecimal.Decimal + output_per_token *alpacadecimal.Decimal + cache_read_per_token *alpacadecimal.Decimal + reasoning_per_token *alpacadecimal.Decimal + cache_write_per_token *alpacadecimal.Decimal + currency *string + source *string + source_prices *llmcost.SourcePricesMap + effective_from *time.Time + effective_to *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*LLMCostPrice, error) + predicates []predicate.LLMCostPrice +} + +var _ ent.Mutation = (*LLMCostPriceMutation)(nil) + +// llmcostpriceOption allows management of the mutation configuration using functional options. +type llmcostpriceOption func(*LLMCostPriceMutation) + +// newLLMCostPriceMutation creates new mutation for the LLMCostPrice entity. +func newLLMCostPriceMutation(c config, op Op, opts ...llmcostpriceOption) *LLMCostPriceMutation { + m := &LLMCostPriceMutation{ + config: c, + op: op, + typ: TypeLLMCostPrice, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLLMCostPriceID sets the ID field of the mutation. +func withLLMCostPriceID(id string) llmcostpriceOption { + return func(m *LLMCostPriceMutation) { + var ( + err error + once sync.Once + value *LLMCostPrice + ) + m.oldValue = func(ctx context.Context) (*LLMCostPrice, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LLMCostPrice.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLLMCostPrice sets the old LLMCostPrice of the mutation. +func withLLMCostPrice(node *LLMCostPrice) llmcostpriceOption { + return func(m *LLMCostPriceMutation) { + m.oldValue = func(context.Context) (*LLMCostPrice, 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 LLMCostPriceMutation) 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 LLMCostPriceMutation) 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 LLMCostPrice entities. +func (m *LLMCostPriceMutation) 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 *LLMCostPriceMutation) 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 *LLMCostPriceMutation) 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().LLMCostPrice.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetMetadata sets the "metadata" field. +func (m *LLMCostPriceMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *LLMCostPriceMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the LLMCostPrice entity. +// If the LLMCostPrice 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 *LLMCostPriceMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *LLMCostPriceMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[llmcostprice.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *LLMCostPriceMutation) MetadataCleared() bool { + _, ok := m.clearedFields[llmcostprice.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *LLMCostPriceMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, llmcostprice.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *LLMCostPriceMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *LLMCostPriceMutation) 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 LLMCostPrice entity. +// If the LLMCostPrice 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 *LLMCostPriceMutation) 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 *LLMCostPriceMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *LLMCostPriceMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *LLMCostPriceMutation) 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 LLMCostPrice entity. +// If the LLMCostPrice 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 *LLMCostPriceMutation) 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 *LLMCostPriceMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *LLMCostPriceMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *LLMCostPriceMutation) 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 LLMCostPrice entity. +// If the LLMCostPrice 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 *LLMCostPriceMutation) 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 *LLMCostPriceMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[llmcostprice.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *LLMCostPriceMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[llmcostprice.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *LLMCostPriceMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, llmcostprice.FieldDeletedAt) +} + +// SetNamespace sets the "namespace" field. +func (m *LLMCostPriceMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *LLMCostPriceMutation) 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 LLMCostPrice entity. +// If the LLMCostPrice 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 *LLMCostPriceMutation) 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 +} + +// ClearNamespace clears the value of the "namespace" field. +func (m *LLMCostPriceMutation) ClearNamespace() { + m.namespace = nil + m.clearedFields[llmcostprice.FieldNamespace] = struct{}{} +} + +// NamespaceCleared returns if the "namespace" field was cleared in this mutation. +func (m *LLMCostPriceMutation) NamespaceCleared() bool { + _, ok := m.clearedFields[llmcostprice.FieldNamespace] + return ok +} + +// ResetNamespace resets all changes to the "namespace" field. +func (m *LLMCostPriceMutation) ResetNamespace() { + m.namespace = nil + delete(m.clearedFields, llmcostprice.FieldNamespace) +} + +// SetProvider sets the "provider" field. +func (m *LLMCostPriceMutation) SetProvider(s string) { + m.provider = &s +} + +// Provider returns the value of the "provider" field in the mutation. +func (m *LLMCostPriceMutation) Provider() (r string, exists bool) { + v := m.provider + if v == nil { + return + } + return *v, true +} + +// OldProvider returns the old "provider" field's value of the LLMCostPrice entity. +// If the LLMCostPrice 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 *LLMCostPriceMutation) OldProvider(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldProvider is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldProvider requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldProvider: %w", err) + } + return oldValue.Provider, nil +} + +// ResetProvider resets all changes to the "provider" field. +func (m *LLMCostPriceMutation) ResetProvider() { + m.provider = nil +} + +// SetModelID sets the "model_id" field. +func (m *LLMCostPriceMutation) SetModelID(s string) { + m.model_id = &s +} + +// ModelID returns the value of the "model_id" field in the mutation. +func (m *LLMCostPriceMutation) ModelID() (r string, exists bool) { + v := m.model_id + if v == nil { + return + } + return *v, true +} + +// OldModelID returns the old "model_id" field's value of the LLMCostPrice entity. +// If the LLMCostPrice 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 *LLMCostPriceMutation) OldModelID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldModelID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldModelID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldModelID: %w", err) + } + return oldValue.ModelID, nil +} + +// ResetModelID resets all changes to the "model_id" field. +func (m *LLMCostPriceMutation) ResetModelID() { + m.model_id = nil +} + +// SetModelName sets the "model_name" field. +func (m *LLMCostPriceMutation) SetModelName(s string) { + m.model_name = &s +} + +// ModelName returns the value of the "model_name" field in the mutation. +func (m *LLMCostPriceMutation) ModelName() (r string, exists bool) { + v := m.model_name + if v == nil { + return + } + return *v, true +} + +// OldModelName returns the old "model_name" field's value of the LLMCostPrice entity. +// If the LLMCostPrice 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 *LLMCostPriceMutation) OldModelName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldModelName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldModelName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldModelName: %w", err) + } + return oldValue.ModelName, nil +} + +// ResetModelName resets all changes to the "model_name" field. +func (m *LLMCostPriceMutation) ResetModelName() { + m.model_name = nil +} + +// SetInputPerToken sets the "input_per_token" field. +func (m *LLMCostPriceMutation) SetInputPerToken(a alpacadecimal.Decimal) { + m.input_per_token = &a +} + +// InputPerToken returns the value of the "input_per_token" field in the mutation. +func (m *LLMCostPriceMutation) InputPerToken() (r alpacadecimal.Decimal, exists bool) { + v := m.input_per_token + if v == nil { + return + } + return *v, true +} + +// OldInputPerToken returns the old "input_per_token" field's value of the LLMCostPrice entity. +// If the LLMCostPrice 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 *LLMCostPriceMutation) OldInputPerToken(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInputPerToken is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInputPerToken requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInputPerToken: %w", err) + } + return oldValue.InputPerToken, nil +} + +// ResetInputPerToken resets all changes to the "input_per_token" field. +func (m *LLMCostPriceMutation) ResetInputPerToken() { + m.input_per_token = nil +} + +// SetOutputPerToken sets the "output_per_token" field. +func (m *LLMCostPriceMutation) SetOutputPerToken(a alpacadecimal.Decimal) { + m.output_per_token = &a +} + +// OutputPerToken returns the value of the "output_per_token" field in the mutation. +func (m *LLMCostPriceMutation) OutputPerToken() (r alpacadecimal.Decimal, exists bool) { + v := m.output_per_token + if v == nil { + return + } + return *v, true +} + +// OldOutputPerToken returns the old "output_per_token" field's value of the LLMCostPrice entity. +// If the LLMCostPrice 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 *LLMCostPriceMutation) OldOutputPerToken(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOutputPerToken is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOutputPerToken requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOutputPerToken: %w", err) + } + return oldValue.OutputPerToken, nil +} + +// ResetOutputPerToken resets all changes to the "output_per_token" field. +func (m *LLMCostPriceMutation) ResetOutputPerToken() { + m.output_per_token = nil +} + +// SetCacheReadPerToken sets the "cache_read_per_token" field. +func (m *LLMCostPriceMutation) SetCacheReadPerToken(a alpacadecimal.Decimal) { + m.cache_read_per_token = &a +} + +// CacheReadPerToken returns the value of the "cache_read_per_token" field in the mutation. +func (m *LLMCostPriceMutation) CacheReadPerToken() (r alpacadecimal.Decimal, exists bool) { + v := m.cache_read_per_token + if v == nil { + return + } + return *v, true +} + +// OldCacheReadPerToken returns the old "cache_read_per_token" field's value of the LLMCostPrice entity. +// If the LLMCostPrice 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 *LLMCostPriceMutation) OldCacheReadPerToken(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCacheReadPerToken is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCacheReadPerToken requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCacheReadPerToken: %w", err) + } + return oldValue.CacheReadPerToken, nil +} + +// ResetCacheReadPerToken resets all changes to the "cache_read_per_token" field. +func (m *LLMCostPriceMutation) ResetCacheReadPerToken() { + m.cache_read_per_token = nil +} + +// SetReasoningPerToken sets the "reasoning_per_token" field. +func (m *LLMCostPriceMutation) SetReasoningPerToken(a alpacadecimal.Decimal) { + m.reasoning_per_token = &a +} + +// ReasoningPerToken returns the value of the "reasoning_per_token" field in the mutation. +func (m *LLMCostPriceMutation) ReasoningPerToken() (r alpacadecimal.Decimal, exists bool) { + v := m.reasoning_per_token + if v == nil { + return + } + return *v, true +} + +// OldReasoningPerToken returns the old "reasoning_per_token" field's value of the LLMCostPrice entity. +// If the LLMCostPrice 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 *LLMCostPriceMutation) OldReasoningPerToken(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldReasoningPerToken is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldReasoningPerToken requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldReasoningPerToken: %w", err) + } + return oldValue.ReasoningPerToken, nil +} + +// ResetReasoningPerToken resets all changes to the "reasoning_per_token" field. +func (m *LLMCostPriceMutation) ResetReasoningPerToken() { + m.reasoning_per_token = nil +} + +// SetCacheWritePerToken sets the "cache_write_per_token" field. +func (m *LLMCostPriceMutation) SetCacheWritePerToken(a alpacadecimal.Decimal) { + m.cache_write_per_token = &a +} + +// CacheWritePerToken returns the value of the "cache_write_per_token" field in the mutation. +func (m *LLMCostPriceMutation) CacheWritePerToken() (r alpacadecimal.Decimal, exists bool) { + v := m.cache_write_per_token + if v == nil { + return + } + return *v, true +} + +// OldCacheWritePerToken returns the old "cache_write_per_token" field's value of the LLMCostPrice entity. +// If the LLMCostPrice 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 *LLMCostPriceMutation) OldCacheWritePerToken(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCacheWritePerToken is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCacheWritePerToken requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCacheWritePerToken: %w", err) + } + return oldValue.CacheWritePerToken, nil +} + +// ResetCacheWritePerToken resets all changes to the "cache_write_per_token" field. +func (m *LLMCostPriceMutation) ResetCacheWritePerToken() { + m.cache_write_per_token = nil +} + +// SetCurrency sets the "currency" field. +func (m *LLMCostPriceMutation) SetCurrency(s string) { + m.currency = &s +} + +// Currency returns the value of the "currency" field in the mutation. +func (m *LLMCostPriceMutation) Currency() (r string, exists bool) { + v := m.currency + if v == nil { + return + } + return *v, true +} + +// OldCurrency returns the old "currency" field's value of the LLMCostPrice entity. +// If the LLMCostPrice 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 *LLMCostPriceMutation) OldCurrency(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrency is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrency requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrency: %w", err) + } + return oldValue.Currency, nil +} + +// ResetCurrency resets all changes to the "currency" field. +func (m *LLMCostPriceMutation) ResetCurrency() { + m.currency = nil +} + +// SetSource sets the "source" field. +func (m *LLMCostPriceMutation) SetSource(s string) { + m.source = &s +} + +// Source returns the value of the "source" field in the mutation. +func (m *LLMCostPriceMutation) Source() (r string, exists bool) { + v := m.source + if v == nil { + return + } + return *v, true +} + +// OldSource returns the old "source" field's value of the LLMCostPrice entity. +// If the LLMCostPrice 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 *LLMCostPriceMutation) OldSource(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSource is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSource requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSource: %w", err) + } + return oldValue.Source, nil +} + +// ResetSource resets all changes to the "source" field. +func (m *LLMCostPriceMutation) ResetSource() { + m.source = nil +} + +// SetSourcePrices sets the "source_prices" field. +func (m *LLMCostPriceMutation) SetSourcePrices(lpm llmcost.SourcePricesMap) { + m.source_prices = &lpm +} + +// SourcePrices returns the value of the "source_prices" field in the mutation. +func (m *LLMCostPriceMutation) SourcePrices() (r llmcost.SourcePricesMap, exists bool) { + v := m.source_prices + if v == nil { + return + } + return *v, true +} + +// OldSourcePrices returns the old "source_prices" field's value of the LLMCostPrice entity. +// If the LLMCostPrice 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 *LLMCostPriceMutation) OldSourcePrices(ctx context.Context) (v llmcost.SourcePricesMap, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSourcePrices is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSourcePrices requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSourcePrices: %w", err) + } + return oldValue.SourcePrices, nil +} + +// ClearSourcePrices clears the value of the "source_prices" field. +func (m *LLMCostPriceMutation) ClearSourcePrices() { + m.source_prices = nil + m.clearedFields[llmcostprice.FieldSourcePrices] = struct{}{} +} + +// SourcePricesCleared returns if the "source_prices" field was cleared in this mutation. +func (m *LLMCostPriceMutation) SourcePricesCleared() bool { + _, ok := m.clearedFields[llmcostprice.FieldSourcePrices] + return ok +} + +// ResetSourcePrices resets all changes to the "source_prices" field. +func (m *LLMCostPriceMutation) ResetSourcePrices() { + m.source_prices = nil + delete(m.clearedFields, llmcostprice.FieldSourcePrices) +} + +// SetEffectiveFrom sets the "effective_from" field. +func (m *LLMCostPriceMutation) SetEffectiveFrom(t time.Time) { + m.effective_from = &t +} + +// EffectiveFrom returns the value of the "effective_from" field in the mutation. +func (m *LLMCostPriceMutation) EffectiveFrom() (r time.Time, exists bool) { + v := m.effective_from + if v == nil { + return + } + return *v, true +} + +// OldEffectiveFrom returns the old "effective_from" field's value of the LLMCostPrice entity. +// If the LLMCostPrice 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 *LLMCostPriceMutation) OldEffectiveFrom(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEffectiveFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEffectiveFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEffectiveFrom: %w", err) + } + return oldValue.EffectiveFrom, nil +} + +// ResetEffectiveFrom resets all changes to the "effective_from" field. +func (m *LLMCostPriceMutation) ResetEffectiveFrom() { + m.effective_from = nil +} + +// SetEffectiveTo sets the "effective_to" field. +func (m *LLMCostPriceMutation) SetEffectiveTo(t time.Time) { + m.effective_to = &t +} + +// EffectiveTo returns the value of the "effective_to" field in the mutation. +func (m *LLMCostPriceMutation) EffectiveTo() (r time.Time, exists bool) { + v := m.effective_to + if v == nil { + return + } + return *v, true +} + +// OldEffectiveTo returns the old "effective_to" field's value of the LLMCostPrice entity. +// If the LLMCostPrice 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 *LLMCostPriceMutation) OldEffectiveTo(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEffectiveTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEffectiveTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEffectiveTo: %w", err) + } + return oldValue.EffectiveTo, nil +} + +// ClearEffectiveTo clears the value of the "effective_to" field. +func (m *LLMCostPriceMutation) ClearEffectiveTo() { + m.effective_to = nil + m.clearedFields[llmcostprice.FieldEffectiveTo] = struct{}{} +} + +// EffectiveToCleared returns if the "effective_to" field was cleared in this mutation. +func (m *LLMCostPriceMutation) EffectiveToCleared() bool { + _, ok := m.clearedFields[llmcostprice.FieldEffectiveTo] + return ok +} + +// ResetEffectiveTo resets all changes to the "effective_to" field. +func (m *LLMCostPriceMutation) ResetEffectiveTo() { + m.effective_to = nil + delete(m.clearedFields, llmcostprice.FieldEffectiveTo) +} + +// Where appends a list predicates to the LLMCostPriceMutation builder. +func (m *LLMCostPriceMutation) Where(ps ...predicate.LLMCostPrice) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the LLMCostPriceMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *LLMCostPriceMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.LLMCostPrice, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *LLMCostPriceMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *LLMCostPriceMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (LLMCostPrice). +func (m *LLMCostPriceMutation) 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 *LLMCostPriceMutation) Fields() []string { + fields := make([]string, 0, 18) + if m.metadata != nil { + fields = append(fields, llmcostprice.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, llmcostprice.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, llmcostprice.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, llmcostprice.FieldDeletedAt) + } + if m.namespace != nil { + fields = append(fields, llmcostprice.FieldNamespace) + } + if m.provider != nil { + fields = append(fields, llmcostprice.FieldProvider) + } + if m.model_id != nil { + fields = append(fields, llmcostprice.FieldModelID) + } + if m.model_name != nil { + fields = append(fields, llmcostprice.FieldModelName) + } + if m.input_per_token != nil { + fields = append(fields, llmcostprice.FieldInputPerToken) + } + if m.output_per_token != nil { + fields = append(fields, llmcostprice.FieldOutputPerToken) + } + if m.cache_read_per_token != nil { + fields = append(fields, llmcostprice.FieldCacheReadPerToken) + } + if m.reasoning_per_token != nil { + fields = append(fields, llmcostprice.FieldReasoningPerToken) + } + if m.cache_write_per_token != nil { + fields = append(fields, llmcostprice.FieldCacheWritePerToken) + } + if m.currency != nil { + fields = append(fields, llmcostprice.FieldCurrency) + } + if m.source != nil { + fields = append(fields, llmcostprice.FieldSource) + } + if m.source_prices != nil { + fields = append(fields, llmcostprice.FieldSourcePrices) + } + if m.effective_from != nil { + fields = append(fields, llmcostprice.FieldEffectiveFrom) + } + if m.effective_to != nil { + fields = append(fields, llmcostprice.FieldEffectiveTo) + } + 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 *LLMCostPriceMutation) Field(name string) (ent.Value, bool) { + switch name { + case llmcostprice.FieldMetadata: + return m.Metadata() + case llmcostprice.FieldCreatedAt: + return m.CreatedAt() + case llmcostprice.FieldUpdatedAt: + return m.UpdatedAt() + case llmcostprice.FieldDeletedAt: + return m.DeletedAt() + case llmcostprice.FieldNamespace: + return m.Namespace() + case llmcostprice.FieldProvider: + return m.Provider() + case llmcostprice.FieldModelID: + return m.ModelID() + case llmcostprice.FieldModelName: + return m.ModelName() + case llmcostprice.FieldInputPerToken: + return m.InputPerToken() + case llmcostprice.FieldOutputPerToken: + return m.OutputPerToken() + case llmcostprice.FieldCacheReadPerToken: + return m.CacheReadPerToken() + case llmcostprice.FieldReasoningPerToken: + return m.ReasoningPerToken() + case llmcostprice.FieldCacheWritePerToken: + return m.CacheWritePerToken() + case llmcostprice.FieldCurrency: + return m.Currency() + case llmcostprice.FieldSource: + return m.Source() + case llmcostprice.FieldSourcePrices: + return m.SourcePrices() + case llmcostprice.FieldEffectiveFrom: + return m.EffectiveFrom() + case llmcostprice.FieldEffectiveTo: + return m.EffectiveTo() + } + 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 *LLMCostPriceMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case llmcostprice.FieldMetadata: + return m.OldMetadata(ctx) + case llmcostprice.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case llmcostprice.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case llmcostprice.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case llmcostprice.FieldNamespace: + return m.OldNamespace(ctx) + case llmcostprice.FieldProvider: + return m.OldProvider(ctx) + case llmcostprice.FieldModelID: + return m.OldModelID(ctx) + case llmcostprice.FieldModelName: + return m.OldModelName(ctx) + case llmcostprice.FieldInputPerToken: + return m.OldInputPerToken(ctx) + case llmcostprice.FieldOutputPerToken: + return m.OldOutputPerToken(ctx) + case llmcostprice.FieldCacheReadPerToken: + return m.OldCacheReadPerToken(ctx) + case llmcostprice.FieldReasoningPerToken: + return m.OldReasoningPerToken(ctx) + case llmcostprice.FieldCacheWritePerToken: + return m.OldCacheWritePerToken(ctx) + case llmcostprice.FieldCurrency: + return m.OldCurrency(ctx) + case llmcostprice.FieldSource: + return m.OldSource(ctx) + case llmcostprice.FieldSourcePrices: + return m.OldSourcePrices(ctx) + case llmcostprice.FieldEffectiveFrom: + return m.OldEffectiveFrom(ctx) + case llmcostprice.FieldEffectiveTo: + return m.OldEffectiveTo(ctx) + } + return nil, fmt.Errorf("unknown LLMCostPrice 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 *LLMCostPriceMutation) SetField(name string, value ent.Value) error { + switch name { + case llmcostprice.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case llmcostprice.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 llmcostprice.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 llmcostprice.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 llmcostprice.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case llmcostprice.FieldProvider: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetProvider(v) + return nil + case llmcostprice.FieldModelID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetModelID(v) + return nil + case llmcostprice.FieldModelName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetModelName(v) + return nil + case llmcostprice.FieldInputPerToken: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInputPerToken(v) + return nil + case llmcostprice.FieldOutputPerToken: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOutputPerToken(v) + return nil + case llmcostprice.FieldCacheReadPerToken: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCacheReadPerToken(v) + return nil + case llmcostprice.FieldReasoningPerToken: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetReasoningPerToken(v) + return nil + case llmcostprice.FieldCacheWritePerToken: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCacheWritePerToken(v) + return nil + case llmcostprice.FieldCurrency: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrency(v) + return nil + case llmcostprice.FieldSource: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSource(v) + return nil + case llmcostprice.FieldSourcePrices: + v, ok := value.(llmcost.SourcePricesMap) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSourcePrices(v) + return nil + case llmcostprice.FieldEffectiveFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEffectiveFrom(v) + return nil + case llmcostprice.FieldEffectiveTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEffectiveTo(v) + return nil + } + return fmt.Errorf("unknown LLMCostPrice field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LLMCostPriceMutation) 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 *LLMCostPriceMutation) 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 *LLMCostPriceMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown LLMCostPrice numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LLMCostPriceMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(llmcostprice.FieldMetadata) { + fields = append(fields, llmcostprice.FieldMetadata) + } + if m.FieldCleared(llmcostprice.FieldDeletedAt) { + fields = append(fields, llmcostprice.FieldDeletedAt) + } + if m.FieldCleared(llmcostprice.FieldNamespace) { + fields = append(fields, llmcostprice.FieldNamespace) + } + if m.FieldCleared(llmcostprice.FieldSourcePrices) { + fields = append(fields, llmcostprice.FieldSourcePrices) + } + if m.FieldCleared(llmcostprice.FieldEffectiveTo) { + fields = append(fields, llmcostprice.FieldEffectiveTo) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LLMCostPriceMutation) 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 *LLMCostPriceMutation) ClearField(name string) error { + switch name { + case llmcostprice.FieldMetadata: + m.ClearMetadata() + return nil + case llmcostprice.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case llmcostprice.FieldNamespace: + m.ClearNamespace() + return nil + case llmcostprice.FieldSourcePrices: + m.ClearSourcePrices() + return nil + case llmcostprice.FieldEffectiveTo: + m.ClearEffectiveTo() + return nil + } + return fmt.Errorf("unknown LLMCostPrice 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 *LLMCostPriceMutation) ResetField(name string) error { + switch name { + case llmcostprice.FieldMetadata: + m.ResetMetadata() + return nil + case llmcostprice.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case llmcostprice.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case llmcostprice.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case llmcostprice.FieldNamespace: + m.ResetNamespace() + return nil + case llmcostprice.FieldProvider: + m.ResetProvider() + return nil + case llmcostprice.FieldModelID: + m.ResetModelID() + return nil + case llmcostprice.FieldModelName: + m.ResetModelName() + return nil + case llmcostprice.FieldInputPerToken: + m.ResetInputPerToken() + return nil + case llmcostprice.FieldOutputPerToken: + m.ResetOutputPerToken() + return nil + case llmcostprice.FieldCacheReadPerToken: + m.ResetCacheReadPerToken() + return nil + case llmcostprice.FieldReasoningPerToken: + m.ResetReasoningPerToken() + return nil + case llmcostprice.FieldCacheWritePerToken: + m.ResetCacheWritePerToken() + return nil + case llmcostprice.FieldCurrency: + m.ResetCurrency() + return nil + case llmcostprice.FieldSource: + m.ResetSource() + return nil + case llmcostprice.FieldSourcePrices: + m.ResetSourcePrices() + return nil + case llmcostprice.FieldEffectiveFrom: + m.ResetEffectiveFrom() + return nil + case llmcostprice.FieldEffectiveTo: + m.ResetEffectiveTo() + return nil + } + return fmt.Errorf("unknown LLMCostPrice field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LLMCostPriceMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LLMCostPriceMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LLMCostPriceMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LLMCostPriceMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LLMCostPriceMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LLMCostPriceMutation) EdgeCleared(name string) bool { + 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 *LLMCostPriceMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown LLMCostPrice 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 *LLMCostPriceMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown LLMCostPrice edge %s", name) +} + +// LedgerAccountMutation represents an operation that mutates the LedgerAccount nodes in the graph. +type LedgerAccountMutation struct { + config + op Op + typ string + id *string + namespace *string + annotations *models.Annotations + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + account_type *ledger.AccountType + clearedFields map[string]struct{} + sub_accounts map[string]struct{} + removedsub_accounts map[string]struct{} + clearedsub_accounts bool + sub_account_routes map[string]struct{} + removedsub_account_routes map[string]struct{} + clearedsub_account_routes bool + customer_accounts map[string]struct{} + removedcustomer_accounts map[string]struct{} + clearedcustomer_accounts bool + done bool + oldValue func(context.Context) (*LedgerAccount, error) + predicates []predicate.LedgerAccount +} + +var _ ent.Mutation = (*LedgerAccountMutation)(nil) + +// ledgeraccountOption allows management of the mutation configuration using functional options. +type ledgeraccountOption func(*LedgerAccountMutation) + +// newLedgerAccountMutation creates new mutation for the LedgerAccount entity. +func newLedgerAccountMutation(c config, op Op, opts ...ledgeraccountOption) *LedgerAccountMutation { + m := &LedgerAccountMutation{ + config: c, + op: op, + typ: TypeLedgerAccount, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLedgerAccountID sets the ID field of the mutation. +func withLedgerAccountID(id string) ledgeraccountOption { + return func(m *LedgerAccountMutation) { + var ( + err error + once sync.Once + value *LedgerAccount + ) + m.oldValue = func(ctx context.Context) (*LedgerAccount, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LedgerAccount.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLedgerAccount sets the old LedgerAccount of the mutation. +func withLedgerAccount(node *LedgerAccount) ledgeraccountOption { + return func(m *LedgerAccountMutation) { + m.oldValue = func(context.Context) (*LedgerAccount, 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 LedgerAccountMutation) 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 LedgerAccountMutation) 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 LedgerAccount entities. +func (m *LedgerAccountMutation) 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 *LedgerAccountMutation) 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 *LedgerAccountMutation) 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().LedgerAccount.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 *LedgerAccountMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *LedgerAccountMutation) 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 LedgerAccount entity. +// If the LedgerAccount 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 *LedgerAccountMutation) 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 *LedgerAccountMutation) ResetNamespace() { + m.namespace = nil +} + +// SetAnnotations sets the "annotations" field. +func (m *LedgerAccountMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *LedgerAccountMutation) 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 LedgerAccount entity. +// If the LedgerAccount 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 *LedgerAccountMutation) 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 *LedgerAccountMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[ledgeraccount.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *LedgerAccountMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[ledgeraccount.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *LedgerAccountMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, ledgeraccount.FieldAnnotations) +} + +// SetCreatedAt sets the "created_at" field. +func (m *LedgerAccountMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *LedgerAccountMutation) 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 LedgerAccount entity. +// If the LedgerAccount 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 *LedgerAccountMutation) 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 *LedgerAccountMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *LedgerAccountMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *LedgerAccountMutation) 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 LedgerAccount entity. +// If the LedgerAccount 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 *LedgerAccountMutation) 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 *LedgerAccountMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *LedgerAccountMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *LedgerAccountMutation) 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 LedgerAccount entity. +// If the LedgerAccount 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 *LedgerAccountMutation) 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 *LedgerAccountMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[ledgeraccount.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *LedgerAccountMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[ledgeraccount.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *LedgerAccountMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, ledgeraccount.FieldDeletedAt) +} + +// SetAccountType sets the "account_type" field. +func (m *LedgerAccountMutation) SetAccountType(lt ledger.AccountType) { + m.account_type = < +} + +// AccountType returns the value of the "account_type" field in the mutation. +func (m *LedgerAccountMutation) AccountType() (r ledger.AccountType, exists bool) { + v := m.account_type + if v == nil { + return + } + return *v, true +} + +// OldAccountType returns the old "account_type" field's value of the LedgerAccount entity. +// If the LedgerAccount 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 *LedgerAccountMutation) OldAccountType(ctx context.Context) (v ledger.AccountType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAccountType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAccountType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAccountType: %w", err) + } + return oldValue.AccountType, nil +} + +// ResetAccountType resets all changes to the "account_type" field. +func (m *LedgerAccountMutation) ResetAccountType() { + m.account_type = nil +} + +// AddSubAccountIDs adds the "sub_accounts" edge to the LedgerSubAccount entity by ids. +func (m *LedgerAccountMutation) AddSubAccountIDs(ids ...string) { + if m.sub_accounts == nil { + m.sub_accounts = make(map[string]struct{}) + } + for i := range ids { + m.sub_accounts[ids[i]] = struct{}{} + } +} + +// ClearSubAccounts clears the "sub_accounts" edge to the LedgerSubAccount entity. +func (m *LedgerAccountMutation) ClearSubAccounts() { + m.clearedsub_accounts = true +} + +// SubAccountsCleared reports if the "sub_accounts" edge to the LedgerSubAccount entity was cleared. +func (m *LedgerAccountMutation) SubAccountsCleared() bool { + return m.clearedsub_accounts +} + +// RemoveSubAccountIDs removes the "sub_accounts" edge to the LedgerSubAccount entity by IDs. +func (m *LedgerAccountMutation) RemoveSubAccountIDs(ids ...string) { + if m.removedsub_accounts == nil { + m.removedsub_accounts = make(map[string]struct{}) + } + for i := range ids { + delete(m.sub_accounts, ids[i]) + m.removedsub_accounts[ids[i]] = struct{}{} + } +} + +// RemovedSubAccounts returns the removed IDs of the "sub_accounts" edge to the LedgerSubAccount entity. +func (m *LedgerAccountMutation) RemovedSubAccountsIDs() (ids []string) { + for id := range m.removedsub_accounts { + ids = append(ids, id) + } + return +} + +// SubAccountsIDs returns the "sub_accounts" edge IDs in the mutation. +func (m *LedgerAccountMutation) SubAccountsIDs() (ids []string) { + for id := range m.sub_accounts { + ids = append(ids, id) + } + return +} + +// ResetSubAccounts resets all changes to the "sub_accounts" edge. +func (m *LedgerAccountMutation) ResetSubAccounts() { + m.sub_accounts = nil + m.clearedsub_accounts = false + m.removedsub_accounts = nil +} + +// AddSubAccountRouteIDs adds the "sub_account_routes" edge to the LedgerSubAccountRoute entity by ids. +func (m *LedgerAccountMutation) AddSubAccountRouteIDs(ids ...string) { + if m.sub_account_routes == nil { + m.sub_account_routes = make(map[string]struct{}) + } + for i := range ids { + m.sub_account_routes[ids[i]] = struct{}{} + } +} + +// ClearSubAccountRoutes clears the "sub_account_routes" edge to the LedgerSubAccountRoute entity. +func (m *LedgerAccountMutation) ClearSubAccountRoutes() { + m.clearedsub_account_routes = true +} + +// SubAccountRoutesCleared reports if the "sub_account_routes" edge to the LedgerSubAccountRoute entity was cleared. +func (m *LedgerAccountMutation) SubAccountRoutesCleared() bool { + return m.clearedsub_account_routes +} + +// RemoveSubAccountRouteIDs removes the "sub_account_routes" edge to the LedgerSubAccountRoute entity by IDs. +func (m *LedgerAccountMutation) RemoveSubAccountRouteIDs(ids ...string) { + if m.removedsub_account_routes == nil { + m.removedsub_account_routes = make(map[string]struct{}) + } + for i := range ids { + delete(m.sub_account_routes, ids[i]) + m.removedsub_account_routes[ids[i]] = struct{}{} + } +} + +// RemovedSubAccountRoutes returns the removed IDs of the "sub_account_routes" edge to the LedgerSubAccountRoute entity. +func (m *LedgerAccountMutation) RemovedSubAccountRoutesIDs() (ids []string) { + for id := range m.removedsub_account_routes { + ids = append(ids, id) + } + return +} + +// SubAccountRoutesIDs returns the "sub_account_routes" edge IDs in the mutation. +func (m *LedgerAccountMutation) SubAccountRoutesIDs() (ids []string) { + for id := range m.sub_account_routes { + ids = append(ids, id) + } + return +} + +// ResetSubAccountRoutes resets all changes to the "sub_account_routes" edge. +func (m *LedgerAccountMutation) ResetSubAccountRoutes() { + m.sub_account_routes = nil + m.clearedsub_account_routes = false + m.removedsub_account_routes = nil +} + +// AddCustomerAccountIDs adds the "customer_accounts" edge to the LedgerCustomerAccount entity by ids. +func (m *LedgerAccountMutation) AddCustomerAccountIDs(ids ...string) { + if m.customer_accounts == nil { + m.customer_accounts = make(map[string]struct{}) + } + for i := range ids { + m.customer_accounts[ids[i]] = struct{}{} + } +} + +// ClearCustomerAccounts clears the "customer_accounts" edge to the LedgerCustomerAccount entity. +func (m *LedgerAccountMutation) ClearCustomerAccounts() { + m.clearedcustomer_accounts = true +} + +// CustomerAccountsCleared reports if the "customer_accounts" edge to the LedgerCustomerAccount entity was cleared. +func (m *LedgerAccountMutation) CustomerAccountsCleared() bool { + return m.clearedcustomer_accounts +} + +// RemoveCustomerAccountIDs removes the "customer_accounts" edge to the LedgerCustomerAccount entity by IDs. +func (m *LedgerAccountMutation) RemoveCustomerAccountIDs(ids ...string) { + if m.removedcustomer_accounts == nil { + m.removedcustomer_accounts = make(map[string]struct{}) + } + for i := range ids { + delete(m.customer_accounts, ids[i]) + m.removedcustomer_accounts[ids[i]] = struct{}{} + } +} + +// RemovedCustomerAccounts returns the removed IDs of the "customer_accounts" edge to the LedgerCustomerAccount entity. +func (m *LedgerAccountMutation) RemovedCustomerAccountsIDs() (ids []string) { + for id := range m.removedcustomer_accounts { + ids = append(ids, id) + } + return +} + +// CustomerAccountsIDs returns the "customer_accounts" edge IDs in the mutation. +func (m *LedgerAccountMutation) CustomerAccountsIDs() (ids []string) { + for id := range m.customer_accounts { + ids = append(ids, id) + } + return +} + +// ResetCustomerAccounts resets all changes to the "customer_accounts" edge. +func (m *LedgerAccountMutation) ResetCustomerAccounts() { + m.customer_accounts = nil + m.clearedcustomer_accounts = false + m.removedcustomer_accounts = nil +} + +// Where appends a list predicates to the LedgerAccountMutation builder. +func (m *LedgerAccountMutation) Where(ps ...predicate.LedgerAccount) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the LedgerAccountMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *LedgerAccountMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.LedgerAccount, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *LedgerAccountMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *LedgerAccountMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (LedgerAccount). +func (m *LedgerAccountMutation) 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 *LedgerAccountMutation) Fields() []string { + fields := make([]string, 0, 6) + if m.namespace != nil { + fields = append(fields, ledgeraccount.FieldNamespace) + } + if m.annotations != nil { + fields = append(fields, ledgeraccount.FieldAnnotations) + } + if m.created_at != nil { + fields = append(fields, ledgeraccount.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, ledgeraccount.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, ledgeraccount.FieldDeletedAt) + } + if m.account_type != nil { + fields = append(fields, ledgeraccount.FieldAccountType) + } + 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 *LedgerAccountMutation) Field(name string) (ent.Value, bool) { + switch name { + case ledgeraccount.FieldNamespace: + return m.Namespace() + case ledgeraccount.FieldAnnotations: + return m.Annotations() + case ledgeraccount.FieldCreatedAt: + return m.CreatedAt() + case ledgeraccount.FieldUpdatedAt: + return m.UpdatedAt() + case ledgeraccount.FieldDeletedAt: + return m.DeletedAt() + case ledgeraccount.FieldAccountType: + return m.AccountType() + } + 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 *LedgerAccountMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case ledgeraccount.FieldNamespace: + return m.OldNamespace(ctx) + case ledgeraccount.FieldAnnotations: + return m.OldAnnotations(ctx) + case ledgeraccount.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case ledgeraccount.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case ledgeraccount.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case ledgeraccount.FieldAccountType: + return m.OldAccountType(ctx) + } + return nil, fmt.Errorf("unknown LedgerAccount 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 *LedgerAccountMutation) SetField(name string, value ent.Value) error { + switch name { + case ledgeraccount.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case ledgeraccount.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 ledgeraccount.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 ledgeraccount.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 ledgeraccount.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 ledgeraccount.FieldAccountType: + v, ok := value.(ledger.AccountType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAccountType(v) + return nil + } + return fmt.Errorf("unknown LedgerAccount field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LedgerAccountMutation) 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 *LedgerAccountMutation) 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 *LedgerAccountMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown LedgerAccount numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LedgerAccountMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(ledgeraccount.FieldAnnotations) { + fields = append(fields, ledgeraccount.FieldAnnotations) + } + if m.FieldCleared(ledgeraccount.FieldDeletedAt) { + fields = append(fields, ledgeraccount.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LedgerAccountMutation) 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 *LedgerAccountMutation) ClearField(name string) error { + switch name { + case ledgeraccount.FieldAnnotations: + m.ClearAnnotations() + return nil + case ledgeraccount.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown LedgerAccount 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 *LedgerAccountMutation) ResetField(name string) error { + switch name { + case ledgeraccount.FieldNamespace: + m.ResetNamespace() + return nil + case ledgeraccount.FieldAnnotations: + m.ResetAnnotations() + return nil + case ledgeraccount.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case ledgeraccount.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case ledgeraccount.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case ledgeraccount.FieldAccountType: + m.ResetAccountType() + return nil + } + return fmt.Errorf("unknown LedgerAccount field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LedgerAccountMutation) AddedEdges() []string { + edges := make([]string, 0, 3) + if m.sub_accounts != nil { + edges = append(edges, ledgeraccount.EdgeSubAccounts) + } + if m.sub_account_routes != nil { + edges = append(edges, ledgeraccount.EdgeSubAccountRoutes) + } + if m.customer_accounts != nil { + edges = append(edges, ledgeraccount.EdgeCustomerAccounts) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LedgerAccountMutation) AddedIDs(name string) []ent.Value { + switch name { + case ledgeraccount.EdgeSubAccounts: + ids := make([]ent.Value, 0, len(m.sub_accounts)) + for id := range m.sub_accounts { + ids = append(ids, id) + } + return ids + case ledgeraccount.EdgeSubAccountRoutes: + ids := make([]ent.Value, 0, len(m.sub_account_routes)) + for id := range m.sub_account_routes { + ids = append(ids, id) + } + return ids + case ledgeraccount.EdgeCustomerAccounts: + ids := make([]ent.Value, 0, len(m.customer_accounts)) + for id := range m.customer_accounts { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LedgerAccountMutation) RemovedEdges() []string { + edges := make([]string, 0, 3) + if m.removedsub_accounts != nil { + edges = append(edges, ledgeraccount.EdgeSubAccounts) + } + if m.removedsub_account_routes != nil { + edges = append(edges, ledgeraccount.EdgeSubAccountRoutes) + } + if m.removedcustomer_accounts != nil { + edges = append(edges, ledgeraccount.EdgeCustomerAccounts) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LedgerAccountMutation) RemovedIDs(name string) []ent.Value { + switch name { + case ledgeraccount.EdgeSubAccounts: + ids := make([]ent.Value, 0, len(m.removedsub_accounts)) + for id := range m.removedsub_accounts { + ids = append(ids, id) + } + return ids + case ledgeraccount.EdgeSubAccountRoutes: + ids := make([]ent.Value, 0, len(m.removedsub_account_routes)) + for id := range m.removedsub_account_routes { + ids = append(ids, id) + } + return ids + case ledgeraccount.EdgeCustomerAccounts: + ids := make([]ent.Value, 0, len(m.removedcustomer_accounts)) + for id := range m.removedcustomer_accounts { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LedgerAccountMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) + if m.clearedsub_accounts { + edges = append(edges, ledgeraccount.EdgeSubAccounts) + } + if m.clearedsub_account_routes { + edges = append(edges, ledgeraccount.EdgeSubAccountRoutes) + } + if m.clearedcustomer_accounts { + edges = append(edges, ledgeraccount.EdgeCustomerAccounts) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LedgerAccountMutation) EdgeCleared(name string) bool { + switch name { + case ledgeraccount.EdgeSubAccounts: + return m.clearedsub_accounts + case ledgeraccount.EdgeSubAccountRoutes: + return m.clearedsub_account_routes + case ledgeraccount.EdgeCustomerAccounts: + return m.clearedcustomer_accounts + } + 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 *LedgerAccountMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown LedgerAccount 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 *LedgerAccountMutation) ResetEdge(name string) error { + switch name { + case ledgeraccount.EdgeSubAccounts: + m.ResetSubAccounts() + return nil + case ledgeraccount.EdgeSubAccountRoutes: + m.ResetSubAccountRoutes() + return nil + case ledgeraccount.EdgeCustomerAccounts: + m.ResetCustomerAccounts() + return nil + } + return fmt.Errorf("unknown LedgerAccount edge %s", name) +} + +// LedgerBreakageRecordMutation represents an operation that mutates the LedgerBreakageRecord nodes in the graph. +type LedgerBreakageRecordMutation struct { + config + op Op + typ string + id *string + namespace *string + annotations *models.Annotations + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + kind *ledger.BreakageKind + amount *alpacadecimal.Decimal + customer_id *string + currency *currencyx.Code + credit_priority *int + addcredit_priority *int + expires_at *time.Time + source_kind *ledger.BreakageSourceKind + source_charge_id *string + clearedFields map[string]struct{} + source_transaction_group *string + clearedsource_transaction_group bool + source_transaction *string + clearedsource_transaction bool + source_entry *string + clearedsource_entry bool + breakage_transaction_group *string + clearedbreakage_transaction_group bool + breakage_transaction *string + clearedbreakage_transaction bool + fbo_sub_account *string + clearedfbo_sub_account bool + breakage_sub_account *string + clearedbreakage_sub_account bool + planned_releases map[string]struct{} + removedplanned_releases map[string]struct{} + clearedplanned_releases bool + release_reopens map[string]struct{} + removedrelease_reopens map[string]struct{} + clearedrelease_reopens bool + plan *string + clearedplan bool + release *string + clearedrelease bool + done bool + oldValue func(context.Context) (*LedgerBreakageRecord, error) + predicates []predicate.LedgerBreakageRecord +} + +var _ ent.Mutation = (*LedgerBreakageRecordMutation)(nil) + +// ledgerbreakagerecordOption allows management of the mutation configuration using functional options. +type ledgerbreakagerecordOption func(*LedgerBreakageRecordMutation) + +// newLedgerBreakageRecordMutation creates new mutation for the LedgerBreakageRecord entity. +func newLedgerBreakageRecordMutation(c config, op Op, opts ...ledgerbreakagerecordOption) *LedgerBreakageRecordMutation { + m := &LedgerBreakageRecordMutation{ + config: c, + op: op, + typ: TypeLedgerBreakageRecord, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLedgerBreakageRecordID sets the ID field of the mutation. +func withLedgerBreakageRecordID(id string) ledgerbreakagerecordOption { + return func(m *LedgerBreakageRecordMutation) { + var ( + err error + once sync.Once + value *LedgerBreakageRecord + ) + m.oldValue = func(ctx context.Context) (*LedgerBreakageRecord, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LedgerBreakageRecord.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLedgerBreakageRecord sets the old LedgerBreakageRecord of the mutation. +func withLedgerBreakageRecord(node *LedgerBreakageRecord) ledgerbreakagerecordOption { + return func(m *LedgerBreakageRecordMutation) { + m.oldValue = func(context.Context) (*LedgerBreakageRecord, 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 LedgerBreakageRecordMutation) 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 LedgerBreakageRecordMutation) 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 LedgerBreakageRecord entities. +func (m *LedgerBreakageRecordMutation) 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 *LedgerBreakageRecordMutation) 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 *LedgerBreakageRecordMutation) 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().LedgerBreakageRecord.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 *LedgerBreakageRecordMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *LedgerBreakageRecordMutation) 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 LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) 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 *LedgerBreakageRecordMutation) ResetNamespace() { + m.namespace = nil +} + +// SetAnnotations sets the "annotations" field. +func (m *LedgerBreakageRecordMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *LedgerBreakageRecordMutation) 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 LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) 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 *LedgerBreakageRecordMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[ledgerbreakagerecord.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *LedgerBreakageRecordMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[ledgerbreakagerecord.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *LedgerBreakageRecordMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, ledgerbreakagerecord.FieldAnnotations) +} + +// SetCreatedAt sets the "created_at" field. +func (m *LedgerBreakageRecordMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *LedgerBreakageRecordMutation) 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 LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) 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 *LedgerBreakageRecordMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *LedgerBreakageRecordMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *LedgerBreakageRecordMutation) 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 LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) 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 *LedgerBreakageRecordMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *LedgerBreakageRecordMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *LedgerBreakageRecordMutation) 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 LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) 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 *LedgerBreakageRecordMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[ledgerbreakagerecord.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *LedgerBreakageRecordMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[ledgerbreakagerecord.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *LedgerBreakageRecordMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, ledgerbreakagerecord.FieldDeletedAt) +} + +// SetKind sets the "kind" field. +func (m *LedgerBreakageRecordMutation) SetKind(lk ledger.BreakageKind) { + m.kind = &lk +} + +// Kind returns the value of the "kind" field in the mutation. +func (m *LedgerBreakageRecordMutation) Kind() (r ledger.BreakageKind, exists bool) { + v := m.kind + if v == nil { + return + } + return *v, true +} + +// OldKind returns the old "kind" field's value of the LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) OldKind(ctx context.Context) (v ledger.BreakageKind, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldKind is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldKind requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldKind: %w", err) + } + return oldValue.Kind, nil +} + +// ResetKind resets all changes to the "kind" field. +func (m *LedgerBreakageRecordMutation) ResetKind() { + m.kind = nil +} + +// SetAmount sets the "amount" field. +func (m *LedgerBreakageRecordMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *LedgerBreakageRecordMutation) 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 LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) 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 *LedgerBreakageRecordMutation) ResetAmount() { + m.amount = nil +} + +// SetCustomerID sets the "customer_id" field. +func (m *LedgerBreakageRecordMutation) SetCustomerID(s string) { + m.customer_id = &s +} + +// CustomerID returns the value of the "customer_id" field in the mutation. +func (m *LedgerBreakageRecordMutation) CustomerID() (r string, exists bool) { + v := m.customer_id + if v == nil { + return + } + return *v, true +} + +// OldCustomerID returns the old "customer_id" field's value of the LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) OldCustomerID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerID: %w", err) + } + return oldValue.CustomerID, nil +} + +// ResetCustomerID resets all changes to the "customer_id" field. +func (m *LedgerBreakageRecordMutation) ResetCustomerID() { + m.customer_id = nil +} + +// SetCurrency sets the "currency" field. +func (m *LedgerBreakageRecordMutation) SetCurrency(c currencyx.Code) { + m.currency = &c +} + +// Currency returns the value of the "currency" field in the mutation. +func (m *LedgerBreakageRecordMutation) Currency() (r currencyx.Code, exists bool) { + v := m.currency + if v == nil { + return + } + return *v, true +} + +// OldCurrency returns the old "currency" field's value of the LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) OldCurrency(ctx context.Context) (v currencyx.Code, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrency is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrency requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrency: %w", err) + } + return oldValue.Currency, nil +} + +// ResetCurrency resets all changes to the "currency" field. +func (m *LedgerBreakageRecordMutation) ResetCurrency() { + m.currency = nil +} + +// SetCreditPriority sets the "credit_priority" field. +func (m *LedgerBreakageRecordMutation) SetCreditPriority(i int) { + m.credit_priority = &i + m.addcredit_priority = nil +} + +// CreditPriority returns the value of the "credit_priority" field in the mutation. +func (m *LedgerBreakageRecordMutation) CreditPriority() (r int, exists bool) { + v := m.credit_priority + if v == nil { + return + } + return *v, true +} + +// OldCreditPriority returns the old "credit_priority" field's value of the LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) OldCreditPriority(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreditPriority is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreditPriority requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreditPriority: %w", err) + } + return oldValue.CreditPriority, nil +} + +// AddCreditPriority adds i to the "credit_priority" field. +func (m *LedgerBreakageRecordMutation) AddCreditPriority(i int) { + if m.addcredit_priority != nil { + *m.addcredit_priority += i + } else { + m.addcredit_priority = &i + } +} + +// AddedCreditPriority returns the value that was added to the "credit_priority" field in this mutation. +func (m *LedgerBreakageRecordMutation) AddedCreditPriority() (r int, exists bool) { + v := m.addcredit_priority + if v == nil { + return + } + return *v, true +} + +// ResetCreditPriority resets all changes to the "credit_priority" field. +func (m *LedgerBreakageRecordMutation) ResetCreditPriority() { + m.credit_priority = nil + m.addcredit_priority = nil +} + +// SetExpiresAt sets the "expires_at" field. +func (m *LedgerBreakageRecordMutation) SetExpiresAt(t time.Time) { + m.expires_at = &t +} + +// ExpiresAt returns the value of the "expires_at" field in the mutation. +func (m *LedgerBreakageRecordMutation) ExpiresAt() (r time.Time, exists bool) { + v := m.expires_at + if v == nil { + return + } + return *v, true +} + +// OldExpiresAt returns the old "expires_at" field's value of the LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) OldExpiresAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldExpiresAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldExpiresAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldExpiresAt: %w", err) + } + return oldValue.ExpiresAt, nil +} + +// ResetExpiresAt resets all changes to the "expires_at" field. +func (m *LedgerBreakageRecordMutation) ResetExpiresAt() { + m.expires_at = nil +} + +// SetSourceKind sets the "source_kind" field. +func (m *LedgerBreakageRecordMutation) SetSourceKind(lsk ledger.BreakageSourceKind) { + m.source_kind = &lsk +} + +// SourceKind returns the value of the "source_kind" field in the mutation. +func (m *LedgerBreakageRecordMutation) SourceKind() (r ledger.BreakageSourceKind, exists bool) { + v := m.source_kind + if v == nil { + return + } + return *v, true +} + +// OldSourceKind returns the old "source_kind" field's value of the LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) OldSourceKind(ctx context.Context) (v ledger.BreakageSourceKind, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSourceKind is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSourceKind requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSourceKind: %w", err) + } + return oldValue.SourceKind, nil +} + +// ResetSourceKind resets all changes to the "source_kind" field. +func (m *LedgerBreakageRecordMutation) ResetSourceKind() { + m.source_kind = nil +} + +// SetSourceChargeID sets the "source_charge_id" field. +func (m *LedgerBreakageRecordMutation) SetSourceChargeID(s string) { + m.source_charge_id = &s +} + +// SourceChargeID returns the value of the "source_charge_id" field in the mutation. +func (m *LedgerBreakageRecordMutation) SourceChargeID() (r string, exists bool) { + v := m.source_charge_id + if v == nil { + return + } + return *v, true +} + +// OldSourceChargeID returns the old "source_charge_id" field's value of the LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) OldSourceChargeID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSourceChargeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSourceChargeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSourceChargeID: %w", err) + } + return oldValue.SourceChargeID, nil +} + +// ClearSourceChargeID clears the value of the "source_charge_id" field. +func (m *LedgerBreakageRecordMutation) ClearSourceChargeID() { + m.source_charge_id = nil + m.clearedFields[ledgerbreakagerecord.FieldSourceChargeID] = struct{}{} +} + +// SourceChargeIDCleared returns if the "source_charge_id" field was cleared in this mutation. +func (m *LedgerBreakageRecordMutation) SourceChargeIDCleared() bool { + _, ok := m.clearedFields[ledgerbreakagerecord.FieldSourceChargeID] + return ok +} + +// ResetSourceChargeID resets all changes to the "source_charge_id" field. +func (m *LedgerBreakageRecordMutation) ResetSourceChargeID() { + m.source_charge_id = nil + delete(m.clearedFields, ledgerbreakagerecord.FieldSourceChargeID) +} + +// SetSourceTransactionGroupID sets the "source_transaction_group_id" field. +func (m *LedgerBreakageRecordMutation) SetSourceTransactionGroupID(s string) { + m.source_transaction_group = &s +} + +// SourceTransactionGroupID returns the value of the "source_transaction_group_id" field in the mutation. +func (m *LedgerBreakageRecordMutation) SourceTransactionGroupID() (r string, exists bool) { + v := m.source_transaction_group + if v == nil { + return + } + return *v, true +} + +// OldSourceTransactionGroupID returns the old "source_transaction_group_id" field's value of the LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) OldSourceTransactionGroupID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSourceTransactionGroupID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSourceTransactionGroupID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSourceTransactionGroupID: %w", err) + } + return oldValue.SourceTransactionGroupID, nil +} + +// ClearSourceTransactionGroupID clears the value of the "source_transaction_group_id" field. +func (m *LedgerBreakageRecordMutation) ClearSourceTransactionGroupID() { + m.source_transaction_group = nil + m.clearedFields[ledgerbreakagerecord.FieldSourceTransactionGroupID] = struct{}{} +} + +// SourceTransactionGroupIDCleared returns if the "source_transaction_group_id" field was cleared in this mutation. +func (m *LedgerBreakageRecordMutation) SourceTransactionGroupIDCleared() bool { + _, ok := m.clearedFields[ledgerbreakagerecord.FieldSourceTransactionGroupID] + return ok +} + +// ResetSourceTransactionGroupID resets all changes to the "source_transaction_group_id" field. +func (m *LedgerBreakageRecordMutation) ResetSourceTransactionGroupID() { + m.source_transaction_group = nil + delete(m.clearedFields, ledgerbreakagerecord.FieldSourceTransactionGroupID) +} + +// SetSourceTransactionID sets the "source_transaction_id" field. +func (m *LedgerBreakageRecordMutation) SetSourceTransactionID(s string) { + m.source_transaction = &s +} + +// SourceTransactionID returns the value of the "source_transaction_id" field in the mutation. +func (m *LedgerBreakageRecordMutation) SourceTransactionID() (r string, exists bool) { + v := m.source_transaction + if v == nil { + return + } + return *v, true +} + +// OldSourceTransactionID returns the old "source_transaction_id" field's value of the LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) OldSourceTransactionID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSourceTransactionID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSourceTransactionID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSourceTransactionID: %w", err) + } + return oldValue.SourceTransactionID, nil +} + +// ClearSourceTransactionID clears the value of the "source_transaction_id" field. +func (m *LedgerBreakageRecordMutation) ClearSourceTransactionID() { + m.source_transaction = nil + m.clearedFields[ledgerbreakagerecord.FieldSourceTransactionID] = struct{}{} +} + +// SourceTransactionIDCleared returns if the "source_transaction_id" field was cleared in this mutation. +func (m *LedgerBreakageRecordMutation) SourceTransactionIDCleared() bool { + _, ok := m.clearedFields[ledgerbreakagerecord.FieldSourceTransactionID] + return ok +} + +// ResetSourceTransactionID resets all changes to the "source_transaction_id" field. +func (m *LedgerBreakageRecordMutation) ResetSourceTransactionID() { + m.source_transaction = nil + delete(m.clearedFields, ledgerbreakagerecord.FieldSourceTransactionID) +} + +// SetSourceEntryID sets the "source_entry_id" field. +func (m *LedgerBreakageRecordMutation) SetSourceEntryID(s string) { + m.source_entry = &s +} + +// SourceEntryID returns the value of the "source_entry_id" field in the mutation. +func (m *LedgerBreakageRecordMutation) SourceEntryID() (r string, exists bool) { + v := m.source_entry + if v == nil { + return + } + return *v, true +} + +// OldSourceEntryID returns the old "source_entry_id" field's value of the LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) OldSourceEntryID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSourceEntryID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSourceEntryID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSourceEntryID: %w", err) + } + return oldValue.SourceEntryID, nil +} + +// ClearSourceEntryID clears the value of the "source_entry_id" field. +func (m *LedgerBreakageRecordMutation) ClearSourceEntryID() { + m.source_entry = nil + m.clearedFields[ledgerbreakagerecord.FieldSourceEntryID] = struct{}{} +} + +// SourceEntryIDCleared returns if the "source_entry_id" field was cleared in this mutation. +func (m *LedgerBreakageRecordMutation) SourceEntryIDCleared() bool { + _, ok := m.clearedFields[ledgerbreakagerecord.FieldSourceEntryID] + return ok +} + +// ResetSourceEntryID resets all changes to the "source_entry_id" field. +func (m *LedgerBreakageRecordMutation) ResetSourceEntryID() { + m.source_entry = nil + delete(m.clearedFields, ledgerbreakagerecord.FieldSourceEntryID) +} + +// SetBreakageTransactionGroupID sets the "breakage_transaction_group_id" field. +func (m *LedgerBreakageRecordMutation) SetBreakageTransactionGroupID(s string) { + m.breakage_transaction_group = &s +} + +// BreakageTransactionGroupID returns the value of the "breakage_transaction_group_id" field in the mutation. +func (m *LedgerBreakageRecordMutation) BreakageTransactionGroupID() (r string, exists bool) { + v := m.breakage_transaction_group + if v == nil { + return + } + return *v, true +} + +// OldBreakageTransactionGroupID returns the old "breakage_transaction_group_id" field's value of the LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) OldBreakageTransactionGroupID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBreakageTransactionGroupID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBreakageTransactionGroupID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBreakageTransactionGroupID: %w", err) + } + return oldValue.BreakageTransactionGroupID, nil +} + +// ResetBreakageTransactionGroupID resets all changes to the "breakage_transaction_group_id" field. +func (m *LedgerBreakageRecordMutation) ResetBreakageTransactionGroupID() { + m.breakage_transaction_group = nil +} + +// SetBreakageTransactionID sets the "breakage_transaction_id" field. +func (m *LedgerBreakageRecordMutation) SetBreakageTransactionID(s string) { + m.breakage_transaction = &s +} + +// BreakageTransactionID returns the value of the "breakage_transaction_id" field in the mutation. +func (m *LedgerBreakageRecordMutation) BreakageTransactionID() (r string, exists bool) { + v := m.breakage_transaction + if v == nil { + return + } + return *v, true +} + +// OldBreakageTransactionID returns the old "breakage_transaction_id" field's value of the LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) OldBreakageTransactionID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBreakageTransactionID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBreakageTransactionID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBreakageTransactionID: %w", err) + } + return oldValue.BreakageTransactionID, nil +} + +// ResetBreakageTransactionID resets all changes to the "breakage_transaction_id" field. +func (m *LedgerBreakageRecordMutation) ResetBreakageTransactionID() { + m.breakage_transaction = nil +} + +// SetFboSubAccountID sets the "fbo_sub_account_id" field. +func (m *LedgerBreakageRecordMutation) SetFboSubAccountID(s string) { + m.fbo_sub_account = &s +} + +// FboSubAccountID returns the value of the "fbo_sub_account_id" field in the mutation. +func (m *LedgerBreakageRecordMutation) FboSubAccountID() (r string, exists bool) { + v := m.fbo_sub_account + if v == nil { + return + } + return *v, true +} + +// OldFboSubAccountID returns the old "fbo_sub_account_id" field's value of the LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) OldFboSubAccountID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFboSubAccountID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFboSubAccountID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFboSubAccountID: %w", err) + } + return oldValue.FboSubAccountID, nil +} + +// ResetFboSubAccountID resets all changes to the "fbo_sub_account_id" field. +func (m *LedgerBreakageRecordMutation) ResetFboSubAccountID() { + m.fbo_sub_account = nil +} + +// SetBreakageSubAccountID sets the "breakage_sub_account_id" field. +func (m *LedgerBreakageRecordMutation) SetBreakageSubAccountID(s string) { + m.breakage_sub_account = &s +} + +// BreakageSubAccountID returns the value of the "breakage_sub_account_id" field in the mutation. +func (m *LedgerBreakageRecordMutation) BreakageSubAccountID() (r string, exists bool) { + v := m.breakage_sub_account + if v == nil { + return + } + return *v, true +} + +// OldBreakageSubAccountID returns the old "breakage_sub_account_id" field's value of the LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) OldBreakageSubAccountID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBreakageSubAccountID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBreakageSubAccountID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBreakageSubAccountID: %w", err) + } + return oldValue.BreakageSubAccountID, nil +} + +// ResetBreakageSubAccountID resets all changes to the "breakage_sub_account_id" field. +func (m *LedgerBreakageRecordMutation) ResetBreakageSubAccountID() { + m.breakage_sub_account = nil +} + +// SetPlanID sets the "plan_id" field. +func (m *LedgerBreakageRecordMutation) SetPlanID(s string) { + m.plan = &s +} + +// PlanID returns the value of the "plan_id" field in the mutation. +func (m *LedgerBreakageRecordMutation) PlanID() (r string, exists bool) { + v := m.plan + if v == nil { + return + } + return *v, true +} + +// OldPlanID returns the old "plan_id" field's value of the LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) OldPlanID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPlanID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPlanID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPlanID: %w", err) + } + return oldValue.PlanID, nil +} + +// ClearPlanID clears the value of the "plan_id" field. +func (m *LedgerBreakageRecordMutation) ClearPlanID() { + m.plan = nil + m.clearedFields[ledgerbreakagerecord.FieldPlanID] = struct{}{} +} + +// PlanIDCleared returns if the "plan_id" field was cleared in this mutation. +func (m *LedgerBreakageRecordMutation) PlanIDCleared() bool { + _, ok := m.clearedFields[ledgerbreakagerecord.FieldPlanID] + return ok +} + +// ResetPlanID resets all changes to the "plan_id" field. +func (m *LedgerBreakageRecordMutation) ResetPlanID() { + m.plan = nil + delete(m.clearedFields, ledgerbreakagerecord.FieldPlanID) +} + +// SetReleaseID sets the "release_id" field. +func (m *LedgerBreakageRecordMutation) SetReleaseID(s string) { + m.release = &s +} + +// ReleaseID returns the value of the "release_id" field in the mutation. +func (m *LedgerBreakageRecordMutation) ReleaseID() (r string, exists bool) { + v := m.release + if v == nil { + return + } + return *v, true +} + +// OldReleaseID returns the old "release_id" field's value of the LedgerBreakageRecord entity. +// If the LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) OldReleaseID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldReleaseID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldReleaseID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldReleaseID: %w", err) + } + return oldValue.ReleaseID, nil +} + +// ClearReleaseID clears the value of the "release_id" field. +func (m *LedgerBreakageRecordMutation) ClearReleaseID() { + m.release = nil + m.clearedFields[ledgerbreakagerecord.FieldReleaseID] = struct{}{} +} + +// ReleaseIDCleared returns if the "release_id" field was cleared in this mutation. +func (m *LedgerBreakageRecordMutation) ReleaseIDCleared() bool { + _, ok := m.clearedFields[ledgerbreakagerecord.FieldReleaseID] + return ok +} + +// ResetReleaseID resets all changes to the "release_id" field. +func (m *LedgerBreakageRecordMutation) ResetReleaseID() { + m.release = nil + delete(m.clearedFields, ledgerbreakagerecord.FieldReleaseID) +} + +// ClearSourceTransactionGroup clears the "source_transaction_group" edge to the LedgerTransactionGroup entity. +func (m *LedgerBreakageRecordMutation) ClearSourceTransactionGroup() { + m.clearedsource_transaction_group = true + m.clearedFields[ledgerbreakagerecord.FieldSourceTransactionGroupID] = struct{}{} +} + +// SourceTransactionGroupCleared reports if the "source_transaction_group" edge to the LedgerTransactionGroup entity was cleared. +func (m *LedgerBreakageRecordMutation) SourceTransactionGroupCleared() bool { + return m.SourceTransactionGroupIDCleared() || m.clearedsource_transaction_group +} + +// SourceTransactionGroupIDs returns the "source_transaction_group" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SourceTransactionGroupID instead. It exists only for internal usage by the builders. +func (m *LedgerBreakageRecordMutation) SourceTransactionGroupIDs() (ids []string) { + if id := m.source_transaction_group; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSourceTransactionGroup resets all changes to the "source_transaction_group" edge. +func (m *LedgerBreakageRecordMutation) ResetSourceTransactionGroup() { + m.source_transaction_group = nil + m.clearedsource_transaction_group = false +} + +// ClearSourceTransaction clears the "source_transaction" edge to the LedgerTransaction entity. +func (m *LedgerBreakageRecordMutation) ClearSourceTransaction() { + m.clearedsource_transaction = true + m.clearedFields[ledgerbreakagerecord.FieldSourceTransactionID] = struct{}{} +} + +// SourceTransactionCleared reports if the "source_transaction" edge to the LedgerTransaction entity was cleared. +func (m *LedgerBreakageRecordMutation) SourceTransactionCleared() bool { + return m.SourceTransactionIDCleared() || m.clearedsource_transaction +} + +// SourceTransactionIDs returns the "source_transaction" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SourceTransactionID instead. It exists only for internal usage by the builders. +func (m *LedgerBreakageRecordMutation) SourceTransactionIDs() (ids []string) { + if id := m.source_transaction; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSourceTransaction resets all changes to the "source_transaction" edge. +func (m *LedgerBreakageRecordMutation) ResetSourceTransaction() { + m.source_transaction = nil + m.clearedsource_transaction = false +} + +// ClearSourceEntry clears the "source_entry" edge to the LedgerEntry entity. +func (m *LedgerBreakageRecordMutation) ClearSourceEntry() { + m.clearedsource_entry = true + m.clearedFields[ledgerbreakagerecord.FieldSourceEntryID] = struct{}{} +} + +// SourceEntryCleared reports if the "source_entry" edge to the LedgerEntry entity was cleared. +func (m *LedgerBreakageRecordMutation) SourceEntryCleared() bool { + return m.SourceEntryIDCleared() || m.clearedsource_entry +} + +// SourceEntryIDs returns the "source_entry" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SourceEntryID instead. It exists only for internal usage by the builders. +func (m *LedgerBreakageRecordMutation) SourceEntryIDs() (ids []string) { + if id := m.source_entry; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSourceEntry resets all changes to the "source_entry" edge. +func (m *LedgerBreakageRecordMutation) ResetSourceEntry() { + m.source_entry = nil + m.clearedsource_entry = false +} + +// ClearBreakageTransactionGroup clears the "breakage_transaction_group" edge to the LedgerTransactionGroup entity. +func (m *LedgerBreakageRecordMutation) ClearBreakageTransactionGroup() { + m.clearedbreakage_transaction_group = true + m.clearedFields[ledgerbreakagerecord.FieldBreakageTransactionGroupID] = struct{}{} +} + +// BreakageTransactionGroupCleared reports if the "breakage_transaction_group" edge to the LedgerTransactionGroup entity was cleared. +func (m *LedgerBreakageRecordMutation) BreakageTransactionGroupCleared() bool { + return m.clearedbreakage_transaction_group +} + +// BreakageTransactionGroupIDs returns the "breakage_transaction_group" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BreakageTransactionGroupID instead. It exists only for internal usage by the builders. +func (m *LedgerBreakageRecordMutation) BreakageTransactionGroupIDs() (ids []string) { + if id := m.breakage_transaction_group; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBreakageTransactionGroup resets all changes to the "breakage_transaction_group" edge. +func (m *LedgerBreakageRecordMutation) ResetBreakageTransactionGroup() { + m.breakage_transaction_group = nil + m.clearedbreakage_transaction_group = false +} + +// ClearBreakageTransaction clears the "breakage_transaction" edge to the LedgerTransaction entity. +func (m *LedgerBreakageRecordMutation) ClearBreakageTransaction() { + m.clearedbreakage_transaction = true + m.clearedFields[ledgerbreakagerecord.FieldBreakageTransactionID] = struct{}{} +} + +// BreakageTransactionCleared reports if the "breakage_transaction" edge to the LedgerTransaction entity was cleared. +func (m *LedgerBreakageRecordMutation) BreakageTransactionCleared() bool { + return m.clearedbreakage_transaction +} + +// BreakageTransactionIDs returns the "breakage_transaction" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BreakageTransactionID instead. It exists only for internal usage by the builders. +func (m *LedgerBreakageRecordMutation) BreakageTransactionIDs() (ids []string) { + if id := m.breakage_transaction; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBreakageTransaction resets all changes to the "breakage_transaction" edge. +func (m *LedgerBreakageRecordMutation) ResetBreakageTransaction() { + m.breakage_transaction = nil + m.clearedbreakage_transaction = false +} + +// ClearFboSubAccount clears the "fbo_sub_account" edge to the LedgerSubAccount entity. +func (m *LedgerBreakageRecordMutation) ClearFboSubAccount() { + m.clearedfbo_sub_account = true + m.clearedFields[ledgerbreakagerecord.FieldFboSubAccountID] = struct{}{} +} + +// FboSubAccountCleared reports if the "fbo_sub_account" edge to the LedgerSubAccount entity was cleared. +func (m *LedgerBreakageRecordMutation) FboSubAccountCleared() bool { + return m.clearedfbo_sub_account +} + +// FboSubAccountIDs returns the "fbo_sub_account" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// FboSubAccountID instead. It exists only for internal usage by the builders. +func (m *LedgerBreakageRecordMutation) FboSubAccountIDs() (ids []string) { + if id := m.fbo_sub_account; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetFboSubAccount resets all changes to the "fbo_sub_account" edge. +func (m *LedgerBreakageRecordMutation) ResetFboSubAccount() { + m.fbo_sub_account = nil + m.clearedfbo_sub_account = false +} + +// ClearBreakageSubAccount clears the "breakage_sub_account" edge to the LedgerSubAccount entity. +func (m *LedgerBreakageRecordMutation) ClearBreakageSubAccount() { + m.clearedbreakage_sub_account = true + m.clearedFields[ledgerbreakagerecord.FieldBreakageSubAccountID] = struct{}{} +} + +// BreakageSubAccountCleared reports if the "breakage_sub_account" edge to the LedgerSubAccount entity was cleared. +func (m *LedgerBreakageRecordMutation) BreakageSubAccountCleared() bool { + return m.clearedbreakage_sub_account +} + +// BreakageSubAccountIDs returns the "breakage_sub_account" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BreakageSubAccountID instead. It exists only for internal usage by the builders. +func (m *LedgerBreakageRecordMutation) BreakageSubAccountIDs() (ids []string) { + if id := m.breakage_sub_account; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBreakageSubAccount resets all changes to the "breakage_sub_account" edge. +func (m *LedgerBreakageRecordMutation) ResetBreakageSubAccount() { + m.breakage_sub_account = nil + m.clearedbreakage_sub_account = false +} + +// AddPlannedReleaseIDs adds the "planned_releases" edge to the LedgerBreakageRecord entity by ids. +func (m *LedgerBreakageRecordMutation) AddPlannedReleaseIDs(ids ...string) { + if m.planned_releases == nil { + m.planned_releases = make(map[string]struct{}) + } + for i := range ids { + m.planned_releases[ids[i]] = struct{}{} + } +} + +// ClearPlannedReleases clears the "planned_releases" edge to the LedgerBreakageRecord entity. +func (m *LedgerBreakageRecordMutation) ClearPlannedReleases() { + m.clearedplanned_releases = true +} + +// PlannedReleasesCleared reports if the "planned_releases" edge to the LedgerBreakageRecord entity was cleared. +func (m *LedgerBreakageRecordMutation) PlannedReleasesCleared() bool { + return m.clearedplanned_releases +} + +// RemovePlannedReleaseIDs removes the "planned_releases" edge to the LedgerBreakageRecord entity by IDs. +func (m *LedgerBreakageRecordMutation) RemovePlannedReleaseIDs(ids ...string) { + if m.removedplanned_releases == nil { + m.removedplanned_releases = make(map[string]struct{}) + } + for i := range ids { + delete(m.planned_releases, ids[i]) + m.removedplanned_releases[ids[i]] = struct{}{} + } +} + +// RemovedPlannedReleases returns the removed IDs of the "planned_releases" edge to the LedgerBreakageRecord entity. +func (m *LedgerBreakageRecordMutation) RemovedPlannedReleasesIDs() (ids []string) { + for id := range m.removedplanned_releases { + ids = append(ids, id) + } + return +} + +// PlannedReleasesIDs returns the "planned_releases" edge IDs in the mutation. +func (m *LedgerBreakageRecordMutation) PlannedReleasesIDs() (ids []string) { + for id := range m.planned_releases { + ids = append(ids, id) + } + return +} + +// ResetPlannedReleases resets all changes to the "planned_releases" edge. +func (m *LedgerBreakageRecordMutation) ResetPlannedReleases() { + m.planned_releases = nil + m.clearedplanned_releases = false + m.removedplanned_releases = nil +} + +// AddReleaseReopenIDs adds the "release_reopens" edge to the LedgerBreakageRecord entity by ids. +func (m *LedgerBreakageRecordMutation) AddReleaseReopenIDs(ids ...string) { + if m.release_reopens == nil { + m.release_reopens = make(map[string]struct{}) + } + for i := range ids { + m.release_reopens[ids[i]] = struct{}{} + } +} + +// ClearReleaseReopens clears the "release_reopens" edge to the LedgerBreakageRecord entity. +func (m *LedgerBreakageRecordMutation) ClearReleaseReopens() { + m.clearedrelease_reopens = true +} + +// ReleaseReopensCleared reports if the "release_reopens" edge to the LedgerBreakageRecord entity was cleared. +func (m *LedgerBreakageRecordMutation) ReleaseReopensCleared() bool { + return m.clearedrelease_reopens +} + +// RemoveReleaseReopenIDs removes the "release_reopens" edge to the LedgerBreakageRecord entity by IDs. +func (m *LedgerBreakageRecordMutation) RemoveReleaseReopenIDs(ids ...string) { + if m.removedrelease_reopens == nil { + m.removedrelease_reopens = make(map[string]struct{}) + } + for i := range ids { + delete(m.release_reopens, ids[i]) + m.removedrelease_reopens[ids[i]] = struct{}{} + } +} + +// RemovedReleaseReopens returns the removed IDs of the "release_reopens" edge to the LedgerBreakageRecord entity. +func (m *LedgerBreakageRecordMutation) RemovedReleaseReopensIDs() (ids []string) { + for id := range m.removedrelease_reopens { + ids = append(ids, id) + } + return +} + +// ReleaseReopensIDs returns the "release_reopens" edge IDs in the mutation. +func (m *LedgerBreakageRecordMutation) ReleaseReopensIDs() (ids []string) { + for id := range m.release_reopens { + ids = append(ids, id) + } + return +} + +// ResetReleaseReopens resets all changes to the "release_reopens" edge. +func (m *LedgerBreakageRecordMutation) ResetReleaseReopens() { + m.release_reopens = nil + m.clearedrelease_reopens = false + m.removedrelease_reopens = nil +} + +// ClearPlan clears the "plan" edge to the LedgerBreakageRecord entity. +func (m *LedgerBreakageRecordMutation) ClearPlan() { + m.clearedplan = true + m.clearedFields[ledgerbreakagerecord.FieldPlanID] = struct{}{} +} + +// PlanCleared reports if the "plan" edge to the LedgerBreakageRecord entity was cleared. +func (m *LedgerBreakageRecordMutation) PlanCleared() bool { + return m.PlanIDCleared() || m.clearedplan +} + +// PlanIDs returns the "plan" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// PlanID instead. It exists only for internal usage by the builders. +func (m *LedgerBreakageRecordMutation) PlanIDs() (ids []string) { + if id := m.plan; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetPlan resets all changes to the "plan" edge. +func (m *LedgerBreakageRecordMutation) ResetPlan() { + m.plan = nil + m.clearedplan = false +} + +// ClearRelease clears the "release" edge to the LedgerBreakageRecord entity. +func (m *LedgerBreakageRecordMutation) ClearRelease() { + m.clearedrelease = true + m.clearedFields[ledgerbreakagerecord.FieldReleaseID] = struct{}{} +} + +// ReleaseCleared reports if the "release" edge to the LedgerBreakageRecord entity was cleared. +func (m *LedgerBreakageRecordMutation) ReleaseCleared() bool { + return m.ReleaseIDCleared() || m.clearedrelease +} + +// ReleaseIDs returns the "release" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ReleaseID instead. It exists only for internal usage by the builders. +func (m *LedgerBreakageRecordMutation) ReleaseIDs() (ids []string) { + if id := m.release; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetRelease resets all changes to the "release" edge. +func (m *LedgerBreakageRecordMutation) ResetRelease() { + m.release = nil + m.clearedrelease = false +} + +// Where appends a list predicates to the LedgerBreakageRecordMutation builder. +func (m *LedgerBreakageRecordMutation) Where(ps ...predicate.LedgerBreakageRecord) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the LedgerBreakageRecordMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *LedgerBreakageRecordMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.LedgerBreakageRecord, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *LedgerBreakageRecordMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *LedgerBreakageRecordMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (LedgerBreakageRecord). +func (m *LedgerBreakageRecordMutation) 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 *LedgerBreakageRecordMutation) Fields() []string { + fields := make([]string, 0, 22) + if m.namespace != nil { + fields = append(fields, ledgerbreakagerecord.FieldNamespace) + } + if m.annotations != nil { + fields = append(fields, ledgerbreakagerecord.FieldAnnotations) + } + if m.created_at != nil { + fields = append(fields, ledgerbreakagerecord.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, ledgerbreakagerecord.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, ledgerbreakagerecord.FieldDeletedAt) + } + if m.kind != nil { + fields = append(fields, ledgerbreakagerecord.FieldKind) + } + if m.amount != nil { + fields = append(fields, ledgerbreakagerecord.FieldAmount) + } + if m.customer_id != nil { + fields = append(fields, ledgerbreakagerecord.FieldCustomerID) + } + if m.currency != nil { + fields = append(fields, ledgerbreakagerecord.FieldCurrency) + } + if m.credit_priority != nil { + fields = append(fields, ledgerbreakagerecord.FieldCreditPriority) + } + if m.expires_at != nil { + fields = append(fields, ledgerbreakagerecord.FieldExpiresAt) + } + if m.source_kind != nil { + fields = append(fields, ledgerbreakagerecord.FieldSourceKind) + } + if m.source_charge_id != nil { + fields = append(fields, ledgerbreakagerecord.FieldSourceChargeID) + } + if m.source_transaction_group != nil { + fields = append(fields, ledgerbreakagerecord.FieldSourceTransactionGroupID) + } + if m.source_transaction != nil { + fields = append(fields, ledgerbreakagerecord.FieldSourceTransactionID) + } + if m.source_entry != nil { + fields = append(fields, ledgerbreakagerecord.FieldSourceEntryID) + } + if m.breakage_transaction_group != nil { + fields = append(fields, ledgerbreakagerecord.FieldBreakageTransactionGroupID) + } + if m.breakage_transaction != nil { + fields = append(fields, ledgerbreakagerecord.FieldBreakageTransactionID) + } + if m.fbo_sub_account != nil { + fields = append(fields, ledgerbreakagerecord.FieldFboSubAccountID) + } + if m.breakage_sub_account != nil { + fields = append(fields, ledgerbreakagerecord.FieldBreakageSubAccountID) + } + if m.plan != nil { + fields = append(fields, ledgerbreakagerecord.FieldPlanID) + } + if m.release != nil { + fields = append(fields, ledgerbreakagerecord.FieldReleaseID) + } + 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 *LedgerBreakageRecordMutation) Field(name string) (ent.Value, bool) { + switch name { + case ledgerbreakagerecord.FieldNamespace: + return m.Namespace() + case ledgerbreakagerecord.FieldAnnotations: + return m.Annotations() + case ledgerbreakagerecord.FieldCreatedAt: + return m.CreatedAt() + case ledgerbreakagerecord.FieldUpdatedAt: + return m.UpdatedAt() + case ledgerbreakagerecord.FieldDeletedAt: + return m.DeletedAt() + case ledgerbreakagerecord.FieldKind: + return m.Kind() + case ledgerbreakagerecord.FieldAmount: + return m.Amount() + case ledgerbreakagerecord.FieldCustomerID: + return m.CustomerID() + case ledgerbreakagerecord.FieldCurrency: + return m.Currency() + case ledgerbreakagerecord.FieldCreditPriority: + return m.CreditPriority() + case ledgerbreakagerecord.FieldExpiresAt: + return m.ExpiresAt() + case ledgerbreakagerecord.FieldSourceKind: + return m.SourceKind() + case ledgerbreakagerecord.FieldSourceChargeID: + return m.SourceChargeID() + case ledgerbreakagerecord.FieldSourceTransactionGroupID: + return m.SourceTransactionGroupID() + case ledgerbreakagerecord.FieldSourceTransactionID: + return m.SourceTransactionID() + case ledgerbreakagerecord.FieldSourceEntryID: + return m.SourceEntryID() + case ledgerbreakagerecord.FieldBreakageTransactionGroupID: + return m.BreakageTransactionGroupID() + case ledgerbreakagerecord.FieldBreakageTransactionID: + return m.BreakageTransactionID() + case ledgerbreakagerecord.FieldFboSubAccountID: + return m.FboSubAccountID() + case ledgerbreakagerecord.FieldBreakageSubAccountID: + return m.BreakageSubAccountID() + case ledgerbreakagerecord.FieldPlanID: + return m.PlanID() + case ledgerbreakagerecord.FieldReleaseID: + return m.ReleaseID() + } + 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 *LedgerBreakageRecordMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case ledgerbreakagerecord.FieldNamespace: + return m.OldNamespace(ctx) + case ledgerbreakagerecord.FieldAnnotations: + return m.OldAnnotations(ctx) + case ledgerbreakagerecord.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case ledgerbreakagerecord.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case ledgerbreakagerecord.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case ledgerbreakagerecord.FieldKind: + return m.OldKind(ctx) + case ledgerbreakagerecord.FieldAmount: + return m.OldAmount(ctx) + case ledgerbreakagerecord.FieldCustomerID: + return m.OldCustomerID(ctx) + case ledgerbreakagerecord.FieldCurrency: + return m.OldCurrency(ctx) + case ledgerbreakagerecord.FieldCreditPriority: + return m.OldCreditPriority(ctx) + case ledgerbreakagerecord.FieldExpiresAt: + return m.OldExpiresAt(ctx) + case ledgerbreakagerecord.FieldSourceKind: + return m.OldSourceKind(ctx) + case ledgerbreakagerecord.FieldSourceChargeID: + return m.OldSourceChargeID(ctx) + case ledgerbreakagerecord.FieldSourceTransactionGroupID: + return m.OldSourceTransactionGroupID(ctx) + case ledgerbreakagerecord.FieldSourceTransactionID: + return m.OldSourceTransactionID(ctx) + case ledgerbreakagerecord.FieldSourceEntryID: + return m.OldSourceEntryID(ctx) + case ledgerbreakagerecord.FieldBreakageTransactionGroupID: + return m.OldBreakageTransactionGroupID(ctx) + case ledgerbreakagerecord.FieldBreakageTransactionID: + return m.OldBreakageTransactionID(ctx) + case ledgerbreakagerecord.FieldFboSubAccountID: + return m.OldFboSubAccountID(ctx) + case ledgerbreakagerecord.FieldBreakageSubAccountID: + return m.OldBreakageSubAccountID(ctx) + case ledgerbreakagerecord.FieldPlanID: + return m.OldPlanID(ctx) + case ledgerbreakagerecord.FieldReleaseID: + return m.OldReleaseID(ctx) + } + return nil, fmt.Errorf("unknown LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) SetField(name string, value ent.Value) error { + switch name { + case ledgerbreakagerecord.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case ledgerbreakagerecord.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 ledgerbreakagerecord.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 ledgerbreakagerecord.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 ledgerbreakagerecord.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 ledgerbreakagerecord.FieldKind: + v, ok := value.(ledger.BreakageKind) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKind(v) + return nil + case ledgerbreakagerecord.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 ledgerbreakagerecord.FieldCustomerID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerID(v) + return nil + case ledgerbreakagerecord.FieldCurrency: + v, ok := value.(currencyx.Code) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrency(v) + return nil + case ledgerbreakagerecord.FieldCreditPriority: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreditPriority(v) + return nil + case ledgerbreakagerecord.FieldExpiresAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetExpiresAt(v) + return nil + case ledgerbreakagerecord.FieldSourceKind: + v, ok := value.(ledger.BreakageSourceKind) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSourceKind(v) + return nil + case ledgerbreakagerecord.FieldSourceChargeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSourceChargeID(v) + return nil + case ledgerbreakagerecord.FieldSourceTransactionGroupID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSourceTransactionGroupID(v) + return nil + case ledgerbreakagerecord.FieldSourceTransactionID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSourceTransactionID(v) + return nil + case ledgerbreakagerecord.FieldSourceEntryID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSourceEntryID(v) + return nil + case ledgerbreakagerecord.FieldBreakageTransactionGroupID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBreakageTransactionGroupID(v) + return nil + case ledgerbreakagerecord.FieldBreakageTransactionID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBreakageTransactionID(v) + return nil + case ledgerbreakagerecord.FieldFboSubAccountID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFboSubAccountID(v) + return nil + case ledgerbreakagerecord.FieldBreakageSubAccountID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBreakageSubAccountID(v) + return nil + case ledgerbreakagerecord.FieldPlanID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPlanID(v) + return nil + case ledgerbreakagerecord.FieldReleaseID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetReleaseID(v) + return nil + } + return fmt.Errorf("unknown LedgerBreakageRecord field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LedgerBreakageRecordMutation) AddedFields() []string { + var fields []string + if m.addcredit_priority != nil { + fields = append(fields, ledgerbreakagerecord.FieldCreditPriority) + } + return fields +} + +// 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 *LedgerBreakageRecordMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case ledgerbreakagerecord.FieldCreditPriority: + return m.AddedCreditPriority() + } + 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 *LedgerBreakageRecordMutation) AddField(name string, value ent.Value) error { + switch name { + case ledgerbreakagerecord.FieldCreditPriority: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddCreditPriority(v) + return nil + } + return fmt.Errorf("unknown LedgerBreakageRecord numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LedgerBreakageRecordMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(ledgerbreakagerecord.FieldAnnotations) { + fields = append(fields, ledgerbreakagerecord.FieldAnnotations) + } + if m.FieldCleared(ledgerbreakagerecord.FieldDeletedAt) { + fields = append(fields, ledgerbreakagerecord.FieldDeletedAt) + } + if m.FieldCleared(ledgerbreakagerecord.FieldSourceChargeID) { + fields = append(fields, ledgerbreakagerecord.FieldSourceChargeID) + } + if m.FieldCleared(ledgerbreakagerecord.FieldSourceTransactionGroupID) { + fields = append(fields, ledgerbreakagerecord.FieldSourceTransactionGroupID) + } + if m.FieldCleared(ledgerbreakagerecord.FieldSourceTransactionID) { + fields = append(fields, ledgerbreakagerecord.FieldSourceTransactionID) + } + if m.FieldCleared(ledgerbreakagerecord.FieldSourceEntryID) { + fields = append(fields, ledgerbreakagerecord.FieldSourceEntryID) + } + if m.FieldCleared(ledgerbreakagerecord.FieldPlanID) { + fields = append(fields, ledgerbreakagerecord.FieldPlanID) + } + if m.FieldCleared(ledgerbreakagerecord.FieldReleaseID) { + fields = append(fields, ledgerbreakagerecord.FieldReleaseID) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LedgerBreakageRecordMutation) 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 *LedgerBreakageRecordMutation) ClearField(name string) error { + switch name { + case ledgerbreakagerecord.FieldAnnotations: + m.ClearAnnotations() + return nil + case ledgerbreakagerecord.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case ledgerbreakagerecord.FieldSourceChargeID: + m.ClearSourceChargeID() + return nil + case ledgerbreakagerecord.FieldSourceTransactionGroupID: + m.ClearSourceTransactionGroupID() + return nil + case ledgerbreakagerecord.FieldSourceTransactionID: + m.ClearSourceTransactionID() + return nil + case ledgerbreakagerecord.FieldSourceEntryID: + m.ClearSourceEntryID() + return nil + case ledgerbreakagerecord.FieldPlanID: + m.ClearPlanID() + return nil + case ledgerbreakagerecord.FieldReleaseID: + m.ClearReleaseID() + return nil + } + return fmt.Errorf("unknown LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) ResetField(name string) error { + switch name { + case ledgerbreakagerecord.FieldNamespace: + m.ResetNamespace() + return nil + case ledgerbreakagerecord.FieldAnnotations: + m.ResetAnnotations() + return nil + case ledgerbreakagerecord.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case ledgerbreakagerecord.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case ledgerbreakagerecord.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case ledgerbreakagerecord.FieldKind: + m.ResetKind() + return nil + case ledgerbreakagerecord.FieldAmount: + m.ResetAmount() + return nil + case ledgerbreakagerecord.FieldCustomerID: + m.ResetCustomerID() + return nil + case ledgerbreakagerecord.FieldCurrency: + m.ResetCurrency() + return nil + case ledgerbreakagerecord.FieldCreditPriority: + m.ResetCreditPriority() + return nil + case ledgerbreakagerecord.FieldExpiresAt: + m.ResetExpiresAt() + return nil + case ledgerbreakagerecord.FieldSourceKind: + m.ResetSourceKind() + return nil + case ledgerbreakagerecord.FieldSourceChargeID: + m.ResetSourceChargeID() + return nil + case ledgerbreakagerecord.FieldSourceTransactionGroupID: + m.ResetSourceTransactionGroupID() + return nil + case ledgerbreakagerecord.FieldSourceTransactionID: + m.ResetSourceTransactionID() + return nil + case ledgerbreakagerecord.FieldSourceEntryID: + m.ResetSourceEntryID() + return nil + case ledgerbreakagerecord.FieldBreakageTransactionGroupID: + m.ResetBreakageTransactionGroupID() + return nil + case ledgerbreakagerecord.FieldBreakageTransactionID: + m.ResetBreakageTransactionID() + return nil + case ledgerbreakagerecord.FieldFboSubAccountID: + m.ResetFboSubAccountID() + return nil + case ledgerbreakagerecord.FieldBreakageSubAccountID: + m.ResetBreakageSubAccountID() + return nil + case ledgerbreakagerecord.FieldPlanID: + m.ResetPlanID() + return nil + case ledgerbreakagerecord.FieldReleaseID: + m.ResetReleaseID() + return nil + } + return fmt.Errorf("unknown LedgerBreakageRecord field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LedgerBreakageRecordMutation) AddedEdges() []string { + edges := make([]string, 0, 11) + if m.source_transaction_group != nil { + edges = append(edges, ledgerbreakagerecord.EdgeSourceTransactionGroup) + } + if m.source_transaction != nil { + edges = append(edges, ledgerbreakagerecord.EdgeSourceTransaction) + } + if m.source_entry != nil { + edges = append(edges, ledgerbreakagerecord.EdgeSourceEntry) + } + if m.breakage_transaction_group != nil { + edges = append(edges, ledgerbreakagerecord.EdgeBreakageTransactionGroup) + } + if m.breakage_transaction != nil { + edges = append(edges, ledgerbreakagerecord.EdgeBreakageTransaction) + } + if m.fbo_sub_account != nil { + edges = append(edges, ledgerbreakagerecord.EdgeFboSubAccount) + } + if m.breakage_sub_account != nil { + edges = append(edges, ledgerbreakagerecord.EdgeBreakageSubAccount) + } + if m.planned_releases != nil { + edges = append(edges, ledgerbreakagerecord.EdgePlannedReleases) + } + if m.release_reopens != nil { + edges = append(edges, ledgerbreakagerecord.EdgeReleaseReopens) + } + if m.plan != nil { + edges = append(edges, ledgerbreakagerecord.EdgePlan) + } + if m.release != nil { + edges = append(edges, ledgerbreakagerecord.EdgeRelease) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LedgerBreakageRecordMutation) AddedIDs(name string) []ent.Value { + switch name { + case ledgerbreakagerecord.EdgeSourceTransactionGroup: + if id := m.source_transaction_group; id != nil { + return []ent.Value{*id} + } + case ledgerbreakagerecord.EdgeSourceTransaction: + if id := m.source_transaction; id != nil { + return []ent.Value{*id} + } + case ledgerbreakagerecord.EdgeSourceEntry: + if id := m.source_entry; id != nil { + return []ent.Value{*id} + } + case ledgerbreakagerecord.EdgeBreakageTransactionGroup: + if id := m.breakage_transaction_group; id != nil { + return []ent.Value{*id} + } + case ledgerbreakagerecord.EdgeBreakageTransaction: + if id := m.breakage_transaction; id != nil { + return []ent.Value{*id} + } + case ledgerbreakagerecord.EdgeFboSubAccount: + if id := m.fbo_sub_account; id != nil { + return []ent.Value{*id} + } + case ledgerbreakagerecord.EdgeBreakageSubAccount: + if id := m.breakage_sub_account; id != nil { + return []ent.Value{*id} + } + case ledgerbreakagerecord.EdgePlannedReleases: + ids := make([]ent.Value, 0, len(m.planned_releases)) + for id := range m.planned_releases { + ids = append(ids, id) + } + return ids + case ledgerbreakagerecord.EdgeReleaseReopens: + ids := make([]ent.Value, 0, len(m.release_reopens)) + for id := range m.release_reopens { + ids = append(ids, id) + } + return ids + case ledgerbreakagerecord.EdgePlan: + if id := m.plan; id != nil { + return []ent.Value{*id} + } + case ledgerbreakagerecord.EdgeRelease: + if id := m.release; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LedgerBreakageRecordMutation) RemovedEdges() []string { + edges := make([]string, 0, 11) + if m.removedplanned_releases != nil { + edges = append(edges, ledgerbreakagerecord.EdgePlannedReleases) + } + if m.removedrelease_reopens != nil { + edges = append(edges, ledgerbreakagerecord.EdgeReleaseReopens) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LedgerBreakageRecordMutation) RemovedIDs(name string) []ent.Value { + switch name { + case ledgerbreakagerecord.EdgePlannedReleases: + ids := make([]ent.Value, 0, len(m.removedplanned_releases)) + for id := range m.removedplanned_releases { + ids = append(ids, id) + } + return ids + case ledgerbreakagerecord.EdgeReleaseReopens: + ids := make([]ent.Value, 0, len(m.removedrelease_reopens)) + for id := range m.removedrelease_reopens { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LedgerBreakageRecordMutation) ClearedEdges() []string { + edges := make([]string, 0, 11) + if m.clearedsource_transaction_group { + edges = append(edges, ledgerbreakagerecord.EdgeSourceTransactionGroup) + } + if m.clearedsource_transaction { + edges = append(edges, ledgerbreakagerecord.EdgeSourceTransaction) + } + if m.clearedsource_entry { + edges = append(edges, ledgerbreakagerecord.EdgeSourceEntry) + } + if m.clearedbreakage_transaction_group { + edges = append(edges, ledgerbreakagerecord.EdgeBreakageTransactionGroup) + } + if m.clearedbreakage_transaction { + edges = append(edges, ledgerbreakagerecord.EdgeBreakageTransaction) + } + if m.clearedfbo_sub_account { + edges = append(edges, ledgerbreakagerecord.EdgeFboSubAccount) + } + if m.clearedbreakage_sub_account { + edges = append(edges, ledgerbreakagerecord.EdgeBreakageSubAccount) + } + if m.clearedplanned_releases { + edges = append(edges, ledgerbreakagerecord.EdgePlannedReleases) + } + if m.clearedrelease_reopens { + edges = append(edges, ledgerbreakagerecord.EdgeReleaseReopens) + } + if m.clearedplan { + edges = append(edges, ledgerbreakagerecord.EdgePlan) + } + if m.clearedrelease { + edges = append(edges, ledgerbreakagerecord.EdgeRelease) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LedgerBreakageRecordMutation) EdgeCleared(name string) bool { + switch name { + case ledgerbreakagerecord.EdgeSourceTransactionGroup: + return m.clearedsource_transaction_group + case ledgerbreakagerecord.EdgeSourceTransaction: + return m.clearedsource_transaction + case ledgerbreakagerecord.EdgeSourceEntry: + return m.clearedsource_entry + case ledgerbreakagerecord.EdgeBreakageTransactionGroup: + return m.clearedbreakage_transaction_group + case ledgerbreakagerecord.EdgeBreakageTransaction: + return m.clearedbreakage_transaction + case ledgerbreakagerecord.EdgeFboSubAccount: + return m.clearedfbo_sub_account + case ledgerbreakagerecord.EdgeBreakageSubAccount: + return m.clearedbreakage_sub_account + case ledgerbreakagerecord.EdgePlannedReleases: + return m.clearedplanned_releases + case ledgerbreakagerecord.EdgeReleaseReopens: + return m.clearedrelease_reopens + case ledgerbreakagerecord.EdgePlan: + return m.clearedplan + case ledgerbreakagerecord.EdgeRelease: + return m.clearedrelease + } + 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 *LedgerBreakageRecordMutation) ClearEdge(name string) error { + switch name { + case ledgerbreakagerecord.EdgeSourceTransactionGroup: + m.ClearSourceTransactionGroup() + return nil + case ledgerbreakagerecord.EdgeSourceTransaction: + m.ClearSourceTransaction() + return nil + case ledgerbreakagerecord.EdgeSourceEntry: + m.ClearSourceEntry() + return nil + case ledgerbreakagerecord.EdgeBreakageTransactionGroup: + m.ClearBreakageTransactionGroup() + return nil + case ledgerbreakagerecord.EdgeBreakageTransaction: + m.ClearBreakageTransaction() + return nil + case ledgerbreakagerecord.EdgeFboSubAccount: + m.ClearFboSubAccount() + return nil + case ledgerbreakagerecord.EdgeBreakageSubAccount: + m.ClearBreakageSubAccount() + return nil + case ledgerbreakagerecord.EdgePlan: + m.ClearPlan() + return nil + case ledgerbreakagerecord.EdgeRelease: + m.ClearRelease() + return nil + } + return fmt.Errorf("unknown LedgerBreakageRecord 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 *LedgerBreakageRecordMutation) ResetEdge(name string) error { + switch name { + case ledgerbreakagerecord.EdgeSourceTransactionGroup: + m.ResetSourceTransactionGroup() + return nil + case ledgerbreakagerecord.EdgeSourceTransaction: + m.ResetSourceTransaction() + return nil + case ledgerbreakagerecord.EdgeSourceEntry: + m.ResetSourceEntry() + return nil + case ledgerbreakagerecord.EdgeBreakageTransactionGroup: + m.ResetBreakageTransactionGroup() + return nil + case ledgerbreakagerecord.EdgeBreakageTransaction: + m.ResetBreakageTransaction() + return nil + case ledgerbreakagerecord.EdgeFboSubAccount: + m.ResetFboSubAccount() + return nil + case ledgerbreakagerecord.EdgeBreakageSubAccount: + m.ResetBreakageSubAccount() + return nil + case ledgerbreakagerecord.EdgePlannedReleases: + m.ResetPlannedReleases() + return nil + case ledgerbreakagerecord.EdgeReleaseReopens: + m.ResetReleaseReopens() + return nil + case ledgerbreakagerecord.EdgePlan: + m.ResetPlan() + return nil + case ledgerbreakagerecord.EdgeRelease: + m.ResetRelease() + return nil + } + return fmt.Errorf("unknown LedgerBreakageRecord edge %s", name) +} + +// LedgerCreditVoidRecordMutation represents an operation that mutates the LedgerCreditVoidRecord nodes in the graph. +type LedgerCreditVoidRecordMutation struct { + config + op Op + typ string + id *string + namespace *string + annotations *models.Annotations + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + amount *alpacadecimal.Decimal + customer_id *string + currency *currencyx.Code + voided_at *time.Time + source_charge_id *string + void_transaction_group_id *string + void_transaction_id *string + fbo_sub_account_id *string + receivable_sub_account_id *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*LedgerCreditVoidRecord, error) + predicates []predicate.LedgerCreditVoidRecord +} + +var _ ent.Mutation = (*LedgerCreditVoidRecordMutation)(nil) + +// ledgercreditvoidrecordOption allows management of the mutation configuration using functional options. +type ledgercreditvoidrecordOption func(*LedgerCreditVoidRecordMutation) + +// newLedgerCreditVoidRecordMutation creates new mutation for the LedgerCreditVoidRecord entity. +func newLedgerCreditVoidRecordMutation(c config, op Op, opts ...ledgercreditvoidrecordOption) *LedgerCreditVoidRecordMutation { + m := &LedgerCreditVoidRecordMutation{ + config: c, + op: op, + typ: TypeLedgerCreditVoidRecord, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLedgerCreditVoidRecordID sets the ID field of the mutation. +func withLedgerCreditVoidRecordID(id string) ledgercreditvoidrecordOption { + return func(m *LedgerCreditVoidRecordMutation) { + var ( + err error + once sync.Once + value *LedgerCreditVoidRecord + ) + m.oldValue = func(ctx context.Context) (*LedgerCreditVoidRecord, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LedgerCreditVoidRecord.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLedgerCreditVoidRecord sets the old LedgerCreditVoidRecord of the mutation. +func withLedgerCreditVoidRecord(node *LedgerCreditVoidRecord) ledgercreditvoidrecordOption { + return func(m *LedgerCreditVoidRecordMutation) { + m.oldValue = func(context.Context) (*LedgerCreditVoidRecord, 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 LedgerCreditVoidRecordMutation) 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 LedgerCreditVoidRecordMutation) 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 LedgerCreditVoidRecord entities. +func (m *LedgerCreditVoidRecordMutation) 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 *LedgerCreditVoidRecordMutation) 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 *LedgerCreditVoidRecordMutation) 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().LedgerCreditVoidRecord.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 *LedgerCreditVoidRecordMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *LedgerCreditVoidRecordMutation) 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 LedgerCreditVoidRecord entity. +// If the LedgerCreditVoidRecord 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 *LedgerCreditVoidRecordMutation) 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 *LedgerCreditVoidRecordMutation) ResetNamespace() { + m.namespace = nil +} + +// SetAnnotations sets the "annotations" field. +func (m *LedgerCreditVoidRecordMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *LedgerCreditVoidRecordMutation) 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 LedgerCreditVoidRecord entity. +// If the LedgerCreditVoidRecord 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 *LedgerCreditVoidRecordMutation) 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 *LedgerCreditVoidRecordMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[ledgercreditvoidrecord.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *LedgerCreditVoidRecordMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[ledgercreditvoidrecord.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *LedgerCreditVoidRecordMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, ledgercreditvoidrecord.FieldAnnotations) +} + +// SetCreatedAt sets the "created_at" field. +func (m *LedgerCreditVoidRecordMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *LedgerCreditVoidRecordMutation) 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 LedgerCreditVoidRecord entity. +// If the LedgerCreditVoidRecord 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 *LedgerCreditVoidRecordMutation) 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 *LedgerCreditVoidRecordMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *LedgerCreditVoidRecordMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *LedgerCreditVoidRecordMutation) 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 LedgerCreditVoidRecord entity. +// If the LedgerCreditVoidRecord 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 *LedgerCreditVoidRecordMutation) 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 *LedgerCreditVoidRecordMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *LedgerCreditVoidRecordMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *LedgerCreditVoidRecordMutation) 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 LedgerCreditVoidRecord entity. +// If the LedgerCreditVoidRecord 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 *LedgerCreditVoidRecordMutation) 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 *LedgerCreditVoidRecordMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[ledgercreditvoidrecord.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *LedgerCreditVoidRecordMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[ledgercreditvoidrecord.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *LedgerCreditVoidRecordMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, ledgercreditvoidrecord.FieldDeletedAt) +} + +// SetAmount sets the "amount" field. +func (m *LedgerCreditVoidRecordMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *LedgerCreditVoidRecordMutation) 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 LedgerCreditVoidRecord entity. +// If the LedgerCreditVoidRecord 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 *LedgerCreditVoidRecordMutation) 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 *LedgerCreditVoidRecordMutation) ResetAmount() { + m.amount = nil +} + +// SetCustomerID sets the "customer_id" field. +func (m *LedgerCreditVoidRecordMutation) SetCustomerID(s string) { + m.customer_id = &s +} + +// CustomerID returns the value of the "customer_id" field in the mutation. +func (m *LedgerCreditVoidRecordMutation) CustomerID() (r string, exists bool) { + v := m.customer_id + if v == nil { + return + } + return *v, true +} + +// OldCustomerID returns the old "customer_id" field's value of the LedgerCreditVoidRecord entity. +// If the LedgerCreditVoidRecord 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 *LedgerCreditVoidRecordMutation) OldCustomerID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerID: %w", err) + } + return oldValue.CustomerID, nil +} + +// ResetCustomerID resets all changes to the "customer_id" field. +func (m *LedgerCreditVoidRecordMutation) ResetCustomerID() { + m.customer_id = nil +} + +// SetCurrency sets the "currency" field. +func (m *LedgerCreditVoidRecordMutation) SetCurrency(c currencyx.Code) { + m.currency = &c +} + +// Currency returns the value of the "currency" field in the mutation. +func (m *LedgerCreditVoidRecordMutation) Currency() (r currencyx.Code, exists bool) { + v := m.currency + if v == nil { + return + } + return *v, true +} + +// OldCurrency returns the old "currency" field's value of the LedgerCreditVoidRecord entity. +// If the LedgerCreditVoidRecord 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 *LedgerCreditVoidRecordMutation) OldCurrency(ctx context.Context) (v currencyx.Code, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrency is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrency requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrency: %w", err) + } + return oldValue.Currency, nil +} + +// ResetCurrency resets all changes to the "currency" field. +func (m *LedgerCreditVoidRecordMutation) ResetCurrency() { + m.currency = nil +} + +// SetVoidedAt sets the "voided_at" field. +func (m *LedgerCreditVoidRecordMutation) SetVoidedAt(t time.Time) { + m.voided_at = &t +} + +// VoidedAt returns the value of the "voided_at" field in the mutation. +func (m *LedgerCreditVoidRecordMutation) VoidedAt() (r time.Time, exists bool) { + v := m.voided_at + if v == nil { + return + } + return *v, true +} + +// OldVoidedAt returns the old "voided_at" field's value of the LedgerCreditVoidRecord entity. +// If the LedgerCreditVoidRecord 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 *LedgerCreditVoidRecordMutation) OldVoidedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldVoidedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldVoidedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldVoidedAt: %w", err) + } + return oldValue.VoidedAt, nil +} + +// ResetVoidedAt resets all changes to the "voided_at" field. +func (m *LedgerCreditVoidRecordMutation) ResetVoidedAt() { + m.voided_at = nil +} + +// SetSourceChargeID sets the "source_charge_id" field. +func (m *LedgerCreditVoidRecordMutation) SetSourceChargeID(s string) { + m.source_charge_id = &s +} + +// SourceChargeID returns the value of the "source_charge_id" field in the mutation. +func (m *LedgerCreditVoidRecordMutation) SourceChargeID() (r string, exists bool) { + v := m.source_charge_id + if v == nil { + return + } + return *v, true +} + +// OldSourceChargeID returns the old "source_charge_id" field's value of the LedgerCreditVoidRecord entity. +// If the LedgerCreditVoidRecord 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 *LedgerCreditVoidRecordMutation) OldSourceChargeID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSourceChargeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSourceChargeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSourceChargeID: %w", err) + } + return oldValue.SourceChargeID, nil +} + +// ResetSourceChargeID resets all changes to the "source_charge_id" field. +func (m *LedgerCreditVoidRecordMutation) ResetSourceChargeID() { + m.source_charge_id = nil +} + +// SetVoidTransactionGroupID sets the "void_transaction_group_id" field. +func (m *LedgerCreditVoidRecordMutation) SetVoidTransactionGroupID(s string) { + m.void_transaction_group_id = &s +} + +// VoidTransactionGroupID returns the value of the "void_transaction_group_id" field in the mutation. +func (m *LedgerCreditVoidRecordMutation) VoidTransactionGroupID() (r string, exists bool) { + v := m.void_transaction_group_id + if v == nil { + return + } + return *v, true +} + +// OldVoidTransactionGroupID returns the old "void_transaction_group_id" field's value of the LedgerCreditVoidRecord entity. +// If the LedgerCreditVoidRecord 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 *LedgerCreditVoidRecordMutation) OldVoidTransactionGroupID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldVoidTransactionGroupID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldVoidTransactionGroupID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldVoidTransactionGroupID: %w", err) + } + return oldValue.VoidTransactionGroupID, nil +} + +// ResetVoidTransactionGroupID resets all changes to the "void_transaction_group_id" field. +func (m *LedgerCreditVoidRecordMutation) ResetVoidTransactionGroupID() { + m.void_transaction_group_id = nil +} + +// SetVoidTransactionID sets the "void_transaction_id" field. +func (m *LedgerCreditVoidRecordMutation) SetVoidTransactionID(s string) { + m.void_transaction_id = &s +} + +// VoidTransactionID returns the value of the "void_transaction_id" field in the mutation. +func (m *LedgerCreditVoidRecordMutation) VoidTransactionID() (r string, exists bool) { + v := m.void_transaction_id + if v == nil { + return + } + return *v, true +} + +// OldVoidTransactionID returns the old "void_transaction_id" field's value of the LedgerCreditVoidRecord entity. +// If the LedgerCreditVoidRecord 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 *LedgerCreditVoidRecordMutation) OldVoidTransactionID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldVoidTransactionID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldVoidTransactionID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldVoidTransactionID: %w", err) + } + return oldValue.VoidTransactionID, nil +} + +// ResetVoidTransactionID resets all changes to the "void_transaction_id" field. +func (m *LedgerCreditVoidRecordMutation) ResetVoidTransactionID() { + m.void_transaction_id = nil +} + +// SetFboSubAccountID sets the "fbo_sub_account_id" field. +func (m *LedgerCreditVoidRecordMutation) SetFboSubAccountID(s string) { + m.fbo_sub_account_id = &s +} + +// FboSubAccountID returns the value of the "fbo_sub_account_id" field in the mutation. +func (m *LedgerCreditVoidRecordMutation) FboSubAccountID() (r string, exists bool) { + v := m.fbo_sub_account_id + if v == nil { + return + } + return *v, true +} + +// OldFboSubAccountID returns the old "fbo_sub_account_id" field's value of the LedgerCreditVoidRecord entity. +// If the LedgerCreditVoidRecord 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 *LedgerCreditVoidRecordMutation) OldFboSubAccountID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFboSubAccountID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFboSubAccountID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFboSubAccountID: %w", err) + } + return oldValue.FboSubAccountID, nil +} + +// ResetFboSubAccountID resets all changes to the "fbo_sub_account_id" field. +func (m *LedgerCreditVoidRecordMutation) ResetFboSubAccountID() { + m.fbo_sub_account_id = nil +} + +// SetReceivableSubAccountID sets the "receivable_sub_account_id" field. +func (m *LedgerCreditVoidRecordMutation) SetReceivableSubAccountID(s string) { + m.receivable_sub_account_id = &s +} + +// ReceivableSubAccountID returns the value of the "receivable_sub_account_id" field in the mutation. +func (m *LedgerCreditVoidRecordMutation) ReceivableSubAccountID() (r string, exists bool) { + v := m.receivable_sub_account_id + if v == nil { + return + } + return *v, true +} + +// OldReceivableSubAccountID returns the old "receivable_sub_account_id" field's value of the LedgerCreditVoidRecord entity. +// If the LedgerCreditVoidRecord 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 *LedgerCreditVoidRecordMutation) OldReceivableSubAccountID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldReceivableSubAccountID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldReceivableSubAccountID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldReceivableSubAccountID: %w", err) + } + return oldValue.ReceivableSubAccountID, nil +} + +// ResetReceivableSubAccountID resets all changes to the "receivable_sub_account_id" field. +func (m *LedgerCreditVoidRecordMutation) ResetReceivableSubAccountID() { + m.receivable_sub_account_id = nil +} + +// Where appends a list predicates to the LedgerCreditVoidRecordMutation builder. +func (m *LedgerCreditVoidRecordMutation) Where(ps ...predicate.LedgerCreditVoidRecord) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the LedgerCreditVoidRecordMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *LedgerCreditVoidRecordMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.LedgerCreditVoidRecord, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *LedgerCreditVoidRecordMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *LedgerCreditVoidRecordMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (LedgerCreditVoidRecord). +func (m *LedgerCreditVoidRecordMutation) 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 *LedgerCreditVoidRecordMutation) Fields() []string { + fields := make([]string, 0, 14) + if m.namespace != nil { + fields = append(fields, ledgercreditvoidrecord.FieldNamespace) + } + if m.annotations != nil { + fields = append(fields, ledgercreditvoidrecord.FieldAnnotations) + } + if m.created_at != nil { + fields = append(fields, ledgercreditvoidrecord.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, ledgercreditvoidrecord.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, ledgercreditvoidrecord.FieldDeletedAt) + } + if m.amount != nil { + fields = append(fields, ledgercreditvoidrecord.FieldAmount) + } + if m.customer_id != nil { + fields = append(fields, ledgercreditvoidrecord.FieldCustomerID) + } + if m.currency != nil { + fields = append(fields, ledgercreditvoidrecord.FieldCurrency) + } + if m.voided_at != nil { + fields = append(fields, ledgercreditvoidrecord.FieldVoidedAt) + } + if m.source_charge_id != nil { + fields = append(fields, ledgercreditvoidrecord.FieldSourceChargeID) + } + if m.void_transaction_group_id != nil { + fields = append(fields, ledgercreditvoidrecord.FieldVoidTransactionGroupID) + } + if m.void_transaction_id != nil { + fields = append(fields, ledgercreditvoidrecord.FieldVoidTransactionID) + } + if m.fbo_sub_account_id != nil { + fields = append(fields, ledgercreditvoidrecord.FieldFboSubAccountID) + } + if m.receivable_sub_account_id != nil { + fields = append(fields, ledgercreditvoidrecord.FieldReceivableSubAccountID) + } + 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 *LedgerCreditVoidRecordMutation) Field(name string) (ent.Value, bool) { + switch name { + case ledgercreditvoidrecord.FieldNamespace: + return m.Namespace() + case ledgercreditvoidrecord.FieldAnnotations: + return m.Annotations() + case ledgercreditvoidrecord.FieldCreatedAt: + return m.CreatedAt() + case ledgercreditvoidrecord.FieldUpdatedAt: + return m.UpdatedAt() + case ledgercreditvoidrecord.FieldDeletedAt: + return m.DeletedAt() + case ledgercreditvoidrecord.FieldAmount: + return m.Amount() + case ledgercreditvoidrecord.FieldCustomerID: + return m.CustomerID() + case ledgercreditvoidrecord.FieldCurrency: + return m.Currency() + case ledgercreditvoidrecord.FieldVoidedAt: + return m.VoidedAt() + case ledgercreditvoidrecord.FieldSourceChargeID: + return m.SourceChargeID() + case ledgercreditvoidrecord.FieldVoidTransactionGroupID: + return m.VoidTransactionGroupID() + case ledgercreditvoidrecord.FieldVoidTransactionID: + return m.VoidTransactionID() + case ledgercreditvoidrecord.FieldFboSubAccountID: + return m.FboSubAccountID() + case ledgercreditvoidrecord.FieldReceivableSubAccountID: + return m.ReceivableSubAccountID() + } + 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 *LedgerCreditVoidRecordMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case ledgercreditvoidrecord.FieldNamespace: + return m.OldNamespace(ctx) + case ledgercreditvoidrecord.FieldAnnotations: + return m.OldAnnotations(ctx) + case ledgercreditvoidrecord.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case ledgercreditvoidrecord.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case ledgercreditvoidrecord.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case ledgercreditvoidrecord.FieldAmount: + return m.OldAmount(ctx) + case ledgercreditvoidrecord.FieldCustomerID: + return m.OldCustomerID(ctx) + case ledgercreditvoidrecord.FieldCurrency: + return m.OldCurrency(ctx) + case ledgercreditvoidrecord.FieldVoidedAt: + return m.OldVoidedAt(ctx) + case ledgercreditvoidrecord.FieldSourceChargeID: + return m.OldSourceChargeID(ctx) + case ledgercreditvoidrecord.FieldVoidTransactionGroupID: + return m.OldVoidTransactionGroupID(ctx) + case ledgercreditvoidrecord.FieldVoidTransactionID: + return m.OldVoidTransactionID(ctx) + case ledgercreditvoidrecord.FieldFboSubAccountID: + return m.OldFboSubAccountID(ctx) + case ledgercreditvoidrecord.FieldReceivableSubAccountID: + return m.OldReceivableSubAccountID(ctx) + } + return nil, fmt.Errorf("unknown LedgerCreditVoidRecord 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 *LedgerCreditVoidRecordMutation) SetField(name string, value ent.Value) error { + switch name { + case ledgercreditvoidrecord.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case ledgercreditvoidrecord.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 ledgercreditvoidrecord.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 ledgercreditvoidrecord.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 ledgercreditvoidrecord.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 ledgercreditvoidrecord.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 ledgercreditvoidrecord.FieldCustomerID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerID(v) + return nil + case ledgercreditvoidrecord.FieldCurrency: + v, ok := value.(currencyx.Code) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrency(v) + return nil + case ledgercreditvoidrecord.FieldVoidedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVoidedAt(v) + return nil + case ledgercreditvoidrecord.FieldSourceChargeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSourceChargeID(v) + return nil + case ledgercreditvoidrecord.FieldVoidTransactionGroupID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVoidTransactionGroupID(v) + return nil + case ledgercreditvoidrecord.FieldVoidTransactionID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVoidTransactionID(v) + return nil + case ledgercreditvoidrecord.FieldFboSubAccountID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFboSubAccountID(v) + return nil + case ledgercreditvoidrecord.FieldReceivableSubAccountID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetReceivableSubAccountID(v) + return nil + } + return fmt.Errorf("unknown LedgerCreditVoidRecord field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LedgerCreditVoidRecordMutation) 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 *LedgerCreditVoidRecordMutation) 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 *LedgerCreditVoidRecordMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown LedgerCreditVoidRecord numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LedgerCreditVoidRecordMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(ledgercreditvoidrecord.FieldAnnotations) { + fields = append(fields, ledgercreditvoidrecord.FieldAnnotations) + } + if m.FieldCleared(ledgercreditvoidrecord.FieldDeletedAt) { + fields = append(fields, ledgercreditvoidrecord.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LedgerCreditVoidRecordMutation) 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 *LedgerCreditVoidRecordMutation) ClearField(name string) error { + switch name { + case ledgercreditvoidrecord.FieldAnnotations: + m.ClearAnnotations() + return nil + case ledgercreditvoidrecord.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown LedgerCreditVoidRecord 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 *LedgerCreditVoidRecordMutation) ResetField(name string) error { + switch name { + case ledgercreditvoidrecord.FieldNamespace: + m.ResetNamespace() + return nil + case ledgercreditvoidrecord.FieldAnnotations: + m.ResetAnnotations() + return nil + case ledgercreditvoidrecord.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case ledgercreditvoidrecord.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case ledgercreditvoidrecord.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case ledgercreditvoidrecord.FieldAmount: + m.ResetAmount() + return nil + case ledgercreditvoidrecord.FieldCustomerID: + m.ResetCustomerID() + return nil + case ledgercreditvoidrecord.FieldCurrency: + m.ResetCurrency() + return nil + case ledgercreditvoidrecord.FieldVoidedAt: + m.ResetVoidedAt() + return nil + case ledgercreditvoidrecord.FieldSourceChargeID: + m.ResetSourceChargeID() + return nil + case ledgercreditvoidrecord.FieldVoidTransactionGroupID: + m.ResetVoidTransactionGroupID() + return nil + case ledgercreditvoidrecord.FieldVoidTransactionID: + m.ResetVoidTransactionID() + return nil + case ledgercreditvoidrecord.FieldFboSubAccountID: + m.ResetFboSubAccountID() + return nil + case ledgercreditvoidrecord.FieldReceivableSubAccountID: + m.ResetReceivableSubAccountID() + return nil + } + return fmt.Errorf("unknown LedgerCreditVoidRecord field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LedgerCreditVoidRecordMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LedgerCreditVoidRecordMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LedgerCreditVoidRecordMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LedgerCreditVoidRecordMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LedgerCreditVoidRecordMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LedgerCreditVoidRecordMutation) EdgeCleared(name string) bool { + 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 *LedgerCreditVoidRecordMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown LedgerCreditVoidRecord 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 *LedgerCreditVoidRecordMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown LedgerCreditVoidRecord edge %s", name) +} + +// LedgerCustomerAccountMutation represents an operation that mutates the LedgerCustomerAccount nodes in the graph. +type LedgerCustomerAccountMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + customer_id *string + account_type *ledger.AccountType + clearedFields map[string]struct{} + account *string + clearedaccount bool + done bool + oldValue func(context.Context) (*LedgerCustomerAccount, error) + predicates []predicate.LedgerCustomerAccount +} + +var _ ent.Mutation = (*LedgerCustomerAccountMutation)(nil) + +// ledgercustomeraccountOption allows management of the mutation configuration using functional options. +type ledgercustomeraccountOption func(*LedgerCustomerAccountMutation) + +// newLedgerCustomerAccountMutation creates new mutation for the LedgerCustomerAccount entity. +func newLedgerCustomerAccountMutation(c config, op Op, opts ...ledgercustomeraccountOption) *LedgerCustomerAccountMutation { + m := &LedgerCustomerAccountMutation{ + config: c, + op: op, + typ: TypeLedgerCustomerAccount, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLedgerCustomerAccountID sets the ID field of the mutation. +func withLedgerCustomerAccountID(id string) ledgercustomeraccountOption { + return func(m *LedgerCustomerAccountMutation) { + var ( + err error + once sync.Once + value *LedgerCustomerAccount + ) + m.oldValue = func(ctx context.Context) (*LedgerCustomerAccount, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LedgerCustomerAccount.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLedgerCustomerAccount sets the old LedgerCustomerAccount of the mutation. +func withLedgerCustomerAccount(node *LedgerCustomerAccount) ledgercustomeraccountOption { + return func(m *LedgerCustomerAccountMutation) { + m.oldValue = func(context.Context) (*LedgerCustomerAccount, 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 LedgerCustomerAccountMutation) 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 LedgerCustomerAccountMutation) 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 LedgerCustomerAccount entities. +func (m *LedgerCustomerAccountMutation) 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 *LedgerCustomerAccountMutation) 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 *LedgerCustomerAccountMutation) 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().LedgerCustomerAccount.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 *LedgerCustomerAccountMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *LedgerCustomerAccountMutation) 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 LedgerCustomerAccount entity. +// If the LedgerCustomerAccount 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 *LedgerCustomerAccountMutation) 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 *LedgerCustomerAccountMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *LedgerCustomerAccountMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *LedgerCustomerAccountMutation) 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 LedgerCustomerAccount entity. +// If the LedgerCustomerAccount 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 *LedgerCustomerAccountMutation) 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 *LedgerCustomerAccountMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *LedgerCustomerAccountMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *LedgerCustomerAccountMutation) 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 LedgerCustomerAccount entity. +// If the LedgerCustomerAccount 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 *LedgerCustomerAccountMutation) 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 *LedgerCustomerAccountMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *LedgerCustomerAccountMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *LedgerCustomerAccountMutation) 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 LedgerCustomerAccount entity. +// If the LedgerCustomerAccount 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 *LedgerCustomerAccountMutation) 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 *LedgerCustomerAccountMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[ledgercustomeraccount.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *LedgerCustomerAccountMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[ledgercustomeraccount.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *LedgerCustomerAccountMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, ledgercustomeraccount.FieldDeletedAt) +} + +// SetCustomerID sets the "customer_id" field. +func (m *LedgerCustomerAccountMutation) SetCustomerID(s string) { + m.customer_id = &s +} + +// CustomerID returns the value of the "customer_id" field in the mutation. +func (m *LedgerCustomerAccountMutation) CustomerID() (r string, exists bool) { + v := m.customer_id + if v == nil { + return + } + return *v, true +} + +// OldCustomerID returns the old "customer_id" field's value of the LedgerCustomerAccount entity. +// If the LedgerCustomerAccount 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 *LedgerCustomerAccountMutation) OldCustomerID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerID: %w", err) + } + return oldValue.CustomerID, nil +} + +// ResetCustomerID resets all changes to the "customer_id" field. +func (m *LedgerCustomerAccountMutation) ResetCustomerID() { + m.customer_id = nil +} + +// SetAccountType sets the "account_type" field. +func (m *LedgerCustomerAccountMutation) SetAccountType(lt ledger.AccountType) { + m.account_type = < +} + +// AccountType returns the value of the "account_type" field in the mutation. +func (m *LedgerCustomerAccountMutation) AccountType() (r ledger.AccountType, exists bool) { + v := m.account_type + if v == nil { + return + } + return *v, true +} + +// OldAccountType returns the old "account_type" field's value of the LedgerCustomerAccount entity. +// If the LedgerCustomerAccount 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 *LedgerCustomerAccountMutation) OldAccountType(ctx context.Context) (v ledger.AccountType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAccountType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAccountType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAccountType: %w", err) + } + return oldValue.AccountType, nil +} + +// ResetAccountType resets all changes to the "account_type" field. +func (m *LedgerCustomerAccountMutation) ResetAccountType() { + m.account_type = nil +} + +// SetAccountID sets the "account_id" field. +func (m *LedgerCustomerAccountMutation) SetAccountID(s string) { + m.account = &s +} + +// AccountID returns the value of the "account_id" field in the mutation. +func (m *LedgerCustomerAccountMutation) AccountID() (r string, exists bool) { + v := m.account + if v == nil { + return + } + return *v, true +} + +// OldAccountID returns the old "account_id" field's value of the LedgerCustomerAccount entity. +// If the LedgerCustomerAccount 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 *LedgerCustomerAccountMutation) OldAccountID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAccountID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAccountID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAccountID: %w", err) + } + return oldValue.AccountID, nil +} + +// ResetAccountID resets all changes to the "account_id" field. +func (m *LedgerCustomerAccountMutation) ResetAccountID() { + m.account = nil +} + +// ClearAccount clears the "account" edge to the LedgerAccount entity. +func (m *LedgerCustomerAccountMutation) ClearAccount() { + m.clearedaccount = true + m.clearedFields[ledgercustomeraccount.FieldAccountID] = struct{}{} +} + +// AccountCleared reports if the "account" edge to the LedgerAccount entity was cleared. +func (m *LedgerCustomerAccountMutation) AccountCleared() bool { + return m.clearedaccount +} + +// AccountIDs returns the "account" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// AccountID instead. It exists only for internal usage by the builders. +func (m *LedgerCustomerAccountMutation) AccountIDs() (ids []string) { + if id := m.account; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetAccount resets all changes to the "account" edge. +func (m *LedgerCustomerAccountMutation) ResetAccount() { + m.account = nil + m.clearedaccount = false +} + +// Where appends a list predicates to the LedgerCustomerAccountMutation builder. +func (m *LedgerCustomerAccountMutation) Where(ps ...predicate.LedgerCustomerAccount) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the LedgerCustomerAccountMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *LedgerCustomerAccountMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.LedgerCustomerAccount, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *LedgerCustomerAccountMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *LedgerCustomerAccountMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (LedgerCustomerAccount). +func (m *LedgerCustomerAccountMutation) 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 *LedgerCustomerAccountMutation) Fields() []string { + fields := make([]string, 0, 7) + if m.namespace != nil { + fields = append(fields, ledgercustomeraccount.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, ledgercustomeraccount.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, ledgercustomeraccount.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, ledgercustomeraccount.FieldDeletedAt) + } + if m.customer_id != nil { + fields = append(fields, ledgercustomeraccount.FieldCustomerID) + } + if m.account_type != nil { + fields = append(fields, ledgercustomeraccount.FieldAccountType) + } + if m.account != nil { + fields = append(fields, ledgercustomeraccount.FieldAccountID) + } + 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 *LedgerCustomerAccountMutation) Field(name string) (ent.Value, bool) { + switch name { + case ledgercustomeraccount.FieldNamespace: + return m.Namespace() + case ledgercustomeraccount.FieldCreatedAt: + return m.CreatedAt() + case ledgercustomeraccount.FieldUpdatedAt: + return m.UpdatedAt() + case ledgercustomeraccount.FieldDeletedAt: + return m.DeletedAt() + case ledgercustomeraccount.FieldCustomerID: + return m.CustomerID() + case ledgercustomeraccount.FieldAccountType: + return m.AccountType() + case ledgercustomeraccount.FieldAccountID: + return m.AccountID() + } + 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 *LedgerCustomerAccountMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case ledgercustomeraccount.FieldNamespace: + return m.OldNamespace(ctx) + case ledgercustomeraccount.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case ledgercustomeraccount.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case ledgercustomeraccount.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case ledgercustomeraccount.FieldCustomerID: + return m.OldCustomerID(ctx) + case ledgercustomeraccount.FieldAccountType: + return m.OldAccountType(ctx) + case ledgercustomeraccount.FieldAccountID: + return m.OldAccountID(ctx) + } + return nil, fmt.Errorf("unknown LedgerCustomerAccount 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 *LedgerCustomerAccountMutation) SetField(name string, value ent.Value) error { + switch name { + case ledgercustomeraccount.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case ledgercustomeraccount.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 ledgercustomeraccount.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 ledgercustomeraccount.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 ledgercustomeraccount.FieldCustomerID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerID(v) + return nil + case ledgercustomeraccount.FieldAccountType: + v, ok := value.(ledger.AccountType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAccountType(v) + return nil + case ledgercustomeraccount.FieldAccountID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAccountID(v) + return nil + } + return fmt.Errorf("unknown LedgerCustomerAccount field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LedgerCustomerAccountMutation) 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 *LedgerCustomerAccountMutation) 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 *LedgerCustomerAccountMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown LedgerCustomerAccount numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LedgerCustomerAccountMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(ledgercustomeraccount.FieldDeletedAt) { + fields = append(fields, ledgercustomeraccount.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LedgerCustomerAccountMutation) 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 *LedgerCustomerAccountMutation) ClearField(name string) error { + switch name { + case ledgercustomeraccount.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown LedgerCustomerAccount 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 *LedgerCustomerAccountMutation) ResetField(name string) error { + switch name { + case ledgercustomeraccount.FieldNamespace: + m.ResetNamespace() + return nil + case ledgercustomeraccount.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case ledgercustomeraccount.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case ledgercustomeraccount.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case ledgercustomeraccount.FieldCustomerID: + m.ResetCustomerID() + return nil + case ledgercustomeraccount.FieldAccountType: + m.ResetAccountType() + return nil + case ledgercustomeraccount.FieldAccountID: + m.ResetAccountID() + return nil + } + return fmt.Errorf("unknown LedgerCustomerAccount field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LedgerCustomerAccountMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.account != nil { + edges = append(edges, ledgercustomeraccount.EdgeAccount) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LedgerCustomerAccountMutation) AddedIDs(name string) []ent.Value { + switch name { + case ledgercustomeraccount.EdgeAccount: + if id := m.account; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LedgerCustomerAccountMutation) 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 *LedgerCustomerAccountMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LedgerCustomerAccountMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedaccount { + edges = append(edges, ledgercustomeraccount.EdgeAccount) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LedgerCustomerAccountMutation) EdgeCleared(name string) bool { + switch name { + case ledgercustomeraccount.EdgeAccount: + return m.clearedaccount + } + 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 *LedgerCustomerAccountMutation) ClearEdge(name string) error { + switch name { + case ledgercustomeraccount.EdgeAccount: + m.ClearAccount() + return nil + } + return fmt.Errorf("unknown LedgerCustomerAccount 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 *LedgerCustomerAccountMutation) ResetEdge(name string) error { + switch name { + case ledgercustomeraccount.EdgeAccount: + m.ResetAccount() + return nil + } + return fmt.Errorf("unknown LedgerCustomerAccount edge %s", name) +} + +// LedgerEntryMutation represents an operation that mutates the LedgerEntry nodes in the graph. +type LedgerEntryMutation struct { + config + op Op + typ string + id *string + namespace *string + annotations *models.Annotations + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + identity_key *string + schema_version *int + addschema_version *int + source_charge_id *string + spend_charge_id *string + amount *alpacadecimal.Decimal + clearedFields map[string]struct{} + transaction *string + clearedtransaction bool + sub_account *string + clearedsub_account bool + source_breakage_records map[string]struct{} + removedsource_breakage_records map[string]struct{} + clearedsource_breakage_records bool + done bool + oldValue func(context.Context) (*LedgerEntry, error) + predicates []predicate.LedgerEntry +} + +var _ ent.Mutation = (*LedgerEntryMutation)(nil) + +// ledgerentryOption allows management of the mutation configuration using functional options. +type ledgerentryOption func(*LedgerEntryMutation) + +// newLedgerEntryMutation creates new mutation for the LedgerEntry entity. +func newLedgerEntryMutation(c config, op Op, opts ...ledgerentryOption) *LedgerEntryMutation { + m := &LedgerEntryMutation{ + config: c, + op: op, + typ: TypeLedgerEntry, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLedgerEntryID sets the ID field of the mutation. +func withLedgerEntryID(id string) ledgerentryOption { + return func(m *LedgerEntryMutation) { + var ( + err error + once sync.Once + value *LedgerEntry + ) + m.oldValue = func(ctx context.Context) (*LedgerEntry, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LedgerEntry.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLedgerEntry sets the old LedgerEntry of the mutation. +func withLedgerEntry(node *LedgerEntry) ledgerentryOption { + return func(m *LedgerEntryMutation) { + m.oldValue = func(context.Context) (*LedgerEntry, 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 LedgerEntryMutation) 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 LedgerEntryMutation) 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 LedgerEntry entities. +func (m *LedgerEntryMutation) 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 *LedgerEntryMutation) 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 *LedgerEntryMutation) 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().LedgerEntry.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 *LedgerEntryMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *LedgerEntryMutation) 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 LedgerEntry entity. +// If the LedgerEntry 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 *LedgerEntryMutation) 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 *LedgerEntryMutation) ResetNamespace() { + m.namespace = nil +} + +// SetAnnotations sets the "annotations" field. +func (m *LedgerEntryMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *LedgerEntryMutation) 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 LedgerEntry entity. +// If the LedgerEntry 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 *LedgerEntryMutation) 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 *LedgerEntryMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[ledgerentry.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *LedgerEntryMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[ledgerentry.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *LedgerEntryMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, ledgerentry.FieldAnnotations) +} + +// SetCreatedAt sets the "created_at" field. +func (m *LedgerEntryMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *LedgerEntryMutation) 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 LedgerEntry entity. +// If the LedgerEntry 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 *LedgerEntryMutation) 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 *LedgerEntryMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *LedgerEntryMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *LedgerEntryMutation) 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 LedgerEntry entity. +// If the LedgerEntry 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 *LedgerEntryMutation) 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 *LedgerEntryMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *LedgerEntryMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *LedgerEntryMutation) 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 LedgerEntry entity. +// If the LedgerEntry 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 *LedgerEntryMutation) 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 *LedgerEntryMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[ledgerentry.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *LedgerEntryMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[ledgerentry.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *LedgerEntryMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, ledgerentry.FieldDeletedAt) +} + +// SetSubAccountID sets the "sub_account_id" field. +func (m *LedgerEntryMutation) SetSubAccountID(s string) { + m.sub_account = &s +} + +// SubAccountID returns the value of the "sub_account_id" field in the mutation. +func (m *LedgerEntryMutation) SubAccountID() (r string, exists bool) { + v := m.sub_account + if v == nil { + return + } + return *v, true +} + +// OldSubAccountID returns the old "sub_account_id" field's value of the LedgerEntry entity. +// If the LedgerEntry 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 *LedgerEntryMutation) OldSubAccountID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubAccountID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubAccountID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubAccountID: %w", err) + } + return oldValue.SubAccountID, nil +} + +// ResetSubAccountID resets all changes to the "sub_account_id" field. +func (m *LedgerEntryMutation) ResetSubAccountID() { + m.sub_account = nil +} + +// SetIdentityKey sets the "identity_key" field. +func (m *LedgerEntryMutation) SetIdentityKey(s string) { + m.identity_key = &s +} + +// IdentityKey returns the value of the "identity_key" field in the mutation. +func (m *LedgerEntryMutation) IdentityKey() (r string, exists bool) { + v := m.identity_key + if v == nil { + return + } + return *v, true +} + +// OldIdentityKey returns the old "identity_key" field's value of the LedgerEntry entity. +// If the LedgerEntry 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 *LedgerEntryMutation) OldIdentityKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIdentityKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIdentityKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIdentityKey: %w", err) + } + return oldValue.IdentityKey, nil +} + +// ResetIdentityKey resets all changes to the "identity_key" field. +func (m *LedgerEntryMutation) ResetIdentityKey() { + m.identity_key = nil +} + +// SetSchemaVersion sets the "schema_version" field. +func (m *LedgerEntryMutation) SetSchemaVersion(i int) { + m.schema_version = &i + m.addschema_version = nil +} + +// SchemaVersion returns the value of the "schema_version" field in the mutation. +func (m *LedgerEntryMutation) SchemaVersion() (r int, exists bool) { + v := m.schema_version + if v == nil { + return + } + return *v, true +} + +// OldSchemaVersion returns the old "schema_version" field's value of the LedgerEntry entity. +// If the LedgerEntry 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 *LedgerEntryMutation) OldSchemaVersion(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSchemaVersion is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSchemaVersion requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSchemaVersion: %w", err) + } + return oldValue.SchemaVersion, nil +} + +// AddSchemaVersion adds i to the "schema_version" field. +func (m *LedgerEntryMutation) AddSchemaVersion(i int) { + if m.addschema_version != nil { + *m.addschema_version += i + } else { + m.addschema_version = &i + } +} + +// AddedSchemaVersion returns the value that was added to the "schema_version" field in this mutation. +func (m *LedgerEntryMutation) AddedSchemaVersion() (r int, exists bool) { + v := m.addschema_version + if v == nil { + return + } + return *v, true +} + +// ResetSchemaVersion resets all changes to the "schema_version" field. +func (m *LedgerEntryMutation) ResetSchemaVersion() { + m.schema_version = nil + m.addschema_version = nil +} + +// SetSourceChargeID sets the "source_charge_id" field. +func (m *LedgerEntryMutation) SetSourceChargeID(s string) { + m.source_charge_id = &s +} + +// SourceChargeID returns the value of the "source_charge_id" field in the mutation. +func (m *LedgerEntryMutation) SourceChargeID() (r string, exists bool) { + v := m.source_charge_id + if v == nil { + return + } + return *v, true +} + +// OldSourceChargeID returns the old "source_charge_id" field's value of the LedgerEntry entity. +// If the LedgerEntry 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 *LedgerEntryMutation) OldSourceChargeID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSourceChargeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSourceChargeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSourceChargeID: %w", err) + } + return oldValue.SourceChargeID, nil +} + +// ClearSourceChargeID clears the value of the "source_charge_id" field. +func (m *LedgerEntryMutation) ClearSourceChargeID() { + m.source_charge_id = nil + m.clearedFields[ledgerentry.FieldSourceChargeID] = struct{}{} +} + +// SourceChargeIDCleared returns if the "source_charge_id" field was cleared in this mutation. +func (m *LedgerEntryMutation) SourceChargeIDCleared() bool { + _, ok := m.clearedFields[ledgerentry.FieldSourceChargeID] + return ok +} + +// ResetSourceChargeID resets all changes to the "source_charge_id" field. +func (m *LedgerEntryMutation) ResetSourceChargeID() { + m.source_charge_id = nil + delete(m.clearedFields, ledgerentry.FieldSourceChargeID) +} + +// SetSpendChargeID sets the "spend_charge_id" field. +func (m *LedgerEntryMutation) SetSpendChargeID(s string) { + m.spend_charge_id = &s +} + +// SpendChargeID returns the value of the "spend_charge_id" field in the mutation. +func (m *LedgerEntryMutation) SpendChargeID() (r string, exists bool) { + v := m.spend_charge_id + if v == nil { + return + } + return *v, true +} + +// OldSpendChargeID returns the old "spend_charge_id" field's value of the LedgerEntry entity. +// If the LedgerEntry 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 *LedgerEntryMutation) OldSpendChargeID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSpendChargeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSpendChargeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSpendChargeID: %w", err) + } + return oldValue.SpendChargeID, nil +} + +// ClearSpendChargeID clears the value of the "spend_charge_id" field. +func (m *LedgerEntryMutation) ClearSpendChargeID() { + m.spend_charge_id = nil + m.clearedFields[ledgerentry.FieldSpendChargeID] = struct{}{} +} + +// SpendChargeIDCleared returns if the "spend_charge_id" field was cleared in this mutation. +func (m *LedgerEntryMutation) SpendChargeIDCleared() bool { + _, ok := m.clearedFields[ledgerentry.FieldSpendChargeID] + return ok +} + +// ResetSpendChargeID resets all changes to the "spend_charge_id" field. +func (m *LedgerEntryMutation) ResetSpendChargeID() { + m.spend_charge_id = nil + delete(m.clearedFields, ledgerentry.FieldSpendChargeID) +} + +// SetAmount sets the "amount" field. +func (m *LedgerEntryMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *LedgerEntryMutation) 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 LedgerEntry entity. +// If the LedgerEntry 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 *LedgerEntryMutation) 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 *LedgerEntryMutation) ResetAmount() { + m.amount = nil +} + +// SetTransactionID sets the "transaction_id" field. +func (m *LedgerEntryMutation) SetTransactionID(s string) { + m.transaction = &s +} + +// TransactionID returns the value of the "transaction_id" field in the mutation. +func (m *LedgerEntryMutation) TransactionID() (r string, exists bool) { + v := m.transaction + if v == nil { + return + } + return *v, true +} + +// OldTransactionID returns the old "transaction_id" field's value of the LedgerEntry entity. +// If the LedgerEntry 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 *LedgerEntryMutation) OldTransactionID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTransactionID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTransactionID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTransactionID: %w", err) + } + return oldValue.TransactionID, nil +} + +// ResetTransactionID resets all changes to the "transaction_id" field. +func (m *LedgerEntryMutation) ResetTransactionID() { + m.transaction = nil +} + +// ClearTransaction clears the "transaction" edge to the LedgerTransaction entity. +func (m *LedgerEntryMutation) ClearTransaction() { + m.clearedtransaction = true + m.clearedFields[ledgerentry.FieldTransactionID] = struct{}{} +} + +// TransactionCleared reports if the "transaction" edge to the LedgerTransaction entity was cleared. +func (m *LedgerEntryMutation) TransactionCleared() bool { + return m.clearedtransaction +} + +// TransactionIDs returns the "transaction" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TransactionID instead. It exists only for internal usage by the builders. +func (m *LedgerEntryMutation) TransactionIDs() (ids []string) { + if id := m.transaction; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTransaction resets all changes to the "transaction" edge. +func (m *LedgerEntryMutation) ResetTransaction() { + m.transaction = nil + m.clearedtransaction = false +} + +// ClearSubAccount clears the "sub_account" edge to the LedgerSubAccount entity. +func (m *LedgerEntryMutation) ClearSubAccount() { + m.clearedsub_account = true + m.clearedFields[ledgerentry.FieldSubAccountID] = struct{}{} +} + +// SubAccountCleared reports if the "sub_account" edge to the LedgerSubAccount entity was cleared. +func (m *LedgerEntryMutation) SubAccountCleared() bool { + return m.clearedsub_account +} + +// SubAccountIDs returns the "sub_account" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubAccountID instead. It exists only for internal usage by the builders. +func (m *LedgerEntryMutation) SubAccountIDs() (ids []string) { + if id := m.sub_account; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSubAccount resets all changes to the "sub_account" edge. +func (m *LedgerEntryMutation) ResetSubAccount() { + m.sub_account = nil + m.clearedsub_account = false +} + +// AddSourceBreakageRecordIDs adds the "source_breakage_records" edge to the LedgerBreakageRecord entity by ids. +func (m *LedgerEntryMutation) AddSourceBreakageRecordIDs(ids ...string) { + if m.source_breakage_records == nil { + m.source_breakage_records = make(map[string]struct{}) + } + for i := range ids { + m.source_breakage_records[ids[i]] = struct{}{} + } +} + +// ClearSourceBreakageRecords clears the "source_breakage_records" edge to the LedgerBreakageRecord entity. +func (m *LedgerEntryMutation) ClearSourceBreakageRecords() { + m.clearedsource_breakage_records = true +} + +// SourceBreakageRecordsCleared reports if the "source_breakage_records" edge to the LedgerBreakageRecord entity was cleared. +func (m *LedgerEntryMutation) SourceBreakageRecordsCleared() bool { + return m.clearedsource_breakage_records +} + +// RemoveSourceBreakageRecordIDs removes the "source_breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (m *LedgerEntryMutation) RemoveSourceBreakageRecordIDs(ids ...string) { + if m.removedsource_breakage_records == nil { + m.removedsource_breakage_records = make(map[string]struct{}) + } + for i := range ids { + delete(m.source_breakage_records, ids[i]) + m.removedsource_breakage_records[ids[i]] = struct{}{} + } +} + +// RemovedSourceBreakageRecords returns the removed IDs of the "source_breakage_records" edge to the LedgerBreakageRecord entity. +func (m *LedgerEntryMutation) RemovedSourceBreakageRecordsIDs() (ids []string) { + for id := range m.removedsource_breakage_records { + ids = append(ids, id) + } + return +} + +// SourceBreakageRecordsIDs returns the "source_breakage_records" edge IDs in the mutation. +func (m *LedgerEntryMutation) SourceBreakageRecordsIDs() (ids []string) { + for id := range m.source_breakage_records { + ids = append(ids, id) + } + return +} + +// ResetSourceBreakageRecords resets all changes to the "source_breakage_records" edge. +func (m *LedgerEntryMutation) ResetSourceBreakageRecords() { + m.source_breakage_records = nil + m.clearedsource_breakage_records = false + m.removedsource_breakage_records = nil +} + +// Where appends a list predicates to the LedgerEntryMutation builder. +func (m *LedgerEntryMutation) Where(ps ...predicate.LedgerEntry) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the LedgerEntryMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *LedgerEntryMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.LedgerEntry, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *LedgerEntryMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *LedgerEntryMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (LedgerEntry). +func (m *LedgerEntryMutation) 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 *LedgerEntryMutation) Fields() []string { + fields := make([]string, 0, 12) + if m.namespace != nil { + fields = append(fields, ledgerentry.FieldNamespace) + } + if m.annotations != nil { + fields = append(fields, ledgerentry.FieldAnnotations) + } + if m.created_at != nil { + fields = append(fields, ledgerentry.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, ledgerentry.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, ledgerentry.FieldDeletedAt) + } + if m.sub_account != nil { + fields = append(fields, ledgerentry.FieldSubAccountID) + } + if m.identity_key != nil { + fields = append(fields, ledgerentry.FieldIdentityKey) + } + if m.schema_version != nil { + fields = append(fields, ledgerentry.FieldSchemaVersion) + } + if m.source_charge_id != nil { + fields = append(fields, ledgerentry.FieldSourceChargeID) + } + if m.spend_charge_id != nil { + fields = append(fields, ledgerentry.FieldSpendChargeID) + } + if m.amount != nil { + fields = append(fields, ledgerentry.FieldAmount) + } + if m.transaction != nil { + fields = append(fields, ledgerentry.FieldTransactionID) + } + 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 *LedgerEntryMutation) Field(name string) (ent.Value, bool) { + switch name { + case ledgerentry.FieldNamespace: + return m.Namespace() + case ledgerentry.FieldAnnotations: + return m.Annotations() + case ledgerentry.FieldCreatedAt: + return m.CreatedAt() + case ledgerentry.FieldUpdatedAt: + return m.UpdatedAt() + case ledgerentry.FieldDeletedAt: + return m.DeletedAt() + case ledgerentry.FieldSubAccountID: + return m.SubAccountID() + case ledgerentry.FieldIdentityKey: + return m.IdentityKey() + case ledgerentry.FieldSchemaVersion: + return m.SchemaVersion() + case ledgerentry.FieldSourceChargeID: + return m.SourceChargeID() + case ledgerentry.FieldSpendChargeID: + return m.SpendChargeID() + case ledgerentry.FieldAmount: + return m.Amount() + case ledgerentry.FieldTransactionID: + return m.TransactionID() + } + 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 *LedgerEntryMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case ledgerentry.FieldNamespace: + return m.OldNamespace(ctx) + case ledgerentry.FieldAnnotations: + return m.OldAnnotations(ctx) + case ledgerentry.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case ledgerentry.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case ledgerentry.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case ledgerentry.FieldSubAccountID: + return m.OldSubAccountID(ctx) + case ledgerentry.FieldIdentityKey: + return m.OldIdentityKey(ctx) + case ledgerentry.FieldSchemaVersion: + return m.OldSchemaVersion(ctx) + case ledgerentry.FieldSourceChargeID: + return m.OldSourceChargeID(ctx) + case ledgerentry.FieldSpendChargeID: + return m.OldSpendChargeID(ctx) + case ledgerentry.FieldAmount: + return m.OldAmount(ctx) + case ledgerentry.FieldTransactionID: + return m.OldTransactionID(ctx) + } + return nil, fmt.Errorf("unknown LedgerEntry 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 *LedgerEntryMutation) SetField(name string, value ent.Value) error { + switch name { + case ledgerentry.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case ledgerentry.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 ledgerentry.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 ledgerentry.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 ledgerentry.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 ledgerentry.FieldSubAccountID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubAccountID(v) + return nil + case ledgerentry.FieldIdentityKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIdentityKey(v) + return nil + case ledgerentry.FieldSchemaVersion: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSchemaVersion(v) + return nil + case ledgerentry.FieldSourceChargeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSourceChargeID(v) + return nil + case ledgerentry.FieldSpendChargeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSpendChargeID(v) + return nil + case ledgerentry.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 ledgerentry.FieldTransactionID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTransactionID(v) + return nil + } + return fmt.Errorf("unknown LedgerEntry field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LedgerEntryMutation) AddedFields() []string { + var fields []string + if m.addschema_version != nil { + fields = append(fields, ledgerentry.FieldSchemaVersion) + } + return fields +} + +// 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 *LedgerEntryMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case ledgerentry.FieldSchemaVersion: + return m.AddedSchemaVersion() + } + 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 *LedgerEntryMutation) AddField(name string, value ent.Value) error { + switch name { + case ledgerentry.FieldSchemaVersion: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddSchemaVersion(v) + return nil + } + return fmt.Errorf("unknown LedgerEntry numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LedgerEntryMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(ledgerentry.FieldAnnotations) { + fields = append(fields, ledgerentry.FieldAnnotations) + } + if m.FieldCleared(ledgerentry.FieldDeletedAt) { + fields = append(fields, ledgerentry.FieldDeletedAt) + } + if m.FieldCleared(ledgerentry.FieldSourceChargeID) { + fields = append(fields, ledgerentry.FieldSourceChargeID) + } + if m.FieldCleared(ledgerentry.FieldSpendChargeID) { + fields = append(fields, ledgerentry.FieldSpendChargeID) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LedgerEntryMutation) 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 *LedgerEntryMutation) ClearField(name string) error { + switch name { + case ledgerentry.FieldAnnotations: + m.ClearAnnotations() + return nil + case ledgerentry.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case ledgerentry.FieldSourceChargeID: + m.ClearSourceChargeID() + return nil + case ledgerentry.FieldSpendChargeID: + m.ClearSpendChargeID() + return nil + } + return fmt.Errorf("unknown LedgerEntry 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 *LedgerEntryMutation) ResetField(name string) error { + switch name { + case ledgerentry.FieldNamespace: + m.ResetNamespace() + return nil + case ledgerentry.FieldAnnotations: + m.ResetAnnotations() + return nil + case ledgerentry.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case ledgerentry.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case ledgerentry.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case ledgerentry.FieldSubAccountID: + m.ResetSubAccountID() + return nil + case ledgerentry.FieldIdentityKey: + m.ResetIdentityKey() + return nil + case ledgerentry.FieldSchemaVersion: + m.ResetSchemaVersion() + return nil + case ledgerentry.FieldSourceChargeID: + m.ResetSourceChargeID() + return nil + case ledgerentry.FieldSpendChargeID: + m.ResetSpendChargeID() + return nil + case ledgerentry.FieldAmount: + m.ResetAmount() + return nil + case ledgerentry.FieldTransactionID: + m.ResetTransactionID() + return nil + } + return fmt.Errorf("unknown LedgerEntry field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LedgerEntryMutation) AddedEdges() []string { + edges := make([]string, 0, 3) + if m.transaction != nil { + edges = append(edges, ledgerentry.EdgeTransaction) + } + if m.sub_account != nil { + edges = append(edges, ledgerentry.EdgeSubAccount) + } + if m.source_breakage_records != nil { + edges = append(edges, ledgerentry.EdgeSourceBreakageRecords) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LedgerEntryMutation) AddedIDs(name string) []ent.Value { + switch name { + case ledgerentry.EdgeTransaction: + if id := m.transaction; id != nil { + return []ent.Value{*id} + } + case ledgerentry.EdgeSubAccount: + if id := m.sub_account; id != nil { + return []ent.Value{*id} + } + case ledgerentry.EdgeSourceBreakageRecords: + ids := make([]ent.Value, 0, len(m.source_breakage_records)) + for id := range m.source_breakage_records { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LedgerEntryMutation) RemovedEdges() []string { + edges := make([]string, 0, 3) + if m.removedsource_breakage_records != nil { + edges = append(edges, ledgerentry.EdgeSourceBreakageRecords) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LedgerEntryMutation) RemovedIDs(name string) []ent.Value { + switch name { + case ledgerentry.EdgeSourceBreakageRecords: + ids := make([]ent.Value, 0, len(m.removedsource_breakage_records)) + for id := range m.removedsource_breakage_records { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LedgerEntryMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) + if m.clearedtransaction { + edges = append(edges, ledgerentry.EdgeTransaction) + } + if m.clearedsub_account { + edges = append(edges, ledgerentry.EdgeSubAccount) + } + if m.clearedsource_breakage_records { + edges = append(edges, ledgerentry.EdgeSourceBreakageRecords) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LedgerEntryMutation) EdgeCleared(name string) bool { + switch name { + case ledgerentry.EdgeTransaction: + return m.clearedtransaction + case ledgerentry.EdgeSubAccount: + return m.clearedsub_account + case ledgerentry.EdgeSourceBreakageRecords: + return m.clearedsource_breakage_records + } + 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 *LedgerEntryMutation) ClearEdge(name string) error { + switch name { + case ledgerentry.EdgeTransaction: + m.ClearTransaction() + return nil + case ledgerentry.EdgeSubAccount: + m.ClearSubAccount() + return nil + } + return fmt.Errorf("unknown LedgerEntry 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 *LedgerEntryMutation) ResetEdge(name string) error { + switch name { + case ledgerentry.EdgeTransaction: + m.ResetTransaction() + return nil + case ledgerentry.EdgeSubAccount: + m.ResetSubAccount() + return nil + case ledgerentry.EdgeSourceBreakageRecords: + m.ResetSourceBreakageRecords() + return nil + } + return fmt.Errorf("unknown LedgerEntry edge %s", name) +} + +// LedgerSubAccountMutation represents an operation that mutates the LedgerSubAccount nodes in the graph. +type LedgerSubAccountMutation struct { + config + op Op + typ string + id *string + namespace *string + annotations *models.Annotations + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + clearedFields map[string]struct{} + account *string + clearedaccount bool + route *string + clearedroute bool + entries map[string]struct{} + removedentries map[string]struct{} + clearedentries bool + fbo_breakage_records map[string]struct{} + removedfbo_breakage_records map[string]struct{} + clearedfbo_breakage_records bool + breakage_records map[string]struct{} + removedbreakage_records map[string]struct{} + clearedbreakage_records bool + done bool + oldValue func(context.Context) (*LedgerSubAccount, error) + predicates []predicate.LedgerSubAccount +} + +var _ ent.Mutation = (*LedgerSubAccountMutation)(nil) + +// ledgersubaccountOption allows management of the mutation configuration using functional options. +type ledgersubaccountOption func(*LedgerSubAccountMutation) + +// newLedgerSubAccountMutation creates new mutation for the LedgerSubAccount entity. +func newLedgerSubAccountMutation(c config, op Op, opts ...ledgersubaccountOption) *LedgerSubAccountMutation { + m := &LedgerSubAccountMutation{ + config: c, + op: op, + typ: TypeLedgerSubAccount, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLedgerSubAccountID sets the ID field of the mutation. +func withLedgerSubAccountID(id string) ledgersubaccountOption { + return func(m *LedgerSubAccountMutation) { + var ( + err error + once sync.Once + value *LedgerSubAccount + ) + m.oldValue = func(ctx context.Context) (*LedgerSubAccount, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LedgerSubAccount.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLedgerSubAccount sets the old LedgerSubAccount of the mutation. +func withLedgerSubAccount(node *LedgerSubAccount) ledgersubaccountOption { + return func(m *LedgerSubAccountMutation) { + m.oldValue = func(context.Context) (*LedgerSubAccount, 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 LedgerSubAccountMutation) 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 LedgerSubAccountMutation) 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 LedgerSubAccount entities. +func (m *LedgerSubAccountMutation) 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 *LedgerSubAccountMutation) 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 *LedgerSubAccountMutation) 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().LedgerSubAccount.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 *LedgerSubAccountMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *LedgerSubAccountMutation) 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 LedgerSubAccount entity. +// If the LedgerSubAccount 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 *LedgerSubAccountMutation) 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 *LedgerSubAccountMutation) ResetNamespace() { + m.namespace = nil +} + +// SetAnnotations sets the "annotations" field. +func (m *LedgerSubAccountMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *LedgerSubAccountMutation) 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 LedgerSubAccount entity. +// If the LedgerSubAccount 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 *LedgerSubAccountMutation) 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 *LedgerSubAccountMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[ledgersubaccount.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *LedgerSubAccountMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[ledgersubaccount.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *LedgerSubAccountMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, ledgersubaccount.FieldAnnotations) +} + +// SetCreatedAt sets the "created_at" field. +func (m *LedgerSubAccountMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *LedgerSubAccountMutation) 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 LedgerSubAccount entity. +// If the LedgerSubAccount 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 *LedgerSubAccountMutation) 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 *LedgerSubAccountMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *LedgerSubAccountMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *LedgerSubAccountMutation) 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 LedgerSubAccount entity. +// If the LedgerSubAccount 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 *LedgerSubAccountMutation) 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 *LedgerSubAccountMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *LedgerSubAccountMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *LedgerSubAccountMutation) 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 LedgerSubAccount entity. +// If the LedgerSubAccount 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 *LedgerSubAccountMutation) 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 *LedgerSubAccountMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[ledgersubaccount.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *LedgerSubAccountMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[ledgersubaccount.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *LedgerSubAccountMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, ledgersubaccount.FieldDeletedAt) +} + +// SetAccountID sets the "account_id" field. +func (m *LedgerSubAccountMutation) SetAccountID(s string) { + m.account = &s +} + +// AccountID returns the value of the "account_id" field in the mutation. +func (m *LedgerSubAccountMutation) AccountID() (r string, exists bool) { + v := m.account + if v == nil { + return + } + return *v, true +} + +// OldAccountID returns the old "account_id" field's value of the LedgerSubAccount entity. +// If the LedgerSubAccount 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 *LedgerSubAccountMutation) OldAccountID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAccountID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAccountID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAccountID: %w", err) + } + return oldValue.AccountID, nil +} + +// ResetAccountID resets all changes to the "account_id" field. +func (m *LedgerSubAccountMutation) ResetAccountID() { + m.account = nil +} + +// SetRouteID sets the "route_id" field. +func (m *LedgerSubAccountMutation) SetRouteID(s string) { + m.route = &s +} + +// RouteID returns the value of the "route_id" field in the mutation. +func (m *LedgerSubAccountMutation) RouteID() (r string, exists bool) { + v := m.route + if v == nil { + return + } + return *v, true +} + +// OldRouteID returns the old "route_id" field's value of the LedgerSubAccount entity. +// If the LedgerSubAccount 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 *LedgerSubAccountMutation) OldRouteID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRouteID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRouteID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRouteID: %w", err) + } + return oldValue.RouteID, nil +} + +// ResetRouteID resets all changes to the "route_id" field. +func (m *LedgerSubAccountMutation) ResetRouteID() { + m.route = nil +} + +// ClearAccount clears the "account" edge to the LedgerAccount entity. +func (m *LedgerSubAccountMutation) ClearAccount() { + m.clearedaccount = true + m.clearedFields[ledgersubaccount.FieldAccountID] = struct{}{} +} + +// AccountCleared reports if the "account" edge to the LedgerAccount entity was cleared. +func (m *LedgerSubAccountMutation) AccountCleared() bool { + return m.clearedaccount +} + +// AccountIDs returns the "account" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// AccountID instead. It exists only for internal usage by the builders. +func (m *LedgerSubAccountMutation) AccountIDs() (ids []string) { + if id := m.account; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetAccount resets all changes to the "account" edge. +func (m *LedgerSubAccountMutation) ResetAccount() { + m.account = nil + m.clearedaccount = false +} + +// ClearRoute clears the "route" edge to the LedgerSubAccountRoute entity. +func (m *LedgerSubAccountMutation) ClearRoute() { + m.clearedroute = true + m.clearedFields[ledgersubaccount.FieldRouteID] = struct{}{} +} + +// RouteCleared reports if the "route" edge to the LedgerSubAccountRoute entity was cleared. +func (m *LedgerSubAccountMutation) RouteCleared() bool { + return m.clearedroute +} + +// RouteIDs returns the "route" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// RouteID instead. It exists only for internal usage by the builders. +func (m *LedgerSubAccountMutation) RouteIDs() (ids []string) { + if id := m.route; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetRoute resets all changes to the "route" edge. +func (m *LedgerSubAccountMutation) ResetRoute() { + m.route = nil + m.clearedroute = false +} + +// AddEntryIDs adds the "entries" edge to the LedgerEntry entity by ids. +func (m *LedgerSubAccountMutation) AddEntryIDs(ids ...string) { + if m.entries == nil { + m.entries = make(map[string]struct{}) + } + for i := range ids { + m.entries[ids[i]] = struct{}{} + } +} + +// ClearEntries clears the "entries" edge to the LedgerEntry entity. +func (m *LedgerSubAccountMutation) ClearEntries() { + m.clearedentries = true +} + +// EntriesCleared reports if the "entries" edge to the LedgerEntry entity was cleared. +func (m *LedgerSubAccountMutation) EntriesCleared() bool { + return m.clearedentries +} + +// RemoveEntryIDs removes the "entries" edge to the LedgerEntry entity by IDs. +func (m *LedgerSubAccountMutation) RemoveEntryIDs(ids ...string) { + if m.removedentries == nil { + m.removedentries = make(map[string]struct{}) + } + for i := range ids { + delete(m.entries, ids[i]) + m.removedentries[ids[i]] = struct{}{} + } +} + +// RemovedEntries returns the removed IDs of the "entries" edge to the LedgerEntry entity. +func (m *LedgerSubAccountMutation) RemovedEntriesIDs() (ids []string) { + for id := range m.removedentries { + ids = append(ids, id) + } + return +} + +// EntriesIDs returns the "entries" edge IDs in the mutation. +func (m *LedgerSubAccountMutation) EntriesIDs() (ids []string) { + for id := range m.entries { + ids = append(ids, id) + } + return +} + +// ResetEntries resets all changes to the "entries" edge. +func (m *LedgerSubAccountMutation) ResetEntries() { + m.entries = nil + m.clearedentries = false + m.removedentries = nil +} + +// AddFboBreakageRecordIDs adds the "fbo_breakage_records" edge to the LedgerBreakageRecord entity by ids. +func (m *LedgerSubAccountMutation) AddFboBreakageRecordIDs(ids ...string) { + if m.fbo_breakage_records == nil { + m.fbo_breakage_records = make(map[string]struct{}) + } + for i := range ids { + m.fbo_breakage_records[ids[i]] = struct{}{} + } +} + +// ClearFboBreakageRecords clears the "fbo_breakage_records" edge to the LedgerBreakageRecord entity. +func (m *LedgerSubAccountMutation) ClearFboBreakageRecords() { + m.clearedfbo_breakage_records = true +} + +// FboBreakageRecordsCleared reports if the "fbo_breakage_records" edge to the LedgerBreakageRecord entity was cleared. +func (m *LedgerSubAccountMutation) FboBreakageRecordsCleared() bool { + return m.clearedfbo_breakage_records +} + +// RemoveFboBreakageRecordIDs removes the "fbo_breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (m *LedgerSubAccountMutation) RemoveFboBreakageRecordIDs(ids ...string) { + if m.removedfbo_breakage_records == nil { + m.removedfbo_breakage_records = make(map[string]struct{}) + } + for i := range ids { + delete(m.fbo_breakage_records, ids[i]) + m.removedfbo_breakage_records[ids[i]] = struct{}{} + } +} + +// RemovedFboBreakageRecords returns the removed IDs of the "fbo_breakage_records" edge to the LedgerBreakageRecord entity. +func (m *LedgerSubAccountMutation) RemovedFboBreakageRecordsIDs() (ids []string) { + for id := range m.removedfbo_breakage_records { + ids = append(ids, id) + } + return +} + +// FboBreakageRecordsIDs returns the "fbo_breakage_records" edge IDs in the mutation. +func (m *LedgerSubAccountMutation) FboBreakageRecordsIDs() (ids []string) { + for id := range m.fbo_breakage_records { + ids = append(ids, id) + } + return +} + +// ResetFboBreakageRecords resets all changes to the "fbo_breakage_records" edge. +func (m *LedgerSubAccountMutation) ResetFboBreakageRecords() { + m.fbo_breakage_records = nil + m.clearedfbo_breakage_records = false + m.removedfbo_breakage_records = nil +} + +// AddBreakageRecordIDs adds the "breakage_records" edge to the LedgerBreakageRecord entity by ids. +func (m *LedgerSubAccountMutation) AddBreakageRecordIDs(ids ...string) { + if m.breakage_records == nil { + m.breakage_records = make(map[string]struct{}) + } + for i := range ids { + m.breakage_records[ids[i]] = struct{}{} + } +} + +// ClearBreakageRecords clears the "breakage_records" edge to the LedgerBreakageRecord entity. +func (m *LedgerSubAccountMutation) ClearBreakageRecords() { + m.clearedbreakage_records = true +} + +// BreakageRecordsCleared reports if the "breakage_records" edge to the LedgerBreakageRecord entity was cleared. +func (m *LedgerSubAccountMutation) BreakageRecordsCleared() bool { + return m.clearedbreakage_records +} + +// RemoveBreakageRecordIDs removes the "breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (m *LedgerSubAccountMutation) RemoveBreakageRecordIDs(ids ...string) { + if m.removedbreakage_records == nil { + m.removedbreakage_records = make(map[string]struct{}) + } + for i := range ids { + delete(m.breakage_records, ids[i]) + m.removedbreakage_records[ids[i]] = struct{}{} + } +} + +// RemovedBreakageRecords returns the removed IDs of the "breakage_records" edge to the LedgerBreakageRecord entity. +func (m *LedgerSubAccountMutation) RemovedBreakageRecordsIDs() (ids []string) { + for id := range m.removedbreakage_records { + ids = append(ids, id) + } + return +} + +// BreakageRecordsIDs returns the "breakage_records" edge IDs in the mutation. +func (m *LedgerSubAccountMutation) BreakageRecordsIDs() (ids []string) { + for id := range m.breakage_records { + ids = append(ids, id) + } + return +} + +// ResetBreakageRecords resets all changes to the "breakage_records" edge. +func (m *LedgerSubAccountMutation) ResetBreakageRecords() { + m.breakage_records = nil + m.clearedbreakage_records = false + m.removedbreakage_records = nil +} + +// Where appends a list predicates to the LedgerSubAccountMutation builder. +func (m *LedgerSubAccountMutation) Where(ps ...predicate.LedgerSubAccount) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the LedgerSubAccountMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *LedgerSubAccountMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.LedgerSubAccount, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *LedgerSubAccountMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *LedgerSubAccountMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (LedgerSubAccount). +func (m *LedgerSubAccountMutation) 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 *LedgerSubAccountMutation) Fields() []string { + fields := make([]string, 0, 7) + if m.namespace != nil { + fields = append(fields, ledgersubaccount.FieldNamespace) + } + if m.annotations != nil { + fields = append(fields, ledgersubaccount.FieldAnnotations) + } + if m.created_at != nil { + fields = append(fields, ledgersubaccount.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, ledgersubaccount.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, ledgersubaccount.FieldDeletedAt) + } + if m.account != nil { + fields = append(fields, ledgersubaccount.FieldAccountID) + } + if m.route != nil { + fields = append(fields, ledgersubaccount.FieldRouteID) + } + 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 *LedgerSubAccountMutation) Field(name string) (ent.Value, bool) { + switch name { + case ledgersubaccount.FieldNamespace: + return m.Namespace() + case ledgersubaccount.FieldAnnotations: + return m.Annotations() + case ledgersubaccount.FieldCreatedAt: + return m.CreatedAt() + case ledgersubaccount.FieldUpdatedAt: + return m.UpdatedAt() + case ledgersubaccount.FieldDeletedAt: + return m.DeletedAt() + case ledgersubaccount.FieldAccountID: + return m.AccountID() + case ledgersubaccount.FieldRouteID: + return m.RouteID() + } + 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 *LedgerSubAccountMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case ledgersubaccount.FieldNamespace: + return m.OldNamespace(ctx) + case ledgersubaccount.FieldAnnotations: + return m.OldAnnotations(ctx) + case ledgersubaccount.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case ledgersubaccount.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case ledgersubaccount.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case ledgersubaccount.FieldAccountID: + return m.OldAccountID(ctx) + case ledgersubaccount.FieldRouteID: + return m.OldRouteID(ctx) + } + return nil, fmt.Errorf("unknown LedgerSubAccount 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 *LedgerSubAccountMutation) SetField(name string, value ent.Value) error { + switch name { + case ledgersubaccount.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case ledgersubaccount.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 ledgersubaccount.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 ledgersubaccount.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 ledgersubaccount.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 ledgersubaccount.FieldAccountID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAccountID(v) + return nil + case ledgersubaccount.FieldRouteID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRouteID(v) + return nil + } + return fmt.Errorf("unknown LedgerSubAccount field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LedgerSubAccountMutation) 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 *LedgerSubAccountMutation) 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 *LedgerSubAccountMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown LedgerSubAccount numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LedgerSubAccountMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(ledgersubaccount.FieldAnnotations) { + fields = append(fields, ledgersubaccount.FieldAnnotations) + } + if m.FieldCleared(ledgersubaccount.FieldDeletedAt) { + fields = append(fields, ledgersubaccount.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LedgerSubAccountMutation) 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 *LedgerSubAccountMutation) ClearField(name string) error { + switch name { + case ledgersubaccount.FieldAnnotations: + m.ClearAnnotations() + return nil + case ledgersubaccount.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown LedgerSubAccount 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 *LedgerSubAccountMutation) ResetField(name string) error { + switch name { + case ledgersubaccount.FieldNamespace: + m.ResetNamespace() + return nil + case ledgersubaccount.FieldAnnotations: + m.ResetAnnotations() + return nil + case ledgersubaccount.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case ledgersubaccount.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case ledgersubaccount.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case ledgersubaccount.FieldAccountID: + m.ResetAccountID() + return nil + case ledgersubaccount.FieldRouteID: + m.ResetRouteID() + return nil + } + return fmt.Errorf("unknown LedgerSubAccount field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LedgerSubAccountMutation) AddedEdges() []string { + edges := make([]string, 0, 5) + if m.account != nil { + edges = append(edges, ledgersubaccount.EdgeAccount) + } + if m.route != nil { + edges = append(edges, ledgersubaccount.EdgeRoute) + } + if m.entries != nil { + edges = append(edges, ledgersubaccount.EdgeEntries) + } + if m.fbo_breakage_records != nil { + edges = append(edges, ledgersubaccount.EdgeFboBreakageRecords) + } + if m.breakage_records != nil { + edges = append(edges, ledgersubaccount.EdgeBreakageRecords) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LedgerSubAccountMutation) AddedIDs(name string) []ent.Value { + switch name { + case ledgersubaccount.EdgeAccount: + if id := m.account; id != nil { + return []ent.Value{*id} + } + case ledgersubaccount.EdgeRoute: + if id := m.route; id != nil { + return []ent.Value{*id} + } + case ledgersubaccount.EdgeEntries: + ids := make([]ent.Value, 0, len(m.entries)) + for id := range m.entries { + ids = append(ids, id) + } + return ids + case ledgersubaccount.EdgeFboBreakageRecords: + ids := make([]ent.Value, 0, len(m.fbo_breakage_records)) + for id := range m.fbo_breakage_records { + ids = append(ids, id) + } + return ids + case ledgersubaccount.EdgeBreakageRecords: + ids := make([]ent.Value, 0, len(m.breakage_records)) + for id := range m.breakage_records { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LedgerSubAccountMutation) RemovedEdges() []string { + edges := make([]string, 0, 5) + if m.removedentries != nil { + edges = append(edges, ledgersubaccount.EdgeEntries) + } + if m.removedfbo_breakage_records != nil { + edges = append(edges, ledgersubaccount.EdgeFboBreakageRecords) + } + if m.removedbreakage_records != nil { + edges = append(edges, ledgersubaccount.EdgeBreakageRecords) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LedgerSubAccountMutation) RemovedIDs(name string) []ent.Value { + switch name { + case ledgersubaccount.EdgeEntries: + ids := make([]ent.Value, 0, len(m.removedentries)) + for id := range m.removedentries { + ids = append(ids, id) + } + return ids + case ledgersubaccount.EdgeFboBreakageRecords: + ids := make([]ent.Value, 0, len(m.removedfbo_breakage_records)) + for id := range m.removedfbo_breakage_records { + ids = append(ids, id) + } + return ids + case ledgersubaccount.EdgeBreakageRecords: + ids := make([]ent.Value, 0, len(m.removedbreakage_records)) + for id := range m.removedbreakage_records { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LedgerSubAccountMutation) ClearedEdges() []string { + edges := make([]string, 0, 5) + if m.clearedaccount { + edges = append(edges, ledgersubaccount.EdgeAccount) + } + if m.clearedroute { + edges = append(edges, ledgersubaccount.EdgeRoute) + } + if m.clearedentries { + edges = append(edges, ledgersubaccount.EdgeEntries) + } + if m.clearedfbo_breakage_records { + edges = append(edges, ledgersubaccount.EdgeFboBreakageRecords) + } + if m.clearedbreakage_records { + edges = append(edges, ledgersubaccount.EdgeBreakageRecords) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LedgerSubAccountMutation) EdgeCleared(name string) bool { + switch name { + case ledgersubaccount.EdgeAccount: + return m.clearedaccount + case ledgersubaccount.EdgeRoute: + return m.clearedroute + case ledgersubaccount.EdgeEntries: + return m.clearedentries + case ledgersubaccount.EdgeFboBreakageRecords: + return m.clearedfbo_breakage_records + case ledgersubaccount.EdgeBreakageRecords: + return m.clearedbreakage_records + } + 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 *LedgerSubAccountMutation) ClearEdge(name string) error { + switch name { + case ledgersubaccount.EdgeAccount: + m.ClearAccount() + return nil + case ledgersubaccount.EdgeRoute: + m.ClearRoute() + return nil + } + return fmt.Errorf("unknown LedgerSubAccount 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 *LedgerSubAccountMutation) ResetEdge(name string) error { + switch name { + case ledgersubaccount.EdgeAccount: + m.ResetAccount() + return nil + case ledgersubaccount.EdgeRoute: + m.ResetRoute() + return nil + case ledgersubaccount.EdgeEntries: + m.ResetEntries() + return nil + case ledgersubaccount.EdgeFboBreakageRecords: + m.ResetFboBreakageRecords() + return nil + case ledgersubaccount.EdgeBreakageRecords: + m.ResetBreakageRecords() + return nil + } + return fmt.Errorf("unknown LedgerSubAccount edge %s", name) +} + +// LedgerSubAccountRouteMutation represents an operation that mutates the LedgerSubAccountRoute nodes in the graph. +type LedgerSubAccountRouteMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + routing_key_version *ledger.RoutingKeyVersion + routing_key *string + currency *string + tax_code *string + tax_behavior *ledger.TaxBehavior + features *pq.StringArray + cost_basis *alpacadecimal.Decimal + credit_priority *int + addcredit_priority *int + transaction_authorization_status *ledger.TransactionAuthorizationStatus + clearedFields map[string]struct{} + account *string + clearedaccount bool + sub_accounts map[string]struct{} + removedsub_accounts map[string]struct{} + clearedsub_accounts bool + done bool + oldValue func(context.Context) (*LedgerSubAccountRoute, error) + predicates []predicate.LedgerSubAccountRoute +} + +var _ ent.Mutation = (*LedgerSubAccountRouteMutation)(nil) + +// ledgersubaccountrouteOption allows management of the mutation configuration using functional options. +type ledgersubaccountrouteOption func(*LedgerSubAccountRouteMutation) + +// newLedgerSubAccountRouteMutation creates new mutation for the LedgerSubAccountRoute entity. +func newLedgerSubAccountRouteMutation(c config, op Op, opts ...ledgersubaccountrouteOption) *LedgerSubAccountRouteMutation { + m := &LedgerSubAccountRouteMutation{ + config: c, + op: op, + typ: TypeLedgerSubAccountRoute, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLedgerSubAccountRouteID sets the ID field of the mutation. +func withLedgerSubAccountRouteID(id string) ledgersubaccountrouteOption { + return func(m *LedgerSubAccountRouteMutation) { + var ( + err error + once sync.Once + value *LedgerSubAccountRoute + ) + m.oldValue = func(ctx context.Context) (*LedgerSubAccountRoute, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LedgerSubAccountRoute.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLedgerSubAccountRoute sets the old LedgerSubAccountRoute of the mutation. +func withLedgerSubAccountRoute(node *LedgerSubAccountRoute) ledgersubaccountrouteOption { + return func(m *LedgerSubAccountRouteMutation) { + m.oldValue = func(context.Context) (*LedgerSubAccountRoute, 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 LedgerSubAccountRouteMutation) 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 LedgerSubAccountRouteMutation) 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 LedgerSubAccountRoute entities. +func (m *LedgerSubAccountRouteMutation) 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 *LedgerSubAccountRouteMutation) 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 *LedgerSubAccountRouteMutation) 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().LedgerSubAccountRoute.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 *LedgerSubAccountRouteMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *LedgerSubAccountRouteMutation) 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 LedgerSubAccountRoute entity. +// If the LedgerSubAccountRoute 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 *LedgerSubAccountRouteMutation) 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 *LedgerSubAccountRouteMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *LedgerSubAccountRouteMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *LedgerSubAccountRouteMutation) 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 LedgerSubAccountRoute entity. +// If the LedgerSubAccountRoute 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 *LedgerSubAccountRouteMutation) 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 *LedgerSubAccountRouteMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *LedgerSubAccountRouteMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *LedgerSubAccountRouteMutation) 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 LedgerSubAccountRoute entity. +// If the LedgerSubAccountRoute 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 *LedgerSubAccountRouteMutation) 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 *LedgerSubAccountRouteMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *LedgerSubAccountRouteMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *LedgerSubAccountRouteMutation) 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 LedgerSubAccountRoute entity. +// If the LedgerSubAccountRoute 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 *LedgerSubAccountRouteMutation) 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 *LedgerSubAccountRouteMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[ledgersubaccountroute.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *LedgerSubAccountRouteMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[ledgersubaccountroute.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *LedgerSubAccountRouteMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, ledgersubaccountroute.FieldDeletedAt) +} + +// SetAccountID sets the "account_id" field. +func (m *LedgerSubAccountRouteMutation) SetAccountID(s string) { + m.account = &s +} + +// AccountID returns the value of the "account_id" field in the mutation. +func (m *LedgerSubAccountRouteMutation) AccountID() (r string, exists bool) { + v := m.account + if v == nil { + return + } + return *v, true +} + +// OldAccountID returns the old "account_id" field's value of the LedgerSubAccountRoute entity. +// If the LedgerSubAccountRoute 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 *LedgerSubAccountRouteMutation) OldAccountID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAccountID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAccountID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAccountID: %w", err) + } + return oldValue.AccountID, nil +} + +// ResetAccountID resets all changes to the "account_id" field. +func (m *LedgerSubAccountRouteMutation) ResetAccountID() { + m.account = nil +} + +// SetRoutingKeyVersion sets the "routing_key_version" field. +func (m *LedgerSubAccountRouteMutation) SetRoutingKeyVersion(lkv ledger.RoutingKeyVersion) { + m.routing_key_version = &lkv +} + +// RoutingKeyVersion returns the value of the "routing_key_version" field in the mutation. +func (m *LedgerSubAccountRouteMutation) RoutingKeyVersion() (r ledger.RoutingKeyVersion, exists bool) { + v := m.routing_key_version + if v == nil { + return + } + return *v, true +} + +// OldRoutingKeyVersion returns the old "routing_key_version" field's value of the LedgerSubAccountRoute entity. +// If the LedgerSubAccountRoute 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 *LedgerSubAccountRouteMutation) OldRoutingKeyVersion(ctx context.Context) (v ledger.RoutingKeyVersion, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRoutingKeyVersion is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRoutingKeyVersion requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRoutingKeyVersion: %w", err) + } + return oldValue.RoutingKeyVersion, nil +} + +// ResetRoutingKeyVersion resets all changes to the "routing_key_version" field. +func (m *LedgerSubAccountRouteMutation) ResetRoutingKeyVersion() { + m.routing_key_version = nil +} + +// SetRoutingKey sets the "routing_key" field. +func (m *LedgerSubAccountRouteMutation) SetRoutingKey(s string) { + m.routing_key = &s +} + +// RoutingKey returns the value of the "routing_key" field in the mutation. +func (m *LedgerSubAccountRouteMutation) RoutingKey() (r string, exists bool) { + v := m.routing_key + if v == nil { + return + } + return *v, true +} + +// OldRoutingKey returns the old "routing_key" field's value of the LedgerSubAccountRoute entity. +// If the LedgerSubAccountRoute 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 *LedgerSubAccountRouteMutation) OldRoutingKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRoutingKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRoutingKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRoutingKey: %w", err) + } + return oldValue.RoutingKey, nil +} + +// ResetRoutingKey resets all changes to the "routing_key" field. +func (m *LedgerSubAccountRouteMutation) ResetRoutingKey() { + m.routing_key = nil +} + +// SetCurrency sets the "currency" field. +func (m *LedgerSubAccountRouteMutation) SetCurrency(s string) { + m.currency = &s +} + +// Currency returns the value of the "currency" field in the mutation. +func (m *LedgerSubAccountRouteMutation) Currency() (r string, exists bool) { + v := m.currency + if v == nil { + return + } + return *v, true +} + +// OldCurrency returns the old "currency" field's value of the LedgerSubAccountRoute entity. +// If the LedgerSubAccountRoute 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 *LedgerSubAccountRouteMutation) OldCurrency(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrency is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrency requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrency: %w", err) + } + return oldValue.Currency, nil +} + +// ResetCurrency resets all changes to the "currency" field. +func (m *LedgerSubAccountRouteMutation) ResetCurrency() { + m.currency = nil +} + +// SetTaxCode sets the "tax_code" field. +func (m *LedgerSubAccountRouteMutation) SetTaxCode(s string) { + m.tax_code = &s +} + +// TaxCode returns the value of the "tax_code" field in the mutation. +func (m *LedgerSubAccountRouteMutation) TaxCode() (r string, exists bool) { + v := m.tax_code + if v == nil { + return + } + return *v, true +} + +// OldTaxCode returns the old "tax_code" field's value of the LedgerSubAccountRoute entity. +// If the LedgerSubAccountRoute 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 *LedgerSubAccountRouteMutation) OldTaxCode(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxCode is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxCode requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxCode: %w", err) + } + return oldValue.TaxCode, nil +} + +// ClearTaxCode clears the value of the "tax_code" field. +func (m *LedgerSubAccountRouteMutation) ClearTaxCode() { + m.tax_code = nil + m.clearedFields[ledgersubaccountroute.FieldTaxCode] = struct{}{} +} + +// TaxCodeCleared returns if the "tax_code" field was cleared in this mutation. +func (m *LedgerSubAccountRouteMutation) TaxCodeCleared() bool { + _, ok := m.clearedFields[ledgersubaccountroute.FieldTaxCode] + return ok +} + +// ResetTaxCode resets all changes to the "tax_code" field. +func (m *LedgerSubAccountRouteMutation) ResetTaxCode() { + m.tax_code = nil + delete(m.clearedFields, ledgersubaccountroute.FieldTaxCode) +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (m *LedgerSubAccountRouteMutation) SetTaxBehavior(lb ledger.TaxBehavior) { + m.tax_behavior = &lb +} + +// TaxBehavior returns the value of the "tax_behavior" field in the mutation. +func (m *LedgerSubAccountRouteMutation) TaxBehavior() (r ledger.TaxBehavior, exists bool) { + v := m.tax_behavior + if v == nil { + return + } + return *v, true +} + +// OldTaxBehavior returns the old "tax_behavior" field's value of the LedgerSubAccountRoute entity. +// If the LedgerSubAccountRoute 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 *LedgerSubAccountRouteMutation) OldTaxBehavior(ctx context.Context) (v *ledger.TaxBehavior, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxBehavior is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxBehavior requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxBehavior: %w", err) + } + return oldValue.TaxBehavior, nil +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (m *LedgerSubAccountRouteMutation) ClearTaxBehavior() { + m.tax_behavior = nil + m.clearedFields[ledgersubaccountroute.FieldTaxBehavior] = struct{}{} +} + +// TaxBehaviorCleared returns if the "tax_behavior" field was cleared in this mutation. +func (m *LedgerSubAccountRouteMutation) TaxBehaviorCleared() bool { + _, ok := m.clearedFields[ledgersubaccountroute.FieldTaxBehavior] + return ok +} + +// ResetTaxBehavior resets all changes to the "tax_behavior" field. +func (m *LedgerSubAccountRouteMutation) ResetTaxBehavior() { + m.tax_behavior = nil + delete(m.clearedFields, ledgersubaccountroute.FieldTaxBehavior) +} + +// SetFeatures sets the "features" field. +func (m *LedgerSubAccountRouteMutation) SetFeatures(pa pq.StringArray) { + m.features = &pa +} + +// Features returns the value of the "features" field in the mutation. +func (m *LedgerSubAccountRouteMutation) Features() (r pq.StringArray, exists bool) { + v := m.features + if v == nil { + return + } + return *v, true +} + +// OldFeatures returns the old "features" field's value of the LedgerSubAccountRoute entity. +// If the LedgerSubAccountRoute 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 *LedgerSubAccountRouteMutation) OldFeatures(ctx context.Context) (v pq.StringArray, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFeatures is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFeatures requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFeatures: %w", err) + } + return oldValue.Features, nil +} + +// ClearFeatures clears the value of the "features" field. +func (m *LedgerSubAccountRouteMutation) ClearFeatures() { + m.features = nil + m.clearedFields[ledgersubaccountroute.FieldFeatures] = struct{}{} +} + +// FeaturesCleared returns if the "features" field was cleared in this mutation. +func (m *LedgerSubAccountRouteMutation) FeaturesCleared() bool { + _, ok := m.clearedFields[ledgersubaccountroute.FieldFeatures] + return ok +} + +// ResetFeatures resets all changes to the "features" field. +func (m *LedgerSubAccountRouteMutation) ResetFeatures() { + m.features = nil + delete(m.clearedFields, ledgersubaccountroute.FieldFeatures) +} + +// SetCostBasis sets the "cost_basis" field. +func (m *LedgerSubAccountRouteMutation) SetCostBasis(a alpacadecimal.Decimal) { + m.cost_basis = &a +} + +// CostBasis returns the value of the "cost_basis" field in the mutation. +func (m *LedgerSubAccountRouteMutation) CostBasis() (r alpacadecimal.Decimal, exists bool) { + v := m.cost_basis + if v == nil { + return + } + return *v, true +} + +// OldCostBasis returns the old "cost_basis" field's value of the LedgerSubAccountRoute entity. +// If the LedgerSubAccountRoute 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 *LedgerSubAccountRouteMutation) OldCostBasis(ctx context.Context) (v *alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCostBasis is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCostBasis requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCostBasis: %w", err) + } + return oldValue.CostBasis, nil +} + +// ClearCostBasis clears the value of the "cost_basis" field. +func (m *LedgerSubAccountRouteMutation) ClearCostBasis() { + m.cost_basis = nil + m.clearedFields[ledgersubaccountroute.FieldCostBasis] = struct{}{} +} + +// CostBasisCleared returns if the "cost_basis" field was cleared in this mutation. +func (m *LedgerSubAccountRouteMutation) CostBasisCleared() bool { + _, ok := m.clearedFields[ledgersubaccountroute.FieldCostBasis] + return ok +} + +// ResetCostBasis resets all changes to the "cost_basis" field. +func (m *LedgerSubAccountRouteMutation) ResetCostBasis() { + m.cost_basis = nil + delete(m.clearedFields, ledgersubaccountroute.FieldCostBasis) +} + +// SetCreditPriority sets the "credit_priority" field. +func (m *LedgerSubAccountRouteMutation) SetCreditPriority(i int) { + m.credit_priority = &i + m.addcredit_priority = nil +} + +// CreditPriority returns the value of the "credit_priority" field in the mutation. +func (m *LedgerSubAccountRouteMutation) CreditPriority() (r int, exists bool) { + v := m.credit_priority + if v == nil { + return + } + return *v, true +} + +// OldCreditPriority returns the old "credit_priority" field's value of the LedgerSubAccountRoute entity. +// If the LedgerSubAccountRoute 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 *LedgerSubAccountRouteMutation) OldCreditPriority(ctx context.Context) (v *int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreditPriority is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreditPriority requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreditPriority: %w", err) + } + return oldValue.CreditPriority, nil +} + +// AddCreditPriority adds i to the "credit_priority" field. +func (m *LedgerSubAccountRouteMutation) AddCreditPriority(i int) { + if m.addcredit_priority != nil { + *m.addcredit_priority += i + } else { + m.addcredit_priority = &i + } +} + +// AddedCreditPriority returns the value that was added to the "credit_priority" field in this mutation. +func (m *LedgerSubAccountRouteMutation) AddedCreditPriority() (r int, exists bool) { + v := m.addcredit_priority + if v == nil { + return + } + return *v, true +} + +// ClearCreditPriority clears the value of the "credit_priority" field. +func (m *LedgerSubAccountRouteMutation) ClearCreditPriority() { + m.credit_priority = nil + m.addcredit_priority = nil + m.clearedFields[ledgersubaccountroute.FieldCreditPriority] = struct{}{} +} + +// CreditPriorityCleared returns if the "credit_priority" field was cleared in this mutation. +func (m *LedgerSubAccountRouteMutation) CreditPriorityCleared() bool { + _, ok := m.clearedFields[ledgersubaccountroute.FieldCreditPriority] + return ok +} + +// ResetCreditPriority resets all changes to the "credit_priority" field. +func (m *LedgerSubAccountRouteMutation) ResetCreditPriority() { + m.credit_priority = nil + m.addcredit_priority = nil + delete(m.clearedFields, ledgersubaccountroute.FieldCreditPriority) +} + +// SetTransactionAuthorizationStatus sets the "transaction_authorization_status" field. +func (m *LedgerSubAccountRouteMutation) SetTransactionAuthorizationStatus(las ledger.TransactionAuthorizationStatus) { + m.transaction_authorization_status = &las +} + +// TransactionAuthorizationStatus returns the value of the "transaction_authorization_status" field in the mutation. +func (m *LedgerSubAccountRouteMutation) TransactionAuthorizationStatus() (r ledger.TransactionAuthorizationStatus, exists bool) { + v := m.transaction_authorization_status + if v == nil { + return + } + return *v, true +} + +// OldTransactionAuthorizationStatus returns the old "transaction_authorization_status" field's value of the LedgerSubAccountRoute entity. +// If the LedgerSubAccountRoute 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 *LedgerSubAccountRouteMutation) OldTransactionAuthorizationStatus(ctx context.Context) (v *ledger.TransactionAuthorizationStatus, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTransactionAuthorizationStatus is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTransactionAuthorizationStatus requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTransactionAuthorizationStatus: %w", err) + } + return oldValue.TransactionAuthorizationStatus, nil +} + +// ClearTransactionAuthorizationStatus clears the value of the "transaction_authorization_status" field. +func (m *LedgerSubAccountRouteMutation) ClearTransactionAuthorizationStatus() { + m.transaction_authorization_status = nil + m.clearedFields[ledgersubaccountroute.FieldTransactionAuthorizationStatus] = struct{}{} +} + +// TransactionAuthorizationStatusCleared returns if the "transaction_authorization_status" field was cleared in this mutation. +func (m *LedgerSubAccountRouteMutation) TransactionAuthorizationStatusCleared() bool { + _, ok := m.clearedFields[ledgersubaccountroute.FieldTransactionAuthorizationStatus] + return ok +} + +// ResetTransactionAuthorizationStatus resets all changes to the "transaction_authorization_status" field. +func (m *LedgerSubAccountRouteMutation) ResetTransactionAuthorizationStatus() { + m.transaction_authorization_status = nil + delete(m.clearedFields, ledgersubaccountroute.FieldTransactionAuthorizationStatus) +} + +// ClearAccount clears the "account" edge to the LedgerAccount entity. +func (m *LedgerSubAccountRouteMutation) ClearAccount() { + m.clearedaccount = true + m.clearedFields[ledgersubaccountroute.FieldAccountID] = struct{}{} +} + +// AccountCleared reports if the "account" edge to the LedgerAccount entity was cleared. +func (m *LedgerSubAccountRouteMutation) AccountCleared() bool { + return m.clearedaccount +} + +// AccountIDs returns the "account" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// AccountID instead. It exists only for internal usage by the builders. +func (m *LedgerSubAccountRouteMutation) AccountIDs() (ids []string) { + if id := m.account; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetAccount resets all changes to the "account" edge. +func (m *LedgerSubAccountRouteMutation) ResetAccount() { + m.account = nil + m.clearedaccount = false +} + +// AddSubAccountIDs adds the "sub_accounts" edge to the LedgerSubAccount entity by ids. +func (m *LedgerSubAccountRouteMutation) AddSubAccountIDs(ids ...string) { + if m.sub_accounts == nil { + m.sub_accounts = make(map[string]struct{}) + } + for i := range ids { + m.sub_accounts[ids[i]] = struct{}{} + } +} + +// ClearSubAccounts clears the "sub_accounts" edge to the LedgerSubAccount entity. +func (m *LedgerSubAccountRouteMutation) ClearSubAccounts() { + m.clearedsub_accounts = true +} + +// SubAccountsCleared reports if the "sub_accounts" edge to the LedgerSubAccount entity was cleared. +func (m *LedgerSubAccountRouteMutation) SubAccountsCleared() bool { + return m.clearedsub_accounts +} + +// RemoveSubAccountIDs removes the "sub_accounts" edge to the LedgerSubAccount entity by IDs. +func (m *LedgerSubAccountRouteMutation) RemoveSubAccountIDs(ids ...string) { + if m.removedsub_accounts == nil { + m.removedsub_accounts = make(map[string]struct{}) + } + for i := range ids { + delete(m.sub_accounts, ids[i]) + m.removedsub_accounts[ids[i]] = struct{}{} + } +} + +// RemovedSubAccounts returns the removed IDs of the "sub_accounts" edge to the LedgerSubAccount entity. +func (m *LedgerSubAccountRouteMutation) RemovedSubAccountsIDs() (ids []string) { + for id := range m.removedsub_accounts { + ids = append(ids, id) + } + return +} + +// SubAccountsIDs returns the "sub_accounts" edge IDs in the mutation. +func (m *LedgerSubAccountRouteMutation) SubAccountsIDs() (ids []string) { + for id := range m.sub_accounts { + ids = append(ids, id) + } + return +} + +// ResetSubAccounts resets all changes to the "sub_accounts" edge. +func (m *LedgerSubAccountRouteMutation) ResetSubAccounts() { + m.sub_accounts = nil + m.clearedsub_accounts = false + m.removedsub_accounts = nil +} + +// Where appends a list predicates to the LedgerSubAccountRouteMutation builder. +func (m *LedgerSubAccountRouteMutation) Where(ps ...predicate.LedgerSubAccountRoute) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the LedgerSubAccountRouteMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *LedgerSubAccountRouteMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.LedgerSubAccountRoute, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *LedgerSubAccountRouteMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *LedgerSubAccountRouteMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (LedgerSubAccountRoute). +func (m *LedgerSubAccountRouteMutation) 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 *LedgerSubAccountRouteMutation) Fields() []string { + fields := make([]string, 0, 14) + if m.namespace != nil { + fields = append(fields, ledgersubaccountroute.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, ledgersubaccountroute.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, ledgersubaccountroute.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, ledgersubaccountroute.FieldDeletedAt) + } + if m.account != nil { + fields = append(fields, ledgersubaccountroute.FieldAccountID) + } + if m.routing_key_version != nil { + fields = append(fields, ledgersubaccountroute.FieldRoutingKeyVersion) + } + if m.routing_key != nil { + fields = append(fields, ledgersubaccountroute.FieldRoutingKey) + } + if m.currency != nil { + fields = append(fields, ledgersubaccountroute.FieldCurrency) + } + if m.tax_code != nil { + fields = append(fields, ledgersubaccountroute.FieldTaxCode) + } + if m.tax_behavior != nil { + fields = append(fields, ledgersubaccountroute.FieldTaxBehavior) + } + if m.features != nil { + fields = append(fields, ledgersubaccountroute.FieldFeatures) + } + if m.cost_basis != nil { + fields = append(fields, ledgersubaccountroute.FieldCostBasis) + } + if m.credit_priority != nil { + fields = append(fields, ledgersubaccountroute.FieldCreditPriority) + } + if m.transaction_authorization_status != nil { + fields = append(fields, ledgersubaccountroute.FieldTransactionAuthorizationStatus) + } + 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 *LedgerSubAccountRouteMutation) Field(name string) (ent.Value, bool) { + switch name { + case ledgersubaccountroute.FieldNamespace: + return m.Namespace() + case ledgersubaccountroute.FieldCreatedAt: + return m.CreatedAt() + case ledgersubaccountroute.FieldUpdatedAt: + return m.UpdatedAt() + case ledgersubaccountroute.FieldDeletedAt: + return m.DeletedAt() + case ledgersubaccountroute.FieldAccountID: + return m.AccountID() + case ledgersubaccountroute.FieldRoutingKeyVersion: + return m.RoutingKeyVersion() + case ledgersubaccountroute.FieldRoutingKey: + return m.RoutingKey() + case ledgersubaccountroute.FieldCurrency: + return m.Currency() + case ledgersubaccountroute.FieldTaxCode: + return m.TaxCode() + case ledgersubaccountroute.FieldTaxBehavior: + return m.TaxBehavior() + case ledgersubaccountroute.FieldFeatures: + return m.Features() + case ledgersubaccountroute.FieldCostBasis: + return m.CostBasis() + case ledgersubaccountroute.FieldCreditPriority: + return m.CreditPriority() + case ledgersubaccountroute.FieldTransactionAuthorizationStatus: + return m.TransactionAuthorizationStatus() + } + 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 *LedgerSubAccountRouteMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case ledgersubaccountroute.FieldNamespace: + return m.OldNamespace(ctx) + case ledgersubaccountroute.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case ledgersubaccountroute.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case ledgersubaccountroute.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case ledgersubaccountroute.FieldAccountID: + return m.OldAccountID(ctx) + case ledgersubaccountroute.FieldRoutingKeyVersion: + return m.OldRoutingKeyVersion(ctx) + case ledgersubaccountroute.FieldRoutingKey: + return m.OldRoutingKey(ctx) + case ledgersubaccountroute.FieldCurrency: + return m.OldCurrency(ctx) + case ledgersubaccountroute.FieldTaxCode: + return m.OldTaxCode(ctx) + case ledgersubaccountroute.FieldTaxBehavior: + return m.OldTaxBehavior(ctx) + case ledgersubaccountroute.FieldFeatures: + return m.OldFeatures(ctx) + case ledgersubaccountroute.FieldCostBasis: + return m.OldCostBasis(ctx) + case ledgersubaccountroute.FieldCreditPriority: + return m.OldCreditPriority(ctx) + case ledgersubaccountroute.FieldTransactionAuthorizationStatus: + return m.OldTransactionAuthorizationStatus(ctx) + } + return nil, fmt.Errorf("unknown LedgerSubAccountRoute 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 *LedgerSubAccountRouteMutation) SetField(name string, value ent.Value) error { + switch name { + case ledgersubaccountroute.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case ledgersubaccountroute.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 ledgersubaccountroute.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 ledgersubaccountroute.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 ledgersubaccountroute.FieldAccountID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAccountID(v) + return nil + case ledgersubaccountroute.FieldRoutingKeyVersion: + v, ok := value.(ledger.RoutingKeyVersion) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRoutingKeyVersion(v) + return nil + case ledgersubaccountroute.FieldRoutingKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRoutingKey(v) + return nil + case ledgersubaccountroute.FieldCurrency: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrency(v) + return nil + case ledgersubaccountroute.FieldTaxCode: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxCode(v) + return nil + case ledgersubaccountroute.FieldTaxBehavior: + v, ok := value.(ledger.TaxBehavior) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxBehavior(v) + return nil + case ledgersubaccountroute.FieldFeatures: + v, ok := value.(pq.StringArray) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFeatures(v) + return nil + case ledgersubaccountroute.FieldCostBasis: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCostBasis(v) + return nil + case ledgersubaccountroute.FieldCreditPriority: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreditPriority(v) + return nil + case ledgersubaccountroute.FieldTransactionAuthorizationStatus: + v, ok := value.(ledger.TransactionAuthorizationStatus) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTransactionAuthorizationStatus(v) + return nil + } + return fmt.Errorf("unknown LedgerSubAccountRoute field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LedgerSubAccountRouteMutation) AddedFields() []string { + var fields []string + if m.addcredit_priority != nil { + fields = append(fields, ledgersubaccountroute.FieldCreditPriority) + } + return fields +} + +// 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 *LedgerSubAccountRouteMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case ledgersubaccountroute.FieldCreditPriority: + return m.AddedCreditPriority() + } + 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 *LedgerSubAccountRouteMutation) AddField(name string, value ent.Value) error { + switch name { + case ledgersubaccountroute.FieldCreditPriority: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddCreditPriority(v) + return nil + } + return fmt.Errorf("unknown LedgerSubAccountRoute numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LedgerSubAccountRouteMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(ledgersubaccountroute.FieldDeletedAt) { + fields = append(fields, ledgersubaccountroute.FieldDeletedAt) + } + if m.FieldCleared(ledgersubaccountroute.FieldTaxCode) { + fields = append(fields, ledgersubaccountroute.FieldTaxCode) + } + if m.FieldCleared(ledgersubaccountroute.FieldTaxBehavior) { + fields = append(fields, ledgersubaccountroute.FieldTaxBehavior) + } + if m.FieldCleared(ledgersubaccountroute.FieldFeatures) { + fields = append(fields, ledgersubaccountroute.FieldFeatures) + } + if m.FieldCleared(ledgersubaccountroute.FieldCostBasis) { + fields = append(fields, ledgersubaccountroute.FieldCostBasis) + } + if m.FieldCleared(ledgersubaccountroute.FieldCreditPriority) { + fields = append(fields, ledgersubaccountroute.FieldCreditPriority) + } + if m.FieldCleared(ledgersubaccountroute.FieldTransactionAuthorizationStatus) { + fields = append(fields, ledgersubaccountroute.FieldTransactionAuthorizationStatus) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LedgerSubAccountRouteMutation) 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 *LedgerSubAccountRouteMutation) ClearField(name string) error { + switch name { + case ledgersubaccountroute.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case ledgersubaccountroute.FieldTaxCode: + m.ClearTaxCode() + return nil + case ledgersubaccountroute.FieldTaxBehavior: + m.ClearTaxBehavior() + return nil + case ledgersubaccountroute.FieldFeatures: + m.ClearFeatures() + return nil + case ledgersubaccountroute.FieldCostBasis: + m.ClearCostBasis() + return nil + case ledgersubaccountroute.FieldCreditPriority: + m.ClearCreditPriority() + return nil + case ledgersubaccountroute.FieldTransactionAuthorizationStatus: + m.ClearTransactionAuthorizationStatus() + return nil + } + return fmt.Errorf("unknown LedgerSubAccountRoute 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 *LedgerSubAccountRouteMutation) ResetField(name string) error { + switch name { + case ledgersubaccountroute.FieldNamespace: + m.ResetNamespace() + return nil + case ledgersubaccountroute.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case ledgersubaccountroute.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case ledgersubaccountroute.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case ledgersubaccountroute.FieldAccountID: + m.ResetAccountID() + return nil + case ledgersubaccountroute.FieldRoutingKeyVersion: + m.ResetRoutingKeyVersion() + return nil + case ledgersubaccountroute.FieldRoutingKey: + m.ResetRoutingKey() + return nil + case ledgersubaccountroute.FieldCurrency: + m.ResetCurrency() + return nil + case ledgersubaccountroute.FieldTaxCode: + m.ResetTaxCode() + return nil + case ledgersubaccountroute.FieldTaxBehavior: + m.ResetTaxBehavior() + return nil + case ledgersubaccountroute.FieldFeatures: + m.ResetFeatures() + return nil + case ledgersubaccountroute.FieldCostBasis: + m.ResetCostBasis() + return nil + case ledgersubaccountroute.FieldCreditPriority: + m.ResetCreditPriority() + return nil + case ledgersubaccountroute.FieldTransactionAuthorizationStatus: + m.ResetTransactionAuthorizationStatus() + return nil + } + return fmt.Errorf("unknown LedgerSubAccountRoute field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LedgerSubAccountRouteMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.account != nil { + edges = append(edges, ledgersubaccountroute.EdgeAccount) + } + if m.sub_accounts != nil { + edges = append(edges, ledgersubaccountroute.EdgeSubAccounts) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LedgerSubAccountRouteMutation) AddedIDs(name string) []ent.Value { + switch name { + case ledgersubaccountroute.EdgeAccount: + if id := m.account; id != nil { + return []ent.Value{*id} + } + case ledgersubaccountroute.EdgeSubAccounts: + ids := make([]ent.Value, 0, len(m.sub_accounts)) + for id := range m.sub_accounts { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LedgerSubAccountRouteMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedsub_accounts != nil { + edges = append(edges, ledgersubaccountroute.EdgeSubAccounts) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LedgerSubAccountRouteMutation) RemovedIDs(name string) []ent.Value { + switch name { + case ledgersubaccountroute.EdgeSubAccounts: + ids := make([]ent.Value, 0, len(m.removedsub_accounts)) + for id := range m.removedsub_accounts { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LedgerSubAccountRouteMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedaccount { + edges = append(edges, ledgersubaccountroute.EdgeAccount) + } + if m.clearedsub_accounts { + edges = append(edges, ledgersubaccountroute.EdgeSubAccounts) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LedgerSubAccountRouteMutation) EdgeCleared(name string) bool { + switch name { + case ledgersubaccountroute.EdgeAccount: + return m.clearedaccount + case ledgersubaccountroute.EdgeSubAccounts: + return m.clearedsub_accounts + } + 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 *LedgerSubAccountRouteMutation) ClearEdge(name string) error { + switch name { + case ledgersubaccountroute.EdgeAccount: + m.ClearAccount() + return nil + } + return fmt.Errorf("unknown LedgerSubAccountRoute 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 *LedgerSubAccountRouteMutation) ResetEdge(name string) error { + switch name { + case ledgersubaccountroute.EdgeAccount: + m.ResetAccount() + return nil + case ledgersubaccountroute.EdgeSubAccounts: + m.ResetSubAccounts() + return nil + } + return fmt.Errorf("unknown LedgerSubAccountRoute edge %s", name) +} + +// LedgerTransactionMutation represents an operation that mutates the LedgerTransaction nodes in the graph. +type LedgerTransactionMutation struct { + config + op Op + typ string + id *string + namespace *string + annotations *models.Annotations + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + booked_at *time.Time + clearedFields map[string]struct{} + group *string + clearedgroup bool + entries map[string]struct{} + removedentries map[string]struct{} + clearedentries bool + source_breakage_records map[string]struct{} + removedsource_breakage_records map[string]struct{} + clearedsource_breakage_records bool + breakage_records map[string]struct{} + removedbreakage_records map[string]struct{} + clearedbreakage_records bool + done bool + oldValue func(context.Context) (*LedgerTransaction, error) + predicates []predicate.LedgerTransaction +} + +var _ ent.Mutation = (*LedgerTransactionMutation)(nil) + +// ledgertransactionOption allows management of the mutation configuration using functional options. +type ledgertransactionOption func(*LedgerTransactionMutation) + +// newLedgerTransactionMutation creates new mutation for the LedgerTransaction entity. +func newLedgerTransactionMutation(c config, op Op, opts ...ledgertransactionOption) *LedgerTransactionMutation { + m := &LedgerTransactionMutation{ + config: c, + op: op, + typ: TypeLedgerTransaction, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLedgerTransactionID sets the ID field of the mutation. +func withLedgerTransactionID(id string) ledgertransactionOption { + return func(m *LedgerTransactionMutation) { + var ( + err error + once sync.Once + value *LedgerTransaction + ) + m.oldValue = func(ctx context.Context) (*LedgerTransaction, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LedgerTransaction.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLedgerTransaction sets the old LedgerTransaction of the mutation. +func withLedgerTransaction(node *LedgerTransaction) ledgertransactionOption { + return func(m *LedgerTransactionMutation) { + m.oldValue = func(context.Context) (*LedgerTransaction, 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 LedgerTransactionMutation) 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 LedgerTransactionMutation) 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 LedgerTransaction entities. +func (m *LedgerTransactionMutation) 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 *LedgerTransactionMutation) 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 *LedgerTransactionMutation) 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().LedgerTransaction.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 *LedgerTransactionMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *LedgerTransactionMutation) 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 LedgerTransaction entity. +// If the LedgerTransaction 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 *LedgerTransactionMutation) 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 *LedgerTransactionMutation) ResetNamespace() { + m.namespace = nil +} + +// SetAnnotations sets the "annotations" field. +func (m *LedgerTransactionMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *LedgerTransactionMutation) 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 LedgerTransaction entity. +// If the LedgerTransaction 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 *LedgerTransactionMutation) 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 *LedgerTransactionMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[ledgertransaction.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *LedgerTransactionMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[ledgertransaction.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *LedgerTransactionMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, ledgertransaction.FieldAnnotations) +} + +// SetCreatedAt sets the "created_at" field. +func (m *LedgerTransactionMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *LedgerTransactionMutation) 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 LedgerTransaction entity. +// If the LedgerTransaction 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 *LedgerTransactionMutation) 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 *LedgerTransactionMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *LedgerTransactionMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *LedgerTransactionMutation) 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 LedgerTransaction entity. +// If the LedgerTransaction 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 *LedgerTransactionMutation) 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 *LedgerTransactionMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *LedgerTransactionMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *LedgerTransactionMutation) 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 LedgerTransaction entity. +// If the LedgerTransaction 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 *LedgerTransactionMutation) 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 *LedgerTransactionMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[ledgertransaction.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *LedgerTransactionMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[ledgertransaction.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *LedgerTransactionMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, ledgertransaction.FieldDeletedAt) +} + +// SetGroupID sets the "group_id" field. +func (m *LedgerTransactionMutation) SetGroupID(s string) { + m.group = &s +} + +// GroupID returns the value of the "group_id" field in the mutation. +func (m *LedgerTransactionMutation) GroupID() (r string, exists bool) { + v := m.group + if v == nil { + return + } + return *v, true +} + +// OldGroupID returns the old "group_id" field's value of the LedgerTransaction entity. +// If the LedgerTransaction 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 *LedgerTransactionMutation) OldGroupID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldGroupID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldGroupID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldGroupID: %w", err) + } + return oldValue.GroupID, nil +} + +// ResetGroupID resets all changes to the "group_id" field. +func (m *LedgerTransactionMutation) ResetGroupID() { + m.group = nil +} + +// SetBookedAt sets the "booked_at" field. +func (m *LedgerTransactionMutation) SetBookedAt(t time.Time) { + m.booked_at = &t +} + +// BookedAt returns the value of the "booked_at" field in the mutation. +func (m *LedgerTransactionMutation) BookedAt() (r time.Time, exists bool) { + v := m.booked_at + if v == nil { + return + } + return *v, true +} + +// OldBookedAt returns the old "booked_at" field's value of the LedgerTransaction entity. +// If the LedgerTransaction 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 *LedgerTransactionMutation) OldBookedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBookedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBookedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBookedAt: %w", err) + } + return oldValue.BookedAt, nil +} + +// ResetBookedAt resets all changes to the "booked_at" field. +func (m *LedgerTransactionMutation) ResetBookedAt() { + m.booked_at = nil +} + +// ClearGroup clears the "group" edge to the LedgerTransactionGroup entity. +func (m *LedgerTransactionMutation) ClearGroup() { + m.clearedgroup = true + m.clearedFields[ledgertransaction.FieldGroupID] = struct{}{} +} + +// GroupCleared reports if the "group" edge to the LedgerTransactionGroup entity was cleared. +func (m *LedgerTransactionMutation) GroupCleared() bool { + return m.clearedgroup +} + +// GroupIDs returns the "group" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// GroupID instead. It exists only for internal usage by the builders. +func (m *LedgerTransactionMutation) GroupIDs() (ids []string) { + if id := m.group; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetGroup resets all changes to the "group" edge. +func (m *LedgerTransactionMutation) ResetGroup() { + m.group = nil + m.clearedgroup = false +} + +// AddEntryIDs adds the "entries" edge to the LedgerEntry entity by ids. +func (m *LedgerTransactionMutation) AddEntryIDs(ids ...string) { + if m.entries == nil { + m.entries = make(map[string]struct{}) + } + for i := range ids { + m.entries[ids[i]] = struct{}{} + } +} + +// ClearEntries clears the "entries" edge to the LedgerEntry entity. +func (m *LedgerTransactionMutation) ClearEntries() { + m.clearedentries = true +} + +// EntriesCleared reports if the "entries" edge to the LedgerEntry entity was cleared. +func (m *LedgerTransactionMutation) EntriesCleared() bool { + return m.clearedentries +} + +// RemoveEntryIDs removes the "entries" edge to the LedgerEntry entity by IDs. +func (m *LedgerTransactionMutation) RemoveEntryIDs(ids ...string) { + if m.removedentries == nil { + m.removedentries = make(map[string]struct{}) + } + for i := range ids { + delete(m.entries, ids[i]) + m.removedentries[ids[i]] = struct{}{} + } +} + +// RemovedEntries returns the removed IDs of the "entries" edge to the LedgerEntry entity. +func (m *LedgerTransactionMutation) RemovedEntriesIDs() (ids []string) { + for id := range m.removedentries { + ids = append(ids, id) + } + return +} + +// EntriesIDs returns the "entries" edge IDs in the mutation. +func (m *LedgerTransactionMutation) EntriesIDs() (ids []string) { + for id := range m.entries { + ids = append(ids, id) + } + return +} + +// ResetEntries resets all changes to the "entries" edge. +func (m *LedgerTransactionMutation) ResetEntries() { + m.entries = nil + m.clearedentries = false + m.removedentries = nil +} + +// AddSourceBreakageRecordIDs adds the "source_breakage_records" edge to the LedgerBreakageRecord entity by ids. +func (m *LedgerTransactionMutation) AddSourceBreakageRecordIDs(ids ...string) { + if m.source_breakage_records == nil { + m.source_breakage_records = make(map[string]struct{}) + } + for i := range ids { + m.source_breakage_records[ids[i]] = struct{}{} + } +} + +// ClearSourceBreakageRecords clears the "source_breakage_records" edge to the LedgerBreakageRecord entity. +func (m *LedgerTransactionMutation) ClearSourceBreakageRecords() { + m.clearedsource_breakage_records = true +} + +// SourceBreakageRecordsCleared reports if the "source_breakage_records" edge to the LedgerBreakageRecord entity was cleared. +func (m *LedgerTransactionMutation) SourceBreakageRecordsCleared() bool { + return m.clearedsource_breakage_records +} + +// RemoveSourceBreakageRecordIDs removes the "source_breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (m *LedgerTransactionMutation) RemoveSourceBreakageRecordIDs(ids ...string) { + if m.removedsource_breakage_records == nil { + m.removedsource_breakage_records = make(map[string]struct{}) + } + for i := range ids { + delete(m.source_breakage_records, ids[i]) + m.removedsource_breakage_records[ids[i]] = struct{}{} + } +} + +// RemovedSourceBreakageRecords returns the removed IDs of the "source_breakage_records" edge to the LedgerBreakageRecord entity. +func (m *LedgerTransactionMutation) RemovedSourceBreakageRecordsIDs() (ids []string) { + for id := range m.removedsource_breakage_records { + ids = append(ids, id) + } + return +} + +// SourceBreakageRecordsIDs returns the "source_breakage_records" edge IDs in the mutation. +func (m *LedgerTransactionMutation) SourceBreakageRecordsIDs() (ids []string) { + for id := range m.source_breakage_records { + ids = append(ids, id) + } + return +} + +// ResetSourceBreakageRecords resets all changes to the "source_breakage_records" edge. +func (m *LedgerTransactionMutation) ResetSourceBreakageRecords() { + m.source_breakage_records = nil + m.clearedsource_breakage_records = false + m.removedsource_breakage_records = nil +} + +// AddBreakageRecordIDs adds the "breakage_records" edge to the LedgerBreakageRecord entity by ids. +func (m *LedgerTransactionMutation) AddBreakageRecordIDs(ids ...string) { + if m.breakage_records == nil { + m.breakage_records = make(map[string]struct{}) + } + for i := range ids { + m.breakage_records[ids[i]] = struct{}{} + } +} + +// ClearBreakageRecords clears the "breakage_records" edge to the LedgerBreakageRecord entity. +func (m *LedgerTransactionMutation) ClearBreakageRecords() { + m.clearedbreakage_records = true +} + +// BreakageRecordsCleared reports if the "breakage_records" edge to the LedgerBreakageRecord entity was cleared. +func (m *LedgerTransactionMutation) BreakageRecordsCleared() bool { + return m.clearedbreakage_records +} + +// RemoveBreakageRecordIDs removes the "breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (m *LedgerTransactionMutation) RemoveBreakageRecordIDs(ids ...string) { + if m.removedbreakage_records == nil { + m.removedbreakage_records = make(map[string]struct{}) + } + for i := range ids { + delete(m.breakage_records, ids[i]) + m.removedbreakage_records[ids[i]] = struct{}{} + } +} + +// RemovedBreakageRecords returns the removed IDs of the "breakage_records" edge to the LedgerBreakageRecord entity. +func (m *LedgerTransactionMutation) RemovedBreakageRecordsIDs() (ids []string) { + for id := range m.removedbreakage_records { + ids = append(ids, id) + } + return +} + +// BreakageRecordsIDs returns the "breakage_records" edge IDs in the mutation. +func (m *LedgerTransactionMutation) BreakageRecordsIDs() (ids []string) { + for id := range m.breakage_records { + ids = append(ids, id) + } + return +} + +// ResetBreakageRecords resets all changes to the "breakage_records" edge. +func (m *LedgerTransactionMutation) ResetBreakageRecords() { + m.breakage_records = nil + m.clearedbreakage_records = false + m.removedbreakage_records = nil +} + +// Where appends a list predicates to the LedgerTransactionMutation builder. +func (m *LedgerTransactionMutation) Where(ps ...predicate.LedgerTransaction) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the LedgerTransactionMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *LedgerTransactionMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.LedgerTransaction, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *LedgerTransactionMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *LedgerTransactionMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (LedgerTransaction). +func (m *LedgerTransactionMutation) 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 *LedgerTransactionMutation) Fields() []string { + fields := make([]string, 0, 7) + if m.namespace != nil { + fields = append(fields, ledgertransaction.FieldNamespace) + } + if m.annotations != nil { + fields = append(fields, ledgertransaction.FieldAnnotations) + } + if m.created_at != nil { + fields = append(fields, ledgertransaction.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, ledgertransaction.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, ledgertransaction.FieldDeletedAt) + } + if m.group != nil { + fields = append(fields, ledgertransaction.FieldGroupID) + } + if m.booked_at != nil { + fields = append(fields, ledgertransaction.FieldBookedAt) + } + 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 *LedgerTransactionMutation) Field(name string) (ent.Value, bool) { + switch name { + case ledgertransaction.FieldNamespace: + return m.Namespace() + case ledgertransaction.FieldAnnotations: + return m.Annotations() + case ledgertransaction.FieldCreatedAt: + return m.CreatedAt() + case ledgertransaction.FieldUpdatedAt: + return m.UpdatedAt() + case ledgertransaction.FieldDeletedAt: + return m.DeletedAt() + case ledgertransaction.FieldGroupID: + return m.GroupID() + case ledgertransaction.FieldBookedAt: + return m.BookedAt() + } + 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 *LedgerTransactionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case ledgertransaction.FieldNamespace: + return m.OldNamespace(ctx) + case ledgertransaction.FieldAnnotations: + return m.OldAnnotations(ctx) + case ledgertransaction.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case ledgertransaction.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case ledgertransaction.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case ledgertransaction.FieldGroupID: + return m.OldGroupID(ctx) + case ledgertransaction.FieldBookedAt: + return m.OldBookedAt(ctx) + } + return nil, fmt.Errorf("unknown LedgerTransaction 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 *LedgerTransactionMutation) SetField(name string, value ent.Value) error { + switch name { + case ledgertransaction.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case ledgertransaction.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 ledgertransaction.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 ledgertransaction.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 ledgertransaction.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 ledgertransaction.FieldGroupID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetGroupID(v) + return nil + case ledgertransaction.FieldBookedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBookedAt(v) + return nil + } + return fmt.Errorf("unknown LedgerTransaction field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LedgerTransactionMutation) 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 *LedgerTransactionMutation) 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 *LedgerTransactionMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown LedgerTransaction numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LedgerTransactionMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(ledgertransaction.FieldAnnotations) { + fields = append(fields, ledgertransaction.FieldAnnotations) + } + if m.FieldCleared(ledgertransaction.FieldDeletedAt) { + fields = append(fields, ledgertransaction.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LedgerTransactionMutation) 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 *LedgerTransactionMutation) ClearField(name string) error { + switch name { + case ledgertransaction.FieldAnnotations: + m.ClearAnnotations() + return nil + case ledgertransaction.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown LedgerTransaction 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 *LedgerTransactionMutation) ResetField(name string) error { + switch name { + case ledgertransaction.FieldNamespace: + m.ResetNamespace() + return nil + case ledgertransaction.FieldAnnotations: + m.ResetAnnotations() + return nil + case ledgertransaction.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case ledgertransaction.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case ledgertransaction.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case ledgertransaction.FieldGroupID: + m.ResetGroupID() + return nil + case ledgertransaction.FieldBookedAt: + m.ResetBookedAt() + return nil + } + return fmt.Errorf("unknown LedgerTransaction field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LedgerTransactionMutation) AddedEdges() []string { + edges := make([]string, 0, 4) + if m.group != nil { + edges = append(edges, ledgertransaction.EdgeGroup) + } + if m.entries != nil { + edges = append(edges, ledgertransaction.EdgeEntries) + } + if m.source_breakage_records != nil { + edges = append(edges, ledgertransaction.EdgeSourceBreakageRecords) + } + if m.breakage_records != nil { + edges = append(edges, ledgertransaction.EdgeBreakageRecords) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LedgerTransactionMutation) AddedIDs(name string) []ent.Value { + switch name { + case ledgertransaction.EdgeGroup: + if id := m.group; id != nil { + return []ent.Value{*id} + } + case ledgertransaction.EdgeEntries: + ids := make([]ent.Value, 0, len(m.entries)) + for id := range m.entries { + ids = append(ids, id) + } + return ids + case ledgertransaction.EdgeSourceBreakageRecords: + ids := make([]ent.Value, 0, len(m.source_breakage_records)) + for id := range m.source_breakage_records { + ids = append(ids, id) + } + return ids + case ledgertransaction.EdgeBreakageRecords: + ids := make([]ent.Value, 0, len(m.breakage_records)) + for id := range m.breakage_records { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LedgerTransactionMutation) RemovedEdges() []string { + edges := make([]string, 0, 4) + if m.removedentries != nil { + edges = append(edges, ledgertransaction.EdgeEntries) + } + if m.removedsource_breakage_records != nil { + edges = append(edges, ledgertransaction.EdgeSourceBreakageRecords) + } + if m.removedbreakage_records != nil { + edges = append(edges, ledgertransaction.EdgeBreakageRecords) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LedgerTransactionMutation) RemovedIDs(name string) []ent.Value { + switch name { + case ledgertransaction.EdgeEntries: + ids := make([]ent.Value, 0, len(m.removedentries)) + for id := range m.removedentries { + ids = append(ids, id) + } + return ids + case ledgertransaction.EdgeSourceBreakageRecords: + ids := make([]ent.Value, 0, len(m.removedsource_breakage_records)) + for id := range m.removedsource_breakage_records { + ids = append(ids, id) + } + return ids + case ledgertransaction.EdgeBreakageRecords: + ids := make([]ent.Value, 0, len(m.removedbreakage_records)) + for id := range m.removedbreakage_records { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LedgerTransactionMutation) ClearedEdges() []string { + edges := make([]string, 0, 4) + if m.clearedgroup { + edges = append(edges, ledgertransaction.EdgeGroup) + } + if m.clearedentries { + edges = append(edges, ledgertransaction.EdgeEntries) + } + if m.clearedsource_breakage_records { + edges = append(edges, ledgertransaction.EdgeSourceBreakageRecords) + } + if m.clearedbreakage_records { + edges = append(edges, ledgertransaction.EdgeBreakageRecords) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LedgerTransactionMutation) EdgeCleared(name string) bool { + switch name { + case ledgertransaction.EdgeGroup: + return m.clearedgroup + case ledgertransaction.EdgeEntries: + return m.clearedentries + case ledgertransaction.EdgeSourceBreakageRecords: + return m.clearedsource_breakage_records + case ledgertransaction.EdgeBreakageRecords: + return m.clearedbreakage_records + } + 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 *LedgerTransactionMutation) ClearEdge(name string) error { + switch name { + case ledgertransaction.EdgeGroup: + m.ClearGroup() + return nil + } + return fmt.Errorf("unknown LedgerTransaction 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 *LedgerTransactionMutation) ResetEdge(name string) error { + switch name { + case ledgertransaction.EdgeGroup: + m.ResetGroup() + return nil + case ledgertransaction.EdgeEntries: + m.ResetEntries() + return nil + case ledgertransaction.EdgeSourceBreakageRecords: + m.ResetSourceBreakageRecords() + return nil + case ledgertransaction.EdgeBreakageRecords: + m.ResetBreakageRecords() + return nil + } + return fmt.Errorf("unknown LedgerTransaction edge %s", name) +} + +// LedgerTransactionGroupMutation represents an operation that mutates the LedgerTransactionGroup nodes in the graph. +type LedgerTransactionGroupMutation struct { + config + op Op + typ string + id *string + namespace *string + annotations *models.Annotations + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + clearedFields map[string]struct{} + transactions map[string]struct{} + removedtransactions map[string]struct{} + clearedtransactions bool + source_breakage_records map[string]struct{} + removedsource_breakage_records map[string]struct{} + clearedsource_breakage_records bool + breakage_records map[string]struct{} + removedbreakage_records map[string]struct{} + clearedbreakage_records bool + done bool + oldValue func(context.Context) (*LedgerTransactionGroup, error) + predicates []predicate.LedgerTransactionGroup +} + +var _ ent.Mutation = (*LedgerTransactionGroupMutation)(nil) + +// ledgertransactiongroupOption allows management of the mutation configuration using functional options. +type ledgertransactiongroupOption func(*LedgerTransactionGroupMutation) + +// newLedgerTransactionGroupMutation creates new mutation for the LedgerTransactionGroup entity. +func newLedgerTransactionGroupMutation(c config, op Op, opts ...ledgertransactiongroupOption) *LedgerTransactionGroupMutation { + m := &LedgerTransactionGroupMutation{ + config: c, + op: op, + typ: TypeLedgerTransactionGroup, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLedgerTransactionGroupID sets the ID field of the mutation. +func withLedgerTransactionGroupID(id string) ledgertransactiongroupOption { + return func(m *LedgerTransactionGroupMutation) { + var ( + err error + once sync.Once + value *LedgerTransactionGroup + ) + m.oldValue = func(ctx context.Context) (*LedgerTransactionGroup, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LedgerTransactionGroup.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLedgerTransactionGroup sets the old LedgerTransactionGroup of the mutation. +func withLedgerTransactionGroup(node *LedgerTransactionGroup) ledgertransactiongroupOption { + return func(m *LedgerTransactionGroupMutation) { + m.oldValue = func(context.Context) (*LedgerTransactionGroup, 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 LedgerTransactionGroupMutation) 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 LedgerTransactionGroupMutation) 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 LedgerTransactionGroup entities. +func (m *LedgerTransactionGroupMutation) 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 *LedgerTransactionGroupMutation) 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 *LedgerTransactionGroupMutation) 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().LedgerTransactionGroup.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 *LedgerTransactionGroupMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *LedgerTransactionGroupMutation) 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 LedgerTransactionGroup entity. +// If the LedgerTransactionGroup 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 *LedgerTransactionGroupMutation) 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 *LedgerTransactionGroupMutation) ResetNamespace() { + m.namespace = nil +} + +// SetAnnotations sets the "annotations" field. +func (m *LedgerTransactionGroupMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *LedgerTransactionGroupMutation) 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 LedgerTransactionGroup entity. +// If the LedgerTransactionGroup 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 *LedgerTransactionGroupMutation) 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 *LedgerTransactionGroupMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[ledgertransactiongroup.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *LedgerTransactionGroupMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[ledgertransactiongroup.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *LedgerTransactionGroupMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, ledgertransactiongroup.FieldAnnotations) +} + +// SetCreatedAt sets the "created_at" field. +func (m *LedgerTransactionGroupMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *LedgerTransactionGroupMutation) 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 LedgerTransactionGroup entity. +// If the LedgerTransactionGroup 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 *LedgerTransactionGroupMutation) 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 *LedgerTransactionGroupMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *LedgerTransactionGroupMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *LedgerTransactionGroupMutation) 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 LedgerTransactionGroup entity. +// If the LedgerTransactionGroup 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 *LedgerTransactionGroupMutation) 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 *LedgerTransactionGroupMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *LedgerTransactionGroupMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *LedgerTransactionGroupMutation) 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 LedgerTransactionGroup entity. +// If the LedgerTransactionGroup 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 *LedgerTransactionGroupMutation) 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 *LedgerTransactionGroupMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[ledgertransactiongroup.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *LedgerTransactionGroupMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[ledgertransactiongroup.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *LedgerTransactionGroupMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, ledgertransactiongroup.FieldDeletedAt) +} + +// AddTransactionIDs adds the "transactions" edge to the LedgerTransaction entity by ids. +func (m *LedgerTransactionGroupMutation) AddTransactionIDs(ids ...string) { + if m.transactions == nil { + m.transactions = make(map[string]struct{}) + } + for i := range ids { + m.transactions[ids[i]] = struct{}{} + } +} + +// ClearTransactions clears the "transactions" edge to the LedgerTransaction entity. +func (m *LedgerTransactionGroupMutation) ClearTransactions() { + m.clearedtransactions = true +} + +// TransactionsCleared reports if the "transactions" edge to the LedgerTransaction entity was cleared. +func (m *LedgerTransactionGroupMutation) TransactionsCleared() bool { + return m.clearedtransactions +} + +// RemoveTransactionIDs removes the "transactions" edge to the LedgerTransaction entity by IDs. +func (m *LedgerTransactionGroupMutation) RemoveTransactionIDs(ids ...string) { + if m.removedtransactions == nil { + m.removedtransactions = make(map[string]struct{}) + } + for i := range ids { + delete(m.transactions, ids[i]) + m.removedtransactions[ids[i]] = struct{}{} + } +} + +// RemovedTransactions returns the removed IDs of the "transactions" edge to the LedgerTransaction entity. +func (m *LedgerTransactionGroupMutation) RemovedTransactionsIDs() (ids []string) { + for id := range m.removedtransactions { + ids = append(ids, id) + } + return +} + +// TransactionsIDs returns the "transactions" edge IDs in the mutation. +func (m *LedgerTransactionGroupMutation) TransactionsIDs() (ids []string) { + for id := range m.transactions { + ids = append(ids, id) + } + return +} + +// ResetTransactions resets all changes to the "transactions" edge. +func (m *LedgerTransactionGroupMutation) ResetTransactions() { + m.transactions = nil + m.clearedtransactions = false + m.removedtransactions = nil +} + +// AddSourceBreakageRecordIDs adds the "source_breakage_records" edge to the LedgerBreakageRecord entity by ids. +func (m *LedgerTransactionGroupMutation) AddSourceBreakageRecordIDs(ids ...string) { + if m.source_breakage_records == nil { + m.source_breakage_records = make(map[string]struct{}) + } + for i := range ids { + m.source_breakage_records[ids[i]] = struct{}{} + } +} + +// ClearSourceBreakageRecords clears the "source_breakage_records" edge to the LedgerBreakageRecord entity. +func (m *LedgerTransactionGroupMutation) ClearSourceBreakageRecords() { + m.clearedsource_breakage_records = true +} + +// SourceBreakageRecordsCleared reports if the "source_breakage_records" edge to the LedgerBreakageRecord entity was cleared. +func (m *LedgerTransactionGroupMutation) SourceBreakageRecordsCleared() bool { + return m.clearedsource_breakage_records +} + +// RemoveSourceBreakageRecordIDs removes the "source_breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (m *LedgerTransactionGroupMutation) RemoveSourceBreakageRecordIDs(ids ...string) { + if m.removedsource_breakage_records == nil { + m.removedsource_breakage_records = make(map[string]struct{}) + } + for i := range ids { + delete(m.source_breakage_records, ids[i]) + m.removedsource_breakage_records[ids[i]] = struct{}{} + } +} + +// RemovedSourceBreakageRecords returns the removed IDs of the "source_breakage_records" edge to the LedgerBreakageRecord entity. +func (m *LedgerTransactionGroupMutation) RemovedSourceBreakageRecordsIDs() (ids []string) { + for id := range m.removedsource_breakage_records { + ids = append(ids, id) + } + return +} + +// SourceBreakageRecordsIDs returns the "source_breakage_records" edge IDs in the mutation. +func (m *LedgerTransactionGroupMutation) SourceBreakageRecordsIDs() (ids []string) { + for id := range m.source_breakage_records { + ids = append(ids, id) + } + return +} + +// ResetSourceBreakageRecords resets all changes to the "source_breakage_records" edge. +func (m *LedgerTransactionGroupMutation) ResetSourceBreakageRecords() { + m.source_breakage_records = nil + m.clearedsource_breakage_records = false + m.removedsource_breakage_records = nil +} + +// AddBreakageRecordIDs adds the "breakage_records" edge to the LedgerBreakageRecord entity by ids. +func (m *LedgerTransactionGroupMutation) AddBreakageRecordIDs(ids ...string) { + if m.breakage_records == nil { + m.breakage_records = make(map[string]struct{}) + } + for i := range ids { + m.breakage_records[ids[i]] = struct{}{} + } +} + +// ClearBreakageRecords clears the "breakage_records" edge to the LedgerBreakageRecord entity. +func (m *LedgerTransactionGroupMutation) ClearBreakageRecords() { + m.clearedbreakage_records = true +} + +// BreakageRecordsCleared reports if the "breakage_records" edge to the LedgerBreakageRecord entity was cleared. +func (m *LedgerTransactionGroupMutation) BreakageRecordsCleared() bool { + return m.clearedbreakage_records +} + +// RemoveBreakageRecordIDs removes the "breakage_records" edge to the LedgerBreakageRecord entity by IDs. +func (m *LedgerTransactionGroupMutation) RemoveBreakageRecordIDs(ids ...string) { + if m.removedbreakage_records == nil { + m.removedbreakage_records = make(map[string]struct{}) + } + for i := range ids { + delete(m.breakage_records, ids[i]) + m.removedbreakage_records[ids[i]] = struct{}{} + } +} + +// RemovedBreakageRecords returns the removed IDs of the "breakage_records" edge to the LedgerBreakageRecord entity. +func (m *LedgerTransactionGroupMutation) RemovedBreakageRecordsIDs() (ids []string) { + for id := range m.removedbreakage_records { + ids = append(ids, id) + } + return +} + +// BreakageRecordsIDs returns the "breakage_records" edge IDs in the mutation. +func (m *LedgerTransactionGroupMutation) BreakageRecordsIDs() (ids []string) { + for id := range m.breakage_records { + ids = append(ids, id) + } + return +} + +// ResetBreakageRecords resets all changes to the "breakage_records" edge. +func (m *LedgerTransactionGroupMutation) ResetBreakageRecords() { + m.breakage_records = nil + m.clearedbreakage_records = false + m.removedbreakage_records = nil +} + +// Where appends a list predicates to the LedgerTransactionGroupMutation builder. +func (m *LedgerTransactionGroupMutation) Where(ps ...predicate.LedgerTransactionGroup) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the LedgerTransactionGroupMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *LedgerTransactionGroupMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.LedgerTransactionGroup, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *LedgerTransactionGroupMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *LedgerTransactionGroupMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (LedgerTransactionGroup). +func (m *LedgerTransactionGroupMutation) 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 *LedgerTransactionGroupMutation) Fields() []string { + fields := make([]string, 0, 5) + if m.namespace != nil { + fields = append(fields, ledgertransactiongroup.FieldNamespace) + } + if m.annotations != nil { + fields = append(fields, ledgertransactiongroup.FieldAnnotations) + } + if m.created_at != nil { + fields = append(fields, ledgertransactiongroup.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, ledgertransactiongroup.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, ledgertransactiongroup.FieldDeletedAt) + } + 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 *LedgerTransactionGroupMutation) Field(name string) (ent.Value, bool) { + switch name { + case ledgertransactiongroup.FieldNamespace: + return m.Namespace() + case ledgertransactiongroup.FieldAnnotations: + return m.Annotations() + case ledgertransactiongroup.FieldCreatedAt: + return m.CreatedAt() + case ledgertransactiongroup.FieldUpdatedAt: + return m.UpdatedAt() + case ledgertransactiongroup.FieldDeletedAt: + return m.DeletedAt() + } + 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 *LedgerTransactionGroupMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case ledgertransactiongroup.FieldNamespace: + return m.OldNamespace(ctx) + case ledgertransactiongroup.FieldAnnotations: + return m.OldAnnotations(ctx) + case ledgertransactiongroup.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case ledgertransactiongroup.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case ledgertransactiongroup.FieldDeletedAt: + return m.OldDeletedAt(ctx) + } + return nil, fmt.Errorf("unknown LedgerTransactionGroup 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 *LedgerTransactionGroupMutation) SetField(name string, value ent.Value) error { + switch name { + case ledgertransactiongroup.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case ledgertransactiongroup.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 ledgertransactiongroup.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 ledgertransactiongroup.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 ledgertransactiongroup.FieldDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeletedAt(v) + return nil + } + return fmt.Errorf("unknown LedgerTransactionGroup field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LedgerTransactionGroupMutation) 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 *LedgerTransactionGroupMutation) 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 *LedgerTransactionGroupMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown LedgerTransactionGroup numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LedgerTransactionGroupMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(ledgertransactiongroup.FieldAnnotations) { + fields = append(fields, ledgertransactiongroup.FieldAnnotations) + } + if m.FieldCleared(ledgertransactiongroup.FieldDeletedAt) { + fields = append(fields, ledgertransactiongroup.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LedgerTransactionGroupMutation) 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 *LedgerTransactionGroupMutation) ClearField(name string) error { + switch name { + case ledgertransactiongroup.FieldAnnotations: + m.ClearAnnotations() + return nil + case ledgertransactiongroup.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown LedgerTransactionGroup 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 *LedgerTransactionGroupMutation) ResetField(name string) error { + switch name { + case ledgertransactiongroup.FieldNamespace: + m.ResetNamespace() + return nil + case ledgertransactiongroup.FieldAnnotations: + m.ResetAnnotations() + return nil + case ledgertransactiongroup.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case ledgertransactiongroup.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case ledgertransactiongroup.FieldDeletedAt: + m.ResetDeletedAt() + return nil + } + return fmt.Errorf("unknown LedgerTransactionGroup field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LedgerTransactionGroupMutation) AddedEdges() []string { + edges := make([]string, 0, 3) + if m.transactions != nil { + edges = append(edges, ledgertransactiongroup.EdgeTransactions) + } + if m.source_breakage_records != nil { + edges = append(edges, ledgertransactiongroup.EdgeSourceBreakageRecords) + } + if m.breakage_records != nil { + edges = append(edges, ledgertransactiongroup.EdgeBreakageRecords) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LedgerTransactionGroupMutation) AddedIDs(name string) []ent.Value { + switch name { + case ledgertransactiongroup.EdgeTransactions: + ids := make([]ent.Value, 0, len(m.transactions)) + for id := range m.transactions { + ids = append(ids, id) + } + return ids + case ledgertransactiongroup.EdgeSourceBreakageRecords: + ids := make([]ent.Value, 0, len(m.source_breakage_records)) + for id := range m.source_breakage_records { + ids = append(ids, id) + } + return ids + case ledgertransactiongroup.EdgeBreakageRecords: + ids := make([]ent.Value, 0, len(m.breakage_records)) + for id := range m.breakage_records { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LedgerTransactionGroupMutation) RemovedEdges() []string { + edges := make([]string, 0, 3) + if m.removedtransactions != nil { + edges = append(edges, ledgertransactiongroup.EdgeTransactions) + } + if m.removedsource_breakage_records != nil { + edges = append(edges, ledgertransactiongroup.EdgeSourceBreakageRecords) + } + if m.removedbreakage_records != nil { + edges = append(edges, ledgertransactiongroup.EdgeBreakageRecords) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LedgerTransactionGroupMutation) RemovedIDs(name string) []ent.Value { + switch name { + case ledgertransactiongroup.EdgeTransactions: + ids := make([]ent.Value, 0, len(m.removedtransactions)) + for id := range m.removedtransactions { + ids = append(ids, id) + } + return ids + case ledgertransactiongroup.EdgeSourceBreakageRecords: + ids := make([]ent.Value, 0, len(m.removedsource_breakage_records)) + for id := range m.removedsource_breakage_records { + ids = append(ids, id) + } + return ids + case ledgertransactiongroup.EdgeBreakageRecords: + ids := make([]ent.Value, 0, len(m.removedbreakage_records)) + for id := range m.removedbreakage_records { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LedgerTransactionGroupMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) + if m.clearedtransactions { + edges = append(edges, ledgertransactiongroup.EdgeTransactions) + } + if m.clearedsource_breakage_records { + edges = append(edges, ledgertransactiongroup.EdgeSourceBreakageRecords) + } + if m.clearedbreakage_records { + edges = append(edges, ledgertransactiongroup.EdgeBreakageRecords) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LedgerTransactionGroupMutation) EdgeCleared(name string) bool { + switch name { + case ledgertransactiongroup.EdgeTransactions: + return m.clearedtransactions + case ledgertransactiongroup.EdgeSourceBreakageRecords: + return m.clearedsource_breakage_records + case ledgertransactiongroup.EdgeBreakageRecords: + return m.clearedbreakage_records + } + 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 *LedgerTransactionGroupMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown LedgerTransactionGroup 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 *LedgerTransactionGroupMutation) ResetEdge(name string) error { + switch name { + case ledgertransactiongroup.EdgeTransactions: + m.ResetTransactions() + return nil + case ledgertransactiongroup.EdgeSourceBreakageRecords: + m.ResetSourceBreakageRecords() + return nil + case ledgertransactiongroup.EdgeBreakageRecords: + m.ResetBreakageRecords() + return nil + } + return fmt.Errorf("unknown LedgerTransactionGroup edge %s", name) +} + +// MeterMutation represents an operation that mutates the Meter nodes in the graph. +type MeterMutation struct { + config + op Op + typ string + id *string + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + name *string + description *string + key *string + annotations *models.Annotations + event_type *string + value_property *string + group_by *map[string]string + aggregation *meter.MeterAggregation + event_from *time.Time + clearedFields map[string]struct{} + feature map[string]struct{} + removedfeature map[string]struct{} + clearedfeature bool + done bool + oldValue func(context.Context) (*Meter, error) + predicates []predicate.Meter +} + +var _ ent.Mutation = (*MeterMutation)(nil) + +// meterOption allows management of the mutation configuration using functional options. +type meterOption func(*MeterMutation) + +// newMeterMutation creates new mutation for the Meter entity. +func newMeterMutation(c config, op Op, opts ...meterOption) *MeterMutation { + m := &MeterMutation{ + config: c, + op: op, + typ: TypeMeter, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withMeterID sets the ID field of the mutation. +func withMeterID(id string) meterOption { + return func(m *MeterMutation) { + var ( + err error + once sync.Once + value *Meter + ) + m.oldValue = func(ctx context.Context) (*Meter, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Meter.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withMeter sets the old Meter of the mutation. +func withMeter(node *Meter) meterOption { + return func(m *MeterMutation) { + m.oldValue = func(context.Context) (*Meter, 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 MeterMutation) 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 MeterMutation) 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 Meter entities. +func (m *MeterMutation) 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 *MeterMutation) 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 *MeterMutation) 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().Meter.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 *MeterMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *MeterMutation) 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 Meter entity. +// If the Meter 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 *MeterMutation) 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 *MeterMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *MeterMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *MeterMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the Meter entity. +// If the Meter 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 *MeterMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *MeterMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[dbmeter.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *MeterMutation) MetadataCleared() bool { + _, ok := m.clearedFields[dbmeter.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *MeterMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, dbmeter.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *MeterMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *MeterMutation) 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 Meter entity. +// If the Meter 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 *MeterMutation) 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 *MeterMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *MeterMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *MeterMutation) 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 Meter entity. +// If the Meter 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 *MeterMutation) 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 *MeterMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *MeterMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *MeterMutation) 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 Meter entity. +// If the Meter 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 *MeterMutation) 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 *MeterMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[dbmeter.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *MeterMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[dbmeter.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *MeterMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, dbmeter.FieldDeletedAt) +} + +// SetName sets the "name" field. +func (m *MeterMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *MeterMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the Meter entity. +// If the Meter 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 *MeterMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *MeterMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *MeterMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *MeterMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the Meter entity. +// If the Meter 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 *MeterMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *MeterMutation) ClearDescription() { + m.description = nil + m.clearedFields[dbmeter.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *MeterMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[dbmeter.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *MeterMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, dbmeter.FieldDescription) +} + +// SetKey sets the "key" field. +func (m *MeterMutation) SetKey(s string) { + m.key = &s +} + +// Key returns the value of the "key" field in the mutation. +func (m *MeterMutation) Key() (r string, exists bool) { + v := m.key + if v == nil { + return + } + return *v, true +} + +// OldKey returns the old "key" field's value of the Meter entity. +// If the Meter 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 *MeterMutation) OldKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldKey: %w", err) + } + return oldValue.Key, nil +} + +// ResetKey resets all changes to the "key" field. +func (m *MeterMutation) ResetKey() { + m.key = nil +} + +// SetAnnotations sets the "annotations" field. +func (m *MeterMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *MeterMutation) 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 Meter entity. +// If the Meter 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 *MeterMutation) 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 *MeterMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[dbmeter.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *MeterMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[dbmeter.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *MeterMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, dbmeter.FieldAnnotations) +} + +// SetEventType sets the "event_type" field. +func (m *MeterMutation) SetEventType(s string) { + m.event_type = &s +} + +// EventType returns the value of the "event_type" field in the mutation. +func (m *MeterMutation) EventType() (r string, exists bool) { + v := m.event_type + if v == nil { + return + } + return *v, true +} + +// OldEventType returns the old "event_type" field's value of the Meter entity. +// If the Meter 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 *MeterMutation) OldEventType(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEventType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEventType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEventType: %w", err) + } + return oldValue.EventType, nil +} + +// ResetEventType resets all changes to the "event_type" field. +func (m *MeterMutation) ResetEventType() { + m.event_type = nil +} + +// SetValueProperty sets the "value_property" field. +func (m *MeterMutation) SetValueProperty(s string) { + m.value_property = &s +} + +// ValueProperty returns the value of the "value_property" field in the mutation. +func (m *MeterMutation) ValueProperty() (r string, exists bool) { + v := m.value_property + if v == nil { + return + } + return *v, true +} + +// OldValueProperty returns the old "value_property" field's value of the Meter entity. +// If the Meter 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 *MeterMutation) OldValueProperty(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldValueProperty is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldValueProperty requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldValueProperty: %w", err) + } + return oldValue.ValueProperty, nil +} + +// ClearValueProperty clears the value of the "value_property" field. +func (m *MeterMutation) ClearValueProperty() { + m.value_property = nil + m.clearedFields[dbmeter.FieldValueProperty] = struct{}{} +} + +// ValuePropertyCleared returns if the "value_property" field was cleared in this mutation. +func (m *MeterMutation) ValuePropertyCleared() bool { + _, ok := m.clearedFields[dbmeter.FieldValueProperty] + return ok +} + +// ResetValueProperty resets all changes to the "value_property" field. +func (m *MeterMutation) ResetValueProperty() { + m.value_property = nil + delete(m.clearedFields, dbmeter.FieldValueProperty) +} + +// SetGroupBy sets the "group_by" field. +func (m *MeterMutation) SetGroupBy(value map[string]string) { + m.group_by = &value +} + +// GroupBy returns the value of the "group_by" field in the mutation. +func (m *MeterMutation) GroupBy() (r map[string]string, exists bool) { + v := m.group_by + if v == nil { + return + } + return *v, true +} + +// OldGroupBy returns the old "group_by" field's value of the Meter entity. +// If the Meter 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 *MeterMutation) OldGroupBy(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldGroupBy is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldGroupBy requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldGroupBy: %w", err) + } + return oldValue.GroupBy, nil +} + +// ClearGroupBy clears the value of the "group_by" field. +func (m *MeterMutation) ClearGroupBy() { + m.group_by = nil + m.clearedFields[dbmeter.FieldGroupBy] = struct{}{} +} + +// GroupByCleared returns if the "group_by" field was cleared in this mutation. +func (m *MeterMutation) GroupByCleared() bool { + _, ok := m.clearedFields[dbmeter.FieldGroupBy] + return ok +} + +// ResetGroupBy resets all changes to the "group_by" field. +func (m *MeterMutation) ResetGroupBy() { + m.group_by = nil + delete(m.clearedFields, dbmeter.FieldGroupBy) +} + +// SetAggregation sets the "aggregation" field. +func (m *MeterMutation) SetAggregation(ma meter.MeterAggregation) { + m.aggregation = &ma +} + +// Aggregation returns the value of the "aggregation" field in the mutation. +func (m *MeterMutation) Aggregation() (r meter.MeterAggregation, exists bool) { + v := m.aggregation + if v == nil { + return + } + return *v, true +} + +// OldAggregation returns the old "aggregation" field's value of the Meter entity. +// If the Meter 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 *MeterMutation) OldAggregation(ctx context.Context) (v meter.MeterAggregation, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAggregation is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAggregation requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAggregation: %w", err) + } + return oldValue.Aggregation, nil +} + +// ResetAggregation resets all changes to the "aggregation" field. +func (m *MeterMutation) ResetAggregation() { + m.aggregation = nil +} + +// SetEventFrom sets the "event_from" field. +func (m *MeterMutation) SetEventFrom(t time.Time) { + m.event_from = &t +} + +// EventFrom returns the value of the "event_from" field in the mutation. +func (m *MeterMutation) EventFrom() (r time.Time, exists bool) { + v := m.event_from + if v == nil { + return + } + return *v, true +} + +// OldEventFrom returns the old "event_from" field's value of the Meter entity. +// If the Meter 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 *MeterMutation) OldEventFrom(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEventFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEventFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEventFrom: %w", err) + } + return oldValue.EventFrom, nil +} + +// ClearEventFrom clears the value of the "event_from" field. +func (m *MeterMutation) ClearEventFrom() { + m.event_from = nil + m.clearedFields[dbmeter.FieldEventFrom] = struct{}{} +} + +// EventFromCleared returns if the "event_from" field was cleared in this mutation. +func (m *MeterMutation) EventFromCleared() bool { + _, ok := m.clearedFields[dbmeter.FieldEventFrom] + return ok +} + +// ResetEventFrom resets all changes to the "event_from" field. +func (m *MeterMutation) ResetEventFrom() { + m.event_from = nil + delete(m.clearedFields, dbmeter.FieldEventFrom) +} + +// AddFeatureIDs adds the "feature" edge to the Feature entity by ids. +func (m *MeterMutation) AddFeatureIDs(ids ...string) { + if m.feature == nil { + m.feature = make(map[string]struct{}) + } + for i := range ids { + m.feature[ids[i]] = struct{}{} + } +} + +// ClearFeature clears the "feature" edge to the Feature entity. +func (m *MeterMutation) ClearFeature() { + m.clearedfeature = true +} + +// FeatureCleared reports if the "feature" edge to the Feature entity was cleared. +func (m *MeterMutation) FeatureCleared() bool { + return m.clearedfeature +} + +// RemoveFeatureIDs removes the "feature" edge to the Feature entity by IDs. +func (m *MeterMutation) RemoveFeatureIDs(ids ...string) { + if m.removedfeature == nil { + m.removedfeature = make(map[string]struct{}) + } + for i := range ids { + delete(m.feature, ids[i]) + m.removedfeature[ids[i]] = struct{}{} + } +} + +// RemovedFeature returns the removed IDs of the "feature" edge to the Feature entity. +func (m *MeterMutation) RemovedFeatureIDs() (ids []string) { + for id := range m.removedfeature { + ids = append(ids, id) + } + return +} + +// FeatureIDs returns the "feature" edge IDs in the mutation. +func (m *MeterMutation) FeatureIDs() (ids []string) { + for id := range m.feature { + ids = append(ids, id) + } + return +} + +// ResetFeature resets all changes to the "feature" edge. +func (m *MeterMutation) ResetFeature() { + m.feature = nil + m.clearedfeature = false + m.removedfeature = nil +} + +// Where appends a list predicates to the MeterMutation builder. +func (m *MeterMutation) Where(ps ...predicate.Meter) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the MeterMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *MeterMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Meter, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *MeterMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *MeterMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Meter). +func (m *MeterMutation) 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 *MeterMutation) Fields() []string { + fields := make([]string, 0, 14) + if m.namespace != nil { + fields = append(fields, dbmeter.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, dbmeter.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, dbmeter.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, dbmeter.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, dbmeter.FieldDeletedAt) + } + if m.name != nil { + fields = append(fields, dbmeter.FieldName) + } + if m.description != nil { + fields = append(fields, dbmeter.FieldDescription) + } + if m.key != nil { + fields = append(fields, dbmeter.FieldKey) + } + if m.annotations != nil { + fields = append(fields, dbmeter.FieldAnnotations) + } + if m.event_type != nil { + fields = append(fields, dbmeter.FieldEventType) + } + if m.value_property != nil { + fields = append(fields, dbmeter.FieldValueProperty) + } + if m.group_by != nil { + fields = append(fields, dbmeter.FieldGroupBy) + } + if m.aggregation != nil { + fields = append(fields, dbmeter.FieldAggregation) + } + if m.event_from != nil { + fields = append(fields, dbmeter.FieldEventFrom) + } + 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 *MeterMutation) Field(name string) (ent.Value, bool) { + switch name { + case dbmeter.FieldNamespace: + return m.Namespace() + case dbmeter.FieldMetadata: + return m.Metadata() + case dbmeter.FieldCreatedAt: + return m.CreatedAt() + case dbmeter.FieldUpdatedAt: + return m.UpdatedAt() + case dbmeter.FieldDeletedAt: + return m.DeletedAt() + case dbmeter.FieldName: + return m.Name() + case dbmeter.FieldDescription: + return m.Description() + case dbmeter.FieldKey: + return m.Key() + case dbmeter.FieldAnnotations: + return m.Annotations() + case dbmeter.FieldEventType: + return m.EventType() + case dbmeter.FieldValueProperty: + return m.ValueProperty() + case dbmeter.FieldGroupBy: + return m.GroupBy() + case dbmeter.FieldAggregation: + return m.Aggregation() + case dbmeter.FieldEventFrom: + return m.EventFrom() + } + 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 *MeterMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case dbmeter.FieldNamespace: + return m.OldNamespace(ctx) + case dbmeter.FieldMetadata: + return m.OldMetadata(ctx) + case dbmeter.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case dbmeter.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case dbmeter.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case dbmeter.FieldName: + return m.OldName(ctx) + case dbmeter.FieldDescription: + return m.OldDescription(ctx) + case dbmeter.FieldKey: + return m.OldKey(ctx) + case dbmeter.FieldAnnotations: + return m.OldAnnotations(ctx) + case dbmeter.FieldEventType: + return m.OldEventType(ctx) + case dbmeter.FieldValueProperty: + return m.OldValueProperty(ctx) + case dbmeter.FieldGroupBy: + return m.OldGroupBy(ctx) + case dbmeter.FieldAggregation: + return m.OldAggregation(ctx) + case dbmeter.FieldEventFrom: + return m.OldEventFrom(ctx) + } + return nil, fmt.Errorf("unknown Meter 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 *MeterMutation) SetField(name string, value ent.Value) error { + switch name { + case dbmeter.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case dbmeter.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case dbmeter.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 dbmeter.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 dbmeter.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 dbmeter.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case dbmeter.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case dbmeter.FieldKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKey(v) + return nil + case dbmeter.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 dbmeter.FieldEventType: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEventType(v) + return nil + case dbmeter.FieldValueProperty: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetValueProperty(v) + return nil + case dbmeter.FieldGroupBy: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetGroupBy(v) + return nil + case dbmeter.FieldAggregation: + v, ok := value.(meter.MeterAggregation) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAggregation(v) + return nil + case dbmeter.FieldEventFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEventFrom(v) + return nil + } + return fmt.Errorf("unknown Meter field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *MeterMutation) 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 *MeterMutation) 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 *MeterMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Meter numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *MeterMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(dbmeter.FieldMetadata) { + fields = append(fields, dbmeter.FieldMetadata) + } + if m.FieldCleared(dbmeter.FieldDeletedAt) { + fields = append(fields, dbmeter.FieldDeletedAt) + } + if m.FieldCleared(dbmeter.FieldDescription) { + fields = append(fields, dbmeter.FieldDescription) + } + if m.FieldCleared(dbmeter.FieldAnnotations) { + fields = append(fields, dbmeter.FieldAnnotations) + } + if m.FieldCleared(dbmeter.FieldValueProperty) { + fields = append(fields, dbmeter.FieldValueProperty) + } + if m.FieldCleared(dbmeter.FieldGroupBy) { + fields = append(fields, dbmeter.FieldGroupBy) + } + if m.FieldCleared(dbmeter.FieldEventFrom) { + fields = append(fields, dbmeter.FieldEventFrom) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *MeterMutation) 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 *MeterMutation) ClearField(name string) error { + switch name { + case dbmeter.FieldMetadata: + m.ClearMetadata() + return nil + case dbmeter.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case dbmeter.FieldDescription: + m.ClearDescription() + return nil + case dbmeter.FieldAnnotations: + m.ClearAnnotations() + return nil + case dbmeter.FieldValueProperty: + m.ClearValueProperty() + return nil + case dbmeter.FieldGroupBy: + m.ClearGroupBy() + return nil + case dbmeter.FieldEventFrom: + m.ClearEventFrom() + return nil + } + return fmt.Errorf("unknown Meter 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 *MeterMutation) ResetField(name string) error { + switch name { + case dbmeter.FieldNamespace: + m.ResetNamespace() + return nil + case dbmeter.FieldMetadata: + m.ResetMetadata() + return nil + case dbmeter.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case dbmeter.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case dbmeter.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case dbmeter.FieldName: + m.ResetName() + return nil + case dbmeter.FieldDescription: + m.ResetDescription() + return nil + case dbmeter.FieldKey: + m.ResetKey() + return nil + case dbmeter.FieldAnnotations: + m.ResetAnnotations() + return nil + case dbmeter.FieldEventType: + m.ResetEventType() + return nil + case dbmeter.FieldValueProperty: + m.ResetValueProperty() + return nil + case dbmeter.FieldGroupBy: + m.ResetGroupBy() + return nil + case dbmeter.FieldAggregation: + m.ResetAggregation() + return nil + case dbmeter.FieldEventFrom: + m.ResetEventFrom() + return nil + } + return fmt.Errorf("unknown Meter field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *MeterMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.feature != nil { + edges = append(edges, dbmeter.EdgeFeature) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *MeterMutation) AddedIDs(name string) []ent.Value { + switch name { + case dbmeter.EdgeFeature: + ids := make([]ent.Value, 0, len(m.feature)) + for id := range m.feature { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *MeterMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + if m.removedfeature != nil { + edges = append(edges, dbmeter.EdgeFeature) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *MeterMutation) RemovedIDs(name string) []ent.Value { + switch name { + case dbmeter.EdgeFeature: + ids := make([]ent.Value, 0, len(m.removedfeature)) + for id := range m.removedfeature { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *MeterMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedfeature { + edges = append(edges, dbmeter.EdgeFeature) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *MeterMutation) EdgeCleared(name string) bool { + switch name { + case dbmeter.EdgeFeature: + return m.clearedfeature + } + 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 *MeterMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown Meter 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 *MeterMutation) ResetEdge(name string) error { + switch name { + case dbmeter.EdgeFeature: + m.ResetFeature() + return nil + } + return fmt.Errorf("unknown Meter edge %s", name) +} + +// NotificationChannelMutation represents an operation that mutates the NotificationChannel nodes in the graph. +type NotificationChannelMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + annotations *models.Annotations + metadata *map[string]string + _type *notification.ChannelType + name *string + disabled *bool + _config *notification.ChannelConfig + clearedFields map[string]struct{} + rules map[string]struct{} + removedrules map[string]struct{} + clearedrules bool + done bool + oldValue func(context.Context) (*NotificationChannel, error) + predicates []predicate.NotificationChannel +} + +var _ ent.Mutation = (*NotificationChannelMutation)(nil) + +// notificationchannelOption allows management of the mutation configuration using functional options. +type notificationchannelOption func(*NotificationChannelMutation) + +// newNotificationChannelMutation creates new mutation for the NotificationChannel entity. +func newNotificationChannelMutation(c config, op Op, opts ...notificationchannelOption) *NotificationChannelMutation { + m := &NotificationChannelMutation{ + config: c, + op: op, + typ: TypeNotificationChannel, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withNotificationChannelID sets the ID field of the mutation. +func withNotificationChannelID(id string) notificationchannelOption { + return func(m *NotificationChannelMutation) { + var ( + err error + once sync.Once + value *NotificationChannel + ) + m.oldValue = func(ctx context.Context) (*NotificationChannel, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().NotificationChannel.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withNotificationChannel sets the old NotificationChannel of the mutation. +func withNotificationChannel(node *NotificationChannel) notificationchannelOption { + return func(m *NotificationChannelMutation) { + m.oldValue = func(context.Context) (*NotificationChannel, 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 NotificationChannelMutation) 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 NotificationChannelMutation) 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 NotificationChannel entities. +func (m *NotificationChannelMutation) 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 *NotificationChannelMutation) 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 *NotificationChannelMutation) 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().NotificationChannel.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 *NotificationChannelMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *NotificationChannelMutation) 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 NotificationChannel entity. +// If the NotificationChannel 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 *NotificationChannelMutation) 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 *NotificationChannelMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *NotificationChannelMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *NotificationChannelMutation) 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 NotificationChannel entity. +// If the NotificationChannel 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 *NotificationChannelMutation) 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 *NotificationChannelMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *NotificationChannelMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *NotificationChannelMutation) 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 NotificationChannel entity. +// If the NotificationChannel 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 *NotificationChannelMutation) 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 *NotificationChannelMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *NotificationChannelMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *NotificationChannelMutation) 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 NotificationChannel entity. +// If the NotificationChannel 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 *NotificationChannelMutation) 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 *NotificationChannelMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[notificationchannel.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *NotificationChannelMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[notificationchannel.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *NotificationChannelMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, notificationchannel.FieldDeletedAt) +} + +// SetAnnotations sets the "annotations" field. +func (m *NotificationChannelMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *NotificationChannelMutation) 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 NotificationChannel entity. +// If the NotificationChannel 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 *NotificationChannelMutation) 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 *NotificationChannelMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[notificationchannel.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *NotificationChannelMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[notificationchannel.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *NotificationChannelMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, notificationchannel.FieldAnnotations) +} + +// SetMetadata sets the "metadata" field. +func (m *NotificationChannelMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *NotificationChannelMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the NotificationChannel entity. +// If the NotificationChannel 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 *NotificationChannelMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *NotificationChannelMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[notificationchannel.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *NotificationChannelMutation) MetadataCleared() bool { + _, ok := m.clearedFields[notificationchannel.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *NotificationChannelMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, notificationchannel.FieldMetadata) +} + +// SetType sets the "type" field. +func (m *NotificationChannelMutation) SetType(nt notification.ChannelType) { + m._type = &nt +} + +// GetType returns the value of the "type" field in the mutation. +func (m *NotificationChannelMutation) GetType() (r notification.ChannelType, exists bool) { + v := m._type + if v == nil { + return + } + return *v, true +} + +// OldType returns the old "type" field's value of the NotificationChannel entity. +// If the NotificationChannel 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 *NotificationChannelMutation) OldType(ctx context.Context) (v notification.ChannelType, 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 *NotificationChannelMutation) ResetType() { + m._type = nil +} + +// SetName sets the "name" field. +func (m *NotificationChannelMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *NotificationChannelMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the NotificationChannel entity. +// If the NotificationChannel 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 *NotificationChannelMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *NotificationChannelMutation) ResetName() { + m.name = nil +} + +// SetDisabled sets the "disabled" field. +func (m *NotificationChannelMutation) SetDisabled(b bool) { + m.disabled = &b +} + +// Disabled returns the value of the "disabled" field in the mutation. +func (m *NotificationChannelMutation) Disabled() (r bool, exists bool) { + v := m.disabled + if v == nil { + return + } + return *v, true +} + +// OldDisabled returns the old "disabled" field's value of the NotificationChannel entity. +// If the NotificationChannel 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 *NotificationChannelMutation) OldDisabled(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDisabled is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDisabled requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDisabled: %w", err) + } + return oldValue.Disabled, nil +} + +// ClearDisabled clears the value of the "disabled" field. +func (m *NotificationChannelMutation) ClearDisabled() { + m.disabled = nil + m.clearedFields[notificationchannel.FieldDisabled] = struct{}{} +} + +// DisabledCleared returns if the "disabled" field was cleared in this mutation. +func (m *NotificationChannelMutation) DisabledCleared() bool { + _, ok := m.clearedFields[notificationchannel.FieldDisabled] + return ok +} + +// ResetDisabled resets all changes to the "disabled" field. +func (m *NotificationChannelMutation) ResetDisabled() { + m.disabled = nil + delete(m.clearedFields, notificationchannel.FieldDisabled) +} + +// SetConfig sets the "config" field. +func (m *NotificationChannelMutation) SetConfig(nc notification.ChannelConfig) { + m._config = &nc +} + +// Config returns the value of the "config" field in the mutation. +func (m *NotificationChannelMutation) Config() (r notification.ChannelConfig, exists bool) { + v := m._config + if v == nil { + return + } + return *v, true +} + +// OldConfig returns the old "config" field's value of the NotificationChannel entity. +// If the NotificationChannel 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 *NotificationChannelMutation) OldConfig(ctx context.Context) (v notification.ChannelConfig, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldConfig is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldConfig requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldConfig: %w", err) + } + return oldValue.Config, nil +} + +// ResetConfig resets all changes to the "config" field. +func (m *NotificationChannelMutation) ResetConfig() { + m._config = nil +} + +// AddRuleIDs adds the "rules" edge to the NotificationRule entity by ids. +func (m *NotificationChannelMutation) AddRuleIDs(ids ...string) { + if m.rules == nil { + m.rules = make(map[string]struct{}) + } + for i := range ids { + m.rules[ids[i]] = struct{}{} + } +} + +// ClearRules clears the "rules" edge to the NotificationRule entity. +func (m *NotificationChannelMutation) ClearRules() { + m.clearedrules = true +} + +// RulesCleared reports if the "rules" edge to the NotificationRule entity was cleared. +func (m *NotificationChannelMutation) RulesCleared() bool { + return m.clearedrules +} + +// RemoveRuleIDs removes the "rules" edge to the NotificationRule entity by IDs. +func (m *NotificationChannelMutation) RemoveRuleIDs(ids ...string) { + if m.removedrules == nil { + m.removedrules = make(map[string]struct{}) + } + for i := range ids { + delete(m.rules, ids[i]) + m.removedrules[ids[i]] = struct{}{} + } +} + +// RemovedRules returns the removed IDs of the "rules" edge to the NotificationRule entity. +func (m *NotificationChannelMutation) RemovedRulesIDs() (ids []string) { + for id := range m.removedrules { + ids = append(ids, id) + } + return +} + +// RulesIDs returns the "rules" edge IDs in the mutation. +func (m *NotificationChannelMutation) RulesIDs() (ids []string) { + for id := range m.rules { + ids = append(ids, id) + } + return +} + +// ResetRules resets all changes to the "rules" edge. +func (m *NotificationChannelMutation) ResetRules() { + m.rules = nil + m.clearedrules = false + m.removedrules = nil +} + +// Where appends a list predicates to the NotificationChannelMutation builder. +func (m *NotificationChannelMutation) Where(ps ...predicate.NotificationChannel) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the NotificationChannelMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *NotificationChannelMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.NotificationChannel, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *NotificationChannelMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *NotificationChannelMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (NotificationChannel). +func (m *NotificationChannelMutation) 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 *NotificationChannelMutation) Fields() []string { + fields := make([]string, 0, 10) + if m.namespace != nil { + fields = append(fields, notificationchannel.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, notificationchannel.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, notificationchannel.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, notificationchannel.FieldDeletedAt) + } + if m.annotations != nil { + fields = append(fields, notificationchannel.FieldAnnotations) + } + if m.metadata != nil { + fields = append(fields, notificationchannel.FieldMetadata) + } + if m._type != nil { + fields = append(fields, notificationchannel.FieldType) + } + if m.name != nil { + fields = append(fields, notificationchannel.FieldName) + } + if m.disabled != nil { + fields = append(fields, notificationchannel.FieldDisabled) + } + if m._config != nil { + fields = append(fields, notificationchannel.FieldConfig) + } + 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 *NotificationChannelMutation) Field(name string) (ent.Value, bool) { + switch name { + case notificationchannel.FieldNamespace: + return m.Namespace() + case notificationchannel.FieldCreatedAt: + return m.CreatedAt() + case notificationchannel.FieldUpdatedAt: + return m.UpdatedAt() + case notificationchannel.FieldDeletedAt: + return m.DeletedAt() + case notificationchannel.FieldAnnotations: + return m.Annotations() + case notificationchannel.FieldMetadata: + return m.Metadata() + case notificationchannel.FieldType: + return m.GetType() + case notificationchannel.FieldName: + return m.Name() + case notificationchannel.FieldDisabled: + return m.Disabled() + case notificationchannel.FieldConfig: + return m.Config() + } + 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 *NotificationChannelMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case notificationchannel.FieldNamespace: + return m.OldNamespace(ctx) + case notificationchannel.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case notificationchannel.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case notificationchannel.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case notificationchannel.FieldAnnotations: + return m.OldAnnotations(ctx) + case notificationchannel.FieldMetadata: + return m.OldMetadata(ctx) + case notificationchannel.FieldType: + return m.OldType(ctx) + case notificationchannel.FieldName: + return m.OldName(ctx) + case notificationchannel.FieldDisabled: + return m.OldDisabled(ctx) + case notificationchannel.FieldConfig: + return m.OldConfig(ctx) + } + return nil, fmt.Errorf("unknown NotificationChannel 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 *NotificationChannelMutation) SetField(name string, value ent.Value) error { + switch name { + case notificationchannel.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case notificationchannel.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 notificationchannel.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 notificationchannel.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 notificationchannel.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 notificationchannel.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case notificationchannel.FieldType: + v, ok := value.(notification.ChannelType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case notificationchannel.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case notificationchannel.FieldDisabled: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDisabled(v) + return nil + case notificationchannel.FieldConfig: + v, ok := value.(notification.ChannelConfig) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetConfig(v) + return nil + } + return fmt.Errorf("unknown NotificationChannel field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *NotificationChannelMutation) 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 *NotificationChannelMutation) 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 *NotificationChannelMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown NotificationChannel numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *NotificationChannelMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(notificationchannel.FieldDeletedAt) { + fields = append(fields, notificationchannel.FieldDeletedAt) + } + if m.FieldCleared(notificationchannel.FieldAnnotations) { + fields = append(fields, notificationchannel.FieldAnnotations) + } + if m.FieldCleared(notificationchannel.FieldMetadata) { + fields = append(fields, notificationchannel.FieldMetadata) + } + if m.FieldCleared(notificationchannel.FieldDisabled) { + fields = append(fields, notificationchannel.FieldDisabled) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *NotificationChannelMutation) 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 *NotificationChannelMutation) ClearField(name string) error { + switch name { + case notificationchannel.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case notificationchannel.FieldAnnotations: + m.ClearAnnotations() + return nil + case notificationchannel.FieldMetadata: + m.ClearMetadata() + return nil + case notificationchannel.FieldDisabled: + m.ClearDisabled() + return nil + } + return fmt.Errorf("unknown NotificationChannel 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 *NotificationChannelMutation) ResetField(name string) error { + switch name { + case notificationchannel.FieldNamespace: + m.ResetNamespace() + return nil + case notificationchannel.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case notificationchannel.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case notificationchannel.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case notificationchannel.FieldAnnotations: + m.ResetAnnotations() + return nil + case notificationchannel.FieldMetadata: + m.ResetMetadata() + return nil + case notificationchannel.FieldType: + m.ResetType() + return nil + case notificationchannel.FieldName: + m.ResetName() + return nil + case notificationchannel.FieldDisabled: + m.ResetDisabled() + return nil + case notificationchannel.FieldConfig: + m.ResetConfig() + return nil + } + return fmt.Errorf("unknown NotificationChannel field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *NotificationChannelMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.rules != nil { + edges = append(edges, notificationchannel.EdgeRules) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *NotificationChannelMutation) AddedIDs(name string) []ent.Value { + switch name { + case notificationchannel.EdgeRules: + ids := make([]ent.Value, 0, len(m.rules)) + for id := range m.rules { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *NotificationChannelMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + if m.removedrules != nil { + edges = append(edges, notificationchannel.EdgeRules) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *NotificationChannelMutation) RemovedIDs(name string) []ent.Value { + switch name { + case notificationchannel.EdgeRules: + ids := make([]ent.Value, 0, len(m.removedrules)) + for id := range m.removedrules { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *NotificationChannelMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedrules { + edges = append(edges, notificationchannel.EdgeRules) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *NotificationChannelMutation) EdgeCleared(name string) bool { + switch name { + case notificationchannel.EdgeRules: + return m.clearedrules + } + 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 *NotificationChannelMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown NotificationChannel 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 *NotificationChannelMutation) ResetEdge(name string) error { + switch name { + case notificationchannel.EdgeRules: + m.ResetRules() + return nil + } + return fmt.Errorf("unknown NotificationChannel edge %s", name) +} + +// NotificationEventMutation represents an operation that mutates the NotificationEvent nodes in the graph. +type NotificationEventMutation struct { + config + op Op + typ string + id *string + namespace *string + annotations *models.Annotations + created_at *time.Time + _type *notification.EventType + payload *string + clearedFields map[string]struct{} + delivery_statuses map[string]struct{} + removeddelivery_statuses map[string]struct{} + cleareddelivery_statuses bool + rules *string + clearedrules bool + done bool + oldValue func(context.Context) (*NotificationEvent, error) + predicates []predicate.NotificationEvent +} + +var _ ent.Mutation = (*NotificationEventMutation)(nil) + +// notificationeventOption allows management of the mutation configuration using functional options. +type notificationeventOption func(*NotificationEventMutation) + +// newNotificationEventMutation creates new mutation for the NotificationEvent entity. +func newNotificationEventMutation(c config, op Op, opts ...notificationeventOption) *NotificationEventMutation { + m := &NotificationEventMutation{ + config: c, + op: op, + typ: TypeNotificationEvent, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withNotificationEventID sets the ID field of the mutation. +func withNotificationEventID(id string) notificationeventOption { + return func(m *NotificationEventMutation) { + var ( + err error + once sync.Once + value *NotificationEvent + ) + m.oldValue = func(ctx context.Context) (*NotificationEvent, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().NotificationEvent.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withNotificationEvent sets the old NotificationEvent of the mutation. +func withNotificationEvent(node *NotificationEvent) notificationeventOption { + return func(m *NotificationEventMutation) { + m.oldValue = func(context.Context) (*NotificationEvent, 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 NotificationEventMutation) 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 NotificationEventMutation) 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 NotificationEvent entities. +func (m *NotificationEventMutation) 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 *NotificationEventMutation) 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 *NotificationEventMutation) 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().NotificationEvent.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 *NotificationEventMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *NotificationEventMutation) 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 NotificationEvent entity. +// If the NotificationEvent 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 *NotificationEventMutation) 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 *NotificationEventMutation) ResetNamespace() { + m.namespace = nil +} + +// SetAnnotations sets the "annotations" field. +func (m *NotificationEventMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *NotificationEventMutation) 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 NotificationEvent entity. +// If the NotificationEvent 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 *NotificationEventMutation) 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 *NotificationEventMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[notificationevent.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *NotificationEventMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[notificationevent.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *NotificationEventMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, notificationevent.FieldAnnotations) +} + +// SetCreatedAt sets the "created_at" field. +func (m *NotificationEventMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *NotificationEventMutation) 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 NotificationEvent entity. +// If the NotificationEvent 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 *NotificationEventMutation) 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 *NotificationEventMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetType sets the "type" field. +func (m *NotificationEventMutation) SetType(nt notification.EventType) { + m._type = &nt +} + +// GetType returns the value of the "type" field in the mutation. +func (m *NotificationEventMutation) GetType() (r notification.EventType, exists bool) { + v := m._type + if v == nil { + return + } + return *v, true +} + +// OldType returns the old "type" field's value of the NotificationEvent entity. +// If the NotificationEvent 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 *NotificationEventMutation) OldType(ctx context.Context) (v notification.EventType, 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 *NotificationEventMutation) ResetType() { + m._type = nil +} + +// SetRuleID sets the "rule_id" field. +func (m *NotificationEventMutation) SetRuleID(s string) { + m.rules = &s +} + +// RuleID returns the value of the "rule_id" field in the mutation. +func (m *NotificationEventMutation) RuleID() (r string, exists bool) { + v := m.rules + if v == nil { + return + } + return *v, true +} + +// OldRuleID returns the old "rule_id" field's value of the NotificationEvent entity. +// If the NotificationEvent 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 *NotificationEventMutation) OldRuleID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRuleID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRuleID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRuleID: %w", err) + } + return oldValue.RuleID, nil +} + +// ResetRuleID resets all changes to the "rule_id" field. +func (m *NotificationEventMutation) ResetRuleID() { + m.rules = nil +} + +// SetPayload sets the "payload" field. +func (m *NotificationEventMutation) SetPayload(s string) { + m.payload = &s +} + +// Payload returns the value of the "payload" field in the mutation. +func (m *NotificationEventMutation) Payload() (r string, exists bool) { + v := m.payload + if v == nil { + return + } + return *v, true +} + +// OldPayload returns the old "payload" field's value of the NotificationEvent entity. +// If the NotificationEvent 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 *NotificationEventMutation) OldPayload(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPayload is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPayload requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPayload: %w", err) + } + return oldValue.Payload, nil +} + +// ResetPayload resets all changes to the "payload" field. +func (m *NotificationEventMutation) ResetPayload() { + m.payload = nil +} + +// AddDeliveryStatusIDs adds the "delivery_statuses" edge to the NotificationEventDeliveryStatus entity by ids. +func (m *NotificationEventMutation) AddDeliveryStatusIDs(ids ...string) { + if m.delivery_statuses == nil { + m.delivery_statuses = make(map[string]struct{}) + } + for i := range ids { + m.delivery_statuses[ids[i]] = struct{}{} + } +} + +// ClearDeliveryStatuses clears the "delivery_statuses" edge to the NotificationEventDeliveryStatus entity. +func (m *NotificationEventMutation) ClearDeliveryStatuses() { + m.cleareddelivery_statuses = true +} + +// DeliveryStatusesCleared reports if the "delivery_statuses" edge to the NotificationEventDeliveryStatus entity was cleared. +func (m *NotificationEventMutation) DeliveryStatusesCleared() bool { + return m.cleareddelivery_statuses +} + +// RemoveDeliveryStatusIDs removes the "delivery_statuses" edge to the NotificationEventDeliveryStatus entity by IDs. +func (m *NotificationEventMutation) RemoveDeliveryStatusIDs(ids ...string) { + if m.removeddelivery_statuses == nil { + m.removeddelivery_statuses = make(map[string]struct{}) + } + for i := range ids { + delete(m.delivery_statuses, ids[i]) + m.removeddelivery_statuses[ids[i]] = struct{}{} + } +} + +// RemovedDeliveryStatuses returns the removed IDs of the "delivery_statuses" edge to the NotificationEventDeliveryStatus entity. +func (m *NotificationEventMutation) RemovedDeliveryStatusesIDs() (ids []string) { + for id := range m.removeddelivery_statuses { + ids = append(ids, id) + } + return +} + +// DeliveryStatusesIDs returns the "delivery_statuses" edge IDs in the mutation. +func (m *NotificationEventMutation) DeliveryStatusesIDs() (ids []string) { + for id := range m.delivery_statuses { + ids = append(ids, id) + } + return +} + +// ResetDeliveryStatuses resets all changes to the "delivery_statuses" edge. +func (m *NotificationEventMutation) ResetDeliveryStatuses() { + m.delivery_statuses = nil + m.cleareddelivery_statuses = false + m.removeddelivery_statuses = nil +} + +// SetRulesID sets the "rules" edge to the NotificationRule entity by id. +func (m *NotificationEventMutation) SetRulesID(id string) { + m.rules = &id +} + +// ClearRules clears the "rules" edge to the NotificationRule entity. +func (m *NotificationEventMutation) ClearRules() { + m.clearedrules = true + m.clearedFields[notificationevent.FieldRuleID] = struct{}{} +} + +// RulesCleared reports if the "rules" edge to the NotificationRule entity was cleared. +func (m *NotificationEventMutation) RulesCleared() bool { + return m.clearedrules +} + +// RulesID returns the "rules" edge ID in the mutation. +func (m *NotificationEventMutation) RulesID() (id string, exists bool) { + if m.rules != nil { + return *m.rules, true + } + return +} + +// RulesIDs returns the "rules" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// RulesID instead. It exists only for internal usage by the builders. +func (m *NotificationEventMutation) RulesIDs() (ids []string) { + if id := m.rules; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetRules resets all changes to the "rules" edge. +func (m *NotificationEventMutation) ResetRules() { + m.rules = nil + m.clearedrules = false +} + +// Where appends a list predicates to the NotificationEventMutation builder. +func (m *NotificationEventMutation) Where(ps ...predicate.NotificationEvent) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the NotificationEventMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *NotificationEventMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.NotificationEvent, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *NotificationEventMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *NotificationEventMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (NotificationEvent). +func (m *NotificationEventMutation) 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 *NotificationEventMutation) Fields() []string { + fields := make([]string, 0, 6) + if m.namespace != nil { + fields = append(fields, notificationevent.FieldNamespace) + } + if m.annotations != nil { + fields = append(fields, notificationevent.FieldAnnotations) + } + if m.created_at != nil { + fields = append(fields, notificationevent.FieldCreatedAt) + } + if m._type != nil { + fields = append(fields, notificationevent.FieldType) + } + if m.rules != nil { + fields = append(fields, notificationevent.FieldRuleID) + } + if m.payload != nil { + fields = append(fields, notificationevent.FieldPayload) + } + 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 *NotificationEventMutation) Field(name string) (ent.Value, bool) { + switch name { + case notificationevent.FieldNamespace: + return m.Namespace() + case notificationevent.FieldAnnotations: + return m.Annotations() + case notificationevent.FieldCreatedAt: + return m.CreatedAt() + case notificationevent.FieldType: + return m.GetType() + case notificationevent.FieldRuleID: + return m.RuleID() + case notificationevent.FieldPayload: + return m.Payload() + } + 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 *NotificationEventMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case notificationevent.FieldNamespace: + return m.OldNamespace(ctx) + case notificationevent.FieldAnnotations: + return m.OldAnnotations(ctx) + case notificationevent.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case notificationevent.FieldType: + return m.OldType(ctx) + case notificationevent.FieldRuleID: + return m.OldRuleID(ctx) + case notificationevent.FieldPayload: + return m.OldPayload(ctx) + } + return nil, fmt.Errorf("unknown NotificationEvent 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 *NotificationEventMutation) SetField(name string, value ent.Value) error { + switch name { + case notificationevent.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case notificationevent.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 notificationevent.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 notificationevent.FieldType: + v, ok := value.(notification.EventType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case notificationevent.FieldRuleID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRuleID(v) + return nil + case notificationevent.FieldPayload: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPayload(v) + return nil + } + return fmt.Errorf("unknown NotificationEvent field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *NotificationEventMutation) 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 *NotificationEventMutation) 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 *NotificationEventMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown NotificationEvent numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *NotificationEventMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(notificationevent.FieldAnnotations) { + fields = append(fields, notificationevent.FieldAnnotations) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *NotificationEventMutation) 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 *NotificationEventMutation) ClearField(name string) error { + switch name { + case notificationevent.FieldAnnotations: + m.ClearAnnotations() + return nil + } + return fmt.Errorf("unknown NotificationEvent 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 *NotificationEventMutation) ResetField(name string) error { + switch name { + case notificationevent.FieldNamespace: + m.ResetNamespace() + return nil + case notificationevent.FieldAnnotations: + m.ResetAnnotations() + return nil + case notificationevent.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case notificationevent.FieldType: + m.ResetType() + return nil + case notificationevent.FieldRuleID: + m.ResetRuleID() + return nil + case notificationevent.FieldPayload: + m.ResetPayload() + return nil + } + return fmt.Errorf("unknown NotificationEvent field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *NotificationEventMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.delivery_statuses != nil { + edges = append(edges, notificationevent.EdgeDeliveryStatuses) + } + if m.rules != nil { + edges = append(edges, notificationevent.EdgeRules) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *NotificationEventMutation) AddedIDs(name string) []ent.Value { + switch name { + case notificationevent.EdgeDeliveryStatuses: + ids := make([]ent.Value, 0, len(m.delivery_statuses)) + for id := range m.delivery_statuses { + ids = append(ids, id) + } + return ids + case notificationevent.EdgeRules: + if id := m.rules; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *NotificationEventMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removeddelivery_statuses != nil { + edges = append(edges, notificationevent.EdgeDeliveryStatuses) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *NotificationEventMutation) RemovedIDs(name string) []ent.Value { + switch name { + case notificationevent.EdgeDeliveryStatuses: + ids := make([]ent.Value, 0, len(m.removeddelivery_statuses)) + for id := range m.removeddelivery_statuses { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *NotificationEventMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.cleareddelivery_statuses { + edges = append(edges, notificationevent.EdgeDeliveryStatuses) + } + if m.clearedrules { + edges = append(edges, notificationevent.EdgeRules) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *NotificationEventMutation) EdgeCleared(name string) bool { + switch name { + case notificationevent.EdgeDeliveryStatuses: + return m.cleareddelivery_statuses + case notificationevent.EdgeRules: + return m.clearedrules + } + 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 *NotificationEventMutation) ClearEdge(name string) error { + switch name { + case notificationevent.EdgeRules: + m.ClearRules() + return nil + } + return fmt.Errorf("unknown NotificationEvent 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 *NotificationEventMutation) ResetEdge(name string) error { + switch name { + case notificationevent.EdgeDeliveryStatuses: + m.ResetDeliveryStatuses() + return nil + case notificationevent.EdgeRules: + m.ResetRules() + return nil + } + return fmt.Errorf("unknown NotificationEvent edge %s", name) +} + +// NotificationEventDeliveryStatusMutation represents an operation that mutates the NotificationEventDeliveryStatus nodes in the graph. +type NotificationEventDeliveryStatusMutation struct { + config + op Op + typ string + id *string + namespace *string + annotations *models.Annotations + created_at *time.Time + updated_at *time.Time + event_id *string + channel_id *string + state *notification.EventDeliveryStatusState + reason *string + next_attempt_at *time.Time + attempts *[]notification.EventDeliveryAttempt + appendattempts []notification.EventDeliveryAttempt + clearedFields map[string]struct{} + events map[string]struct{} + removedevents map[string]struct{} + clearedevents bool + done bool + oldValue func(context.Context) (*NotificationEventDeliveryStatus, error) + predicates []predicate.NotificationEventDeliveryStatus +} + +var _ ent.Mutation = (*NotificationEventDeliveryStatusMutation)(nil) + +// notificationeventdeliverystatusOption allows management of the mutation configuration using functional options. +type notificationeventdeliverystatusOption func(*NotificationEventDeliveryStatusMutation) + +// newNotificationEventDeliveryStatusMutation creates new mutation for the NotificationEventDeliveryStatus entity. +func newNotificationEventDeliveryStatusMutation(c config, op Op, opts ...notificationeventdeliverystatusOption) *NotificationEventDeliveryStatusMutation { + m := &NotificationEventDeliveryStatusMutation{ + config: c, + op: op, + typ: TypeNotificationEventDeliveryStatus, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withNotificationEventDeliveryStatusID sets the ID field of the mutation. +func withNotificationEventDeliveryStatusID(id string) notificationeventdeliverystatusOption { + return func(m *NotificationEventDeliveryStatusMutation) { + var ( + err error + once sync.Once + value *NotificationEventDeliveryStatus + ) + m.oldValue = func(ctx context.Context) (*NotificationEventDeliveryStatus, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().NotificationEventDeliveryStatus.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withNotificationEventDeliveryStatus sets the old NotificationEventDeliveryStatus of the mutation. +func withNotificationEventDeliveryStatus(node *NotificationEventDeliveryStatus) notificationeventdeliverystatusOption { + return func(m *NotificationEventDeliveryStatusMutation) { + m.oldValue = func(context.Context) (*NotificationEventDeliveryStatus, 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 NotificationEventDeliveryStatusMutation) 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 NotificationEventDeliveryStatusMutation) 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 NotificationEventDeliveryStatus entities. +func (m *NotificationEventDeliveryStatusMutation) 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 *NotificationEventDeliveryStatusMutation) 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 *NotificationEventDeliveryStatusMutation) 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().NotificationEventDeliveryStatus.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 *NotificationEventDeliveryStatusMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *NotificationEventDeliveryStatusMutation) 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 NotificationEventDeliveryStatus entity. +// If the NotificationEventDeliveryStatus 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 *NotificationEventDeliveryStatusMutation) 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 *NotificationEventDeliveryStatusMutation) ResetNamespace() { + m.namespace = nil +} + +// SetAnnotations sets the "annotations" field. +func (m *NotificationEventDeliveryStatusMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *NotificationEventDeliveryStatusMutation) 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 NotificationEventDeliveryStatus entity. +// If the NotificationEventDeliveryStatus 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 *NotificationEventDeliveryStatusMutation) 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 *NotificationEventDeliveryStatusMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[notificationeventdeliverystatus.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *NotificationEventDeliveryStatusMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[notificationeventdeliverystatus.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *NotificationEventDeliveryStatusMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, notificationeventdeliverystatus.FieldAnnotations) +} + +// SetCreatedAt sets the "created_at" field. +func (m *NotificationEventDeliveryStatusMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *NotificationEventDeliveryStatusMutation) 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 NotificationEventDeliveryStatus entity. +// If the NotificationEventDeliveryStatus 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 *NotificationEventDeliveryStatusMutation) 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 *NotificationEventDeliveryStatusMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *NotificationEventDeliveryStatusMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *NotificationEventDeliveryStatusMutation) 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 NotificationEventDeliveryStatus entity. +// If the NotificationEventDeliveryStatus 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 *NotificationEventDeliveryStatusMutation) 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 *NotificationEventDeliveryStatusMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetEventID sets the "event_id" field. +func (m *NotificationEventDeliveryStatusMutation) SetEventID(s string) { + m.event_id = &s +} + +// EventID returns the value of the "event_id" field in the mutation. +func (m *NotificationEventDeliveryStatusMutation) EventID() (r string, exists bool) { + v := m.event_id + if v == nil { + return + } + return *v, true +} + +// OldEventID returns the old "event_id" field's value of the NotificationEventDeliveryStatus entity. +// If the NotificationEventDeliveryStatus 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 *NotificationEventDeliveryStatusMutation) OldEventID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEventID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEventID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEventID: %w", err) + } + return oldValue.EventID, nil +} + +// ResetEventID resets all changes to the "event_id" field. +func (m *NotificationEventDeliveryStatusMutation) ResetEventID() { + m.event_id = nil +} + +// SetChannelID sets the "channel_id" field. +func (m *NotificationEventDeliveryStatusMutation) SetChannelID(s string) { + m.channel_id = &s +} + +// ChannelID returns the value of the "channel_id" field in the mutation. +func (m *NotificationEventDeliveryStatusMutation) ChannelID() (r string, exists bool) { + v := m.channel_id + if v == nil { + return + } + return *v, true +} + +// OldChannelID returns the old "channel_id" field's value of the NotificationEventDeliveryStatus entity. +// If the NotificationEventDeliveryStatus 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 *NotificationEventDeliveryStatusMutation) OldChannelID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldChannelID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldChannelID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldChannelID: %w", err) + } + return oldValue.ChannelID, nil +} + +// ResetChannelID resets all changes to the "channel_id" field. +func (m *NotificationEventDeliveryStatusMutation) ResetChannelID() { + m.channel_id = nil +} + +// SetState sets the "state" field. +func (m *NotificationEventDeliveryStatusMutation) SetState(ndss notification.EventDeliveryStatusState) { + m.state = &ndss +} + +// State returns the value of the "state" field in the mutation. +func (m *NotificationEventDeliveryStatusMutation) State() (r notification.EventDeliveryStatusState, exists bool) { + v := m.state + if v == nil { + return + } + return *v, true +} + +// OldState returns the old "state" field's value of the NotificationEventDeliveryStatus entity. +// If the NotificationEventDeliveryStatus 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 *NotificationEventDeliveryStatusMutation) OldState(ctx context.Context) (v notification.EventDeliveryStatusState, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldState is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldState requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldState: %w", err) + } + return oldValue.State, nil +} + +// ResetState resets all changes to the "state" field. +func (m *NotificationEventDeliveryStatusMutation) ResetState() { + m.state = nil +} + +// SetReason sets the "reason" field. +func (m *NotificationEventDeliveryStatusMutation) SetReason(s string) { + m.reason = &s +} + +// Reason returns the value of the "reason" field in the mutation. +func (m *NotificationEventDeliveryStatusMutation) Reason() (r string, exists bool) { + v := m.reason + if v == nil { + return + } + return *v, true +} + +// OldReason returns the old "reason" field's value of the NotificationEventDeliveryStatus entity. +// If the NotificationEventDeliveryStatus 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 *NotificationEventDeliveryStatusMutation) OldReason(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldReason is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldReason requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldReason: %w", err) + } + return oldValue.Reason, nil +} + +// ClearReason clears the value of the "reason" field. +func (m *NotificationEventDeliveryStatusMutation) ClearReason() { + m.reason = nil + m.clearedFields[notificationeventdeliverystatus.FieldReason] = struct{}{} +} + +// ReasonCleared returns if the "reason" field was cleared in this mutation. +func (m *NotificationEventDeliveryStatusMutation) ReasonCleared() bool { + _, ok := m.clearedFields[notificationeventdeliverystatus.FieldReason] + return ok +} + +// ResetReason resets all changes to the "reason" field. +func (m *NotificationEventDeliveryStatusMutation) ResetReason() { + m.reason = nil + delete(m.clearedFields, notificationeventdeliverystatus.FieldReason) +} + +// SetNextAttemptAt sets the "next_attempt_at" field. +func (m *NotificationEventDeliveryStatusMutation) SetNextAttemptAt(t time.Time) { + m.next_attempt_at = &t +} + +// NextAttemptAt returns the value of the "next_attempt_at" field in the mutation. +func (m *NotificationEventDeliveryStatusMutation) NextAttemptAt() (r time.Time, exists bool) { + v := m.next_attempt_at + if v == nil { + return + } + return *v, true +} + +// OldNextAttemptAt returns the old "next_attempt_at" field's value of the NotificationEventDeliveryStatus entity. +// If the NotificationEventDeliveryStatus 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 *NotificationEventDeliveryStatusMutation) OldNextAttemptAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNextAttemptAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNextAttemptAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNextAttemptAt: %w", err) + } + return oldValue.NextAttemptAt, nil +} + +// ClearNextAttemptAt clears the value of the "next_attempt_at" field. +func (m *NotificationEventDeliveryStatusMutation) ClearNextAttemptAt() { + m.next_attempt_at = nil + m.clearedFields[notificationeventdeliverystatus.FieldNextAttemptAt] = struct{}{} +} + +// NextAttemptAtCleared returns if the "next_attempt_at" field was cleared in this mutation. +func (m *NotificationEventDeliveryStatusMutation) NextAttemptAtCleared() bool { + _, ok := m.clearedFields[notificationeventdeliverystatus.FieldNextAttemptAt] + return ok +} + +// ResetNextAttemptAt resets all changes to the "next_attempt_at" field. +func (m *NotificationEventDeliveryStatusMutation) ResetNextAttemptAt() { + m.next_attempt_at = nil + delete(m.clearedFields, notificationeventdeliverystatus.FieldNextAttemptAt) +} + +// SetAttempts sets the "attempts" field. +func (m *NotificationEventDeliveryStatusMutation) SetAttempts(nda []notification.EventDeliveryAttempt) { + m.attempts = &nda + m.appendattempts = nil +} + +// Attempts returns the value of the "attempts" field in the mutation. +func (m *NotificationEventDeliveryStatusMutation) Attempts() (r []notification.EventDeliveryAttempt, exists bool) { + v := m.attempts + if v == nil { + return + } + return *v, true +} + +// OldAttempts returns the old "attempts" field's value of the NotificationEventDeliveryStatus entity. +// If the NotificationEventDeliveryStatus 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 *NotificationEventDeliveryStatusMutation) OldAttempts(ctx context.Context) (v []notification.EventDeliveryAttempt, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAttempts is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAttempts requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAttempts: %w", err) + } + return oldValue.Attempts, nil +} + +// AppendAttempts adds nda to the "attempts" field. +func (m *NotificationEventDeliveryStatusMutation) AppendAttempts(nda []notification.EventDeliveryAttempt) { + m.appendattempts = append(m.appendattempts, nda...) +} + +// AppendedAttempts returns the list of values that were appended to the "attempts" field in this mutation. +func (m *NotificationEventDeliveryStatusMutation) AppendedAttempts() ([]notification.EventDeliveryAttempt, bool) { + if len(m.appendattempts) == 0 { + return nil, false + } + return m.appendattempts, true +} + +// ClearAttempts clears the value of the "attempts" field. +func (m *NotificationEventDeliveryStatusMutation) ClearAttempts() { + m.attempts = nil + m.appendattempts = nil + m.clearedFields[notificationeventdeliverystatus.FieldAttempts] = struct{}{} +} + +// AttemptsCleared returns if the "attempts" field was cleared in this mutation. +func (m *NotificationEventDeliveryStatusMutation) AttemptsCleared() bool { + _, ok := m.clearedFields[notificationeventdeliverystatus.FieldAttempts] + return ok +} + +// ResetAttempts resets all changes to the "attempts" field. +func (m *NotificationEventDeliveryStatusMutation) ResetAttempts() { + m.attempts = nil + m.appendattempts = nil + delete(m.clearedFields, notificationeventdeliverystatus.FieldAttempts) +} + +// AddEventIDs adds the "events" edge to the NotificationEvent entity by ids. +func (m *NotificationEventDeliveryStatusMutation) AddEventIDs(ids ...string) { + if m.events == nil { + m.events = make(map[string]struct{}) + } + for i := range ids { + m.events[ids[i]] = struct{}{} + } +} + +// ClearEvents clears the "events" edge to the NotificationEvent entity. +func (m *NotificationEventDeliveryStatusMutation) ClearEvents() { + m.clearedevents = true +} + +// EventsCleared reports if the "events" edge to the NotificationEvent entity was cleared. +func (m *NotificationEventDeliveryStatusMutation) EventsCleared() bool { + return m.clearedevents +} + +// RemoveEventIDs removes the "events" edge to the NotificationEvent entity by IDs. +func (m *NotificationEventDeliveryStatusMutation) RemoveEventIDs(ids ...string) { + if m.removedevents == nil { + m.removedevents = make(map[string]struct{}) + } + for i := range ids { + delete(m.events, ids[i]) + m.removedevents[ids[i]] = struct{}{} + } +} + +// RemovedEvents returns the removed IDs of the "events" edge to the NotificationEvent entity. +func (m *NotificationEventDeliveryStatusMutation) RemovedEventsIDs() (ids []string) { + for id := range m.removedevents { + ids = append(ids, id) + } + return +} + +// EventsIDs returns the "events" edge IDs in the mutation. +func (m *NotificationEventDeliveryStatusMutation) EventsIDs() (ids []string) { + for id := range m.events { + ids = append(ids, id) + } + return +} + +// ResetEvents resets all changes to the "events" edge. +func (m *NotificationEventDeliveryStatusMutation) ResetEvents() { + m.events = nil + m.clearedevents = false + m.removedevents = nil +} + +// Where appends a list predicates to the NotificationEventDeliveryStatusMutation builder. +func (m *NotificationEventDeliveryStatusMutation) Where(ps ...predicate.NotificationEventDeliveryStatus) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the NotificationEventDeliveryStatusMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *NotificationEventDeliveryStatusMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.NotificationEventDeliveryStatus, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *NotificationEventDeliveryStatusMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *NotificationEventDeliveryStatusMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (NotificationEventDeliveryStatus). +func (m *NotificationEventDeliveryStatusMutation) 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 *NotificationEventDeliveryStatusMutation) Fields() []string { + fields := make([]string, 0, 10) + if m.namespace != nil { + fields = append(fields, notificationeventdeliverystatus.FieldNamespace) + } + if m.annotations != nil { + fields = append(fields, notificationeventdeliverystatus.FieldAnnotations) + } + if m.created_at != nil { + fields = append(fields, notificationeventdeliverystatus.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, notificationeventdeliverystatus.FieldUpdatedAt) + } + if m.event_id != nil { + fields = append(fields, notificationeventdeliverystatus.FieldEventID) + } + if m.channel_id != nil { + fields = append(fields, notificationeventdeliverystatus.FieldChannelID) + } + if m.state != nil { + fields = append(fields, notificationeventdeliverystatus.FieldState) + } + if m.reason != nil { + fields = append(fields, notificationeventdeliverystatus.FieldReason) + } + if m.next_attempt_at != nil { + fields = append(fields, notificationeventdeliverystatus.FieldNextAttemptAt) + } + if m.attempts != nil { + fields = append(fields, notificationeventdeliverystatus.FieldAttempts) + } + 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 *NotificationEventDeliveryStatusMutation) Field(name string) (ent.Value, bool) { + switch name { + case notificationeventdeliverystatus.FieldNamespace: + return m.Namespace() + case notificationeventdeliverystatus.FieldAnnotations: + return m.Annotations() + case notificationeventdeliverystatus.FieldCreatedAt: + return m.CreatedAt() + case notificationeventdeliverystatus.FieldUpdatedAt: + return m.UpdatedAt() + case notificationeventdeliverystatus.FieldEventID: + return m.EventID() + case notificationeventdeliverystatus.FieldChannelID: + return m.ChannelID() + case notificationeventdeliverystatus.FieldState: + return m.State() + case notificationeventdeliverystatus.FieldReason: + return m.Reason() + case notificationeventdeliverystatus.FieldNextAttemptAt: + return m.NextAttemptAt() + case notificationeventdeliverystatus.FieldAttempts: + return m.Attempts() + } + 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 *NotificationEventDeliveryStatusMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case notificationeventdeliverystatus.FieldNamespace: + return m.OldNamespace(ctx) + case notificationeventdeliverystatus.FieldAnnotations: + return m.OldAnnotations(ctx) + case notificationeventdeliverystatus.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case notificationeventdeliverystatus.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case notificationeventdeliverystatus.FieldEventID: + return m.OldEventID(ctx) + case notificationeventdeliverystatus.FieldChannelID: + return m.OldChannelID(ctx) + case notificationeventdeliverystatus.FieldState: + return m.OldState(ctx) + case notificationeventdeliverystatus.FieldReason: + return m.OldReason(ctx) + case notificationeventdeliverystatus.FieldNextAttemptAt: + return m.OldNextAttemptAt(ctx) + case notificationeventdeliverystatus.FieldAttempts: + return m.OldAttempts(ctx) + } + return nil, fmt.Errorf("unknown NotificationEventDeliveryStatus 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 *NotificationEventDeliveryStatusMutation) SetField(name string, value ent.Value) error { + switch name { + case notificationeventdeliverystatus.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case notificationeventdeliverystatus.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 notificationeventdeliverystatus.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 notificationeventdeliverystatus.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 notificationeventdeliverystatus.FieldEventID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEventID(v) + return nil + case notificationeventdeliverystatus.FieldChannelID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChannelID(v) + return nil + case notificationeventdeliverystatus.FieldState: + v, ok := value.(notification.EventDeliveryStatusState) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetState(v) + return nil + case notificationeventdeliverystatus.FieldReason: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetReason(v) + return nil + case notificationeventdeliverystatus.FieldNextAttemptAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNextAttemptAt(v) + return nil + case notificationeventdeliverystatus.FieldAttempts: + v, ok := value.([]notification.EventDeliveryAttempt) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAttempts(v) + return nil + } + return fmt.Errorf("unknown NotificationEventDeliveryStatus field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *NotificationEventDeliveryStatusMutation) 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 *NotificationEventDeliveryStatusMutation) 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 *NotificationEventDeliveryStatusMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown NotificationEventDeliveryStatus numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *NotificationEventDeliveryStatusMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(notificationeventdeliverystatus.FieldAnnotations) { + fields = append(fields, notificationeventdeliverystatus.FieldAnnotations) + } + if m.FieldCleared(notificationeventdeliverystatus.FieldReason) { + fields = append(fields, notificationeventdeliverystatus.FieldReason) + } + if m.FieldCleared(notificationeventdeliverystatus.FieldNextAttemptAt) { + fields = append(fields, notificationeventdeliverystatus.FieldNextAttemptAt) + } + if m.FieldCleared(notificationeventdeliverystatus.FieldAttempts) { + fields = append(fields, notificationeventdeliverystatus.FieldAttempts) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *NotificationEventDeliveryStatusMutation) 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 *NotificationEventDeliveryStatusMutation) ClearField(name string) error { + switch name { + case notificationeventdeliverystatus.FieldAnnotations: + m.ClearAnnotations() + return nil + case notificationeventdeliverystatus.FieldReason: + m.ClearReason() + return nil + case notificationeventdeliverystatus.FieldNextAttemptAt: + m.ClearNextAttemptAt() + return nil + case notificationeventdeliverystatus.FieldAttempts: + m.ClearAttempts() + return nil + } + return fmt.Errorf("unknown NotificationEventDeliveryStatus 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 *NotificationEventDeliveryStatusMutation) ResetField(name string) error { + switch name { + case notificationeventdeliverystatus.FieldNamespace: + m.ResetNamespace() + return nil + case notificationeventdeliverystatus.FieldAnnotations: + m.ResetAnnotations() + return nil + case notificationeventdeliverystatus.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case notificationeventdeliverystatus.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case notificationeventdeliverystatus.FieldEventID: + m.ResetEventID() + return nil + case notificationeventdeliverystatus.FieldChannelID: + m.ResetChannelID() + return nil + case notificationeventdeliverystatus.FieldState: + m.ResetState() + return nil + case notificationeventdeliverystatus.FieldReason: + m.ResetReason() + return nil + case notificationeventdeliverystatus.FieldNextAttemptAt: + m.ResetNextAttemptAt() + return nil + case notificationeventdeliverystatus.FieldAttempts: + m.ResetAttempts() + return nil + } + return fmt.Errorf("unknown NotificationEventDeliveryStatus field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *NotificationEventDeliveryStatusMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.events != nil { + edges = append(edges, notificationeventdeliverystatus.EdgeEvents) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *NotificationEventDeliveryStatusMutation) AddedIDs(name string) []ent.Value { + switch name { + case notificationeventdeliverystatus.EdgeEvents: + ids := make([]ent.Value, 0, len(m.events)) + for id := range m.events { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *NotificationEventDeliveryStatusMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + if m.removedevents != nil { + edges = append(edges, notificationeventdeliverystatus.EdgeEvents) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *NotificationEventDeliveryStatusMutation) RemovedIDs(name string) []ent.Value { + switch name { + case notificationeventdeliverystatus.EdgeEvents: + ids := make([]ent.Value, 0, len(m.removedevents)) + for id := range m.removedevents { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *NotificationEventDeliveryStatusMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedevents { + edges = append(edges, notificationeventdeliverystatus.EdgeEvents) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *NotificationEventDeliveryStatusMutation) EdgeCleared(name string) bool { + switch name { + case notificationeventdeliverystatus.EdgeEvents: + return m.clearedevents + } + 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 *NotificationEventDeliveryStatusMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown NotificationEventDeliveryStatus 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 *NotificationEventDeliveryStatusMutation) ResetEdge(name string) error { + switch name { + case notificationeventdeliverystatus.EdgeEvents: + m.ResetEvents() + return nil + } + return fmt.Errorf("unknown NotificationEventDeliveryStatus edge %s", name) +} + +// NotificationRuleMutation represents an operation that mutates the NotificationRule nodes in the graph. +type NotificationRuleMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + annotations *models.Annotations + metadata *map[string]string + _type *notification.EventType + name *string + disabled *bool + _config *notification.RuleConfig + clearedFields map[string]struct{} + channels map[string]struct{} + removedchannels map[string]struct{} + clearedchannels bool + events map[string]struct{} + removedevents map[string]struct{} + clearedevents bool + done bool + oldValue func(context.Context) (*NotificationRule, error) + predicates []predicate.NotificationRule +} + +var _ ent.Mutation = (*NotificationRuleMutation)(nil) + +// notificationruleOption allows management of the mutation configuration using functional options. +type notificationruleOption func(*NotificationRuleMutation) + +// newNotificationRuleMutation creates new mutation for the NotificationRule entity. +func newNotificationRuleMutation(c config, op Op, opts ...notificationruleOption) *NotificationRuleMutation { + m := &NotificationRuleMutation{ + config: c, + op: op, + typ: TypeNotificationRule, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withNotificationRuleID sets the ID field of the mutation. +func withNotificationRuleID(id string) notificationruleOption { + return func(m *NotificationRuleMutation) { + var ( + err error + once sync.Once + value *NotificationRule + ) + m.oldValue = func(ctx context.Context) (*NotificationRule, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().NotificationRule.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withNotificationRule sets the old NotificationRule of the mutation. +func withNotificationRule(node *NotificationRule) notificationruleOption { + return func(m *NotificationRuleMutation) { + m.oldValue = func(context.Context) (*NotificationRule, 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 NotificationRuleMutation) 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 NotificationRuleMutation) 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 NotificationRule entities. +func (m *NotificationRuleMutation) 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 *NotificationRuleMutation) 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 *NotificationRuleMutation) 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().NotificationRule.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 *NotificationRuleMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *NotificationRuleMutation) 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 NotificationRule entity. +// If the NotificationRule 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 *NotificationRuleMutation) 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 *NotificationRuleMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *NotificationRuleMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *NotificationRuleMutation) 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 NotificationRule entity. +// If the NotificationRule 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 *NotificationRuleMutation) 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 *NotificationRuleMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *NotificationRuleMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *NotificationRuleMutation) 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 NotificationRule entity. +// If the NotificationRule 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 *NotificationRuleMutation) 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 *NotificationRuleMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *NotificationRuleMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *NotificationRuleMutation) 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 NotificationRule entity. +// If the NotificationRule 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 *NotificationRuleMutation) 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 *NotificationRuleMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[notificationrule.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *NotificationRuleMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[notificationrule.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *NotificationRuleMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, notificationrule.FieldDeletedAt) +} + +// SetAnnotations sets the "annotations" field. +func (m *NotificationRuleMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *NotificationRuleMutation) 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 NotificationRule entity. +// If the NotificationRule 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 *NotificationRuleMutation) 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 *NotificationRuleMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[notificationrule.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *NotificationRuleMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[notificationrule.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *NotificationRuleMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, notificationrule.FieldAnnotations) +} + +// SetMetadata sets the "metadata" field. +func (m *NotificationRuleMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *NotificationRuleMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the NotificationRule entity. +// If the NotificationRule 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 *NotificationRuleMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *NotificationRuleMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[notificationrule.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *NotificationRuleMutation) MetadataCleared() bool { + _, ok := m.clearedFields[notificationrule.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *NotificationRuleMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, notificationrule.FieldMetadata) +} + +// SetType sets the "type" field. +func (m *NotificationRuleMutation) SetType(nt notification.EventType) { + m._type = &nt +} + +// GetType returns the value of the "type" field in the mutation. +func (m *NotificationRuleMutation) GetType() (r notification.EventType, exists bool) { + v := m._type + if v == nil { + return + } + return *v, true +} + +// OldType returns the old "type" field's value of the NotificationRule entity. +// If the NotificationRule 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 *NotificationRuleMutation) OldType(ctx context.Context) (v notification.EventType, 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 *NotificationRuleMutation) ResetType() { + m._type = nil +} + +// SetName sets the "name" field. +func (m *NotificationRuleMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *NotificationRuleMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the NotificationRule entity. +// If the NotificationRule 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 *NotificationRuleMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *NotificationRuleMutation) ResetName() { + m.name = nil +} + +// SetDisabled sets the "disabled" field. +func (m *NotificationRuleMutation) SetDisabled(b bool) { + m.disabled = &b +} + +// Disabled returns the value of the "disabled" field in the mutation. +func (m *NotificationRuleMutation) Disabled() (r bool, exists bool) { + v := m.disabled + if v == nil { + return + } + return *v, true +} + +// OldDisabled returns the old "disabled" field's value of the NotificationRule entity. +// If the NotificationRule 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 *NotificationRuleMutation) OldDisabled(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDisabled is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDisabled requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDisabled: %w", err) + } + return oldValue.Disabled, nil +} + +// ClearDisabled clears the value of the "disabled" field. +func (m *NotificationRuleMutation) ClearDisabled() { + m.disabled = nil + m.clearedFields[notificationrule.FieldDisabled] = struct{}{} +} + +// DisabledCleared returns if the "disabled" field was cleared in this mutation. +func (m *NotificationRuleMutation) DisabledCleared() bool { + _, ok := m.clearedFields[notificationrule.FieldDisabled] + return ok +} + +// ResetDisabled resets all changes to the "disabled" field. +func (m *NotificationRuleMutation) ResetDisabled() { + m.disabled = nil + delete(m.clearedFields, notificationrule.FieldDisabled) +} + +// SetConfig sets the "config" field. +func (m *NotificationRuleMutation) SetConfig(nc notification.RuleConfig) { + m._config = &nc +} + +// Config returns the value of the "config" field in the mutation. +func (m *NotificationRuleMutation) Config() (r notification.RuleConfig, exists bool) { + v := m._config + if v == nil { + return + } + return *v, true +} + +// OldConfig returns the old "config" field's value of the NotificationRule entity. +// If the NotificationRule 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 *NotificationRuleMutation) OldConfig(ctx context.Context) (v notification.RuleConfig, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldConfig is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldConfig requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldConfig: %w", err) + } + return oldValue.Config, nil +} + +// ResetConfig resets all changes to the "config" field. +func (m *NotificationRuleMutation) ResetConfig() { + m._config = nil +} + +// AddChannelIDs adds the "channels" edge to the NotificationChannel entity by ids. +func (m *NotificationRuleMutation) AddChannelIDs(ids ...string) { + if m.channels == nil { + m.channels = make(map[string]struct{}) + } + for i := range ids { + m.channels[ids[i]] = struct{}{} + } +} + +// ClearChannels clears the "channels" edge to the NotificationChannel entity. +func (m *NotificationRuleMutation) ClearChannels() { + m.clearedchannels = true +} + +// ChannelsCleared reports if the "channels" edge to the NotificationChannel entity was cleared. +func (m *NotificationRuleMutation) ChannelsCleared() bool { + return m.clearedchannels +} + +// RemoveChannelIDs removes the "channels" edge to the NotificationChannel entity by IDs. +func (m *NotificationRuleMutation) RemoveChannelIDs(ids ...string) { + if m.removedchannels == nil { + m.removedchannels = make(map[string]struct{}) + } + for i := range ids { + delete(m.channels, ids[i]) + m.removedchannels[ids[i]] = struct{}{} + } +} + +// RemovedChannels returns the removed IDs of the "channels" edge to the NotificationChannel entity. +func (m *NotificationRuleMutation) RemovedChannelsIDs() (ids []string) { + for id := range m.removedchannels { + ids = append(ids, id) + } + return +} + +// ChannelsIDs returns the "channels" edge IDs in the mutation. +func (m *NotificationRuleMutation) ChannelsIDs() (ids []string) { + for id := range m.channels { + ids = append(ids, id) + } + return +} + +// ResetChannels resets all changes to the "channels" edge. +func (m *NotificationRuleMutation) ResetChannels() { + m.channels = nil + m.clearedchannels = false + m.removedchannels = nil +} + +// AddEventIDs adds the "events" edge to the NotificationEvent entity by ids. +func (m *NotificationRuleMutation) AddEventIDs(ids ...string) { + if m.events == nil { + m.events = make(map[string]struct{}) + } + for i := range ids { + m.events[ids[i]] = struct{}{} + } +} + +// ClearEvents clears the "events" edge to the NotificationEvent entity. +func (m *NotificationRuleMutation) ClearEvents() { + m.clearedevents = true +} + +// EventsCleared reports if the "events" edge to the NotificationEvent entity was cleared. +func (m *NotificationRuleMutation) EventsCleared() bool { + return m.clearedevents +} + +// RemoveEventIDs removes the "events" edge to the NotificationEvent entity by IDs. +func (m *NotificationRuleMutation) RemoveEventIDs(ids ...string) { + if m.removedevents == nil { + m.removedevents = make(map[string]struct{}) + } + for i := range ids { + delete(m.events, ids[i]) + m.removedevents[ids[i]] = struct{}{} + } +} + +// RemovedEvents returns the removed IDs of the "events" edge to the NotificationEvent entity. +func (m *NotificationRuleMutation) RemovedEventsIDs() (ids []string) { + for id := range m.removedevents { + ids = append(ids, id) + } + return +} + +// EventsIDs returns the "events" edge IDs in the mutation. +func (m *NotificationRuleMutation) EventsIDs() (ids []string) { + for id := range m.events { + ids = append(ids, id) + } + return +} + +// ResetEvents resets all changes to the "events" edge. +func (m *NotificationRuleMutation) ResetEvents() { + m.events = nil + m.clearedevents = false + m.removedevents = nil +} + +// Where appends a list predicates to the NotificationRuleMutation builder. +func (m *NotificationRuleMutation) Where(ps ...predicate.NotificationRule) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the NotificationRuleMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *NotificationRuleMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.NotificationRule, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *NotificationRuleMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *NotificationRuleMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (NotificationRule). +func (m *NotificationRuleMutation) 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 *NotificationRuleMutation) Fields() []string { + fields := make([]string, 0, 10) + if m.namespace != nil { + fields = append(fields, notificationrule.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, notificationrule.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, notificationrule.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, notificationrule.FieldDeletedAt) + } + if m.annotations != nil { + fields = append(fields, notificationrule.FieldAnnotations) + } + if m.metadata != nil { + fields = append(fields, notificationrule.FieldMetadata) + } + if m._type != nil { + fields = append(fields, notificationrule.FieldType) + } + if m.name != nil { + fields = append(fields, notificationrule.FieldName) + } + if m.disabled != nil { + fields = append(fields, notificationrule.FieldDisabled) + } + if m._config != nil { + fields = append(fields, notificationrule.FieldConfig) + } + 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 *NotificationRuleMutation) Field(name string) (ent.Value, bool) { + switch name { + case notificationrule.FieldNamespace: + return m.Namespace() + case notificationrule.FieldCreatedAt: + return m.CreatedAt() + case notificationrule.FieldUpdatedAt: + return m.UpdatedAt() + case notificationrule.FieldDeletedAt: + return m.DeletedAt() + case notificationrule.FieldAnnotations: + return m.Annotations() + case notificationrule.FieldMetadata: + return m.Metadata() + case notificationrule.FieldType: + return m.GetType() + case notificationrule.FieldName: + return m.Name() + case notificationrule.FieldDisabled: + return m.Disabled() + case notificationrule.FieldConfig: + return m.Config() + } + 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 *NotificationRuleMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case notificationrule.FieldNamespace: + return m.OldNamespace(ctx) + case notificationrule.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case notificationrule.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case notificationrule.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case notificationrule.FieldAnnotations: + return m.OldAnnotations(ctx) + case notificationrule.FieldMetadata: + return m.OldMetadata(ctx) + case notificationrule.FieldType: + return m.OldType(ctx) + case notificationrule.FieldName: + return m.OldName(ctx) + case notificationrule.FieldDisabled: + return m.OldDisabled(ctx) + case notificationrule.FieldConfig: + return m.OldConfig(ctx) + } + return nil, fmt.Errorf("unknown NotificationRule 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 *NotificationRuleMutation) SetField(name string, value ent.Value) error { + switch name { + case notificationrule.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case notificationrule.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 notificationrule.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 notificationrule.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 notificationrule.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 notificationrule.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case notificationrule.FieldType: + v, ok := value.(notification.EventType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case notificationrule.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case notificationrule.FieldDisabled: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDisabled(v) + return nil + case notificationrule.FieldConfig: + v, ok := value.(notification.RuleConfig) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetConfig(v) + return nil + } + return fmt.Errorf("unknown NotificationRule field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *NotificationRuleMutation) 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 *NotificationRuleMutation) 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 *NotificationRuleMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown NotificationRule numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *NotificationRuleMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(notificationrule.FieldDeletedAt) { + fields = append(fields, notificationrule.FieldDeletedAt) + } + if m.FieldCleared(notificationrule.FieldAnnotations) { + fields = append(fields, notificationrule.FieldAnnotations) + } + if m.FieldCleared(notificationrule.FieldMetadata) { + fields = append(fields, notificationrule.FieldMetadata) + } + if m.FieldCleared(notificationrule.FieldDisabled) { + fields = append(fields, notificationrule.FieldDisabled) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *NotificationRuleMutation) 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 *NotificationRuleMutation) ClearField(name string) error { + switch name { + case notificationrule.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case notificationrule.FieldAnnotations: + m.ClearAnnotations() + return nil + case notificationrule.FieldMetadata: + m.ClearMetadata() + return nil + case notificationrule.FieldDisabled: + m.ClearDisabled() + return nil + } + return fmt.Errorf("unknown NotificationRule 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 *NotificationRuleMutation) ResetField(name string) error { + switch name { + case notificationrule.FieldNamespace: + m.ResetNamespace() + return nil + case notificationrule.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case notificationrule.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case notificationrule.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case notificationrule.FieldAnnotations: + m.ResetAnnotations() + return nil + case notificationrule.FieldMetadata: + m.ResetMetadata() + return nil + case notificationrule.FieldType: + m.ResetType() + return nil + case notificationrule.FieldName: + m.ResetName() + return nil + case notificationrule.FieldDisabled: + m.ResetDisabled() + return nil + case notificationrule.FieldConfig: + m.ResetConfig() + return nil + } + return fmt.Errorf("unknown NotificationRule field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *NotificationRuleMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.channels != nil { + edges = append(edges, notificationrule.EdgeChannels) + } + if m.events != nil { + edges = append(edges, notificationrule.EdgeEvents) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *NotificationRuleMutation) AddedIDs(name string) []ent.Value { + switch name { + case notificationrule.EdgeChannels: + ids := make([]ent.Value, 0, len(m.channels)) + for id := range m.channels { + ids = append(ids, id) + } + return ids + case notificationrule.EdgeEvents: + ids := make([]ent.Value, 0, len(m.events)) + for id := range m.events { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *NotificationRuleMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedchannels != nil { + edges = append(edges, notificationrule.EdgeChannels) + } + if m.removedevents != nil { + edges = append(edges, notificationrule.EdgeEvents) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *NotificationRuleMutation) RemovedIDs(name string) []ent.Value { + switch name { + case notificationrule.EdgeChannels: + ids := make([]ent.Value, 0, len(m.removedchannels)) + for id := range m.removedchannels { + ids = append(ids, id) + } + return ids + case notificationrule.EdgeEvents: + ids := make([]ent.Value, 0, len(m.removedevents)) + for id := range m.removedevents { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *NotificationRuleMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedchannels { + edges = append(edges, notificationrule.EdgeChannels) + } + if m.clearedevents { + edges = append(edges, notificationrule.EdgeEvents) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *NotificationRuleMutation) EdgeCleared(name string) bool { + switch name { + case notificationrule.EdgeChannels: + return m.clearedchannels + case notificationrule.EdgeEvents: + return m.clearedevents + } + 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 *NotificationRuleMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown NotificationRule 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 *NotificationRuleMutation) ResetEdge(name string) error { + switch name { + case notificationrule.EdgeChannels: + m.ResetChannels() + return nil + case notificationrule.EdgeEvents: + m.ResetEvents() + return nil + } + return fmt.Errorf("unknown NotificationRule edge %s", name) +} + +// OrganizationDefaultTaxCodesMutation represents an operation that mutates the OrganizationDefaultTaxCodes nodes in the graph. +type OrganizationDefaultTaxCodesMutation struct { + config + op Op + typ string + id *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + namespace *string + clearedFields map[string]struct{} + invoicing_tax_code *string + clearedinvoicing_tax_code bool + credit_grant_tax_code *string + clearedcredit_grant_tax_code bool + done bool + oldValue func(context.Context) (*OrganizationDefaultTaxCodes, error) + predicates []predicate.OrganizationDefaultTaxCodes +} + +var _ ent.Mutation = (*OrganizationDefaultTaxCodesMutation)(nil) + +// organizationdefaulttaxcodesOption allows management of the mutation configuration using functional options. +type organizationdefaulttaxcodesOption func(*OrganizationDefaultTaxCodesMutation) + +// newOrganizationDefaultTaxCodesMutation creates new mutation for the OrganizationDefaultTaxCodes entity. +func newOrganizationDefaultTaxCodesMutation(c config, op Op, opts ...organizationdefaulttaxcodesOption) *OrganizationDefaultTaxCodesMutation { + m := &OrganizationDefaultTaxCodesMutation{ + config: c, + op: op, + typ: TypeOrganizationDefaultTaxCodes, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withOrganizationDefaultTaxCodesID sets the ID field of the mutation. +func withOrganizationDefaultTaxCodesID(id string) organizationdefaulttaxcodesOption { + return func(m *OrganizationDefaultTaxCodesMutation) { + var ( + err error + once sync.Once + value *OrganizationDefaultTaxCodes + ) + m.oldValue = func(ctx context.Context) (*OrganizationDefaultTaxCodes, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().OrganizationDefaultTaxCodes.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withOrganizationDefaultTaxCodes sets the old OrganizationDefaultTaxCodes of the mutation. +func withOrganizationDefaultTaxCodes(node *OrganizationDefaultTaxCodes) organizationdefaulttaxcodesOption { + return func(m *OrganizationDefaultTaxCodesMutation) { + m.oldValue = func(context.Context) (*OrganizationDefaultTaxCodes, 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 OrganizationDefaultTaxCodesMutation) 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 OrganizationDefaultTaxCodesMutation) 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 OrganizationDefaultTaxCodes entities. +func (m *OrganizationDefaultTaxCodesMutation) 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 *OrganizationDefaultTaxCodesMutation) 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 *OrganizationDefaultTaxCodesMutation) 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().OrganizationDefaultTaxCodes.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetCreatedAt sets the "created_at" field. +func (m *OrganizationDefaultTaxCodesMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *OrganizationDefaultTaxCodesMutation) 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 OrganizationDefaultTaxCodes entity. +// If the OrganizationDefaultTaxCodes 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 *OrganizationDefaultTaxCodesMutation) 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 *OrganizationDefaultTaxCodesMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *OrganizationDefaultTaxCodesMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *OrganizationDefaultTaxCodesMutation) 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 OrganizationDefaultTaxCodes entity. +// If the OrganizationDefaultTaxCodes 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 *OrganizationDefaultTaxCodesMutation) 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 *OrganizationDefaultTaxCodesMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *OrganizationDefaultTaxCodesMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *OrganizationDefaultTaxCodesMutation) 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 OrganizationDefaultTaxCodes entity. +// If the OrganizationDefaultTaxCodes 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 *OrganizationDefaultTaxCodesMutation) 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 *OrganizationDefaultTaxCodesMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[organizationdefaulttaxcodes.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *OrganizationDefaultTaxCodesMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[organizationdefaulttaxcodes.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *OrganizationDefaultTaxCodesMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, organizationdefaulttaxcodes.FieldDeletedAt) +} + +// SetNamespace sets the "namespace" field. +func (m *OrganizationDefaultTaxCodesMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *OrganizationDefaultTaxCodesMutation) 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 OrganizationDefaultTaxCodes entity. +// If the OrganizationDefaultTaxCodes 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 *OrganizationDefaultTaxCodesMutation) 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 *OrganizationDefaultTaxCodesMutation) ResetNamespace() { + m.namespace = nil +} + +// SetInvoicingTaxCodeID sets the "invoicing_tax_code_id" field. +func (m *OrganizationDefaultTaxCodesMutation) SetInvoicingTaxCodeID(s string) { + m.invoicing_tax_code = &s +} + +// InvoicingTaxCodeID returns the value of the "invoicing_tax_code_id" field in the mutation. +func (m *OrganizationDefaultTaxCodesMutation) InvoicingTaxCodeID() (r string, exists bool) { + v := m.invoicing_tax_code + if v == nil { + return + } + return *v, true +} + +// OldInvoicingTaxCodeID returns the old "invoicing_tax_code_id" field's value of the OrganizationDefaultTaxCodes entity. +// If the OrganizationDefaultTaxCodes 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 *OrganizationDefaultTaxCodesMutation) OldInvoicingTaxCodeID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoicingTaxCodeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoicingTaxCodeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoicingTaxCodeID: %w", err) + } + return oldValue.InvoicingTaxCodeID, nil +} + +// ResetInvoicingTaxCodeID resets all changes to the "invoicing_tax_code_id" field. +func (m *OrganizationDefaultTaxCodesMutation) ResetInvoicingTaxCodeID() { + m.invoicing_tax_code = nil +} + +// SetCreditGrantTaxCodeID sets the "credit_grant_tax_code_id" field. +func (m *OrganizationDefaultTaxCodesMutation) SetCreditGrantTaxCodeID(s string) { + m.credit_grant_tax_code = &s +} + +// CreditGrantTaxCodeID returns the value of the "credit_grant_tax_code_id" field in the mutation. +func (m *OrganizationDefaultTaxCodesMutation) CreditGrantTaxCodeID() (r string, exists bool) { + v := m.credit_grant_tax_code + if v == nil { + return + } + return *v, true +} + +// OldCreditGrantTaxCodeID returns the old "credit_grant_tax_code_id" field's value of the OrganizationDefaultTaxCodes entity. +// If the OrganizationDefaultTaxCodes 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 *OrganizationDefaultTaxCodesMutation) OldCreditGrantTaxCodeID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreditGrantTaxCodeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreditGrantTaxCodeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreditGrantTaxCodeID: %w", err) + } + return oldValue.CreditGrantTaxCodeID, nil +} + +// ResetCreditGrantTaxCodeID resets all changes to the "credit_grant_tax_code_id" field. +func (m *OrganizationDefaultTaxCodesMutation) ResetCreditGrantTaxCodeID() { + m.credit_grant_tax_code = nil +} + +// ClearInvoicingTaxCode clears the "invoicing_tax_code" edge to the TaxCode entity. +func (m *OrganizationDefaultTaxCodesMutation) ClearInvoicingTaxCode() { + m.clearedinvoicing_tax_code = true + m.clearedFields[organizationdefaulttaxcodes.FieldInvoicingTaxCodeID] = struct{}{} +} + +// InvoicingTaxCodeCleared reports if the "invoicing_tax_code" edge to the TaxCode entity was cleared. +func (m *OrganizationDefaultTaxCodesMutation) InvoicingTaxCodeCleared() bool { + return m.clearedinvoicing_tax_code +} + +// InvoicingTaxCodeIDs returns the "invoicing_tax_code" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// InvoicingTaxCodeID instead. It exists only for internal usage by the builders. +func (m *OrganizationDefaultTaxCodesMutation) InvoicingTaxCodeIDs() (ids []string) { + if id := m.invoicing_tax_code; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetInvoicingTaxCode resets all changes to the "invoicing_tax_code" edge. +func (m *OrganizationDefaultTaxCodesMutation) ResetInvoicingTaxCode() { + m.invoicing_tax_code = nil + m.clearedinvoicing_tax_code = false +} + +// ClearCreditGrantTaxCode clears the "credit_grant_tax_code" edge to the TaxCode entity. +func (m *OrganizationDefaultTaxCodesMutation) ClearCreditGrantTaxCode() { + m.clearedcredit_grant_tax_code = true + m.clearedFields[organizationdefaulttaxcodes.FieldCreditGrantTaxCodeID] = struct{}{} +} + +// CreditGrantTaxCodeCleared reports if the "credit_grant_tax_code" edge to the TaxCode entity was cleared. +func (m *OrganizationDefaultTaxCodesMutation) CreditGrantTaxCodeCleared() bool { + return m.clearedcredit_grant_tax_code +} + +// CreditGrantTaxCodeIDs returns the "credit_grant_tax_code" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CreditGrantTaxCodeID instead. It exists only for internal usage by the builders. +func (m *OrganizationDefaultTaxCodesMutation) CreditGrantTaxCodeIDs() (ids []string) { + if id := m.credit_grant_tax_code; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCreditGrantTaxCode resets all changes to the "credit_grant_tax_code" edge. +func (m *OrganizationDefaultTaxCodesMutation) ResetCreditGrantTaxCode() { + m.credit_grant_tax_code = nil + m.clearedcredit_grant_tax_code = false +} + +// Where appends a list predicates to the OrganizationDefaultTaxCodesMutation builder. +func (m *OrganizationDefaultTaxCodesMutation) Where(ps ...predicate.OrganizationDefaultTaxCodes) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the OrganizationDefaultTaxCodesMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *OrganizationDefaultTaxCodesMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.OrganizationDefaultTaxCodes, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *OrganizationDefaultTaxCodesMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *OrganizationDefaultTaxCodesMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (OrganizationDefaultTaxCodes). +func (m *OrganizationDefaultTaxCodesMutation) 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 *OrganizationDefaultTaxCodesMutation) Fields() []string { + fields := make([]string, 0, 6) + if m.created_at != nil { + fields = append(fields, organizationdefaulttaxcodes.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, organizationdefaulttaxcodes.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, organizationdefaulttaxcodes.FieldDeletedAt) + } + if m.namespace != nil { + fields = append(fields, organizationdefaulttaxcodes.FieldNamespace) + } + if m.invoicing_tax_code != nil { + fields = append(fields, organizationdefaulttaxcodes.FieldInvoicingTaxCodeID) + } + if m.credit_grant_tax_code != nil { + fields = append(fields, organizationdefaulttaxcodes.FieldCreditGrantTaxCodeID) + } + 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 *OrganizationDefaultTaxCodesMutation) Field(name string) (ent.Value, bool) { + switch name { + case organizationdefaulttaxcodes.FieldCreatedAt: + return m.CreatedAt() + case organizationdefaulttaxcodes.FieldUpdatedAt: + return m.UpdatedAt() + case organizationdefaulttaxcodes.FieldDeletedAt: + return m.DeletedAt() + case organizationdefaulttaxcodes.FieldNamespace: + return m.Namespace() + case organizationdefaulttaxcodes.FieldInvoicingTaxCodeID: + return m.InvoicingTaxCodeID() + case organizationdefaulttaxcodes.FieldCreditGrantTaxCodeID: + return m.CreditGrantTaxCodeID() + } + 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 *OrganizationDefaultTaxCodesMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case organizationdefaulttaxcodes.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case organizationdefaulttaxcodes.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case organizationdefaulttaxcodes.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case organizationdefaulttaxcodes.FieldNamespace: + return m.OldNamespace(ctx) + case organizationdefaulttaxcodes.FieldInvoicingTaxCodeID: + return m.OldInvoicingTaxCodeID(ctx) + case organizationdefaulttaxcodes.FieldCreditGrantTaxCodeID: + return m.OldCreditGrantTaxCodeID(ctx) + } + return nil, fmt.Errorf("unknown OrganizationDefaultTaxCodes 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 *OrganizationDefaultTaxCodesMutation) SetField(name string, value ent.Value) error { + switch name { + case organizationdefaulttaxcodes.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 organizationdefaulttaxcodes.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 organizationdefaulttaxcodes.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 organizationdefaulttaxcodes.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case organizationdefaulttaxcodes.FieldInvoicingTaxCodeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoicingTaxCodeID(v) + return nil + case organizationdefaulttaxcodes.FieldCreditGrantTaxCodeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreditGrantTaxCodeID(v) + return nil + } + return fmt.Errorf("unknown OrganizationDefaultTaxCodes field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *OrganizationDefaultTaxCodesMutation) 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 *OrganizationDefaultTaxCodesMutation) 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 *OrganizationDefaultTaxCodesMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown OrganizationDefaultTaxCodes numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *OrganizationDefaultTaxCodesMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(organizationdefaulttaxcodes.FieldDeletedAt) { + fields = append(fields, organizationdefaulttaxcodes.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *OrganizationDefaultTaxCodesMutation) 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 *OrganizationDefaultTaxCodesMutation) ClearField(name string) error { + switch name { + case organizationdefaulttaxcodes.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown OrganizationDefaultTaxCodes 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 *OrganizationDefaultTaxCodesMutation) ResetField(name string) error { + switch name { + case organizationdefaulttaxcodes.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case organizationdefaulttaxcodes.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case organizationdefaulttaxcodes.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case organizationdefaulttaxcodes.FieldNamespace: + m.ResetNamespace() + return nil + case organizationdefaulttaxcodes.FieldInvoicingTaxCodeID: + m.ResetInvoicingTaxCodeID() + return nil + case organizationdefaulttaxcodes.FieldCreditGrantTaxCodeID: + m.ResetCreditGrantTaxCodeID() + return nil + } + return fmt.Errorf("unknown OrganizationDefaultTaxCodes field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *OrganizationDefaultTaxCodesMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.invoicing_tax_code != nil { + edges = append(edges, organizationdefaulttaxcodes.EdgeInvoicingTaxCode) + } + if m.credit_grant_tax_code != nil { + edges = append(edges, organizationdefaulttaxcodes.EdgeCreditGrantTaxCode) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *OrganizationDefaultTaxCodesMutation) AddedIDs(name string) []ent.Value { + switch name { + case organizationdefaulttaxcodes.EdgeInvoicingTaxCode: + if id := m.invoicing_tax_code; id != nil { + return []ent.Value{*id} + } + case organizationdefaulttaxcodes.EdgeCreditGrantTaxCode: + if id := m.credit_grant_tax_code; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *OrganizationDefaultTaxCodesMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *OrganizationDefaultTaxCodesMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *OrganizationDefaultTaxCodesMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedinvoicing_tax_code { + edges = append(edges, organizationdefaulttaxcodes.EdgeInvoicingTaxCode) + } + if m.clearedcredit_grant_tax_code { + edges = append(edges, organizationdefaulttaxcodes.EdgeCreditGrantTaxCode) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *OrganizationDefaultTaxCodesMutation) EdgeCleared(name string) bool { + switch name { + case organizationdefaulttaxcodes.EdgeInvoicingTaxCode: + return m.clearedinvoicing_tax_code + case organizationdefaulttaxcodes.EdgeCreditGrantTaxCode: + return m.clearedcredit_grant_tax_code + } + 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 *OrganizationDefaultTaxCodesMutation) ClearEdge(name string) error { + switch name { + case organizationdefaulttaxcodes.EdgeInvoicingTaxCode: + m.ClearInvoicingTaxCode() + return nil + case organizationdefaulttaxcodes.EdgeCreditGrantTaxCode: + m.ClearCreditGrantTaxCode() + return nil + } + return fmt.Errorf("unknown OrganizationDefaultTaxCodes 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 *OrganizationDefaultTaxCodesMutation) ResetEdge(name string) error { + switch name { + case organizationdefaulttaxcodes.EdgeInvoicingTaxCode: + m.ResetInvoicingTaxCode() + return nil + case organizationdefaulttaxcodes.EdgeCreditGrantTaxCode: + m.ResetCreditGrantTaxCode() + return nil + } + return fmt.Errorf("unknown OrganizationDefaultTaxCodes edge %s", name) +} + +// PlanMutation represents an operation that mutates the Plan nodes in the graph. +type PlanMutation struct { + config + op Op + typ string + id *string + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + name *string + description *string + key *string + version *int + addversion *int + currency *string + billing_cadence *datetime.ISODurationString + pro_rating_config *productcatalog.ProRatingConfig + effective_from *time.Time + effective_to *time.Time + settlement_mode *productcatalog.SettlementMode + clearedFields map[string]struct{} + phases map[string]struct{} + removedphases map[string]struct{} + clearedphases bool + addons map[string]struct{} + removedaddons map[string]struct{} + clearedaddons bool + subscriptions map[string]struct{} + removedsubscriptions map[string]struct{} + clearedsubscriptions bool + done bool + oldValue func(context.Context) (*Plan, error) + predicates []predicate.Plan +} + +var _ ent.Mutation = (*PlanMutation)(nil) + +// planOption allows management of the mutation configuration using functional options. +type planOption func(*PlanMutation) + +// newPlanMutation creates new mutation for the Plan entity. +func newPlanMutation(c config, op Op, opts ...planOption) *PlanMutation { + m := &PlanMutation{ + config: c, + op: op, + typ: TypePlan, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withPlanID sets the ID field of the mutation. +func withPlanID(id string) planOption { + return func(m *PlanMutation) { + var ( + err error + once sync.Once + value *Plan + ) + m.oldValue = func(ctx context.Context) (*Plan, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Plan.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withPlan sets the old Plan of the mutation. +func withPlan(node *Plan) planOption { + return func(m *PlanMutation) { + m.oldValue = func(context.Context) (*Plan, 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 PlanMutation) 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 PlanMutation) 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 Plan entities. +func (m *PlanMutation) 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 *PlanMutation) 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 *PlanMutation) 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().Plan.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 *PlanMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *PlanMutation) 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 Plan entity. +// If the Plan 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 *PlanMutation) 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 *PlanMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *PlanMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *PlanMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the Plan entity. +// If the Plan 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 *PlanMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *PlanMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[plan.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *PlanMutation) MetadataCleared() bool { + _, ok := m.clearedFields[plan.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *PlanMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, plan.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *PlanMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *PlanMutation) 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 Plan entity. +// If the Plan 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 *PlanMutation) 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 *PlanMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *PlanMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *PlanMutation) 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 Plan entity. +// If the Plan 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 *PlanMutation) 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 *PlanMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *PlanMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *PlanMutation) 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 Plan entity. +// If the Plan 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 *PlanMutation) 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 *PlanMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[plan.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *PlanMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[plan.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *PlanMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, plan.FieldDeletedAt) +} + +// SetName sets the "name" field. +func (m *PlanMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *PlanMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the Plan entity. +// If the Plan 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 *PlanMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *PlanMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *PlanMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *PlanMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the Plan entity. +// If the Plan 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 *PlanMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *PlanMutation) ClearDescription() { + m.description = nil + m.clearedFields[plan.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *PlanMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[plan.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *PlanMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, plan.FieldDescription) +} + +// SetKey sets the "key" field. +func (m *PlanMutation) SetKey(s string) { + m.key = &s +} + +// Key returns the value of the "key" field in the mutation. +func (m *PlanMutation) Key() (r string, exists bool) { + v := m.key + if v == nil { + return + } + return *v, true +} + +// OldKey returns the old "key" field's value of the Plan entity. +// If the Plan 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 *PlanMutation) OldKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldKey: %w", err) + } + return oldValue.Key, nil +} + +// ResetKey resets all changes to the "key" field. +func (m *PlanMutation) ResetKey() { + m.key = nil +} + +// SetVersion sets the "version" field. +func (m *PlanMutation) SetVersion(i int) { + m.version = &i + m.addversion = nil +} + +// Version returns the value of the "version" field in the mutation. +func (m *PlanMutation) Version() (r int, exists bool) { + v := m.version + if v == nil { + return + } + return *v, true +} + +// OldVersion returns the old "version" field's value of the Plan entity. +// If the Plan 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 *PlanMutation) OldVersion(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldVersion is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldVersion requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldVersion: %w", err) + } + return oldValue.Version, nil +} + +// AddVersion adds i to the "version" field. +func (m *PlanMutation) AddVersion(i int) { + if m.addversion != nil { + *m.addversion += i + } else { + m.addversion = &i + } +} + +// AddedVersion returns the value that was added to the "version" field in this mutation. +func (m *PlanMutation) AddedVersion() (r int, exists bool) { + v := m.addversion + if v == nil { + return + } + return *v, true +} + +// ResetVersion resets all changes to the "version" field. +func (m *PlanMutation) ResetVersion() { + m.version = nil + m.addversion = nil +} + +// SetCurrency sets the "currency" field. +func (m *PlanMutation) SetCurrency(s string) { + m.currency = &s +} + +// Currency returns the value of the "currency" field in the mutation. +func (m *PlanMutation) Currency() (r string, exists bool) { + v := m.currency + if v == nil { + return + } + return *v, true +} + +// OldCurrency returns the old "currency" field's value of the Plan entity. +// If the Plan 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 *PlanMutation) OldCurrency(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrency is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrency requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrency: %w", err) + } + return oldValue.Currency, nil +} + +// ResetCurrency resets all changes to the "currency" field. +func (m *PlanMutation) ResetCurrency() { + m.currency = nil +} + +// SetBillingCadence sets the "billing_cadence" field. +func (m *PlanMutation) SetBillingCadence(dds datetime.ISODurationString) { + m.billing_cadence = &dds +} + +// BillingCadence returns the value of the "billing_cadence" field in the mutation. +func (m *PlanMutation) BillingCadence() (r datetime.ISODurationString, exists bool) { + v := m.billing_cadence + if v == nil { + return + } + return *v, true +} + +// OldBillingCadence returns the old "billing_cadence" field's value of the Plan entity. +// If the Plan 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 *PlanMutation) OldBillingCadence(ctx context.Context) (v datetime.ISODurationString, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingCadence is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingCadence requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingCadence: %w", err) + } + return oldValue.BillingCadence, nil +} + +// ResetBillingCadence resets all changes to the "billing_cadence" field. +func (m *PlanMutation) ResetBillingCadence() { + m.billing_cadence = nil +} + +// SetProRatingConfig sets the "pro_rating_config" field. +func (m *PlanMutation) SetProRatingConfig(prc productcatalog.ProRatingConfig) { + m.pro_rating_config = &prc +} + +// ProRatingConfig returns the value of the "pro_rating_config" field in the mutation. +func (m *PlanMutation) ProRatingConfig() (r productcatalog.ProRatingConfig, exists bool) { + v := m.pro_rating_config + if v == nil { + return + } + return *v, true +} + +// OldProRatingConfig returns the old "pro_rating_config" field's value of the Plan entity. +// If the Plan 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 *PlanMutation) OldProRatingConfig(ctx context.Context) (v productcatalog.ProRatingConfig, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldProRatingConfig is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldProRatingConfig requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldProRatingConfig: %w", err) + } + return oldValue.ProRatingConfig, nil +} + +// ResetProRatingConfig resets all changes to the "pro_rating_config" field. +func (m *PlanMutation) ResetProRatingConfig() { + m.pro_rating_config = nil +} + +// SetEffectiveFrom sets the "effective_from" field. +func (m *PlanMutation) SetEffectiveFrom(t time.Time) { + m.effective_from = &t +} + +// EffectiveFrom returns the value of the "effective_from" field in the mutation. +func (m *PlanMutation) EffectiveFrom() (r time.Time, exists bool) { + v := m.effective_from + if v == nil { + return + } + return *v, true +} + +// OldEffectiveFrom returns the old "effective_from" field's value of the Plan entity. +// If the Plan 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 *PlanMutation) OldEffectiveFrom(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEffectiveFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEffectiveFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEffectiveFrom: %w", err) + } + return oldValue.EffectiveFrom, nil +} + +// ClearEffectiveFrom clears the value of the "effective_from" field. +func (m *PlanMutation) ClearEffectiveFrom() { + m.effective_from = nil + m.clearedFields[plan.FieldEffectiveFrom] = struct{}{} +} + +// EffectiveFromCleared returns if the "effective_from" field was cleared in this mutation. +func (m *PlanMutation) EffectiveFromCleared() bool { + _, ok := m.clearedFields[plan.FieldEffectiveFrom] + return ok +} + +// ResetEffectiveFrom resets all changes to the "effective_from" field. +func (m *PlanMutation) ResetEffectiveFrom() { + m.effective_from = nil + delete(m.clearedFields, plan.FieldEffectiveFrom) +} + +// SetEffectiveTo sets the "effective_to" field. +func (m *PlanMutation) SetEffectiveTo(t time.Time) { + m.effective_to = &t +} + +// EffectiveTo returns the value of the "effective_to" field in the mutation. +func (m *PlanMutation) EffectiveTo() (r time.Time, exists bool) { + v := m.effective_to + if v == nil { + return + } + return *v, true +} + +// OldEffectiveTo returns the old "effective_to" field's value of the Plan entity. +// If the Plan 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 *PlanMutation) OldEffectiveTo(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEffectiveTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEffectiveTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEffectiveTo: %w", err) + } + return oldValue.EffectiveTo, nil +} + +// ClearEffectiveTo clears the value of the "effective_to" field. +func (m *PlanMutation) ClearEffectiveTo() { + m.effective_to = nil + m.clearedFields[plan.FieldEffectiveTo] = struct{}{} +} + +// EffectiveToCleared returns if the "effective_to" field was cleared in this mutation. +func (m *PlanMutation) EffectiveToCleared() bool { + _, ok := m.clearedFields[plan.FieldEffectiveTo] + return ok +} + +// ResetEffectiveTo resets all changes to the "effective_to" field. +func (m *PlanMutation) ResetEffectiveTo() { + m.effective_to = nil + delete(m.clearedFields, plan.FieldEffectiveTo) +} + +// SetSettlementMode sets the "settlement_mode" field. +func (m *PlanMutation) SetSettlementMode(pm productcatalog.SettlementMode) { + m.settlement_mode = &pm +} + +// SettlementMode returns the value of the "settlement_mode" field in the mutation. +func (m *PlanMutation) 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 Plan entity. +// If the Plan 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 *PlanMutation) 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 *PlanMutation) ResetSettlementMode() { + m.settlement_mode = nil +} + +// AddPhaseIDs adds the "phases" edge to the PlanPhase entity by ids. +func (m *PlanMutation) AddPhaseIDs(ids ...string) { + if m.phases == nil { + m.phases = make(map[string]struct{}) + } + for i := range ids { + m.phases[ids[i]] = struct{}{} + } +} + +// ClearPhases clears the "phases" edge to the PlanPhase entity. +func (m *PlanMutation) ClearPhases() { + m.clearedphases = true +} + +// PhasesCleared reports if the "phases" edge to the PlanPhase entity was cleared. +func (m *PlanMutation) PhasesCleared() bool { + return m.clearedphases +} + +// RemovePhaseIDs removes the "phases" edge to the PlanPhase entity by IDs. +func (m *PlanMutation) RemovePhaseIDs(ids ...string) { + if m.removedphases == nil { + m.removedphases = make(map[string]struct{}) + } + for i := range ids { + delete(m.phases, ids[i]) + m.removedphases[ids[i]] = struct{}{} + } +} + +// RemovedPhases returns the removed IDs of the "phases" edge to the PlanPhase entity. +func (m *PlanMutation) RemovedPhasesIDs() (ids []string) { + for id := range m.removedphases { + ids = append(ids, id) + } + return +} + +// PhasesIDs returns the "phases" edge IDs in the mutation. +func (m *PlanMutation) PhasesIDs() (ids []string) { + for id := range m.phases { + ids = append(ids, id) + } + return +} + +// ResetPhases resets all changes to the "phases" edge. +func (m *PlanMutation) ResetPhases() { + m.phases = nil + m.clearedphases = false + m.removedphases = nil +} + +// AddAddonIDs adds the "addons" edge to the PlanAddon entity by ids. +func (m *PlanMutation) AddAddonIDs(ids ...string) { + if m.addons == nil { + m.addons = make(map[string]struct{}) + } + for i := range ids { + m.addons[ids[i]] = struct{}{} + } +} + +// ClearAddons clears the "addons" edge to the PlanAddon entity. +func (m *PlanMutation) ClearAddons() { + m.clearedaddons = true +} + +// AddonsCleared reports if the "addons" edge to the PlanAddon entity was cleared. +func (m *PlanMutation) AddonsCleared() bool { + return m.clearedaddons +} + +// RemoveAddonIDs removes the "addons" edge to the PlanAddon entity by IDs. +func (m *PlanMutation) RemoveAddonIDs(ids ...string) { + if m.removedaddons == nil { + m.removedaddons = make(map[string]struct{}) + } + for i := range ids { + delete(m.addons, ids[i]) + m.removedaddons[ids[i]] = struct{}{} + } +} + +// RemovedAddons returns the removed IDs of the "addons" edge to the PlanAddon entity. +func (m *PlanMutation) RemovedAddonsIDs() (ids []string) { + for id := range m.removedaddons { + ids = append(ids, id) + } + return +} + +// AddonsIDs returns the "addons" edge IDs in the mutation. +func (m *PlanMutation) AddonsIDs() (ids []string) { + for id := range m.addons { + ids = append(ids, id) + } + return +} + +// ResetAddons resets all changes to the "addons" edge. +func (m *PlanMutation) ResetAddons() { + m.addons = nil + m.clearedaddons = false + m.removedaddons = nil +} + +// AddSubscriptionIDs adds the "subscriptions" edge to the Subscription entity by ids. +func (m *PlanMutation) AddSubscriptionIDs(ids ...string) { + if m.subscriptions == nil { + m.subscriptions = make(map[string]struct{}) + } + for i := range ids { + m.subscriptions[ids[i]] = struct{}{} + } +} + +// ClearSubscriptions clears the "subscriptions" edge to the Subscription entity. +func (m *PlanMutation) ClearSubscriptions() { + m.clearedsubscriptions = true +} + +// SubscriptionsCleared reports if the "subscriptions" edge to the Subscription entity was cleared. +func (m *PlanMutation) SubscriptionsCleared() bool { + return m.clearedsubscriptions +} + +// RemoveSubscriptionIDs removes the "subscriptions" edge to the Subscription entity by IDs. +func (m *PlanMutation) RemoveSubscriptionIDs(ids ...string) { + if m.removedsubscriptions == nil { + m.removedsubscriptions = make(map[string]struct{}) + } + for i := range ids { + delete(m.subscriptions, ids[i]) + m.removedsubscriptions[ids[i]] = struct{}{} + } +} + +// RemovedSubscriptions returns the removed IDs of the "subscriptions" edge to the Subscription entity. +func (m *PlanMutation) RemovedSubscriptionsIDs() (ids []string) { + for id := range m.removedsubscriptions { + ids = append(ids, id) + } + return +} + +// SubscriptionsIDs returns the "subscriptions" edge IDs in the mutation. +func (m *PlanMutation) SubscriptionsIDs() (ids []string) { + for id := range m.subscriptions { + ids = append(ids, id) + } + return +} + +// ResetSubscriptions resets all changes to the "subscriptions" edge. +func (m *PlanMutation) ResetSubscriptions() { + m.subscriptions = nil + m.clearedsubscriptions = false + m.removedsubscriptions = nil +} + +// Where appends a list predicates to the PlanMutation builder. +func (m *PlanMutation) Where(ps ...predicate.Plan) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the PlanMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *PlanMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Plan, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *PlanMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *PlanMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Plan). +func (m *PlanMutation) 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 *PlanMutation) Fields() []string { + fields := make([]string, 0, 15) + if m.namespace != nil { + fields = append(fields, plan.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, plan.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, plan.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, plan.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, plan.FieldDeletedAt) + } + if m.name != nil { + fields = append(fields, plan.FieldName) + } + if m.description != nil { + fields = append(fields, plan.FieldDescription) + } + if m.key != nil { + fields = append(fields, plan.FieldKey) + } + if m.version != nil { + fields = append(fields, plan.FieldVersion) + } + if m.currency != nil { + fields = append(fields, plan.FieldCurrency) + } + if m.billing_cadence != nil { + fields = append(fields, plan.FieldBillingCadence) + } + if m.pro_rating_config != nil { + fields = append(fields, plan.FieldProRatingConfig) + } + if m.effective_from != nil { + fields = append(fields, plan.FieldEffectiveFrom) + } + if m.effective_to != nil { + fields = append(fields, plan.FieldEffectiveTo) + } + if m.settlement_mode != nil { + fields = append(fields, plan.FieldSettlementMode) + } + 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 *PlanMutation) Field(name string) (ent.Value, bool) { + switch name { + case plan.FieldNamespace: + return m.Namespace() + case plan.FieldMetadata: + return m.Metadata() + case plan.FieldCreatedAt: + return m.CreatedAt() + case plan.FieldUpdatedAt: + return m.UpdatedAt() + case plan.FieldDeletedAt: + return m.DeletedAt() + case plan.FieldName: + return m.Name() + case plan.FieldDescription: + return m.Description() + case plan.FieldKey: + return m.Key() + case plan.FieldVersion: + return m.Version() + case plan.FieldCurrency: + return m.Currency() + case plan.FieldBillingCadence: + return m.BillingCadence() + case plan.FieldProRatingConfig: + return m.ProRatingConfig() + case plan.FieldEffectiveFrom: + return m.EffectiveFrom() + case plan.FieldEffectiveTo: + return m.EffectiveTo() + case plan.FieldSettlementMode: + return m.SettlementMode() + } + 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 *PlanMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case plan.FieldNamespace: + return m.OldNamespace(ctx) + case plan.FieldMetadata: + return m.OldMetadata(ctx) + case plan.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case plan.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case plan.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case plan.FieldName: + return m.OldName(ctx) + case plan.FieldDescription: + return m.OldDescription(ctx) + case plan.FieldKey: + return m.OldKey(ctx) + case plan.FieldVersion: + return m.OldVersion(ctx) + case plan.FieldCurrency: + return m.OldCurrency(ctx) + case plan.FieldBillingCadence: + return m.OldBillingCadence(ctx) + case plan.FieldProRatingConfig: + return m.OldProRatingConfig(ctx) + case plan.FieldEffectiveFrom: + return m.OldEffectiveFrom(ctx) + case plan.FieldEffectiveTo: + return m.OldEffectiveTo(ctx) + case plan.FieldSettlementMode: + return m.OldSettlementMode(ctx) + } + return nil, fmt.Errorf("unknown Plan 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 *PlanMutation) SetField(name string, value ent.Value) error { + switch name { + case plan.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case plan.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case plan.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 plan.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 plan.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 plan.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case plan.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case plan.FieldKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKey(v) + return nil + case plan.FieldVersion: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVersion(v) + return nil + case plan.FieldCurrency: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrency(v) + return nil + case plan.FieldBillingCadence: + v, ok := value.(datetime.ISODurationString) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingCadence(v) + return nil + case plan.FieldProRatingConfig: + v, ok := value.(productcatalog.ProRatingConfig) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetProRatingConfig(v) + return nil + case plan.FieldEffectiveFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEffectiveFrom(v) + return nil + case plan.FieldEffectiveTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEffectiveTo(v) + return nil + case plan.FieldSettlementMode: + v, ok := value.(productcatalog.SettlementMode) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSettlementMode(v) + return nil + } + return fmt.Errorf("unknown Plan field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *PlanMutation) AddedFields() []string { + var fields []string + if m.addversion != nil { + fields = append(fields, plan.FieldVersion) + } + return fields +} + +// 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 *PlanMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case plan.FieldVersion: + return m.AddedVersion() + } + 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 *PlanMutation) AddField(name string, value ent.Value) error { + switch name { + case plan.FieldVersion: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddVersion(v) + return nil + } + return fmt.Errorf("unknown Plan numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *PlanMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(plan.FieldMetadata) { + fields = append(fields, plan.FieldMetadata) + } + if m.FieldCleared(plan.FieldDeletedAt) { + fields = append(fields, plan.FieldDeletedAt) + } + if m.FieldCleared(plan.FieldDescription) { + fields = append(fields, plan.FieldDescription) + } + if m.FieldCleared(plan.FieldEffectiveFrom) { + fields = append(fields, plan.FieldEffectiveFrom) + } + if m.FieldCleared(plan.FieldEffectiveTo) { + fields = append(fields, plan.FieldEffectiveTo) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *PlanMutation) 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 *PlanMutation) ClearField(name string) error { + switch name { + case plan.FieldMetadata: + m.ClearMetadata() + return nil + case plan.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case plan.FieldDescription: + m.ClearDescription() + return nil + case plan.FieldEffectiveFrom: + m.ClearEffectiveFrom() + return nil + case plan.FieldEffectiveTo: + m.ClearEffectiveTo() + return nil + } + return fmt.Errorf("unknown Plan 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 *PlanMutation) ResetField(name string) error { + switch name { + case plan.FieldNamespace: + m.ResetNamespace() + return nil + case plan.FieldMetadata: + m.ResetMetadata() + return nil + case plan.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case plan.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case plan.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case plan.FieldName: + m.ResetName() + return nil + case plan.FieldDescription: + m.ResetDescription() + return nil + case plan.FieldKey: + m.ResetKey() + return nil + case plan.FieldVersion: + m.ResetVersion() + return nil + case plan.FieldCurrency: + m.ResetCurrency() + return nil + case plan.FieldBillingCadence: + m.ResetBillingCadence() + return nil + case plan.FieldProRatingConfig: + m.ResetProRatingConfig() + return nil + case plan.FieldEffectiveFrom: + m.ResetEffectiveFrom() + return nil + case plan.FieldEffectiveTo: + m.ResetEffectiveTo() + return nil + case plan.FieldSettlementMode: + m.ResetSettlementMode() + return nil + } + return fmt.Errorf("unknown Plan field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *PlanMutation) AddedEdges() []string { + edges := make([]string, 0, 3) + if m.phases != nil { + edges = append(edges, plan.EdgePhases) + } + if m.addons != nil { + edges = append(edges, plan.EdgeAddons) + } + if m.subscriptions != nil { + edges = append(edges, plan.EdgeSubscriptions) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *PlanMutation) AddedIDs(name string) []ent.Value { + switch name { + case plan.EdgePhases: + ids := make([]ent.Value, 0, len(m.phases)) + for id := range m.phases { + ids = append(ids, id) + } + return ids + case plan.EdgeAddons: + ids := make([]ent.Value, 0, len(m.addons)) + for id := range m.addons { + ids = append(ids, id) + } + return ids + case plan.EdgeSubscriptions: + ids := make([]ent.Value, 0, len(m.subscriptions)) + for id := range m.subscriptions { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *PlanMutation) RemovedEdges() []string { + edges := make([]string, 0, 3) + if m.removedphases != nil { + edges = append(edges, plan.EdgePhases) + } + if m.removedaddons != nil { + edges = append(edges, plan.EdgeAddons) + } + if m.removedsubscriptions != nil { + edges = append(edges, plan.EdgeSubscriptions) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *PlanMutation) RemovedIDs(name string) []ent.Value { + switch name { + case plan.EdgePhases: + ids := make([]ent.Value, 0, len(m.removedphases)) + for id := range m.removedphases { + ids = append(ids, id) + } + return ids + case plan.EdgeAddons: + ids := make([]ent.Value, 0, len(m.removedaddons)) + for id := range m.removedaddons { + ids = append(ids, id) + } + return ids + case plan.EdgeSubscriptions: + ids := make([]ent.Value, 0, len(m.removedsubscriptions)) + for id := range m.removedsubscriptions { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *PlanMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) + if m.clearedphases { + edges = append(edges, plan.EdgePhases) + } + if m.clearedaddons { + edges = append(edges, plan.EdgeAddons) + } + if m.clearedsubscriptions { + edges = append(edges, plan.EdgeSubscriptions) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *PlanMutation) EdgeCleared(name string) bool { + switch name { + case plan.EdgePhases: + return m.clearedphases + case plan.EdgeAddons: + return m.clearedaddons + case plan.EdgeSubscriptions: + return m.clearedsubscriptions + } + 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 *PlanMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown Plan 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 *PlanMutation) ResetEdge(name string) error { + switch name { + case plan.EdgePhases: + m.ResetPhases() + return nil + case plan.EdgeAddons: + m.ResetAddons() + return nil + case plan.EdgeSubscriptions: + m.ResetSubscriptions() + return nil + } + return fmt.Errorf("unknown Plan edge %s", name) +} + +// PlanAddonMutation represents an operation that mutates the PlanAddon nodes in the graph. +type PlanAddonMutation struct { + config + op Op + typ string + id *string + namespace *string + metadata *map[string]string + annotations *models.Annotations + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + from_plan_phase *string + max_quantity *int + addmax_quantity *int + clearedFields map[string]struct{} + plan *string + clearedplan bool + addon *string + clearedaddon bool + done bool + oldValue func(context.Context) (*PlanAddon, error) + predicates []predicate.PlanAddon +} + +var _ ent.Mutation = (*PlanAddonMutation)(nil) + +// planaddonOption allows management of the mutation configuration using functional options. +type planaddonOption func(*PlanAddonMutation) + +// newPlanAddonMutation creates new mutation for the PlanAddon entity. +func newPlanAddonMutation(c config, op Op, opts ...planaddonOption) *PlanAddonMutation { + m := &PlanAddonMutation{ + config: c, + op: op, + typ: TypePlanAddon, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withPlanAddonID sets the ID field of the mutation. +func withPlanAddonID(id string) planaddonOption { + return func(m *PlanAddonMutation) { + var ( + err error + once sync.Once + value *PlanAddon + ) + m.oldValue = func(ctx context.Context) (*PlanAddon, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().PlanAddon.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withPlanAddon sets the old PlanAddon of the mutation. +func withPlanAddon(node *PlanAddon) planaddonOption { + return func(m *PlanAddonMutation) { + m.oldValue = func(context.Context) (*PlanAddon, 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 PlanAddonMutation) 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 PlanAddonMutation) 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 PlanAddon entities. +func (m *PlanAddonMutation) 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 *PlanAddonMutation) 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 *PlanAddonMutation) 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().PlanAddon.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 *PlanAddonMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *PlanAddonMutation) 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 PlanAddon entity. +// If the PlanAddon 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 *PlanAddonMutation) 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 *PlanAddonMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *PlanAddonMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *PlanAddonMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the PlanAddon entity. +// If the PlanAddon 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 *PlanAddonMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *PlanAddonMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[planaddon.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *PlanAddonMutation) MetadataCleared() bool { + _, ok := m.clearedFields[planaddon.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *PlanAddonMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, planaddon.FieldMetadata) +} + +// SetAnnotations sets the "annotations" field. +func (m *PlanAddonMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *PlanAddonMutation) 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 PlanAddon entity. +// If the PlanAddon 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 *PlanAddonMutation) 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 *PlanAddonMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[planaddon.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *PlanAddonMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[planaddon.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *PlanAddonMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, planaddon.FieldAnnotations) +} + +// SetCreatedAt sets the "created_at" field. +func (m *PlanAddonMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *PlanAddonMutation) 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 PlanAddon entity. +// If the PlanAddon 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 *PlanAddonMutation) 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 *PlanAddonMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *PlanAddonMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *PlanAddonMutation) 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 PlanAddon entity. +// If the PlanAddon 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 *PlanAddonMutation) 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 *PlanAddonMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *PlanAddonMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *PlanAddonMutation) 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 PlanAddon entity. +// If the PlanAddon 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 *PlanAddonMutation) 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 *PlanAddonMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[planaddon.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *PlanAddonMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[planaddon.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *PlanAddonMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, planaddon.FieldDeletedAt) +} + +// SetPlanID sets the "plan_id" field. +func (m *PlanAddonMutation) SetPlanID(s string) { + m.plan = &s +} + +// PlanID returns the value of the "plan_id" field in the mutation. +func (m *PlanAddonMutation) PlanID() (r string, exists bool) { + v := m.plan + if v == nil { + return + } + return *v, true +} + +// OldPlanID returns the old "plan_id" field's value of the PlanAddon entity. +// If the PlanAddon 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 *PlanAddonMutation) OldPlanID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPlanID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPlanID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPlanID: %w", err) + } + return oldValue.PlanID, nil +} + +// ResetPlanID resets all changes to the "plan_id" field. +func (m *PlanAddonMutation) ResetPlanID() { + m.plan = nil +} + +// SetAddonID sets the "addon_id" field. +func (m *PlanAddonMutation) SetAddonID(s string) { + m.addon = &s +} + +// AddonID returns the value of the "addon_id" field in the mutation. +func (m *PlanAddonMutation) AddonID() (r string, exists bool) { + v := m.addon + if v == nil { + return + } + return *v, true +} + +// OldAddonID returns the old "addon_id" field's value of the PlanAddon entity. +// If the PlanAddon 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 *PlanAddonMutation) OldAddonID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAddonID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAddonID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAddonID: %w", err) + } + return oldValue.AddonID, nil +} + +// ResetAddonID resets all changes to the "addon_id" field. +func (m *PlanAddonMutation) ResetAddonID() { + m.addon = nil +} + +// SetFromPlanPhase sets the "from_plan_phase" field. +func (m *PlanAddonMutation) SetFromPlanPhase(s string) { + m.from_plan_phase = &s +} + +// FromPlanPhase returns the value of the "from_plan_phase" field in the mutation. +func (m *PlanAddonMutation) FromPlanPhase() (r string, exists bool) { + v := m.from_plan_phase + if v == nil { + return + } + return *v, true +} + +// OldFromPlanPhase returns the old "from_plan_phase" field's value of the PlanAddon entity. +// If the PlanAddon 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 *PlanAddonMutation) OldFromPlanPhase(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFromPlanPhase is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFromPlanPhase requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFromPlanPhase: %w", err) + } + return oldValue.FromPlanPhase, nil +} + +// ResetFromPlanPhase resets all changes to the "from_plan_phase" field. +func (m *PlanAddonMutation) ResetFromPlanPhase() { + m.from_plan_phase = nil +} + +// SetMaxQuantity sets the "max_quantity" field. +func (m *PlanAddonMutation) SetMaxQuantity(i int) { + m.max_quantity = &i + m.addmax_quantity = nil +} + +// MaxQuantity returns the value of the "max_quantity" field in the mutation. +func (m *PlanAddonMutation) MaxQuantity() (r int, exists bool) { + v := m.max_quantity + if v == nil { + return + } + return *v, true +} + +// OldMaxQuantity returns the old "max_quantity" field's value of the PlanAddon entity. +// If the PlanAddon 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 *PlanAddonMutation) OldMaxQuantity(ctx context.Context) (v *int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMaxQuantity is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMaxQuantity requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMaxQuantity: %w", err) + } + return oldValue.MaxQuantity, nil +} + +// AddMaxQuantity adds i to the "max_quantity" field. +func (m *PlanAddonMutation) AddMaxQuantity(i int) { + if m.addmax_quantity != nil { + *m.addmax_quantity += i + } else { + m.addmax_quantity = &i + } +} + +// AddedMaxQuantity returns the value that was added to the "max_quantity" field in this mutation. +func (m *PlanAddonMutation) AddedMaxQuantity() (r int, exists bool) { + v := m.addmax_quantity + if v == nil { + return + } + return *v, true +} + +// ClearMaxQuantity clears the value of the "max_quantity" field. +func (m *PlanAddonMutation) ClearMaxQuantity() { + m.max_quantity = nil + m.addmax_quantity = nil + m.clearedFields[planaddon.FieldMaxQuantity] = struct{}{} +} + +// MaxQuantityCleared returns if the "max_quantity" field was cleared in this mutation. +func (m *PlanAddonMutation) MaxQuantityCleared() bool { + _, ok := m.clearedFields[planaddon.FieldMaxQuantity] + return ok +} + +// ResetMaxQuantity resets all changes to the "max_quantity" field. +func (m *PlanAddonMutation) ResetMaxQuantity() { + m.max_quantity = nil + m.addmax_quantity = nil + delete(m.clearedFields, planaddon.FieldMaxQuantity) +} + +// ClearPlan clears the "plan" edge to the Plan entity. +func (m *PlanAddonMutation) ClearPlan() { + m.clearedplan = true + m.clearedFields[planaddon.FieldPlanID] = struct{}{} +} + +// PlanCleared reports if the "plan" edge to the Plan entity was cleared. +func (m *PlanAddonMutation) PlanCleared() bool { + return m.clearedplan +} + +// PlanIDs returns the "plan" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// PlanID instead. It exists only for internal usage by the builders. +func (m *PlanAddonMutation) PlanIDs() (ids []string) { + if id := m.plan; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetPlan resets all changes to the "plan" edge. +func (m *PlanAddonMutation) ResetPlan() { + m.plan = nil + m.clearedplan = false +} + +// ClearAddon clears the "addon" edge to the Addon entity. +func (m *PlanAddonMutation) ClearAddon() { + m.clearedaddon = true + m.clearedFields[planaddon.FieldAddonID] = struct{}{} +} + +// AddonCleared reports if the "addon" edge to the Addon entity was cleared. +func (m *PlanAddonMutation) AddonCleared() bool { + return m.clearedaddon +} + +// AddonIDs returns the "addon" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// AddonID instead. It exists only for internal usage by the builders. +func (m *PlanAddonMutation) AddonIDs() (ids []string) { + if id := m.addon; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetAddon resets all changes to the "addon" edge. +func (m *PlanAddonMutation) ResetAddon() { + m.addon = nil + m.clearedaddon = false +} + +// Where appends a list predicates to the PlanAddonMutation builder. +func (m *PlanAddonMutation) Where(ps ...predicate.PlanAddon) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the PlanAddonMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *PlanAddonMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.PlanAddon, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *PlanAddonMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *PlanAddonMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (PlanAddon). +func (m *PlanAddonMutation) 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 *PlanAddonMutation) Fields() []string { + fields := make([]string, 0, 10) + if m.namespace != nil { + fields = append(fields, planaddon.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, planaddon.FieldMetadata) + } + if m.annotations != nil { + fields = append(fields, planaddon.FieldAnnotations) + } + if m.created_at != nil { + fields = append(fields, planaddon.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, planaddon.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, planaddon.FieldDeletedAt) + } + if m.plan != nil { + fields = append(fields, planaddon.FieldPlanID) + } + if m.addon != nil { + fields = append(fields, planaddon.FieldAddonID) + } + if m.from_plan_phase != nil { + fields = append(fields, planaddon.FieldFromPlanPhase) + } + if m.max_quantity != nil { + fields = append(fields, planaddon.FieldMaxQuantity) + } + 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 *PlanAddonMutation) Field(name string) (ent.Value, bool) { + switch name { + case planaddon.FieldNamespace: + return m.Namespace() + case planaddon.FieldMetadata: + return m.Metadata() + case planaddon.FieldAnnotations: + return m.Annotations() + case planaddon.FieldCreatedAt: + return m.CreatedAt() + case planaddon.FieldUpdatedAt: + return m.UpdatedAt() + case planaddon.FieldDeletedAt: + return m.DeletedAt() + case planaddon.FieldPlanID: + return m.PlanID() + case planaddon.FieldAddonID: + return m.AddonID() + case planaddon.FieldFromPlanPhase: + return m.FromPlanPhase() + case planaddon.FieldMaxQuantity: + return m.MaxQuantity() + } + 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 *PlanAddonMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case planaddon.FieldNamespace: + return m.OldNamespace(ctx) + case planaddon.FieldMetadata: + return m.OldMetadata(ctx) + case planaddon.FieldAnnotations: + return m.OldAnnotations(ctx) + case planaddon.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case planaddon.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case planaddon.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case planaddon.FieldPlanID: + return m.OldPlanID(ctx) + case planaddon.FieldAddonID: + return m.OldAddonID(ctx) + case planaddon.FieldFromPlanPhase: + return m.OldFromPlanPhase(ctx) + case planaddon.FieldMaxQuantity: + return m.OldMaxQuantity(ctx) + } + return nil, fmt.Errorf("unknown PlanAddon 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 *PlanAddonMutation) SetField(name string, value ent.Value) error { + switch name { + case planaddon.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case planaddon.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case planaddon.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 planaddon.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 planaddon.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 planaddon.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 planaddon.FieldPlanID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPlanID(v) + return nil + case planaddon.FieldAddonID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAddonID(v) + return nil + case planaddon.FieldFromPlanPhase: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFromPlanPhase(v) + return nil + case planaddon.FieldMaxQuantity: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMaxQuantity(v) + return nil + } + return fmt.Errorf("unknown PlanAddon field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *PlanAddonMutation) AddedFields() []string { + var fields []string + if m.addmax_quantity != nil { + fields = append(fields, planaddon.FieldMaxQuantity) + } + return fields +} + +// 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 *PlanAddonMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case planaddon.FieldMaxQuantity: + return m.AddedMaxQuantity() + } + 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 *PlanAddonMutation) AddField(name string, value ent.Value) error { + switch name { + case planaddon.FieldMaxQuantity: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddMaxQuantity(v) + return nil + } + return fmt.Errorf("unknown PlanAddon numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *PlanAddonMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(planaddon.FieldMetadata) { + fields = append(fields, planaddon.FieldMetadata) + } + if m.FieldCleared(planaddon.FieldAnnotations) { + fields = append(fields, planaddon.FieldAnnotations) + } + if m.FieldCleared(planaddon.FieldDeletedAt) { + fields = append(fields, planaddon.FieldDeletedAt) + } + if m.FieldCleared(planaddon.FieldMaxQuantity) { + fields = append(fields, planaddon.FieldMaxQuantity) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *PlanAddonMutation) 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 *PlanAddonMutation) ClearField(name string) error { + switch name { + case planaddon.FieldMetadata: + m.ClearMetadata() + return nil + case planaddon.FieldAnnotations: + m.ClearAnnotations() + return nil + case planaddon.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case planaddon.FieldMaxQuantity: + m.ClearMaxQuantity() + return nil + } + return fmt.Errorf("unknown PlanAddon 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 *PlanAddonMutation) ResetField(name string) error { + switch name { + case planaddon.FieldNamespace: + m.ResetNamespace() + return nil + case planaddon.FieldMetadata: + m.ResetMetadata() + return nil + case planaddon.FieldAnnotations: + m.ResetAnnotations() + return nil + case planaddon.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case planaddon.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case planaddon.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case planaddon.FieldPlanID: + m.ResetPlanID() + return nil + case planaddon.FieldAddonID: + m.ResetAddonID() + return nil + case planaddon.FieldFromPlanPhase: + m.ResetFromPlanPhase() + return nil + case planaddon.FieldMaxQuantity: + m.ResetMaxQuantity() + return nil + } + return fmt.Errorf("unknown PlanAddon field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *PlanAddonMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.plan != nil { + edges = append(edges, planaddon.EdgePlan) + } + if m.addon != nil { + edges = append(edges, planaddon.EdgeAddon) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *PlanAddonMutation) AddedIDs(name string) []ent.Value { + switch name { + case planaddon.EdgePlan: + if id := m.plan; id != nil { + return []ent.Value{*id} + } + case planaddon.EdgeAddon: + if id := m.addon; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *PlanAddonMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *PlanAddonMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *PlanAddonMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedplan { + edges = append(edges, planaddon.EdgePlan) + } + if m.clearedaddon { + edges = append(edges, planaddon.EdgeAddon) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *PlanAddonMutation) EdgeCleared(name string) bool { + switch name { + case planaddon.EdgePlan: + return m.clearedplan + case planaddon.EdgeAddon: + return m.clearedaddon + } + 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 *PlanAddonMutation) ClearEdge(name string) error { + switch name { + case planaddon.EdgePlan: + m.ClearPlan() + return nil + case planaddon.EdgeAddon: + m.ClearAddon() + return nil + } + return fmt.Errorf("unknown PlanAddon 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 *PlanAddonMutation) ResetEdge(name string) error { + switch name { + case planaddon.EdgePlan: + m.ResetPlan() + return nil + case planaddon.EdgeAddon: + m.ResetAddon() + return nil + } + return fmt.Errorf("unknown PlanAddon edge %s", name) +} + +// PlanPhaseMutation represents an operation that mutates the PlanPhase nodes in the graph. +type PlanPhaseMutation struct { + config + op Op + typ string + id *string + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + name *string + description *string + key *string + index *uint8 + addindex *int8 + duration *datetime.ISODurationString + clearedFields map[string]struct{} + plan *string + clearedplan bool + ratecards map[string]struct{} + removedratecards map[string]struct{} + clearedratecards bool + done bool + oldValue func(context.Context) (*PlanPhase, error) + predicates []predicate.PlanPhase +} + +var _ ent.Mutation = (*PlanPhaseMutation)(nil) + +// planphaseOption allows management of the mutation configuration using functional options. +type planphaseOption func(*PlanPhaseMutation) + +// newPlanPhaseMutation creates new mutation for the PlanPhase entity. +func newPlanPhaseMutation(c config, op Op, opts ...planphaseOption) *PlanPhaseMutation { + m := &PlanPhaseMutation{ + config: c, + op: op, + typ: TypePlanPhase, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withPlanPhaseID sets the ID field of the mutation. +func withPlanPhaseID(id string) planphaseOption { + return func(m *PlanPhaseMutation) { + var ( + err error + once sync.Once + value *PlanPhase + ) + m.oldValue = func(ctx context.Context) (*PlanPhase, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().PlanPhase.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withPlanPhase sets the old PlanPhase of the mutation. +func withPlanPhase(node *PlanPhase) planphaseOption { + return func(m *PlanPhaseMutation) { + m.oldValue = func(context.Context) (*PlanPhase, 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 PlanPhaseMutation) 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 PlanPhaseMutation) 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 PlanPhase entities. +func (m *PlanPhaseMutation) 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 *PlanPhaseMutation) 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 *PlanPhaseMutation) 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().PlanPhase.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 *PlanPhaseMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *PlanPhaseMutation) 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 PlanPhase entity. +// If the PlanPhase 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 *PlanPhaseMutation) 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 *PlanPhaseMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *PlanPhaseMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *PlanPhaseMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the PlanPhase entity. +// If the PlanPhase 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 *PlanPhaseMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *PlanPhaseMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[planphase.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *PlanPhaseMutation) MetadataCleared() bool { + _, ok := m.clearedFields[planphase.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *PlanPhaseMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, planphase.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *PlanPhaseMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *PlanPhaseMutation) 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 PlanPhase entity. +// If the PlanPhase 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 *PlanPhaseMutation) 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 *PlanPhaseMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *PlanPhaseMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *PlanPhaseMutation) 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 PlanPhase entity. +// If the PlanPhase 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 *PlanPhaseMutation) 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 *PlanPhaseMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *PlanPhaseMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *PlanPhaseMutation) 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 PlanPhase entity. +// If the PlanPhase 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 *PlanPhaseMutation) 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 *PlanPhaseMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[planphase.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *PlanPhaseMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[planphase.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *PlanPhaseMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, planphase.FieldDeletedAt) +} + +// SetName sets the "name" field. +func (m *PlanPhaseMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *PlanPhaseMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the PlanPhase entity. +// If the PlanPhase 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 *PlanPhaseMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *PlanPhaseMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *PlanPhaseMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *PlanPhaseMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the PlanPhase entity. +// If the PlanPhase 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 *PlanPhaseMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *PlanPhaseMutation) ClearDescription() { + m.description = nil + m.clearedFields[planphase.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *PlanPhaseMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[planphase.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *PlanPhaseMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, planphase.FieldDescription) +} + +// SetKey sets the "key" field. +func (m *PlanPhaseMutation) SetKey(s string) { + m.key = &s +} + +// Key returns the value of the "key" field in the mutation. +func (m *PlanPhaseMutation) Key() (r string, exists bool) { + v := m.key + if v == nil { + return + } + return *v, true +} + +// OldKey returns the old "key" field's value of the PlanPhase entity. +// If the PlanPhase 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 *PlanPhaseMutation) OldKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldKey: %w", err) + } + return oldValue.Key, nil +} + +// ResetKey resets all changes to the "key" field. +func (m *PlanPhaseMutation) ResetKey() { + m.key = nil +} + +// SetPlanID sets the "plan_id" field. +func (m *PlanPhaseMutation) SetPlanID(s string) { + m.plan = &s +} + +// PlanID returns the value of the "plan_id" field in the mutation. +func (m *PlanPhaseMutation) PlanID() (r string, exists bool) { + v := m.plan + if v == nil { + return + } + return *v, true +} + +// OldPlanID returns the old "plan_id" field's value of the PlanPhase entity. +// If the PlanPhase 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 *PlanPhaseMutation) OldPlanID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPlanID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPlanID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPlanID: %w", err) + } + return oldValue.PlanID, nil +} + +// ResetPlanID resets all changes to the "plan_id" field. +func (m *PlanPhaseMutation) ResetPlanID() { + m.plan = nil +} + +// SetIndex sets the "index" field. +func (m *PlanPhaseMutation) SetIndex(u uint8) { + m.index = &u + m.addindex = nil +} + +// Index returns the value of the "index" field in the mutation. +func (m *PlanPhaseMutation) Index() (r uint8, exists bool) { + v := m.index + if v == nil { + return + } + return *v, true +} + +// OldIndex returns the old "index" field's value of the PlanPhase entity. +// If the PlanPhase 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 *PlanPhaseMutation) OldIndex(ctx context.Context) (v uint8, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIndex is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIndex requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIndex: %w", err) + } + return oldValue.Index, nil +} + +// AddIndex adds u to the "index" field. +func (m *PlanPhaseMutation) AddIndex(u int8) { + if m.addindex != nil { + *m.addindex += u + } else { + m.addindex = &u + } +} + +// AddedIndex returns the value that was added to the "index" field in this mutation. +func (m *PlanPhaseMutation) AddedIndex() (r int8, exists bool) { + v := m.addindex + if v == nil { + return + } + return *v, true +} + +// ResetIndex resets all changes to the "index" field. +func (m *PlanPhaseMutation) ResetIndex() { + m.index = nil + m.addindex = nil +} + +// SetDuration sets the "duration" field. +func (m *PlanPhaseMutation) SetDuration(dds datetime.ISODurationString) { + m.duration = &dds +} + +// Duration returns the value of the "duration" field in the mutation. +func (m *PlanPhaseMutation) Duration() (r datetime.ISODurationString, exists bool) { + v := m.duration + if v == nil { + return + } + return *v, true +} + +// OldDuration returns the old "duration" field's value of the PlanPhase entity. +// If the PlanPhase 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 *PlanPhaseMutation) OldDuration(ctx context.Context) (v *datetime.ISODurationString, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDuration is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDuration requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDuration: %w", err) + } + return oldValue.Duration, nil +} + +// ClearDuration clears the value of the "duration" field. +func (m *PlanPhaseMutation) ClearDuration() { + m.duration = nil + m.clearedFields[planphase.FieldDuration] = struct{}{} +} + +// DurationCleared returns if the "duration" field was cleared in this mutation. +func (m *PlanPhaseMutation) DurationCleared() bool { + _, ok := m.clearedFields[planphase.FieldDuration] + return ok +} + +// ResetDuration resets all changes to the "duration" field. +func (m *PlanPhaseMutation) ResetDuration() { + m.duration = nil + delete(m.clearedFields, planphase.FieldDuration) +} + +// ClearPlan clears the "plan" edge to the Plan entity. +func (m *PlanPhaseMutation) ClearPlan() { + m.clearedplan = true + m.clearedFields[planphase.FieldPlanID] = struct{}{} +} + +// PlanCleared reports if the "plan" edge to the Plan entity was cleared. +func (m *PlanPhaseMutation) PlanCleared() bool { + return m.clearedplan +} + +// PlanIDs returns the "plan" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// PlanID instead. It exists only for internal usage by the builders. +func (m *PlanPhaseMutation) PlanIDs() (ids []string) { + if id := m.plan; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetPlan resets all changes to the "plan" edge. +func (m *PlanPhaseMutation) ResetPlan() { + m.plan = nil + m.clearedplan = false +} + +// AddRatecardIDs adds the "ratecards" edge to the PlanRateCard entity by ids. +func (m *PlanPhaseMutation) AddRatecardIDs(ids ...string) { + if m.ratecards == nil { + m.ratecards = make(map[string]struct{}) + } + for i := range ids { + m.ratecards[ids[i]] = struct{}{} + } +} + +// ClearRatecards clears the "ratecards" edge to the PlanRateCard entity. +func (m *PlanPhaseMutation) ClearRatecards() { + m.clearedratecards = true +} + +// RatecardsCleared reports if the "ratecards" edge to the PlanRateCard entity was cleared. +func (m *PlanPhaseMutation) RatecardsCleared() bool { + return m.clearedratecards +} + +// RemoveRatecardIDs removes the "ratecards" edge to the PlanRateCard entity by IDs. +func (m *PlanPhaseMutation) RemoveRatecardIDs(ids ...string) { + if m.removedratecards == nil { + m.removedratecards = make(map[string]struct{}) + } + for i := range ids { + delete(m.ratecards, ids[i]) + m.removedratecards[ids[i]] = struct{}{} + } +} + +// RemovedRatecards returns the removed IDs of the "ratecards" edge to the PlanRateCard entity. +func (m *PlanPhaseMutation) RemovedRatecardsIDs() (ids []string) { + for id := range m.removedratecards { + ids = append(ids, id) + } + return +} + +// RatecardsIDs returns the "ratecards" edge IDs in the mutation. +func (m *PlanPhaseMutation) RatecardsIDs() (ids []string) { + for id := range m.ratecards { + ids = append(ids, id) + } + return +} + +// ResetRatecards resets all changes to the "ratecards" edge. +func (m *PlanPhaseMutation) ResetRatecards() { + m.ratecards = nil + m.clearedratecards = false + m.removedratecards = nil +} + +// Where appends a list predicates to the PlanPhaseMutation builder. +func (m *PlanPhaseMutation) Where(ps ...predicate.PlanPhase) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the PlanPhaseMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *PlanPhaseMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.PlanPhase, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *PlanPhaseMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *PlanPhaseMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (PlanPhase). +func (m *PlanPhaseMutation) 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 *PlanPhaseMutation) Fields() []string { + fields := make([]string, 0, 11) + if m.namespace != nil { + fields = append(fields, planphase.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, planphase.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, planphase.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, planphase.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, planphase.FieldDeletedAt) + } + if m.name != nil { + fields = append(fields, planphase.FieldName) + } + if m.description != nil { + fields = append(fields, planphase.FieldDescription) + } + if m.key != nil { + fields = append(fields, planphase.FieldKey) + } + if m.plan != nil { + fields = append(fields, planphase.FieldPlanID) + } + if m.index != nil { + fields = append(fields, planphase.FieldIndex) + } + if m.duration != nil { + fields = append(fields, planphase.FieldDuration) + } + 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 *PlanPhaseMutation) Field(name string) (ent.Value, bool) { + switch name { + case planphase.FieldNamespace: + return m.Namespace() + case planphase.FieldMetadata: + return m.Metadata() + case planphase.FieldCreatedAt: + return m.CreatedAt() + case planphase.FieldUpdatedAt: + return m.UpdatedAt() + case planphase.FieldDeletedAt: + return m.DeletedAt() + case planphase.FieldName: + return m.Name() + case planphase.FieldDescription: + return m.Description() + case planphase.FieldKey: + return m.Key() + case planphase.FieldPlanID: + return m.PlanID() + case planphase.FieldIndex: + return m.Index() + case planphase.FieldDuration: + return m.Duration() + } + 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 *PlanPhaseMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case planphase.FieldNamespace: + return m.OldNamespace(ctx) + case planphase.FieldMetadata: + return m.OldMetadata(ctx) + case planphase.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case planphase.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case planphase.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case planphase.FieldName: + return m.OldName(ctx) + case planphase.FieldDescription: + return m.OldDescription(ctx) + case planphase.FieldKey: + return m.OldKey(ctx) + case planphase.FieldPlanID: + return m.OldPlanID(ctx) + case planphase.FieldIndex: + return m.OldIndex(ctx) + case planphase.FieldDuration: + return m.OldDuration(ctx) + } + return nil, fmt.Errorf("unknown PlanPhase 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 *PlanPhaseMutation) SetField(name string, value ent.Value) error { + switch name { + case planphase.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case planphase.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case planphase.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 planphase.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 planphase.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 planphase.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case planphase.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case planphase.FieldKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKey(v) + return nil + case planphase.FieldPlanID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPlanID(v) + return nil + case planphase.FieldIndex: + v, ok := value.(uint8) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIndex(v) + return nil + case planphase.FieldDuration: + v, ok := value.(datetime.ISODurationString) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDuration(v) + return nil + } + return fmt.Errorf("unknown PlanPhase field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *PlanPhaseMutation) AddedFields() []string { + var fields []string + if m.addindex != nil { + fields = append(fields, planphase.FieldIndex) + } + return fields +} + +// 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 *PlanPhaseMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case planphase.FieldIndex: + return m.AddedIndex() + } + 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 *PlanPhaseMutation) AddField(name string, value ent.Value) error { + switch name { + case planphase.FieldIndex: + v, ok := value.(int8) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddIndex(v) + return nil + } + return fmt.Errorf("unknown PlanPhase numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *PlanPhaseMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(planphase.FieldMetadata) { + fields = append(fields, planphase.FieldMetadata) + } + if m.FieldCleared(planphase.FieldDeletedAt) { + fields = append(fields, planphase.FieldDeletedAt) + } + if m.FieldCleared(planphase.FieldDescription) { + fields = append(fields, planphase.FieldDescription) + } + if m.FieldCleared(planphase.FieldDuration) { + fields = append(fields, planphase.FieldDuration) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *PlanPhaseMutation) 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 *PlanPhaseMutation) ClearField(name string) error { + switch name { + case planphase.FieldMetadata: + m.ClearMetadata() + return nil + case planphase.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case planphase.FieldDescription: + m.ClearDescription() + return nil + case planphase.FieldDuration: + m.ClearDuration() + return nil + } + return fmt.Errorf("unknown PlanPhase 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 *PlanPhaseMutation) ResetField(name string) error { + switch name { + case planphase.FieldNamespace: + m.ResetNamespace() + return nil + case planphase.FieldMetadata: + m.ResetMetadata() + return nil + case planphase.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case planphase.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case planphase.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case planphase.FieldName: + m.ResetName() + return nil + case planphase.FieldDescription: + m.ResetDescription() + return nil + case planphase.FieldKey: + m.ResetKey() + return nil + case planphase.FieldPlanID: + m.ResetPlanID() + return nil + case planphase.FieldIndex: + m.ResetIndex() + return nil + case planphase.FieldDuration: + m.ResetDuration() + return nil + } + return fmt.Errorf("unknown PlanPhase field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *PlanPhaseMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.plan != nil { + edges = append(edges, planphase.EdgePlan) + } + if m.ratecards != nil { + edges = append(edges, planphase.EdgeRatecards) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *PlanPhaseMutation) AddedIDs(name string) []ent.Value { + switch name { + case planphase.EdgePlan: + if id := m.plan; id != nil { + return []ent.Value{*id} + } + case planphase.EdgeRatecards: + ids := make([]ent.Value, 0, len(m.ratecards)) + for id := range m.ratecards { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *PlanPhaseMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedratecards != nil { + edges = append(edges, planphase.EdgeRatecards) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *PlanPhaseMutation) RemovedIDs(name string) []ent.Value { + switch name { + case planphase.EdgeRatecards: + ids := make([]ent.Value, 0, len(m.removedratecards)) + for id := range m.removedratecards { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *PlanPhaseMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedplan { + edges = append(edges, planphase.EdgePlan) + } + if m.clearedratecards { + edges = append(edges, planphase.EdgeRatecards) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *PlanPhaseMutation) EdgeCleared(name string) bool { + switch name { + case planphase.EdgePlan: + return m.clearedplan + case planphase.EdgeRatecards: + return m.clearedratecards + } + 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 *PlanPhaseMutation) ClearEdge(name string) error { + switch name { + case planphase.EdgePlan: + m.ClearPlan() + return nil + } + return fmt.Errorf("unknown PlanPhase 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 *PlanPhaseMutation) ResetEdge(name string) error { + switch name { + case planphase.EdgePlan: + m.ResetPlan() + return nil + case planphase.EdgeRatecards: + m.ResetRatecards() + return nil + } + return fmt.Errorf("unknown PlanPhase edge %s", name) +} + +// PlanRateCardMutation represents an operation that mutates the PlanRateCard nodes in the graph. +type PlanRateCardMutation struct { + config + op Op + typ string + id *string + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + name *string + description *string + key *string + tax_behavior *productcatalog.TaxBehavior + _type *productcatalog.RateCardType + feature_key *string + entitlement_template **productcatalog.EntitlementTemplate + tax_config **productcatalog.TaxConfig + billing_cadence *datetime.ISODurationString + price **productcatalog.Price + discounts **productcatalog.Discounts + unit_config **productcatalog.UnitConfig + clearedFields map[string]struct{} + phase *string + clearedphase bool + features *string + clearedfeatures bool + tax_code *string + clearedtax_code bool + done bool + oldValue func(context.Context) (*PlanRateCard, error) + predicates []predicate.PlanRateCard +} + +var _ ent.Mutation = (*PlanRateCardMutation)(nil) + +// planratecardOption allows management of the mutation configuration using functional options. +type planratecardOption func(*PlanRateCardMutation) + +// newPlanRateCardMutation creates new mutation for the PlanRateCard entity. +func newPlanRateCardMutation(c config, op Op, opts ...planratecardOption) *PlanRateCardMutation { + m := &PlanRateCardMutation{ + config: c, + op: op, + typ: TypePlanRateCard, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withPlanRateCardID sets the ID field of the mutation. +func withPlanRateCardID(id string) planratecardOption { + return func(m *PlanRateCardMutation) { + var ( + err error + once sync.Once + value *PlanRateCard + ) + m.oldValue = func(ctx context.Context) (*PlanRateCard, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().PlanRateCard.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withPlanRateCard sets the old PlanRateCard of the mutation. +func withPlanRateCard(node *PlanRateCard) planratecardOption { + return func(m *PlanRateCardMutation) { + m.oldValue = func(context.Context) (*PlanRateCard, 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 PlanRateCardMutation) 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 PlanRateCardMutation) 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 PlanRateCard entities. +func (m *PlanRateCardMutation) 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 *PlanRateCardMutation) 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 *PlanRateCardMutation) 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().PlanRateCard.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 *PlanRateCardMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *PlanRateCardMutation) 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 PlanRateCard entity. +// If the PlanRateCard 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 *PlanRateCardMutation) 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 *PlanRateCardMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *PlanRateCardMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *PlanRateCardMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the PlanRateCard entity. +// If the PlanRateCard 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 *PlanRateCardMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *PlanRateCardMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[planratecard.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *PlanRateCardMutation) MetadataCleared() bool { + _, ok := m.clearedFields[planratecard.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *PlanRateCardMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, planratecard.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *PlanRateCardMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *PlanRateCardMutation) 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 PlanRateCard entity. +// If the PlanRateCard 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 *PlanRateCardMutation) 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 *PlanRateCardMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *PlanRateCardMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *PlanRateCardMutation) 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 PlanRateCard entity. +// If the PlanRateCard 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 *PlanRateCardMutation) 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 *PlanRateCardMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *PlanRateCardMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *PlanRateCardMutation) 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 PlanRateCard entity. +// If the PlanRateCard 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 *PlanRateCardMutation) 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 *PlanRateCardMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[planratecard.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *PlanRateCardMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[planratecard.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *PlanRateCardMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, planratecard.FieldDeletedAt) +} + +// SetName sets the "name" field. +func (m *PlanRateCardMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *PlanRateCardMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the PlanRateCard entity. +// If the PlanRateCard 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 *PlanRateCardMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *PlanRateCardMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *PlanRateCardMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *PlanRateCardMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the PlanRateCard entity. +// If the PlanRateCard 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 *PlanRateCardMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *PlanRateCardMutation) ClearDescription() { + m.description = nil + m.clearedFields[planratecard.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *PlanRateCardMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[planratecard.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *PlanRateCardMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, planratecard.FieldDescription) +} + +// SetKey sets the "key" field. +func (m *PlanRateCardMutation) SetKey(s string) { + m.key = &s +} + +// Key returns the value of the "key" field in the mutation. +func (m *PlanRateCardMutation) Key() (r string, exists bool) { + v := m.key + if v == nil { + return + } + return *v, true +} + +// OldKey returns the old "key" field's value of the PlanRateCard entity. +// If the PlanRateCard 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 *PlanRateCardMutation) OldKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldKey: %w", err) + } + return oldValue.Key, nil +} + +// ResetKey resets all changes to the "key" field. +func (m *PlanRateCardMutation) ResetKey() { + m.key = nil +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (m *PlanRateCardMutation) SetTaxCodeID(s string) { + m.tax_code = &s +} + +// TaxCodeID returns the value of the "tax_code_id" field in the mutation. +func (m *PlanRateCardMutation) TaxCodeID() (r string, exists bool) { + v := m.tax_code + if v == nil { + return + } + return *v, true +} + +// OldTaxCodeID returns the old "tax_code_id" field's value of the PlanRateCard entity. +// If the PlanRateCard 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 *PlanRateCardMutation) OldTaxCodeID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxCodeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxCodeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxCodeID: %w", err) + } + return oldValue.TaxCodeID, nil +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (m *PlanRateCardMutation) ClearTaxCodeID() { + m.tax_code = nil + m.clearedFields[planratecard.FieldTaxCodeID] = struct{}{} +} + +// TaxCodeIDCleared returns if the "tax_code_id" field was cleared in this mutation. +func (m *PlanRateCardMutation) TaxCodeIDCleared() bool { + _, ok := m.clearedFields[planratecard.FieldTaxCodeID] + return ok +} + +// ResetTaxCodeID resets all changes to the "tax_code_id" field. +func (m *PlanRateCardMutation) ResetTaxCodeID() { + m.tax_code = nil + delete(m.clearedFields, planratecard.FieldTaxCodeID) +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (m *PlanRateCardMutation) SetTaxBehavior(pb productcatalog.TaxBehavior) { + m.tax_behavior = &pb +} + +// TaxBehavior returns the value of the "tax_behavior" field in the mutation. +func (m *PlanRateCardMutation) TaxBehavior() (r productcatalog.TaxBehavior, exists bool) { + v := m.tax_behavior + if v == nil { + return + } + return *v, true +} + +// OldTaxBehavior returns the old "tax_behavior" field's value of the PlanRateCard entity. +// If the PlanRateCard 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 *PlanRateCardMutation) OldTaxBehavior(ctx context.Context) (v *productcatalog.TaxBehavior, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxBehavior is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxBehavior requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxBehavior: %w", err) + } + return oldValue.TaxBehavior, nil +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (m *PlanRateCardMutation) ClearTaxBehavior() { + m.tax_behavior = nil + m.clearedFields[planratecard.FieldTaxBehavior] = struct{}{} +} + +// TaxBehaviorCleared returns if the "tax_behavior" field was cleared in this mutation. +func (m *PlanRateCardMutation) TaxBehaviorCleared() bool { + _, ok := m.clearedFields[planratecard.FieldTaxBehavior] + return ok +} + +// ResetTaxBehavior resets all changes to the "tax_behavior" field. +func (m *PlanRateCardMutation) ResetTaxBehavior() { + m.tax_behavior = nil + delete(m.clearedFields, planratecard.FieldTaxBehavior) +} + +// SetType sets the "type" field. +func (m *PlanRateCardMutation) SetType(pct productcatalog.RateCardType) { + m._type = &pct +} + +// GetType returns the value of the "type" field in the mutation. +func (m *PlanRateCardMutation) GetType() (r productcatalog.RateCardType, exists bool) { + v := m._type + if v == nil { + return + } + return *v, true +} + +// OldType returns the old "type" field's value of the PlanRateCard entity. +// If the PlanRateCard 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 *PlanRateCardMutation) OldType(ctx context.Context) (v productcatalog.RateCardType, 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 *PlanRateCardMutation) ResetType() { + m._type = nil +} + +// SetFeatureKey sets the "feature_key" field. +func (m *PlanRateCardMutation) SetFeatureKey(s string) { + m.feature_key = &s +} + +// FeatureKey returns the value of the "feature_key" field in the mutation. +func (m *PlanRateCardMutation) 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 PlanRateCard entity. +// If the PlanRateCard 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 *PlanRateCardMutation) 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 +} + +// ClearFeatureKey clears the value of the "feature_key" field. +func (m *PlanRateCardMutation) ClearFeatureKey() { + m.feature_key = nil + m.clearedFields[planratecard.FieldFeatureKey] = struct{}{} +} + +// FeatureKeyCleared returns if the "feature_key" field was cleared in this mutation. +func (m *PlanRateCardMutation) FeatureKeyCleared() bool { + _, ok := m.clearedFields[planratecard.FieldFeatureKey] + return ok +} + +// ResetFeatureKey resets all changes to the "feature_key" field. +func (m *PlanRateCardMutation) ResetFeatureKey() { + m.feature_key = nil + delete(m.clearedFields, planratecard.FieldFeatureKey) +} + +// SetEntitlementTemplate sets the "entitlement_template" field. +func (m *PlanRateCardMutation) SetEntitlementTemplate(pt *productcatalog.EntitlementTemplate) { + m.entitlement_template = &pt +} + +// EntitlementTemplate returns the value of the "entitlement_template" field in the mutation. +func (m *PlanRateCardMutation) EntitlementTemplate() (r *productcatalog.EntitlementTemplate, exists bool) { + v := m.entitlement_template + if v == nil { + return + } + return *v, true +} + +// OldEntitlementTemplate returns the old "entitlement_template" field's value of the PlanRateCard entity. +// If the PlanRateCard 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 *PlanRateCardMutation) OldEntitlementTemplate(ctx context.Context) (v *productcatalog.EntitlementTemplate, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEntitlementTemplate is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEntitlementTemplate requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEntitlementTemplate: %w", err) + } + return oldValue.EntitlementTemplate, nil +} + +// ClearEntitlementTemplate clears the value of the "entitlement_template" field. +func (m *PlanRateCardMutation) ClearEntitlementTemplate() { + m.entitlement_template = nil + m.clearedFields[planratecard.FieldEntitlementTemplate] = struct{}{} +} + +// EntitlementTemplateCleared returns if the "entitlement_template" field was cleared in this mutation. +func (m *PlanRateCardMutation) EntitlementTemplateCleared() bool { + _, ok := m.clearedFields[planratecard.FieldEntitlementTemplate] + return ok +} + +// ResetEntitlementTemplate resets all changes to the "entitlement_template" field. +func (m *PlanRateCardMutation) ResetEntitlementTemplate() { + m.entitlement_template = nil + delete(m.clearedFields, planratecard.FieldEntitlementTemplate) +} + +// SetTaxConfig sets the "tax_config" field. +func (m *PlanRateCardMutation) SetTaxConfig(pc *productcatalog.TaxConfig) { + m.tax_config = &pc +} + +// TaxConfig returns the value of the "tax_config" field in the mutation. +func (m *PlanRateCardMutation) TaxConfig() (r *productcatalog.TaxConfig, exists bool) { + v := m.tax_config + if v == nil { + return + } + return *v, true +} + +// OldTaxConfig returns the old "tax_config" field's value of the PlanRateCard entity. +// If the PlanRateCard 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 *PlanRateCardMutation) OldTaxConfig(ctx context.Context) (v *productcatalog.TaxConfig, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxConfig is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxConfig requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxConfig: %w", err) + } + return oldValue.TaxConfig, nil +} + +// ClearTaxConfig clears the value of the "tax_config" field. +func (m *PlanRateCardMutation) ClearTaxConfig() { + m.tax_config = nil + m.clearedFields[planratecard.FieldTaxConfig] = struct{}{} +} + +// TaxConfigCleared returns if the "tax_config" field was cleared in this mutation. +func (m *PlanRateCardMutation) TaxConfigCleared() bool { + _, ok := m.clearedFields[planratecard.FieldTaxConfig] + return ok +} + +// ResetTaxConfig resets all changes to the "tax_config" field. +func (m *PlanRateCardMutation) ResetTaxConfig() { + m.tax_config = nil + delete(m.clearedFields, planratecard.FieldTaxConfig) +} + +// SetBillingCadence sets the "billing_cadence" field. +func (m *PlanRateCardMutation) SetBillingCadence(dds datetime.ISODurationString) { + m.billing_cadence = &dds +} + +// BillingCadence returns the value of the "billing_cadence" field in the mutation. +func (m *PlanRateCardMutation) BillingCadence() (r datetime.ISODurationString, exists bool) { + v := m.billing_cadence + if v == nil { + return + } + return *v, true +} + +// OldBillingCadence returns the old "billing_cadence" field's value of the PlanRateCard entity. +// If the PlanRateCard 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 *PlanRateCardMutation) OldBillingCadence(ctx context.Context) (v *datetime.ISODurationString, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingCadence is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingCadence requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingCadence: %w", err) + } + return oldValue.BillingCadence, nil +} + +// ClearBillingCadence clears the value of the "billing_cadence" field. +func (m *PlanRateCardMutation) ClearBillingCadence() { + m.billing_cadence = nil + m.clearedFields[planratecard.FieldBillingCadence] = struct{}{} +} + +// BillingCadenceCleared returns if the "billing_cadence" field was cleared in this mutation. +func (m *PlanRateCardMutation) BillingCadenceCleared() bool { + _, ok := m.clearedFields[planratecard.FieldBillingCadence] + return ok +} + +// ResetBillingCadence resets all changes to the "billing_cadence" field. +func (m *PlanRateCardMutation) ResetBillingCadence() { + m.billing_cadence = nil + delete(m.clearedFields, planratecard.FieldBillingCadence) +} + +// SetPrice sets the "price" field. +func (m *PlanRateCardMutation) SetPrice(pr *productcatalog.Price) { + m.price = &pr +} + +// Price returns the value of the "price" field in the mutation. +func (m *PlanRateCardMutation) 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 PlanRateCard entity. +// If the PlanRateCard 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 *PlanRateCardMutation) 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 +} + +// ClearPrice clears the value of the "price" field. +func (m *PlanRateCardMutation) ClearPrice() { + m.price = nil + m.clearedFields[planratecard.FieldPrice] = struct{}{} +} + +// PriceCleared returns if the "price" field was cleared in this mutation. +func (m *PlanRateCardMutation) PriceCleared() bool { + _, ok := m.clearedFields[planratecard.FieldPrice] + return ok +} + +// ResetPrice resets all changes to the "price" field. +func (m *PlanRateCardMutation) ResetPrice() { + m.price = nil + delete(m.clearedFields, planratecard.FieldPrice) +} + +// SetDiscounts sets the "discounts" field. +func (m *PlanRateCardMutation) SetDiscounts(pr *productcatalog.Discounts) { + m.discounts = &pr +} + +// Discounts returns the value of the "discounts" field in the mutation. +func (m *PlanRateCardMutation) 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 PlanRateCard entity. +// If the PlanRateCard 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 *PlanRateCardMutation) 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 *PlanRateCardMutation) ClearDiscounts() { + m.discounts = nil + m.clearedFields[planratecard.FieldDiscounts] = struct{}{} +} + +// DiscountsCleared returns if the "discounts" field was cleared in this mutation. +func (m *PlanRateCardMutation) DiscountsCleared() bool { + _, ok := m.clearedFields[planratecard.FieldDiscounts] + return ok +} + +// ResetDiscounts resets all changes to the "discounts" field. +func (m *PlanRateCardMutation) ResetDiscounts() { + m.discounts = nil + delete(m.clearedFields, planratecard.FieldDiscounts) +} + +// SetUnitConfig sets the "unit_config" field. +func (m *PlanRateCardMutation) SetUnitConfig(pc *productcatalog.UnitConfig) { + m.unit_config = &pc +} + +// UnitConfig returns the value of the "unit_config" field in the mutation. +func (m *PlanRateCardMutation) UnitConfig() (r *productcatalog.UnitConfig, exists bool) { + v := m.unit_config + if v == nil { + return + } + return *v, true +} + +// OldUnitConfig returns the old "unit_config" field's value of the PlanRateCard entity. +// If the PlanRateCard 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 *PlanRateCardMutation) OldUnitConfig(ctx context.Context) (v *productcatalog.UnitConfig, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUnitConfig is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUnitConfig requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUnitConfig: %w", err) + } + return oldValue.UnitConfig, nil +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (m *PlanRateCardMutation) ClearUnitConfig() { + m.unit_config = nil + m.clearedFields[planratecard.FieldUnitConfig] = struct{}{} +} + +// UnitConfigCleared returns if the "unit_config" field was cleared in this mutation. +func (m *PlanRateCardMutation) UnitConfigCleared() bool { + _, ok := m.clearedFields[planratecard.FieldUnitConfig] + return ok +} + +// ResetUnitConfig resets all changes to the "unit_config" field. +func (m *PlanRateCardMutation) ResetUnitConfig() { + m.unit_config = nil + delete(m.clearedFields, planratecard.FieldUnitConfig) +} + +// SetPhaseID sets the "phase_id" field. +func (m *PlanRateCardMutation) SetPhaseID(s string) { + m.phase = &s +} + +// PhaseID returns the value of the "phase_id" field in the mutation. +func (m *PlanRateCardMutation) PhaseID() (r string, exists bool) { + v := m.phase + if v == nil { + return + } + return *v, true +} + +// OldPhaseID returns the old "phase_id" field's value of the PlanRateCard entity. +// If the PlanRateCard 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 *PlanRateCardMutation) OldPhaseID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPhaseID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPhaseID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPhaseID: %w", err) + } + return oldValue.PhaseID, nil +} + +// ResetPhaseID resets all changes to the "phase_id" field. +func (m *PlanRateCardMutation) ResetPhaseID() { + m.phase = nil +} + +// SetFeatureID sets the "feature_id" field. +func (m *PlanRateCardMutation) SetFeatureID(s string) { + m.features = &s +} + +// FeatureID returns the value of the "feature_id" field in the mutation. +func (m *PlanRateCardMutation) FeatureID() (r string, exists bool) { + v := m.features + if v == nil { + return + } + return *v, true +} + +// OldFeatureID returns the old "feature_id" field's value of the PlanRateCard entity. +// If the PlanRateCard 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 *PlanRateCardMutation) OldFeatureID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFeatureID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFeatureID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFeatureID: %w", err) + } + return oldValue.FeatureID, nil +} + +// ClearFeatureID clears the value of the "feature_id" field. +func (m *PlanRateCardMutation) ClearFeatureID() { + m.features = nil + m.clearedFields[planratecard.FieldFeatureID] = struct{}{} +} + +// FeatureIDCleared returns if the "feature_id" field was cleared in this mutation. +func (m *PlanRateCardMutation) FeatureIDCleared() bool { + _, ok := m.clearedFields[planratecard.FieldFeatureID] + return ok +} + +// ResetFeatureID resets all changes to the "feature_id" field. +func (m *PlanRateCardMutation) ResetFeatureID() { + m.features = nil + delete(m.clearedFields, planratecard.FieldFeatureID) +} + +// ClearPhase clears the "phase" edge to the PlanPhase entity. +func (m *PlanRateCardMutation) ClearPhase() { + m.clearedphase = true + m.clearedFields[planratecard.FieldPhaseID] = struct{}{} +} + +// PhaseCleared reports if the "phase" edge to the PlanPhase entity was cleared. +func (m *PlanRateCardMutation) PhaseCleared() bool { + return m.clearedphase +} + +// PhaseIDs returns the "phase" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// PhaseID instead. It exists only for internal usage by the builders. +func (m *PlanRateCardMutation) PhaseIDs() (ids []string) { + if id := m.phase; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetPhase resets all changes to the "phase" edge. +func (m *PlanRateCardMutation) ResetPhase() { + m.phase = nil + m.clearedphase = false +} + +// SetFeaturesID sets the "features" edge to the Feature entity by id. +func (m *PlanRateCardMutation) SetFeaturesID(id string) { + m.features = &id +} + +// ClearFeatures clears the "features" edge to the Feature entity. +func (m *PlanRateCardMutation) ClearFeatures() { + m.clearedfeatures = true + m.clearedFields[planratecard.FieldFeatureID] = struct{}{} +} + +// FeaturesCleared reports if the "features" edge to the Feature entity was cleared. +func (m *PlanRateCardMutation) FeaturesCleared() bool { + return m.FeatureIDCleared() || m.clearedfeatures +} + +// FeaturesID returns the "features" edge ID in the mutation. +func (m *PlanRateCardMutation) FeaturesID() (id string, exists bool) { + if m.features != nil { + return *m.features, true + } + return +} + +// FeaturesIDs returns the "features" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// FeaturesID instead. It exists only for internal usage by the builders. +func (m *PlanRateCardMutation) FeaturesIDs() (ids []string) { + if id := m.features; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetFeatures resets all changes to the "features" edge. +func (m *PlanRateCardMutation) ResetFeatures() { + m.features = nil + m.clearedfeatures = false +} + +// ClearTaxCode clears the "tax_code" edge to the TaxCode entity. +func (m *PlanRateCardMutation) ClearTaxCode() { + m.clearedtax_code = true + m.clearedFields[planratecard.FieldTaxCodeID] = struct{}{} +} + +// TaxCodeCleared reports if the "tax_code" edge to the TaxCode entity was cleared. +func (m *PlanRateCardMutation) TaxCodeCleared() bool { + return m.TaxCodeIDCleared() || m.clearedtax_code +} + +// TaxCodeIDs returns the "tax_code" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TaxCodeID instead. It exists only for internal usage by the builders. +func (m *PlanRateCardMutation) TaxCodeIDs() (ids []string) { + if id := m.tax_code; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTaxCode resets all changes to the "tax_code" edge. +func (m *PlanRateCardMutation) ResetTaxCode() { + m.tax_code = nil + m.clearedtax_code = false +} + +// Where appends a list predicates to the PlanRateCardMutation builder. +func (m *PlanRateCardMutation) Where(ps ...predicate.PlanRateCard) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the PlanRateCardMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *PlanRateCardMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.PlanRateCard, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *PlanRateCardMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *PlanRateCardMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (PlanRateCard). +func (m *PlanRateCardMutation) 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 *PlanRateCardMutation) Fields() []string { + fields := make([]string, 0, 20) + if m.namespace != nil { + fields = append(fields, planratecard.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, planratecard.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, planratecard.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, planratecard.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, planratecard.FieldDeletedAt) + } + if m.name != nil { + fields = append(fields, planratecard.FieldName) + } + if m.description != nil { + fields = append(fields, planratecard.FieldDescription) + } + if m.key != nil { + fields = append(fields, planratecard.FieldKey) + } + if m.tax_code != nil { + fields = append(fields, planratecard.FieldTaxCodeID) + } + if m.tax_behavior != nil { + fields = append(fields, planratecard.FieldTaxBehavior) + } + if m._type != nil { + fields = append(fields, planratecard.FieldType) + } + if m.feature_key != nil { + fields = append(fields, planratecard.FieldFeatureKey) + } + if m.entitlement_template != nil { + fields = append(fields, planratecard.FieldEntitlementTemplate) + } + if m.tax_config != nil { + fields = append(fields, planratecard.FieldTaxConfig) + } + if m.billing_cadence != nil { + fields = append(fields, planratecard.FieldBillingCadence) + } + if m.price != nil { + fields = append(fields, planratecard.FieldPrice) + } + if m.discounts != nil { + fields = append(fields, planratecard.FieldDiscounts) + } + if m.unit_config != nil { + fields = append(fields, planratecard.FieldUnitConfig) + } + if m.phase != nil { + fields = append(fields, planratecard.FieldPhaseID) + } + if m.features != nil { + fields = append(fields, planratecard.FieldFeatureID) + } + 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 *PlanRateCardMutation) Field(name string) (ent.Value, bool) { + switch name { + case planratecard.FieldNamespace: + return m.Namespace() + case planratecard.FieldMetadata: + return m.Metadata() + case planratecard.FieldCreatedAt: + return m.CreatedAt() + case planratecard.FieldUpdatedAt: + return m.UpdatedAt() + case planratecard.FieldDeletedAt: + return m.DeletedAt() + case planratecard.FieldName: + return m.Name() + case planratecard.FieldDescription: + return m.Description() + case planratecard.FieldKey: + return m.Key() + case planratecard.FieldTaxCodeID: + return m.TaxCodeID() + case planratecard.FieldTaxBehavior: + return m.TaxBehavior() + case planratecard.FieldType: + return m.GetType() + case planratecard.FieldFeatureKey: + return m.FeatureKey() + case planratecard.FieldEntitlementTemplate: + return m.EntitlementTemplate() + case planratecard.FieldTaxConfig: + return m.TaxConfig() + case planratecard.FieldBillingCadence: + return m.BillingCadence() + case planratecard.FieldPrice: + return m.Price() + case planratecard.FieldDiscounts: + return m.Discounts() + case planratecard.FieldUnitConfig: + return m.UnitConfig() + case planratecard.FieldPhaseID: + return m.PhaseID() + case planratecard.FieldFeatureID: + return m.FeatureID() + } + 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 *PlanRateCardMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case planratecard.FieldNamespace: + return m.OldNamespace(ctx) + case planratecard.FieldMetadata: + return m.OldMetadata(ctx) + case planratecard.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case planratecard.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case planratecard.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case planratecard.FieldName: + return m.OldName(ctx) + case planratecard.FieldDescription: + return m.OldDescription(ctx) + case planratecard.FieldKey: + return m.OldKey(ctx) + case planratecard.FieldTaxCodeID: + return m.OldTaxCodeID(ctx) + case planratecard.FieldTaxBehavior: + return m.OldTaxBehavior(ctx) + case planratecard.FieldType: + return m.OldType(ctx) + case planratecard.FieldFeatureKey: + return m.OldFeatureKey(ctx) + case planratecard.FieldEntitlementTemplate: + return m.OldEntitlementTemplate(ctx) + case planratecard.FieldTaxConfig: + return m.OldTaxConfig(ctx) + case planratecard.FieldBillingCadence: + return m.OldBillingCadence(ctx) + case planratecard.FieldPrice: + return m.OldPrice(ctx) + case planratecard.FieldDiscounts: + return m.OldDiscounts(ctx) + case planratecard.FieldUnitConfig: + return m.OldUnitConfig(ctx) + case planratecard.FieldPhaseID: + return m.OldPhaseID(ctx) + case planratecard.FieldFeatureID: + return m.OldFeatureID(ctx) + } + return nil, fmt.Errorf("unknown PlanRateCard 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 *PlanRateCardMutation) SetField(name string, value ent.Value) error { + switch name { + case planratecard.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case planratecard.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case planratecard.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 planratecard.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 planratecard.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 planratecard.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case planratecard.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case planratecard.FieldKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKey(v) + return nil + case planratecard.FieldTaxCodeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxCodeID(v) + return nil + case planratecard.FieldTaxBehavior: + v, ok := value.(productcatalog.TaxBehavior) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxBehavior(v) + return nil + case planratecard.FieldType: + v, ok := value.(productcatalog.RateCardType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case planratecard.FieldFeatureKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFeatureKey(v) + return nil + case planratecard.FieldEntitlementTemplate: + v, ok := value.(*productcatalog.EntitlementTemplate) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEntitlementTemplate(v) + return nil + case planratecard.FieldTaxConfig: + v, ok := value.(*productcatalog.TaxConfig) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxConfig(v) + return nil + case planratecard.FieldBillingCadence: + v, ok := value.(datetime.ISODurationString) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingCadence(v) + return nil + case planratecard.FieldPrice: + v, ok := value.(*productcatalog.Price) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPrice(v) + return nil + case planratecard.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 planratecard.FieldUnitConfig: + v, ok := value.(*productcatalog.UnitConfig) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUnitConfig(v) + return nil + case planratecard.FieldPhaseID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPhaseID(v) + return nil + case planratecard.FieldFeatureID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFeatureID(v) + return nil + } + return fmt.Errorf("unknown PlanRateCard field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *PlanRateCardMutation) 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 *PlanRateCardMutation) 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 *PlanRateCardMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown PlanRateCard numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *PlanRateCardMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(planratecard.FieldMetadata) { + fields = append(fields, planratecard.FieldMetadata) + } + if m.FieldCleared(planratecard.FieldDeletedAt) { + fields = append(fields, planratecard.FieldDeletedAt) + } + if m.FieldCleared(planratecard.FieldDescription) { + fields = append(fields, planratecard.FieldDescription) + } + if m.FieldCleared(planratecard.FieldTaxCodeID) { + fields = append(fields, planratecard.FieldTaxCodeID) + } + if m.FieldCleared(planratecard.FieldTaxBehavior) { + fields = append(fields, planratecard.FieldTaxBehavior) + } + if m.FieldCleared(planratecard.FieldFeatureKey) { + fields = append(fields, planratecard.FieldFeatureKey) + } + if m.FieldCleared(planratecard.FieldEntitlementTemplate) { + fields = append(fields, planratecard.FieldEntitlementTemplate) + } + if m.FieldCleared(planratecard.FieldTaxConfig) { + fields = append(fields, planratecard.FieldTaxConfig) + } + if m.FieldCleared(planratecard.FieldBillingCadence) { + fields = append(fields, planratecard.FieldBillingCadence) + } + if m.FieldCleared(planratecard.FieldPrice) { + fields = append(fields, planratecard.FieldPrice) + } + if m.FieldCleared(planratecard.FieldDiscounts) { + fields = append(fields, planratecard.FieldDiscounts) + } + if m.FieldCleared(planratecard.FieldUnitConfig) { + fields = append(fields, planratecard.FieldUnitConfig) + } + if m.FieldCleared(planratecard.FieldFeatureID) { + fields = append(fields, planratecard.FieldFeatureID) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *PlanRateCardMutation) 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 *PlanRateCardMutation) ClearField(name string) error { + switch name { + case planratecard.FieldMetadata: + m.ClearMetadata() + return nil + case planratecard.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case planratecard.FieldDescription: + m.ClearDescription() + return nil + case planratecard.FieldTaxCodeID: + m.ClearTaxCodeID() + return nil + case planratecard.FieldTaxBehavior: + m.ClearTaxBehavior() + return nil + case planratecard.FieldFeatureKey: + m.ClearFeatureKey() + return nil + case planratecard.FieldEntitlementTemplate: + m.ClearEntitlementTemplate() + return nil + case planratecard.FieldTaxConfig: + m.ClearTaxConfig() + return nil + case planratecard.FieldBillingCadence: + m.ClearBillingCadence() + return nil + case planratecard.FieldPrice: + m.ClearPrice() + return nil + case planratecard.FieldDiscounts: + m.ClearDiscounts() + return nil + case planratecard.FieldUnitConfig: + m.ClearUnitConfig() + return nil + case planratecard.FieldFeatureID: + m.ClearFeatureID() + return nil + } + return fmt.Errorf("unknown PlanRateCard 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 *PlanRateCardMutation) ResetField(name string) error { + switch name { + case planratecard.FieldNamespace: + m.ResetNamespace() + return nil + case planratecard.FieldMetadata: + m.ResetMetadata() + return nil + case planratecard.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case planratecard.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case planratecard.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case planratecard.FieldName: + m.ResetName() + return nil + case planratecard.FieldDescription: + m.ResetDescription() + return nil + case planratecard.FieldKey: + m.ResetKey() + return nil + case planratecard.FieldTaxCodeID: + m.ResetTaxCodeID() + return nil + case planratecard.FieldTaxBehavior: + m.ResetTaxBehavior() + return nil + case planratecard.FieldType: + m.ResetType() + return nil + case planratecard.FieldFeatureKey: + m.ResetFeatureKey() + return nil + case planratecard.FieldEntitlementTemplate: + m.ResetEntitlementTemplate() + return nil + case planratecard.FieldTaxConfig: + m.ResetTaxConfig() + return nil + case planratecard.FieldBillingCadence: + m.ResetBillingCadence() + return nil + case planratecard.FieldPrice: + m.ResetPrice() + return nil + case planratecard.FieldDiscounts: + m.ResetDiscounts() + return nil + case planratecard.FieldUnitConfig: + m.ResetUnitConfig() + return nil + case planratecard.FieldPhaseID: + m.ResetPhaseID() + return nil + case planratecard.FieldFeatureID: + m.ResetFeatureID() + return nil + } + return fmt.Errorf("unknown PlanRateCard field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *PlanRateCardMutation) AddedEdges() []string { + edges := make([]string, 0, 3) + if m.phase != nil { + edges = append(edges, planratecard.EdgePhase) + } + if m.features != nil { + edges = append(edges, planratecard.EdgeFeatures) + } + if m.tax_code != nil { + edges = append(edges, planratecard.EdgeTaxCode) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *PlanRateCardMutation) AddedIDs(name string) []ent.Value { + switch name { + case planratecard.EdgePhase: + if id := m.phase; id != nil { + return []ent.Value{*id} + } + case planratecard.EdgeFeatures: + if id := m.features; id != nil { + return []ent.Value{*id} + } + case planratecard.EdgeTaxCode: + if id := m.tax_code; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *PlanRateCardMutation) RemovedEdges() []string { + edges := make([]string, 0, 3) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *PlanRateCardMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *PlanRateCardMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) + if m.clearedphase { + edges = append(edges, planratecard.EdgePhase) + } + if m.clearedfeatures { + edges = append(edges, planratecard.EdgeFeatures) + } + if m.clearedtax_code { + edges = append(edges, planratecard.EdgeTaxCode) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *PlanRateCardMutation) EdgeCleared(name string) bool { + switch name { + case planratecard.EdgePhase: + return m.clearedphase + case planratecard.EdgeFeatures: + return m.clearedfeatures + case planratecard.EdgeTaxCode: + return m.clearedtax_code + } + 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 *PlanRateCardMutation) ClearEdge(name string) error { + switch name { + case planratecard.EdgePhase: + m.ClearPhase() + return nil + case planratecard.EdgeFeatures: + m.ClearFeatures() + return nil + case planratecard.EdgeTaxCode: + m.ClearTaxCode() + return nil + } + return fmt.Errorf("unknown PlanRateCard 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 *PlanRateCardMutation) ResetEdge(name string) error { + switch name { + case planratecard.EdgePhase: + m.ResetPhase() + return nil + case planratecard.EdgeFeatures: + m.ResetFeatures() + return nil + case planratecard.EdgeTaxCode: + m.ResetTaxCode() + return nil + } + return fmt.Errorf("unknown PlanRateCard edge %s", name) +} + +// SubjectMutation represents an operation that mutates the Subject nodes in the graph. +type SubjectMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + key *string + display_name *string + stripe_customer_id *string + metadata *map[string]interface{} + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Subject, error) + predicates []predicate.Subject +} + +var _ ent.Mutation = (*SubjectMutation)(nil) + +// subjectOption allows management of the mutation configuration using functional options. +type subjectOption func(*SubjectMutation) + +// newSubjectMutation creates new mutation for the Subject entity. +func newSubjectMutation(c config, op Op, opts ...subjectOption) *SubjectMutation { + m := &SubjectMutation{ + config: c, + op: op, + typ: TypeSubject, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withSubjectID sets the ID field of the mutation. +func withSubjectID(id string) subjectOption { + return func(m *SubjectMutation) { + var ( + err error + once sync.Once + value *Subject + ) + m.oldValue = func(ctx context.Context) (*Subject, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Subject.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withSubject sets the old Subject of the mutation. +func withSubject(node *Subject) subjectOption { + return func(m *SubjectMutation) { + m.oldValue = func(context.Context) (*Subject, 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 SubjectMutation) 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 SubjectMutation) 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 Subject entities. +func (m *SubjectMutation) 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 *SubjectMutation) 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 *SubjectMutation) 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().Subject.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 *SubjectMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *SubjectMutation) 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 Subject entity. +// If the Subject 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 *SubjectMutation) 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 *SubjectMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *SubjectMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *SubjectMutation) 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 Subject entity. +// If the Subject 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 *SubjectMutation) 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 *SubjectMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *SubjectMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *SubjectMutation) 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 Subject entity. +// If the Subject 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 *SubjectMutation) 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 *SubjectMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *SubjectMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *SubjectMutation) 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 Subject entity. +// If the Subject 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 *SubjectMutation) 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 *SubjectMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[subject.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *SubjectMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[subject.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *SubjectMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, subject.FieldDeletedAt) +} + +// SetKey sets the "key" field. +func (m *SubjectMutation) SetKey(s string) { + m.key = &s +} + +// Key returns the value of the "key" field in the mutation. +func (m *SubjectMutation) Key() (r string, exists bool) { + v := m.key + if v == nil { + return + } + return *v, true +} + +// OldKey returns the old "key" field's value of the Subject entity. +// If the Subject 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 *SubjectMutation) OldKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldKey: %w", err) + } + return oldValue.Key, nil +} + +// ResetKey resets all changes to the "key" field. +func (m *SubjectMutation) ResetKey() { + m.key = nil +} + +// SetDisplayName sets the "display_name" field. +func (m *SubjectMutation) SetDisplayName(s string) { + m.display_name = &s +} + +// DisplayName returns the value of the "display_name" field in the mutation. +func (m *SubjectMutation) DisplayName() (r string, exists bool) { + v := m.display_name + if v == nil { + return + } + return *v, true +} + +// OldDisplayName returns the old "display_name" field's value of the Subject entity. +// If the Subject 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 *SubjectMutation) OldDisplayName(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDisplayName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDisplayName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDisplayName: %w", err) + } + return oldValue.DisplayName, nil +} + +// ClearDisplayName clears the value of the "display_name" field. +func (m *SubjectMutation) ClearDisplayName() { + m.display_name = nil + m.clearedFields[subject.FieldDisplayName] = struct{}{} +} + +// DisplayNameCleared returns if the "display_name" field was cleared in this mutation. +func (m *SubjectMutation) DisplayNameCleared() bool { + _, ok := m.clearedFields[subject.FieldDisplayName] + return ok +} + +// ResetDisplayName resets all changes to the "display_name" field. +func (m *SubjectMutation) ResetDisplayName() { + m.display_name = nil + delete(m.clearedFields, subject.FieldDisplayName) +} + +// SetStripeCustomerID sets the "stripe_customer_id" field. +func (m *SubjectMutation) SetStripeCustomerID(s string) { + m.stripe_customer_id = &s +} + +// StripeCustomerID returns the value of the "stripe_customer_id" field in the mutation. +func (m *SubjectMutation) StripeCustomerID() (r string, exists bool) { + v := m.stripe_customer_id + if v == nil { + return + } + return *v, true +} + +// OldStripeCustomerID returns the old "stripe_customer_id" field's value of the Subject entity. +// If the Subject 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 *SubjectMutation) OldStripeCustomerID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStripeCustomerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStripeCustomerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStripeCustomerID: %w", err) + } + return oldValue.StripeCustomerID, nil +} + +// ClearStripeCustomerID clears the value of the "stripe_customer_id" field. +func (m *SubjectMutation) ClearStripeCustomerID() { + m.stripe_customer_id = nil + m.clearedFields[subject.FieldStripeCustomerID] = struct{}{} +} + +// StripeCustomerIDCleared returns if the "stripe_customer_id" field was cleared in this mutation. +func (m *SubjectMutation) StripeCustomerIDCleared() bool { + _, ok := m.clearedFields[subject.FieldStripeCustomerID] + return ok +} + +// ResetStripeCustomerID resets all changes to the "stripe_customer_id" field. +func (m *SubjectMutation) ResetStripeCustomerID() { + m.stripe_customer_id = nil + delete(m.clearedFields, subject.FieldStripeCustomerID) +} + +// SetMetadata sets the "metadata" field. +func (m *SubjectMutation) SetMetadata(value map[string]interface{}) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *SubjectMutation) Metadata() (r map[string]interface{}, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the Subject entity. +// If the Subject 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 *SubjectMutation) OldMetadata(ctx context.Context) (v map[string]interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *SubjectMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[subject.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *SubjectMutation) MetadataCleared() bool { + _, ok := m.clearedFields[subject.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *SubjectMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, subject.FieldMetadata) +} + +// Where appends a list predicates to the SubjectMutation builder. +func (m *SubjectMutation) Where(ps ...predicate.Subject) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SubjectMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SubjectMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Subject, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *SubjectMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *SubjectMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Subject). +func (m *SubjectMutation) 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 *SubjectMutation) Fields() []string { + fields := make([]string, 0, 8) + if m.namespace != nil { + fields = append(fields, subject.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, subject.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, subject.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, subject.FieldDeletedAt) + } + if m.key != nil { + fields = append(fields, subject.FieldKey) + } + if m.display_name != nil { + fields = append(fields, subject.FieldDisplayName) + } + if m.stripe_customer_id != nil { + fields = append(fields, subject.FieldStripeCustomerID) + } + if m.metadata != nil { + fields = append(fields, subject.FieldMetadata) + } + 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 *SubjectMutation) Field(name string) (ent.Value, bool) { + switch name { + case subject.FieldNamespace: + return m.Namespace() + case subject.FieldCreatedAt: + return m.CreatedAt() + case subject.FieldUpdatedAt: + return m.UpdatedAt() + case subject.FieldDeletedAt: + return m.DeletedAt() + case subject.FieldKey: + return m.Key() + case subject.FieldDisplayName: + return m.DisplayName() + case subject.FieldStripeCustomerID: + return m.StripeCustomerID() + case subject.FieldMetadata: + return m.Metadata() + } + 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 *SubjectMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case subject.FieldNamespace: + return m.OldNamespace(ctx) + case subject.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case subject.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case subject.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case subject.FieldKey: + return m.OldKey(ctx) + case subject.FieldDisplayName: + return m.OldDisplayName(ctx) + case subject.FieldStripeCustomerID: + return m.OldStripeCustomerID(ctx) + case subject.FieldMetadata: + return m.OldMetadata(ctx) + } + return nil, fmt.Errorf("unknown Subject 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 *SubjectMutation) SetField(name string, value ent.Value) error { + switch name { + case subject.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case subject.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 subject.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 subject.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 subject.FieldKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKey(v) + return nil + case subject.FieldDisplayName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDisplayName(v) + return nil + case subject.FieldStripeCustomerID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStripeCustomerID(v) + return nil + case subject.FieldMetadata: + v, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + } + return fmt.Errorf("unknown Subject field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SubjectMutation) 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 *SubjectMutation) 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 *SubjectMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Subject numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SubjectMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(subject.FieldDeletedAt) { + fields = append(fields, subject.FieldDeletedAt) + } + if m.FieldCleared(subject.FieldDisplayName) { + fields = append(fields, subject.FieldDisplayName) + } + if m.FieldCleared(subject.FieldStripeCustomerID) { + fields = append(fields, subject.FieldStripeCustomerID) + } + if m.FieldCleared(subject.FieldMetadata) { + fields = append(fields, subject.FieldMetadata) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SubjectMutation) 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 *SubjectMutation) ClearField(name string) error { + switch name { + case subject.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case subject.FieldDisplayName: + m.ClearDisplayName() + return nil + case subject.FieldStripeCustomerID: + m.ClearStripeCustomerID() + return nil + case subject.FieldMetadata: + m.ClearMetadata() + return nil + } + return fmt.Errorf("unknown Subject 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 *SubjectMutation) ResetField(name string) error { + switch name { + case subject.FieldNamespace: + m.ResetNamespace() + return nil + case subject.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case subject.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case subject.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case subject.FieldKey: + m.ResetKey() + return nil + case subject.FieldDisplayName: + m.ResetDisplayName() + return nil + case subject.FieldStripeCustomerID: + m.ResetStripeCustomerID() + return nil + case subject.FieldMetadata: + m.ResetMetadata() + return nil + } + return fmt.Errorf("unknown Subject field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SubjectMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *SubjectMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SubjectMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *SubjectMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SubjectMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *SubjectMutation) EdgeCleared(name string) bool { + 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 *SubjectMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Subject 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 *SubjectMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Subject edge %s", name) +} + +// SubscriptionMutation represents an operation that mutates the Subscription nodes in the graph. +type SubscriptionMutation struct { + config + op Op + typ string + id *string + namespace *string + annotations *models.Annotations + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + metadata *map[string]string + active_from *time.Time + active_to *time.Time + name *string + description *string + currency *currencyx.Code + billing_anchor *time.Time + billing_cadence *datetime.ISODurationString + pro_rating_config *productcatalog.ProRatingConfig + settlement_mode *productcatalog.SettlementMode + clearedFields map[string]struct{} + plan *string + clearedplan bool + customer *string + clearedcustomer bool + phases map[string]struct{} + removedphases map[string]struct{} + clearedphases bool + billing_lines map[string]struct{} + removedbilling_lines map[string]struct{} + clearedbilling_lines bool + billing_split_line_groups map[string]struct{} + removedbilling_split_line_groups map[string]struct{} + clearedbilling_split_line_groups bool + charges_usage_based map[string]struct{} + removedcharges_usage_based map[string]struct{} + clearedcharges_usage_based bool + charges_credit_purchase map[string]struct{} + removedcharges_credit_purchase map[string]struct{} + clearedcharges_credit_purchase bool + charges_flat_fee map[string]struct{} + removedcharges_flat_fee map[string]struct{} + clearedcharges_flat_fee bool + addons map[string]struct{} + removedaddons map[string]struct{} + clearedaddons bool + billing_sync_state *string + clearedbilling_sync_state bool + done bool + oldValue func(context.Context) (*Subscription, error) + predicates []predicate.Subscription +} + +var _ ent.Mutation = (*SubscriptionMutation)(nil) + +// subscriptionOption allows management of the mutation configuration using functional options. +type subscriptionOption func(*SubscriptionMutation) + +// newSubscriptionMutation creates new mutation for the Subscription entity. +func newSubscriptionMutation(c config, op Op, opts ...subscriptionOption) *SubscriptionMutation { + m := &SubscriptionMutation{ + config: c, + op: op, + typ: TypeSubscription, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withSubscriptionID sets the ID field of the mutation. +func withSubscriptionID(id string) subscriptionOption { + return func(m *SubscriptionMutation) { + var ( + err error + once sync.Once + value *Subscription + ) + m.oldValue = func(ctx context.Context) (*Subscription, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Subscription.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withSubscription sets the old Subscription of the mutation. +func withSubscription(node *Subscription) subscriptionOption { + return func(m *SubscriptionMutation) { + m.oldValue = func(context.Context) (*Subscription, 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 SubscriptionMutation) 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 SubscriptionMutation) 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 Subscription entities. +func (m *SubscriptionMutation) 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 *SubscriptionMutation) 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 *SubscriptionMutation) 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().Subscription.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 *SubscriptionMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *SubscriptionMutation) 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 Subscription entity. +// If the Subscription 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 *SubscriptionMutation) 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 *SubscriptionMutation) ResetNamespace() { + m.namespace = nil +} + +// SetAnnotations sets the "annotations" field. +func (m *SubscriptionMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *SubscriptionMutation) 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 Subscription entity. +// If the Subscription 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 *SubscriptionMutation) 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 *SubscriptionMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[subscription.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *SubscriptionMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[subscription.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *SubscriptionMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, subscription.FieldAnnotations) +} + +// SetCreatedAt sets the "created_at" field. +func (m *SubscriptionMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *SubscriptionMutation) 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 Subscription entity. +// If the Subscription 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 *SubscriptionMutation) 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 *SubscriptionMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *SubscriptionMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *SubscriptionMutation) 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 Subscription entity. +// If the Subscription 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 *SubscriptionMutation) 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 *SubscriptionMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *SubscriptionMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *SubscriptionMutation) 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 Subscription entity. +// If the Subscription 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 *SubscriptionMutation) 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 *SubscriptionMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[subscription.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *SubscriptionMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[subscription.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *SubscriptionMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, subscription.FieldDeletedAt) +} + +// SetMetadata sets the "metadata" field. +func (m *SubscriptionMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *SubscriptionMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the Subscription entity. +// If the Subscription 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 *SubscriptionMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *SubscriptionMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[subscription.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *SubscriptionMutation) MetadataCleared() bool { + _, ok := m.clearedFields[subscription.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *SubscriptionMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, subscription.FieldMetadata) +} + +// SetActiveFrom sets the "active_from" field. +func (m *SubscriptionMutation) SetActiveFrom(t time.Time) { + m.active_from = &t +} + +// ActiveFrom returns the value of the "active_from" field in the mutation. +func (m *SubscriptionMutation) ActiveFrom() (r time.Time, exists bool) { + v := m.active_from + if v == nil { + return + } + return *v, true +} + +// OldActiveFrom returns the old "active_from" field's value of the Subscription entity. +// If the Subscription 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 *SubscriptionMutation) OldActiveFrom(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldActiveFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldActiveFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldActiveFrom: %w", err) + } + return oldValue.ActiveFrom, nil +} + +// ResetActiveFrom resets all changes to the "active_from" field. +func (m *SubscriptionMutation) ResetActiveFrom() { + m.active_from = nil +} + +// SetActiveTo sets the "active_to" field. +func (m *SubscriptionMutation) SetActiveTo(t time.Time) { + m.active_to = &t +} + +// ActiveTo returns the value of the "active_to" field in the mutation. +func (m *SubscriptionMutation) ActiveTo() (r time.Time, exists bool) { + v := m.active_to + if v == nil { + return + } + return *v, true +} + +// OldActiveTo returns the old "active_to" field's value of the Subscription entity. +// If the Subscription 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 *SubscriptionMutation) OldActiveTo(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldActiveTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldActiveTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldActiveTo: %w", err) + } + return oldValue.ActiveTo, nil +} + +// ClearActiveTo clears the value of the "active_to" field. +func (m *SubscriptionMutation) ClearActiveTo() { + m.active_to = nil + m.clearedFields[subscription.FieldActiveTo] = struct{}{} +} + +// ActiveToCleared returns if the "active_to" field was cleared in this mutation. +func (m *SubscriptionMutation) ActiveToCleared() bool { + _, ok := m.clearedFields[subscription.FieldActiveTo] + return ok +} + +// ResetActiveTo resets all changes to the "active_to" field. +func (m *SubscriptionMutation) ResetActiveTo() { + m.active_to = nil + delete(m.clearedFields, subscription.FieldActiveTo) +} + +// SetName sets the "name" field. +func (m *SubscriptionMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *SubscriptionMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the Subscription entity. +// If the Subscription 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 *SubscriptionMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *SubscriptionMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *SubscriptionMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *SubscriptionMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the Subscription entity. +// If the Subscription 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 *SubscriptionMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *SubscriptionMutation) ClearDescription() { + m.description = nil + m.clearedFields[subscription.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *SubscriptionMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[subscription.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *SubscriptionMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, subscription.FieldDescription) +} + +// SetPlanID sets the "plan_id" field. +func (m *SubscriptionMutation) SetPlanID(s string) { + m.plan = &s +} + +// PlanID returns the value of the "plan_id" field in the mutation. +func (m *SubscriptionMutation) PlanID() (r string, exists bool) { + v := m.plan + if v == nil { + return + } + return *v, true +} + +// OldPlanID returns the old "plan_id" field's value of the Subscription entity. +// If the Subscription 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 *SubscriptionMutation) OldPlanID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPlanID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPlanID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPlanID: %w", err) + } + return oldValue.PlanID, nil +} + +// ClearPlanID clears the value of the "plan_id" field. +func (m *SubscriptionMutation) ClearPlanID() { + m.plan = nil + m.clearedFields[subscription.FieldPlanID] = struct{}{} +} + +// PlanIDCleared returns if the "plan_id" field was cleared in this mutation. +func (m *SubscriptionMutation) PlanIDCleared() bool { + _, ok := m.clearedFields[subscription.FieldPlanID] + return ok +} + +// ResetPlanID resets all changes to the "plan_id" field. +func (m *SubscriptionMutation) ResetPlanID() { + m.plan = nil + delete(m.clearedFields, subscription.FieldPlanID) +} + +// SetCustomerID sets the "customer_id" field. +func (m *SubscriptionMutation) SetCustomerID(s string) { + m.customer = &s +} + +// CustomerID returns the value of the "customer_id" field in the mutation. +func (m *SubscriptionMutation) CustomerID() (r string, exists bool) { + v := m.customer + if v == nil { + return + } + return *v, true +} + +// OldCustomerID returns the old "customer_id" field's value of the Subscription entity. +// If the Subscription 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 *SubscriptionMutation) OldCustomerID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerID: %w", err) + } + return oldValue.CustomerID, nil +} + +// ResetCustomerID resets all changes to the "customer_id" field. +func (m *SubscriptionMutation) ResetCustomerID() { + m.customer = nil +} + +// SetCurrency sets the "currency" field. +func (m *SubscriptionMutation) SetCurrency(c currencyx.Code) { + m.currency = &c +} + +// Currency returns the value of the "currency" field in the mutation. +func (m *SubscriptionMutation) Currency() (r currencyx.Code, exists bool) { + v := m.currency + if v == nil { + return + } + return *v, true +} + +// OldCurrency returns the old "currency" field's value of the Subscription entity. +// If the Subscription 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 *SubscriptionMutation) OldCurrency(ctx context.Context) (v currencyx.Code, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCurrency is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCurrency requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCurrency: %w", err) + } + return oldValue.Currency, nil +} + +// ResetCurrency resets all changes to the "currency" field. +func (m *SubscriptionMutation) ResetCurrency() { + m.currency = nil +} + +// SetBillingAnchor sets the "billing_anchor" field. +func (m *SubscriptionMutation) SetBillingAnchor(t time.Time) { + m.billing_anchor = &t +} + +// BillingAnchor returns the value of the "billing_anchor" field in the mutation. +func (m *SubscriptionMutation) BillingAnchor() (r time.Time, exists bool) { + v := m.billing_anchor + if v == nil { + return + } + return *v, true +} + +// OldBillingAnchor returns the old "billing_anchor" field's value of the Subscription entity. +// If the Subscription 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 *SubscriptionMutation) OldBillingAnchor(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingAnchor is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingAnchor requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingAnchor: %w", err) + } + return oldValue.BillingAnchor, nil +} + +// ResetBillingAnchor resets all changes to the "billing_anchor" field. +func (m *SubscriptionMutation) ResetBillingAnchor() { + m.billing_anchor = nil +} + +// SetBillingCadence sets the "billing_cadence" field. +func (m *SubscriptionMutation) SetBillingCadence(dds datetime.ISODurationString) { + m.billing_cadence = &dds +} + +// BillingCadence returns the value of the "billing_cadence" field in the mutation. +func (m *SubscriptionMutation) BillingCadence() (r datetime.ISODurationString, exists bool) { + v := m.billing_cadence + if v == nil { + return + } + return *v, true +} + +// OldBillingCadence returns the old "billing_cadence" field's value of the Subscription entity. +// If the Subscription 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 *SubscriptionMutation) OldBillingCadence(ctx context.Context) (v datetime.ISODurationString, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingCadence is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingCadence requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingCadence: %w", err) + } + return oldValue.BillingCadence, nil +} + +// ResetBillingCadence resets all changes to the "billing_cadence" field. +func (m *SubscriptionMutation) ResetBillingCadence() { + m.billing_cadence = nil +} + +// SetProRatingConfig sets the "pro_rating_config" field. +func (m *SubscriptionMutation) SetProRatingConfig(prc productcatalog.ProRatingConfig) { + m.pro_rating_config = &prc +} + +// ProRatingConfig returns the value of the "pro_rating_config" field in the mutation. +func (m *SubscriptionMutation) ProRatingConfig() (r productcatalog.ProRatingConfig, exists bool) { + v := m.pro_rating_config + if v == nil { + return + } + return *v, true +} + +// OldProRatingConfig returns the old "pro_rating_config" field's value of the Subscription entity. +// If the Subscription 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 *SubscriptionMutation) OldProRatingConfig(ctx context.Context) (v productcatalog.ProRatingConfig, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldProRatingConfig is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldProRatingConfig requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldProRatingConfig: %w", err) + } + return oldValue.ProRatingConfig, nil +} + +// ResetProRatingConfig resets all changes to the "pro_rating_config" field. +func (m *SubscriptionMutation) ResetProRatingConfig() { + m.pro_rating_config = nil +} + +// SetSettlementMode sets the "settlement_mode" field. +func (m *SubscriptionMutation) SetSettlementMode(pm productcatalog.SettlementMode) { + m.settlement_mode = &pm +} + +// SettlementMode returns the value of the "settlement_mode" field in the mutation. +func (m *SubscriptionMutation) 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 Subscription entity. +// If the Subscription 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 *SubscriptionMutation) 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 *SubscriptionMutation) ResetSettlementMode() { + m.settlement_mode = nil +} + +// ClearPlan clears the "plan" edge to the Plan entity. +func (m *SubscriptionMutation) ClearPlan() { + m.clearedplan = true + m.clearedFields[subscription.FieldPlanID] = struct{}{} +} + +// PlanCleared reports if the "plan" edge to the Plan entity was cleared. +func (m *SubscriptionMutation) PlanCleared() bool { + return m.PlanIDCleared() || m.clearedplan +} + +// PlanIDs returns the "plan" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// PlanID instead. It exists only for internal usage by the builders. +func (m *SubscriptionMutation) PlanIDs() (ids []string) { + if id := m.plan; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetPlan resets all changes to the "plan" edge. +func (m *SubscriptionMutation) ResetPlan() { + m.plan = nil + m.clearedplan = false +} + +// ClearCustomer clears the "customer" edge to the Customer entity. +func (m *SubscriptionMutation) ClearCustomer() { + m.clearedcustomer = true + m.clearedFields[subscription.FieldCustomerID] = struct{}{} +} + +// CustomerCleared reports if the "customer" edge to the Customer entity was cleared. +func (m *SubscriptionMutation) CustomerCleared() bool { + return m.clearedcustomer +} + +// CustomerIDs returns the "customer" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CustomerID instead. It exists only for internal usage by the builders. +func (m *SubscriptionMutation) CustomerIDs() (ids []string) { + if id := m.customer; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCustomer resets all changes to the "customer" edge. +func (m *SubscriptionMutation) ResetCustomer() { + m.customer = nil + m.clearedcustomer = false +} + +// AddPhaseIDs adds the "phases" edge to the SubscriptionPhase entity by ids. +func (m *SubscriptionMutation) AddPhaseIDs(ids ...string) { + if m.phases == nil { + m.phases = make(map[string]struct{}) + } + for i := range ids { + m.phases[ids[i]] = struct{}{} + } +} + +// ClearPhases clears the "phases" edge to the SubscriptionPhase entity. +func (m *SubscriptionMutation) ClearPhases() { + m.clearedphases = true +} + +// PhasesCleared reports if the "phases" edge to the SubscriptionPhase entity was cleared. +func (m *SubscriptionMutation) PhasesCleared() bool { + return m.clearedphases +} + +// RemovePhaseIDs removes the "phases" edge to the SubscriptionPhase entity by IDs. +func (m *SubscriptionMutation) RemovePhaseIDs(ids ...string) { + if m.removedphases == nil { + m.removedphases = make(map[string]struct{}) + } + for i := range ids { + delete(m.phases, ids[i]) + m.removedphases[ids[i]] = struct{}{} + } +} + +// RemovedPhases returns the removed IDs of the "phases" edge to the SubscriptionPhase entity. +func (m *SubscriptionMutation) RemovedPhasesIDs() (ids []string) { + for id := range m.removedphases { + ids = append(ids, id) + } + return +} + +// PhasesIDs returns the "phases" edge IDs in the mutation. +func (m *SubscriptionMutation) PhasesIDs() (ids []string) { + for id := range m.phases { + ids = append(ids, id) + } + return +} + +// ResetPhases resets all changes to the "phases" edge. +func (m *SubscriptionMutation) ResetPhases() { + m.phases = nil + m.clearedphases = false + m.removedphases = nil +} + +// AddBillingLineIDs adds the "billing_lines" edge to the BillingInvoiceLine entity by ids. +func (m *SubscriptionMutation) AddBillingLineIDs(ids ...string) { + if m.billing_lines == nil { + m.billing_lines = make(map[string]struct{}) + } + for i := range ids { + m.billing_lines[ids[i]] = struct{}{} + } +} + +// ClearBillingLines clears the "billing_lines" edge to the BillingInvoiceLine entity. +func (m *SubscriptionMutation) ClearBillingLines() { + m.clearedbilling_lines = true +} + +// BillingLinesCleared reports if the "billing_lines" edge to the BillingInvoiceLine entity was cleared. +func (m *SubscriptionMutation) BillingLinesCleared() bool { + return m.clearedbilling_lines +} + +// RemoveBillingLineIDs removes the "billing_lines" edge to the BillingInvoiceLine entity by IDs. +func (m *SubscriptionMutation) RemoveBillingLineIDs(ids ...string) { + if m.removedbilling_lines == nil { + m.removedbilling_lines = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_lines, ids[i]) + m.removedbilling_lines[ids[i]] = struct{}{} + } +} + +// RemovedBillingLines returns the removed IDs of the "billing_lines" edge to the BillingInvoiceLine entity. +func (m *SubscriptionMutation) RemovedBillingLinesIDs() (ids []string) { + for id := range m.removedbilling_lines { + ids = append(ids, id) + } + return +} + +// BillingLinesIDs returns the "billing_lines" edge IDs in the mutation. +func (m *SubscriptionMutation) BillingLinesIDs() (ids []string) { + for id := range m.billing_lines { + ids = append(ids, id) + } + return +} + +// ResetBillingLines resets all changes to the "billing_lines" edge. +func (m *SubscriptionMutation) ResetBillingLines() { + m.billing_lines = nil + m.clearedbilling_lines = false + m.removedbilling_lines = nil +} + +// AddBillingSplitLineGroupIDs adds the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity by ids. +func (m *SubscriptionMutation) AddBillingSplitLineGroupIDs(ids ...string) { + if m.billing_split_line_groups == nil { + m.billing_split_line_groups = make(map[string]struct{}) + } + for i := range ids { + m.billing_split_line_groups[ids[i]] = struct{}{} + } +} + +// ClearBillingSplitLineGroups clears the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity. +func (m *SubscriptionMutation) ClearBillingSplitLineGroups() { + m.clearedbilling_split_line_groups = true +} + +// BillingSplitLineGroupsCleared reports if the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity was cleared. +func (m *SubscriptionMutation) BillingSplitLineGroupsCleared() bool { + return m.clearedbilling_split_line_groups +} + +// RemoveBillingSplitLineGroupIDs removes the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity by IDs. +func (m *SubscriptionMutation) RemoveBillingSplitLineGroupIDs(ids ...string) { + if m.removedbilling_split_line_groups == nil { + m.removedbilling_split_line_groups = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_split_line_groups, ids[i]) + m.removedbilling_split_line_groups[ids[i]] = struct{}{} + } +} + +// RemovedBillingSplitLineGroups returns the removed IDs of the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity. +func (m *SubscriptionMutation) RemovedBillingSplitLineGroupsIDs() (ids []string) { + for id := range m.removedbilling_split_line_groups { + ids = append(ids, id) + } + return +} + +// BillingSplitLineGroupsIDs returns the "billing_split_line_groups" edge IDs in the mutation. +func (m *SubscriptionMutation) BillingSplitLineGroupsIDs() (ids []string) { + for id := range m.billing_split_line_groups { + ids = append(ids, id) + } + return +} + +// ResetBillingSplitLineGroups resets all changes to the "billing_split_line_groups" edge. +func (m *SubscriptionMutation) ResetBillingSplitLineGroups() { + m.billing_split_line_groups = nil + m.clearedbilling_split_line_groups = false + m.removedbilling_split_line_groups = nil +} + +// AddChargesUsageBasedIDs adds the "charges_usage_based" edge to the ChargeUsageBased entity by ids. +func (m *SubscriptionMutation) AddChargesUsageBasedIDs(ids ...string) { + if m.charges_usage_based == nil { + m.charges_usage_based = make(map[string]struct{}) + } + for i := range ids { + m.charges_usage_based[ids[i]] = struct{}{} + } +} + +// ClearChargesUsageBased clears the "charges_usage_based" edge to the ChargeUsageBased entity. +func (m *SubscriptionMutation) ClearChargesUsageBased() { + m.clearedcharges_usage_based = true +} + +// ChargesUsageBasedCleared reports if the "charges_usage_based" edge to the ChargeUsageBased entity was cleared. +func (m *SubscriptionMutation) ChargesUsageBasedCleared() bool { + return m.clearedcharges_usage_based +} + +// RemoveChargesUsageBasedIDs removes the "charges_usage_based" edge to the ChargeUsageBased entity by IDs. +func (m *SubscriptionMutation) RemoveChargesUsageBasedIDs(ids ...string) { + if m.removedcharges_usage_based == nil { + m.removedcharges_usage_based = make(map[string]struct{}) + } + for i := range ids { + delete(m.charges_usage_based, ids[i]) + m.removedcharges_usage_based[ids[i]] = struct{}{} + } +} + +// RemovedChargesUsageBased returns the removed IDs of the "charges_usage_based" edge to the ChargeUsageBased entity. +func (m *SubscriptionMutation) RemovedChargesUsageBasedIDs() (ids []string) { + for id := range m.removedcharges_usage_based { + ids = append(ids, id) + } + return +} + +// ChargesUsageBasedIDs returns the "charges_usage_based" edge IDs in the mutation. +func (m *SubscriptionMutation) ChargesUsageBasedIDs() (ids []string) { + for id := range m.charges_usage_based { + ids = append(ids, id) + } + return +} + +// ResetChargesUsageBased resets all changes to the "charges_usage_based" edge. +func (m *SubscriptionMutation) ResetChargesUsageBased() { + m.charges_usage_based = nil + m.clearedcharges_usage_based = false + m.removedcharges_usage_based = nil +} + +// AddChargesCreditPurchaseIDs adds the "charges_credit_purchase" edge to the ChargeCreditPurchase entity by ids. +func (m *SubscriptionMutation) AddChargesCreditPurchaseIDs(ids ...string) { + if m.charges_credit_purchase == nil { + m.charges_credit_purchase = make(map[string]struct{}) + } + for i := range ids { + m.charges_credit_purchase[ids[i]] = struct{}{} + } +} + +// ClearChargesCreditPurchase clears the "charges_credit_purchase" edge to the ChargeCreditPurchase entity. +func (m *SubscriptionMutation) ClearChargesCreditPurchase() { + m.clearedcharges_credit_purchase = true +} + +// ChargesCreditPurchaseCleared reports if the "charges_credit_purchase" edge to the ChargeCreditPurchase entity was cleared. +func (m *SubscriptionMutation) ChargesCreditPurchaseCleared() bool { + return m.clearedcharges_credit_purchase +} + +// RemoveChargesCreditPurchaseIDs removes the "charges_credit_purchase" edge to the ChargeCreditPurchase entity by IDs. +func (m *SubscriptionMutation) RemoveChargesCreditPurchaseIDs(ids ...string) { + if m.removedcharges_credit_purchase == nil { + m.removedcharges_credit_purchase = make(map[string]struct{}) + } + for i := range ids { + delete(m.charges_credit_purchase, ids[i]) + m.removedcharges_credit_purchase[ids[i]] = struct{}{} + } +} + +// RemovedChargesCreditPurchase returns the removed IDs of the "charges_credit_purchase" edge to the ChargeCreditPurchase entity. +func (m *SubscriptionMutation) RemovedChargesCreditPurchaseIDs() (ids []string) { + for id := range m.removedcharges_credit_purchase { + ids = append(ids, id) + } + return +} + +// ChargesCreditPurchaseIDs returns the "charges_credit_purchase" edge IDs in the mutation. +func (m *SubscriptionMutation) ChargesCreditPurchaseIDs() (ids []string) { + for id := range m.charges_credit_purchase { + ids = append(ids, id) + } + return +} + +// ResetChargesCreditPurchase resets all changes to the "charges_credit_purchase" edge. +func (m *SubscriptionMutation) ResetChargesCreditPurchase() { + m.charges_credit_purchase = nil + m.clearedcharges_credit_purchase = false + m.removedcharges_credit_purchase = nil +} + +// AddChargesFlatFeeIDs adds the "charges_flat_fee" edge to the ChargeFlatFee entity by ids. +func (m *SubscriptionMutation) AddChargesFlatFeeIDs(ids ...string) { + if m.charges_flat_fee == nil { + m.charges_flat_fee = make(map[string]struct{}) + } + for i := range ids { + m.charges_flat_fee[ids[i]] = struct{}{} + } +} + +// ClearChargesFlatFee clears the "charges_flat_fee" edge to the ChargeFlatFee entity. +func (m *SubscriptionMutation) ClearChargesFlatFee() { + m.clearedcharges_flat_fee = true +} + +// ChargesFlatFeeCleared reports if the "charges_flat_fee" edge to the ChargeFlatFee entity was cleared. +func (m *SubscriptionMutation) ChargesFlatFeeCleared() bool { + return m.clearedcharges_flat_fee +} + +// RemoveChargesFlatFeeIDs removes the "charges_flat_fee" edge to the ChargeFlatFee entity by IDs. +func (m *SubscriptionMutation) RemoveChargesFlatFeeIDs(ids ...string) { + if m.removedcharges_flat_fee == nil { + m.removedcharges_flat_fee = make(map[string]struct{}) + } + for i := range ids { + delete(m.charges_flat_fee, ids[i]) + m.removedcharges_flat_fee[ids[i]] = struct{}{} + } +} + +// RemovedChargesFlatFee returns the removed IDs of the "charges_flat_fee" edge to the ChargeFlatFee entity. +func (m *SubscriptionMutation) RemovedChargesFlatFeeIDs() (ids []string) { + for id := range m.removedcharges_flat_fee { + ids = append(ids, id) + } + return +} + +// ChargesFlatFeeIDs returns the "charges_flat_fee" edge IDs in the mutation. +func (m *SubscriptionMutation) ChargesFlatFeeIDs() (ids []string) { + for id := range m.charges_flat_fee { + ids = append(ids, id) + } + return +} + +// ResetChargesFlatFee resets all changes to the "charges_flat_fee" edge. +func (m *SubscriptionMutation) ResetChargesFlatFee() { + m.charges_flat_fee = nil + m.clearedcharges_flat_fee = false + m.removedcharges_flat_fee = nil +} + +// AddAddonIDs adds the "addons" edge to the SubscriptionAddon entity by ids. +func (m *SubscriptionMutation) AddAddonIDs(ids ...string) { + if m.addons == nil { + m.addons = make(map[string]struct{}) + } + for i := range ids { + m.addons[ids[i]] = struct{}{} + } +} + +// ClearAddons clears the "addons" edge to the SubscriptionAddon entity. +func (m *SubscriptionMutation) ClearAddons() { + m.clearedaddons = true +} + +// AddonsCleared reports if the "addons" edge to the SubscriptionAddon entity was cleared. +func (m *SubscriptionMutation) AddonsCleared() bool { + return m.clearedaddons +} + +// RemoveAddonIDs removes the "addons" edge to the SubscriptionAddon entity by IDs. +func (m *SubscriptionMutation) RemoveAddonIDs(ids ...string) { + if m.removedaddons == nil { + m.removedaddons = make(map[string]struct{}) + } + for i := range ids { + delete(m.addons, ids[i]) + m.removedaddons[ids[i]] = struct{}{} + } +} + +// RemovedAddons returns the removed IDs of the "addons" edge to the SubscriptionAddon entity. +func (m *SubscriptionMutation) RemovedAddonsIDs() (ids []string) { + for id := range m.removedaddons { + ids = append(ids, id) + } + return +} + +// AddonsIDs returns the "addons" edge IDs in the mutation. +func (m *SubscriptionMutation) AddonsIDs() (ids []string) { + for id := range m.addons { + ids = append(ids, id) + } + return +} + +// ResetAddons resets all changes to the "addons" edge. +func (m *SubscriptionMutation) ResetAddons() { + m.addons = nil + m.clearedaddons = false + m.removedaddons = nil +} + +// SetBillingSyncStateID sets the "billing_sync_state" edge to the SubscriptionBillingSyncState entity by id. +func (m *SubscriptionMutation) SetBillingSyncStateID(id string) { + m.billing_sync_state = &id +} + +// ClearBillingSyncState clears the "billing_sync_state" edge to the SubscriptionBillingSyncState entity. +func (m *SubscriptionMutation) ClearBillingSyncState() { + m.clearedbilling_sync_state = true +} + +// BillingSyncStateCleared reports if the "billing_sync_state" edge to the SubscriptionBillingSyncState entity was cleared. +func (m *SubscriptionMutation) BillingSyncStateCleared() bool { + return m.clearedbilling_sync_state +} + +// BillingSyncStateID returns the "billing_sync_state" edge ID in the mutation. +func (m *SubscriptionMutation) BillingSyncStateID() (id string, exists bool) { + if m.billing_sync_state != nil { + return *m.billing_sync_state, true + } + return +} + +// BillingSyncStateIDs returns the "billing_sync_state" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// BillingSyncStateID instead. It exists only for internal usage by the builders. +func (m *SubscriptionMutation) BillingSyncStateIDs() (ids []string) { + if id := m.billing_sync_state; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetBillingSyncState resets all changes to the "billing_sync_state" edge. +func (m *SubscriptionMutation) ResetBillingSyncState() { + m.billing_sync_state = nil + m.clearedbilling_sync_state = false +} + +// Where appends a list predicates to the SubscriptionMutation builder. +func (m *SubscriptionMutation) Where(ps ...predicate.Subscription) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SubscriptionMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SubscriptionMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Subscription, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *SubscriptionMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *SubscriptionMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Subscription). +func (m *SubscriptionMutation) 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 *SubscriptionMutation) Fields() []string { + fields := make([]string, 0, 17) + if m.namespace != nil { + fields = append(fields, subscription.FieldNamespace) + } + if m.annotations != nil { + fields = append(fields, subscription.FieldAnnotations) + } + if m.created_at != nil { + fields = append(fields, subscription.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, subscription.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, subscription.FieldDeletedAt) + } + if m.metadata != nil { + fields = append(fields, subscription.FieldMetadata) + } + if m.active_from != nil { + fields = append(fields, subscription.FieldActiveFrom) + } + if m.active_to != nil { + fields = append(fields, subscription.FieldActiveTo) + } + if m.name != nil { + fields = append(fields, subscription.FieldName) + } + if m.description != nil { + fields = append(fields, subscription.FieldDescription) + } + if m.plan != nil { + fields = append(fields, subscription.FieldPlanID) + } + if m.customer != nil { + fields = append(fields, subscription.FieldCustomerID) + } + if m.currency != nil { + fields = append(fields, subscription.FieldCurrency) + } + if m.billing_anchor != nil { + fields = append(fields, subscription.FieldBillingAnchor) + } + if m.billing_cadence != nil { + fields = append(fields, subscription.FieldBillingCadence) + } + if m.pro_rating_config != nil { + fields = append(fields, subscription.FieldProRatingConfig) + } + if m.settlement_mode != nil { + fields = append(fields, subscription.FieldSettlementMode) + } + 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 *SubscriptionMutation) Field(name string) (ent.Value, bool) { + switch name { + case subscription.FieldNamespace: + return m.Namespace() + case subscription.FieldAnnotations: + return m.Annotations() + case subscription.FieldCreatedAt: + return m.CreatedAt() + case subscription.FieldUpdatedAt: + return m.UpdatedAt() + case subscription.FieldDeletedAt: + return m.DeletedAt() + case subscription.FieldMetadata: + return m.Metadata() + case subscription.FieldActiveFrom: + return m.ActiveFrom() + case subscription.FieldActiveTo: + return m.ActiveTo() + case subscription.FieldName: + return m.Name() + case subscription.FieldDescription: + return m.Description() + case subscription.FieldPlanID: + return m.PlanID() + case subscription.FieldCustomerID: + return m.CustomerID() + case subscription.FieldCurrency: + return m.Currency() + case subscription.FieldBillingAnchor: + return m.BillingAnchor() + case subscription.FieldBillingCadence: + return m.BillingCadence() + case subscription.FieldProRatingConfig: + return m.ProRatingConfig() + case subscription.FieldSettlementMode: + return m.SettlementMode() + } + 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 *SubscriptionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case subscription.FieldNamespace: + return m.OldNamespace(ctx) + case subscription.FieldAnnotations: + return m.OldAnnotations(ctx) + case subscription.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case subscription.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case subscription.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case subscription.FieldMetadata: + return m.OldMetadata(ctx) + case subscription.FieldActiveFrom: + return m.OldActiveFrom(ctx) + case subscription.FieldActiveTo: + return m.OldActiveTo(ctx) + case subscription.FieldName: + return m.OldName(ctx) + case subscription.FieldDescription: + return m.OldDescription(ctx) + case subscription.FieldPlanID: + return m.OldPlanID(ctx) + case subscription.FieldCustomerID: + return m.OldCustomerID(ctx) + case subscription.FieldCurrency: + return m.OldCurrency(ctx) + case subscription.FieldBillingAnchor: + return m.OldBillingAnchor(ctx) + case subscription.FieldBillingCadence: + return m.OldBillingCadence(ctx) + case subscription.FieldProRatingConfig: + return m.OldProRatingConfig(ctx) + case subscription.FieldSettlementMode: + return m.OldSettlementMode(ctx) + } + return nil, fmt.Errorf("unknown Subscription 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 *SubscriptionMutation) SetField(name string, value ent.Value) error { + switch name { + case subscription.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case subscription.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 subscription.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 subscription.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 subscription.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 subscription.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case subscription.FieldActiveFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetActiveFrom(v) + return nil + case subscription.FieldActiveTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetActiveTo(v) + return nil + case subscription.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case subscription.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case subscription.FieldPlanID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPlanID(v) + return nil + case subscription.FieldCustomerID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerID(v) + return nil + case subscription.FieldCurrency: + v, ok := value.(currencyx.Code) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCurrency(v) + return nil + case subscription.FieldBillingAnchor: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingAnchor(v) + return nil + case subscription.FieldBillingCadence: + v, ok := value.(datetime.ISODurationString) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingCadence(v) + return nil + case subscription.FieldProRatingConfig: + v, ok := value.(productcatalog.ProRatingConfig) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetProRatingConfig(v) + return nil + case subscription.FieldSettlementMode: + v, ok := value.(productcatalog.SettlementMode) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSettlementMode(v) + return nil + } + return fmt.Errorf("unknown Subscription field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SubscriptionMutation) 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 *SubscriptionMutation) 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 *SubscriptionMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Subscription numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SubscriptionMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(subscription.FieldAnnotations) { + fields = append(fields, subscription.FieldAnnotations) + } + if m.FieldCleared(subscription.FieldDeletedAt) { + fields = append(fields, subscription.FieldDeletedAt) + } + if m.FieldCleared(subscription.FieldMetadata) { + fields = append(fields, subscription.FieldMetadata) + } + if m.FieldCleared(subscription.FieldActiveTo) { + fields = append(fields, subscription.FieldActiveTo) + } + if m.FieldCleared(subscription.FieldDescription) { + fields = append(fields, subscription.FieldDescription) + } + if m.FieldCleared(subscription.FieldPlanID) { + fields = append(fields, subscription.FieldPlanID) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SubscriptionMutation) 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 *SubscriptionMutation) ClearField(name string) error { + switch name { + case subscription.FieldAnnotations: + m.ClearAnnotations() + return nil + case subscription.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case subscription.FieldMetadata: + m.ClearMetadata() + return nil + case subscription.FieldActiveTo: + m.ClearActiveTo() + return nil + case subscription.FieldDescription: + m.ClearDescription() + return nil + case subscription.FieldPlanID: + m.ClearPlanID() + return nil + } + return fmt.Errorf("unknown Subscription 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 *SubscriptionMutation) ResetField(name string) error { + switch name { + case subscription.FieldNamespace: + m.ResetNamespace() + return nil + case subscription.FieldAnnotations: + m.ResetAnnotations() + return nil + case subscription.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case subscription.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case subscription.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case subscription.FieldMetadata: + m.ResetMetadata() + return nil + case subscription.FieldActiveFrom: + m.ResetActiveFrom() + return nil + case subscription.FieldActiveTo: + m.ResetActiveTo() + return nil + case subscription.FieldName: + m.ResetName() + return nil + case subscription.FieldDescription: + m.ResetDescription() + return nil + case subscription.FieldPlanID: + m.ResetPlanID() + return nil + case subscription.FieldCustomerID: + m.ResetCustomerID() + return nil + case subscription.FieldCurrency: + m.ResetCurrency() + return nil + case subscription.FieldBillingAnchor: + m.ResetBillingAnchor() + return nil + case subscription.FieldBillingCadence: + m.ResetBillingCadence() + return nil + case subscription.FieldProRatingConfig: + m.ResetProRatingConfig() + return nil + case subscription.FieldSettlementMode: + m.ResetSettlementMode() + return nil + } + return fmt.Errorf("unknown Subscription field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SubscriptionMutation) AddedEdges() []string { + edges := make([]string, 0, 10) + if m.plan != nil { + edges = append(edges, subscription.EdgePlan) + } + if m.customer != nil { + edges = append(edges, subscription.EdgeCustomer) + } + if m.phases != nil { + edges = append(edges, subscription.EdgePhases) + } + if m.billing_lines != nil { + edges = append(edges, subscription.EdgeBillingLines) + } + if m.billing_split_line_groups != nil { + edges = append(edges, subscription.EdgeBillingSplitLineGroups) + } + if m.charges_usage_based != nil { + edges = append(edges, subscription.EdgeChargesUsageBased) + } + if m.charges_credit_purchase != nil { + edges = append(edges, subscription.EdgeChargesCreditPurchase) + } + if m.charges_flat_fee != nil { + edges = append(edges, subscription.EdgeChargesFlatFee) + } + if m.addons != nil { + edges = append(edges, subscription.EdgeAddons) + } + if m.billing_sync_state != nil { + edges = append(edges, subscription.EdgeBillingSyncState) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *SubscriptionMutation) AddedIDs(name string) []ent.Value { + switch name { + case subscription.EdgePlan: + if id := m.plan; id != nil { + return []ent.Value{*id} + } + case subscription.EdgeCustomer: + if id := m.customer; id != nil { + return []ent.Value{*id} + } + case subscription.EdgePhases: + ids := make([]ent.Value, 0, len(m.phases)) + for id := range m.phases { + ids = append(ids, id) + } + return ids + case subscription.EdgeBillingLines: + ids := make([]ent.Value, 0, len(m.billing_lines)) + for id := range m.billing_lines { + ids = append(ids, id) + } + return ids + case subscription.EdgeBillingSplitLineGroups: + ids := make([]ent.Value, 0, len(m.billing_split_line_groups)) + for id := range m.billing_split_line_groups { + ids = append(ids, id) + } + return ids + case subscription.EdgeChargesUsageBased: + ids := make([]ent.Value, 0, len(m.charges_usage_based)) + for id := range m.charges_usage_based { + ids = append(ids, id) + } + return ids + case subscription.EdgeChargesCreditPurchase: + ids := make([]ent.Value, 0, len(m.charges_credit_purchase)) + for id := range m.charges_credit_purchase { + ids = append(ids, id) + } + return ids + case subscription.EdgeChargesFlatFee: + ids := make([]ent.Value, 0, len(m.charges_flat_fee)) + for id := range m.charges_flat_fee { + ids = append(ids, id) + } + return ids + case subscription.EdgeAddons: + ids := make([]ent.Value, 0, len(m.addons)) + for id := range m.addons { + ids = append(ids, id) + } + return ids + case subscription.EdgeBillingSyncState: + if id := m.billing_sync_state; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SubscriptionMutation) RemovedEdges() []string { + edges := make([]string, 0, 10) + if m.removedphases != nil { + edges = append(edges, subscription.EdgePhases) + } + if m.removedbilling_lines != nil { + edges = append(edges, subscription.EdgeBillingLines) + } + if m.removedbilling_split_line_groups != nil { + edges = append(edges, subscription.EdgeBillingSplitLineGroups) + } + if m.removedcharges_usage_based != nil { + edges = append(edges, subscription.EdgeChargesUsageBased) + } + if m.removedcharges_credit_purchase != nil { + edges = append(edges, subscription.EdgeChargesCreditPurchase) + } + if m.removedcharges_flat_fee != nil { + edges = append(edges, subscription.EdgeChargesFlatFee) + } + if m.removedaddons != nil { + edges = append(edges, subscription.EdgeAddons) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *SubscriptionMutation) RemovedIDs(name string) []ent.Value { + switch name { + case subscription.EdgePhases: + ids := make([]ent.Value, 0, len(m.removedphases)) + for id := range m.removedphases { + ids = append(ids, id) + } + return ids + case subscription.EdgeBillingLines: + ids := make([]ent.Value, 0, len(m.removedbilling_lines)) + for id := range m.removedbilling_lines { + ids = append(ids, id) + } + return ids + case subscription.EdgeBillingSplitLineGroups: + ids := make([]ent.Value, 0, len(m.removedbilling_split_line_groups)) + for id := range m.removedbilling_split_line_groups { + ids = append(ids, id) + } + return ids + case subscription.EdgeChargesUsageBased: + ids := make([]ent.Value, 0, len(m.removedcharges_usage_based)) + for id := range m.removedcharges_usage_based { + ids = append(ids, id) + } + return ids + case subscription.EdgeChargesCreditPurchase: + ids := make([]ent.Value, 0, len(m.removedcharges_credit_purchase)) + for id := range m.removedcharges_credit_purchase { + ids = append(ids, id) + } + return ids + case subscription.EdgeChargesFlatFee: + ids := make([]ent.Value, 0, len(m.removedcharges_flat_fee)) + for id := range m.removedcharges_flat_fee { + ids = append(ids, id) + } + return ids + case subscription.EdgeAddons: + ids := make([]ent.Value, 0, len(m.removedaddons)) + for id := range m.removedaddons { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SubscriptionMutation) ClearedEdges() []string { + edges := make([]string, 0, 10) + if m.clearedplan { + edges = append(edges, subscription.EdgePlan) + } + if m.clearedcustomer { + edges = append(edges, subscription.EdgeCustomer) + } + if m.clearedphases { + edges = append(edges, subscription.EdgePhases) + } + if m.clearedbilling_lines { + edges = append(edges, subscription.EdgeBillingLines) + } + if m.clearedbilling_split_line_groups { + edges = append(edges, subscription.EdgeBillingSplitLineGroups) + } + if m.clearedcharges_usage_based { + edges = append(edges, subscription.EdgeChargesUsageBased) + } + if m.clearedcharges_credit_purchase { + edges = append(edges, subscription.EdgeChargesCreditPurchase) + } + if m.clearedcharges_flat_fee { + edges = append(edges, subscription.EdgeChargesFlatFee) + } + if m.clearedaddons { + edges = append(edges, subscription.EdgeAddons) + } + if m.clearedbilling_sync_state { + edges = append(edges, subscription.EdgeBillingSyncState) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *SubscriptionMutation) EdgeCleared(name string) bool { + switch name { + case subscription.EdgePlan: + return m.clearedplan + case subscription.EdgeCustomer: + return m.clearedcustomer + case subscription.EdgePhases: + return m.clearedphases + case subscription.EdgeBillingLines: + return m.clearedbilling_lines + case subscription.EdgeBillingSplitLineGroups: + return m.clearedbilling_split_line_groups + case subscription.EdgeChargesUsageBased: + return m.clearedcharges_usage_based + case subscription.EdgeChargesCreditPurchase: + return m.clearedcharges_credit_purchase + case subscription.EdgeChargesFlatFee: + return m.clearedcharges_flat_fee + case subscription.EdgeAddons: + return m.clearedaddons + case subscription.EdgeBillingSyncState: + return m.clearedbilling_sync_state + } + 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 *SubscriptionMutation) ClearEdge(name string) error { + switch name { + case subscription.EdgePlan: + m.ClearPlan() + return nil + case subscription.EdgeCustomer: + m.ClearCustomer() + return nil + case subscription.EdgeBillingSyncState: + m.ClearBillingSyncState() + return nil + } + return fmt.Errorf("unknown Subscription 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 *SubscriptionMutation) ResetEdge(name string) error { + switch name { + case subscription.EdgePlan: + m.ResetPlan() + return nil + case subscription.EdgeCustomer: + m.ResetCustomer() + return nil + case subscription.EdgePhases: + m.ResetPhases() + return nil + case subscription.EdgeBillingLines: + m.ResetBillingLines() + return nil + case subscription.EdgeBillingSplitLineGroups: + m.ResetBillingSplitLineGroups() + return nil + case subscription.EdgeChargesUsageBased: + m.ResetChargesUsageBased() + return nil + case subscription.EdgeChargesCreditPurchase: + m.ResetChargesCreditPurchase() + return nil + case subscription.EdgeChargesFlatFee: + m.ResetChargesFlatFee() + return nil + case subscription.EdgeAddons: + m.ResetAddons() + return nil + case subscription.EdgeBillingSyncState: + m.ResetBillingSyncState() + return nil + } + return fmt.Errorf("unknown Subscription edge %s", name) +} + +// SubscriptionAddonMutation represents an operation that mutates the SubscriptionAddon nodes in the graph. +type SubscriptionAddonMutation struct { + config + op Op + typ string + id *string + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + clearedFields map[string]struct{} + subscription *string + clearedsubscription bool + quantities map[string]struct{} + removedquantities map[string]struct{} + clearedquantities bool + addon *string + clearedaddon bool + done bool + oldValue func(context.Context) (*SubscriptionAddon, error) + predicates []predicate.SubscriptionAddon +} + +var _ ent.Mutation = (*SubscriptionAddonMutation)(nil) + +// subscriptionaddonOption allows management of the mutation configuration using functional options. +type subscriptionaddonOption func(*SubscriptionAddonMutation) + +// newSubscriptionAddonMutation creates new mutation for the SubscriptionAddon entity. +func newSubscriptionAddonMutation(c config, op Op, opts ...subscriptionaddonOption) *SubscriptionAddonMutation { + m := &SubscriptionAddonMutation{ + config: c, + op: op, + typ: TypeSubscriptionAddon, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withSubscriptionAddonID sets the ID field of the mutation. +func withSubscriptionAddonID(id string) subscriptionaddonOption { + return func(m *SubscriptionAddonMutation) { + var ( + err error + once sync.Once + value *SubscriptionAddon + ) + m.oldValue = func(ctx context.Context) (*SubscriptionAddon, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().SubscriptionAddon.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withSubscriptionAddon sets the old SubscriptionAddon of the mutation. +func withSubscriptionAddon(node *SubscriptionAddon) subscriptionaddonOption { + return func(m *SubscriptionAddonMutation) { + m.oldValue = func(context.Context) (*SubscriptionAddon, 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 SubscriptionAddonMutation) 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 SubscriptionAddonMutation) 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 SubscriptionAddon entities. +func (m *SubscriptionAddonMutation) 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 *SubscriptionAddonMutation) 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 *SubscriptionAddonMutation) 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().SubscriptionAddon.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 *SubscriptionAddonMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *SubscriptionAddonMutation) 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 SubscriptionAddon entity. +// If the SubscriptionAddon 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 *SubscriptionAddonMutation) 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 *SubscriptionAddonMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *SubscriptionAddonMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *SubscriptionAddonMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the SubscriptionAddon entity. +// If the SubscriptionAddon 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 *SubscriptionAddonMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *SubscriptionAddonMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[subscriptionaddon.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *SubscriptionAddonMutation) MetadataCleared() bool { + _, ok := m.clearedFields[subscriptionaddon.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *SubscriptionAddonMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, subscriptionaddon.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *SubscriptionAddonMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *SubscriptionAddonMutation) 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 SubscriptionAddon entity. +// If the SubscriptionAddon 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 *SubscriptionAddonMutation) 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 *SubscriptionAddonMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *SubscriptionAddonMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *SubscriptionAddonMutation) 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 SubscriptionAddon entity. +// If the SubscriptionAddon 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 *SubscriptionAddonMutation) 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 *SubscriptionAddonMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *SubscriptionAddonMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *SubscriptionAddonMutation) 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 SubscriptionAddon entity. +// If the SubscriptionAddon 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 *SubscriptionAddonMutation) 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 *SubscriptionAddonMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[subscriptionaddon.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *SubscriptionAddonMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[subscriptionaddon.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *SubscriptionAddonMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, subscriptionaddon.FieldDeletedAt) +} + +// SetAddonID sets the "addon_id" field. +func (m *SubscriptionAddonMutation) SetAddonID(s string) { + m.addon = &s +} + +// AddonID returns the value of the "addon_id" field in the mutation. +func (m *SubscriptionAddonMutation) AddonID() (r string, exists bool) { + v := m.addon + if v == nil { + return + } + return *v, true +} + +// OldAddonID returns the old "addon_id" field's value of the SubscriptionAddon entity. +// If the SubscriptionAddon 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 *SubscriptionAddonMutation) OldAddonID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAddonID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAddonID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAddonID: %w", err) + } + return oldValue.AddonID, nil +} + +// ResetAddonID resets all changes to the "addon_id" field. +func (m *SubscriptionAddonMutation) ResetAddonID() { + m.addon = nil +} + +// SetSubscriptionID sets the "subscription_id" field. +func (m *SubscriptionAddonMutation) SetSubscriptionID(s string) { + m.subscription = &s +} + +// SubscriptionID returns the value of the "subscription_id" field in the mutation. +func (m *SubscriptionAddonMutation) SubscriptionID() (r string, exists bool) { + v := m.subscription + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionID returns the old "subscription_id" field's value of the SubscriptionAddon entity. +// If the SubscriptionAddon 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 *SubscriptionAddonMutation) OldSubscriptionID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionID: %w", err) + } + return oldValue.SubscriptionID, nil +} + +// ResetSubscriptionID resets all changes to the "subscription_id" field. +func (m *SubscriptionAddonMutation) ResetSubscriptionID() { + m.subscription = nil +} + +// ClearSubscription clears the "subscription" edge to the Subscription entity. +func (m *SubscriptionAddonMutation) ClearSubscription() { + m.clearedsubscription = true + m.clearedFields[subscriptionaddon.FieldSubscriptionID] = struct{}{} +} + +// SubscriptionCleared reports if the "subscription" edge to the Subscription entity was cleared. +func (m *SubscriptionAddonMutation) SubscriptionCleared() bool { + return m.clearedsubscription +} + +// SubscriptionIDs returns the "subscription" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubscriptionID instead. It exists only for internal usage by the builders. +func (m *SubscriptionAddonMutation) SubscriptionIDs() (ids []string) { + if id := m.subscription; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSubscription resets all changes to the "subscription" edge. +func (m *SubscriptionAddonMutation) ResetSubscription() { + m.subscription = nil + m.clearedsubscription = false +} + +// AddQuantityIDs adds the "quantities" edge to the SubscriptionAddonQuantity entity by ids. +func (m *SubscriptionAddonMutation) AddQuantityIDs(ids ...string) { + if m.quantities == nil { + m.quantities = make(map[string]struct{}) + } + for i := range ids { + m.quantities[ids[i]] = struct{}{} + } +} + +// ClearQuantities clears the "quantities" edge to the SubscriptionAddonQuantity entity. +func (m *SubscriptionAddonMutation) ClearQuantities() { + m.clearedquantities = true +} + +// QuantitiesCleared reports if the "quantities" edge to the SubscriptionAddonQuantity entity was cleared. +func (m *SubscriptionAddonMutation) QuantitiesCleared() bool { + return m.clearedquantities +} + +// RemoveQuantityIDs removes the "quantities" edge to the SubscriptionAddonQuantity entity by IDs. +func (m *SubscriptionAddonMutation) RemoveQuantityIDs(ids ...string) { + if m.removedquantities == nil { + m.removedquantities = make(map[string]struct{}) + } + for i := range ids { + delete(m.quantities, ids[i]) + m.removedquantities[ids[i]] = struct{}{} + } +} + +// RemovedQuantities returns the removed IDs of the "quantities" edge to the SubscriptionAddonQuantity entity. +func (m *SubscriptionAddonMutation) RemovedQuantitiesIDs() (ids []string) { + for id := range m.removedquantities { + ids = append(ids, id) + } + return +} + +// QuantitiesIDs returns the "quantities" edge IDs in the mutation. +func (m *SubscriptionAddonMutation) QuantitiesIDs() (ids []string) { + for id := range m.quantities { + ids = append(ids, id) + } + return +} + +// ResetQuantities resets all changes to the "quantities" edge. +func (m *SubscriptionAddonMutation) ResetQuantities() { + m.quantities = nil + m.clearedquantities = false + m.removedquantities = nil +} + +// ClearAddon clears the "addon" edge to the Addon entity. +func (m *SubscriptionAddonMutation) ClearAddon() { + m.clearedaddon = true + m.clearedFields[subscriptionaddon.FieldAddonID] = struct{}{} +} + +// AddonCleared reports if the "addon" edge to the Addon entity was cleared. +func (m *SubscriptionAddonMutation) AddonCleared() bool { + return m.clearedaddon +} + +// AddonIDs returns the "addon" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// AddonID instead. It exists only for internal usage by the builders. +func (m *SubscriptionAddonMutation) AddonIDs() (ids []string) { + if id := m.addon; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetAddon resets all changes to the "addon" edge. +func (m *SubscriptionAddonMutation) ResetAddon() { + m.addon = nil + m.clearedaddon = false +} + +// Where appends a list predicates to the SubscriptionAddonMutation builder. +func (m *SubscriptionAddonMutation) Where(ps ...predicate.SubscriptionAddon) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SubscriptionAddonMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SubscriptionAddonMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.SubscriptionAddon, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *SubscriptionAddonMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *SubscriptionAddonMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (SubscriptionAddon). +func (m *SubscriptionAddonMutation) 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 *SubscriptionAddonMutation) Fields() []string { + fields := make([]string, 0, 7) + if m.namespace != nil { + fields = append(fields, subscriptionaddon.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, subscriptionaddon.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, subscriptionaddon.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, subscriptionaddon.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, subscriptionaddon.FieldDeletedAt) + } + if m.addon != nil { + fields = append(fields, subscriptionaddon.FieldAddonID) + } + if m.subscription != nil { + fields = append(fields, subscriptionaddon.FieldSubscriptionID) + } + 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 *SubscriptionAddonMutation) Field(name string) (ent.Value, bool) { + switch name { + case subscriptionaddon.FieldNamespace: + return m.Namespace() + case subscriptionaddon.FieldMetadata: + return m.Metadata() + case subscriptionaddon.FieldCreatedAt: + return m.CreatedAt() + case subscriptionaddon.FieldUpdatedAt: + return m.UpdatedAt() + case subscriptionaddon.FieldDeletedAt: + return m.DeletedAt() + case subscriptionaddon.FieldAddonID: + return m.AddonID() + case subscriptionaddon.FieldSubscriptionID: + return m.SubscriptionID() + } + 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 *SubscriptionAddonMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case subscriptionaddon.FieldNamespace: + return m.OldNamespace(ctx) + case subscriptionaddon.FieldMetadata: + return m.OldMetadata(ctx) + case subscriptionaddon.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case subscriptionaddon.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case subscriptionaddon.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case subscriptionaddon.FieldAddonID: + return m.OldAddonID(ctx) + case subscriptionaddon.FieldSubscriptionID: + return m.OldSubscriptionID(ctx) + } + return nil, fmt.Errorf("unknown SubscriptionAddon 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 *SubscriptionAddonMutation) SetField(name string, value ent.Value) error { + switch name { + case subscriptionaddon.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case subscriptionaddon.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case subscriptionaddon.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 subscriptionaddon.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 subscriptionaddon.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 subscriptionaddon.FieldAddonID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAddonID(v) + return nil + case subscriptionaddon.FieldSubscriptionID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionID(v) + return nil + } + return fmt.Errorf("unknown SubscriptionAddon field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SubscriptionAddonMutation) 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 *SubscriptionAddonMutation) 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 *SubscriptionAddonMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown SubscriptionAddon numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SubscriptionAddonMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(subscriptionaddon.FieldMetadata) { + fields = append(fields, subscriptionaddon.FieldMetadata) + } + if m.FieldCleared(subscriptionaddon.FieldDeletedAt) { + fields = append(fields, subscriptionaddon.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SubscriptionAddonMutation) 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 *SubscriptionAddonMutation) ClearField(name string) error { + switch name { + case subscriptionaddon.FieldMetadata: + m.ClearMetadata() + return nil + case subscriptionaddon.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown SubscriptionAddon 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 *SubscriptionAddonMutation) ResetField(name string) error { + switch name { + case subscriptionaddon.FieldNamespace: + m.ResetNamespace() + return nil + case subscriptionaddon.FieldMetadata: + m.ResetMetadata() + return nil + case subscriptionaddon.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case subscriptionaddon.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case subscriptionaddon.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case subscriptionaddon.FieldAddonID: + m.ResetAddonID() + return nil + case subscriptionaddon.FieldSubscriptionID: + m.ResetSubscriptionID() + return nil + } + return fmt.Errorf("unknown SubscriptionAddon field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SubscriptionAddonMutation) AddedEdges() []string { + edges := make([]string, 0, 3) + if m.subscription != nil { + edges = append(edges, subscriptionaddon.EdgeSubscription) + } + if m.quantities != nil { + edges = append(edges, subscriptionaddon.EdgeQuantities) + } + if m.addon != nil { + edges = append(edges, subscriptionaddon.EdgeAddon) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *SubscriptionAddonMutation) AddedIDs(name string) []ent.Value { + switch name { + case subscriptionaddon.EdgeSubscription: + if id := m.subscription; id != nil { + return []ent.Value{*id} + } + case subscriptionaddon.EdgeQuantities: + ids := make([]ent.Value, 0, len(m.quantities)) + for id := range m.quantities { + ids = append(ids, id) + } + return ids + case subscriptionaddon.EdgeAddon: + if id := m.addon; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SubscriptionAddonMutation) RemovedEdges() []string { + edges := make([]string, 0, 3) + if m.removedquantities != nil { + edges = append(edges, subscriptionaddon.EdgeQuantities) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *SubscriptionAddonMutation) RemovedIDs(name string) []ent.Value { + switch name { + case subscriptionaddon.EdgeQuantities: + ids := make([]ent.Value, 0, len(m.removedquantities)) + for id := range m.removedquantities { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SubscriptionAddonMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) + if m.clearedsubscription { + edges = append(edges, subscriptionaddon.EdgeSubscription) + } + if m.clearedquantities { + edges = append(edges, subscriptionaddon.EdgeQuantities) + } + if m.clearedaddon { + edges = append(edges, subscriptionaddon.EdgeAddon) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *SubscriptionAddonMutation) EdgeCleared(name string) bool { + switch name { + case subscriptionaddon.EdgeSubscription: + return m.clearedsubscription + case subscriptionaddon.EdgeQuantities: + return m.clearedquantities + case subscriptionaddon.EdgeAddon: + return m.clearedaddon + } + 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 *SubscriptionAddonMutation) ClearEdge(name string) error { + switch name { + case subscriptionaddon.EdgeSubscription: + m.ClearSubscription() + return nil + case subscriptionaddon.EdgeAddon: + m.ClearAddon() + return nil + } + return fmt.Errorf("unknown SubscriptionAddon 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 *SubscriptionAddonMutation) ResetEdge(name string) error { + switch name { + case subscriptionaddon.EdgeSubscription: + m.ResetSubscription() + return nil + case subscriptionaddon.EdgeQuantities: + m.ResetQuantities() + return nil + case subscriptionaddon.EdgeAddon: + m.ResetAddon() + return nil + } + return fmt.Errorf("unknown SubscriptionAddon edge %s", name) +} + +// SubscriptionAddonQuantityMutation represents an operation that mutates the SubscriptionAddonQuantity nodes in the graph. +type SubscriptionAddonQuantityMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + active_from *time.Time + quantity *int + addquantity *int + clearedFields map[string]struct{} + subscription_addon *string + clearedsubscription_addon bool + done bool + oldValue func(context.Context) (*SubscriptionAddonQuantity, error) + predicates []predicate.SubscriptionAddonQuantity +} + +var _ ent.Mutation = (*SubscriptionAddonQuantityMutation)(nil) + +// subscriptionaddonquantityOption allows management of the mutation configuration using functional options. +type subscriptionaddonquantityOption func(*SubscriptionAddonQuantityMutation) + +// newSubscriptionAddonQuantityMutation creates new mutation for the SubscriptionAddonQuantity entity. +func newSubscriptionAddonQuantityMutation(c config, op Op, opts ...subscriptionaddonquantityOption) *SubscriptionAddonQuantityMutation { + m := &SubscriptionAddonQuantityMutation{ + config: c, + op: op, + typ: TypeSubscriptionAddonQuantity, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withSubscriptionAddonQuantityID sets the ID field of the mutation. +func withSubscriptionAddonQuantityID(id string) subscriptionaddonquantityOption { + return func(m *SubscriptionAddonQuantityMutation) { + var ( + err error + once sync.Once + value *SubscriptionAddonQuantity + ) + m.oldValue = func(ctx context.Context) (*SubscriptionAddonQuantity, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().SubscriptionAddonQuantity.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withSubscriptionAddonQuantity sets the old SubscriptionAddonQuantity of the mutation. +func withSubscriptionAddonQuantity(node *SubscriptionAddonQuantity) subscriptionaddonquantityOption { + return func(m *SubscriptionAddonQuantityMutation) { + m.oldValue = func(context.Context) (*SubscriptionAddonQuantity, 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 SubscriptionAddonQuantityMutation) 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 SubscriptionAddonQuantityMutation) 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 SubscriptionAddonQuantity entities. +func (m *SubscriptionAddonQuantityMutation) 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 *SubscriptionAddonQuantityMutation) 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 *SubscriptionAddonQuantityMutation) 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().SubscriptionAddonQuantity.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 *SubscriptionAddonQuantityMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *SubscriptionAddonQuantityMutation) 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 SubscriptionAddonQuantity entity. +// If the SubscriptionAddonQuantity 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 *SubscriptionAddonQuantityMutation) 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 *SubscriptionAddonQuantityMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *SubscriptionAddonQuantityMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *SubscriptionAddonQuantityMutation) 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 SubscriptionAddonQuantity entity. +// If the SubscriptionAddonQuantity 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 *SubscriptionAddonQuantityMutation) 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 *SubscriptionAddonQuantityMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *SubscriptionAddonQuantityMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *SubscriptionAddonQuantityMutation) 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 SubscriptionAddonQuantity entity. +// If the SubscriptionAddonQuantity 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 *SubscriptionAddonQuantityMutation) 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 *SubscriptionAddonQuantityMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *SubscriptionAddonQuantityMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *SubscriptionAddonQuantityMutation) 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 SubscriptionAddonQuantity entity. +// If the SubscriptionAddonQuantity 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 *SubscriptionAddonQuantityMutation) 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 *SubscriptionAddonQuantityMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[subscriptionaddonquantity.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *SubscriptionAddonQuantityMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[subscriptionaddonquantity.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *SubscriptionAddonQuantityMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, subscriptionaddonquantity.FieldDeletedAt) +} + +// SetActiveFrom sets the "active_from" field. +func (m *SubscriptionAddonQuantityMutation) SetActiveFrom(t time.Time) { + m.active_from = &t +} + +// ActiveFrom returns the value of the "active_from" field in the mutation. +func (m *SubscriptionAddonQuantityMutation) ActiveFrom() (r time.Time, exists bool) { + v := m.active_from + if v == nil { + return + } + return *v, true +} + +// OldActiveFrom returns the old "active_from" field's value of the SubscriptionAddonQuantity entity. +// If the SubscriptionAddonQuantity 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 *SubscriptionAddonQuantityMutation) OldActiveFrom(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldActiveFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldActiveFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldActiveFrom: %w", err) + } + return oldValue.ActiveFrom, nil +} + +// ResetActiveFrom resets all changes to the "active_from" field. +func (m *SubscriptionAddonQuantityMutation) ResetActiveFrom() { + m.active_from = nil +} + +// SetQuantity sets the "quantity" field. +func (m *SubscriptionAddonQuantityMutation) SetQuantity(i int) { + m.quantity = &i + m.addquantity = nil +} + +// Quantity returns the value of the "quantity" field in the mutation. +func (m *SubscriptionAddonQuantityMutation) Quantity() (r int, exists bool) { + v := m.quantity + if v == nil { + return + } + return *v, true +} + +// OldQuantity returns the old "quantity" field's value of the SubscriptionAddonQuantity entity. +// If the SubscriptionAddonQuantity 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 *SubscriptionAddonQuantityMutation) OldQuantity(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldQuantity is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldQuantity requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldQuantity: %w", err) + } + return oldValue.Quantity, nil +} + +// AddQuantity adds i to the "quantity" field. +func (m *SubscriptionAddonQuantityMutation) AddQuantity(i int) { + if m.addquantity != nil { + *m.addquantity += i + } else { + m.addquantity = &i + } +} + +// AddedQuantity returns the value that was added to the "quantity" field in this mutation. +func (m *SubscriptionAddonQuantityMutation) AddedQuantity() (r int, exists bool) { + v := m.addquantity + if v == nil { + return + } + return *v, true +} + +// ResetQuantity resets all changes to the "quantity" field. +func (m *SubscriptionAddonQuantityMutation) ResetQuantity() { + m.quantity = nil + m.addquantity = nil +} + +// SetSubscriptionAddonID sets the "subscription_addon_id" field. +func (m *SubscriptionAddonQuantityMutation) SetSubscriptionAddonID(s string) { + m.subscription_addon = &s +} + +// SubscriptionAddonID returns the value of the "subscription_addon_id" field in the mutation. +func (m *SubscriptionAddonQuantityMutation) SubscriptionAddonID() (r string, exists bool) { + v := m.subscription_addon + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionAddonID returns the old "subscription_addon_id" field's value of the SubscriptionAddonQuantity entity. +// If the SubscriptionAddonQuantity 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 *SubscriptionAddonQuantityMutation) OldSubscriptionAddonID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionAddonID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionAddonID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionAddonID: %w", err) + } + return oldValue.SubscriptionAddonID, nil +} + +// ResetSubscriptionAddonID resets all changes to the "subscription_addon_id" field. +func (m *SubscriptionAddonQuantityMutation) ResetSubscriptionAddonID() { + m.subscription_addon = nil +} + +// ClearSubscriptionAddon clears the "subscription_addon" edge to the SubscriptionAddon entity. +func (m *SubscriptionAddonQuantityMutation) ClearSubscriptionAddon() { + m.clearedsubscription_addon = true + m.clearedFields[subscriptionaddonquantity.FieldSubscriptionAddonID] = struct{}{} +} + +// SubscriptionAddonCleared reports if the "subscription_addon" edge to the SubscriptionAddon entity was cleared. +func (m *SubscriptionAddonQuantityMutation) SubscriptionAddonCleared() bool { + return m.clearedsubscription_addon +} + +// SubscriptionAddonIDs returns the "subscription_addon" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubscriptionAddonID instead. It exists only for internal usage by the builders. +func (m *SubscriptionAddonQuantityMutation) SubscriptionAddonIDs() (ids []string) { + if id := m.subscription_addon; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSubscriptionAddon resets all changes to the "subscription_addon" edge. +func (m *SubscriptionAddonQuantityMutation) ResetSubscriptionAddon() { + m.subscription_addon = nil + m.clearedsubscription_addon = false +} + +// Where appends a list predicates to the SubscriptionAddonQuantityMutation builder. +func (m *SubscriptionAddonQuantityMutation) Where(ps ...predicate.SubscriptionAddonQuantity) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SubscriptionAddonQuantityMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SubscriptionAddonQuantityMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.SubscriptionAddonQuantity, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *SubscriptionAddonQuantityMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *SubscriptionAddonQuantityMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (SubscriptionAddonQuantity). +func (m *SubscriptionAddonQuantityMutation) 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 *SubscriptionAddonQuantityMutation) Fields() []string { + fields := make([]string, 0, 7) + if m.namespace != nil { + fields = append(fields, subscriptionaddonquantity.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, subscriptionaddonquantity.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, subscriptionaddonquantity.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, subscriptionaddonquantity.FieldDeletedAt) + } + if m.active_from != nil { + fields = append(fields, subscriptionaddonquantity.FieldActiveFrom) + } + if m.quantity != nil { + fields = append(fields, subscriptionaddonquantity.FieldQuantity) + } + if m.subscription_addon != nil { + fields = append(fields, subscriptionaddonquantity.FieldSubscriptionAddonID) + } + 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 *SubscriptionAddonQuantityMutation) Field(name string) (ent.Value, bool) { + switch name { + case subscriptionaddonquantity.FieldNamespace: + return m.Namespace() + case subscriptionaddonquantity.FieldCreatedAt: + return m.CreatedAt() + case subscriptionaddonquantity.FieldUpdatedAt: + return m.UpdatedAt() + case subscriptionaddonquantity.FieldDeletedAt: + return m.DeletedAt() + case subscriptionaddonquantity.FieldActiveFrom: + return m.ActiveFrom() + case subscriptionaddonquantity.FieldQuantity: + return m.Quantity() + case subscriptionaddonquantity.FieldSubscriptionAddonID: + return m.SubscriptionAddonID() + } + 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 *SubscriptionAddonQuantityMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case subscriptionaddonquantity.FieldNamespace: + return m.OldNamespace(ctx) + case subscriptionaddonquantity.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case subscriptionaddonquantity.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case subscriptionaddonquantity.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case subscriptionaddonquantity.FieldActiveFrom: + return m.OldActiveFrom(ctx) + case subscriptionaddonquantity.FieldQuantity: + return m.OldQuantity(ctx) + case subscriptionaddonquantity.FieldSubscriptionAddonID: + return m.OldSubscriptionAddonID(ctx) + } + return nil, fmt.Errorf("unknown SubscriptionAddonQuantity 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 *SubscriptionAddonQuantityMutation) SetField(name string, value ent.Value) error { + switch name { + case subscriptionaddonquantity.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case subscriptionaddonquantity.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 subscriptionaddonquantity.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 subscriptionaddonquantity.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 subscriptionaddonquantity.FieldActiveFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetActiveFrom(v) + return nil + case subscriptionaddonquantity.FieldQuantity: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetQuantity(v) + return nil + case subscriptionaddonquantity.FieldSubscriptionAddonID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionAddonID(v) + return nil + } + return fmt.Errorf("unknown SubscriptionAddonQuantity field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SubscriptionAddonQuantityMutation) AddedFields() []string { + var fields []string + if m.addquantity != nil { + fields = append(fields, subscriptionaddonquantity.FieldQuantity) + } + return fields +} + +// 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 *SubscriptionAddonQuantityMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case subscriptionaddonquantity.FieldQuantity: + return m.AddedQuantity() + } + 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 *SubscriptionAddonQuantityMutation) AddField(name string, value ent.Value) error { + switch name { + case subscriptionaddonquantity.FieldQuantity: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddQuantity(v) + return nil + } + return fmt.Errorf("unknown SubscriptionAddonQuantity numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SubscriptionAddonQuantityMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(subscriptionaddonquantity.FieldDeletedAt) { + fields = append(fields, subscriptionaddonquantity.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SubscriptionAddonQuantityMutation) 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 *SubscriptionAddonQuantityMutation) ClearField(name string) error { + switch name { + case subscriptionaddonquantity.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown SubscriptionAddonQuantity 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 *SubscriptionAddonQuantityMutation) ResetField(name string) error { + switch name { + case subscriptionaddonquantity.FieldNamespace: + m.ResetNamespace() + return nil + case subscriptionaddonquantity.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case subscriptionaddonquantity.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case subscriptionaddonquantity.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case subscriptionaddonquantity.FieldActiveFrom: + m.ResetActiveFrom() + return nil + case subscriptionaddonquantity.FieldQuantity: + m.ResetQuantity() + return nil + case subscriptionaddonquantity.FieldSubscriptionAddonID: + m.ResetSubscriptionAddonID() + return nil + } + return fmt.Errorf("unknown SubscriptionAddonQuantity field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SubscriptionAddonQuantityMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.subscription_addon != nil { + edges = append(edges, subscriptionaddonquantity.EdgeSubscriptionAddon) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *SubscriptionAddonQuantityMutation) AddedIDs(name string) []ent.Value { + switch name { + case subscriptionaddonquantity.EdgeSubscriptionAddon: + if id := m.subscription_addon; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SubscriptionAddonQuantityMutation) 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 *SubscriptionAddonQuantityMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SubscriptionAddonQuantityMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedsubscription_addon { + edges = append(edges, subscriptionaddonquantity.EdgeSubscriptionAddon) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *SubscriptionAddonQuantityMutation) EdgeCleared(name string) bool { + switch name { + case subscriptionaddonquantity.EdgeSubscriptionAddon: + return m.clearedsubscription_addon + } + 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 *SubscriptionAddonQuantityMutation) ClearEdge(name string) error { + switch name { + case subscriptionaddonquantity.EdgeSubscriptionAddon: + m.ClearSubscriptionAddon() + return nil + } + return fmt.Errorf("unknown SubscriptionAddonQuantity 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 *SubscriptionAddonQuantityMutation) ResetEdge(name string) error { + switch name { + case subscriptionaddonquantity.EdgeSubscriptionAddon: + m.ResetSubscriptionAddon() + return nil + } + return fmt.Errorf("unknown SubscriptionAddonQuantity edge %s", name) +} + +// SubscriptionBillingSyncStateMutation represents an operation that mutates the SubscriptionBillingSyncState nodes in the graph. +type SubscriptionBillingSyncStateMutation struct { + config + op Op + typ string + id *string + namespace *string + has_billables *bool + synced_at *time.Time + next_sync_after *time.Time + clearedFields map[string]struct{} + subscription *string + clearedsubscription bool + done bool + oldValue func(context.Context) (*SubscriptionBillingSyncState, error) + predicates []predicate.SubscriptionBillingSyncState +} + +var _ ent.Mutation = (*SubscriptionBillingSyncStateMutation)(nil) + +// subscriptionbillingsyncstateOption allows management of the mutation configuration using functional options. +type subscriptionbillingsyncstateOption func(*SubscriptionBillingSyncStateMutation) + +// newSubscriptionBillingSyncStateMutation creates new mutation for the SubscriptionBillingSyncState entity. +func newSubscriptionBillingSyncStateMutation(c config, op Op, opts ...subscriptionbillingsyncstateOption) *SubscriptionBillingSyncStateMutation { + m := &SubscriptionBillingSyncStateMutation{ + config: c, + op: op, + typ: TypeSubscriptionBillingSyncState, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withSubscriptionBillingSyncStateID sets the ID field of the mutation. +func withSubscriptionBillingSyncStateID(id string) subscriptionbillingsyncstateOption { + return func(m *SubscriptionBillingSyncStateMutation) { + var ( + err error + once sync.Once + value *SubscriptionBillingSyncState + ) + m.oldValue = func(ctx context.Context) (*SubscriptionBillingSyncState, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().SubscriptionBillingSyncState.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withSubscriptionBillingSyncState sets the old SubscriptionBillingSyncState of the mutation. +func withSubscriptionBillingSyncState(node *SubscriptionBillingSyncState) subscriptionbillingsyncstateOption { + return func(m *SubscriptionBillingSyncStateMutation) { + m.oldValue = func(context.Context) (*SubscriptionBillingSyncState, 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 SubscriptionBillingSyncStateMutation) 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 SubscriptionBillingSyncStateMutation) 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 SubscriptionBillingSyncState entities. +func (m *SubscriptionBillingSyncStateMutation) 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 *SubscriptionBillingSyncStateMutation) 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 *SubscriptionBillingSyncStateMutation) 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().SubscriptionBillingSyncState.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 *SubscriptionBillingSyncStateMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *SubscriptionBillingSyncStateMutation) 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 SubscriptionBillingSyncState entity. +// If the SubscriptionBillingSyncState 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 *SubscriptionBillingSyncStateMutation) 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 *SubscriptionBillingSyncStateMutation) ResetNamespace() { + m.namespace = nil +} + +// SetSubscriptionID sets the "subscription_id" field. +func (m *SubscriptionBillingSyncStateMutation) SetSubscriptionID(s string) { + m.subscription = &s +} + +// SubscriptionID returns the value of the "subscription_id" field in the mutation. +func (m *SubscriptionBillingSyncStateMutation) SubscriptionID() (r string, exists bool) { + v := m.subscription + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionID returns the old "subscription_id" field's value of the SubscriptionBillingSyncState entity. +// If the SubscriptionBillingSyncState 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 *SubscriptionBillingSyncStateMutation) OldSubscriptionID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionID: %w", err) + } + return oldValue.SubscriptionID, nil +} + +// ResetSubscriptionID resets all changes to the "subscription_id" field. +func (m *SubscriptionBillingSyncStateMutation) ResetSubscriptionID() { + m.subscription = nil +} + +// SetHasBillables sets the "has_billables" field. +func (m *SubscriptionBillingSyncStateMutation) SetHasBillables(b bool) { + m.has_billables = &b +} + +// HasBillables returns the value of the "has_billables" field in the mutation. +func (m *SubscriptionBillingSyncStateMutation) HasBillables() (r bool, exists bool) { + v := m.has_billables + if v == nil { + return + } + return *v, true +} + +// OldHasBillables returns the old "has_billables" field's value of the SubscriptionBillingSyncState entity. +// If the SubscriptionBillingSyncState 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 *SubscriptionBillingSyncStateMutation) OldHasBillables(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldHasBillables is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldHasBillables requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldHasBillables: %w", err) + } + return oldValue.HasBillables, nil +} + +// ResetHasBillables resets all changes to the "has_billables" field. +func (m *SubscriptionBillingSyncStateMutation) ResetHasBillables() { + m.has_billables = nil +} + +// SetSyncedAt sets the "synced_at" field. +func (m *SubscriptionBillingSyncStateMutation) SetSyncedAt(t time.Time) { + m.synced_at = &t +} + +// SyncedAt returns the value of the "synced_at" field in the mutation. +func (m *SubscriptionBillingSyncStateMutation) SyncedAt() (r time.Time, exists bool) { + v := m.synced_at + if v == nil { + return + } + return *v, true +} + +// OldSyncedAt returns the old "synced_at" field's value of the SubscriptionBillingSyncState entity. +// If the SubscriptionBillingSyncState 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 *SubscriptionBillingSyncStateMutation) OldSyncedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSyncedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSyncedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSyncedAt: %w", err) + } + return oldValue.SyncedAt, nil +} + +// ResetSyncedAt resets all changes to the "synced_at" field. +func (m *SubscriptionBillingSyncStateMutation) ResetSyncedAt() { + m.synced_at = nil +} + +// SetNextSyncAfter sets the "next_sync_after" field. +func (m *SubscriptionBillingSyncStateMutation) SetNextSyncAfter(t time.Time) { + m.next_sync_after = &t +} + +// NextSyncAfter returns the value of the "next_sync_after" field in the mutation. +func (m *SubscriptionBillingSyncStateMutation) NextSyncAfter() (r time.Time, exists bool) { + v := m.next_sync_after + if v == nil { + return + } + return *v, true +} + +// OldNextSyncAfter returns the old "next_sync_after" field's value of the SubscriptionBillingSyncState entity. +// If the SubscriptionBillingSyncState 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 *SubscriptionBillingSyncStateMutation) OldNextSyncAfter(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNextSyncAfter is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNextSyncAfter requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNextSyncAfter: %w", err) + } + return oldValue.NextSyncAfter, nil +} + +// ClearNextSyncAfter clears the value of the "next_sync_after" field. +func (m *SubscriptionBillingSyncStateMutation) ClearNextSyncAfter() { + m.next_sync_after = nil + m.clearedFields[subscriptionbillingsyncstate.FieldNextSyncAfter] = struct{}{} +} + +// NextSyncAfterCleared returns if the "next_sync_after" field was cleared in this mutation. +func (m *SubscriptionBillingSyncStateMutation) NextSyncAfterCleared() bool { + _, ok := m.clearedFields[subscriptionbillingsyncstate.FieldNextSyncAfter] + return ok +} + +// ResetNextSyncAfter resets all changes to the "next_sync_after" field. +func (m *SubscriptionBillingSyncStateMutation) ResetNextSyncAfter() { + m.next_sync_after = nil + delete(m.clearedFields, subscriptionbillingsyncstate.FieldNextSyncAfter) +} + +// ClearSubscription clears the "subscription" edge to the Subscription entity. +func (m *SubscriptionBillingSyncStateMutation) ClearSubscription() { + m.clearedsubscription = true + m.clearedFields[subscriptionbillingsyncstate.FieldSubscriptionID] = struct{}{} +} + +// SubscriptionCleared reports if the "subscription" edge to the Subscription entity was cleared. +func (m *SubscriptionBillingSyncStateMutation) SubscriptionCleared() bool { + return m.clearedsubscription +} + +// SubscriptionIDs returns the "subscription" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubscriptionID instead. It exists only for internal usage by the builders. +func (m *SubscriptionBillingSyncStateMutation) SubscriptionIDs() (ids []string) { + if id := m.subscription; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSubscription resets all changes to the "subscription" edge. +func (m *SubscriptionBillingSyncStateMutation) ResetSubscription() { + m.subscription = nil + m.clearedsubscription = false +} + +// Where appends a list predicates to the SubscriptionBillingSyncStateMutation builder. +func (m *SubscriptionBillingSyncStateMutation) Where(ps ...predicate.SubscriptionBillingSyncState) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SubscriptionBillingSyncStateMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SubscriptionBillingSyncStateMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.SubscriptionBillingSyncState, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *SubscriptionBillingSyncStateMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *SubscriptionBillingSyncStateMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (SubscriptionBillingSyncState). +func (m *SubscriptionBillingSyncStateMutation) 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 *SubscriptionBillingSyncStateMutation) Fields() []string { + fields := make([]string, 0, 5) + if m.namespace != nil { + fields = append(fields, subscriptionbillingsyncstate.FieldNamespace) + } + if m.subscription != nil { + fields = append(fields, subscriptionbillingsyncstate.FieldSubscriptionID) + } + if m.has_billables != nil { + fields = append(fields, subscriptionbillingsyncstate.FieldHasBillables) + } + if m.synced_at != nil { + fields = append(fields, subscriptionbillingsyncstate.FieldSyncedAt) + } + if m.next_sync_after != nil { + fields = append(fields, subscriptionbillingsyncstate.FieldNextSyncAfter) + } + 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 *SubscriptionBillingSyncStateMutation) Field(name string) (ent.Value, bool) { + switch name { + case subscriptionbillingsyncstate.FieldNamespace: + return m.Namespace() + case subscriptionbillingsyncstate.FieldSubscriptionID: + return m.SubscriptionID() + case subscriptionbillingsyncstate.FieldHasBillables: + return m.HasBillables() + case subscriptionbillingsyncstate.FieldSyncedAt: + return m.SyncedAt() + case subscriptionbillingsyncstate.FieldNextSyncAfter: + return m.NextSyncAfter() + } + 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 *SubscriptionBillingSyncStateMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case subscriptionbillingsyncstate.FieldNamespace: + return m.OldNamespace(ctx) + case subscriptionbillingsyncstate.FieldSubscriptionID: + return m.OldSubscriptionID(ctx) + case subscriptionbillingsyncstate.FieldHasBillables: + return m.OldHasBillables(ctx) + case subscriptionbillingsyncstate.FieldSyncedAt: + return m.OldSyncedAt(ctx) + case subscriptionbillingsyncstate.FieldNextSyncAfter: + return m.OldNextSyncAfter(ctx) + } + return nil, fmt.Errorf("unknown SubscriptionBillingSyncState 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 *SubscriptionBillingSyncStateMutation) SetField(name string, value ent.Value) error { + switch name { + case subscriptionbillingsyncstate.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case subscriptionbillingsyncstate.FieldSubscriptionID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionID(v) + return nil + case subscriptionbillingsyncstate.FieldHasBillables: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetHasBillables(v) + return nil + case subscriptionbillingsyncstate.FieldSyncedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSyncedAt(v) + return nil + case subscriptionbillingsyncstate.FieldNextSyncAfter: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNextSyncAfter(v) + return nil + } + return fmt.Errorf("unknown SubscriptionBillingSyncState field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SubscriptionBillingSyncStateMutation) 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 *SubscriptionBillingSyncStateMutation) 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 *SubscriptionBillingSyncStateMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown SubscriptionBillingSyncState numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SubscriptionBillingSyncStateMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(subscriptionbillingsyncstate.FieldNextSyncAfter) { + fields = append(fields, subscriptionbillingsyncstate.FieldNextSyncAfter) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SubscriptionBillingSyncStateMutation) 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 *SubscriptionBillingSyncStateMutation) ClearField(name string) error { + switch name { + case subscriptionbillingsyncstate.FieldNextSyncAfter: + m.ClearNextSyncAfter() + return nil + } + return fmt.Errorf("unknown SubscriptionBillingSyncState 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 *SubscriptionBillingSyncStateMutation) ResetField(name string) error { + switch name { + case subscriptionbillingsyncstate.FieldNamespace: + m.ResetNamespace() + return nil + case subscriptionbillingsyncstate.FieldSubscriptionID: + m.ResetSubscriptionID() + return nil + case subscriptionbillingsyncstate.FieldHasBillables: + m.ResetHasBillables() + return nil + case subscriptionbillingsyncstate.FieldSyncedAt: + m.ResetSyncedAt() + return nil + case subscriptionbillingsyncstate.FieldNextSyncAfter: + m.ResetNextSyncAfter() + return nil + } + return fmt.Errorf("unknown SubscriptionBillingSyncState field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SubscriptionBillingSyncStateMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.subscription != nil { + edges = append(edges, subscriptionbillingsyncstate.EdgeSubscription) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *SubscriptionBillingSyncStateMutation) AddedIDs(name string) []ent.Value { + switch name { + case subscriptionbillingsyncstate.EdgeSubscription: + if id := m.subscription; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SubscriptionBillingSyncStateMutation) 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 *SubscriptionBillingSyncStateMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SubscriptionBillingSyncStateMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedsubscription { + edges = append(edges, subscriptionbillingsyncstate.EdgeSubscription) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *SubscriptionBillingSyncStateMutation) EdgeCleared(name string) bool { + switch name { + case subscriptionbillingsyncstate.EdgeSubscription: + return m.clearedsubscription + } + 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 *SubscriptionBillingSyncStateMutation) ClearEdge(name string) error { + switch name { + case subscriptionbillingsyncstate.EdgeSubscription: + m.ClearSubscription() + return nil + } + return fmt.Errorf("unknown SubscriptionBillingSyncState 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 *SubscriptionBillingSyncStateMutation) ResetEdge(name string) error { + switch name { + case subscriptionbillingsyncstate.EdgeSubscription: + m.ResetSubscription() + return nil + } + return fmt.Errorf("unknown SubscriptionBillingSyncState edge %s", name) +} + +// SubscriptionItemMutation represents an operation that mutates the SubscriptionItem nodes in the graph. +type SubscriptionItemMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + metadata *map[string]string + tax_behavior *productcatalog.TaxBehavior + annotations *models.Annotations + active_from *time.Time + active_to *time.Time + key *string + restarts_billing_period *bool + active_from_override_relative_to_phase_start *datetime.ISODurationString + active_to_override_relative_to_phase_start *datetime.ISODurationString + name *string + description *string + feature_key *string + entitlement_template **productcatalog.EntitlementTemplate + tax_config **productcatalog.TaxConfig + billing_cadence *datetime.ISODurationString + price **productcatalog.Price + discounts **productcatalog.Discounts + unit_config **productcatalog.UnitConfig + clearedFields map[string]struct{} + phase *string + clearedphase bool + entitlement *string + clearedentitlement bool + billing_lines map[string]struct{} + removedbilling_lines map[string]struct{} + clearedbilling_lines bool + billing_split_line_groups map[string]struct{} + removedbilling_split_line_groups map[string]struct{} + clearedbilling_split_line_groups bool + charges_usage_based map[string]struct{} + removedcharges_usage_based map[string]struct{} + clearedcharges_usage_based bool + charges_credit_purchase map[string]struct{} + removedcharges_credit_purchase map[string]struct{} + clearedcharges_credit_purchase bool + charges_flat_fee map[string]struct{} + removedcharges_flat_fee map[string]struct{} + clearedcharges_flat_fee bool + tax_code *string + clearedtax_code bool + done bool + oldValue func(context.Context) (*SubscriptionItem, error) + predicates []predicate.SubscriptionItem +} + +var _ ent.Mutation = (*SubscriptionItemMutation)(nil) + +// subscriptionitemOption allows management of the mutation configuration using functional options. +type subscriptionitemOption func(*SubscriptionItemMutation) + +// newSubscriptionItemMutation creates new mutation for the SubscriptionItem entity. +func newSubscriptionItemMutation(c config, op Op, opts ...subscriptionitemOption) *SubscriptionItemMutation { + m := &SubscriptionItemMutation{ + config: c, + op: op, + typ: TypeSubscriptionItem, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withSubscriptionItemID sets the ID field of the mutation. +func withSubscriptionItemID(id string) subscriptionitemOption { + return func(m *SubscriptionItemMutation) { + var ( + err error + once sync.Once + value *SubscriptionItem + ) + m.oldValue = func(ctx context.Context) (*SubscriptionItem, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().SubscriptionItem.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withSubscriptionItem sets the old SubscriptionItem of the mutation. +func withSubscriptionItem(node *SubscriptionItem) subscriptionitemOption { + return func(m *SubscriptionItemMutation) { + m.oldValue = func(context.Context) (*SubscriptionItem, 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 SubscriptionItemMutation) 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 SubscriptionItemMutation) 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 SubscriptionItem entities. +func (m *SubscriptionItemMutation) 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 *SubscriptionItemMutation) 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 *SubscriptionItemMutation) 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().SubscriptionItem.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 *SubscriptionItemMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *SubscriptionItemMutation) 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 SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) 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 *SubscriptionItemMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *SubscriptionItemMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *SubscriptionItemMutation) 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 SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) 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 *SubscriptionItemMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *SubscriptionItemMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *SubscriptionItemMutation) 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 SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) 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 *SubscriptionItemMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *SubscriptionItemMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *SubscriptionItemMutation) 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 SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) 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 *SubscriptionItemMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[subscriptionitem.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *SubscriptionItemMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[subscriptionitem.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *SubscriptionItemMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, subscriptionitem.FieldDeletedAt) +} + +// SetMetadata sets the "metadata" field. +func (m *SubscriptionItemMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *SubscriptionItemMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *SubscriptionItemMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[subscriptionitem.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *SubscriptionItemMutation) MetadataCleared() bool { + _, ok := m.clearedFields[subscriptionitem.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *SubscriptionItemMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, subscriptionitem.FieldMetadata) +} + +// SetTaxCodeID sets the "tax_code_id" field. +func (m *SubscriptionItemMutation) SetTaxCodeID(s string) { + m.tax_code = &s +} + +// TaxCodeID returns the value of the "tax_code_id" field in the mutation. +func (m *SubscriptionItemMutation) TaxCodeID() (r string, exists bool) { + v := m.tax_code + if v == nil { + return + } + return *v, true +} + +// OldTaxCodeID returns the old "tax_code_id" field's value of the SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) OldTaxCodeID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxCodeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxCodeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxCodeID: %w", err) + } + return oldValue.TaxCodeID, nil +} + +// ClearTaxCodeID clears the value of the "tax_code_id" field. +func (m *SubscriptionItemMutation) ClearTaxCodeID() { + m.tax_code = nil + m.clearedFields[subscriptionitem.FieldTaxCodeID] = struct{}{} +} + +// TaxCodeIDCleared returns if the "tax_code_id" field was cleared in this mutation. +func (m *SubscriptionItemMutation) TaxCodeIDCleared() bool { + _, ok := m.clearedFields[subscriptionitem.FieldTaxCodeID] + return ok +} + +// ResetTaxCodeID resets all changes to the "tax_code_id" field. +func (m *SubscriptionItemMutation) ResetTaxCodeID() { + m.tax_code = nil + delete(m.clearedFields, subscriptionitem.FieldTaxCodeID) +} + +// SetTaxBehavior sets the "tax_behavior" field. +func (m *SubscriptionItemMutation) SetTaxBehavior(pb productcatalog.TaxBehavior) { + m.tax_behavior = &pb +} + +// TaxBehavior returns the value of the "tax_behavior" field in the mutation. +func (m *SubscriptionItemMutation) TaxBehavior() (r productcatalog.TaxBehavior, exists bool) { + v := m.tax_behavior + if v == nil { + return + } + return *v, true +} + +// OldTaxBehavior returns the old "tax_behavior" field's value of the SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) OldTaxBehavior(ctx context.Context) (v *productcatalog.TaxBehavior, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxBehavior is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxBehavior requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxBehavior: %w", err) + } + return oldValue.TaxBehavior, nil +} + +// ClearTaxBehavior clears the value of the "tax_behavior" field. +func (m *SubscriptionItemMutation) ClearTaxBehavior() { + m.tax_behavior = nil + m.clearedFields[subscriptionitem.FieldTaxBehavior] = struct{}{} +} + +// TaxBehaviorCleared returns if the "tax_behavior" field was cleared in this mutation. +func (m *SubscriptionItemMutation) TaxBehaviorCleared() bool { + _, ok := m.clearedFields[subscriptionitem.FieldTaxBehavior] + return ok +} + +// ResetTaxBehavior resets all changes to the "tax_behavior" field. +func (m *SubscriptionItemMutation) ResetTaxBehavior() { + m.tax_behavior = nil + delete(m.clearedFields, subscriptionitem.FieldTaxBehavior) +} + +// SetAnnotations sets the "annotations" field. +func (m *SubscriptionItemMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *SubscriptionItemMutation) 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 SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) 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 *SubscriptionItemMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[subscriptionitem.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *SubscriptionItemMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[subscriptionitem.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *SubscriptionItemMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, subscriptionitem.FieldAnnotations) +} + +// SetActiveFrom sets the "active_from" field. +func (m *SubscriptionItemMutation) SetActiveFrom(t time.Time) { + m.active_from = &t +} + +// ActiveFrom returns the value of the "active_from" field in the mutation. +func (m *SubscriptionItemMutation) ActiveFrom() (r time.Time, exists bool) { + v := m.active_from + if v == nil { + return + } + return *v, true +} + +// OldActiveFrom returns the old "active_from" field's value of the SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) OldActiveFrom(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldActiveFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldActiveFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldActiveFrom: %w", err) + } + return oldValue.ActiveFrom, nil +} + +// ResetActiveFrom resets all changes to the "active_from" field. +func (m *SubscriptionItemMutation) ResetActiveFrom() { + m.active_from = nil +} + +// SetActiveTo sets the "active_to" field. +func (m *SubscriptionItemMutation) SetActiveTo(t time.Time) { + m.active_to = &t +} + +// ActiveTo returns the value of the "active_to" field in the mutation. +func (m *SubscriptionItemMutation) ActiveTo() (r time.Time, exists bool) { + v := m.active_to + if v == nil { + return + } + return *v, true +} + +// OldActiveTo returns the old "active_to" field's value of the SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) OldActiveTo(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldActiveTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldActiveTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldActiveTo: %w", err) + } + return oldValue.ActiveTo, nil +} + +// ClearActiveTo clears the value of the "active_to" field. +func (m *SubscriptionItemMutation) ClearActiveTo() { + m.active_to = nil + m.clearedFields[subscriptionitem.FieldActiveTo] = struct{}{} +} + +// ActiveToCleared returns if the "active_to" field was cleared in this mutation. +func (m *SubscriptionItemMutation) ActiveToCleared() bool { + _, ok := m.clearedFields[subscriptionitem.FieldActiveTo] + return ok +} + +// ResetActiveTo resets all changes to the "active_to" field. +func (m *SubscriptionItemMutation) ResetActiveTo() { + m.active_to = nil + delete(m.clearedFields, subscriptionitem.FieldActiveTo) +} + +// SetPhaseID sets the "phase_id" field. +func (m *SubscriptionItemMutation) SetPhaseID(s string) { + m.phase = &s +} + +// PhaseID returns the value of the "phase_id" field in the mutation. +func (m *SubscriptionItemMutation) PhaseID() (r string, exists bool) { + v := m.phase + if v == nil { + return + } + return *v, true +} + +// OldPhaseID returns the old "phase_id" field's value of the SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) OldPhaseID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPhaseID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPhaseID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPhaseID: %w", err) + } + return oldValue.PhaseID, nil +} + +// ResetPhaseID resets all changes to the "phase_id" field. +func (m *SubscriptionItemMutation) ResetPhaseID() { + m.phase = nil +} + +// SetKey sets the "key" field. +func (m *SubscriptionItemMutation) SetKey(s string) { + m.key = &s +} + +// Key returns the value of the "key" field in the mutation. +func (m *SubscriptionItemMutation) Key() (r string, exists bool) { + v := m.key + if v == nil { + return + } + return *v, true +} + +// OldKey returns the old "key" field's value of the SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) OldKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldKey: %w", err) + } + return oldValue.Key, nil +} + +// ResetKey resets all changes to the "key" field. +func (m *SubscriptionItemMutation) ResetKey() { + m.key = nil +} + +// SetEntitlementID sets the "entitlement_id" field. +func (m *SubscriptionItemMutation) SetEntitlementID(s string) { + m.entitlement = &s +} + +// EntitlementID returns the value of the "entitlement_id" field in the mutation. +func (m *SubscriptionItemMutation) EntitlementID() (r string, exists bool) { + v := m.entitlement + if v == nil { + return + } + return *v, true +} + +// OldEntitlementID returns the old "entitlement_id" field's value of the SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) OldEntitlementID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEntitlementID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEntitlementID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEntitlementID: %w", err) + } + return oldValue.EntitlementID, nil +} + +// ClearEntitlementID clears the value of the "entitlement_id" field. +func (m *SubscriptionItemMutation) ClearEntitlementID() { + m.entitlement = nil + m.clearedFields[subscriptionitem.FieldEntitlementID] = struct{}{} +} + +// EntitlementIDCleared returns if the "entitlement_id" field was cleared in this mutation. +func (m *SubscriptionItemMutation) EntitlementIDCleared() bool { + _, ok := m.clearedFields[subscriptionitem.FieldEntitlementID] + return ok +} + +// ResetEntitlementID resets all changes to the "entitlement_id" field. +func (m *SubscriptionItemMutation) ResetEntitlementID() { + m.entitlement = nil + delete(m.clearedFields, subscriptionitem.FieldEntitlementID) +} + +// SetRestartsBillingPeriod sets the "restarts_billing_period" field. +func (m *SubscriptionItemMutation) SetRestartsBillingPeriod(b bool) { + m.restarts_billing_period = &b +} + +// RestartsBillingPeriod returns the value of the "restarts_billing_period" field in the mutation. +func (m *SubscriptionItemMutation) RestartsBillingPeriod() (r bool, exists bool) { + v := m.restarts_billing_period + if v == nil { + return + } + return *v, true +} + +// OldRestartsBillingPeriod returns the old "restarts_billing_period" field's value of the SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) OldRestartsBillingPeriod(ctx context.Context) (v *bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRestartsBillingPeriod is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRestartsBillingPeriod requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRestartsBillingPeriod: %w", err) + } + return oldValue.RestartsBillingPeriod, nil +} + +// ClearRestartsBillingPeriod clears the value of the "restarts_billing_period" field. +func (m *SubscriptionItemMutation) ClearRestartsBillingPeriod() { + m.restarts_billing_period = nil + m.clearedFields[subscriptionitem.FieldRestartsBillingPeriod] = struct{}{} +} + +// RestartsBillingPeriodCleared returns if the "restarts_billing_period" field was cleared in this mutation. +func (m *SubscriptionItemMutation) RestartsBillingPeriodCleared() bool { + _, ok := m.clearedFields[subscriptionitem.FieldRestartsBillingPeriod] + return ok +} + +// ResetRestartsBillingPeriod resets all changes to the "restarts_billing_period" field. +func (m *SubscriptionItemMutation) ResetRestartsBillingPeriod() { + m.restarts_billing_period = nil + delete(m.clearedFields, subscriptionitem.FieldRestartsBillingPeriod) +} + +// SetActiveFromOverrideRelativeToPhaseStart sets the "active_from_override_relative_to_phase_start" field. +func (m *SubscriptionItemMutation) SetActiveFromOverrideRelativeToPhaseStart(dds datetime.ISODurationString) { + m.active_from_override_relative_to_phase_start = &dds +} + +// ActiveFromOverrideRelativeToPhaseStart returns the value of the "active_from_override_relative_to_phase_start" field in the mutation. +func (m *SubscriptionItemMutation) ActiveFromOverrideRelativeToPhaseStart() (r datetime.ISODurationString, exists bool) { + v := m.active_from_override_relative_to_phase_start + if v == nil { + return + } + return *v, true +} + +// OldActiveFromOverrideRelativeToPhaseStart returns the old "active_from_override_relative_to_phase_start" field's value of the SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) OldActiveFromOverrideRelativeToPhaseStart(ctx context.Context) (v *datetime.ISODurationString, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldActiveFromOverrideRelativeToPhaseStart is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldActiveFromOverrideRelativeToPhaseStart requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldActiveFromOverrideRelativeToPhaseStart: %w", err) + } + return oldValue.ActiveFromOverrideRelativeToPhaseStart, nil +} + +// ClearActiveFromOverrideRelativeToPhaseStart clears the value of the "active_from_override_relative_to_phase_start" field. +func (m *SubscriptionItemMutation) ClearActiveFromOverrideRelativeToPhaseStart() { + m.active_from_override_relative_to_phase_start = nil + m.clearedFields[subscriptionitem.FieldActiveFromOverrideRelativeToPhaseStart] = struct{}{} +} + +// ActiveFromOverrideRelativeToPhaseStartCleared returns if the "active_from_override_relative_to_phase_start" field was cleared in this mutation. +func (m *SubscriptionItemMutation) ActiveFromOverrideRelativeToPhaseStartCleared() bool { + _, ok := m.clearedFields[subscriptionitem.FieldActiveFromOverrideRelativeToPhaseStart] + return ok +} + +// ResetActiveFromOverrideRelativeToPhaseStart resets all changes to the "active_from_override_relative_to_phase_start" field. +func (m *SubscriptionItemMutation) ResetActiveFromOverrideRelativeToPhaseStart() { + m.active_from_override_relative_to_phase_start = nil + delete(m.clearedFields, subscriptionitem.FieldActiveFromOverrideRelativeToPhaseStart) +} + +// SetActiveToOverrideRelativeToPhaseStart sets the "active_to_override_relative_to_phase_start" field. +func (m *SubscriptionItemMutation) SetActiveToOverrideRelativeToPhaseStart(dds datetime.ISODurationString) { + m.active_to_override_relative_to_phase_start = &dds +} + +// ActiveToOverrideRelativeToPhaseStart returns the value of the "active_to_override_relative_to_phase_start" field in the mutation. +func (m *SubscriptionItemMutation) ActiveToOverrideRelativeToPhaseStart() (r datetime.ISODurationString, exists bool) { + v := m.active_to_override_relative_to_phase_start + if v == nil { + return + } + return *v, true +} + +// OldActiveToOverrideRelativeToPhaseStart returns the old "active_to_override_relative_to_phase_start" field's value of the SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) OldActiveToOverrideRelativeToPhaseStart(ctx context.Context) (v *datetime.ISODurationString, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldActiveToOverrideRelativeToPhaseStart is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldActiveToOverrideRelativeToPhaseStart requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldActiveToOverrideRelativeToPhaseStart: %w", err) + } + return oldValue.ActiveToOverrideRelativeToPhaseStart, nil +} + +// ClearActiveToOverrideRelativeToPhaseStart clears the value of the "active_to_override_relative_to_phase_start" field. +func (m *SubscriptionItemMutation) ClearActiveToOverrideRelativeToPhaseStart() { + m.active_to_override_relative_to_phase_start = nil + m.clearedFields[subscriptionitem.FieldActiveToOverrideRelativeToPhaseStart] = struct{}{} +} + +// ActiveToOverrideRelativeToPhaseStartCleared returns if the "active_to_override_relative_to_phase_start" field was cleared in this mutation. +func (m *SubscriptionItemMutation) ActiveToOverrideRelativeToPhaseStartCleared() bool { + _, ok := m.clearedFields[subscriptionitem.FieldActiveToOverrideRelativeToPhaseStart] + return ok +} + +// ResetActiveToOverrideRelativeToPhaseStart resets all changes to the "active_to_override_relative_to_phase_start" field. +func (m *SubscriptionItemMutation) ResetActiveToOverrideRelativeToPhaseStart() { + m.active_to_override_relative_to_phase_start = nil + delete(m.clearedFields, subscriptionitem.FieldActiveToOverrideRelativeToPhaseStart) +} + +// SetName sets the "name" field. +func (m *SubscriptionItemMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *SubscriptionItemMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *SubscriptionItemMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *SubscriptionItemMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *SubscriptionItemMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *SubscriptionItemMutation) ClearDescription() { + m.description = nil + m.clearedFields[subscriptionitem.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *SubscriptionItemMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[subscriptionitem.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *SubscriptionItemMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, subscriptionitem.FieldDescription) +} + +// SetFeatureKey sets the "feature_key" field. +func (m *SubscriptionItemMutation) SetFeatureKey(s string) { + m.feature_key = &s +} + +// FeatureKey returns the value of the "feature_key" field in the mutation. +func (m *SubscriptionItemMutation) 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 SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) 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 +} + +// ClearFeatureKey clears the value of the "feature_key" field. +func (m *SubscriptionItemMutation) ClearFeatureKey() { + m.feature_key = nil + m.clearedFields[subscriptionitem.FieldFeatureKey] = struct{}{} +} + +// FeatureKeyCleared returns if the "feature_key" field was cleared in this mutation. +func (m *SubscriptionItemMutation) FeatureKeyCleared() bool { + _, ok := m.clearedFields[subscriptionitem.FieldFeatureKey] + return ok +} + +// ResetFeatureKey resets all changes to the "feature_key" field. +func (m *SubscriptionItemMutation) ResetFeatureKey() { + m.feature_key = nil + delete(m.clearedFields, subscriptionitem.FieldFeatureKey) +} + +// SetEntitlementTemplate sets the "entitlement_template" field. +func (m *SubscriptionItemMutation) SetEntitlementTemplate(pt *productcatalog.EntitlementTemplate) { + m.entitlement_template = &pt +} + +// EntitlementTemplate returns the value of the "entitlement_template" field in the mutation. +func (m *SubscriptionItemMutation) EntitlementTemplate() (r *productcatalog.EntitlementTemplate, exists bool) { + v := m.entitlement_template + if v == nil { + return + } + return *v, true +} + +// OldEntitlementTemplate returns the old "entitlement_template" field's value of the SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) OldEntitlementTemplate(ctx context.Context) (v *productcatalog.EntitlementTemplate, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEntitlementTemplate is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEntitlementTemplate requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEntitlementTemplate: %w", err) + } + return oldValue.EntitlementTemplate, nil +} + +// ClearEntitlementTemplate clears the value of the "entitlement_template" field. +func (m *SubscriptionItemMutation) ClearEntitlementTemplate() { + m.entitlement_template = nil + m.clearedFields[subscriptionitem.FieldEntitlementTemplate] = struct{}{} +} + +// EntitlementTemplateCleared returns if the "entitlement_template" field was cleared in this mutation. +func (m *SubscriptionItemMutation) EntitlementTemplateCleared() bool { + _, ok := m.clearedFields[subscriptionitem.FieldEntitlementTemplate] + return ok +} + +// ResetEntitlementTemplate resets all changes to the "entitlement_template" field. +func (m *SubscriptionItemMutation) ResetEntitlementTemplate() { + m.entitlement_template = nil + delete(m.clearedFields, subscriptionitem.FieldEntitlementTemplate) +} + +// SetTaxConfig sets the "tax_config" field. +func (m *SubscriptionItemMutation) SetTaxConfig(pc *productcatalog.TaxConfig) { + m.tax_config = &pc +} + +// TaxConfig returns the value of the "tax_config" field in the mutation. +func (m *SubscriptionItemMutation) TaxConfig() (r *productcatalog.TaxConfig, exists bool) { + v := m.tax_config + if v == nil { + return + } + return *v, true +} + +// OldTaxConfig returns the old "tax_config" field's value of the SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) OldTaxConfig(ctx context.Context) (v *productcatalog.TaxConfig, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxConfig is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxConfig requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxConfig: %w", err) + } + return oldValue.TaxConfig, nil +} + +// ClearTaxConfig clears the value of the "tax_config" field. +func (m *SubscriptionItemMutation) ClearTaxConfig() { + m.tax_config = nil + m.clearedFields[subscriptionitem.FieldTaxConfig] = struct{}{} +} + +// TaxConfigCleared returns if the "tax_config" field was cleared in this mutation. +func (m *SubscriptionItemMutation) TaxConfigCleared() bool { + _, ok := m.clearedFields[subscriptionitem.FieldTaxConfig] + return ok +} + +// ResetTaxConfig resets all changes to the "tax_config" field. +func (m *SubscriptionItemMutation) ResetTaxConfig() { + m.tax_config = nil + delete(m.clearedFields, subscriptionitem.FieldTaxConfig) +} + +// SetBillingCadence sets the "billing_cadence" field. +func (m *SubscriptionItemMutation) SetBillingCadence(dds datetime.ISODurationString) { + m.billing_cadence = &dds +} + +// BillingCadence returns the value of the "billing_cadence" field in the mutation. +func (m *SubscriptionItemMutation) BillingCadence() (r datetime.ISODurationString, exists bool) { + v := m.billing_cadence + if v == nil { + return + } + return *v, true +} + +// OldBillingCadence returns the old "billing_cadence" field's value of the SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) OldBillingCadence(ctx context.Context) (v *datetime.ISODurationString, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBillingCadence is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBillingCadence requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBillingCadence: %w", err) + } + return oldValue.BillingCadence, nil +} + +// ClearBillingCadence clears the value of the "billing_cadence" field. +func (m *SubscriptionItemMutation) ClearBillingCadence() { + m.billing_cadence = nil + m.clearedFields[subscriptionitem.FieldBillingCadence] = struct{}{} +} + +// BillingCadenceCleared returns if the "billing_cadence" field was cleared in this mutation. +func (m *SubscriptionItemMutation) BillingCadenceCleared() bool { + _, ok := m.clearedFields[subscriptionitem.FieldBillingCadence] + return ok +} + +// ResetBillingCadence resets all changes to the "billing_cadence" field. +func (m *SubscriptionItemMutation) ResetBillingCadence() { + m.billing_cadence = nil + delete(m.clearedFields, subscriptionitem.FieldBillingCadence) +} + +// SetPrice sets the "price" field. +func (m *SubscriptionItemMutation) SetPrice(pr *productcatalog.Price) { + m.price = &pr +} + +// Price returns the value of the "price" field in the mutation. +func (m *SubscriptionItemMutation) 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 SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) 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 +} + +// ClearPrice clears the value of the "price" field. +func (m *SubscriptionItemMutation) ClearPrice() { + m.price = nil + m.clearedFields[subscriptionitem.FieldPrice] = struct{}{} +} + +// PriceCleared returns if the "price" field was cleared in this mutation. +func (m *SubscriptionItemMutation) PriceCleared() bool { + _, ok := m.clearedFields[subscriptionitem.FieldPrice] + return ok +} + +// ResetPrice resets all changes to the "price" field. +func (m *SubscriptionItemMutation) ResetPrice() { + m.price = nil + delete(m.clearedFields, subscriptionitem.FieldPrice) +} + +// SetDiscounts sets the "discounts" field. +func (m *SubscriptionItemMutation) SetDiscounts(pr *productcatalog.Discounts) { + m.discounts = &pr +} + +// Discounts returns the value of the "discounts" field in the mutation. +func (m *SubscriptionItemMutation) 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 SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) 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 *SubscriptionItemMutation) ClearDiscounts() { + m.discounts = nil + m.clearedFields[subscriptionitem.FieldDiscounts] = struct{}{} +} + +// DiscountsCleared returns if the "discounts" field was cleared in this mutation. +func (m *SubscriptionItemMutation) DiscountsCleared() bool { + _, ok := m.clearedFields[subscriptionitem.FieldDiscounts] + return ok +} + +// ResetDiscounts resets all changes to the "discounts" field. +func (m *SubscriptionItemMutation) ResetDiscounts() { + m.discounts = nil + delete(m.clearedFields, subscriptionitem.FieldDiscounts) +} + +// SetUnitConfig sets the "unit_config" field. +func (m *SubscriptionItemMutation) SetUnitConfig(pc *productcatalog.UnitConfig) { + m.unit_config = &pc +} + +// UnitConfig returns the value of the "unit_config" field in the mutation. +func (m *SubscriptionItemMutation) UnitConfig() (r *productcatalog.UnitConfig, exists bool) { + v := m.unit_config + if v == nil { + return + } + return *v, true +} + +// OldUnitConfig returns the old "unit_config" field's value of the SubscriptionItem entity. +// If the SubscriptionItem 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 *SubscriptionItemMutation) OldUnitConfig(ctx context.Context) (v *productcatalog.UnitConfig, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUnitConfig is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUnitConfig requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUnitConfig: %w", err) + } + return oldValue.UnitConfig, nil +} + +// ClearUnitConfig clears the value of the "unit_config" field. +func (m *SubscriptionItemMutation) ClearUnitConfig() { + m.unit_config = nil + m.clearedFields[subscriptionitem.FieldUnitConfig] = struct{}{} +} + +// UnitConfigCleared returns if the "unit_config" field was cleared in this mutation. +func (m *SubscriptionItemMutation) UnitConfigCleared() bool { + _, ok := m.clearedFields[subscriptionitem.FieldUnitConfig] + return ok +} + +// ResetUnitConfig resets all changes to the "unit_config" field. +func (m *SubscriptionItemMutation) ResetUnitConfig() { + m.unit_config = nil + delete(m.clearedFields, subscriptionitem.FieldUnitConfig) +} + +// ClearPhase clears the "phase" edge to the SubscriptionPhase entity. +func (m *SubscriptionItemMutation) ClearPhase() { + m.clearedphase = true + m.clearedFields[subscriptionitem.FieldPhaseID] = struct{}{} +} + +// PhaseCleared reports if the "phase" edge to the SubscriptionPhase entity was cleared. +func (m *SubscriptionItemMutation) PhaseCleared() bool { + return m.clearedphase +} + +// PhaseIDs returns the "phase" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// PhaseID instead. It exists only for internal usage by the builders. +func (m *SubscriptionItemMutation) PhaseIDs() (ids []string) { + if id := m.phase; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetPhase resets all changes to the "phase" edge. +func (m *SubscriptionItemMutation) ResetPhase() { + m.phase = nil + m.clearedphase = false +} + +// ClearEntitlement clears the "entitlement" edge to the Entitlement entity. +func (m *SubscriptionItemMutation) ClearEntitlement() { + m.clearedentitlement = true + m.clearedFields[subscriptionitem.FieldEntitlementID] = struct{}{} +} + +// EntitlementCleared reports if the "entitlement" edge to the Entitlement entity was cleared. +func (m *SubscriptionItemMutation) EntitlementCleared() bool { + return m.EntitlementIDCleared() || m.clearedentitlement +} + +// EntitlementIDs returns the "entitlement" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// EntitlementID instead. It exists only for internal usage by the builders. +func (m *SubscriptionItemMutation) EntitlementIDs() (ids []string) { + if id := m.entitlement; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetEntitlement resets all changes to the "entitlement" edge. +func (m *SubscriptionItemMutation) ResetEntitlement() { + m.entitlement = nil + m.clearedentitlement = false +} + +// AddBillingLineIDs adds the "billing_lines" edge to the BillingInvoiceLine entity by ids. +func (m *SubscriptionItemMutation) AddBillingLineIDs(ids ...string) { + if m.billing_lines == nil { + m.billing_lines = make(map[string]struct{}) + } + for i := range ids { + m.billing_lines[ids[i]] = struct{}{} + } +} + +// ClearBillingLines clears the "billing_lines" edge to the BillingInvoiceLine entity. +func (m *SubscriptionItemMutation) ClearBillingLines() { + m.clearedbilling_lines = true +} + +// BillingLinesCleared reports if the "billing_lines" edge to the BillingInvoiceLine entity was cleared. +func (m *SubscriptionItemMutation) BillingLinesCleared() bool { + return m.clearedbilling_lines +} + +// RemoveBillingLineIDs removes the "billing_lines" edge to the BillingInvoiceLine entity by IDs. +func (m *SubscriptionItemMutation) RemoveBillingLineIDs(ids ...string) { + if m.removedbilling_lines == nil { + m.removedbilling_lines = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_lines, ids[i]) + m.removedbilling_lines[ids[i]] = struct{}{} + } +} + +// RemovedBillingLines returns the removed IDs of the "billing_lines" edge to the BillingInvoiceLine entity. +func (m *SubscriptionItemMutation) RemovedBillingLinesIDs() (ids []string) { + for id := range m.removedbilling_lines { + ids = append(ids, id) + } + return +} + +// BillingLinesIDs returns the "billing_lines" edge IDs in the mutation. +func (m *SubscriptionItemMutation) BillingLinesIDs() (ids []string) { + for id := range m.billing_lines { + ids = append(ids, id) + } + return +} + +// ResetBillingLines resets all changes to the "billing_lines" edge. +func (m *SubscriptionItemMutation) ResetBillingLines() { + m.billing_lines = nil + m.clearedbilling_lines = false + m.removedbilling_lines = nil +} + +// AddBillingSplitLineGroupIDs adds the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity by ids. +func (m *SubscriptionItemMutation) AddBillingSplitLineGroupIDs(ids ...string) { + if m.billing_split_line_groups == nil { + m.billing_split_line_groups = make(map[string]struct{}) + } + for i := range ids { + m.billing_split_line_groups[ids[i]] = struct{}{} + } +} + +// ClearBillingSplitLineGroups clears the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity. +func (m *SubscriptionItemMutation) ClearBillingSplitLineGroups() { + m.clearedbilling_split_line_groups = true +} + +// BillingSplitLineGroupsCleared reports if the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity was cleared. +func (m *SubscriptionItemMutation) BillingSplitLineGroupsCleared() bool { + return m.clearedbilling_split_line_groups +} + +// RemoveBillingSplitLineGroupIDs removes the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity by IDs. +func (m *SubscriptionItemMutation) RemoveBillingSplitLineGroupIDs(ids ...string) { + if m.removedbilling_split_line_groups == nil { + m.removedbilling_split_line_groups = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_split_line_groups, ids[i]) + m.removedbilling_split_line_groups[ids[i]] = struct{}{} + } +} + +// RemovedBillingSplitLineGroups returns the removed IDs of the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity. +func (m *SubscriptionItemMutation) RemovedBillingSplitLineGroupsIDs() (ids []string) { + for id := range m.removedbilling_split_line_groups { + ids = append(ids, id) + } + return +} + +// BillingSplitLineGroupsIDs returns the "billing_split_line_groups" edge IDs in the mutation. +func (m *SubscriptionItemMutation) BillingSplitLineGroupsIDs() (ids []string) { + for id := range m.billing_split_line_groups { + ids = append(ids, id) + } + return +} + +// ResetBillingSplitLineGroups resets all changes to the "billing_split_line_groups" edge. +func (m *SubscriptionItemMutation) ResetBillingSplitLineGroups() { + m.billing_split_line_groups = nil + m.clearedbilling_split_line_groups = false + m.removedbilling_split_line_groups = nil +} + +// AddChargesUsageBasedIDs adds the "charges_usage_based" edge to the ChargeUsageBased entity by ids. +func (m *SubscriptionItemMutation) AddChargesUsageBasedIDs(ids ...string) { + if m.charges_usage_based == nil { + m.charges_usage_based = make(map[string]struct{}) + } + for i := range ids { + m.charges_usage_based[ids[i]] = struct{}{} + } +} + +// ClearChargesUsageBased clears the "charges_usage_based" edge to the ChargeUsageBased entity. +func (m *SubscriptionItemMutation) ClearChargesUsageBased() { + m.clearedcharges_usage_based = true +} + +// ChargesUsageBasedCleared reports if the "charges_usage_based" edge to the ChargeUsageBased entity was cleared. +func (m *SubscriptionItemMutation) ChargesUsageBasedCleared() bool { + return m.clearedcharges_usage_based +} + +// RemoveChargesUsageBasedIDs removes the "charges_usage_based" edge to the ChargeUsageBased entity by IDs. +func (m *SubscriptionItemMutation) RemoveChargesUsageBasedIDs(ids ...string) { + if m.removedcharges_usage_based == nil { + m.removedcharges_usage_based = make(map[string]struct{}) + } + for i := range ids { + delete(m.charges_usage_based, ids[i]) + m.removedcharges_usage_based[ids[i]] = struct{}{} + } +} + +// RemovedChargesUsageBased returns the removed IDs of the "charges_usage_based" edge to the ChargeUsageBased entity. +func (m *SubscriptionItemMutation) RemovedChargesUsageBasedIDs() (ids []string) { + for id := range m.removedcharges_usage_based { + ids = append(ids, id) + } + return +} + +// ChargesUsageBasedIDs returns the "charges_usage_based" edge IDs in the mutation. +func (m *SubscriptionItemMutation) ChargesUsageBasedIDs() (ids []string) { + for id := range m.charges_usage_based { + ids = append(ids, id) + } + return +} + +// ResetChargesUsageBased resets all changes to the "charges_usage_based" edge. +func (m *SubscriptionItemMutation) ResetChargesUsageBased() { + m.charges_usage_based = nil + m.clearedcharges_usage_based = false + m.removedcharges_usage_based = nil +} + +// AddChargesCreditPurchaseIDs adds the "charges_credit_purchase" edge to the ChargeCreditPurchase entity by ids. +func (m *SubscriptionItemMutation) AddChargesCreditPurchaseIDs(ids ...string) { + if m.charges_credit_purchase == nil { + m.charges_credit_purchase = make(map[string]struct{}) + } + for i := range ids { + m.charges_credit_purchase[ids[i]] = struct{}{} + } +} + +// ClearChargesCreditPurchase clears the "charges_credit_purchase" edge to the ChargeCreditPurchase entity. +func (m *SubscriptionItemMutation) ClearChargesCreditPurchase() { + m.clearedcharges_credit_purchase = true +} + +// ChargesCreditPurchaseCleared reports if the "charges_credit_purchase" edge to the ChargeCreditPurchase entity was cleared. +func (m *SubscriptionItemMutation) ChargesCreditPurchaseCleared() bool { + return m.clearedcharges_credit_purchase +} + +// RemoveChargesCreditPurchaseIDs removes the "charges_credit_purchase" edge to the ChargeCreditPurchase entity by IDs. +func (m *SubscriptionItemMutation) RemoveChargesCreditPurchaseIDs(ids ...string) { + if m.removedcharges_credit_purchase == nil { + m.removedcharges_credit_purchase = make(map[string]struct{}) + } + for i := range ids { + delete(m.charges_credit_purchase, ids[i]) + m.removedcharges_credit_purchase[ids[i]] = struct{}{} + } +} + +// RemovedChargesCreditPurchase returns the removed IDs of the "charges_credit_purchase" edge to the ChargeCreditPurchase entity. +func (m *SubscriptionItemMutation) RemovedChargesCreditPurchaseIDs() (ids []string) { + for id := range m.removedcharges_credit_purchase { + ids = append(ids, id) + } + return +} + +// ChargesCreditPurchaseIDs returns the "charges_credit_purchase" edge IDs in the mutation. +func (m *SubscriptionItemMutation) ChargesCreditPurchaseIDs() (ids []string) { + for id := range m.charges_credit_purchase { + ids = append(ids, id) + } + return +} + +// ResetChargesCreditPurchase resets all changes to the "charges_credit_purchase" edge. +func (m *SubscriptionItemMutation) ResetChargesCreditPurchase() { + m.charges_credit_purchase = nil + m.clearedcharges_credit_purchase = false + m.removedcharges_credit_purchase = nil +} + +// AddChargesFlatFeeIDs adds the "charges_flat_fee" edge to the ChargeFlatFee entity by ids. +func (m *SubscriptionItemMutation) AddChargesFlatFeeIDs(ids ...string) { + if m.charges_flat_fee == nil { + m.charges_flat_fee = make(map[string]struct{}) + } + for i := range ids { + m.charges_flat_fee[ids[i]] = struct{}{} + } +} + +// ClearChargesFlatFee clears the "charges_flat_fee" edge to the ChargeFlatFee entity. +func (m *SubscriptionItemMutation) ClearChargesFlatFee() { + m.clearedcharges_flat_fee = true +} + +// ChargesFlatFeeCleared reports if the "charges_flat_fee" edge to the ChargeFlatFee entity was cleared. +func (m *SubscriptionItemMutation) ChargesFlatFeeCleared() bool { + return m.clearedcharges_flat_fee +} + +// RemoveChargesFlatFeeIDs removes the "charges_flat_fee" edge to the ChargeFlatFee entity by IDs. +func (m *SubscriptionItemMutation) RemoveChargesFlatFeeIDs(ids ...string) { + if m.removedcharges_flat_fee == nil { + m.removedcharges_flat_fee = make(map[string]struct{}) + } + for i := range ids { + delete(m.charges_flat_fee, ids[i]) + m.removedcharges_flat_fee[ids[i]] = struct{}{} + } +} + +// RemovedChargesFlatFee returns the removed IDs of the "charges_flat_fee" edge to the ChargeFlatFee entity. +func (m *SubscriptionItemMutation) RemovedChargesFlatFeeIDs() (ids []string) { + for id := range m.removedcharges_flat_fee { + ids = append(ids, id) + } + return +} + +// ChargesFlatFeeIDs returns the "charges_flat_fee" edge IDs in the mutation. +func (m *SubscriptionItemMutation) ChargesFlatFeeIDs() (ids []string) { + for id := range m.charges_flat_fee { + ids = append(ids, id) + } + return +} + +// ResetChargesFlatFee resets all changes to the "charges_flat_fee" edge. +func (m *SubscriptionItemMutation) ResetChargesFlatFee() { + m.charges_flat_fee = nil + m.clearedcharges_flat_fee = false + m.removedcharges_flat_fee = nil +} + +// ClearTaxCode clears the "tax_code" edge to the TaxCode entity. +func (m *SubscriptionItemMutation) ClearTaxCode() { + m.clearedtax_code = true + m.clearedFields[subscriptionitem.FieldTaxCodeID] = struct{}{} +} + +// TaxCodeCleared reports if the "tax_code" edge to the TaxCode entity was cleared. +func (m *SubscriptionItemMutation) TaxCodeCleared() bool { + return m.TaxCodeIDCleared() || m.clearedtax_code +} + +// TaxCodeIDs returns the "tax_code" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TaxCodeID instead. It exists only for internal usage by the builders. +func (m *SubscriptionItemMutation) TaxCodeIDs() (ids []string) { + if id := m.tax_code; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTaxCode resets all changes to the "tax_code" edge. +func (m *SubscriptionItemMutation) ResetTaxCode() { + m.tax_code = nil + m.clearedtax_code = false +} + +// Where appends a list predicates to the SubscriptionItemMutation builder. +func (m *SubscriptionItemMutation) Where(ps ...predicate.SubscriptionItem) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SubscriptionItemMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SubscriptionItemMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.SubscriptionItem, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *SubscriptionItemMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *SubscriptionItemMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (SubscriptionItem). +func (m *SubscriptionItemMutation) 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 *SubscriptionItemMutation) Fields() []string { + fields := make([]string, 0, 25) + if m.namespace != nil { + fields = append(fields, subscriptionitem.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, subscriptionitem.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, subscriptionitem.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, subscriptionitem.FieldDeletedAt) + } + if m.metadata != nil { + fields = append(fields, subscriptionitem.FieldMetadata) + } + if m.tax_code != nil { + fields = append(fields, subscriptionitem.FieldTaxCodeID) + } + if m.tax_behavior != nil { + fields = append(fields, subscriptionitem.FieldTaxBehavior) + } + if m.annotations != nil { + fields = append(fields, subscriptionitem.FieldAnnotations) + } + if m.active_from != nil { + fields = append(fields, subscriptionitem.FieldActiveFrom) + } + if m.active_to != nil { + fields = append(fields, subscriptionitem.FieldActiveTo) + } + if m.phase != nil { + fields = append(fields, subscriptionitem.FieldPhaseID) + } + if m.key != nil { + fields = append(fields, subscriptionitem.FieldKey) + } + if m.entitlement != nil { + fields = append(fields, subscriptionitem.FieldEntitlementID) + } + if m.restarts_billing_period != nil { + fields = append(fields, subscriptionitem.FieldRestartsBillingPeriod) + } + if m.active_from_override_relative_to_phase_start != nil { + fields = append(fields, subscriptionitem.FieldActiveFromOverrideRelativeToPhaseStart) + } + if m.active_to_override_relative_to_phase_start != nil { + fields = append(fields, subscriptionitem.FieldActiveToOverrideRelativeToPhaseStart) + } + if m.name != nil { + fields = append(fields, subscriptionitem.FieldName) + } + if m.description != nil { + fields = append(fields, subscriptionitem.FieldDescription) + } + if m.feature_key != nil { + fields = append(fields, subscriptionitem.FieldFeatureKey) + } + if m.entitlement_template != nil { + fields = append(fields, subscriptionitem.FieldEntitlementTemplate) + } + if m.tax_config != nil { + fields = append(fields, subscriptionitem.FieldTaxConfig) + } + if m.billing_cadence != nil { + fields = append(fields, subscriptionitem.FieldBillingCadence) + } + if m.price != nil { + fields = append(fields, subscriptionitem.FieldPrice) + } + if m.discounts != nil { + fields = append(fields, subscriptionitem.FieldDiscounts) + } + if m.unit_config != nil { + fields = append(fields, subscriptionitem.FieldUnitConfig) + } + 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 *SubscriptionItemMutation) Field(name string) (ent.Value, bool) { + switch name { + case subscriptionitem.FieldNamespace: + return m.Namespace() + case subscriptionitem.FieldCreatedAt: + return m.CreatedAt() + case subscriptionitem.FieldUpdatedAt: + return m.UpdatedAt() + case subscriptionitem.FieldDeletedAt: + return m.DeletedAt() + case subscriptionitem.FieldMetadata: + return m.Metadata() + case subscriptionitem.FieldTaxCodeID: + return m.TaxCodeID() + case subscriptionitem.FieldTaxBehavior: + return m.TaxBehavior() + case subscriptionitem.FieldAnnotations: + return m.Annotations() + case subscriptionitem.FieldActiveFrom: + return m.ActiveFrom() + case subscriptionitem.FieldActiveTo: + return m.ActiveTo() + case subscriptionitem.FieldPhaseID: + return m.PhaseID() + case subscriptionitem.FieldKey: + return m.Key() + case subscriptionitem.FieldEntitlementID: + return m.EntitlementID() + case subscriptionitem.FieldRestartsBillingPeriod: + return m.RestartsBillingPeriod() + case subscriptionitem.FieldActiveFromOverrideRelativeToPhaseStart: + return m.ActiveFromOverrideRelativeToPhaseStart() + case subscriptionitem.FieldActiveToOverrideRelativeToPhaseStart: + return m.ActiveToOverrideRelativeToPhaseStart() + case subscriptionitem.FieldName: + return m.Name() + case subscriptionitem.FieldDescription: + return m.Description() + case subscriptionitem.FieldFeatureKey: + return m.FeatureKey() + case subscriptionitem.FieldEntitlementTemplate: + return m.EntitlementTemplate() + case subscriptionitem.FieldTaxConfig: + return m.TaxConfig() + case subscriptionitem.FieldBillingCadence: + return m.BillingCadence() + case subscriptionitem.FieldPrice: + return m.Price() + case subscriptionitem.FieldDiscounts: + return m.Discounts() + case subscriptionitem.FieldUnitConfig: + return m.UnitConfig() + } + 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 *SubscriptionItemMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case subscriptionitem.FieldNamespace: + return m.OldNamespace(ctx) + case subscriptionitem.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case subscriptionitem.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case subscriptionitem.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case subscriptionitem.FieldMetadata: + return m.OldMetadata(ctx) + case subscriptionitem.FieldTaxCodeID: + return m.OldTaxCodeID(ctx) + case subscriptionitem.FieldTaxBehavior: + return m.OldTaxBehavior(ctx) + case subscriptionitem.FieldAnnotations: + return m.OldAnnotations(ctx) + case subscriptionitem.FieldActiveFrom: + return m.OldActiveFrom(ctx) + case subscriptionitem.FieldActiveTo: + return m.OldActiveTo(ctx) + case subscriptionitem.FieldPhaseID: + return m.OldPhaseID(ctx) + case subscriptionitem.FieldKey: + return m.OldKey(ctx) + case subscriptionitem.FieldEntitlementID: + return m.OldEntitlementID(ctx) + case subscriptionitem.FieldRestartsBillingPeriod: + return m.OldRestartsBillingPeriod(ctx) + case subscriptionitem.FieldActiveFromOverrideRelativeToPhaseStart: + return m.OldActiveFromOverrideRelativeToPhaseStart(ctx) + case subscriptionitem.FieldActiveToOverrideRelativeToPhaseStart: + return m.OldActiveToOverrideRelativeToPhaseStart(ctx) + case subscriptionitem.FieldName: + return m.OldName(ctx) + case subscriptionitem.FieldDescription: + return m.OldDescription(ctx) + case subscriptionitem.FieldFeatureKey: + return m.OldFeatureKey(ctx) + case subscriptionitem.FieldEntitlementTemplate: + return m.OldEntitlementTemplate(ctx) + case subscriptionitem.FieldTaxConfig: + return m.OldTaxConfig(ctx) + case subscriptionitem.FieldBillingCadence: + return m.OldBillingCadence(ctx) + case subscriptionitem.FieldPrice: + return m.OldPrice(ctx) + case subscriptionitem.FieldDiscounts: + return m.OldDiscounts(ctx) + case subscriptionitem.FieldUnitConfig: + return m.OldUnitConfig(ctx) + } + return nil, fmt.Errorf("unknown SubscriptionItem 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 *SubscriptionItemMutation) SetField(name string, value ent.Value) error { + switch name { + case subscriptionitem.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case subscriptionitem.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 subscriptionitem.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 subscriptionitem.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 subscriptionitem.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case subscriptionitem.FieldTaxCodeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxCodeID(v) + return nil + case subscriptionitem.FieldTaxBehavior: + v, ok := value.(productcatalog.TaxBehavior) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxBehavior(v) + return nil + case subscriptionitem.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 subscriptionitem.FieldActiveFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetActiveFrom(v) + return nil + case subscriptionitem.FieldActiveTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetActiveTo(v) + return nil + case subscriptionitem.FieldPhaseID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPhaseID(v) + return nil + case subscriptionitem.FieldKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKey(v) + return nil + case subscriptionitem.FieldEntitlementID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEntitlementID(v) + return nil + case subscriptionitem.FieldRestartsBillingPeriod: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRestartsBillingPeriod(v) + return nil + case subscriptionitem.FieldActiveFromOverrideRelativeToPhaseStart: + v, ok := value.(datetime.ISODurationString) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetActiveFromOverrideRelativeToPhaseStart(v) + return nil + case subscriptionitem.FieldActiveToOverrideRelativeToPhaseStart: + v, ok := value.(datetime.ISODurationString) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetActiveToOverrideRelativeToPhaseStart(v) + return nil + case subscriptionitem.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case subscriptionitem.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case subscriptionitem.FieldFeatureKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFeatureKey(v) + return nil + case subscriptionitem.FieldEntitlementTemplate: + v, ok := value.(*productcatalog.EntitlementTemplate) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEntitlementTemplate(v) + return nil + case subscriptionitem.FieldTaxConfig: + v, ok := value.(*productcatalog.TaxConfig) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxConfig(v) + return nil + case subscriptionitem.FieldBillingCadence: + v, ok := value.(datetime.ISODurationString) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBillingCadence(v) + return nil + case subscriptionitem.FieldPrice: + v, ok := value.(*productcatalog.Price) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPrice(v) + return nil + case subscriptionitem.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 subscriptionitem.FieldUnitConfig: + v, ok := value.(*productcatalog.UnitConfig) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUnitConfig(v) + return nil + } + return fmt.Errorf("unknown SubscriptionItem field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SubscriptionItemMutation) 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 *SubscriptionItemMutation) 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 *SubscriptionItemMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown SubscriptionItem numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SubscriptionItemMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(subscriptionitem.FieldDeletedAt) { + fields = append(fields, subscriptionitem.FieldDeletedAt) + } + if m.FieldCleared(subscriptionitem.FieldMetadata) { + fields = append(fields, subscriptionitem.FieldMetadata) + } + if m.FieldCleared(subscriptionitem.FieldTaxCodeID) { + fields = append(fields, subscriptionitem.FieldTaxCodeID) + } + if m.FieldCleared(subscriptionitem.FieldTaxBehavior) { + fields = append(fields, subscriptionitem.FieldTaxBehavior) + } + if m.FieldCleared(subscriptionitem.FieldAnnotations) { + fields = append(fields, subscriptionitem.FieldAnnotations) + } + if m.FieldCleared(subscriptionitem.FieldActiveTo) { + fields = append(fields, subscriptionitem.FieldActiveTo) + } + if m.FieldCleared(subscriptionitem.FieldEntitlementID) { + fields = append(fields, subscriptionitem.FieldEntitlementID) + } + if m.FieldCleared(subscriptionitem.FieldRestartsBillingPeriod) { + fields = append(fields, subscriptionitem.FieldRestartsBillingPeriod) + } + if m.FieldCleared(subscriptionitem.FieldActiveFromOverrideRelativeToPhaseStart) { + fields = append(fields, subscriptionitem.FieldActiveFromOverrideRelativeToPhaseStart) + } + if m.FieldCleared(subscriptionitem.FieldActiveToOverrideRelativeToPhaseStart) { + fields = append(fields, subscriptionitem.FieldActiveToOverrideRelativeToPhaseStart) + } + if m.FieldCleared(subscriptionitem.FieldDescription) { + fields = append(fields, subscriptionitem.FieldDescription) + } + if m.FieldCleared(subscriptionitem.FieldFeatureKey) { + fields = append(fields, subscriptionitem.FieldFeatureKey) + } + if m.FieldCleared(subscriptionitem.FieldEntitlementTemplate) { + fields = append(fields, subscriptionitem.FieldEntitlementTemplate) + } + if m.FieldCleared(subscriptionitem.FieldTaxConfig) { + fields = append(fields, subscriptionitem.FieldTaxConfig) + } + if m.FieldCleared(subscriptionitem.FieldBillingCadence) { + fields = append(fields, subscriptionitem.FieldBillingCadence) + } + if m.FieldCleared(subscriptionitem.FieldPrice) { + fields = append(fields, subscriptionitem.FieldPrice) + } + if m.FieldCleared(subscriptionitem.FieldDiscounts) { + fields = append(fields, subscriptionitem.FieldDiscounts) + } + if m.FieldCleared(subscriptionitem.FieldUnitConfig) { + fields = append(fields, subscriptionitem.FieldUnitConfig) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SubscriptionItemMutation) 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 *SubscriptionItemMutation) ClearField(name string) error { + switch name { + case subscriptionitem.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case subscriptionitem.FieldMetadata: + m.ClearMetadata() + return nil + case subscriptionitem.FieldTaxCodeID: + m.ClearTaxCodeID() + return nil + case subscriptionitem.FieldTaxBehavior: + m.ClearTaxBehavior() + return nil + case subscriptionitem.FieldAnnotations: + m.ClearAnnotations() + return nil + case subscriptionitem.FieldActiveTo: + m.ClearActiveTo() + return nil + case subscriptionitem.FieldEntitlementID: + m.ClearEntitlementID() + return nil + case subscriptionitem.FieldRestartsBillingPeriod: + m.ClearRestartsBillingPeriod() + return nil + case subscriptionitem.FieldActiveFromOverrideRelativeToPhaseStart: + m.ClearActiveFromOverrideRelativeToPhaseStart() + return nil + case subscriptionitem.FieldActiveToOverrideRelativeToPhaseStart: + m.ClearActiveToOverrideRelativeToPhaseStart() + return nil + case subscriptionitem.FieldDescription: + m.ClearDescription() + return nil + case subscriptionitem.FieldFeatureKey: + m.ClearFeatureKey() + return nil + case subscriptionitem.FieldEntitlementTemplate: + m.ClearEntitlementTemplate() + return nil + case subscriptionitem.FieldTaxConfig: + m.ClearTaxConfig() + return nil + case subscriptionitem.FieldBillingCadence: + m.ClearBillingCadence() + return nil + case subscriptionitem.FieldPrice: + m.ClearPrice() + return nil + case subscriptionitem.FieldDiscounts: + m.ClearDiscounts() + return nil + case subscriptionitem.FieldUnitConfig: + m.ClearUnitConfig() + return nil + } + return fmt.Errorf("unknown SubscriptionItem 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 *SubscriptionItemMutation) ResetField(name string) error { + switch name { + case subscriptionitem.FieldNamespace: + m.ResetNamespace() + return nil + case subscriptionitem.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case subscriptionitem.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case subscriptionitem.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case subscriptionitem.FieldMetadata: + m.ResetMetadata() + return nil + case subscriptionitem.FieldTaxCodeID: + m.ResetTaxCodeID() + return nil + case subscriptionitem.FieldTaxBehavior: + m.ResetTaxBehavior() + return nil + case subscriptionitem.FieldAnnotations: + m.ResetAnnotations() + return nil + case subscriptionitem.FieldActiveFrom: + m.ResetActiveFrom() + return nil + case subscriptionitem.FieldActiveTo: + m.ResetActiveTo() + return nil + case subscriptionitem.FieldPhaseID: + m.ResetPhaseID() + return nil + case subscriptionitem.FieldKey: + m.ResetKey() + return nil + case subscriptionitem.FieldEntitlementID: + m.ResetEntitlementID() + return nil + case subscriptionitem.FieldRestartsBillingPeriod: + m.ResetRestartsBillingPeriod() + return nil + case subscriptionitem.FieldActiveFromOverrideRelativeToPhaseStart: + m.ResetActiveFromOverrideRelativeToPhaseStart() + return nil + case subscriptionitem.FieldActiveToOverrideRelativeToPhaseStart: + m.ResetActiveToOverrideRelativeToPhaseStart() + return nil + case subscriptionitem.FieldName: + m.ResetName() + return nil + case subscriptionitem.FieldDescription: + m.ResetDescription() + return nil + case subscriptionitem.FieldFeatureKey: + m.ResetFeatureKey() + return nil + case subscriptionitem.FieldEntitlementTemplate: + m.ResetEntitlementTemplate() + return nil + case subscriptionitem.FieldTaxConfig: + m.ResetTaxConfig() + return nil + case subscriptionitem.FieldBillingCadence: + m.ResetBillingCadence() + return nil + case subscriptionitem.FieldPrice: + m.ResetPrice() + return nil + case subscriptionitem.FieldDiscounts: + m.ResetDiscounts() + return nil + case subscriptionitem.FieldUnitConfig: + m.ResetUnitConfig() + return nil + } + return fmt.Errorf("unknown SubscriptionItem field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SubscriptionItemMutation) AddedEdges() []string { + edges := make([]string, 0, 8) + if m.phase != nil { + edges = append(edges, subscriptionitem.EdgePhase) + } + if m.entitlement != nil { + edges = append(edges, subscriptionitem.EdgeEntitlement) + } + if m.billing_lines != nil { + edges = append(edges, subscriptionitem.EdgeBillingLines) + } + if m.billing_split_line_groups != nil { + edges = append(edges, subscriptionitem.EdgeBillingSplitLineGroups) + } + if m.charges_usage_based != nil { + edges = append(edges, subscriptionitem.EdgeChargesUsageBased) + } + if m.charges_credit_purchase != nil { + edges = append(edges, subscriptionitem.EdgeChargesCreditPurchase) + } + if m.charges_flat_fee != nil { + edges = append(edges, subscriptionitem.EdgeChargesFlatFee) + } + if m.tax_code != nil { + edges = append(edges, subscriptionitem.EdgeTaxCode) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *SubscriptionItemMutation) AddedIDs(name string) []ent.Value { + switch name { + case subscriptionitem.EdgePhase: + if id := m.phase; id != nil { + return []ent.Value{*id} + } + case subscriptionitem.EdgeEntitlement: + if id := m.entitlement; id != nil { + return []ent.Value{*id} + } + case subscriptionitem.EdgeBillingLines: + ids := make([]ent.Value, 0, len(m.billing_lines)) + for id := range m.billing_lines { + ids = append(ids, id) + } + return ids + case subscriptionitem.EdgeBillingSplitLineGroups: + ids := make([]ent.Value, 0, len(m.billing_split_line_groups)) + for id := range m.billing_split_line_groups { + ids = append(ids, id) + } + return ids + case subscriptionitem.EdgeChargesUsageBased: + ids := make([]ent.Value, 0, len(m.charges_usage_based)) + for id := range m.charges_usage_based { + ids = append(ids, id) + } + return ids + case subscriptionitem.EdgeChargesCreditPurchase: + ids := make([]ent.Value, 0, len(m.charges_credit_purchase)) + for id := range m.charges_credit_purchase { + ids = append(ids, id) + } + return ids + case subscriptionitem.EdgeChargesFlatFee: + ids := make([]ent.Value, 0, len(m.charges_flat_fee)) + for id := range m.charges_flat_fee { + ids = append(ids, id) + } + return ids + case subscriptionitem.EdgeTaxCode: + if id := m.tax_code; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SubscriptionItemMutation) RemovedEdges() []string { + edges := make([]string, 0, 8) + if m.removedbilling_lines != nil { + edges = append(edges, subscriptionitem.EdgeBillingLines) + } + if m.removedbilling_split_line_groups != nil { + edges = append(edges, subscriptionitem.EdgeBillingSplitLineGroups) + } + if m.removedcharges_usage_based != nil { + edges = append(edges, subscriptionitem.EdgeChargesUsageBased) + } + if m.removedcharges_credit_purchase != nil { + edges = append(edges, subscriptionitem.EdgeChargesCreditPurchase) + } + if m.removedcharges_flat_fee != nil { + edges = append(edges, subscriptionitem.EdgeChargesFlatFee) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *SubscriptionItemMutation) RemovedIDs(name string) []ent.Value { + switch name { + case subscriptionitem.EdgeBillingLines: + ids := make([]ent.Value, 0, len(m.removedbilling_lines)) + for id := range m.removedbilling_lines { + ids = append(ids, id) + } + return ids + case subscriptionitem.EdgeBillingSplitLineGroups: + ids := make([]ent.Value, 0, len(m.removedbilling_split_line_groups)) + for id := range m.removedbilling_split_line_groups { + ids = append(ids, id) + } + return ids + case subscriptionitem.EdgeChargesUsageBased: + ids := make([]ent.Value, 0, len(m.removedcharges_usage_based)) + for id := range m.removedcharges_usage_based { + ids = append(ids, id) + } + return ids + case subscriptionitem.EdgeChargesCreditPurchase: + ids := make([]ent.Value, 0, len(m.removedcharges_credit_purchase)) + for id := range m.removedcharges_credit_purchase { + ids = append(ids, id) + } + return ids + case subscriptionitem.EdgeChargesFlatFee: + ids := make([]ent.Value, 0, len(m.removedcharges_flat_fee)) + for id := range m.removedcharges_flat_fee { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SubscriptionItemMutation) ClearedEdges() []string { + edges := make([]string, 0, 8) + if m.clearedphase { + edges = append(edges, subscriptionitem.EdgePhase) + } + if m.clearedentitlement { + edges = append(edges, subscriptionitem.EdgeEntitlement) + } + if m.clearedbilling_lines { + edges = append(edges, subscriptionitem.EdgeBillingLines) + } + if m.clearedbilling_split_line_groups { + edges = append(edges, subscriptionitem.EdgeBillingSplitLineGroups) + } + if m.clearedcharges_usage_based { + edges = append(edges, subscriptionitem.EdgeChargesUsageBased) + } + if m.clearedcharges_credit_purchase { + edges = append(edges, subscriptionitem.EdgeChargesCreditPurchase) + } + if m.clearedcharges_flat_fee { + edges = append(edges, subscriptionitem.EdgeChargesFlatFee) + } + if m.clearedtax_code { + edges = append(edges, subscriptionitem.EdgeTaxCode) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *SubscriptionItemMutation) EdgeCleared(name string) bool { + switch name { + case subscriptionitem.EdgePhase: + return m.clearedphase + case subscriptionitem.EdgeEntitlement: + return m.clearedentitlement + case subscriptionitem.EdgeBillingLines: + return m.clearedbilling_lines + case subscriptionitem.EdgeBillingSplitLineGroups: + return m.clearedbilling_split_line_groups + case subscriptionitem.EdgeChargesUsageBased: + return m.clearedcharges_usage_based + case subscriptionitem.EdgeChargesCreditPurchase: + return m.clearedcharges_credit_purchase + case subscriptionitem.EdgeChargesFlatFee: + return m.clearedcharges_flat_fee + case subscriptionitem.EdgeTaxCode: + return m.clearedtax_code + } + 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 *SubscriptionItemMutation) ClearEdge(name string) error { + switch name { + case subscriptionitem.EdgePhase: + m.ClearPhase() + return nil + case subscriptionitem.EdgeEntitlement: + m.ClearEntitlement() + return nil + case subscriptionitem.EdgeTaxCode: + m.ClearTaxCode() + return nil + } + return fmt.Errorf("unknown SubscriptionItem 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 *SubscriptionItemMutation) ResetEdge(name string) error { + switch name { + case subscriptionitem.EdgePhase: + m.ResetPhase() + return nil + case subscriptionitem.EdgeEntitlement: + m.ResetEntitlement() + return nil + case subscriptionitem.EdgeBillingLines: + m.ResetBillingLines() + return nil + case subscriptionitem.EdgeBillingSplitLineGroups: + m.ResetBillingSplitLineGroups() + return nil + case subscriptionitem.EdgeChargesUsageBased: + m.ResetChargesUsageBased() + return nil + case subscriptionitem.EdgeChargesCreditPurchase: + m.ResetChargesCreditPurchase() + return nil + case subscriptionitem.EdgeChargesFlatFee: + m.ResetChargesFlatFee() + return nil + case subscriptionitem.EdgeTaxCode: + m.ResetTaxCode() + return nil + } + return fmt.Errorf("unknown SubscriptionItem edge %s", name) +} + +// SubscriptionPhaseMutation represents an operation that mutates the SubscriptionPhase nodes in the graph. +type SubscriptionPhaseMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + metadata *map[string]string + key *string + name *string + description *string + active_from *time.Time + sort_hint *uint8 + addsort_hint *int8 + clearedFields map[string]struct{} + subscription *string + clearedsubscription bool + items map[string]struct{} + removeditems map[string]struct{} + cleareditems bool + billing_lines map[string]struct{} + removedbilling_lines map[string]struct{} + clearedbilling_lines bool + billing_split_line_groups map[string]struct{} + removedbilling_split_line_groups map[string]struct{} + clearedbilling_split_line_groups bool + charges_usage_based map[string]struct{} + removedcharges_usage_based map[string]struct{} + clearedcharges_usage_based bool + charges_credit_purchase map[string]struct{} + removedcharges_credit_purchase map[string]struct{} + clearedcharges_credit_purchase bool + charges_flat_fee map[string]struct{} + removedcharges_flat_fee map[string]struct{} + clearedcharges_flat_fee bool + done bool + oldValue func(context.Context) (*SubscriptionPhase, error) + predicates []predicate.SubscriptionPhase +} + +var _ ent.Mutation = (*SubscriptionPhaseMutation)(nil) + +// subscriptionphaseOption allows management of the mutation configuration using functional options. +type subscriptionphaseOption func(*SubscriptionPhaseMutation) + +// newSubscriptionPhaseMutation creates new mutation for the SubscriptionPhase entity. +func newSubscriptionPhaseMutation(c config, op Op, opts ...subscriptionphaseOption) *SubscriptionPhaseMutation { + m := &SubscriptionPhaseMutation{ + config: c, + op: op, + typ: TypeSubscriptionPhase, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withSubscriptionPhaseID sets the ID field of the mutation. +func withSubscriptionPhaseID(id string) subscriptionphaseOption { + return func(m *SubscriptionPhaseMutation) { + var ( + err error + once sync.Once + value *SubscriptionPhase + ) + m.oldValue = func(ctx context.Context) (*SubscriptionPhase, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().SubscriptionPhase.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withSubscriptionPhase sets the old SubscriptionPhase of the mutation. +func withSubscriptionPhase(node *SubscriptionPhase) subscriptionphaseOption { + return func(m *SubscriptionPhaseMutation) { + m.oldValue = func(context.Context) (*SubscriptionPhase, 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 SubscriptionPhaseMutation) 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 SubscriptionPhaseMutation) 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 SubscriptionPhase entities. +func (m *SubscriptionPhaseMutation) 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 *SubscriptionPhaseMutation) 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 *SubscriptionPhaseMutation) 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().SubscriptionPhase.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 *SubscriptionPhaseMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *SubscriptionPhaseMutation) 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 SubscriptionPhase entity. +// If the SubscriptionPhase 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 *SubscriptionPhaseMutation) 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 *SubscriptionPhaseMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *SubscriptionPhaseMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *SubscriptionPhaseMutation) 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 SubscriptionPhase entity. +// If the SubscriptionPhase 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 *SubscriptionPhaseMutation) 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 *SubscriptionPhaseMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *SubscriptionPhaseMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *SubscriptionPhaseMutation) 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 SubscriptionPhase entity. +// If the SubscriptionPhase 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 *SubscriptionPhaseMutation) 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 *SubscriptionPhaseMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *SubscriptionPhaseMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *SubscriptionPhaseMutation) 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 SubscriptionPhase entity. +// If the SubscriptionPhase 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 *SubscriptionPhaseMutation) 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 *SubscriptionPhaseMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[subscriptionphase.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *SubscriptionPhaseMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[subscriptionphase.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *SubscriptionPhaseMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, subscriptionphase.FieldDeletedAt) +} + +// SetMetadata sets the "metadata" field. +func (m *SubscriptionPhaseMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *SubscriptionPhaseMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the SubscriptionPhase entity. +// If the SubscriptionPhase 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 *SubscriptionPhaseMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *SubscriptionPhaseMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[subscriptionphase.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *SubscriptionPhaseMutation) MetadataCleared() bool { + _, ok := m.clearedFields[subscriptionphase.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *SubscriptionPhaseMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, subscriptionphase.FieldMetadata) +} + +// SetSubscriptionID sets the "subscription_id" field. +func (m *SubscriptionPhaseMutation) SetSubscriptionID(s string) { + m.subscription = &s +} + +// SubscriptionID returns the value of the "subscription_id" field in the mutation. +func (m *SubscriptionPhaseMutation) SubscriptionID() (r string, exists bool) { + v := m.subscription + if v == nil { + return + } + return *v, true +} + +// OldSubscriptionID returns the old "subscription_id" field's value of the SubscriptionPhase entity. +// If the SubscriptionPhase 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 *SubscriptionPhaseMutation) OldSubscriptionID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSubscriptionID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSubscriptionID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSubscriptionID: %w", err) + } + return oldValue.SubscriptionID, nil +} + +// ResetSubscriptionID resets all changes to the "subscription_id" field. +func (m *SubscriptionPhaseMutation) ResetSubscriptionID() { + m.subscription = nil +} + +// SetKey sets the "key" field. +func (m *SubscriptionPhaseMutation) SetKey(s string) { + m.key = &s +} + +// Key returns the value of the "key" field in the mutation. +func (m *SubscriptionPhaseMutation) Key() (r string, exists bool) { + v := m.key + if v == nil { + return + } + return *v, true +} + +// OldKey returns the old "key" field's value of the SubscriptionPhase entity. +// If the SubscriptionPhase 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 *SubscriptionPhaseMutation) OldKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldKey: %w", err) + } + return oldValue.Key, nil +} + +// ResetKey resets all changes to the "key" field. +func (m *SubscriptionPhaseMutation) ResetKey() { + m.key = nil +} + +// SetName sets the "name" field. +func (m *SubscriptionPhaseMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *SubscriptionPhaseMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the SubscriptionPhase entity. +// If the SubscriptionPhase 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 *SubscriptionPhaseMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *SubscriptionPhaseMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *SubscriptionPhaseMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *SubscriptionPhaseMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the SubscriptionPhase entity. +// If the SubscriptionPhase 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 *SubscriptionPhaseMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *SubscriptionPhaseMutation) ClearDescription() { + m.description = nil + m.clearedFields[subscriptionphase.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *SubscriptionPhaseMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[subscriptionphase.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *SubscriptionPhaseMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, subscriptionphase.FieldDescription) +} + +// SetActiveFrom sets the "active_from" field. +func (m *SubscriptionPhaseMutation) SetActiveFrom(t time.Time) { + m.active_from = &t +} + +// ActiveFrom returns the value of the "active_from" field in the mutation. +func (m *SubscriptionPhaseMutation) ActiveFrom() (r time.Time, exists bool) { + v := m.active_from + if v == nil { + return + } + return *v, true +} + +// OldActiveFrom returns the old "active_from" field's value of the SubscriptionPhase entity. +// If the SubscriptionPhase 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 *SubscriptionPhaseMutation) OldActiveFrom(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldActiveFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldActiveFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldActiveFrom: %w", err) + } + return oldValue.ActiveFrom, nil +} + +// ResetActiveFrom resets all changes to the "active_from" field. +func (m *SubscriptionPhaseMutation) ResetActiveFrom() { + m.active_from = nil +} + +// SetSortHint sets the "sort_hint" field. +func (m *SubscriptionPhaseMutation) SetSortHint(u uint8) { + m.sort_hint = &u + m.addsort_hint = nil +} + +// SortHint returns the value of the "sort_hint" field in the mutation. +func (m *SubscriptionPhaseMutation) SortHint() (r uint8, exists bool) { + v := m.sort_hint + if v == nil { + return + } + return *v, true +} + +// OldSortHint returns the old "sort_hint" field's value of the SubscriptionPhase entity. +// If the SubscriptionPhase 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 *SubscriptionPhaseMutation) OldSortHint(ctx context.Context) (v *uint8, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSortHint is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSortHint requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSortHint: %w", err) + } + return oldValue.SortHint, nil +} + +// AddSortHint adds u to the "sort_hint" field. +func (m *SubscriptionPhaseMutation) AddSortHint(u int8) { + if m.addsort_hint != nil { + *m.addsort_hint += u + } else { + m.addsort_hint = &u + } +} + +// AddedSortHint returns the value that was added to the "sort_hint" field in this mutation. +func (m *SubscriptionPhaseMutation) AddedSortHint() (r int8, exists bool) { + v := m.addsort_hint + if v == nil { + return + } + return *v, true +} + +// ClearSortHint clears the value of the "sort_hint" field. +func (m *SubscriptionPhaseMutation) ClearSortHint() { + m.sort_hint = nil + m.addsort_hint = nil + m.clearedFields[subscriptionphase.FieldSortHint] = struct{}{} +} + +// SortHintCleared returns if the "sort_hint" field was cleared in this mutation. +func (m *SubscriptionPhaseMutation) SortHintCleared() bool { + _, ok := m.clearedFields[subscriptionphase.FieldSortHint] + return ok +} + +// ResetSortHint resets all changes to the "sort_hint" field. +func (m *SubscriptionPhaseMutation) ResetSortHint() { + m.sort_hint = nil + m.addsort_hint = nil + delete(m.clearedFields, subscriptionphase.FieldSortHint) +} + +// ClearSubscription clears the "subscription" edge to the Subscription entity. +func (m *SubscriptionPhaseMutation) ClearSubscription() { + m.clearedsubscription = true + m.clearedFields[subscriptionphase.FieldSubscriptionID] = struct{}{} +} + +// SubscriptionCleared reports if the "subscription" edge to the Subscription entity was cleared. +func (m *SubscriptionPhaseMutation) SubscriptionCleared() bool { + return m.clearedsubscription +} + +// SubscriptionIDs returns the "subscription" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubscriptionID instead. It exists only for internal usage by the builders. +func (m *SubscriptionPhaseMutation) SubscriptionIDs() (ids []string) { + if id := m.subscription; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSubscription resets all changes to the "subscription" edge. +func (m *SubscriptionPhaseMutation) ResetSubscription() { + m.subscription = nil + m.clearedsubscription = false +} + +// AddItemIDs adds the "items" edge to the SubscriptionItem entity by ids. +func (m *SubscriptionPhaseMutation) AddItemIDs(ids ...string) { + if m.items == nil { + m.items = make(map[string]struct{}) + } + for i := range ids { + m.items[ids[i]] = struct{}{} + } +} + +// ClearItems clears the "items" edge to the SubscriptionItem entity. +func (m *SubscriptionPhaseMutation) ClearItems() { + m.cleareditems = true +} + +// ItemsCleared reports if the "items" edge to the SubscriptionItem entity was cleared. +func (m *SubscriptionPhaseMutation) ItemsCleared() bool { + return m.cleareditems +} + +// RemoveItemIDs removes the "items" edge to the SubscriptionItem entity by IDs. +func (m *SubscriptionPhaseMutation) RemoveItemIDs(ids ...string) { + if m.removeditems == nil { + m.removeditems = make(map[string]struct{}) + } + for i := range ids { + delete(m.items, ids[i]) + m.removeditems[ids[i]] = struct{}{} + } +} + +// RemovedItems returns the removed IDs of the "items" edge to the SubscriptionItem entity. +func (m *SubscriptionPhaseMutation) RemovedItemsIDs() (ids []string) { + for id := range m.removeditems { + ids = append(ids, id) + } + return +} + +// ItemsIDs returns the "items" edge IDs in the mutation. +func (m *SubscriptionPhaseMutation) ItemsIDs() (ids []string) { + for id := range m.items { + ids = append(ids, id) + } + return +} + +// ResetItems resets all changes to the "items" edge. +func (m *SubscriptionPhaseMutation) ResetItems() { + m.items = nil + m.cleareditems = false + m.removeditems = nil +} + +// AddBillingLineIDs adds the "billing_lines" edge to the BillingInvoiceLine entity by ids. +func (m *SubscriptionPhaseMutation) AddBillingLineIDs(ids ...string) { + if m.billing_lines == nil { + m.billing_lines = make(map[string]struct{}) + } + for i := range ids { + m.billing_lines[ids[i]] = struct{}{} + } +} + +// ClearBillingLines clears the "billing_lines" edge to the BillingInvoiceLine entity. +func (m *SubscriptionPhaseMutation) ClearBillingLines() { + m.clearedbilling_lines = true +} + +// BillingLinesCleared reports if the "billing_lines" edge to the BillingInvoiceLine entity was cleared. +func (m *SubscriptionPhaseMutation) BillingLinesCleared() bool { + return m.clearedbilling_lines +} + +// RemoveBillingLineIDs removes the "billing_lines" edge to the BillingInvoiceLine entity by IDs. +func (m *SubscriptionPhaseMutation) RemoveBillingLineIDs(ids ...string) { + if m.removedbilling_lines == nil { + m.removedbilling_lines = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_lines, ids[i]) + m.removedbilling_lines[ids[i]] = struct{}{} + } +} + +// RemovedBillingLines returns the removed IDs of the "billing_lines" edge to the BillingInvoiceLine entity. +func (m *SubscriptionPhaseMutation) RemovedBillingLinesIDs() (ids []string) { + for id := range m.removedbilling_lines { + ids = append(ids, id) + } + return +} + +// BillingLinesIDs returns the "billing_lines" edge IDs in the mutation. +func (m *SubscriptionPhaseMutation) BillingLinesIDs() (ids []string) { + for id := range m.billing_lines { + ids = append(ids, id) + } + return +} + +// ResetBillingLines resets all changes to the "billing_lines" edge. +func (m *SubscriptionPhaseMutation) ResetBillingLines() { + m.billing_lines = nil + m.clearedbilling_lines = false + m.removedbilling_lines = nil +} + +// AddBillingSplitLineGroupIDs adds the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity by ids. +func (m *SubscriptionPhaseMutation) AddBillingSplitLineGroupIDs(ids ...string) { + if m.billing_split_line_groups == nil { + m.billing_split_line_groups = make(map[string]struct{}) + } + for i := range ids { + m.billing_split_line_groups[ids[i]] = struct{}{} + } +} + +// ClearBillingSplitLineGroups clears the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity. +func (m *SubscriptionPhaseMutation) ClearBillingSplitLineGroups() { + m.clearedbilling_split_line_groups = true +} + +// BillingSplitLineGroupsCleared reports if the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity was cleared. +func (m *SubscriptionPhaseMutation) BillingSplitLineGroupsCleared() bool { + return m.clearedbilling_split_line_groups +} + +// RemoveBillingSplitLineGroupIDs removes the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity by IDs. +func (m *SubscriptionPhaseMutation) RemoveBillingSplitLineGroupIDs(ids ...string) { + if m.removedbilling_split_line_groups == nil { + m.removedbilling_split_line_groups = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_split_line_groups, ids[i]) + m.removedbilling_split_line_groups[ids[i]] = struct{}{} + } +} + +// RemovedBillingSplitLineGroups returns the removed IDs of the "billing_split_line_groups" edge to the BillingInvoiceSplitLineGroup entity. +func (m *SubscriptionPhaseMutation) RemovedBillingSplitLineGroupsIDs() (ids []string) { + for id := range m.removedbilling_split_line_groups { + ids = append(ids, id) + } + return +} + +// BillingSplitLineGroupsIDs returns the "billing_split_line_groups" edge IDs in the mutation. +func (m *SubscriptionPhaseMutation) BillingSplitLineGroupsIDs() (ids []string) { + for id := range m.billing_split_line_groups { + ids = append(ids, id) + } + return +} + +// ResetBillingSplitLineGroups resets all changes to the "billing_split_line_groups" edge. +func (m *SubscriptionPhaseMutation) ResetBillingSplitLineGroups() { + m.billing_split_line_groups = nil + m.clearedbilling_split_line_groups = false + m.removedbilling_split_line_groups = nil +} + +// AddChargesUsageBasedIDs adds the "charges_usage_based" edge to the ChargeUsageBased entity by ids. +func (m *SubscriptionPhaseMutation) AddChargesUsageBasedIDs(ids ...string) { + if m.charges_usage_based == nil { + m.charges_usage_based = make(map[string]struct{}) + } + for i := range ids { + m.charges_usage_based[ids[i]] = struct{}{} + } +} + +// ClearChargesUsageBased clears the "charges_usage_based" edge to the ChargeUsageBased entity. +func (m *SubscriptionPhaseMutation) ClearChargesUsageBased() { + m.clearedcharges_usage_based = true +} + +// ChargesUsageBasedCleared reports if the "charges_usage_based" edge to the ChargeUsageBased entity was cleared. +func (m *SubscriptionPhaseMutation) ChargesUsageBasedCleared() bool { + return m.clearedcharges_usage_based +} + +// RemoveChargesUsageBasedIDs removes the "charges_usage_based" edge to the ChargeUsageBased entity by IDs. +func (m *SubscriptionPhaseMutation) RemoveChargesUsageBasedIDs(ids ...string) { + if m.removedcharges_usage_based == nil { + m.removedcharges_usage_based = make(map[string]struct{}) + } + for i := range ids { + delete(m.charges_usage_based, ids[i]) + m.removedcharges_usage_based[ids[i]] = struct{}{} + } +} + +// RemovedChargesUsageBased returns the removed IDs of the "charges_usage_based" edge to the ChargeUsageBased entity. +func (m *SubscriptionPhaseMutation) RemovedChargesUsageBasedIDs() (ids []string) { + for id := range m.removedcharges_usage_based { + ids = append(ids, id) + } + return +} + +// ChargesUsageBasedIDs returns the "charges_usage_based" edge IDs in the mutation. +func (m *SubscriptionPhaseMutation) ChargesUsageBasedIDs() (ids []string) { + for id := range m.charges_usage_based { + ids = append(ids, id) + } + return +} + +// ResetChargesUsageBased resets all changes to the "charges_usage_based" edge. +func (m *SubscriptionPhaseMutation) ResetChargesUsageBased() { + m.charges_usage_based = nil + m.clearedcharges_usage_based = false + m.removedcharges_usage_based = nil +} + +// AddChargesCreditPurchaseIDs adds the "charges_credit_purchase" edge to the ChargeCreditPurchase entity by ids. +func (m *SubscriptionPhaseMutation) AddChargesCreditPurchaseIDs(ids ...string) { + if m.charges_credit_purchase == nil { + m.charges_credit_purchase = make(map[string]struct{}) + } + for i := range ids { + m.charges_credit_purchase[ids[i]] = struct{}{} + } +} + +// ClearChargesCreditPurchase clears the "charges_credit_purchase" edge to the ChargeCreditPurchase entity. +func (m *SubscriptionPhaseMutation) ClearChargesCreditPurchase() { + m.clearedcharges_credit_purchase = true +} + +// ChargesCreditPurchaseCleared reports if the "charges_credit_purchase" edge to the ChargeCreditPurchase entity was cleared. +func (m *SubscriptionPhaseMutation) ChargesCreditPurchaseCleared() bool { + return m.clearedcharges_credit_purchase +} + +// RemoveChargesCreditPurchaseIDs removes the "charges_credit_purchase" edge to the ChargeCreditPurchase entity by IDs. +func (m *SubscriptionPhaseMutation) RemoveChargesCreditPurchaseIDs(ids ...string) { + if m.removedcharges_credit_purchase == nil { + m.removedcharges_credit_purchase = make(map[string]struct{}) + } + for i := range ids { + delete(m.charges_credit_purchase, ids[i]) + m.removedcharges_credit_purchase[ids[i]] = struct{}{} + } +} + +// RemovedChargesCreditPurchase returns the removed IDs of the "charges_credit_purchase" edge to the ChargeCreditPurchase entity. +func (m *SubscriptionPhaseMutation) RemovedChargesCreditPurchaseIDs() (ids []string) { + for id := range m.removedcharges_credit_purchase { + ids = append(ids, id) + } + return +} + +// ChargesCreditPurchaseIDs returns the "charges_credit_purchase" edge IDs in the mutation. +func (m *SubscriptionPhaseMutation) ChargesCreditPurchaseIDs() (ids []string) { + for id := range m.charges_credit_purchase { + ids = append(ids, id) + } + return +} + +// ResetChargesCreditPurchase resets all changes to the "charges_credit_purchase" edge. +func (m *SubscriptionPhaseMutation) ResetChargesCreditPurchase() { + m.charges_credit_purchase = nil + m.clearedcharges_credit_purchase = false + m.removedcharges_credit_purchase = nil +} + +// AddChargesFlatFeeIDs adds the "charges_flat_fee" edge to the ChargeFlatFee entity by ids. +func (m *SubscriptionPhaseMutation) AddChargesFlatFeeIDs(ids ...string) { + if m.charges_flat_fee == nil { + m.charges_flat_fee = make(map[string]struct{}) + } + for i := range ids { + m.charges_flat_fee[ids[i]] = struct{}{} + } +} + +// ClearChargesFlatFee clears the "charges_flat_fee" edge to the ChargeFlatFee entity. +func (m *SubscriptionPhaseMutation) ClearChargesFlatFee() { + m.clearedcharges_flat_fee = true +} + +// ChargesFlatFeeCleared reports if the "charges_flat_fee" edge to the ChargeFlatFee entity was cleared. +func (m *SubscriptionPhaseMutation) ChargesFlatFeeCleared() bool { + return m.clearedcharges_flat_fee +} + +// RemoveChargesFlatFeeIDs removes the "charges_flat_fee" edge to the ChargeFlatFee entity by IDs. +func (m *SubscriptionPhaseMutation) RemoveChargesFlatFeeIDs(ids ...string) { + if m.removedcharges_flat_fee == nil { + m.removedcharges_flat_fee = make(map[string]struct{}) + } + for i := range ids { + delete(m.charges_flat_fee, ids[i]) + m.removedcharges_flat_fee[ids[i]] = struct{}{} + } +} + +// RemovedChargesFlatFee returns the removed IDs of the "charges_flat_fee" edge to the ChargeFlatFee entity. +func (m *SubscriptionPhaseMutation) RemovedChargesFlatFeeIDs() (ids []string) { + for id := range m.removedcharges_flat_fee { + ids = append(ids, id) + } + return +} + +// ChargesFlatFeeIDs returns the "charges_flat_fee" edge IDs in the mutation. +func (m *SubscriptionPhaseMutation) ChargesFlatFeeIDs() (ids []string) { + for id := range m.charges_flat_fee { + ids = append(ids, id) + } + return +} + +// ResetChargesFlatFee resets all changes to the "charges_flat_fee" edge. +func (m *SubscriptionPhaseMutation) ResetChargesFlatFee() { + m.charges_flat_fee = nil + m.clearedcharges_flat_fee = false + m.removedcharges_flat_fee = nil +} + +// Where appends a list predicates to the SubscriptionPhaseMutation builder. +func (m *SubscriptionPhaseMutation) Where(ps ...predicate.SubscriptionPhase) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SubscriptionPhaseMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SubscriptionPhaseMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.SubscriptionPhase, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *SubscriptionPhaseMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *SubscriptionPhaseMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (SubscriptionPhase). +func (m *SubscriptionPhaseMutation) 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 *SubscriptionPhaseMutation) Fields() []string { + fields := make([]string, 0, 11) + if m.namespace != nil { + fields = append(fields, subscriptionphase.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, subscriptionphase.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, subscriptionphase.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, subscriptionphase.FieldDeletedAt) + } + if m.metadata != nil { + fields = append(fields, subscriptionphase.FieldMetadata) + } + if m.subscription != nil { + fields = append(fields, subscriptionphase.FieldSubscriptionID) + } + if m.key != nil { + fields = append(fields, subscriptionphase.FieldKey) + } + if m.name != nil { + fields = append(fields, subscriptionphase.FieldName) + } + if m.description != nil { + fields = append(fields, subscriptionphase.FieldDescription) + } + if m.active_from != nil { + fields = append(fields, subscriptionphase.FieldActiveFrom) + } + if m.sort_hint != nil { + fields = append(fields, subscriptionphase.FieldSortHint) + } + 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 *SubscriptionPhaseMutation) Field(name string) (ent.Value, bool) { + switch name { + case subscriptionphase.FieldNamespace: + return m.Namespace() + case subscriptionphase.FieldCreatedAt: + return m.CreatedAt() + case subscriptionphase.FieldUpdatedAt: + return m.UpdatedAt() + case subscriptionphase.FieldDeletedAt: + return m.DeletedAt() + case subscriptionphase.FieldMetadata: + return m.Metadata() + case subscriptionphase.FieldSubscriptionID: + return m.SubscriptionID() + case subscriptionphase.FieldKey: + return m.Key() + case subscriptionphase.FieldName: + return m.Name() + case subscriptionphase.FieldDescription: + return m.Description() + case subscriptionphase.FieldActiveFrom: + return m.ActiveFrom() + case subscriptionphase.FieldSortHint: + return m.SortHint() + } + 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 *SubscriptionPhaseMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case subscriptionphase.FieldNamespace: + return m.OldNamespace(ctx) + case subscriptionphase.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case subscriptionphase.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case subscriptionphase.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case subscriptionphase.FieldMetadata: + return m.OldMetadata(ctx) + case subscriptionphase.FieldSubscriptionID: + return m.OldSubscriptionID(ctx) + case subscriptionphase.FieldKey: + return m.OldKey(ctx) + case subscriptionphase.FieldName: + return m.OldName(ctx) + case subscriptionphase.FieldDescription: + return m.OldDescription(ctx) + case subscriptionphase.FieldActiveFrom: + return m.OldActiveFrom(ctx) + case subscriptionphase.FieldSortHint: + return m.OldSortHint(ctx) + } + return nil, fmt.Errorf("unknown SubscriptionPhase 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 *SubscriptionPhaseMutation) SetField(name string, value ent.Value) error { + switch name { + case subscriptionphase.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case subscriptionphase.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 subscriptionphase.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 subscriptionphase.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 subscriptionphase.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case subscriptionphase.FieldSubscriptionID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSubscriptionID(v) + return nil + case subscriptionphase.FieldKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKey(v) + return nil + case subscriptionphase.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case subscriptionphase.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case subscriptionphase.FieldActiveFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetActiveFrom(v) + return nil + case subscriptionphase.FieldSortHint: + v, ok := value.(uint8) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSortHint(v) + return nil + } + return fmt.Errorf("unknown SubscriptionPhase field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SubscriptionPhaseMutation) AddedFields() []string { + var fields []string + if m.addsort_hint != nil { + fields = append(fields, subscriptionphase.FieldSortHint) + } + return fields +} + +// 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 *SubscriptionPhaseMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case subscriptionphase.FieldSortHint: + return m.AddedSortHint() + } + 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 *SubscriptionPhaseMutation) AddField(name string, value ent.Value) error { + switch name { + case subscriptionphase.FieldSortHint: + v, ok := value.(int8) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddSortHint(v) + return nil + } + return fmt.Errorf("unknown SubscriptionPhase numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SubscriptionPhaseMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(subscriptionphase.FieldDeletedAt) { + fields = append(fields, subscriptionphase.FieldDeletedAt) + } + if m.FieldCleared(subscriptionphase.FieldMetadata) { + fields = append(fields, subscriptionphase.FieldMetadata) + } + if m.FieldCleared(subscriptionphase.FieldDescription) { + fields = append(fields, subscriptionphase.FieldDescription) + } + if m.FieldCleared(subscriptionphase.FieldSortHint) { + fields = append(fields, subscriptionphase.FieldSortHint) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SubscriptionPhaseMutation) 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 *SubscriptionPhaseMutation) ClearField(name string) error { + switch name { + case subscriptionphase.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case subscriptionphase.FieldMetadata: + m.ClearMetadata() + return nil + case subscriptionphase.FieldDescription: + m.ClearDescription() + return nil + case subscriptionphase.FieldSortHint: + m.ClearSortHint() + return nil + } + return fmt.Errorf("unknown SubscriptionPhase 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 *SubscriptionPhaseMutation) ResetField(name string) error { + switch name { + case subscriptionphase.FieldNamespace: + m.ResetNamespace() + return nil + case subscriptionphase.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case subscriptionphase.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case subscriptionphase.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case subscriptionphase.FieldMetadata: + m.ResetMetadata() + return nil + case subscriptionphase.FieldSubscriptionID: + m.ResetSubscriptionID() + return nil + case subscriptionphase.FieldKey: + m.ResetKey() + return nil + case subscriptionphase.FieldName: + m.ResetName() + return nil + case subscriptionphase.FieldDescription: + m.ResetDescription() + return nil + case subscriptionphase.FieldActiveFrom: + m.ResetActiveFrom() + return nil + case subscriptionphase.FieldSortHint: + m.ResetSortHint() + return nil + } + return fmt.Errorf("unknown SubscriptionPhase field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SubscriptionPhaseMutation) AddedEdges() []string { + edges := make([]string, 0, 7) + if m.subscription != nil { + edges = append(edges, subscriptionphase.EdgeSubscription) + } + if m.items != nil { + edges = append(edges, subscriptionphase.EdgeItems) + } + if m.billing_lines != nil { + edges = append(edges, subscriptionphase.EdgeBillingLines) + } + if m.billing_split_line_groups != nil { + edges = append(edges, subscriptionphase.EdgeBillingSplitLineGroups) + } + if m.charges_usage_based != nil { + edges = append(edges, subscriptionphase.EdgeChargesUsageBased) + } + if m.charges_credit_purchase != nil { + edges = append(edges, subscriptionphase.EdgeChargesCreditPurchase) + } + if m.charges_flat_fee != nil { + edges = append(edges, subscriptionphase.EdgeChargesFlatFee) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *SubscriptionPhaseMutation) AddedIDs(name string) []ent.Value { + switch name { + case subscriptionphase.EdgeSubscription: + if id := m.subscription; id != nil { + return []ent.Value{*id} + } + case subscriptionphase.EdgeItems: + ids := make([]ent.Value, 0, len(m.items)) + for id := range m.items { + ids = append(ids, id) + } + return ids + case subscriptionphase.EdgeBillingLines: + ids := make([]ent.Value, 0, len(m.billing_lines)) + for id := range m.billing_lines { + ids = append(ids, id) + } + return ids + case subscriptionphase.EdgeBillingSplitLineGroups: + ids := make([]ent.Value, 0, len(m.billing_split_line_groups)) + for id := range m.billing_split_line_groups { + ids = append(ids, id) + } + return ids + case subscriptionphase.EdgeChargesUsageBased: + ids := make([]ent.Value, 0, len(m.charges_usage_based)) + for id := range m.charges_usage_based { + ids = append(ids, id) + } + return ids + case subscriptionphase.EdgeChargesCreditPurchase: + ids := make([]ent.Value, 0, len(m.charges_credit_purchase)) + for id := range m.charges_credit_purchase { + ids = append(ids, id) + } + return ids + case subscriptionphase.EdgeChargesFlatFee: + ids := make([]ent.Value, 0, len(m.charges_flat_fee)) + for id := range m.charges_flat_fee { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SubscriptionPhaseMutation) RemovedEdges() []string { + edges := make([]string, 0, 7) + if m.removeditems != nil { + edges = append(edges, subscriptionphase.EdgeItems) + } + if m.removedbilling_lines != nil { + edges = append(edges, subscriptionphase.EdgeBillingLines) + } + if m.removedbilling_split_line_groups != nil { + edges = append(edges, subscriptionphase.EdgeBillingSplitLineGroups) + } + if m.removedcharges_usage_based != nil { + edges = append(edges, subscriptionphase.EdgeChargesUsageBased) + } + if m.removedcharges_credit_purchase != nil { + edges = append(edges, subscriptionphase.EdgeChargesCreditPurchase) + } + if m.removedcharges_flat_fee != nil { + edges = append(edges, subscriptionphase.EdgeChargesFlatFee) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *SubscriptionPhaseMutation) RemovedIDs(name string) []ent.Value { + switch name { + case subscriptionphase.EdgeItems: + ids := make([]ent.Value, 0, len(m.removeditems)) + for id := range m.removeditems { + ids = append(ids, id) + } + return ids + case subscriptionphase.EdgeBillingLines: + ids := make([]ent.Value, 0, len(m.removedbilling_lines)) + for id := range m.removedbilling_lines { + ids = append(ids, id) + } + return ids + case subscriptionphase.EdgeBillingSplitLineGroups: + ids := make([]ent.Value, 0, len(m.removedbilling_split_line_groups)) + for id := range m.removedbilling_split_line_groups { + ids = append(ids, id) + } + return ids + case subscriptionphase.EdgeChargesUsageBased: + ids := make([]ent.Value, 0, len(m.removedcharges_usage_based)) + for id := range m.removedcharges_usage_based { + ids = append(ids, id) + } + return ids + case subscriptionphase.EdgeChargesCreditPurchase: + ids := make([]ent.Value, 0, len(m.removedcharges_credit_purchase)) + for id := range m.removedcharges_credit_purchase { + ids = append(ids, id) + } + return ids + case subscriptionphase.EdgeChargesFlatFee: + ids := make([]ent.Value, 0, len(m.removedcharges_flat_fee)) + for id := range m.removedcharges_flat_fee { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SubscriptionPhaseMutation) ClearedEdges() []string { + edges := make([]string, 0, 7) + if m.clearedsubscription { + edges = append(edges, subscriptionphase.EdgeSubscription) + } + if m.cleareditems { + edges = append(edges, subscriptionphase.EdgeItems) + } + if m.clearedbilling_lines { + edges = append(edges, subscriptionphase.EdgeBillingLines) + } + if m.clearedbilling_split_line_groups { + edges = append(edges, subscriptionphase.EdgeBillingSplitLineGroups) + } + if m.clearedcharges_usage_based { + edges = append(edges, subscriptionphase.EdgeChargesUsageBased) + } + if m.clearedcharges_credit_purchase { + edges = append(edges, subscriptionphase.EdgeChargesCreditPurchase) + } + if m.clearedcharges_flat_fee { + edges = append(edges, subscriptionphase.EdgeChargesFlatFee) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *SubscriptionPhaseMutation) EdgeCleared(name string) bool { + switch name { + case subscriptionphase.EdgeSubscription: + return m.clearedsubscription + case subscriptionphase.EdgeItems: + return m.cleareditems + case subscriptionphase.EdgeBillingLines: + return m.clearedbilling_lines + case subscriptionphase.EdgeBillingSplitLineGroups: + return m.clearedbilling_split_line_groups + case subscriptionphase.EdgeChargesUsageBased: + return m.clearedcharges_usage_based + case subscriptionphase.EdgeChargesCreditPurchase: + return m.clearedcharges_credit_purchase + case subscriptionphase.EdgeChargesFlatFee: + return m.clearedcharges_flat_fee + } + 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 *SubscriptionPhaseMutation) ClearEdge(name string) error { + switch name { + case subscriptionphase.EdgeSubscription: + m.ClearSubscription() + return nil + } + return fmt.Errorf("unknown SubscriptionPhase 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 *SubscriptionPhaseMutation) ResetEdge(name string) error { + switch name { + case subscriptionphase.EdgeSubscription: + m.ResetSubscription() + return nil + case subscriptionphase.EdgeItems: + m.ResetItems() + return nil + case subscriptionphase.EdgeBillingLines: + m.ResetBillingLines() + return nil + case subscriptionphase.EdgeBillingSplitLineGroups: + m.ResetBillingSplitLineGroups() + return nil + case subscriptionphase.EdgeChargesUsageBased: + m.ResetChargesUsageBased() + return nil + case subscriptionphase.EdgeChargesCreditPurchase: + m.ResetChargesCreditPurchase() + return nil + case subscriptionphase.EdgeChargesFlatFee: + m.ResetChargesFlatFee() + return nil + } + return fmt.Errorf("unknown SubscriptionPhase edge %s", name) +} + +// TaxCodeMutation represents an operation that mutates the TaxCode nodes in the graph. +type TaxCodeMutation struct { + config + op Op + typ string + id *string + namespace *string + metadata *map[string]string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + name *string + description *string + key *string + annotations *models.Annotations + app_mappings **taxcode.TaxCodeAppMappings + clearedFields map[string]struct{} + billing_workflow_configs map[string]struct{} + removedbilling_workflow_configs map[string]struct{} + clearedbilling_workflow_configs bool + billing_customer_overrides map[string]struct{} + removedbilling_customer_overrides map[string]struct{} + clearedbilling_customer_overrides bool + billing_invoice_lines map[string]struct{} + removedbilling_invoice_lines map[string]struct{} + clearedbilling_invoice_lines bool + subscription_items map[string]struct{} + removedsubscription_items map[string]struct{} + clearedsubscription_items bool + plan_rate_cards map[string]struct{} + removedplan_rate_cards map[string]struct{} + clearedplan_rate_cards bool + addon_rate_cards map[string]struct{} + removedaddon_rate_cards map[string]struct{} + clearedaddon_rate_cards bool + charge_flat_fees map[string]struct{} + removedcharge_flat_fees map[string]struct{} + clearedcharge_flat_fees bool + charge_flat_fee_overrides map[string]struct{} + removedcharge_flat_fee_overrides map[string]struct{} + clearedcharge_flat_fee_overrides bool + charge_usage_based map[string]struct{} + removedcharge_usage_based map[string]struct{} + clearedcharge_usage_based bool + charge_usage_based_overrides map[string]struct{} + removedcharge_usage_based_overrides map[string]struct{} + clearedcharge_usage_based_overrides bool + charge_credit_purchases map[string]struct{} + removedcharge_credit_purchases map[string]struct{} + clearedcharge_credit_purchases bool + organization_default_invoicing map[string]struct{} + removedorganization_default_invoicing map[string]struct{} + clearedorganization_default_invoicing bool + organization_default_credit_grant map[string]struct{} + removedorganization_default_credit_grant map[string]struct{} + clearedorganization_default_credit_grant bool + done bool + oldValue func(context.Context) (*TaxCode, error) + predicates []predicate.TaxCode +} + +var _ ent.Mutation = (*TaxCodeMutation)(nil) + +// taxcodeOption allows management of the mutation configuration using functional options. +type taxcodeOption func(*TaxCodeMutation) + +// newTaxCodeMutation creates new mutation for the TaxCode entity. +func newTaxCodeMutation(c config, op Op, opts ...taxcodeOption) *TaxCodeMutation { + m := &TaxCodeMutation{ + config: c, + op: op, + typ: TypeTaxCode, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withTaxCodeID sets the ID field of the mutation. +func withTaxCodeID(id string) taxcodeOption { + return func(m *TaxCodeMutation) { + var ( + err error + once sync.Once + value *TaxCode + ) + m.oldValue = func(ctx context.Context) (*TaxCode, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().TaxCode.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withTaxCode sets the old TaxCode of the mutation. +func withTaxCode(node *TaxCode) taxcodeOption { + return func(m *TaxCodeMutation) { + m.oldValue = func(context.Context) (*TaxCode, 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 TaxCodeMutation) 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 TaxCodeMutation) 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 TaxCode entities. +func (m *TaxCodeMutation) 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 *TaxCodeMutation) 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 *TaxCodeMutation) 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().TaxCode.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 *TaxCodeMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *TaxCodeMutation) 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 TaxCode entity. +// If the TaxCode 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 *TaxCodeMutation) 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 *TaxCodeMutation) ResetNamespace() { + m.namespace = nil +} + +// SetMetadata sets the "metadata" field. +func (m *TaxCodeMutation) SetMetadata(value map[string]string) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *TaxCodeMutation) Metadata() (r map[string]string, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the TaxCode entity. +// If the TaxCode 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 *TaxCodeMutation) OldMetadata(ctx context.Context) (v map[string]string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *TaxCodeMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[dbtaxcode.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *TaxCodeMutation) MetadataCleared() bool { + _, ok := m.clearedFields[dbtaxcode.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *TaxCodeMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, dbtaxcode.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *TaxCodeMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *TaxCodeMutation) 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 TaxCode entity. +// If the TaxCode 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 *TaxCodeMutation) 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 *TaxCodeMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *TaxCodeMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *TaxCodeMutation) 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 TaxCode entity. +// If the TaxCode 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 *TaxCodeMutation) 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 *TaxCodeMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *TaxCodeMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *TaxCodeMutation) 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 TaxCode entity. +// If the TaxCode 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 *TaxCodeMutation) 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 *TaxCodeMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[dbtaxcode.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *TaxCodeMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[dbtaxcode.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *TaxCodeMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, dbtaxcode.FieldDeletedAt) +} + +// SetName sets the "name" field. +func (m *TaxCodeMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *TaxCodeMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the TaxCode entity. +// If the TaxCode 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 *TaxCodeMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *TaxCodeMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *TaxCodeMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *TaxCodeMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the TaxCode entity. +// If the TaxCode 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 *TaxCodeMutation) OldDescription(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *TaxCodeMutation) ClearDescription() { + m.description = nil + m.clearedFields[dbtaxcode.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *TaxCodeMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[dbtaxcode.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *TaxCodeMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, dbtaxcode.FieldDescription) +} + +// SetKey sets the "key" field. +func (m *TaxCodeMutation) SetKey(s string) { + m.key = &s +} + +// Key returns the value of the "key" field in the mutation. +func (m *TaxCodeMutation) Key() (r string, exists bool) { + v := m.key + if v == nil { + return + } + return *v, true +} + +// OldKey returns the old "key" field's value of the TaxCode entity. +// If the TaxCode 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 *TaxCodeMutation) OldKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldKey: %w", err) + } + return oldValue.Key, nil +} + +// ResetKey resets all changes to the "key" field. +func (m *TaxCodeMutation) ResetKey() { + m.key = nil +} + +// SetAnnotations sets the "annotations" field. +func (m *TaxCodeMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *TaxCodeMutation) 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 TaxCode entity. +// If the TaxCode 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 *TaxCodeMutation) 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 *TaxCodeMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[dbtaxcode.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *TaxCodeMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[dbtaxcode.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *TaxCodeMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, dbtaxcode.FieldAnnotations) +} + +// SetAppMappings sets the "app_mappings" field. +func (m *TaxCodeMutation) SetAppMappings(tcam *taxcode.TaxCodeAppMappings) { + m.app_mappings = &tcam +} + +// AppMappings returns the value of the "app_mappings" field in the mutation. +func (m *TaxCodeMutation) AppMappings() (r *taxcode.TaxCodeAppMappings, exists bool) { + v := m.app_mappings + if v == nil { + return + } + return *v, true +} + +// OldAppMappings returns the old "app_mappings" field's value of the TaxCode entity. +// If the TaxCode 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 *TaxCodeMutation) OldAppMappings(ctx context.Context) (v *taxcode.TaxCodeAppMappings, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAppMappings is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAppMappings requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAppMappings: %w", err) + } + return oldValue.AppMappings, nil +} + +// ClearAppMappings clears the value of the "app_mappings" field. +func (m *TaxCodeMutation) ClearAppMappings() { + m.app_mappings = nil + m.clearedFields[dbtaxcode.FieldAppMappings] = struct{}{} +} + +// AppMappingsCleared returns if the "app_mappings" field was cleared in this mutation. +func (m *TaxCodeMutation) AppMappingsCleared() bool { + _, ok := m.clearedFields[dbtaxcode.FieldAppMappings] + return ok +} + +// ResetAppMappings resets all changes to the "app_mappings" field. +func (m *TaxCodeMutation) ResetAppMappings() { + m.app_mappings = nil + delete(m.clearedFields, dbtaxcode.FieldAppMappings) +} + +// AddBillingWorkflowConfigIDs adds the "billing_workflow_configs" edge to the BillingWorkflowConfig entity by ids. +func (m *TaxCodeMutation) AddBillingWorkflowConfigIDs(ids ...string) { + if m.billing_workflow_configs == nil { + m.billing_workflow_configs = make(map[string]struct{}) + } + for i := range ids { + m.billing_workflow_configs[ids[i]] = struct{}{} + } +} + +// ClearBillingWorkflowConfigs clears the "billing_workflow_configs" edge to the BillingWorkflowConfig entity. +func (m *TaxCodeMutation) ClearBillingWorkflowConfigs() { + m.clearedbilling_workflow_configs = true +} + +// BillingWorkflowConfigsCleared reports if the "billing_workflow_configs" edge to the BillingWorkflowConfig entity was cleared. +func (m *TaxCodeMutation) BillingWorkflowConfigsCleared() bool { + return m.clearedbilling_workflow_configs +} + +// RemoveBillingWorkflowConfigIDs removes the "billing_workflow_configs" edge to the BillingWorkflowConfig entity by IDs. +func (m *TaxCodeMutation) RemoveBillingWorkflowConfigIDs(ids ...string) { + if m.removedbilling_workflow_configs == nil { + m.removedbilling_workflow_configs = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_workflow_configs, ids[i]) + m.removedbilling_workflow_configs[ids[i]] = struct{}{} + } +} + +// RemovedBillingWorkflowConfigs returns the removed IDs of the "billing_workflow_configs" edge to the BillingWorkflowConfig entity. +func (m *TaxCodeMutation) RemovedBillingWorkflowConfigsIDs() (ids []string) { + for id := range m.removedbilling_workflow_configs { + ids = append(ids, id) + } + return +} + +// BillingWorkflowConfigsIDs returns the "billing_workflow_configs" edge IDs in the mutation. +func (m *TaxCodeMutation) BillingWorkflowConfigsIDs() (ids []string) { + for id := range m.billing_workflow_configs { + ids = append(ids, id) + } + return +} + +// ResetBillingWorkflowConfigs resets all changes to the "billing_workflow_configs" edge. +func (m *TaxCodeMutation) ResetBillingWorkflowConfigs() { + m.billing_workflow_configs = nil + m.clearedbilling_workflow_configs = false + m.removedbilling_workflow_configs = nil +} + +// AddBillingCustomerOverrideIDs adds the "billing_customer_overrides" edge to the BillingCustomerOverride entity by ids. +func (m *TaxCodeMutation) AddBillingCustomerOverrideIDs(ids ...string) { + if m.billing_customer_overrides == nil { + m.billing_customer_overrides = make(map[string]struct{}) + } + for i := range ids { + m.billing_customer_overrides[ids[i]] = struct{}{} + } +} + +// ClearBillingCustomerOverrides clears the "billing_customer_overrides" edge to the BillingCustomerOverride entity. +func (m *TaxCodeMutation) ClearBillingCustomerOverrides() { + m.clearedbilling_customer_overrides = true +} + +// BillingCustomerOverridesCleared reports if the "billing_customer_overrides" edge to the BillingCustomerOverride entity was cleared. +func (m *TaxCodeMutation) BillingCustomerOverridesCleared() bool { + return m.clearedbilling_customer_overrides +} + +// RemoveBillingCustomerOverrideIDs removes the "billing_customer_overrides" edge to the BillingCustomerOverride entity by IDs. +func (m *TaxCodeMutation) RemoveBillingCustomerOverrideIDs(ids ...string) { + if m.removedbilling_customer_overrides == nil { + m.removedbilling_customer_overrides = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_customer_overrides, ids[i]) + m.removedbilling_customer_overrides[ids[i]] = struct{}{} + } +} + +// RemovedBillingCustomerOverrides returns the removed IDs of the "billing_customer_overrides" edge to the BillingCustomerOverride entity. +func (m *TaxCodeMutation) RemovedBillingCustomerOverridesIDs() (ids []string) { + for id := range m.removedbilling_customer_overrides { + ids = append(ids, id) + } + return +} + +// BillingCustomerOverridesIDs returns the "billing_customer_overrides" edge IDs in the mutation. +func (m *TaxCodeMutation) BillingCustomerOverridesIDs() (ids []string) { + for id := range m.billing_customer_overrides { + ids = append(ids, id) + } + return +} + +// ResetBillingCustomerOverrides resets all changes to the "billing_customer_overrides" edge. +func (m *TaxCodeMutation) ResetBillingCustomerOverrides() { + m.billing_customer_overrides = nil + m.clearedbilling_customer_overrides = false + m.removedbilling_customer_overrides = nil +} + +// AddBillingInvoiceLineIDs adds the "billing_invoice_lines" edge to the BillingInvoiceLine entity by ids. +func (m *TaxCodeMutation) AddBillingInvoiceLineIDs(ids ...string) { + if m.billing_invoice_lines == nil { + m.billing_invoice_lines = make(map[string]struct{}) + } + for i := range ids { + m.billing_invoice_lines[ids[i]] = struct{}{} + } +} + +// ClearBillingInvoiceLines clears the "billing_invoice_lines" edge to the BillingInvoiceLine entity. +func (m *TaxCodeMutation) ClearBillingInvoiceLines() { + m.clearedbilling_invoice_lines = true +} + +// BillingInvoiceLinesCleared reports if the "billing_invoice_lines" edge to the BillingInvoiceLine entity was cleared. +func (m *TaxCodeMutation) BillingInvoiceLinesCleared() bool { + return m.clearedbilling_invoice_lines +} + +// RemoveBillingInvoiceLineIDs removes the "billing_invoice_lines" edge to the BillingInvoiceLine entity by IDs. +func (m *TaxCodeMutation) RemoveBillingInvoiceLineIDs(ids ...string) { + if m.removedbilling_invoice_lines == nil { + m.removedbilling_invoice_lines = make(map[string]struct{}) + } + for i := range ids { + delete(m.billing_invoice_lines, ids[i]) + m.removedbilling_invoice_lines[ids[i]] = struct{}{} + } +} + +// RemovedBillingInvoiceLines returns the removed IDs of the "billing_invoice_lines" edge to the BillingInvoiceLine entity. +func (m *TaxCodeMutation) RemovedBillingInvoiceLinesIDs() (ids []string) { + for id := range m.removedbilling_invoice_lines { + ids = append(ids, id) + } + return +} + +// BillingInvoiceLinesIDs returns the "billing_invoice_lines" edge IDs in the mutation. +func (m *TaxCodeMutation) BillingInvoiceLinesIDs() (ids []string) { + for id := range m.billing_invoice_lines { + ids = append(ids, id) + } + return +} + +// ResetBillingInvoiceLines resets all changes to the "billing_invoice_lines" edge. +func (m *TaxCodeMutation) ResetBillingInvoiceLines() { + m.billing_invoice_lines = nil + m.clearedbilling_invoice_lines = false + m.removedbilling_invoice_lines = nil +} + +// AddSubscriptionItemIDs adds the "subscription_items" edge to the SubscriptionItem entity by ids. +func (m *TaxCodeMutation) AddSubscriptionItemIDs(ids ...string) { + if m.subscription_items == nil { + m.subscription_items = make(map[string]struct{}) + } + for i := range ids { + m.subscription_items[ids[i]] = struct{}{} + } +} + +// ClearSubscriptionItems clears the "subscription_items" edge to the SubscriptionItem entity. +func (m *TaxCodeMutation) ClearSubscriptionItems() { + m.clearedsubscription_items = true +} + +// SubscriptionItemsCleared reports if the "subscription_items" edge to the SubscriptionItem entity was cleared. +func (m *TaxCodeMutation) SubscriptionItemsCleared() bool { + return m.clearedsubscription_items +} + +// RemoveSubscriptionItemIDs removes the "subscription_items" edge to the SubscriptionItem entity by IDs. +func (m *TaxCodeMutation) RemoveSubscriptionItemIDs(ids ...string) { + if m.removedsubscription_items == nil { + m.removedsubscription_items = make(map[string]struct{}) + } + for i := range ids { + delete(m.subscription_items, ids[i]) + m.removedsubscription_items[ids[i]] = struct{}{} + } +} + +// RemovedSubscriptionItems returns the removed IDs of the "subscription_items" edge to the SubscriptionItem entity. +func (m *TaxCodeMutation) RemovedSubscriptionItemsIDs() (ids []string) { + for id := range m.removedsubscription_items { + ids = append(ids, id) + } + return +} + +// SubscriptionItemsIDs returns the "subscription_items" edge IDs in the mutation. +func (m *TaxCodeMutation) SubscriptionItemsIDs() (ids []string) { + for id := range m.subscription_items { + ids = append(ids, id) + } + return +} + +// ResetSubscriptionItems resets all changes to the "subscription_items" edge. +func (m *TaxCodeMutation) ResetSubscriptionItems() { + m.subscription_items = nil + m.clearedsubscription_items = false + m.removedsubscription_items = nil +} + +// AddPlanRateCardIDs adds the "plan_rate_cards" edge to the PlanRateCard entity by ids. +func (m *TaxCodeMutation) AddPlanRateCardIDs(ids ...string) { + if m.plan_rate_cards == nil { + m.plan_rate_cards = make(map[string]struct{}) + } + for i := range ids { + m.plan_rate_cards[ids[i]] = struct{}{} + } +} + +// ClearPlanRateCards clears the "plan_rate_cards" edge to the PlanRateCard entity. +func (m *TaxCodeMutation) ClearPlanRateCards() { + m.clearedplan_rate_cards = true +} + +// PlanRateCardsCleared reports if the "plan_rate_cards" edge to the PlanRateCard entity was cleared. +func (m *TaxCodeMutation) PlanRateCardsCleared() bool { + return m.clearedplan_rate_cards +} + +// RemovePlanRateCardIDs removes the "plan_rate_cards" edge to the PlanRateCard entity by IDs. +func (m *TaxCodeMutation) RemovePlanRateCardIDs(ids ...string) { + if m.removedplan_rate_cards == nil { + m.removedplan_rate_cards = make(map[string]struct{}) + } + for i := range ids { + delete(m.plan_rate_cards, ids[i]) + m.removedplan_rate_cards[ids[i]] = struct{}{} + } +} + +// RemovedPlanRateCards returns the removed IDs of the "plan_rate_cards" edge to the PlanRateCard entity. +func (m *TaxCodeMutation) RemovedPlanRateCardsIDs() (ids []string) { + for id := range m.removedplan_rate_cards { + ids = append(ids, id) + } + return +} + +// PlanRateCardsIDs returns the "plan_rate_cards" edge IDs in the mutation. +func (m *TaxCodeMutation) PlanRateCardsIDs() (ids []string) { + for id := range m.plan_rate_cards { + ids = append(ids, id) + } + return +} + +// ResetPlanRateCards resets all changes to the "plan_rate_cards" edge. +func (m *TaxCodeMutation) ResetPlanRateCards() { + m.plan_rate_cards = nil + m.clearedplan_rate_cards = false + m.removedplan_rate_cards = nil +} + +// AddAddonRateCardIDs adds the "addon_rate_cards" edge to the AddonRateCard entity by ids. +func (m *TaxCodeMutation) AddAddonRateCardIDs(ids ...string) { + if m.addon_rate_cards == nil { + m.addon_rate_cards = make(map[string]struct{}) + } + for i := range ids { + m.addon_rate_cards[ids[i]] = struct{}{} + } +} + +// ClearAddonRateCards clears the "addon_rate_cards" edge to the AddonRateCard entity. +func (m *TaxCodeMutation) ClearAddonRateCards() { + m.clearedaddon_rate_cards = true +} + +// AddonRateCardsCleared reports if the "addon_rate_cards" edge to the AddonRateCard entity was cleared. +func (m *TaxCodeMutation) AddonRateCardsCleared() bool { + return m.clearedaddon_rate_cards +} + +// RemoveAddonRateCardIDs removes the "addon_rate_cards" edge to the AddonRateCard entity by IDs. +func (m *TaxCodeMutation) RemoveAddonRateCardIDs(ids ...string) { + if m.removedaddon_rate_cards == nil { + m.removedaddon_rate_cards = make(map[string]struct{}) + } + for i := range ids { + delete(m.addon_rate_cards, ids[i]) + m.removedaddon_rate_cards[ids[i]] = struct{}{} + } +} + +// RemovedAddonRateCards returns the removed IDs of the "addon_rate_cards" edge to the AddonRateCard entity. +func (m *TaxCodeMutation) RemovedAddonRateCardsIDs() (ids []string) { + for id := range m.removedaddon_rate_cards { + ids = append(ids, id) + } + return +} + +// AddonRateCardsIDs returns the "addon_rate_cards" edge IDs in the mutation. +func (m *TaxCodeMutation) AddonRateCardsIDs() (ids []string) { + for id := range m.addon_rate_cards { + ids = append(ids, id) + } + return +} + +// ResetAddonRateCards resets all changes to the "addon_rate_cards" edge. +func (m *TaxCodeMutation) ResetAddonRateCards() { + m.addon_rate_cards = nil + m.clearedaddon_rate_cards = false + m.removedaddon_rate_cards = nil +} + +// AddChargeFlatFeeIDs adds the "charge_flat_fees" edge to the ChargeFlatFee entity by ids. +func (m *TaxCodeMutation) AddChargeFlatFeeIDs(ids ...string) { + if m.charge_flat_fees == nil { + m.charge_flat_fees = make(map[string]struct{}) + } + for i := range ids { + m.charge_flat_fees[ids[i]] = struct{}{} + } +} + +// ClearChargeFlatFees clears the "charge_flat_fees" edge to the ChargeFlatFee entity. +func (m *TaxCodeMutation) ClearChargeFlatFees() { + m.clearedcharge_flat_fees = true +} + +// ChargeFlatFeesCleared reports if the "charge_flat_fees" edge to the ChargeFlatFee entity was cleared. +func (m *TaxCodeMutation) ChargeFlatFeesCleared() bool { + return m.clearedcharge_flat_fees +} + +// RemoveChargeFlatFeeIDs removes the "charge_flat_fees" edge to the ChargeFlatFee entity by IDs. +func (m *TaxCodeMutation) RemoveChargeFlatFeeIDs(ids ...string) { + if m.removedcharge_flat_fees == nil { + m.removedcharge_flat_fees = make(map[string]struct{}) + } + for i := range ids { + delete(m.charge_flat_fees, ids[i]) + m.removedcharge_flat_fees[ids[i]] = struct{}{} + } +} + +// RemovedChargeFlatFees returns the removed IDs of the "charge_flat_fees" edge to the ChargeFlatFee entity. +func (m *TaxCodeMutation) RemovedChargeFlatFeesIDs() (ids []string) { + for id := range m.removedcharge_flat_fees { + ids = append(ids, id) + } + return +} + +// ChargeFlatFeesIDs returns the "charge_flat_fees" edge IDs in the mutation. +func (m *TaxCodeMutation) ChargeFlatFeesIDs() (ids []string) { + for id := range m.charge_flat_fees { + ids = append(ids, id) + } + return +} + +// ResetChargeFlatFees resets all changes to the "charge_flat_fees" edge. +func (m *TaxCodeMutation) ResetChargeFlatFees() { + m.charge_flat_fees = nil + m.clearedcharge_flat_fees = false + m.removedcharge_flat_fees = nil +} + +// AddChargeFlatFeeOverrideIDs adds the "charge_flat_fee_overrides" edge to the ChargeFlatFeeOverride entity by ids. +func (m *TaxCodeMutation) AddChargeFlatFeeOverrideIDs(ids ...string) { + if m.charge_flat_fee_overrides == nil { + m.charge_flat_fee_overrides = make(map[string]struct{}) + } + for i := range ids { + m.charge_flat_fee_overrides[ids[i]] = struct{}{} + } +} + +// ClearChargeFlatFeeOverrides clears the "charge_flat_fee_overrides" edge to the ChargeFlatFeeOverride entity. +func (m *TaxCodeMutation) ClearChargeFlatFeeOverrides() { + m.clearedcharge_flat_fee_overrides = true +} + +// ChargeFlatFeeOverridesCleared reports if the "charge_flat_fee_overrides" edge to the ChargeFlatFeeOverride entity was cleared. +func (m *TaxCodeMutation) ChargeFlatFeeOverridesCleared() bool { + return m.clearedcharge_flat_fee_overrides +} + +// RemoveChargeFlatFeeOverrideIDs removes the "charge_flat_fee_overrides" edge to the ChargeFlatFeeOverride entity by IDs. +func (m *TaxCodeMutation) RemoveChargeFlatFeeOverrideIDs(ids ...string) { + if m.removedcharge_flat_fee_overrides == nil { + m.removedcharge_flat_fee_overrides = make(map[string]struct{}) + } + for i := range ids { + delete(m.charge_flat_fee_overrides, ids[i]) + m.removedcharge_flat_fee_overrides[ids[i]] = struct{}{} + } +} + +// RemovedChargeFlatFeeOverrides returns the removed IDs of the "charge_flat_fee_overrides" edge to the ChargeFlatFeeOverride entity. +func (m *TaxCodeMutation) RemovedChargeFlatFeeOverridesIDs() (ids []string) { + for id := range m.removedcharge_flat_fee_overrides { + ids = append(ids, id) + } + return +} + +// ChargeFlatFeeOverridesIDs returns the "charge_flat_fee_overrides" edge IDs in the mutation. +func (m *TaxCodeMutation) ChargeFlatFeeOverridesIDs() (ids []string) { + for id := range m.charge_flat_fee_overrides { + ids = append(ids, id) + } + return +} + +// ResetChargeFlatFeeOverrides resets all changes to the "charge_flat_fee_overrides" edge. +func (m *TaxCodeMutation) ResetChargeFlatFeeOverrides() { + m.charge_flat_fee_overrides = nil + m.clearedcharge_flat_fee_overrides = false + m.removedcharge_flat_fee_overrides = nil +} + +// AddChargeUsageBasedIDs adds the "charge_usage_based" edge to the ChargeUsageBased entity by ids. +func (m *TaxCodeMutation) AddChargeUsageBasedIDs(ids ...string) { + if m.charge_usage_based == nil { + m.charge_usage_based = make(map[string]struct{}) + } + for i := range ids { + m.charge_usage_based[ids[i]] = struct{}{} + } +} + +// ClearChargeUsageBased clears the "charge_usage_based" edge to the ChargeUsageBased entity. +func (m *TaxCodeMutation) ClearChargeUsageBased() { + m.clearedcharge_usage_based = true +} + +// ChargeUsageBasedCleared reports if the "charge_usage_based" edge to the ChargeUsageBased entity was cleared. +func (m *TaxCodeMutation) ChargeUsageBasedCleared() bool { + return m.clearedcharge_usage_based +} + +// RemoveChargeUsageBasedIDs removes the "charge_usage_based" edge to the ChargeUsageBased entity by IDs. +func (m *TaxCodeMutation) RemoveChargeUsageBasedIDs(ids ...string) { + if m.removedcharge_usage_based == nil { + m.removedcharge_usage_based = make(map[string]struct{}) + } + for i := range ids { + delete(m.charge_usage_based, ids[i]) + m.removedcharge_usage_based[ids[i]] = struct{}{} + } +} + +// RemovedChargeUsageBased returns the removed IDs of the "charge_usage_based" edge to the ChargeUsageBased entity. +func (m *TaxCodeMutation) RemovedChargeUsageBasedIDs() (ids []string) { + for id := range m.removedcharge_usage_based { + ids = append(ids, id) + } + return +} + +// ChargeUsageBasedIDs returns the "charge_usage_based" edge IDs in the mutation. +func (m *TaxCodeMutation) ChargeUsageBasedIDs() (ids []string) { + for id := range m.charge_usage_based { + ids = append(ids, id) + } + return +} + +// ResetChargeUsageBased resets all changes to the "charge_usage_based" edge. +func (m *TaxCodeMutation) ResetChargeUsageBased() { + m.charge_usage_based = nil + m.clearedcharge_usage_based = false + m.removedcharge_usage_based = nil +} + +// AddChargeUsageBasedOverrideIDs adds the "charge_usage_based_overrides" edge to the ChargeUsageBasedOverride entity by ids. +func (m *TaxCodeMutation) AddChargeUsageBasedOverrideIDs(ids ...string) { + if m.charge_usage_based_overrides == nil { + m.charge_usage_based_overrides = make(map[string]struct{}) + } + for i := range ids { + m.charge_usage_based_overrides[ids[i]] = struct{}{} + } +} + +// ClearChargeUsageBasedOverrides clears the "charge_usage_based_overrides" edge to the ChargeUsageBasedOverride entity. +func (m *TaxCodeMutation) ClearChargeUsageBasedOverrides() { + m.clearedcharge_usage_based_overrides = true +} + +// ChargeUsageBasedOverridesCleared reports if the "charge_usage_based_overrides" edge to the ChargeUsageBasedOverride entity was cleared. +func (m *TaxCodeMutation) ChargeUsageBasedOverridesCleared() bool { + return m.clearedcharge_usage_based_overrides +} + +// RemoveChargeUsageBasedOverrideIDs removes the "charge_usage_based_overrides" edge to the ChargeUsageBasedOverride entity by IDs. +func (m *TaxCodeMutation) RemoveChargeUsageBasedOverrideIDs(ids ...string) { + if m.removedcharge_usage_based_overrides == nil { + m.removedcharge_usage_based_overrides = make(map[string]struct{}) + } + for i := range ids { + delete(m.charge_usage_based_overrides, ids[i]) + m.removedcharge_usage_based_overrides[ids[i]] = struct{}{} + } +} + +// RemovedChargeUsageBasedOverrides returns the removed IDs of the "charge_usage_based_overrides" edge to the ChargeUsageBasedOverride entity. +func (m *TaxCodeMutation) RemovedChargeUsageBasedOverridesIDs() (ids []string) { + for id := range m.removedcharge_usage_based_overrides { + ids = append(ids, id) + } + return +} + +// ChargeUsageBasedOverridesIDs returns the "charge_usage_based_overrides" edge IDs in the mutation. +func (m *TaxCodeMutation) ChargeUsageBasedOverridesIDs() (ids []string) { + for id := range m.charge_usage_based_overrides { + ids = append(ids, id) + } + return +} + +// ResetChargeUsageBasedOverrides resets all changes to the "charge_usage_based_overrides" edge. +func (m *TaxCodeMutation) ResetChargeUsageBasedOverrides() { + m.charge_usage_based_overrides = nil + m.clearedcharge_usage_based_overrides = false + m.removedcharge_usage_based_overrides = nil +} + +// AddChargeCreditPurchaseIDs adds the "charge_credit_purchases" edge to the ChargeCreditPurchase entity by ids. +func (m *TaxCodeMutation) AddChargeCreditPurchaseIDs(ids ...string) { + if m.charge_credit_purchases == nil { + m.charge_credit_purchases = make(map[string]struct{}) + } + for i := range ids { + m.charge_credit_purchases[ids[i]] = struct{}{} + } +} + +// ClearChargeCreditPurchases clears the "charge_credit_purchases" edge to the ChargeCreditPurchase entity. +func (m *TaxCodeMutation) ClearChargeCreditPurchases() { + m.clearedcharge_credit_purchases = true +} + +// ChargeCreditPurchasesCleared reports if the "charge_credit_purchases" edge to the ChargeCreditPurchase entity was cleared. +func (m *TaxCodeMutation) ChargeCreditPurchasesCleared() bool { + return m.clearedcharge_credit_purchases +} + +// RemoveChargeCreditPurchaseIDs removes the "charge_credit_purchases" edge to the ChargeCreditPurchase entity by IDs. +func (m *TaxCodeMutation) RemoveChargeCreditPurchaseIDs(ids ...string) { + if m.removedcharge_credit_purchases == nil { + m.removedcharge_credit_purchases = make(map[string]struct{}) + } + for i := range ids { + delete(m.charge_credit_purchases, ids[i]) + m.removedcharge_credit_purchases[ids[i]] = struct{}{} + } +} + +// RemovedChargeCreditPurchases returns the removed IDs of the "charge_credit_purchases" edge to the ChargeCreditPurchase entity. +func (m *TaxCodeMutation) RemovedChargeCreditPurchasesIDs() (ids []string) { + for id := range m.removedcharge_credit_purchases { + ids = append(ids, id) + } + return +} + +// ChargeCreditPurchasesIDs returns the "charge_credit_purchases" edge IDs in the mutation. +func (m *TaxCodeMutation) ChargeCreditPurchasesIDs() (ids []string) { + for id := range m.charge_credit_purchases { + ids = append(ids, id) + } + return +} + +// ResetChargeCreditPurchases resets all changes to the "charge_credit_purchases" edge. +func (m *TaxCodeMutation) ResetChargeCreditPurchases() { + m.charge_credit_purchases = nil + m.clearedcharge_credit_purchases = false + m.removedcharge_credit_purchases = nil +} + +// AddOrganizationDefaultInvoicingIDs adds the "organization_default_invoicing" edge to the OrganizationDefaultTaxCodes entity by ids. +func (m *TaxCodeMutation) AddOrganizationDefaultInvoicingIDs(ids ...string) { + if m.organization_default_invoicing == nil { + m.organization_default_invoicing = make(map[string]struct{}) + } + for i := range ids { + m.organization_default_invoicing[ids[i]] = struct{}{} + } +} + +// ClearOrganizationDefaultInvoicing clears the "organization_default_invoicing" edge to the OrganizationDefaultTaxCodes entity. +func (m *TaxCodeMutation) ClearOrganizationDefaultInvoicing() { + m.clearedorganization_default_invoicing = true +} + +// OrganizationDefaultInvoicingCleared reports if the "organization_default_invoicing" edge to the OrganizationDefaultTaxCodes entity was cleared. +func (m *TaxCodeMutation) OrganizationDefaultInvoicingCleared() bool { + return m.clearedorganization_default_invoicing +} + +// RemoveOrganizationDefaultInvoicingIDs removes the "organization_default_invoicing" edge to the OrganizationDefaultTaxCodes entity by IDs. +func (m *TaxCodeMutation) RemoveOrganizationDefaultInvoicingIDs(ids ...string) { + if m.removedorganization_default_invoicing == nil { + m.removedorganization_default_invoicing = make(map[string]struct{}) + } + for i := range ids { + delete(m.organization_default_invoicing, ids[i]) + m.removedorganization_default_invoicing[ids[i]] = struct{}{} + } +} + +// RemovedOrganizationDefaultInvoicing returns the removed IDs of the "organization_default_invoicing" edge to the OrganizationDefaultTaxCodes entity. +func (m *TaxCodeMutation) RemovedOrganizationDefaultInvoicingIDs() (ids []string) { + for id := range m.removedorganization_default_invoicing { + ids = append(ids, id) + } + return +} + +// OrganizationDefaultInvoicingIDs returns the "organization_default_invoicing" edge IDs in the mutation. +func (m *TaxCodeMutation) OrganizationDefaultInvoicingIDs() (ids []string) { + for id := range m.organization_default_invoicing { + ids = append(ids, id) + } + return +} + +// ResetOrganizationDefaultInvoicing resets all changes to the "organization_default_invoicing" edge. +func (m *TaxCodeMutation) ResetOrganizationDefaultInvoicing() { + m.organization_default_invoicing = nil + m.clearedorganization_default_invoicing = false + m.removedorganization_default_invoicing = nil +} + +// AddOrganizationDefaultCreditGrantIDs adds the "organization_default_credit_grant" edge to the OrganizationDefaultTaxCodes entity by ids. +func (m *TaxCodeMutation) AddOrganizationDefaultCreditGrantIDs(ids ...string) { + if m.organization_default_credit_grant == nil { + m.organization_default_credit_grant = make(map[string]struct{}) + } + for i := range ids { + m.organization_default_credit_grant[ids[i]] = struct{}{} + } +} + +// ClearOrganizationDefaultCreditGrant clears the "organization_default_credit_grant" edge to the OrganizationDefaultTaxCodes entity. +func (m *TaxCodeMutation) ClearOrganizationDefaultCreditGrant() { + m.clearedorganization_default_credit_grant = true +} + +// OrganizationDefaultCreditGrantCleared reports if the "organization_default_credit_grant" edge to the OrganizationDefaultTaxCodes entity was cleared. +func (m *TaxCodeMutation) OrganizationDefaultCreditGrantCleared() bool { + return m.clearedorganization_default_credit_grant +} + +// RemoveOrganizationDefaultCreditGrantIDs removes the "organization_default_credit_grant" edge to the OrganizationDefaultTaxCodes entity by IDs. +func (m *TaxCodeMutation) RemoveOrganizationDefaultCreditGrantIDs(ids ...string) { + if m.removedorganization_default_credit_grant == nil { + m.removedorganization_default_credit_grant = make(map[string]struct{}) + } + for i := range ids { + delete(m.organization_default_credit_grant, ids[i]) + m.removedorganization_default_credit_grant[ids[i]] = struct{}{} + } +} + +// RemovedOrganizationDefaultCreditGrant returns the removed IDs of the "organization_default_credit_grant" edge to the OrganizationDefaultTaxCodes entity. +func (m *TaxCodeMutation) RemovedOrganizationDefaultCreditGrantIDs() (ids []string) { + for id := range m.removedorganization_default_credit_grant { + ids = append(ids, id) + } + return +} + +// OrganizationDefaultCreditGrantIDs returns the "organization_default_credit_grant" edge IDs in the mutation. +func (m *TaxCodeMutation) OrganizationDefaultCreditGrantIDs() (ids []string) { + for id := range m.organization_default_credit_grant { + ids = append(ids, id) + } + return +} + +// ResetOrganizationDefaultCreditGrant resets all changes to the "organization_default_credit_grant" edge. +func (m *TaxCodeMutation) ResetOrganizationDefaultCreditGrant() { + m.organization_default_credit_grant = nil + m.clearedorganization_default_credit_grant = false + m.removedorganization_default_credit_grant = nil +} + +// Where appends a list predicates to the TaxCodeMutation builder. +func (m *TaxCodeMutation) Where(ps ...predicate.TaxCode) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the TaxCodeMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *TaxCodeMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.TaxCode, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *TaxCodeMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *TaxCodeMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (TaxCode). +func (m *TaxCodeMutation) 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 *TaxCodeMutation) Fields() []string { + fields := make([]string, 0, 10) + if m.namespace != nil { + fields = append(fields, dbtaxcode.FieldNamespace) + } + if m.metadata != nil { + fields = append(fields, dbtaxcode.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, dbtaxcode.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, dbtaxcode.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, dbtaxcode.FieldDeletedAt) + } + if m.name != nil { + fields = append(fields, dbtaxcode.FieldName) + } + if m.description != nil { + fields = append(fields, dbtaxcode.FieldDescription) + } + if m.key != nil { + fields = append(fields, dbtaxcode.FieldKey) + } + if m.annotations != nil { + fields = append(fields, dbtaxcode.FieldAnnotations) + } + if m.app_mappings != nil { + fields = append(fields, dbtaxcode.FieldAppMappings) + } + 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 *TaxCodeMutation) Field(name string) (ent.Value, bool) { + switch name { + case dbtaxcode.FieldNamespace: + return m.Namespace() + case dbtaxcode.FieldMetadata: + return m.Metadata() + case dbtaxcode.FieldCreatedAt: + return m.CreatedAt() + case dbtaxcode.FieldUpdatedAt: + return m.UpdatedAt() + case dbtaxcode.FieldDeletedAt: + return m.DeletedAt() + case dbtaxcode.FieldName: + return m.Name() + case dbtaxcode.FieldDescription: + return m.Description() + case dbtaxcode.FieldKey: + return m.Key() + case dbtaxcode.FieldAnnotations: + return m.Annotations() + case dbtaxcode.FieldAppMappings: + return m.AppMappings() + } + 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 *TaxCodeMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case dbtaxcode.FieldNamespace: + return m.OldNamespace(ctx) + case dbtaxcode.FieldMetadata: + return m.OldMetadata(ctx) + case dbtaxcode.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case dbtaxcode.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case dbtaxcode.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case dbtaxcode.FieldName: + return m.OldName(ctx) + case dbtaxcode.FieldDescription: + return m.OldDescription(ctx) + case dbtaxcode.FieldKey: + return m.OldKey(ctx) + case dbtaxcode.FieldAnnotations: + return m.OldAnnotations(ctx) + case dbtaxcode.FieldAppMappings: + return m.OldAppMappings(ctx) + } + return nil, fmt.Errorf("unknown TaxCode 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 *TaxCodeMutation) SetField(name string, value ent.Value) error { + switch name { + case dbtaxcode.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case dbtaxcode.FieldMetadata: + v, ok := value.(map[string]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case dbtaxcode.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 dbtaxcode.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 dbtaxcode.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 dbtaxcode.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case dbtaxcode.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case dbtaxcode.FieldKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKey(v) + return nil + case dbtaxcode.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 dbtaxcode.FieldAppMappings: + v, ok := value.(*taxcode.TaxCodeAppMappings) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAppMappings(v) + return nil + } + return fmt.Errorf("unknown TaxCode field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *TaxCodeMutation) 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 *TaxCodeMutation) 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 *TaxCodeMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown TaxCode numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *TaxCodeMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(dbtaxcode.FieldMetadata) { + fields = append(fields, dbtaxcode.FieldMetadata) + } + if m.FieldCleared(dbtaxcode.FieldDeletedAt) { + fields = append(fields, dbtaxcode.FieldDeletedAt) + } + if m.FieldCleared(dbtaxcode.FieldDescription) { + fields = append(fields, dbtaxcode.FieldDescription) + } + if m.FieldCleared(dbtaxcode.FieldAnnotations) { + fields = append(fields, dbtaxcode.FieldAnnotations) + } + if m.FieldCleared(dbtaxcode.FieldAppMappings) { + fields = append(fields, dbtaxcode.FieldAppMappings) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *TaxCodeMutation) 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 *TaxCodeMutation) ClearField(name string) error { + switch name { + case dbtaxcode.FieldMetadata: + m.ClearMetadata() + return nil + case dbtaxcode.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case dbtaxcode.FieldDescription: + m.ClearDescription() + return nil + case dbtaxcode.FieldAnnotations: + m.ClearAnnotations() + return nil + case dbtaxcode.FieldAppMappings: + m.ClearAppMappings() + return nil + } + return fmt.Errorf("unknown TaxCode 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 *TaxCodeMutation) ResetField(name string) error { + switch name { + case dbtaxcode.FieldNamespace: + m.ResetNamespace() + return nil + case dbtaxcode.FieldMetadata: + m.ResetMetadata() + return nil + case dbtaxcode.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case dbtaxcode.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case dbtaxcode.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case dbtaxcode.FieldName: + m.ResetName() + return nil + case dbtaxcode.FieldDescription: + m.ResetDescription() + return nil + case dbtaxcode.FieldKey: + m.ResetKey() + return nil + case dbtaxcode.FieldAnnotations: + m.ResetAnnotations() + return nil + case dbtaxcode.FieldAppMappings: + m.ResetAppMappings() + return nil + } + return fmt.Errorf("unknown TaxCode field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *TaxCodeMutation) AddedEdges() []string { + edges := make([]string, 0, 13) + if m.billing_workflow_configs != nil { + edges = append(edges, dbtaxcode.EdgeBillingWorkflowConfigs) + } + if m.billing_customer_overrides != nil { + edges = append(edges, dbtaxcode.EdgeBillingCustomerOverrides) + } + if m.billing_invoice_lines != nil { + edges = append(edges, dbtaxcode.EdgeBillingInvoiceLines) + } + if m.subscription_items != nil { + edges = append(edges, dbtaxcode.EdgeSubscriptionItems) + } + if m.plan_rate_cards != nil { + edges = append(edges, dbtaxcode.EdgePlanRateCards) + } + if m.addon_rate_cards != nil { + edges = append(edges, dbtaxcode.EdgeAddonRateCards) + } + if m.charge_flat_fees != nil { + edges = append(edges, dbtaxcode.EdgeChargeFlatFees) + } + if m.charge_flat_fee_overrides != nil { + edges = append(edges, dbtaxcode.EdgeChargeFlatFeeOverrides) + } + if m.charge_usage_based != nil { + edges = append(edges, dbtaxcode.EdgeChargeUsageBased) + } + if m.charge_usage_based_overrides != nil { + edges = append(edges, dbtaxcode.EdgeChargeUsageBasedOverrides) + } + if m.charge_credit_purchases != nil { + edges = append(edges, dbtaxcode.EdgeChargeCreditPurchases) + } + if m.organization_default_invoicing != nil { + edges = append(edges, dbtaxcode.EdgeOrganizationDefaultInvoicing) + } + if m.organization_default_credit_grant != nil { + edges = append(edges, dbtaxcode.EdgeOrganizationDefaultCreditGrant) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *TaxCodeMutation) AddedIDs(name string) []ent.Value { + switch name { + case dbtaxcode.EdgeBillingWorkflowConfigs: + ids := make([]ent.Value, 0, len(m.billing_workflow_configs)) + for id := range m.billing_workflow_configs { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeBillingCustomerOverrides: + ids := make([]ent.Value, 0, len(m.billing_customer_overrides)) + for id := range m.billing_customer_overrides { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeBillingInvoiceLines: + ids := make([]ent.Value, 0, len(m.billing_invoice_lines)) + for id := range m.billing_invoice_lines { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeSubscriptionItems: + ids := make([]ent.Value, 0, len(m.subscription_items)) + for id := range m.subscription_items { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgePlanRateCards: + ids := make([]ent.Value, 0, len(m.plan_rate_cards)) + for id := range m.plan_rate_cards { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeAddonRateCards: + ids := make([]ent.Value, 0, len(m.addon_rate_cards)) + for id := range m.addon_rate_cards { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeChargeFlatFees: + ids := make([]ent.Value, 0, len(m.charge_flat_fees)) + for id := range m.charge_flat_fees { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeChargeFlatFeeOverrides: + ids := make([]ent.Value, 0, len(m.charge_flat_fee_overrides)) + for id := range m.charge_flat_fee_overrides { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeChargeUsageBased: + ids := make([]ent.Value, 0, len(m.charge_usage_based)) + for id := range m.charge_usage_based { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeChargeUsageBasedOverrides: + ids := make([]ent.Value, 0, len(m.charge_usage_based_overrides)) + for id := range m.charge_usage_based_overrides { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeChargeCreditPurchases: + ids := make([]ent.Value, 0, len(m.charge_credit_purchases)) + for id := range m.charge_credit_purchases { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeOrganizationDefaultInvoicing: + ids := make([]ent.Value, 0, len(m.organization_default_invoicing)) + for id := range m.organization_default_invoicing { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeOrganizationDefaultCreditGrant: + ids := make([]ent.Value, 0, len(m.organization_default_credit_grant)) + for id := range m.organization_default_credit_grant { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *TaxCodeMutation) RemovedEdges() []string { + edges := make([]string, 0, 13) + if m.removedbilling_workflow_configs != nil { + edges = append(edges, dbtaxcode.EdgeBillingWorkflowConfigs) + } + if m.removedbilling_customer_overrides != nil { + edges = append(edges, dbtaxcode.EdgeBillingCustomerOverrides) + } + if m.removedbilling_invoice_lines != nil { + edges = append(edges, dbtaxcode.EdgeBillingInvoiceLines) + } + if m.removedsubscription_items != nil { + edges = append(edges, dbtaxcode.EdgeSubscriptionItems) + } + if m.removedplan_rate_cards != nil { + edges = append(edges, dbtaxcode.EdgePlanRateCards) + } + if m.removedaddon_rate_cards != nil { + edges = append(edges, dbtaxcode.EdgeAddonRateCards) + } + if m.removedcharge_flat_fees != nil { + edges = append(edges, dbtaxcode.EdgeChargeFlatFees) + } + if m.removedcharge_flat_fee_overrides != nil { + edges = append(edges, dbtaxcode.EdgeChargeFlatFeeOverrides) + } + if m.removedcharge_usage_based != nil { + edges = append(edges, dbtaxcode.EdgeChargeUsageBased) + } + if m.removedcharge_usage_based_overrides != nil { + edges = append(edges, dbtaxcode.EdgeChargeUsageBasedOverrides) + } + if m.removedcharge_credit_purchases != nil { + edges = append(edges, dbtaxcode.EdgeChargeCreditPurchases) + } + if m.removedorganization_default_invoicing != nil { + edges = append(edges, dbtaxcode.EdgeOrganizationDefaultInvoicing) + } + if m.removedorganization_default_credit_grant != nil { + edges = append(edges, dbtaxcode.EdgeOrganizationDefaultCreditGrant) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *TaxCodeMutation) RemovedIDs(name string) []ent.Value { + switch name { + case dbtaxcode.EdgeBillingWorkflowConfigs: + ids := make([]ent.Value, 0, len(m.removedbilling_workflow_configs)) + for id := range m.removedbilling_workflow_configs { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeBillingCustomerOverrides: + ids := make([]ent.Value, 0, len(m.removedbilling_customer_overrides)) + for id := range m.removedbilling_customer_overrides { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeBillingInvoiceLines: + ids := make([]ent.Value, 0, len(m.removedbilling_invoice_lines)) + for id := range m.removedbilling_invoice_lines { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeSubscriptionItems: + ids := make([]ent.Value, 0, len(m.removedsubscription_items)) + for id := range m.removedsubscription_items { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgePlanRateCards: + ids := make([]ent.Value, 0, len(m.removedplan_rate_cards)) + for id := range m.removedplan_rate_cards { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeAddonRateCards: + ids := make([]ent.Value, 0, len(m.removedaddon_rate_cards)) + for id := range m.removedaddon_rate_cards { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeChargeFlatFees: + ids := make([]ent.Value, 0, len(m.removedcharge_flat_fees)) + for id := range m.removedcharge_flat_fees { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeChargeFlatFeeOverrides: + ids := make([]ent.Value, 0, len(m.removedcharge_flat_fee_overrides)) + for id := range m.removedcharge_flat_fee_overrides { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeChargeUsageBased: + ids := make([]ent.Value, 0, len(m.removedcharge_usage_based)) + for id := range m.removedcharge_usage_based { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeChargeUsageBasedOverrides: + ids := make([]ent.Value, 0, len(m.removedcharge_usage_based_overrides)) + for id := range m.removedcharge_usage_based_overrides { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeChargeCreditPurchases: + ids := make([]ent.Value, 0, len(m.removedcharge_credit_purchases)) + for id := range m.removedcharge_credit_purchases { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeOrganizationDefaultInvoicing: + ids := make([]ent.Value, 0, len(m.removedorganization_default_invoicing)) + for id := range m.removedorganization_default_invoicing { + ids = append(ids, id) + } + return ids + case dbtaxcode.EdgeOrganizationDefaultCreditGrant: + ids := make([]ent.Value, 0, len(m.removedorganization_default_credit_grant)) + for id := range m.removedorganization_default_credit_grant { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *TaxCodeMutation) ClearedEdges() []string { + edges := make([]string, 0, 13) + if m.clearedbilling_workflow_configs { + edges = append(edges, dbtaxcode.EdgeBillingWorkflowConfigs) + } + if m.clearedbilling_customer_overrides { + edges = append(edges, dbtaxcode.EdgeBillingCustomerOverrides) + } + if m.clearedbilling_invoice_lines { + edges = append(edges, dbtaxcode.EdgeBillingInvoiceLines) + } + if m.clearedsubscription_items { + edges = append(edges, dbtaxcode.EdgeSubscriptionItems) + } + if m.clearedplan_rate_cards { + edges = append(edges, dbtaxcode.EdgePlanRateCards) + } + if m.clearedaddon_rate_cards { + edges = append(edges, dbtaxcode.EdgeAddonRateCards) + } + if m.clearedcharge_flat_fees { + edges = append(edges, dbtaxcode.EdgeChargeFlatFees) + } + if m.clearedcharge_flat_fee_overrides { + edges = append(edges, dbtaxcode.EdgeChargeFlatFeeOverrides) + } + if m.clearedcharge_usage_based { + edges = append(edges, dbtaxcode.EdgeChargeUsageBased) + } + if m.clearedcharge_usage_based_overrides { + edges = append(edges, dbtaxcode.EdgeChargeUsageBasedOverrides) + } + if m.clearedcharge_credit_purchases { + edges = append(edges, dbtaxcode.EdgeChargeCreditPurchases) + } + if m.clearedorganization_default_invoicing { + edges = append(edges, dbtaxcode.EdgeOrganizationDefaultInvoicing) + } + if m.clearedorganization_default_credit_grant { + edges = append(edges, dbtaxcode.EdgeOrganizationDefaultCreditGrant) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *TaxCodeMutation) EdgeCleared(name string) bool { + switch name { + case dbtaxcode.EdgeBillingWorkflowConfigs: + return m.clearedbilling_workflow_configs + case dbtaxcode.EdgeBillingCustomerOverrides: + return m.clearedbilling_customer_overrides + case dbtaxcode.EdgeBillingInvoiceLines: + return m.clearedbilling_invoice_lines + case dbtaxcode.EdgeSubscriptionItems: + return m.clearedsubscription_items + case dbtaxcode.EdgePlanRateCards: + return m.clearedplan_rate_cards + case dbtaxcode.EdgeAddonRateCards: + return m.clearedaddon_rate_cards + case dbtaxcode.EdgeChargeFlatFees: + return m.clearedcharge_flat_fees + case dbtaxcode.EdgeChargeFlatFeeOverrides: + return m.clearedcharge_flat_fee_overrides + case dbtaxcode.EdgeChargeUsageBased: + return m.clearedcharge_usage_based + case dbtaxcode.EdgeChargeUsageBasedOverrides: + return m.clearedcharge_usage_based_overrides + case dbtaxcode.EdgeChargeCreditPurchases: + return m.clearedcharge_credit_purchases + case dbtaxcode.EdgeOrganizationDefaultInvoicing: + return m.clearedorganization_default_invoicing + case dbtaxcode.EdgeOrganizationDefaultCreditGrant: + return m.clearedorganization_default_credit_grant + } + 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 *TaxCodeMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown TaxCode 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 *TaxCodeMutation) ResetEdge(name string) error { + switch name { + case dbtaxcode.EdgeBillingWorkflowConfigs: + m.ResetBillingWorkflowConfigs() + return nil + case dbtaxcode.EdgeBillingCustomerOverrides: + m.ResetBillingCustomerOverrides() + return nil + case dbtaxcode.EdgeBillingInvoiceLines: + m.ResetBillingInvoiceLines() + return nil + case dbtaxcode.EdgeSubscriptionItems: + m.ResetSubscriptionItems() + return nil + case dbtaxcode.EdgePlanRateCards: + m.ResetPlanRateCards() + return nil + case dbtaxcode.EdgeAddonRateCards: + m.ResetAddonRateCards() + return nil + case dbtaxcode.EdgeChargeFlatFees: + m.ResetChargeFlatFees() + return nil + case dbtaxcode.EdgeChargeFlatFeeOverrides: + m.ResetChargeFlatFeeOverrides() + return nil + case dbtaxcode.EdgeChargeUsageBased: + m.ResetChargeUsageBased() + return nil + case dbtaxcode.EdgeChargeUsageBasedOverrides: + m.ResetChargeUsageBasedOverrides() + return nil + case dbtaxcode.EdgeChargeCreditPurchases: + m.ResetChargeCreditPurchases() + return nil + case dbtaxcode.EdgeOrganizationDefaultInvoicing: + m.ResetOrganizationDefaultInvoicing() + return nil + case dbtaxcode.EdgeOrganizationDefaultCreditGrant: + m.ResetOrganizationDefaultCreditGrant() + return nil + } + return fmt.Errorf("unknown TaxCode edge %s", name) +} + +// UsageResetMutation represents an operation that mutates the UsageReset nodes in the graph. +type UsageResetMutation struct { + config + op Op + typ string + id *string + namespace *string + annotations *models.Annotations + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + reset_time *time.Time + anchor *time.Time + usage_period_interval *datetime.ISODurationString + clearedFields map[string]struct{} + entitlement *string + clearedentitlement bool + done bool + oldValue func(context.Context) (*UsageReset, error) + predicates []predicate.UsageReset +} + +var _ ent.Mutation = (*UsageResetMutation)(nil) + +// usageresetOption allows management of the mutation configuration using functional options. +type usageresetOption func(*UsageResetMutation) + +// newUsageResetMutation creates new mutation for the UsageReset entity. +func newUsageResetMutation(c config, op Op, opts ...usageresetOption) *UsageResetMutation { + m := &UsageResetMutation{ + config: c, + op: op, + typ: TypeUsageReset, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withUsageResetID sets the ID field of the mutation. +func withUsageResetID(id string) usageresetOption { + return func(m *UsageResetMutation) { + var ( + err error + once sync.Once + value *UsageReset + ) + m.oldValue = func(ctx context.Context) (*UsageReset, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().UsageReset.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withUsageReset sets the old UsageReset of the mutation. +func withUsageReset(node *UsageReset) usageresetOption { + return func(m *UsageResetMutation) { + m.oldValue = func(context.Context) (*UsageReset, 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 UsageResetMutation) 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 UsageResetMutation) 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 UsageReset entities. +func (m *UsageResetMutation) 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 *UsageResetMutation) 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 *UsageResetMutation) 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().UsageReset.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 *UsageResetMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *UsageResetMutation) 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 UsageReset entity. +// If the UsageReset 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 *UsageResetMutation) 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 *UsageResetMutation) ResetNamespace() { + m.namespace = nil +} + +// SetAnnotations sets the "annotations" field. +func (m *UsageResetMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *UsageResetMutation) 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 UsageReset entity. +// If the UsageReset 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 *UsageResetMutation) 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 *UsageResetMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[usagereset.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *UsageResetMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[usagereset.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *UsageResetMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, usagereset.FieldAnnotations) +} + +// SetCreatedAt sets the "created_at" field. +func (m *UsageResetMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *UsageResetMutation) 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 UsageReset entity. +// If the UsageReset 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 *UsageResetMutation) 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 *UsageResetMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *UsageResetMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *UsageResetMutation) 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 UsageReset entity. +// If the UsageReset 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 *UsageResetMutation) 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 *UsageResetMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *UsageResetMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *UsageResetMutation) 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 UsageReset entity. +// If the UsageReset 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 *UsageResetMutation) 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 *UsageResetMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[usagereset.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *UsageResetMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[usagereset.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *UsageResetMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, usagereset.FieldDeletedAt) +} + +// SetEntitlementID sets the "entitlement_id" field. +func (m *UsageResetMutation) SetEntitlementID(s string) { + m.entitlement = &s +} + +// EntitlementID returns the value of the "entitlement_id" field in the mutation. +func (m *UsageResetMutation) EntitlementID() (r string, exists bool) { + v := m.entitlement + if v == nil { + return + } + return *v, true +} + +// OldEntitlementID returns the old "entitlement_id" field's value of the UsageReset entity. +// If the UsageReset 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 *UsageResetMutation) OldEntitlementID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEntitlementID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEntitlementID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEntitlementID: %w", err) + } + return oldValue.EntitlementID, nil +} + +// ResetEntitlementID resets all changes to the "entitlement_id" field. +func (m *UsageResetMutation) ResetEntitlementID() { + m.entitlement = nil +} + +// SetResetTime sets the "reset_time" field. +func (m *UsageResetMutation) SetResetTime(t time.Time) { + m.reset_time = &t +} + +// ResetTime returns the value of the "reset_time" field in the mutation. +func (m *UsageResetMutation) ResetTime() (r time.Time, exists bool) { + v := m.reset_time + if v == nil { + return + } + return *v, true +} + +// OldResetTime returns the old "reset_time" field's value of the UsageReset entity. +// If the UsageReset 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 *UsageResetMutation) OldResetTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldResetTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldResetTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldResetTime: %w", err) + } + return oldValue.ResetTime, nil +} + +// ResetResetTime resets all changes to the "reset_time" field. +func (m *UsageResetMutation) ResetResetTime() { + m.reset_time = nil +} + +// SetAnchor sets the "anchor" field. +func (m *UsageResetMutation) SetAnchor(t time.Time) { + m.anchor = &t +} + +// Anchor returns the value of the "anchor" field in the mutation. +func (m *UsageResetMutation) Anchor() (r time.Time, exists bool) { + v := m.anchor + if v == nil { + return + } + return *v, true +} + +// OldAnchor returns the old "anchor" field's value of the UsageReset entity. +// If the UsageReset 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 *UsageResetMutation) OldAnchor(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAnchor is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAnchor requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAnchor: %w", err) + } + return oldValue.Anchor, nil +} + +// ResetAnchor resets all changes to the "anchor" field. +func (m *UsageResetMutation) ResetAnchor() { + m.anchor = nil +} + +// SetUsagePeriodInterval sets the "usage_period_interval" field. +func (m *UsageResetMutation) SetUsagePeriodInterval(dds datetime.ISODurationString) { + m.usage_period_interval = &dds +} + +// UsagePeriodInterval returns the value of the "usage_period_interval" field in the mutation. +func (m *UsageResetMutation) UsagePeriodInterval() (r datetime.ISODurationString, exists bool) { + v := m.usage_period_interval + if v == nil { + return + } + return *v, true +} + +// OldUsagePeriodInterval returns the old "usage_period_interval" field's value of the UsageReset entity. +// If the UsageReset 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 *UsageResetMutation) OldUsagePeriodInterval(ctx context.Context) (v datetime.ISODurationString, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUsagePeriodInterval is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUsagePeriodInterval requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUsagePeriodInterval: %w", err) + } + return oldValue.UsagePeriodInterval, nil +} + +// ResetUsagePeriodInterval resets all changes to the "usage_period_interval" field. +func (m *UsageResetMutation) ResetUsagePeriodInterval() { + m.usage_period_interval = nil +} + +// ClearEntitlement clears the "entitlement" edge to the Entitlement entity. +func (m *UsageResetMutation) ClearEntitlement() { + m.clearedentitlement = true + m.clearedFields[usagereset.FieldEntitlementID] = struct{}{} +} + +// EntitlementCleared reports if the "entitlement" edge to the Entitlement entity was cleared. +func (m *UsageResetMutation) EntitlementCleared() bool { + return m.clearedentitlement +} + +// EntitlementIDs returns the "entitlement" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// EntitlementID instead. It exists only for internal usage by the builders. +func (m *UsageResetMutation) EntitlementIDs() (ids []string) { + if id := m.entitlement; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetEntitlement resets all changes to the "entitlement" edge. +func (m *UsageResetMutation) ResetEntitlement() { + m.entitlement = nil + m.clearedentitlement = false +} + +// Where appends a list predicates to the UsageResetMutation builder. +func (m *UsageResetMutation) Where(ps ...predicate.UsageReset) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the UsageResetMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *UsageResetMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.UsageReset, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *UsageResetMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *UsageResetMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (UsageReset). +func (m *UsageResetMutation) 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 *UsageResetMutation) Fields() []string { + fields := make([]string, 0, 9) + if m.namespace != nil { + fields = append(fields, usagereset.FieldNamespace) + } + if m.annotations != nil { + fields = append(fields, usagereset.FieldAnnotations) + } + if m.created_at != nil { + fields = append(fields, usagereset.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, usagereset.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, usagereset.FieldDeletedAt) + } + if m.entitlement != nil { + fields = append(fields, usagereset.FieldEntitlementID) + } + if m.reset_time != nil { + fields = append(fields, usagereset.FieldResetTime) + } + if m.anchor != nil { + fields = append(fields, usagereset.FieldAnchor) + } + if m.usage_period_interval != nil { + fields = append(fields, usagereset.FieldUsagePeriodInterval) + } + 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 *UsageResetMutation) Field(name string) (ent.Value, bool) { + switch name { + case usagereset.FieldNamespace: + return m.Namespace() + case usagereset.FieldAnnotations: + return m.Annotations() + case usagereset.FieldCreatedAt: + return m.CreatedAt() + case usagereset.FieldUpdatedAt: + return m.UpdatedAt() + case usagereset.FieldDeletedAt: + return m.DeletedAt() + case usagereset.FieldEntitlementID: + return m.EntitlementID() + case usagereset.FieldResetTime: + return m.ResetTime() + case usagereset.FieldAnchor: + return m.Anchor() + case usagereset.FieldUsagePeriodInterval: + return m.UsagePeriodInterval() + } + 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 *UsageResetMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case usagereset.FieldNamespace: + return m.OldNamespace(ctx) + case usagereset.FieldAnnotations: + return m.OldAnnotations(ctx) + case usagereset.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case usagereset.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case usagereset.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case usagereset.FieldEntitlementID: + return m.OldEntitlementID(ctx) + case usagereset.FieldResetTime: + return m.OldResetTime(ctx) + case usagereset.FieldAnchor: + return m.OldAnchor(ctx) + case usagereset.FieldUsagePeriodInterval: + return m.OldUsagePeriodInterval(ctx) + } + return nil, fmt.Errorf("unknown UsageReset 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 *UsageResetMutation) SetField(name string, value ent.Value) error { + switch name { + case usagereset.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case usagereset.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 usagereset.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 usagereset.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 usagereset.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 usagereset.FieldEntitlementID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEntitlementID(v) + return nil + case usagereset.FieldResetTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetResetTime(v) + return nil + case usagereset.FieldAnchor: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAnchor(v) + return nil + case usagereset.FieldUsagePeriodInterval: + v, ok := value.(datetime.ISODurationString) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUsagePeriodInterval(v) + return nil + } + return fmt.Errorf("unknown UsageReset field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *UsageResetMutation) 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 *UsageResetMutation) 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 *UsageResetMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown UsageReset numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *UsageResetMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(usagereset.FieldAnnotations) { + fields = append(fields, usagereset.FieldAnnotations) + } + if m.FieldCleared(usagereset.FieldDeletedAt) { + fields = append(fields, usagereset.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *UsageResetMutation) 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 *UsageResetMutation) ClearField(name string) error { + switch name { + case usagereset.FieldAnnotations: + m.ClearAnnotations() + return nil + case usagereset.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown UsageReset 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 *UsageResetMutation) ResetField(name string) error { + switch name { + case usagereset.FieldNamespace: + m.ResetNamespace() + return nil + case usagereset.FieldAnnotations: + m.ResetAnnotations() + return nil + case usagereset.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case usagereset.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case usagereset.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case usagereset.FieldEntitlementID: + m.ResetEntitlementID() + return nil + case usagereset.FieldResetTime: + m.ResetResetTime() + return nil + case usagereset.FieldAnchor: + m.ResetAnchor() + return nil + case usagereset.FieldUsagePeriodInterval: + m.ResetUsagePeriodInterval() + return nil + } + return fmt.Errorf("unknown UsageReset field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *UsageResetMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.entitlement != nil { + edges = append(edges, usagereset.EdgeEntitlement) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *UsageResetMutation) AddedIDs(name string) []ent.Value { + switch name { + case usagereset.EdgeEntitlement: + if id := m.entitlement; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *UsageResetMutation) 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 *UsageResetMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *UsageResetMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedentitlement { + edges = append(edges, usagereset.EdgeEntitlement) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *UsageResetMutation) EdgeCleared(name string) bool { + switch name { + case usagereset.EdgeEntitlement: + return m.clearedentitlement + } + 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 *UsageResetMutation) ClearEdge(name string) error { + switch name { + case usagereset.EdgeEntitlement: + m.ClearEntitlement() + return nil + } + return fmt.Errorf("unknown UsageReset 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 *UsageResetMutation) ResetEdge(name string) error { + switch name { + case usagereset.EdgeEntitlement: + m.ResetEntitlement() + return nil + } + return fmt.Errorf("unknown UsageReset edge %s", name) +} diff --git a/ent/db/notificationchannel.go b/ent/db/notificationchannel.go new file mode 100644 index 0000000000000000000000000000000000000000..ddd974f3ed7214d97f39f71d7ab3c4ae569ca601 --- /dev/null +++ b/ent/db/notificationchannel.go @@ -0,0 +1,245 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/notificationchannel" + "github.com/openmeterio/openmeter/openmeter/notification" + "github.com/openmeterio/openmeter/pkg/models" +) + +// NotificationChannel is the model entity for the NotificationChannel schema. +type NotificationChannel 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"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,omitempty"` + // Metadata holds the value of the "metadata" field. + Metadata map[string]string `json:"metadata,omitempty"` + // Type holds the value of the "type" field. + Type notification.ChannelType `json:"type,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Disabled holds the value of the "disabled" field. + Disabled bool `json:"disabled,omitempty"` + // Config holds the value of the "config" field. + Config notification.ChannelConfig `json:"config,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the NotificationChannelQuery when eager-loading is set. + Edges NotificationChannelEdges `json:"edges"` + selectValues sql.SelectValues +} + +// NotificationChannelEdges holds the relations/edges for other nodes in the graph. +type NotificationChannelEdges struct { + // Rules holds the value of the rules edge. + Rules []*NotificationRule `json:"rules,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// RulesOrErr returns the Rules value or an error if the edge +// was not loaded in eager-loading. +func (e NotificationChannelEdges) RulesOrErr() ([]*NotificationRule, error) { + if e.loadedTypes[0] { + return e.Rules, nil + } + return nil, &NotLoadedError{edge: "rules"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*NotificationChannel) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case notificationchannel.FieldAnnotations, notificationchannel.FieldMetadata: + values[i] = new([]byte) + case notificationchannel.FieldDisabled: + values[i] = new(sql.NullBool) + case notificationchannel.FieldID, notificationchannel.FieldNamespace, notificationchannel.FieldType, notificationchannel.FieldName: + values[i] = new(sql.NullString) + case notificationchannel.FieldCreatedAt, notificationchannel.FieldUpdatedAt, notificationchannel.FieldDeletedAt: + values[i] = new(sql.NullTime) + case notificationchannel.FieldConfig: + values[i] = notificationchannel.ValueScanner.Config.ScanValue() + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the NotificationChannel fields. +func (_m *NotificationChannel) 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 notificationchannel.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 notificationchannel.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 notificationchannel.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 notificationchannel.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 notificationchannel.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 notificationchannel.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 notificationchannel.FieldMetadata: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field metadata", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Metadata); err != nil { + return fmt.Errorf("unmarshal field metadata: %w", err) + } + } + case notificationchannel.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 = notification.ChannelType(value.String) + } + case notificationchannel.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case notificationchannel.FieldDisabled: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field disabled", values[i]) + } else if value.Valid { + _m.Disabled = value.Bool + } + case notificationchannel.FieldConfig: + if value, err := notificationchannel.ValueScanner.Config.FromValue(values[i]); err != nil { + return err + } else { + _m.Config = value + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the NotificationChannel. +// This includes values selected through modifiers, order, etc. +func (_m *NotificationChannel) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryRules queries the "rules" edge of the NotificationChannel entity. +func (_m *NotificationChannel) QueryRules() *NotificationRuleQuery { + return NewNotificationChannelClient(_m.config).QueryRules(_m) +} + +// Update returns a builder for updating this NotificationChannel. +// Note that you need to call NotificationChannel.Unwrap() before calling this method if this NotificationChannel +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *NotificationChannel) Update() *NotificationChannelUpdateOne { + return NewNotificationChannelClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the NotificationChannel 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 *NotificationChannel) Unwrap() *NotificationChannel { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: NotificationChannel is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *NotificationChannel) String() string { + var builder strings.Builder + builder.WriteString("NotificationChannel(") + 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("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + builder.WriteString(", ") + builder.WriteString("metadata=") + builder.WriteString(fmt.Sprintf("%v", _m.Metadata)) + builder.WriteString(", ") + builder.WriteString("type=") + builder.WriteString(fmt.Sprintf("%v", _m.Type)) + builder.WriteString(", ") + builder.WriteString("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + builder.WriteString("disabled=") + builder.WriteString(fmt.Sprintf("%v", _m.Disabled)) + builder.WriteString(", ") + builder.WriteString("config=") + builder.WriteString(fmt.Sprintf("%v", _m.Config)) + builder.WriteByte(')') + return builder.String() +} + +// NotificationChannels is a parsable slice of NotificationChannel. +type NotificationChannels []*NotificationChannel diff --git a/ent/db/notificationchannel/notificationchannel.go b/ent/db/notificationchannel/notificationchannel.go new file mode 100644 index 0000000000000000000000000000000000000000..96ec2a214203f4e83791962d2d0043526d09aa8f --- /dev/null +++ b/ent/db/notificationchannel/notificationchannel.go @@ -0,0 +1,180 @@ +// Code generated by ent, DO NOT EDIT. + +package notificationchannel + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/notification" +) + +const ( + // Label holds the string label denoting the notificationchannel type in the database. + Label = "notification_channel" + // 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" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // FieldType holds the string denoting the type field in the database. + FieldType = "type" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDisabled holds the string denoting the disabled field in the database. + FieldDisabled = "disabled" + // FieldConfig holds the string denoting the config field in the database. + FieldConfig = "config" + // EdgeRules holds the string denoting the rules edge name in mutations. + EdgeRules = "rules" + // Table holds the table name of the notificationchannel in the database. + Table = "notification_channels" + // RulesTable is the table that holds the rules relation/edge. The primary key declared below. + RulesTable = "notification_channel_rules" + // RulesInverseTable is the table name for the NotificationRule entity. + // It exists in this package in order to avoid circular dependency with the "notificationrule" package. + RulesInverseTable = "notification_rules" +) + +// Columns holds all SQL columns for notificationchannel fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldAnnotations, + FieldMetadata, + FieldType, + FieldName, + FieldDisabled, + FieldConfig, +} + +var ( + // RulesPrimaryKey and RulesColumn2 are the table columns denoting the + // primary key for the rules relation (M2M). + RulesPrimaryKey = []string{"notification_channel_id", "notification_rule_id"} +) + +// 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 + // NameValidator is a validator for the "name" field. It is called by the builders before save. + NameValidator func(string) error + // DefaultDisabled holds the default value on creation for the "disabled" field. + DefaultDisabled bool + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string + // ValueScanner of all NotificationChannel fields. + ValueScanner struct { + Config field.TypeValueScanner[notification.ChannelConfig] + } +) + +// TypeValidator is a validator for the "type" field enum values. It is called by the builders before save. +func TypeValidator(_type notification.ChannelType) error { + switch _type { + case "WEBHOOK": + return nil + default: + return fmt.Errorf("notificationchannel: invalid enum value for type field: %q", _type) + } +} + +// OrderOption defines the ordering options for the NotificationChannel 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() +} + +// ByType orders the results by the type field. +func ByType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldType, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDisabled orders the results by the disabled field. +func ByDisabled(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDisabled, opts...).ToFunc() +} + +// ByConfig orders the results by the config field. +func ByConfig(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldConfig, opts...).ToFunc() +} + +// ByRulesCount orders the results by rules count. +func ByRulesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newRulesStep(), opts...) + } +} + +// ByRules orders the results by rules terms. +func ByRules(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newRulesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newRulesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RulesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, RulesTable, RulesPrimaryKey...), + ) +} diff --git a/ent/db/notificationchannel/where.go b/ent/db/notificationchannel/where.go new file mode 100644 index 0000000000000000000000000000000000000000..334d79cb4cf389d28871cdb7bb1053cea0df42ad --- /dev/null +++ b/ent/db/notificationchannel/where.go @@ -0,0 +1,465 @@ +// Code generated by ent, DO NOT EDIT. + +package notificationchannel + +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/notification" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(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.NotificationChannel { + return predicate.NotificationChannel(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.NotificationChannel { + return predicate.NotificationChannel(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.NotificationChannel { + return predicate.NotificationChannel(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldEQ(FieldName, v)) +} + +// Disabled applies equality check predicate on the "disabled" field. It's identical to DisabledEQ. +func Disabled(v bool) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldEQ(FieldDisabled, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldNotNull(FieldDeletedAt)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldNotNull(FieldAnnotations)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldNotNull(FieldMetadata)) +} + +// TypeEQ applies the EQ predicate on the "type" field. +func TypeEQ(v notification.ChannelType) predicate.NotificationChannel { + vc := v + return predicate.NotificationChannel(sql.FieldEQ(FieldType, vc)) +} + +// TypeNEQ applies the NEQ predicate on the "type" field. +func TypeNEQ(v notification.ChannelType) predicate.NotificationChannel { + vc := v + return predicate.NotificationChannel(sql.FieldNEQ(FieldType, vc)) +} + +// TypeIn applies the In predicate on the "type" field. +func TypeIn(vs ...notification.ChannelType) predicate.NotificationChannel { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.NotificationChannel(sql.FieldIn(FieldType, v...)) +} + +// TypeNotIn applies the NotIn predicate on the "type" field. +func TypeNotIn(vs ...notification.ChannelType) predicate.NotificationChannel { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.NotificationChannel(sql.FieldNotIn(FieldType, v...)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldContainsFold(FieldName, v)) +} + +// DisabledEQ applies the EQ predicate on the "disabled" field. +func DisabledEQ(v bool) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldEQ(FieldDisabled, v)) +} + +// DisabledNEQ applies the NEQ predicate on the "disabled" field. +func DisabledNEQ(v bool) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldNEQ(FieldDisabled, v)) +} + +// DisabledIsNil applies the IsNil predicate on the "disabled" field. +func DisabledIsNil() predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldIsNull(FieldDisabled)) +} + +// DisabledNotNil applies the NotNil predicate on the "disabled" field. +func DisabledNotNil() predicate.NotificationChannel { + return predicate.NotificationChannel(sql.FieldNotNull(FieldDisabled)) +} + +// HasRules applies the HasEdge predicate on the "rules" edge. +func HasRules() predicate.NotificationChannel { + return predicate.NotificationChannel(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, RulesTable, RulesPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasRulesWith applies the HasEdge predicate on the "rules" edge with a given conditions (other predicates). +func HasRulesWith(preds ...predicate.NotificationRule) predicate.NotificationChannel { + return predicate.NotificationChannel(func(s *sql.Selector) { + step := newRulesStep() + 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.NotificationChannel) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.NotificationChannel) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.NotificationChannel) predicate.NotificationChannel { + return predicate.NotificationChannel(sql.NotPredicates(p)) +} diff --git a/ent/db/notificationchannel_create.go b/ent/db/notificationchannel_create.go new file mode 100644 index 0000000000000000000000000000000000000000..edfad28b5a61a46deee92a3122f940a17ada4174 --- /dev/null +++ b/ent/db/notificationchannel_create.go @@ -0,0 +1,1059 @@ +// 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/notificationchannel" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationrule" + "github.com/openmeterio/openmeter/openmeter/notification" + "github.com/openmeterio/openmeter/pkg/models" +) + +// NotificationChannelCreate is the builder for creating a NotificationChannel entity. +type NotificationChannelCreate struct { + config + mutation *NotificationChannelMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *NotificationChannelCreate) SetNamespace(v string) *NotificationChannelCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *NotificationChannelCreate) SetCreatedAt(v time.Time) *NotificationChannelCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *NotificationChannelCreate) SetNillableCreatedAt(v *time.Time) *NotificationChannelCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *NotificationChannelCreate) SetUpdatedAt(v time.Time) *NotificationChannelCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *NotificationChannelCreate) SetNillableUpdatedAt(v *time.Time) *NotificationChannelCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *NotificationChannelCreate) SetDeletedAt(v time.Time) *NotificationChannelCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *NotificationChannelCreate) SetNillableDeletedAt(v *time.Time) *NotificationChannelCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *NotificationChannelCreate) SetAnnotations(v models.Annotations) *NotificationChannelCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetMetadata sets the "metadata" field. +func (_c *NotificationChannelCreate) SetMetadata(v map[string]string) *NotificationChannelCreate { + _c.mutation.SetMetadata(v) + return _c +} + +// SetType sets the "type" field. +func (_c *NotificationChannelCreate) SetType(v notification.ChannelType) *NotificationChannelCreate { + _c.mutation.SetType(v) + return _c +} + +// SetName sets the "name" field. +func (_c *NotificationChannelCreate) SetName(v string) *NotificationChannelCreate { + _c.mutation.SetName(v) + return _c +} + +// SetDisabled sets the "disabled" field. +func (_c *NotificationChannelCreate) SetDisabled(v bool) *NotificationChannelCreate { + _c.mutation.SetDisabled(v) + return _c +} + +// SetNillableDisabled sets the "disabled" field if the given value is not nil. +func (_c *NotificationChannelCreate) SetNillableDisabled(v *bool) *NotificationChannelCreate { + if v != nil { + _c.SetDisabled(*v) + } + return _c +} + +// SetConfig sets the "config" field. +func (_c *NotificationChannelCreate) SetConfig(v notification.ChannelConfig) *NotificationChannelCreate { + _c.mutation.SetConfig(v) + return _c +} + +// SetID sets the "id" field. +func (_c *NotificationChannelCreate) SetID(v string) *NotificationChannelCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *NotificationChannelCreate) SetNillableID(v *string) *NotificationChannelCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// AddRuleIDs adds the "rules" edge to the NotificationRule entity by IDs. +func (_c *NotificationChannelCreate) AddRuleIDs(ids ...string) *NotificationChannelCreate { + _c.mutation.AddRuleIDs(ids...) + return _c +} + +// AddRules adds the "rules" edges to the NotificationRule entity. +func (_c *NotificationChannelCreate) AddRules(v ...*NotificationRule) *NotificationChannelCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddRuleIDs(ids...) +} + +// Mutation returns the NotificationChannelMutation object of the builder. +func (_c *NotificationChannelCreate) Mutation() *NotificationChannelMutation { + return _c.mutation +} + +// Save creates the NotificationChannel in the database. +func (_c *NotificationChannelCreate) Save(ctx context.Context) (*NotificationChannel, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *NotificationChannelCreate) SaveX(ctx context.Context) *NotificationChannel { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *NotificationChannelCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *NotificationChannelCreate) 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 *NotificationChannelCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := notificationchannel.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := notificationchannel.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.Disabled(); !ok { + v := notificationchannel.DefaultDisabled + _c.mutation.SetDisabled(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := notificationchannel.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *NotificationChannelCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "NotificationChannel.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := notificationchannel.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "NotificationChannel.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "NotificationChannel.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "NotificationChannel.updated_at"`)} + } + if _, ok := _c.mutation.GetType(); !ok { + return &ValidationError{Name: "type", err: errors.New(`db: missing required field "NotificationChannel.type"`)} + } + if v, ok := _c.mutation.GetType(); ok { + if err := notificationchannel.TypeValidator(v); err != nil { + return &ValidationError{Name: "type", err: fmt.Errorf(`db: validator failed for field "NotificationChannel.type": %w`, err)} + } + } + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "NotificationChannel.name"`)} + } + if v, ok := _c.mutation.Name(); ok { + if err := notificationchannel.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "NotificationChannel.name": %w`, err)} + } + } + if _, ok := _c.mutation.Config(); !ok { + return &ValidationError{Name: "config", err: errors.New(`db: missing required field "NotificationChannel.config"`)} + } + if v, ok := _c.mutation.Config(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "config", err: fmt.Errorf(`db: validator failed for field "NotificationChannel.config": %w`, err)} + } + } + return nil +} + +func (_c *NotificationChannelCreate) sqlSave(ctx context.Context) (*NotificationChannel, 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 NotificationChannel.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *NotificationChannelCreate) createSpec() (*NotificationChannel, *sqlgraph.CreateSpec, error) { + var ( + _node = &NotificationChannel{config: _c.config} + _spec = sqlgraph.NewCreateSpec(notificationchannel.Table, sqlgraph.NewFieldSpec(notificationchannel.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(notificationchannel.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(notificationchannel.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(notificationchannel.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(notificationchannel.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(notificationchannel.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.Metadata(); ok { + _spec.SetField(notificationchannel.FieldMetadata, field.TypeJSON, value) + _node.Metadata = value + } + if value, ok := _c.mutation.GetType(); ok { + _spec.SetField(notificationchannel.FieldType, field.TypeEnum, value) + _node.Type = value + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(notificationchannel.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Disabled(); ok { + _spec.SetField(notificationchannel.FieldDisabled, field.TypeBool, value) + _node.Disabled = value + } + if value, ok := _c.mutation.Config(); ok { + vv, err := notificationchannel.ValueScanner.Config.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(notificationchannel.FieldConfig, field.TypeString, vv) + _node.Config = value + } + if nodes := _c.mutation.RulesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: notificationchannel.RulesTable, + Columns: notificationchannel.RulesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationrule.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.NotificationChannel.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.NotificationChannelUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *NotificationChannelCreate) OnConflict(opts ...sql.ConflictOption) *NotificationChannelUpsertOne { + _c.conflict = opts + return &NotificationChannelUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.NotificationChannel.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *NotificationChannelCreate) OnConflictColumns(columns ...string) *NotificationChannelUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &NotificationChannelUpsertOne{ + create: _c, + } +} + +type ( + // NotificationChannelUpsertOne is the builder for "upsert"-ing + // one NotificationChannel node. + NotificationChannelUpsertOne struct { + create *NotificationChannelCreate + } + + // NotificationChannelUpsert is the "OnConflict" setter. + NotificationChannelUpsert struct { + *sql.UpdateSet + } +) + +// SetUpdatedAt sets the "updated_at" field. +func (u *NotificationChannelUpsert) SetUpdatedAt(v time.Time) *NotificationChannelUpsert { + u.Set(notificationchannel.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *NotificationChannelUpsert) UpdateUpdatedAt() *NotificationChannelUpsert { + u.SetExcluded(notificationchannel.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *NotificationChannelUpsert) SetDeletedAt(v time.Time) *NotificationChannelUpsert { + u.Set(notificationchannel.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *NotificationChannelUpsert) UpdateDeletedAt() *NotificationChannelUpsert { + u.SetExcluded(notificationchannel.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *NotificationChannelUpsert) ClearDeletedAt() *NotificationChannelUpsert { + u.SetNull(notificationchannel.FieldDeletedAt) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *NotificationChannelUpsert) SetAnnotations(v models.Annotations) *NotificationChannelUpsert { + u.Set(notificationchannel.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *NotificationChannelUpsert) UpdateAnnotations() *NotificationChannelUpsert { + u.SetExcluded(notificationchannel.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *NotificationChannelUpsert) ClearAnnotations() *NotificationChannelUpsert { + u.SetNull(notificationchannel.FieldAnnotations) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *NotificationChannelUpsert) SetMetadata(v map[string]string) *NotificationChannelUpsert { + u.Set(notificationchannel.FieldMetadata, v) + return u +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *NotificationChannelUpsert) UpdateMetadata() *NotificationChannelUpsert { + u.SetExcluded(notificationchannel.FieldMetadata) + return u +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *NotificationChannelUpsert) ClearMetadata() *NotificationChannelUpsert { + u.SetNull(notificationchannel.FieldMetadata) + return u +} + +// SetName sets the "name" field. +func (u *NotificationChannelUpsert) SetName(v string) *NotificationChannelUpsert { + u.Set(notificationchannel.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *NotificationChannelUpsert) UpdateName() *NotificationChannelUpsert { + u.SetExcluded(notificationchannel.FieldName) + return u +} + +// SetDisabled sets the "disabled" field. +func (u *NotificationChannelUpsert) SetDisabled(v bool) *NotificationChannelUpsert { + u.Set(notificationchannel.FieldDisabled, v) + return u +} + +// UpdateDisabled sets the "disabled" field to the value that was provided on create. +func (u *NotificationChannelUpsert) UpdateDisabled() *NotificationChannelUpsert { + u.SetExcluded(notificationchannel.FieldDisabled) + return u +} + +// ClearDisabled clears the value of the "disabled" field. +func (u *NotificationChannelUpsert) ClearDisabled() *NotificationChannelUpsert { + u.SetNull(notificationchannel.FieldDisabled) + return u +} + +// SetConfig sets the "config" field. +func (u *NotificationChannelUpsert) SetConfig(v notification.ChannelConfig) *NotificationChannelUpsert { + u.Set(notificationchannel.FieldConfig, v) + return u +} + +// UpdateConfig sets the "config" field to the value that was provided on create. +func (u *NotificationChannelUpsert) UpdateConfig() *NotificationChannelUpsert { + u.SetExcluded(notificationchannel.FieldConfig) + 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.NotificationChannel.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(notificationchannel.FieldID) +// }), +// ). +// Exec(ctx) +func (u *NotificationChannelUpsertOne) UpdateNewValues() *NotificationChannelUpsertOne { + 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(notificationchannel.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(notificationchannel.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(notificationchannel.FieldCreatedAt) + } + if _, exists := u.create.mutation.GetType(); exists { + s.SetIgnore(notificationchannel.FieldType) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.NotificationChannel.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *NotificationChannelUpsertOne) Ignore() *NotificationChannelUpsertOne { + 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 *NotificationChannelUpsertOne) DoNothing() *NotificationChannelUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the NotificationChannelCreate.OnConflict +// documentation for more info. +func (u *NotificationChannelUpsertOne) Update(set func(*NotificationChannelUpsert)) *NotificationChannelUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&NotificationChannelUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *NotificationChannelUpsertOne) SetUpdatedAt(v time.Time) *NotificationChannelUpsertOne { + return u.Update(func(s *NotificationChannelUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *NotificationChannelUpsertOne) UpdateUpdatedAt() *NotificationChannelUpsertOne { + return u.Update(func(s *NotificationChannelUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *NotificationChannelUpsertOne) SetDeletedAt(v time.Time) *NotificationChannelUpsertOne { + return u.Update(func(s *NotificationChannelUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *NotificationChannelUpsertOne) UpdateDeletedAt() *NotificationChannelUpsertOne { + return u.Update(func(s *NotificationChannelUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *NotificationChannelUpsertOne) ClearDeletedAt() *NotificationChannelUpsertOne { + return u.Update(func(s *NotificationChannelUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *NotificationChannelUpsertOne) SetAnnotations(v models.Annotations) *NotificationChannelUpsertOne { + return u.Update(func(s *NotificationChannelUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *NotificationChannelUpsertOne) UpdateAnnotations() *NotificationChannelUpsertOne { + return u.Update(func(s *NotificationChannelUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *NotificationChannelUpsertOne) ClearAnnotations() *NotificationChannelUpsertOne { + return u.Update(func(s *NotificationChannelUpsert) { + s.ClearAnnotations() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *NotificationChannelUpsertOne) SetMetadata(v map[string]string) *NotificationChannelUpsertOne { + return u.Update(func(s *NotificationChannelUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *NotificationChannelUpsertOne) UpdateMetadata() *NotificationChannelUpsertOne { + return u.Update(func(s *NotificationChannelUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *NotificationChannelUpsertOne) ClearMetadata() *NotificationChannelUpsertOne { + return u.Update(func(s *NotificationChannelUpsert) { + s.ClearMetadata() + }) +} + +// SetName sets the "name" field. +func (u *NotificationChannelUpsertOne) SetName(v string) *NotificationChannelUpsertOne { + return u.Update(func(s *NotificationChannelUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *NotificationChannelUpsertOne) UpdateName() *NotificationChannelUpsertOne { + return u.Update(func(s *NotificationChannelUpsert) { + s.UpdateName() + }) +} + +// SetDisabled sets the "disabled" field. +func (u *NotificationChannelUpsertOne) SetDisabled(v bool) *NotificationChannelUpsertOne { + return u.Update(func(s *NotificationChannelUpsert) { + s.SetDisabled(v) + }) +} + +// UpdateDisabled sets the "disabled" field to the value that was provided on create. +func (u *NotificationChannelUpsertOne) UpdateDisabled() *NotificationChannelUpsertOne { + return u.Update(func(s *NotificationChannelUpsert) { + s.UpdateDisabled() + }) +} + +// ClearDisabled clears the value of the "disabled" field. +func (u *NotificationChannelUpsertOne) ClearDisabled() *NotificationChannelUpsertOne { + return u.Update(func(s *NotificationChannelUpsert) { + s.ClearDisabled() + }) +} + +// SetConfig sets the "config" field. +func (u *NotificationChannelUpsertOne) SetConfig(v notification.ChannelConfig) *NotificationChannelUpsertOne { + return u.Update(func(s *NotificationChannelUpsert) { + s.SetConfig(v) + }) +} + +// UpdateConfig sets the "config" field to the value that was provided on create. +func (u *NotificationChannelUpsertOne) UpdateConfig() *NotificationChannelUpsertOne { + return u.Update(func(s *NotificationChannelUpsert) { + s.UpdateConfig() + }) +} + +// Exec executes the query. +func (u *NotificationChannelUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for NotificationChannelCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *NotificationChannelUpsertOne) 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 *NotificationChannelUpsertOne) 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: NotificationChannelUpsertOne.ID is not supported by MySQL driver. Use NotificationChannelUpsertOne.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 *NotificationChannelUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// NotificationChannelCreateBulk is the builder for creating many NotificationChannel entities in bulk. +type NotificationChannelCreateBulk struct { + config + err error + builders []*NotificationChannelCreate + conflict []sql.ConflictOption +} + +// Save creates the NotificationChannel entities in the database. +func (_c *NotificationChannelCreateBulk) Save(ctx context.Context) ([]*NotificationChannel, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*NotificationChannel, 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.(*NotificationChannelMutation) + 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 *NotificationChannelCreateBulk) SaveX(ctx context.Context) []*NotificationChannel { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *NotificationChannelCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *NotificationChannelCreateBulk) 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.NotificationChannel.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.NotificationChannelUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *NotificationChannelCreateBulk) OnConflict(opts ...sql.ConflictOption) *NotificationChannelUpsertBulk { + _c.conflict = opts + return &NotificationChannelUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.NotificationChannel.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *NotificationChannelCreateBulk) OnConflictColumns(columns ...string) *NotificationChannelUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &NotificationChannelUpsertBulk{ + create: _c, + } +} + +// NotificationChannelUpsertBulk is the builder for "upsert"-ing +// a bulk of NotificationChannel nodes. +type NotificationChannelUpsertBulk struct { + create *NotificationChannelCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.NotificationChannel.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(notificationchannel.FieldID) +// }), +// ). +// Exec(ctx) +func (u *NotificationChannelUpsertBulk) UpdateNewValues() *NotificationChannelUpsertBulk { + 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(notificationchannel.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(notificationchannel.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(notificationchannel.FieldCreatedAt) + } + if _, exists := b.mutation.GetType(); exists { + s.SetIgnore(notificationchannel.FieldType) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.NotificationChannel.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *NotificationChannelUpsertBulk) Ignore() *NotificationChannelUpsertBulk { + 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 *NotificationChannelUpsertBulk) DoNothing() *NotificationChannelUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the NotificationChannelCreateBulk.OnConflict +// documentation for more info. +func (u *NotificationChannelUpsertBulk) Update(set func(*NotificationChannelUpsert)) *NotificationChannelUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&NotificationChannelUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *NotificationChannelUpsertBulk) SetUpdatedAt(v time.Time) *NotificationChannelUpsertBulk { + return u.Update(func(s *NotificationChannelUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *NotificationChannelUpsertBulk) UpdateUpdatedAt() *NotificationChannelUpsertBulk { + return u.Update(func(s *NotificationChannelUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *NotificationChannelUpsertBulk) SetDeletedAt(v time.Time) *NotificationChannelUpsertBulk { + return u.Update(func(s *NotificationChannelUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *NotificationChannelUpsertBulk) UpdateDeletedAt() *NotificationChannelUpsertBulk { + return u.Update(func(s *NotificationChannelUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *NotificationChannelUpsertBulk) ClearDeletedAt() *NotificationChannelUpsertBulk { + return u.Update(func(s *NotificationChannelUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *NotificationChannelUpsertBulk) SetAnnotations(v models.Annotations) *NotificationChannelUpsertBulk { + return u.Update(func(s *NotificationChannelUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *NotificationChannelUpsertBulk) UpdateAnnotations() *NotificationChannelUpsertBulk { + return u.Update(func(s *NotificationChannelUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *NotificationChannelUpsertBulk) ClearAnnotations() *NotificationChannelUpsertBulk { + return u.Update(func(s *NotificationChannelUpsert) { + s.ClearAnnotations() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *NotificationChannelUpsertBulk) SetMetadata(v map[string]string) *NotificationChannelUpsertBulk { + return u.Update(func(s *NotificationChannelUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *NotificationChannelUpsertBulk) UpdateMetadata() *NotificationChannelUpsertBulk { + return u.Update(func(s *NotificationChannelUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *NotificationChannelUpsertBulk) ClearMetadata() *NotificationChannelUpsertBulk { + return u.Update(func(s *NotificationChannelUpsert) { + s.ClearMetadata() + }) +} + +// SetName sets the "name" field. +func (u *NotificationChannelUpsertBulk) SetName(v string) *NotificationChannelUpsertBulk { + return u.Update(func(s *NotificationChannelUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *NotificationChannelUpsertBulk) UpdateName() *NotificationChannelUpsertBulk { + return u.Update(func(s *NotificationChannelUpsert) { + s.UpdateName() + }) +} + +// SetDisabled sets the "disabled" field. +func (u *NotificationChannelUpsertBulk) SetDisabled(v bool) *NotificationChannelUpsertBulk { + return u.Update(func(s *NotificationChannelUpsert) { + s.SetDisabled(v) + }) +} + +// UpdateDisabled sets the "disabled" field to the value that was provided on create. +func (u *NotificationChannelUpsertBulk) UpdateDisabled() *NotificationChannelUpsertBulk { + return u.Update(func(s *NotificationChannelUpsert) { + s.UpdateDisabled() + }) +} + +// ClearDisabled clears the value of the "disabled" field. +func (u *NotificationChannelUpsertBulk) ClearDisabled() *NotificationChannelUpsertBulk { + return u.Update(func(s *NotificationChannelUpsert) { + s.ClearDisabled() + }) +} + +// SetConfig sets the "config" field. +func (u *NotificationChannelUpsertBulk) SetConfig(v notification.ChannelConfig) *NotificationChannelUpsertBulk { + return u.Update(func(s *NotificationChannelUpsert) { + s.SetConfig(v) + }) +} + +// UpdateConfig sets the "config" field to the value that was provided on create. +func (u *NotificationChannelUpsertBulk) UpdateConfig() *NotificationChannelUpsertBulk { + return u.Update(func(s *NotificationChannelUpsert) { + s.UpdateConfig() + }) +} + +// Exec executes the query. +func (u *NotificationChannelUpsertBulk) 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 NotificationChannelCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for NotificationChannelCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *NotificationChannelUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/notificationchannel_delete.go b/ent/db/notificationchannel_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..1b594b4633a0087b2b2399d65dafb746ae5d1a71 --- /dev/null +++ b/ent/db/notificationchannel_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/notificationchannel" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// NotificationChannelDelete is the builder for deleting a NotificationChannel entity. +type NotificationChannelDelete struct { + config + hooks []Hook + mutation *NotificationChannelMutation +} + +// Where appends a list predicates to the NotificationChannelDelete builder. +func (_d *NotificationChannelDelete) Where(ps ...predicate.NotificationChannel) *NotificationChannelDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *NotificationChannelDelete) 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 *NotificationChannelDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *NotificationChannelDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(notificationchannel.Table, sqlgraph.NewFieldSpec(notificationchannel.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 +} + +// NotificationChannelDeleteOne is the builder for deleting a single NotificationChannel entity. +type NotificationChannelDeleteOne struct { + _d *NotificationChannelDelete +} + +// Where appends a list predicates to the NotificationChannelDelete builder. +func (_d *NotificationChannelDeleteOne) Where(ps ...predicate.NotificationChannel) *NotificationChannelDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *NotificationChannelDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{notificationchannel.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *NotificationChannelDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/notificationchannel_query.go b/ent/db/notificationchannel_query.go new file mode 100644 index 0000000000000000000000000000000000000000..1b6a9caf6456749a44b05837c33d2f41ef1ed14d --- /dev/null +++ b/ent/db/notificationchannel_query.go @@ -0,0 +1,674 @@ +// 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/notificationchannel" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationrule" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// NotificationChannelQuery is the builder for querying NotificationChannel entities. +type NotificationChannelQuery struct { + config + ctx *QueryContext + order []notificationchannel.OrderOption + inters []Interceptor + predicates []predicate.NotificationChannel + withRules *NotificationRuleQuery + 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 NotificationChannelQuery builder. +func (_q *NotificationChannelQuery) Where(ps ...predicate.NotificationChannel) *NotificationChannelQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *NotificationChannelQuery) Limit(limit int) *NotificationChannelQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *NotificationChannelQuery) Offset(offset int) *NotificationChannelQuery { + _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 *NotificationChannelQuery) Unique(unique bool) *NotificationChannelQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *NotificationChannelQuery) Order(o ...notificationchannel.OrderOption) *NotificationChannelQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryRules chains the current query on the "rules" edge. +func (_q *NotificationChannelQuery) QueryRules() *NotificationRuleQuery { + query := (&NotificationRuleClient{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(notificationchannel.Table, notificationchannel.FieldID, selector), + sqlgraph.To(notificationrule.Table, notificationrule.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, notificationchannel.RulesTable, notificationchannel.RulesPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first NotificationChannel entity from the query. +// Returns a *NotFoundError when no NotificationChannel was found. +func (_q *NotificationChannelQuery) First(ctx context.Context) (*NotificationChannel, 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{notificationchannel.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *NotificationChannelQuery) FirstX(ctx context.Context) *NotificationChannel { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first NotificationChannel ID from the query. +// Returns a *NotFoundError when no NotificationChannel ID was found. +func (_q *NotificationChannelQuery) 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{notificationchannel.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *NotificationChannelQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single NotificationChannel entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one NotificationChannel entity is found. +// Returns a *NotFoundError when no NotificationChannel entities are found. +func (_q *NotificationChannelQuery) Only(ctx context.Context) (*NotificationChannel, 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{notificationchannel.Label} + default: + return nil, &NotSingularError{notificationchannel.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *NotificationChannelQuery) OnlyX(ctx context.Context) *NotificationChannel { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only NotificationChannel ID in the query. +// Returns a *NotSingularError when more than one NotificationChannel ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *NotificationChannelQuery) 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{notificationchannel.Label} + default: + err = &NotSingularError{notificationchannel.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *NotificationChannelQuery) 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 NotificationChannels. +func (_q *NotificationChannelQuery) All(ctx context.Context) ([]*NotificationChannel, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*NotificationChannel, *NotificationChannelQuery]() + return withInterceptors[[]*NotificationChannel](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *NotificationChannelQuery) AllX(ctx context.Context) []*NotificationChannel { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of NotificationChannel IDs. +func (_q *NotificationChannelQuery) 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(notificationchannel.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *NotificationChannelQuery) 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 *NotificationChannelQuery) 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[*NotificationChannelQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *NotificationChannelQuery) 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 *NotificationChannelQuery) 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 *NotificationChannelQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the NotificationChannelQuery 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 *NotificationChannelQuery) Clone() *NotificationChannelQuery { + if _q == nil { + return nil + } + return &NotificationChannelQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]notificationchannel.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.NotificationChannel{}, _q.predicates...), + withRules: _q.withRules.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithRules tells the query-builder to eager-load the nodes that are connected to +// the "rules" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *NotificationChannelQuery) WithRules(opts ...func(*NotificationRuleQuery)) *NotificationChannelQuery { + query := (&NotificationRuleClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withRules = 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.NotificationChannel.Query(). +// GroupBy(notificationchannel.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *NotificationChannelQuery) GroupBy(field string, fields ...string) *NotificationChannelGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &NotificationChannelGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = notificationchannel.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.NotificationChannel.Query(). +// Select(notificationchannel.FieldNamespace). +// Scan(ctx, &v) +func (_q *NotificationChannelQuery) Select(fields ...string) *NotificationChannelSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &NotificationChannelSelect{NotificationChannelQuery: _q} + sbuild.label = notificationchannel.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a NotificationChannelSelect configured with the given aggregations. +func (_q *NotificationChannelQuery) Aggregate(fns ...AggregateFunc) *NotificationChannelSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *NotificationChannelQuery) 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 !notificationchannel.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 *NotificationChannelQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*NotificationChannel, error) { + var ( + nodes = []*NotificationChannel{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withRules != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*NotificationChannel).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &NotificationChannel{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.withRules; query != nil { + if err := _q.loadRules(ctx, query, nodes, + func(n *NotificationChannel) { n.Edges.Rules = []*NotificationRule{} }, + func(n *NotificationChannel, e *NotificationRule) { n.Edges.Rules = append(n.Edges.Rules, e) }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *NotificationChannelQuery) loadRules(ctx context.Context, query *NotificationRuleQuery, nodes []*NotificationChannel, init func(*NotificationChannel), assign func(*NotificationChannel, *NotificationRule)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[string]*NotificationChannel) + nids := make(map[string]map[*NotificationChannel]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(notificationchannel.RulesTable) + s.Join(joinT).On(s.C(notificationrule.FieldID), joinT.C(notificationchannel.RulesPrimaryKey[1])) + s.Where(sql.InValues(joinT.C(notificationchannel.RulesPrimaryKey[0]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(notificationchannel.RulesPrimaryKey[0])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + if err := query.prepareQuery(ctx); err != nil { + return err + } + qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]any, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]any{new(sql.NullString)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := values[0].(*sql.NullString).String + inValue := values[1].(*sql.NullString).String + if nids[inValue] == nil { + nids[inValue] = map[*NotificationChannel]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*NotificationRule](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "rules" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} + +func (_q *NotificationChannelQuery) 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 *NotificationChannelQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(notificationchannel.Table, notificationchannel.Columns, sqlgraph.NewFieldSpec(notificationchannel.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, notificationchannel.FieldID) + for i := range fields { + if fields[i] != notificationchannel.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 *NotificationChannelQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(notificationchannel.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = notificationchannel.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 *NotificationChannelQuery) ForUpdate(opts ...sql.LockOption) *NotificationChannelQuery { + 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 *NotificationChannelQuery) ForShare(opts ...sql.LockOption) *NotificationChannelQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// NotificationChannelGroupBy is the group-by builder for NotificationChannel entities. +type NotificationChannelGroupBy struct { + selector + build *NotificationChannelQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *NotificationChannelGroupBy) Aggregate(fns ...AggregateFunc) *NotificationChannelGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *NotificationChannelGroupBy) 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[*NotificationChannelQuery, *NotificationChannelGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *NotificationChannelGroupBy) sqlScan(ctx context.Context, root *NotificationChannelQuery, 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) +} + +// NotificationChannelSelect is the builder for selecting fields of NotificationChannel entities. +type NotificationChannelSelect struct { + *NotificationChannelQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *NotificationChannelSelect) Aggregate(fns ...AggregateFunc) *NotificationChannelSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *NotificationChannelSelect) 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[*NotificationChannelQuery, *NotificationChannelSelect](ctx, _s.NotificationChannelQuery, _s, _s.inters, v) +} + +func (_s *NotificationChannelSelect) sqlScan(ctx context.Context, root *NotificationChannelQuery, 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/ent/db/notificationchannel_update.go b/ent/db/notificationchannel_update.go new file mode 100644 index 0000000000000000000000000000000000000000..cfcf7615d4bed7305c6f9048a2cb31769f2d0730 --- /dev/null +++ b/ent/db/notificationchannel_update.go @@ -0,0 +1,665 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/notificationchannel" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationrule" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/notification" + "github.com/openmeterio/openmeter/pkg/models" +) + +// NotificationChannelUpdate is the builder for updating NotificationChannel entities. +type NotificationChannelUpdate struct { + config + hooks []Hook + mutation *NotificationChannelMutation +} + +// Where appends a list predicates to the NotificationChannelUpdate builder. +func (_u *NotificationChannelUpdate) Where(ps ...predicate.NotificationChannel) *NotificationChannelUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *NotificationChannelUpdate) SetUpdatedAt(v time.Time) *NotificationChannelUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *NotificationChannelUpdate) SetDeletedAt(v time.Time) *NotificationChannelUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *NotificationChannelUpdate) SetNillableDeletedAt(v *time.Time) *NotificationChannelUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *NotificationChannelUpdate) ClearDeletedAt() *NotificationChannelUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *NotificationChannelUpdate) SetAnnotations(v models.Annotations) *NotificationChannelUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *NotificationChannelUpdate) ClearAnnotations() *NotificationChannelUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *NotificationChannelUpdate) SetMetadata(v map[string]string) *NotificationChannelUpdate { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *NotificationChannelUpdate) ClearMetadata() *NotificationChannelUpdate { + _u.mutation.ClearMetadata() + return _u +} + +// SetName sets the "name" field. +func (_u *NotificationChannelUpdate) SetName(v string) *NotificationChannelUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *NotificationChannelUpdate) SetNillableName(v *string) *NotificationChannelUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDisabled sets the "disabled" field. +func (_u *NotificationChannelUpdate) SetDisabled(v bool) *NotificationChannelUpdate { + _u.mutation.SetDisabled(v) + return _u +} + +// SetNillableDisabled sets the "disabled" field if the given value is not nil. +func (_u *NotificationChannelUpdate) SetNillableDisabled(v *bool) *NotificationChannelUpdate { + if v != nil { + _u.SetDisabled(*v) + } + return _u +} + +// ClearDisabled clears the value of the "disabled" field. +func (_u *NotificationChannelUpdate) ClearDisabled() *NotificationChannelUpdate { + _u.mutation.ClearDisabled() + return _u +} + +// SetConfig sets the "config" field. +func (_u *NotificationChannelUpdate) SetConfig(v notification.ChannelConfig) *NotificationChannelUpdate { + _u.mutation.SetConfig(v) + return _u +} + +// SetNillableConfig sets the "config" field if the given value is not nil. +func (_u *NotificationChannelUpdate) SetNillableConfig(v *notification.ChannelConfig) *NotificationChannelUpdate { + if v != nil { + _u.SetConfig(*v) + } + return _u +} + +// AddRuleIDs adds the "rules" edge to the NotificationRule entity by IDs. +func (_u *NotificationChannelUpdate) AddRuleIDs(ids ...string) *NotificationChannelUpdate { + _u.mutation.AddRuleIDs(ids...) + return _u +} + +// AddRules adds the "rules" edges to the NotificationRule entity. +func (_u *NotificationChannelUpdate) AddRules(v ...*NotificationRule) *NotificationChannelUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddRuleIDs(ids...) +} + +// Mutation returns the NotificationChannelMutation object of the builder. +func (_u *NotificationChannelUpdate) Mutation() *NotificationChannelMutation { + return _u.mutation +} + +// ClearRules clears all "rules" edges to the NotificationRule entity. +func (_u *NotificationChannelUpdate) ClearRules() *NotificationChannelUpdate { + _u.mutation.ClearRules() + return _u +} + +// RemoveRuleIDs removes the "rules" edge to NotificationRule entities by IDs. +func (_u *NotificationChannelUpdate) RemoveRuleIDs(ids ...string) *NotificationChannelUpdate { + _u.mutation.RemoveRuleIDs(ids...) + return _u +} + +// RemoveRules removes "rules" edges to NotificationRule entities. +func (_u *NotificationChannelUpdate) RemoveRules(v ...*NotificationRule) *NotificationChannelUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveRuleIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *NotificationChannelUpdate) 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 *NotificationChannelUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *NotificationChannelUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *NotificationChannelUpdate) 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 *NotificationChannelUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := notificationchannel.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *NotificationChannelUpdate) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := notificationchannel.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "NotificationChannel.name": %w`, err)} + } + } + if v, ok := _u.mutation.Config(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "config", err: fmt.Errorf(`db: validator failed for field "NotificationChannel.config": %w`, err)} + } + } + return nil +} + +func (_u *NotificationChannelUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(notificationchannel.Table, notificationchannel.Columns, sqlgraph.NewFieldSpec(notificationchannel.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(notificationchannel.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(notificationchannel.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(notificationchannel.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(notificationchannel.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(notificationchannel.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(notificationchannel.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(notificationchannel.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(notificationchannel.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Disabled(); ok { + _spec.SetField(notificationchannel.FieldDisabled, field.TypeBool, value) + } + if _u.mutation.DisabledCleared() { + _spec.ClearField(notificationchannel.FieldDisabled, field.TypeBool) + } + if value, ok := _u.mutation.Config(); ok { + vv, err := notificationchannel.ValueScanner.Config.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(notificationchannel.FieldConfig, field.TypeString, vv) + } + if _u.mutation.RulesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: notificationchannel.RulesTable, + Columns: notificationchannel.RulesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationrule.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedRulesIDs(); len(nodes) > 0 && !_u.mutation.RulesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: notificationchannel.RulesTable, + Columns: notificationchannel.RulesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationrule.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.RulesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: notificationchannel.RulesTable, + Columns: notificationchannel.RulesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationrule.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{notificationchannel.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// NotificationChannelUpdateOne is the builder for updating a single NotificationChannel entity. +type NotificationChannelUpdateOne struct { + config + fields []string + hooks []Hook + mutation *NotificationChannelMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *NotificationChannelUpdateOne) SetUpdatedAt(v time.Time) *NotificationChannelUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *NotificationChannelUpdateOne) SetDeletedAt(v time.Time) *NotificationChannelUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *NotificationChannelUpdateOne) SetNillableDeletedAt(v *time.Time) *NotificationChannelUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *NotificationChannelUpdateOne) ClearDeletedAt() *NotificationChannelUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *NotificationChannelUpdateOne) SetAnnotations(v models.Annotations) *NotificationChannelUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *NotificationChannelUpdateOne) ClearAnnotations() *NotificationChannelUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *NotificationChannelUpdateOne) SetMetadata(v map[string]string) *NotificationChannelUpdateOne { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *NotificationChannelUpdateOne) ClearMetadata() *NotificationChannelUpdateOne { + _u.mutation.ClearMetadata() + return _u +} + +// SetName sets the "name" field. +func (_u *NotificationChannelUpdateOne) SetName(v string) *NotificationChannelUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *NotificationChannelUpdateOne) SetNillableName(v *string) *NotificationChannelUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDisabled sets the "disabled" field. +func (_u *NotificationChannelUpdateOne) SetDisabled(v bool) *NotificationChannelUpdateOne { + _u.mutation.SetDisabled(v) + return _u +} + +// SetNillableDisabled sets the "disabled" field if the given value is not nil. +func (_u *NotificationChannelUpdateOne) SetNillableDisabled(v *bool) *NotificationChannelUpdateOne { + if v != nil { + _u.SetDisabled(*v) + } + return _u +} + +// ClearDisabled clears the value of the "disabled" field. +func (_u *NotificationChannelUpdateOne) ClearDisabled() *NotificationChannelUpdateOne { + _u.mutation.ClearDisabled() + return _u +} + +// SetConfig sets the "config" field. +func (_u *NotificationChannelUpdateOne) SetConfig(v notification.ChannelConfig) *NotificationChannelUpdateOne { + _u.mutation.SetConfig(v) + return _u +} + +// SetNillableConfig sets the "config" field if the given value is not nil. +func (_u *NotificationChannelUpdateOne) SetNillableConfig(v *notification.ChannelConfig) *NotificationChannelUpdateOne { + if v != nil { + _u.SetConfig(*v) + } + return _u +} + +// AddRuleIDs adds the "rules" edge to the NotificationRule entity by IDs. +func (_u *NotificationChannelUpdateOne) AddRuleIDs(ids ...string) *NotificationChannelUpdateOne { + _u.mutation.AddRuleIDs(ids...) + return _u +} + +// AddRules adds the "rules" edges to the NotificationRule entity. +func (_u *NotificationChannelUpdateOne) AddRules(v ...*NotificationRule) *NotificationChannelUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddRuleIDs(ids...) +} + +// Mutation returns the NotificationChannelMutation object of the builder. +func (_u *NotificationChannelUpdateOne) Mutation() *NotificationChannelMutation { + return _u.mutation +} + +// ClearRules clears all "rules" edges to the NotificationRule entity. +func (_u *NotificationChannelUpdateOne) ClearRules() *NotificationChannelUpdateOne { + _u.mutation.ClearRules() + return _u +} + +// RemoveRuleIDs removes the "rules" edge to NotificationRule entities by IDs. +func (_u *NotificationChannelUpdateOne) RemoveRuleIDs(ids ...string) *NotificationChannelUpdateOne { + _u.mutation.RemoveRuleIDs(ids...) + return _u +} + +// RemoveRules removes "rules" edges to NotificationRule entities. +func (_u *NotificationChannelUpdateOne) RemoveRules(v ...*NotificationRule) *NotificationChannelUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveRuleIDs(ids...) +} + +// Where appends a list predicates to the NotificationChannelUpdate builder. +func (_u *NotificationChannelUpdateOne) Where(ps ...predicate.NotificationChannel) *NotificationChannelUpdateOne { + _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 *NotificationChannelUpdateOne) Select(field string, fields ...string) *NotificationChannelUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated NotificationChannel entity. +func (_u *NotificationChannelUpdateOne) Save(ctx context.Context) (*NotificationChannel, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *NotificationChannelUpdateOne) SaveX(ctx context.Context) *NotificationChannel { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *NotificationChannelUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *NotificationChannelUpdateOne) 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 *NotificationChannelUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := notificationchannel.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *NotificationChannelUpdateOne) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := notificationchannel.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "NotificationChannel.name": %w`, err)} + } + } + if v, ok := _u.mutation.Config(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "config", err: fmt.Errorf(`db: validator failed for field "NotificationChannel.config": %w`, err)} + } + } + return nil +} + +func (_u *NotificationChannelUpdateOne) sqlSave(ctx context.Context) (_node *NotificationChannel, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(notificationchannel.Table, notificationchannel.Columns, sqlgraph.NewFieldSpec(notificationchannel.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "NotificationChannel.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, notificationchannel.FieldID) + for _, f := range fields { + if !notificationchannel.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != notificationchannel.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(notificationchannel.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(notificationchannel.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(notificationchannel.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(notificationchannel.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(notificationchannel.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(notificationchannel.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(notificationchannel.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(notificationchannel.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Disabled(); ok { + _spec.SetField(notificationchannel.FieldDisabled, field.TypeBool, value) + } + if _u.mutation.DisabledCleared() { + _spec.ClearField(notificationchannel.FieldDisabled, field.TypeBool) + } + if value, ok := _u.mutation.Config(); ok { + vv, err := notificationchannel.ValueScanner.Config.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(notificationchannel.FieldConfig, field.TypeString, vv) + } + if _u.mutation.RulesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: notificationchannel.RulesTable, + Columns: notificationchannel.RulesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationrule.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedRulesIDs(); len(nodes) > 0 && !_u.mutation.RulesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: notificationchannel.RulesTable, + Columns: notificationchannel.RulesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationrule.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.RulesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: notificationchannel.RulesTable, + Columns: notificationchannel.RulesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationrule.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &NotificationChannel{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{notificationchannel.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/ent/db/notificationevent.go b/ent/db/notificationevent.go new file mode 100644 index 0000000000000000000000000000000000000000..e5d46e50fe8f8052e340d94ad64c77b6c7072fa5 --- /dev/null +++ b/ent/db/notificationevent.go @@ -0,0 +1,211 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/notificationevent" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationrule" + "github.com/openmeterio/openmeter/openmeter/notification" + "github.com/openmeterio/openmeter/pkg/models" +) + +// NotificationEvent is the model entity for the NotificationEvent schema. +type NotificationEvent 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"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // The event type the rule associated with + Type notification.EventType `json:"type,omitempty"` + // RuleID holds the value of the "rule_id" field. + RuleID string `json:"rule_id,omitempty"` + // Payload holds the value of the "payload" field. + Payload string `json:"payload,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the NotificationEventQuery when eager-loading is set. + Edges NotificationEventEdges `json:"edges"` + selectValues sql.SelectValues +} + +// NotificationEventEdges holds the relations/edges for other nodes in the graph. +type NotificationEventEdges struct { + // DeliveryStatuses holds the value of the delivery_statuses edge. + DeliveryStatuses []*NotificationEventDeliveryStatus `json:"delivery_statuses,omitempty"` + // Rules holds the value of the rules edge. + Rules *NotificationRule `json:"rules,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// DeliveryStatusesOrErr returns the DeliveryStatuses value or an error if the edge +// was not loaded in eager-loading. +func (e NotificationEventEdges) DeliveryStatusesOrErr() ([]*NotificationEventDeliveryStatus, error) { + if e.loadedTypes[0] { + return e.DeliveryStatuses, nil + } + return nil, &NotLoadedError{edge: "delivery_statuses"} +} + +// RulesOrErr returns the Rules value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e NotificationEventEdges) RulesOrErr() (*NotificationRule, error) { + if e.Rules != nil { + return e.Rules, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: notificationrule.Label} + } + return nil, &NotLoadedError{edge: "rules"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*NotificationEvent) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case notificationevent.FieldAnnotations: + values[i] = new([]byte) + case notificationevent.FieldID, notificationevent.FieldNamespace, notificationevent.FieldType, notificationevent.FieldRuleID, notificationevent.FieldPayload: + values[i] = new(sql.NullString) + case notificationevent.FieldCreatedAt: + 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 NotificationEvent fields. +func (_m *NotificationEvent) 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 notificationevent.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 notificationevent.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 notificationevent.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 notificationevent.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 notificationevent.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 = notification.EventType(value.String) + } + case notificationevent.FieldRuleID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field rule_id", values[i]) + } else if value.Valid { + _m.RuleID = value.String + } + case notificationevent.FieldPayload: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field payload", values[i]) + } else if value.Valid { + _m.Payload = 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 NotificationEvent. +// This includes values selected through modifiers, order, etc. +func (_m *NotificationEvent) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryDeliveryStatuses queries the "delivery_statuses" edge of the NotificationEvent entity. +func (_m *NotificationEvent) QueryDeliveryStatuses() *NotificationEventDeliveryStatusQuery { + return NewNotificationEventClient(_m.config).QueryDeliveryStatuses(_m) +} + +// QueryRules queries the "rules" edge of the NotificationEvent entity. +func (_m *NotificationEvent) QueryRules() *NotificationRuleQuery { + return NewNotificationEventClient(_m.config).QueryRules(_m) +} + +// Update returns a builder for updating this NotificationEvent. +// Note that you need to call NotificationEvent.Unwrap() before calling this method if this NotificationEvent +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *NotificationEvent) Update() *NotificationEventUpdateOne { + return NewNotificationEventClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the NotificationEvent 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 *NotificationEvent) Unwrap() *NotificationEvent { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: NotificationEvent is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *NotificationEvent) String() string { + var builder strings.Builder + builder.WriteString("NotificationEvent(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("type=") + builder.WriteString(fmt.Sprintf("%v", _m.Type)) + builder.WriteString(", ") + builder.WriteString("rule_id=") + builder.WriteString(_m.RuleID) + builder.WriteString(", ") + builder.WriteString("payload=") + builder.WriteString(_m.Payload) + builder.WriteByte(')') + return builder.String() +} + +// NotificationEvents is a parsable slice of NotificationEvent. +type NotificationEvents []*NotificationEvent diff --git a/ent/db/notificationevent/notificationevent.go b/ent/db/notificationevent/notificationevent.go new file mode 100644 index 0000000000000000000000000000000000000000..87edecb5d48c8bcf73af9d364171da09c68a8cf4 --- /dev/null +++ b/ent/db/notificationevent/notificationevent.go @@ -0,0 +1,163 @@ +// Code generated by ent, DO NOT EDIT. + +package notificationevent + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/notification" +) + +const ( + // Label holds the string label denoting the notificationevent type in the database. + Label = "notification_event" + // 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" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldType holds the string denoting the type field in the database. + FieldType = "type" + // FieldRuleID holds the string denoting the rule_id field in the database. + FieldRuleID = "rule_id" + // FieldPayload holds the string denoting the payload field in the database. + FieldPayload = "payload" + // EdgeDeliveryStatuses holds the string denoting the delivery_statuses edge name in mutations. + EdgeDeliveryStatuses = "delivery_statuses" + // EdgeRules holds the string denoting the rules edge name in mutations. + EdgeRules = "rules" + // Table holds the table name of the notificationevent in the database. + Table = "notification_events" + // DeliveryStatusesTable is the table that holds the delivery_statuses relation/edge. The primary key declared below. + DeliveryStatusesTable = "notification_event_delivery_status_events" + // DeliveryStatusesInverseTable is the table name for the NotificationEventDeliveryStatus entity. + // It exists in this package in order to avoid circular dependency with the "notificationeventdeliverystatus" package. + DeliveryStatusesInverseTable = "notification_event_delivery_status" + // RulesTable is the table that holds the rules relation/edge. + RulesTable = "notification_events" + // RulesInverseTable is the table name for the NotificationRule entity. + // It exists in this package in order to avoid circular dependency with the "notificationrule" package. + RulesInverseTable = "notification_rules" + // RulesColumn is the table column denoting the rules relation/edge. + RulesColumn = "rule_id" +) + +// Columns holds all SQL columns for notificationevent fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldAnnotations, + FieldCreatedAt, + FieldType, + FieldRuleID, + FieldPayload, +} + +var ( + // DeliveryStatusesPrimaryKey and DeliveryStatusesColumn2 are the table columns denoting the + // primary key for the delivery_statuses relation (M2M). + DeliveryStatusesPrimaryKey = []string{"notification_event_delivery_status_id", "notification_event_id"} +) + +// 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 + // 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 notification.EventType) error { + switch _type.String() { + case "entitlements.balance.threshold", "entitlements.reset", "invoice.created", "invoice.updated": + return nil + default: + return fmt.Errorf("notificationevent: invalid enum value for type field: %q", _type) + } +} + +// OrderOption defines the ordering options for the NotificationEvent 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() +} + +// ByType orders the results by the type field. +func ByType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldType, opts...).ToFunc() +} + +// ByRuleID orders the results by the rule_id field. +func ByRuleID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRuleID, opts...).ToFunc() +} + +// ByPayload orders the results by the payload field. +func ByPayload(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPayload, opts...).ToFunc() +} + +// ByDeliveryStatusesCount orders the results by delivery_statuses count. +func ByDeliveryStatusesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newDeliveryStatusesStep(), opts...) + } +} + +// ByDeliveryStatuses orders the results by delivery_statuses terms. +func ByDeliveryStatuses(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newDeliveryStatusesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByRulesField orders the results by rules field. +func ByRulesField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newRulesStep(), sql.OrderByField(field, opts...)) + } +} +func newDeliveryStatusesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(DeliveryStatusesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, DeliveryStatusesTable, DeliveryStatusesPrimaryKey...), + ) +} +func newRulesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RulesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, RulesTable, RulesColumn), + ) +} diff --git a/ent/db/notificationevent/where.go b/ent/db/notificationevent/where.go new file mode 100644 index 0000000000000000000000000000000000000000..f5797ee3daeea508d01e5bf9b8dc097bde682089 --- /dev/null +++ b/ent/db/notificationevent/where.go @@ -0,0 +1,423 @@ +// Code generated by ent, DO NOT EDIT. + +package notificationevent + +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/notification" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(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.NotificationEvent { + return predicate.NotificationEvent(sql.FieldEQ(FieldCreatedAt, v)) +} + +// RuleID applies equality check predicate on the "rule_id" field. It's identical to RuleIDEQ. +func RuleID(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldEQ(FieldRuleID, v)) +} + +// Payload applies equality check predicate on the "payload" field. It's identical to PayloadEQ. +func Payload(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldEQ(FieldPayload, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldContainsFold(FieldNamespace, v)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldNotNull(FieldAnnotations)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldLTE(FieldCreatedAt, v)) +} + +// TypeEQ applies the EQ predicate on the "type" field. +func TypeEQ(v notification.EventType) predicate.NotificationEvent { + vc := v + return predicate.NotificationEvent(sql.FieldEQ(FieldType, vc)) +} + +// TypeNEQ applies the NEQ predicate on the "type" field. +func TypeNEQ(v notification.EventType) predicate.NotificationEvent { + vc := v + return predicate.NotificationEvent(sql.FieldNEQ(FieldType, vc)) +} + +// TypeIn applies the In predicate on the "type" field. +func TypeIn(vs ...notification.EventType) predicate.NotificationEvent { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.NotificationEvent(sql.FieldIn(FieldType, v...)) +} + +// TypeNotIn applies the NotIn predicate on the "type" field. +func TypeNotIn(vs ...notification.EventType) predicate.NotificationEvent { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.NotificationEvent(sql.FieldNotIn(FieldType, v...)) +} + +// RuleIDEQ applies the EQ predicate on the "rule_id" field. +func RuleIDEQ(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldEQ(FieldRuleID, v)) +} + +// RuleIDNEQ applies the NEQ predicate on the "rule_id" field. +func RuleIDNEQ(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldNEQ(FieldRuleID, v)) +} + +// RuleIDIn applies the In predicate on the "rule_id" field. +func RuleIDIn(vs ...string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldIn(FieldRuleID, vs...)) +} + +// RuleIDNotIn applies the NotIn predicate on the "rule_id" field. +func RuleIDNotIn(vs ...string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldNotIn(FieldRuleID, vs...)) +} + +// RuleIDGT applies the GT predicate on the "rule_id" field. +func RuleIDGT(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldGT(FieldRuleID, v)) +} + +// RuleIDGTE applies the GTE predicate on the "rule_id" field. +func RuleIDGTE(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldGTE(FieldRuleID, v)) +} + +// RuleIDLT applies the LT predicate on the "rule_id" field. +func RuleIDLT(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldLT(FieldRuleID, v)) +} + +// RuleIDLTE applies the LTE predicate on the "rule_id" field. +func RuleIDLTE(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldLTE(FieldRuleID, v)) +} + +// RuleIDContains applies the Contains predicate on the "rule_id" field. +func RuleIDContains(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldContains(FieldRuleID, v)) +} + +// RuleIDHasPrefix applies the HasPrefix predicate on the "rule_id" field. +func RuleIDHasPrefix(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldHasPrefix(FieldRuleID, v)) +} + +// RuleIDHasSuffix applies the HasSuffix predicate on the "rule_id" field. +func RuleIDHasSuffix(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldHasSuffix(FieldRuleID, v)) +} + +// RuleIDEqualFold applies the EqualFold predicate on the "rule_id" field. +func RuleIDEqualFold(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldEqualFold(FieldRuleID, v)) +} + +// RuleIDContainsFold applies the ContainsFold predicate on the "rule_id" field. +func RuleIDContainsFold(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldContainsFold(FieldRuleID, v)) +} + +// PayloadEQ applies the EQ predicate on the "payload" field. +func PayloadEQ(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldEQ(FieldPayload, v)) +} + +// PayloadNEQ applies the NEQ predicate on the "payload" field. +func PayloadNEQ(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldNEQ(FieldPayload, v)) +} + +// PayloadIn applies the In predicate on the "payload" field. +func PayloadIn(vs ...string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldIn(FieldPayload, vs...)) +} + +// PayloadNotIn applies the NotIn predicate on the "payload" field. +func PayloadNotIn(vs ...string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldNotIn(FieldPayload, vs...)) +} + +// PayloadGT applies the GT predicate on the "payload" field. +func PayloadGT(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldGT(FieldPayload, v)) +} + +// PayloadGTE applies the GTE predicate on the "payload" field. +func PayloadGTE(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldGTE(FieldPayload, v)) +} + +// PayloadLT applies the LT predicate on the "payload" field. +func PayloadLT(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldLT(FieldPayload, v)) +} + +// PayloadLTE applies the LTE predicate on the "payload" field. +func PayloadLTE(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldLTE(FieldPayload, v)) +} + +// PayloadContains applies the Contains predicate on the "payload" field. +func PayloadContains(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldContains(FieldPayload, v)) +} + +// PayloadHasPrefix applies the HasPrefix predicate on the "payload" field. +func PayloadHasPrefix(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldHasPrefix(FieldPayload, v)) +} + +// PayloadHasSuffix applies the HasSuffix predicate on the "payload" field. +func PayloadHasSuffix(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldHasSuffix(FieldPayload, v)) +} + +// PayloadEqualFold applies the EqualFold predicate on the "payload" field. +func PayloadEqualFold(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldEqualFold(FieldPayload, v)) +} + +// PayloadContainsFold applies the ContainsFold predicate on the "payload" field. +func PayloadContainsFold(v string) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.FieldContainsFold(FieldPayload, v)) +} + +// HasDeliveryStatuses applies the HasEdge predicate on the "delivery_statuses" edge. +func HasDeliveryStatuses() predicate.NotificationEvent { + return predicate.NotificationEvent(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, DeliveryStatusesTable, DeliveryStatusesPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasDeliveryStatusesWith applies the HasEdge predicate on the "delivery_statuses" edge with a given conditions (other predicates). +func HasDeliveryStatusesWith(preds ...predicate.NotificationEventDeliveryStatus) predicate.NotificationEvent { + return predicate.NotificationEvent(func(s *sql.Selector) { + step := newDeliveryStatusesStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasRules applies the HasEdge predicate on the "rules" edge. +func HasRules() predicate.NotificationEvent { + return predicate.NotificationEvent(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, RulesTable, RulesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasRulesWith applies the HasEdge predicate on the "rules" edge with a given conditions (other predicates). +func HasRulesWith(preds ...predicate.NotificationRule) predicate.NotificationEvent { + return predicate.NotificationEvent(func(s *sql.Selector) { + step := newRulesStep() + 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.NotificationEvent) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.NotificationEvent) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.NotificationEvent) predicate.NotificationEvent { + return predicate.NotificationEvent(sql.NotPredicates(p)) +} diff --git a/ent/db/notificationevent_create.go b/ent/db/notificationevent_create.go new file mode 100644 index 0000000000000000000000000000000000000000..bd2fc88d011ea3663b9235e92658ab936a4ed801 --- /dev/null +++ b/ent/db/notificationevent_create.go @@ -0,0 +1,738 @@ +// 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/notificationevent" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationeventdeliverystatus" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationrule" + "github.com/openmeterio/openmeter/openmeter/notification" + "github.com/openmeterio/openmeter/pkg/models" +) + +// NotificationEventCreate is the builder for creating a NotificationEvent entity. +type NotificationEventCreate struct { + config + mutation *NotificationEventMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *NotificationEventCreate) SetNamespace(v string) *NotificationEventCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *NotificationEventCreate) SetAnnotations(v models.Annotations) *NotificationEventCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *NotificationEventCreate) SetCreatedAt(v time.Time) *NotificationEventCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *NotificationEventCreate) SetNillableCreatedAt(v *time.Time) *NotificationEventCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetType sets the "type" field. +func (_c *NotificationEventCreate) SetType(v notification.EventType) *NotificationEventCreate { + _c.mutation.SetType(v) + return _c +} + +// SetRuleID sets the "rule_id" field. +func (_c *NotificationEventCreate) SetRuleID(v string) *NotificationEventCreate { + _c.mutation.SetRuleID(v) + return _c +} + +// SetPayload sets the "payload" field. +func (_c *NotificationEventCreate) SetPayload(v string) *NotificationEventCreate { + _c.mutation.SetPayload(v) + return _c +} + +// SetID sets the "id" field. +func (_c *NotificationEventCreate) SetID(v string) *NotificationEventCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *NotificationEventCreate) SetNillableID(v *string) *NotificationEventCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// AddDeliveryStatusIDs adds the "delivery_statuses" edge to the NotificationEventDeliveryStatus entity by IDs. +func (_c *NotificationEventCreate) AddDeliveryStatusIDs(ids ...string) *NotificationEventCreate { + _c.mutation.AddDeliveryStatusIDs(ids...) + return _c +} + +// AddDeliveryStatuses adds the "delivery_statuses" edges to the NotificationEventDeliveryStatus entity. +func (_c *NotificationEventCreate) AddDeliveryStatuses(v ...*NotificationEventDeliveryStatus) *NotificationEventCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddDeliveryStatusIDs(ids...) +} + +// SetRulesID sets the "rules" edge to the NotificationRule entity by ID. +func (_c *NotificationEventCreate) SetRulesID(id string) *NotificationEventCreate { + _c.mutation.SetRulesID(id) + return _c +} + +// SetRules sets the "rules" edge to the NotificationRule entity. +func (_c *NotificationEventCreate) SetRules(v *NotificationRule) *NotificationEventCreate { + return _c.SetRulesID(v.ID) +} + +// Mutation returns the NotificationEventMutation object of the builder. +func (_c *NotificationEventCreate) Mutation() *NotificationEventMutation { + return _c.mutation +} + +// Save creates the NotificationEvent in the database. +func (_c *NotificationEventCreate) Save(ctx context.Context) (*NotificationEvent, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *NotificationEventCreate) SaveX(ctx context.Context) *NotificationEvent { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *NotificationEventCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *NotificationEventCreate) 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 *NotificationEventCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := notificationevent.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := notificationevent.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *NotificationEventCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "NotificationEvent.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := notificationevent.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "NotificationEvent.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "NotificationEvent.created_at"`)} + } + if _, ok := _c.mutation.GetType(); !ok { + return &ValidationError{Name: "type", err: errors.New(`db: missing required field "NotificationEvent.type"`)} + } + if v, ok := _c.mutation.GetType(); ok { + if err := notificationevent.TypeValidator(v); err != nil { + return &ValidationError{Name: "type", err: fmt.Errorf(`db: validator failed for field "NotificationEvent.type": %w`, err)} + } + } + if _, ok := _c.mutation.RuleID(); !ok { + return &ValidationError{Name: "rule_id", err: errors.New(`db: missing required field "NotificationEvent.rule_id"`)} + } + if _, ok := _c.mutation.Payload(); !ok { + return &ValidationError{Name: "payload", err: errors.New(`db: missing required field "NotificationEvent.payload"`)} + } + if len(_c.mutation.RulesIDs()) == 0 { + return &ValidationError{Name: "rules", err: errors.New(`db: missing required edge "NotificationEvent.rules"`)} + } + return nil +} + +func (_c *NotificationEventCreate) sqlSave(ctx context.Context) (*NotificationEvent, 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 NotificationEvent.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *NotificationEventCreate) createSpec() (*NotificationEvent, *sqlgraph.CreateSpec) { + var ( + _node = &NotificationEvent{config: _c.config} + _spec = sqlgraph.NewCreateSpec(notificationevent.Table, sqlgraph.NewFieldSpec(notificationevent.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(notificationevent.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(notificationevent.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(notificationevent.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.GetType(); ok { + _spec.SetField(notificationevent.FieldType, field.TypeEnum, value) + _node.Type = value + } + if value, ok := _c.mutation.Payload(); ok { + _spec.SetField(notificationevent.FieldPayload, field.TypeString, value) + _node.Payload = value + } + if nodes := _c.mutation.DeliveryStatusesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: notificationevent.DeliveryStatusesTable, + Columns: notificationevent.DeliveryStatusesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationeventdeliverystatus.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.RulesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: notificationevent.RulesTable, + Columns: []string{notificationevent.RulesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationrule.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.RuleID = 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.NotificationEvent.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.NotificationEventUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *NotificationEventCreate) OnConflict(opts ...sql.ConflictOption) *NotificationEventUpsertOne { + _c.conflict = opts + return &NotificationEventUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.NotificationEvent.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *NotificationEventCreate) OnConflictColumns(columns ...string) *NotificationEventUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &NotificationEventUpsertOne{ + create: _c, + } +} + +type ( + // NotificationEventUpsertOne is the builder for "upsert"-ing + // one NotificationEvent node. + NotificationEventUpsertOne struct { + create *NotificationEventCreate + } + + // NotificationEventUpsert is the "OnConflict" setter. + NotificationEventUpsert struct { + *sql.UpdateSet + } +) + +// SetAnnotations sets the "annotations" field. +func (u *NotificationEventUpsert) SetAnnotations(v models.Annotations) *NotificationEventUpsert { + u.Set(notificationevent.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *NotificationEventUpsert) UpdateAnnotations() *NotificationEventUpsert { + u.SetExcluded(notificationevent.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *NotificationEventUpsert) ClearAnnotations() *NotificationEventUpsert { + u.SetNull(notificationevent.FieldAnnotations) + return u +} + +// SetPayload sets the "payload" field. +func (u *NotificationEventUpsert) SetPayload(v string) *NotificationEventUpsert { + u.Set(notificationevent.FieldPayload, v) + return u +} + +// UpdatePayload sets the "payload" field to the value that was provided on create. +func (u *NotificationEventUpsert) UpdatePayload() *NotificationEventUpsert { + u.SetExcluded(notificationevent.FieldPayload) + 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.NotificationEvent.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(notificationevent.FieldID) +// }), +// ). +// Exec(ctx) +func (u *NotificationEventUpsertOne) UpdateNewValues() *NotificationEventUpsertOne { + 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(notificationevent.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(notificationevent.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(notificationevent.FieldCreatedAt) + } + if _, exists := u.create.mutation.GetType(); exists { + s.SetIgnore(notificationevent.FieldType) + } + if _, exists := u.create.mutation.RuleID(); exists { + s.SetIgnore(notificationevent.FieldRuleID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.NotificationEvent.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *NotificationEventUpsertOne) Ignore() *NotificationEventUpsertOne { + 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 *NotificationEventUpsertOne) DoNothing() *NotificationEventUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the NotificationEventCreate.OnConflict +// documentation for more info. +func (u *NotificationEventUpsertOne) Update(set func(*NotificationEventUpsert)) *NotificationEventUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&NotificationEventUpsert{UpdateSet: update}) + })) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *NotificationEventUpsertOne) SetAnnotations(v models.Annotations) *NotificationEventUpsertOne { + return u.Update(func(s *NotificationEventUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *NotificationEventUpsertOne) UpdateAnnotations() *NotificationEventUpsertOne { + return u.Update(func(s *NotificationEventUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *NotificationEventUpsertOne) ClearAnnotations() *NotificationEventUpsertOne { + return u.Update(func(s *NotificationEventUpsert) { + s.ClearAnnotations() + }) +} + +// SetPayload sets the "payload" field. +func (u *NotificationEventUpsertOne) SetPayload(v string) *NotificationEventUpsertOne { + return u.Update(func(s *NotificationEventUpsert) { + s.SetPayload(v) + }) +} + +// UpdatePayload sets the "payload" field to the value that was provided on create. +func (u *NotificationEventUpsertOne) UpdatePayload() *NotificationEventUpsertOne { + return u.Update(func(s *NotificationEventUpsert) { + s.UpdatePayload() + }) +} + +// Exec executes the query. +func (u *NotificationEventUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for NotificationEventCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *NotificationEventUpsertOne) 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 *NotificationEventUpsertOne) 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: NotificationEventUpsertOne.ID is not supported by MySQL driver. Use NotificationEventUpsertOne.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 *NotificationEventUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// NotificationEventCreateBulk is the builder for creating many NotificationEvent entities in bulk. +type NotificationEventCreateBulk struct { + config + err error + builders []*NotificationEventCreate + conflict []sql.ConflictOption +} + +// Save creates the NotificationEvent entities in the database. +func (_c *NotificationEventCreateBulk) Save(ctx context.Context) ([]*NotificationEvent, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*NotificationEvent, 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.(*NotificationEventMutation) + 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 *NotificationEventCreateBulk) SaveX(ctx context.Context) []*NotificationEvent { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *NotificationEventCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *NotificationEventCreateBulk) 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.NotificationEvent.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.NotificationEventUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *NotificationEventCreateBulk) OnConflict(opts ...sql.ConflictOption) *NotificationEventUpsertBulk { + _c.conflict = opts + return &NotificationEventUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.NotificationEvent.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *NotificationEventCreateBulk) OnConflictColumns(columns ...string) *NotificationEventUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &NotificationEventUpsertBulk{ + create: _c, + } +} + +// NotificationEventUpsertBulk is the builder for "upsert"-ing +// a bulk of NotificationEvent nodes. +type NotificationEventUpsertBulk struct { + create *NotificationEventCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.NotificationEvent.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(notificationevent.FieldID) +// }), +// ). +// Exec(ctx) +func (u *NotificationEventUpsertBulk) UpdateNewValues() *NotificationEventUpsertBulk { + 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(notificationevent.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(notificationevent.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(notificationevent.FieldCreatedAt) + } + if _, exists := b.mutation.GetType(); exists { + s.SetIgnore(notificationevent.FieldType) + } + if _, exists := b.mutation.RuleID(); exists { + s.SetIgnore(notificationevent.FieldRuleID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.NotificationEvent.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *NotificationEventUpsertBulk) Ignore() *NotificationEventUpsertBulk { + 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 *NotificationEventUpsertBulk) DoNothing() *NotificationEventUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the NotificationEventCreateBulk.OnConflict +// documentation for more info. +func (u *NotificationEventUpsertBulk) Update(set func(*NotificationEventUpsert)) *NotificationEventUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&NotificationEventUpsert{UpdateSet: update}) + })) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *NotificationEventUpsertBulk) SetAnnotations(v models.Annotations) *NotificationEventUpsertBulk { + return u.Update(func(s *NotificationEventUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *NotificationEventUpsertBulk) UpdateAnnotations() *NotificationEventUpsertBulk { + return u.Update(func(s *NotificationEventUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *NotificationEventUpsertBulk) ClearAnnotations() *NotificationEventUpsertBulk { + return u.Update(func(s *NotificationEventUpsert) { + s.ClearAnnotations() + }) +} + +// SetPayload sets the "payload" field. +func (u *NotificationEventUpsertBulk) SetPayload(v string) *NotificationEventUpsertBulk { + return u.Update(func(s *NotificationEventUpsert) { + s.SetPayload(v) + }) +} + +// UpdatePayload sets the "payload" field to the value that was provided on create. +func (u *NotificationEventUpsertBulk) UpdatePayload() *NotificationEventUpsertBulk { + return u.Update(func(s *NotificationEventUpsert) { + s.UpdatePayload() + }) +} + +// Exec executes the query. +func (u *NotificationEventUpsertBulk) 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 NotificationEventCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for NotificationEventCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *NotificationEventUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/notificationevent_delete.go b/ent/db/notificationevent_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..96dda57b8d7d1ee901b219fa831e6d451fc24570 --- /dev/null +++ b/ent/db/notificationevent_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/notificationevent" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// NotificationEventDelete is the builder for deleting a NotificationEvent entity. +type NotificationEventDelete struct { + config + hooks []Hook + mutation *NotificationEventMutation +} + +// Where appends a list predicates to the NotificationEventDelete builder. +func (_d *NotificationEventDelete) Where(ps ...predicate.NotificationEvent) *NotificationEventDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *NotificationEventDelete) 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 *NotificationEventDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *NotificationEventDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(notificationevent.Table, sqlgraph.NewFieldSpec(notificationevent.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 +} + +// NotificationEventDeleteOne is the builder for deleting a single NotificationEvent entity. +type NotificationEventDeleteOne struct { + _d *NotificationEventDelete +} + +// Where appends a list predicates to the NotificationEventDelete builder. +func (_d *NotificationEventDeleteOne) Where(ps ...predicate.NotificationEvent) *NotificationEventDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *NotificationEventDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{notificationevent.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *NotificationEventDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/notificationevent_query.go b/ent/db/notificationevent_query.go new file mode 100644 index 0000000000000000000000000000000000000000..4e547c0bcb08c96d9ad7b109ed42017103dd3396 --- /dev/null +++ b/ent/db/notificationevent_query.go @@ -0,0 +1,751 @@ +// 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/notificationevent" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationeventdeliverystatus" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationrule" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// NotificationEventQuery is the builder for querying NotificationEvent entities. +type NotificationEventQuery struct { + config + ctx *QueryContext + order []notificationevent.OrderOption + inters []Interceptor + predicates []predicate.NotificationEvent + withDeliveryStatuses *NotificationEventDeliveryStatusQuery + withRules *NotificationRuleQuery + 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 NotificationEventQuery builder. +func (_q *NotificationEventQuery) Where(ps ...predicate.NotificationEvent) *NotificationEventQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *NotificationEventQuery) Limit(limit int) *NotificationEventQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *NotificationEventQuery) Offset(offset int) *NotificationEventQuery { + _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 *NotificationEventQuery) Unique(unique bool) *NotificationEventQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *NotificationEventQuery) Order(o ...notificationevent.OrderOption) *NotificationEventQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryDeliveryStatuses chains the current query on the "delivery_statuses" edge. +func (_q *NotificationEventQuery) QueryDeliveryStatuses() *NotificationEventDeliveryStatusQuery { + query := (&NotificationEventDeliveryStatusClient{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(notificationevent.Table, notificationevent.FieldID, selector), + sqlgraph.To(notificationeventdeliverystatus.Table, notificationeventdeliverystatus.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, notificationevent.DeliveryStatusesTable, notificationevent.DeliveryStatusesPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryRules chains the current query on the "rules" edge. +func (_q *NotificationEventQuery) QueryRules() *NotificationRuleQuery { + query := (&NotificationRuleClient{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(notificationevent.Table, notificationevent.FieldID, selector), + sqlgraph.To(notificationrule.Table, notificationrule.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, notificationevent.RulesTable, notificationevent.RulesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first NotificationEvent entity from the query. +// Returns a *NotFoundError when no NotificationEvent was found. +func (_q *NotificationEventQuery) First(ctx context.Context) (*NotificationEvent, 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{notificationevent.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *NotificationEventQuery) FirstX(ctx context.Context) *NotificationEvent { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first NotificationEvent ID from the query. +// Returns a *NotFoundError when no NotificationEvent ID was found. +func (_q *NotificationEventQuery) 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{notificationevent.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *NotificationEventQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single NotificationEvent entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one NotificationEvent entity is found. +// Returns a *NotFoundError when no NotificationEvent entities are found. +func (_q *NotificationEventQuery) Only(ctx context.Context) (*NotificationEvent, 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{notificationevent.Label} + default: + return nil, &NotSingularError{notificationevent.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *NotificationEventQuery) OnlyX(ctx context.Context) *NotificationEvent { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only NotificationEvent ID in the query. +// Returns a *NotSingularError when more than one NotificationEvent ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *NotificationEventQuery) 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{notificationevent.Label} + default: + err = &NotSingularError{notificationevent.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *NotificationEventQuery) 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 NotificationEvents. +func (_q *NotificationEventQuery) All(ctx context.Context) ([]*NotificationEvent, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*NotificationEvent, *NotificationEventQuery]() + return withInterceptors[[]*NotificationEvent](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *NotificationEventQuery) AllX(ctx context.Context) []*NotificationEvent { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of NotificationEvent IDs. +func (_q *NotificationEventQuery) 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(notificationevent.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *NotificationEventQuery) 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 *NotificationEventQuery) 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[*NotificationEventQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *NotificationEventQuery) 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 *NotificationEventQuery) 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 *NotificationEventQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the NotificationEventQuery 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 *NotificationEventQuery) Clone() *NotificationEventQuery { + if _q == nil { + return nil + } + return &NotificationEventQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]notificationevent.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.NotificationEvent{}, _q.predicates...), + withDeliveryStatuses: _q.withDeliveryStatuses.Clone(), + withRules: _q.withRules.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithDeliveryStatuses tells the query-builder to eager-load the nodes that are connected to +// the "delivery_statuses" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *NotificationEventQuery) WithDeliveryStatuses(opts ...func(*NotificationEventDeliveryStatusQuery)) *NotificationEventQuery { + query := (&NotificationEventDeliveryStatusClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withDeliveryStatuses = query + return _q +} + +// WithRules tells the query-builder to eager-load the nodes that are connected to +// the "rules" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *NotificationEventQuery) WithRules(opts ...func(*NotificationRuleQuery)) *NotificationEventQuery { + query := (&NotificationRuleClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withRules = 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.NotificationEvent.Query(). +// GroupBy(notificationevent.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *NotificationEventQuery) GroupBy(field string, fields ...string) *NotificationEventGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &NotificationEventGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = notificationevent.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.NotificationEvent.Query(). +// Select(notificationevent.FieldNamespace). +// Scan(ctx, &v) +func (_q *NotificationEventQuery) Select(fields ...string) *NotificationEventSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &NotificationEventSelect{NotificationEventQuery: _q} + sbuild.label = notificationevent.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a NotificationEventSelect configured with the given aggregations. +func (_q *NotificationEventQuery) Aggregate(fns ...AggregateFunc) *NotificationEventSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *NotificationEventQuery) 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 !notificationevent.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 *NotificationEventQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*NotificationEvent, error) { + var ( + nodes = []*NotificationEvent{} + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withDeliveryStatuses != nil, + _q.withRules != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*NotificationEvent).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &NotificationEvent{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.withDeliveryStatuses; query != nil { + if err := _q.loadDeliveryStatuses(ctx, query, nodes, + func(n *NotificationEvent) { n.Edges.DeliveryStatuses = []*NotificationEventDeliveryStatus{} }, + func(n *NotificationEvent, e *NotificationEventDeliveryStatus) { + n.Edges.DeliveryStatuses = append(n.Edges.DeliveryStatuses, e) + }); err != nil { + return nil, err + } + } + if query := _q.withRules; query != nil { + if err := _q.loadRules(ctx, query, nodes, nil, + func(n *NotificationEvent, e *NotificationRule) { n.Edges.Rules = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *NotificationEventQuery) loadDeliveryStatuses(ctx context.Context, query *NotificationEventDeliveryStatusQuery, nodes []*NotificationEvent, init func(*NotificationEvent), assign func(*NotificationEvent, *NotificationEventDeliveryStatus)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[string]*NotificationEvent) + nids := make(map[string]map[*NotificationEvent]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(notificationevent.DeliveryStatusesTable) + s.Join(joinT).On(s.C(notificationeventdeliverystatus.FieldID), joinT.C(notificationevent.DeliveryStatusesPrimaryKey[0])) + s.Where(sql.InValues(joinT.C(notificationevent.DeliveryStatusesPrimaryKey[1]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(notificationevent.DeliveryStatusesPrimaryKey[1])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + if err := query.prepareQuery(ctx); err != nil { + return err + } + qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]any, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]any{new(sql.NullString)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := values[0].(*sql.NullString).String + inValue := values[1].(*sql.NullString).String + if nids[inValue] == nil { + nids[inValue] = map[*NotificationEvent]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*NotificationEventDeliveryStatus](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "delivery_statuses" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} +func (_q *NotificationEventQuery) loadRules(ctx context.Context, query *NotificationRuleQuery, nodes []*NotificationEvent, init func(*NotificationEvent), assign func(*NotificationEvent, *NotificationRule)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*NotificationEvent) + for i := range nodes { + fk := nodes[i].RuleID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(notificationrule.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 "rule_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *NotificationEventQuery) 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 *NotificationEventQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(notificationevent.Table, notificationevent.Columns, sqlgraph.NewFieldSpec(notificationevent.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, notificationevent.FieldID) + for i := range fields { + if fields[i] != notificationevent.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withRules != nil { + _spec.Node.AddColumnOnce(notificationevent.FieldRuleID) + } + } + 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 *NotificationEventQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(notificationevent.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = notificationevent.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 *NotificationEventQuery) ForUpdate(opts ...sql.LockOption) *NotificationEventQuery { + 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 *NotificationEventQuery) ForShare(opts ...sql.LockOption) *NotificationEventQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// NotificationEventGroupBy is the group-by builder for NotificationEvent entities. +type NotificationEventGroupBy struct { + selector + build *NotificationEventQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *NotificationEventGroupBy) Aggregate(fns ...AggregateFunc) *NotificationEventGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *NotificationEventGroupBy) 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[*NotificationEventQuery, *NotificationEventGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *NotificationEventGroupBy) sqlScan(ctx context.Context, root *NotificationEventQuery, 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) +} + +// NotificationEventSelect is the builder for selecting fields of NotificationEvent entities. +type NotificationEventSelect struct { + *NotificationEventQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *NotificationEventSelect) Aggregate(fns ...AggregateFunc) *NotificationEventSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *NotificationEventSelect) 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[*NotificationEventQuery, *NotificationEventSelect](ctx, _s.NotificationEventQuery, _s, _s.inters, v) +} + +func (_s *NotificationEventSelect) sqlScan(ctx context.Context, root *NotificationEventQuery, 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/ent/db/notificationevent_update.go b/ent/db/notificationevent_update.go new file mode 100644 index 0000000000000000000000000000000000000000..57eb964f89536151f91a1b5b61427870e30691c3 --- /dev/null +++ b/ent/db/notificationevent_update.go @@ -0,0 +1,431 @@ +// 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/notificationevent" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationeventdeliverystatus" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/models" +) + +// NotificationEventUpdate is the builder for updating NotificationEvent entities. +type NotificationEventUpdate struct { + config + hooks []Hook + mutation *NotificationEventMutation +} + +// Where appends a list predicates to the NotificationEventUpdate builder. +func (_u *NotificationEventUpdate) Where(ps ...predicate.NotificationEvent) *NotificationEventUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *NotificationEventUpdate) SetAnnotations(v models.Annotations) *NotificationEventUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *NotificationEventUpdate) ClearAnnotations() *NotificationEventUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetPayload sets the "payload" field. +func (_u *NotificationEventUpdate) SetPayload(v string) *NotificationEventUpdate { + _u.mutation.SetPayload(v) + return _u +} + +// SetNillablePayload sets the "payload" field if the given value is not nil. +func (_u *NotificationEventUpdate) SetNillablePayload(v *string) *NotificationEventUpdate { + if v != nil { + _u.SetPayload(*v) + } + return _u +} + +// AddDeliveryStatusIDs adds the "delivery_statuses" edge to the NotificationEventDeliveryStatus entity by IDs. +func (_u *NotificationEventUpdate) AddDeliveryStatusIDs(ids ...string) *NotificationEventUpdate { + _u.mutation.AddDeliveryStatusIDs(ids...) + return _u +} + +// AddDeliveryStatuses adds the "delivery_statuses" edges to the NotificationEventDeliveryStatus entity. +func (_u *NotificationEventUpdate) AddDeliveryStatuses(v ...*NotificationEventDeliveryStatus) *NotificationEventUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddDeliveryStatusIDs(ids...) +} + +// Mutation returns the NotificationEventMutation object of the builder. +func (_u *NotificationEventUpdate) Mutation() *NotificationEventMutation { + return _u.mutation +} + +// ClearDeliveryStatuses clears all "delivery_statuses" edges to the NotificationEventDeliveryStatus entity. +func (_u *NotificationEventUpdate) ClearDeliveryStatuses() *NotificationEventUpdate { + _u.mutation.ClearDeliveryStatuses() + return _u +} + +// RemoveDeliveryStatusIDs removes the "delivery_statuses" edge to NotificationEventDeliveryStatus entities by IDs. +func (_u *NotificationEventUpdate) RemoveDeliveryStatusIDs(ids ...string) *NotificationEventUpdate { + _u.mutation.RemoveDeliveryStatusIDs(ids...) + return _u +} + +// RemoveDeliveryStatuses removes "delivery_statuses" edges to NotificationEventDeliveryStatus entities. +func (_u *NotificationEventUpdate) RemoveDeliveryStatuses(v ...*NotificationEventDeliveryStatus) *NotificationEventUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveDeliveryStatusIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *NotificationEventUpdate) 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 *NotificationEventUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *NotificationEventUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *NotificationEventUpdate) 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 *NotificationEventUpdate) check() error { + if _u.mutation.RulesCleared() && len(_u.mutation.RulesIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "NotificationEvent.rules"`) + } + return nil +} + +func (_u *NotificationEventUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(notificationevent.Table, notificationevent.Columns, sqlgraph.NewFieldSpec(notificationevent.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.Annotations(); ok { + _spec.SetField(notificationevent.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(notificationevent.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Payload(); ok { + _spec.SetField(notificationevent.FieldPayload, field.TypeString, value) + } + if _u.mutation.DeliveryStatusesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: notificationevent.DeliveryStatusesTable, + Columns: notificationevent.DeliveryStatusesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationeventdeliverystatus.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedDeliveryStatusesIDs(); len(nodes) > 0 && !_u.mutation.DeliveryStatusesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: notificationevent.DeliveryStatusesTable, + Columns: notificationevent.DeliveryStatusesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationeventdeliverystatus.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.DeliveryStatusesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: notificationevent.DeliveryStatusesTable, + Columns: notificationevent.DeliveryStatusesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationeventdeliverystatus.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{notificationevent.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// NotificationEventUpdateOne is the builder for updating a single NotificationEvent entity. +type NotificationEventUpdateOne struct { + config + fields []string + hooks []Hook + mutation *NotificationEventMutation +} + +// SetAnnotations sets the "annotations" field. +func (_u *NotificationEventUpdateOne) SetAnnotations(v models.Annotations) *NotificationEventUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *NotificationEventUpdateOne) ClearAnnotations() *NotificationEventUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetPayload sets the "payload" field. +func (_u *NotificationEventUpdateOne) SetPayload(v string) *NotificationEventUpdateOne { + _u.mutation.SetPayload(v) + return _u +} + +// SetNillablePayload sets the "payload" field if the given value is not nil. +func (_u *NotificationEventUpdateOne) SetNillablePayload(v *string) *NotificationEventUpdateOne { + if v != nil { + _u.SetPayload(*v) + } + return _u +} + +// AddDeliveryStatusIDs adds the "delivery_statuses" edge to the NotificationEventDeliveryStatus entity by IDs. +func (_u *NotificationEventUpdateOne) AddDeliveryStatusIDs(ids ...string) *NotificationEventUpdateOne { + _u.mutation.AddDeliveryStatusIDs(ids...) + return _u +} + +// AddDeliveryStatuses adds the "delivery_statuses" edges to the NotificationEventDeliveryStatus entity. +func (_u *NotificationEventUpdateOne) AddDeliveryStatuses(v ...*NotificationEventDeliveryStatus) *NotificationEventUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddDeliveryStatusIDs(ids...) +} + +// Mutation returns the NotificationEventMutation object of the builder. +func (_u *NotificationEventUpdateOne) Mutation() *NotificationEventMutation { + return _u.mutation +} + +// ClearDeliveryStatuses clears all "delivery_statuses" edges to the NotificationEventDeliveryStatus entity. +func (_u *NotificationEventUpdateOne) ClearDeliveryStatuses() *NotificationEventUpdateOne { + _u.mutation.ClearDeliveryStatuses() + return _u +} + +// RemoveDeliveryStatusIDs removes the "delivery_statuses" edge to NotificationEventDeliveryStatus entities by IDs. +func (_u *NotificationEventUpdateOne) RemoveDeliveryStatusIDs(ids ...string) *NotificationEventUpdateOne { + _u.mutation.RemoveDeliveryStatusIDs(ids...) + return _u +} + +// RemoveDeliveryStatuses removes "delivery_statuses" edges to NotificationEventDeliveryStatus entities. +func (_u *NotificationEventUpdateOne) RemoveDeliveryStatuses(v ...*NotificationEventDeliveryStatus) *NotificationEventUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveDeliveryStatusIDs(ids...) +} + +// Where appends a list predicates to the NotificationEventUpdate builder. +func (_u *NotificationEventUpdateOne) Where(ps ...predicate.NotificationEvent) *NotificationEventUpdateOne { + _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 *NotificationEventUpdateOne) Select(field string, fields ...string) *NotificationEventUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated NotificationEvent entity. +func (_u *NotificationEventUpdateOne) Save(ctx context.Context) (*NotificationEvent, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *NotificationEventUpdateOne) SaveX(ctx context.Context) *NotificationEvent { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *NotificationEventUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *NotificationEventUpdateOne) 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 *NotificationEventUpdateOne) check() error { + if _u.mutation.RulesCleared() && len(_u.mutation.RulesIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "NotificationEvent.rules"`) + } + return nil +} + +func (_u *NotificationEventUpdateOne) sqlSave(ctx context.Context) (_node *NotificationEvent, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(notificationevent.Table, notificationevent.Columns, sqlgraph.NewFieldSpec(notificationevent.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "NotificationEvent.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, notificationevent.FieldID) + for _, f := range fields { + if !notificationevent.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != notificationevent.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.Annotations(); ok { + _spec.SetField(notificationevent.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(notificationevent.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Payload(); ok { + _spec.SetField(notificationevent.FieldPayload, field.TypeString, value) + } + if _u.mutation.DeliveryStatusesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: notificationevent.DeliveryStatusesTable, + Columns: notificationevent.DeliveryStatusesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationeventdeliverystatus.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedDeliveryStatusesIDs(); len(nodes) > 0 && !_u.mutation.DeliveryStatusesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: notificationevent.DeliveryStatusesTable, + Columns: notificationevent.DeliveryStatusesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationeventdeliverystatus.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.DeliveryStatusesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: notificationevent.DeliveryStatusesTable, + Columns: notificationevent.DeliveryStatusesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationeventdeliverystatus.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &NotificationEvent{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{notificationevent.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/ent/db/notificationeventdeliverystatus.go b/ent/db/notificationeventdeliverystatus.go new file mode 100644 index 0000000000000000000000000000000000000000..63a057e48e025f6c91df9902dd80afb065b852a4 --- /dev/null +++ b/ent/db/notificationeventdeliverystatus.go @@ -0,0 +1,241 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/notificationeventdeliverystatus" + "github.com/openmeterio/openmeter/openmeter/notification" + "github.com/openmeterio/openmeter/pkg/models" +) + +// NotificationEventDeliveryStatus is the model entity for the NotificationEventDeliveryStatus schema. +type NotificationEventDeliveryStatus 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"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,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"` + // EventID holds the value of the "event_id" field. + EventID string `json:"event_id,omitempty"` + // ChannelID holds the value of the "channel_id" field. + ChannelID string `json:"channel_id,omitempty"` + // State holds the value of the "state" field. + State notification.EventDeliveryStatusState `json:"state,omitempty"` + // Reason holds the value of the "reason" field. + Reason string `json:"reason,omitempty"` + // NextAttemptAt holds the value of the "next_attempt_at" field. + NextAttemptAt *time.Time `json:"next_attempt_at,omitempty"` + // Attempts holds the value of the "attempts" field. + Attempts []notification.EventDeliveryAttempt `json:"attempts,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the NotificationEventDeliveryStatusQuery when eager-loading is set. + Edges NotificationEventDeliveryStatusEdges `json:"edges"` + selectValues sql.SelectValues +} + +// NotificationEventDeliveryStatusEdges holds the relations/edges for other nodes in the graph. +type NotificationEventDeliveryStatusEdges struct { + // Events holds the value of the events edge. + Events []*NotificationEvent `json:"events,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// EventsOrErr returns the Events value or an error if the edge +// was not loaded in eager-loading. +func (e NotificationEventDeliveryStatusEdges) EventsOrErr() ([]*NotificationEvent, error) { + if e.loadedTypes[0] { + return e.Events, nil + } + return nil, &NotLoadedError{edge: "events"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*NotificationEventDeliveryStatus) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case notificationeventdeliverystatus.FieldAnnotations, notificationeventdeliverystatus.FieldAttempts: + values[i] = new([]byte) + case notificationeventdeliverystatus.FieldID, notificationeventdeliverystatus.FieldNamespace, notificationeventdeliverystatus.FieldEventID, notificationeventdeliverystatus.FieldChannelID, notificationeventdeliverystatus.FieldState, notificationeventdeliverystatus.FieldReason: + values[i] = new(sql.NullString) + case notificationeventdeliverystatus.FieldCreatedAt, notificationeventdeliverystatus.FieldUpdatedAt, notificationeventdeliverystatus.FieldNextAttemptAt: + 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 NotificationEventDeliveryStatus fields. +func (_m *NotificationEventDeliveryStatus) 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 notificationeventdeliverystatus.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 notificationeventdeliverystatus.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 notificationeventdeliverystatus.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 notificationeventdeliverystatus.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 notificationeventdeliverystatus.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 notificationeventdeliverystatus.FieldEventID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field event_id", values[i]) + } else if value.Valid { + _m.EventID = value.String + } + case notificationeventdeliverystatus.FieldChannelID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field channel_id", values[i]) + } else if value.Valid { + _m.ChannelID = value.String + } + case notificationeventdeliverystatus.FieldState: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field state", values[i]) + } else if value.Valid { + _m.State = notification.EventDeliveryStatusState(value.String) + } + case notificationeventdeliverystatus.FieldReason: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field reason", values[i]) + } else if value.Valid { + _m.Reason = value.String + } + case notificationeventdeliverystatus.FieldNextAttemptAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field next_attempt_at", values[i]) + } else if value.Valid { + _m.NextAttemptAt = new(time.Time) + *_m.NextAttemptAt = value.Time + } + case notificationeventdeliverystatus.FieldAttempts: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field attempts", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Attempts); err != nil { + return fmt.Errorf("unmarshal field attempts: %w", err) + } + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the NotificationEventDeliveryStatus. +// This includes values selected through modifiers, order, etc. +func (_m *NotificationEventDeliveryStatus) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryEvents queries the "events" edge of the NotificationEventDeliveryStatus entity. +func (_m *NotificationEventDeliveryStatus) QueryEvents() *NotificationEventQuery { + return NewNotificationEventDeliveryStatusClient(_m.config).QueryEvents(_m) +} + +// Update returns a builder for updating this NotificationEventDeliveryStatus. +// Note that you need to call NotificationEventDeliveryStatus.Unwrap() before calling this method if this NotificationEventDeliveryStatus +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *NotificationEventDeliveryStatus) Update() *NotificationEventDeliveryStatusUpdateOne { + return NewNotificationEventDeliveryStatusClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the NotificationEventDeliveryStatus 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 *NotificationEventDeliveryStatus) Unwrap() *NotificationEventDeliveryStatus { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: NotificationEventDeliveryStatus is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *NotificationEventDeliveryStatus) String() string { + var builder strings.Builder + builder.WriteString("NotificationEventDeliveryStatus(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + 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(", ") + builder.WriteString("event_id=") + builder.WriteString(_m.EventID) + builder.WriteString(", ") + builder.WriteString("channel_id=") + builder.WriteString(_m.ChannelID) + builder.WriteString(", ") + builder.WriteString("state=") + builder.WriteString(fmt.Sprintf("%v", _m.State)) + builder.WriteString(", ") + builder.WriteString("reason=") + builder.WriteString(_m.Reason) + builder.WriteString(", ") + if v := _m.NextAttemptAt; v != nil { + builder.WriteString("next_attempt_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + builder.WriteString("attempts=") + builder.WriteString(fmt.Sprintf("%v", _m.Attempts)) + builder.WriteByte(')') + return builder.String() +} + +// NotificationEventDeliveryStatusSlice is a parsable slice of NotificationEventDeliveryStatus. +type NotificationEventDeliveryStatusSlice []*NotificationEventDeliveryStatus diff --git a/ent/db/notificationeventdeliverystatus/notificationeventdeliverystatus.go b/ent/db/notificationeventdeliverystatus/notificationeventdeliverystatus.go new file mode 100644 index 0000000000000000000000000000000000000000..9b7a18cbde93da631633690c97dc212a49962947 --- /dev/null +++ b/ent/db/notificationeventdeliverystatus/notificationeventdeliverystatus.go @@ -0,0 +1,177 @@ +// Code generated by ent, DO NOT EDIT. + +package notificationeventdeliverystatus + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/notification" +) + +const ( + // Label holds the string label denoting the notificationeventdeliverystatus type in the database. + Label = "notification_event_delivery_status" + // 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" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // 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" + // FieldEventID holds the string denoting the event_id field in the database. + FieldEventID = "event_id" + // FieldChannelID holds the string denoting the channel_id field in the database. + FieldChannelID = "channel_id" + // FieldState holds the string denoting the state field in the database. + FieldState = "state" + // FieldReason holds the string denoting the reason field in the database. + FieldReason = "reason" + // FieldNextAttemptAt holds the string denoting the next_attempt_at field in the database. + FieldNextAttemptAt = "next_attempt_at" + // FieldAttempts holds the string denoting the attempts field in the database. + FieldAttempts = "attempts" + // EdgeEvents holds the string denoting the events edge name in mutations. + EdgeEvents = "events" + // Table holds the table name of the notificationeventdeliverystatus in the database. + Table = "notification_event_delivery_status" + // EventsTable is the table that holds the events relation/edge. The primary key declared below. + EventsTable = "notification_event_delivery_status_events" + // EventsInverseTable is the table name for the NotificationEvent entity. + // It exists in this package in order to avoid circular dependency with the "notificationevent" package. + EventsInverseTable = "notification_events" +) + +// Columns holds all SQL columns for notificationeventdeliverystatus fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldAnnotations, + FieldCreatedAt, + FieldUpdatedAt, + FieldEventID, + FieldChannelID, + FieldState, + FieldReason, + FieldNextAttemptAt, + FieldAttempts, +} + +var ( + // EventsPrimaryKey and EventsColumn2 are the table columns denoting the + // primary key for the events relation (M2M). + EventsPrimaryKey = []string{"notification_event_delivery_status_id", "notification_event_id"} +) + +// 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 + // EventIDValidator is a validator for the "event_id" field. It is called by the builders before save. + EventIDValidator func(string) error + // ChannelIDValidator is a validator for the "channel_id" field. It is called by the builders before save. + ChannelIDValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +const DefaultState notification.EventDeliveryStatusState = "PENDING" + +// StateValidator is a validator for the "state" field enum values. It is called by the builders before save. +func StateValidator(s notification.EventDeliveryStatusState) error { + switch s.String() { + case "SUCCESS", "FAILED", "SENDING", "PENDING", "RESENDING": + return nil + default: + return fmt.Errorf("notificationeventdeliverystatus: invalid enum value for state field: %q", s) + } +} + +// OrderOption defines the ordering options for the NotificationEventDeliveryStatus 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() +} + +// ByEventID orders the results by the event_id field. +func ByEventID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEventID, opts...).ToFunc() +} + +// ByChannelID orders the results by the channel_id field. +func ByChannelID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChannelID, opts...).ToFunc() +} + +// ByState orders the results by the state field. +func ByState(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldState, opts...).ToFunc() +} + +// ByReason orders the results by the reason field. +func ByReason(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldReason, opts...).ToFunc() +} + +// ByNextAttemptAt orders the results by the next_attempt_at field. +func ByNextAttemptAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldNextAttemptAt, opts...).ToFunc() +} + +// ByEventsCount orders the results by events count. +func ByEventsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newEventsStep(), opts...) + } +} + +// ByEvents orders the results by events terms. +func ByEvents(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newEventsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newEventsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(EventsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, EventsTable, EventsPrimaryKey...), + ) +} diff --git a/ent/db/notificationeventdeliverystatus/where.go b/ent/db/notificationeventdeliverystatus/where.go new file mode 100644 index 0000000000000000000000000000000000000000..7a64fb8c6cd66f768b82efd00cb31e8c23d9baf1 --- /dev/null +++ b/ent/db/notificationeventdeliverystatus/where.go @@ -0,0 +1,590 @@ +// Code generated by ent, DO NOT EDIT. + +package notificationeventdeliverystatus + +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/notification" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(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.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(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.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// EventID applies equality check predicate on the "event_id" field. It's identical to EventIDEQ. +func EventID(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldEQ(FieldEventID, v)) +} + +// ChannelID applies equality check predicate on the "channel_id" field. It's identical to ChannelIDEQ. +func ChannelID(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldEQ(FieldChannelID, v)) +} + +// Reason applies equality check predicate on the "reason" field. It's identical to ReasonEQ. +func Reason(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldEQ(FieldReason, v)) +} + +// NextAttemptAt applies equality check predicate on the "next_attempt_at" field. It's identical to NextAttemptAtEQ. +func NextAttemptAt(v time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldEQ(FieldNextAttemptAt, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldContainsFold(FieldNamespace, v)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldNotNull(FieldAnnotations)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// EventIDEQ applies the EQ predicate on the "event_id" field. +func EventIDEQ(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldEQ(FieldEventID, v)) +} + +// EventIDNEQ applies the NEQ predicate on the "event_id" field. +func EventIDNEQ(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldNEQ(FieldEventID, v)) +} + +// EventIDIn applies the In predicate on the "event_id" field. +func EventIDIn(vs ...string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldIn(FieldEventID, vs...)) +} + +// EventIDNotIn applies the NotIn predicate on the "event_id" field. +func EventIDNotIn(vs ...string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldNotIn(FieldEventID, vs...)) +} + +// EventIDGT applies the GT predicate on the "event_id" field. +func EventIDGT(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldGT(FieldEventID, v)) +} + +// EventIDGTE applies the GTE predicate on the "event_id" field. +func EventIDGTE(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldGTE(FieldEventID, v)) +} + +// EventIDLT applies the LT predicate on the "event_id" field. +func EventIDLT(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldLT(FieldEventID, v)) +} + +// EventIDLTE applies the LTE predicate on the "event_id" field. +func EventIDLTE(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldLTE(FieldEventID, v)) +} + +// EventIDContains applies the Contains predicate on the "event_id" field. +func EventIDContains(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldContains(FieldEventID, v)) +} + +// EventIDHasPrefix applies the HasPrefix predicate on the "event_id" field. +func EventIDHasPrefix(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldHasPrefix(FieldEventID, v)) +} + +// EventIDHasSuffix applies the HasSuffix predicate on the "event_id" field. +func EventIDHasSuffix(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldHasSuffix(FieldEventID, v)) +} + +// EventIDEqualFold applies the EqualFold predicate on the "event_id" field. +func EventIDEqualFold(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldEqualFold(FieldEventID, v)) +} + +// EventIDContainsFold applies the ContainsFold predicate on the "event_id" field. +func EventIDContainsFold(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldContainsFold(FieldEventID, v)) +} + +// ChannelIDEQ applies the EQ predicate on the "channel_id" field. +func ChannelIDEQ(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldEQ(FieldChannelID, v)) +} + +// ChannelIDNEQ applies the NEQ predicate on the "channel_id" field. +func ChannelIDNEQ(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldNEQ(FieldChannelID, v)) +} + +// ChannelIDIn applies the In predicate on the "channel_id" field. +func ChannelIDIn(vs ...string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldIn(FieldChannelID, vs...)) +} + +// ChannelIDNotIn applies the NotIn predicate on the "channel_id" field. +func ChannelIDNotIn(vs ...string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldNotIn(FieldChannelID, vs...)) +} + +// ChannelIDGT applies the GT predicate on the "channel_id" field. +func ChannelIDGT(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldGT(FieldChannelID, v)) +} + +// ChannelIDGTE applies the GTE predicate on the "channel_id" field. +func ChannelIDGTE(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldGTE(FieldChannelID, v)) +} + +// ChannelIDLT applies the LT predicate on the "channel_id" field. +func ChannelIDLT(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldLT(FieldChannelID, v)) +} + +// ChannelIDLTE applies the LTE predicate on the "channel_id" field. +func ChannelIDLTE(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldLTE(FieldChannelID, v)) +} + +// ChannelIDContains applies the Contains predicate on the "channel_id" field. +func ChannelIDContains(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldContains(FieldChannelID, v)) +} + +// ChannelIDHasPrefix applies the HasPrefix predicate on the "channel_id" field. +func ChannelIDHasPrefix(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldHasPrefix(FieldChannelID, v)) +} + +// ChannelIDHasSuffix applies the HasSuffix predicate on the "channel_id" field. +func ChannelIDHasSuffix(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldHasSuffix(FieldChannelID, v)) +} + +// ChannelIDEqualFold applies the EqualFold predicate on the "channel_id" field. +func ChannelIDEqualFold(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldEqualFold(FieldChannelID, v)) +} + +// ChannelIDContainsFold applies the ContainsFold predicate on the "channel_id" field. +func ChannelIDContainsFold(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldContainsFold(FieldChannelID, v)) +} + +// StateEQ applies the EQ predicate on the "state" field. +func StateEQ(v notification.EventDeliveryStatusState) predicate.NotificationEventDeliveryStatus { + vc := v + return predicate.NotificationEventDeliveryStatus(sql.FieldEQ(FieldState, vc)) +} + +// StateNEQ applies the NEQ predicate on the "state" field. +func StateNEQ(v notification.EventDeliveryStatusState) predicate.NotificationEventDeliveryStatus { + vc := v + return predicate.NotificationEventDeliveryStatus(sql.FieldNEQ(FieldState, vc)) +} + +// StateIn applies the In predicate on the "state" field. +func StateIn(vs ...notification.EventDeliveryStatusState) predicate.NotificationEventDeliveryStatus { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.NotificationEventDeliveryStatus(sql.FieldIn(FieldState, v...)) +} + +// StateNotIn applies the NotIn predicate on the "state" field. +func StateNotIn(vs ...notification.EventDeliveryStatusState) predicate.NotificationEventDeliveryStatus { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.NotificationEventDeliveryStatus(sql.FieldNotIn(FieldState, v...)) +} + +// ReasonEQ applies the EQ predicate on the "reason" field. +func ReasonEQ(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldEQ(FieldReason, v)) +} + +// ReasonNEQ applies the NEQ predicate on the "reason" field. +func ReasonNEQ(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldNEQ(FieldReason, v)) +} + +// ReasonIn applies the In predicate on the "reason" field. +func ReasonIn(vs ...string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldIn(FieldReason, vs...)) +} + +// ReasonNotIn applies the NotIn predicate on the "reason" field. +func ReasonNotIn(vs ...string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldNotIn(FieldReason, vs...)) +} + +// ReasonGT applies the GT predicate on the "reason" field. +func ReasonGT(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldGT(FieldReason, v)) +} + +// ReasonGTE applies the GTE predicate on the "reason" field. +func ReasonGTE(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldGTE(FieldReason, v)) +} + +// ReasonLT applies the LT predicate on the "reason" field. +func ReasonLT(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldLT(FieldReason, v)) +} + +// ReasonLTE applies the LTE predicate on the "reason" field. +func ReasonLTE(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldLTE(FieldReason, v)) +} + +// ReasonContains applies the Contains predicate on the "reason" field. +func ReasonContains(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldContains(FieldReason, v)) +} + +// ReasonHasPrefix applies the HasPrefix predicate on the "reason" field. +func ReasonHasPrefix(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldHasPrefix(FieldReason, v)) +} + +// ReasonHasSuffix applies the HasSuffix predicate on the "reason" field. +func ReasonHasSuffix(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldHasSuffix(FieldReason, v)) +} + +// ReasonIsNil applies the IsNil predicate on the "reason" field. +func ReasonIsNil() predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldIsNull(FieldReason)) +} + +// ReasonNotNil applies the NotNil predicate on the "reason" field. +func ReasonNotNil() predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldNotNull(FieldReason)) +} + +// ReasonEqualFold applies the EqualFold predicate on the "reason" field. +func ReasonEqualFold(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldEqualFold(FieldReason, v)) +} + +// ReasonContainsFold applies the ContainsFold predicate on the "reason" field. +func ReasonContainsFold(v string) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldContainsFold(FieldReason, v)) +} + +// NextAttemptAtEQ applies the EQ predicate on the "next_attempt_at" field. +func NextAttemptAtEQ(v time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldEQ(FieldNextAttemptAt, v)) +} + +// NextAttemptAtNEQ applies the NEQ predicate on the "next_attempt_at" field. +func NextAttemptAtNEQ(v time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldNEQ(FieldNextAttemptAt, v)) +} + +// NextAttemptAtIn applies the In predicate on the "next_attempt_at" field. +func NextAttemptAtIn(vs ...time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldIn(FieldNextAttemptAt, vs...)) +} + +// NextAttemptAtNotIn applies the NotIn predicate on the "next_attempt_at" field. +func NextAttemptAtNotIn(vs ...time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldNotIn(FieldNextAttemptAt, vs...)) +} + +// NextAttemptAtGT applies the GT predicate on the "next_attempt_at" field. +func NextAttemptAtGT(v time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldGT(FieldNextAttemptAt, v)) +} + +// NextAttemptAtGTE applies the GTE predicate on the "next_attempt_at" field. +func NextAttemptAtGTE(v time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldGTE(FieldNextAttemptAt, v)) +} + +// NextAttemptAtLT applies the LT predicate on the "next_attempt_at" field. +func NextAttemptAtLT(v time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldLT(FieldNextAttemptAt, v)) +} + +// NextAttemptAtLTE applies the LTE predicate on the "next_attempt_at" field. +func NextAttemptAtLTE(v time.Time) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldLTE(FieldNextAttemptAt, v)) +} + +// NextAttemptAtIsNil applies the IsNil predicate on the "next_attempt_at" field. +func NextAttemptAtIsNil() predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldIsNull(FieldNextAttemptAt)) +} + +// NextAttemptAtNotNil applies the NotNil predicate on the "next_attempt_at" field. +func NextAttemptAtNotNil() predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldNotNull(FieldNextAttemptAt)) +} + +// AttemptsIsNil applies the IsNil predicate on the "attempts" field. +func AttemptsIsNil() predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldIsNull(FieldAttempts)) +} + +// AttemptsNotNil applies the NotNil predicate on the "attempts" field. +func AttemptsNotNil() predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.FieldNotNull(FieldAttempts)) +} + +// HasEvents applies the HasEdge predicate on the "events" edge. +func HasEvents() predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, EventsTable, EventsPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasEventsWith applies the HasEdge predicate on the "events" edge with a given conditions (other predicates). +func HasEventsWith(preds ...predicate.NotificationEvent) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(func(s *sql.Selector) { + step := newEventsStep() + 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.NotificationEventDeliveryStatus) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.NotificationEventDeliveryStatus) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.NotificationEventDeliveryStatus) predicate.NotificationEventDeliveryStatus { + return predicate.NotificationEventDeliveryStatus(sql.NotPredicates(p)) +} diff --git a/ent/db/notificationeventdeliverystatus_create.go b/ent/db/notificationeventdeliverystatus_create.go new file mode 100644 index 0000000000000000000000000000000000000000..1c088ff7297a66f3ec5c0c23403d73fe6facacd4 --- /dev/null +++ b/ent/db/notificationeventdeliverystatus_create.go @@ -0,0 +1,1023 @@ +// 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/notificationevent" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationeventdeliverystatus" + "github.com/openmeterio/openmeter/openmeter/notification" + "github.com/openmeterio/openmeter/pkg/models" +) + +// NotificationEventDeliveryStatusCreate is the builder for creating a NotificationEventDeliveryStatus entity. +type NotificationEventDeliveryStatusCreate struct { + config + mutation *NotificationEventDeliveryStatusMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *NotificationEventDeliveryStatusCreate) SetNamespace(v string) *NotificationEventDeliveryStatusCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *NotificationEventDeliveryStatusCreate) SetAnnotations(v models.Annotations) *NotificationEventDeliveryStatusCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *NotificationEventDeliveryStatusCreate) SetCreatedAt(v time.Time) *NotificationEventDeliveryStatusCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *NotificationEventDeliveryStatusCreate) SetNillableCreatedAt(v *time.Time) *NotificationEventDeliveryStatusCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *NotificationEventDeliveryStatusCreate) SetUpdatedAt(v time.Time) *NotificationEventDeliveryStatusCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *NotificationEventDeliveryStatusCreate) SetNillableUpdatedAt(v *time.Time) *NotificationEventDeliveryStatusCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetEventID sets the "event_id" field. +func (_c *NotificationEventDeliveryStatusCreate) SetEventID(v string) *NotificationEventDeliveryStatusCreate { + _c.mutation.SetEventID(v) + return _c +} + +// SetChannelID sets the "channel_id" field. +func (_c *NotificationEventDeliveryStatusCreate) SetChannelID(v string) *NotificationEventDeliveryStatusCreate { + _c.mutation.SetChannelID(v) + return _c +} + +// SetState sets the "state" field. +func (_c *NotificationEventDeliveryStatusCreate) SetState(v notification.EventDeliveryStatusState) *NotificationEventDeliveryStatusCreate { + _c.mutation.SetState(v) + return _c +} + +// SetNillableState sets the "state" field if the given value is not nil. +func (_c *NotificationEventDeliveryStatusCreate) SetNillableState(v *notification.EventDeliveryStatusState) *NotificationEventDeliveryStatusCreate { + if v != nil { + _c.SetState(*v) + } + return _c +} + +// SetReason sets the "reason" field. +func (_c *NotificationEventDeliveryStatusCreate) SetReason(v string) *NotificationEventDeliveryStatusCreate { + _c.mutation.SetReason(v) + return _c +} + +// SetNillableReason sets the "reason" field if the given value is not nil. +func (_c *NotificationEventDeliveryStatusCreate) SetNillableReason(v *string) *NotificationEventDeliveryStatusCreate { + if v != nil { + _c.SetReason(*v) + } + return _c +} + +// SetNextAttemptAt sets the "next_attempt_at" field. +func (_c *NotificationEventDeliveryStatusCreate) SetNextAttemptAt(v time.Time) *NotificationEventDeliveryStatusCreate { + _c.mutation.SetNextAttemptAt(v) + return _c +} + +// SetNillableNextAttemptAt sets the "next_attempt_at" field if the given value is not nil. +func (_c *NotificationEventDeliveryStatusCreate) SetNillableNextAttemptAt(v *time.Time) *NotificationEventDeliveryStatusCreate { + if v != nil { + _c.SetNextAttemptAt(*v) + } + return _c +} + +// SetAttempts sets the "attempts" field. +func (_c *NotificationEventDeliveryStatusCreate) SetAttempts(v []notification.EventDeliveryAttempt) *NotificationEventDeliveryStatusCreate { + _c.mutation.SetAttempts(v) + return _c +} + +// SetID sets the "id" field. +func (_c *NotificationEventDeliveryStatusCreate) SetID(v string) *NotificationEventDeliveryStatusCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *NotificationEventDeliveryStatusCreate) SetNillableID(v *string) *NotificationEventDeliveryStatusCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// AddEventIDs adds the "events" edge to the NotificationEvent entity by IDs. +func (_c *NotificationEventDeliveryStatusCreate) AddEventIDs(ids ...string) *NotificationEventDeliveryStatusCreate { + _c.mutation.AddEventIDs(ids...) + return _c +} + +// AddEvents adds the "events" edges to the NotificationEvent entity. +func (_c *NotificationEventDeliveryStatusCreate) AddEvents(v ...*NotificationEvent) *NotificationEventDeliveryStatusCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddEventIDs(ids...) +} + +// Mutation returns the NotificationEventDeliveryStatusMutation object of the builder. +func (_c *NotificationEventDeliveryStatusCreate) Mutation() *NotificationEventDeliveryStatusMutation { + return _c.mutation +} + +// Save creates the NotificationEventDeliveryStatus in the database. +func (_c *NotificationEventDeliveryStatusCreate) Save(ctx context.Context) (*NotificationEventDeliveryStatus, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *NotificationEventDeliveryStatusCreate) SaveX(ctx context.Context) *NotificationEventDeliveryStatus { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *NotificationEventDeliveryStatusCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *NotificationEventDeliveryStatusCreate) 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 *NotificationEventDeliveryStatusCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := notificationeventdeliverystatus.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := notificationeventdeliverystatus.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.State(); !ok { + v := notificationeventdeliverystatus.DefaultState + _c.mutation.SetState(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := notificationeventdeliverystatus.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *NotificationEventDeliveryStatusCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "NotificationEventDeliveryStatus.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := notificationeventdeliverystatus.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "NotificationEventDeliveryStatus.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "NotificationEventDeliveryStatus.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "NotificationEventDeliveryStatus.updated_at"`)} + } + if _, ok := _c.mutation.EventID(); !ok { + return &ValidationError{Name: "event_id", err: errors.New(`db: missing required field "NotificationEventDeliveryStatus.event_id"`)} + } + if v, ok := _c.mutation.EventID(); ok { + if err := notificationeventdeliverystatus.EventIDValidator(v); err != nil { + return &ValidationError{Name: "event_id", err: fmt.Errorf(`db: validator failed for field "NotificationEventDeliveryStatus.event_id": %w`, err)} + } + } + if _, ok := _c.mutation.ChannelID(); !ok { + return &ValidationError{Name: "channel_id", err: errors.New(`db: missing required field "NotificationEventDeliveryStatus.channel_id"`)} + } + if v, ok := _c.mutation.ChannelID(); ok { + if err := notificationeventdeliverystatus.ChannelIDValidator(v); err != nil { + return &ValidationError{Name: "channel_id", err: fmt.Errorf(`db: validator failed for field "NotificationEventDeliveryStatus.channel_id": %w`, err)} + } + } + if _, ok := _c.mutation.State(); !ok { + return &ValidationError{Name: "state", err: errors.New(`db: missing required field "NotificationEventDeliveryStatus.state"`)} + } + if v, ok := _c.mutation.State(); ok { + if err := notificationeventdeliverystatus.StateValidator(v); err != nil { + return &ValidationError{Name: "state", err: fmt.Errorf(`db: validator failed for field "NotificationEventDeliveryStatus.state": %w`, err)} + } + } + return nil +} + +func (_c *NotificationEventDeliveryStatusCreate) sqlSave(ctx context.Context) (*NotificationEventDeliveryStatus, 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 NotificationEventDeliveryStatus.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *NotificationEventDeliveryStatusCreate) createSpec() (*NotificationEventDeliveryStatus, *sqlgraph.CreateSpec) { + var ( + _node = &NotificationEventDeliveryStatus{config: _c.config} + _spec = sqlgraph.NewCreateSpec(notificationeventdeliverystatus.Table, sqlgraph.NewFieldSpec(notificationeventdeliverystatus.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(notificationeventdeliverystatus.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.EventID(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldEventID, field.TypeString, value) + _node.EventID = value + } + if value, ok := _c.mutation.ChannelID(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldChannelID, field.TypeString, value) + _node.ChannelID = value + } + if value, ok := _c.mutation.State(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldState, field.TypeEnum, value) + _node.State = value + } + if value, ok := _c.mutation.Reason(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldReason, field.TypeString, value) + _node.Reason = value + } + if value, ok := _c.mutation.NextAttemptAt(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldNextAttemptAt, field.TypeTime, value) + _node.NextAttemptAt = &value + } + if value, ok := _c.mutation.Attempts(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldAttempts, field.TypeJSON, value) + _node.Attempts = value + } + if nodes := _c.mutation.EventsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: notificationeventdeliverystatus.EventsTable, + Columns: notificationeventdeliverystatus.EventsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationevent.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.NotificationEventDeliveryStatus.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.NotificationEventDeliveryStatusUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *NotificationEventDeliveryStatusCreate) OnConflict(opts ...sql.ConflictOption) *NotificationEventDeliveryStatusUpsertOne { + _c.conflict = opts + return &NotificationEventDeliveryStatusUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.NotificationEventDeliveryStatus.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *NotificationEventDeliveryStatusCreate) OnConflictColumns(columns ...string) *NotificationEventDeliveryStatusUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &NotificationEventDeliveryStatusUpsertOne{ + create: _c, + } +} + +type ( + // NotificationEventDeliveryStatusUpsertOne is the builder for "upsert"-ing + // one NotificationEventDeliveryStatus node. + NotificationEventDeliveryStatusUpsertOne struct { + create *NotificationEventDeliveryStatusCreate + } + + // NotificationEventDeliveryStatusUpsert is the "OnConflict" setter. + NotificationEventDeliveryStatusUpsert struct { + *sql.UpdateSet + } +) + +// SetAnnotations sets the "annotations" field. +func (u *NotificationEventDeliveryStatusUpsert) SetAnnotations(v models.Annotations) *NotificationEventDeliveryStatusUpsert { + u.Set(notificationeventdeliverystatus.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *NotificationEventDeliveryStatusUpsert) UpdateAnnotations() *NotificationEventDeliveryStatusUpsert { + u.SetExcluded(notificationeventdeliverystatus.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *NotificationEventDeliveryStatusUpsert) ClearAnnotations() *NotificationEventDeliveryStatusUpsert { + u.SetNull(notificationeventdeliverystatus.FieldAnnotations) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *NotificationEventDeliveryStatusUpsert) SetUpdatedAt(v time.Time) *NotificationEventDeliveryStatusUpsert { + u.Set(notificationeventdeliverystatus.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *NotificationEventDeliveryStatusUpsert) UpdateUpdatedAt() *NotificationEventDeliveryStatusUpsert { + u.SetExcluded(notificationeventdeliverystatus.FieldUpdatedAt) + return u +} + +// SetState sets the "state" field. +func (u *NotificationEventDeliveryStatusUpsert) SetState(v notification.EventDeliveryStatusState) *NotificationEventDeliveryStatusUpsert { + u.Set(notificationeventdeliverystatus.FieldState, v) + return u +} + +// UpdateState sets the "state" field to the value that was provided on create. +func (u *NotificationEventDeliveryStatusUpsert) UpdateState() *NotificationEventDeliveryStatusUpsert { + u.SetExcluded(notificationeventdeliverystatus.FieldState) + return u +} + +// SetReason sets the "reason" field. +func (u *NotificationEventDeliveryStatusUpsert) SetReason(v string) *NotificationEventDeliveryStatusUpsert { + u.Set(notificationeventdeliverystatus.FieldReason, v) + return u +} + +// UpdateReason sets the "reason" field to the value that was provided on create. +func (u *NotificationEventDeliveryStatusUpsert) UpdateReason() *NotificationEventDeliveryStatusUpsert { + u.SetExcluded(notificationeventdeliverystatus.FieldReason) + return u +} + +// ClearReason clears the value of the "reason" field. +func (u *NotificationEventDeliveryStatusUpsert) ClearReason() *NotificationEventDeliveryStatusUpsert { + u.SetNull(notificationeventdeliverystatus.FieldReason) + return u +} + +// SetNextAttemptAt sets the "next_attempt_at" field. +func (u *NotificationEventDeliveryStatusUpsert) SetNextAttemptAt(v time.Time) *NotificationEventDeliveryStatusUpsert { + u.Set(notificationeventdeliverystatus.FieldNextAttemptAt, v) + return u +} + +// UpdateNextAttemptAt sets the "next_attempt_at" field to the value that was provided on create. +func (u *NotificationEventDeliveryStatusUpsert) UpdateNextAttemptAt() *NotificationEventDeliveryStatusUpsert { + u.SetExcluded(notificationeventdeliverystatus.FieldNextAttemptAt) + return u +} + +// ClearNextAttemptAt clears the value of the "next_attempt_at" field. +func (u *NotificationEventDeliveryStatusUpsert) ClearNextAttemptAt() *NotificationEventDeliveryStatusUpsert { + u.SetNull(notificationeventdeliverystatus.FieldNextAttemptAt) + return u +} + +// SetAttempts sets the "attempts" field. +func (u *NotificationEventDeliveryStatusUpsert) SetAttempts(v []notification.EventDeliveryAttempt) *NotificationEventDeliveryStatusUpsert { + u.Set(notificationeventdeliverystatus.FieldAttempts, v) + return u +} + +// UpdateAttempts sets the "attempts" field to the value that was provided on create. +func (u *NotificationEventDeliveryStatusUpsert) UpdateAttempts() *NotificationEventDeliveryStatusUpsert { + u.SetExcluded(notificationeventdeliverystatus.FieldAttempts) + return u +} + +// ClearAttempts clears the value of the "attempts" field. +func (u *NotificationEventDeliveryStatusUpsert) ClearAttempts() *NotificationEventDeliveryStatusUpsert { + u.SetNull(notificationeventdeliverystatus.FieldAttempts) + 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.NotificationEventDeliveryStatus.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(notificationeventdeliverystatus.FieldID) +// }), +// ). +// Exec(ctx) +func (u *NotificationEventDeliveryStatusUpsertOne) UpdateNewValues() *NotificationEventDeliveryStatusUpsertOne { + 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(notificationeventdeliverystatus.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(notificationeventdeliverystatus.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(notificationeventdeliverystatus.FieldCreatedAt) + } + if _, exists := u.create.mutation.EventID(); exists { + s.SetIgnore(notificationeventdeliverystatus.FieldEventID) + } + if _, exists := u.create.mutation.ChannelID(); exists { + s.SetIgnore(notificationeventdeliverystatus.FieldChannelID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.NotificationEventDeliveryStatus.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *NotificationEventDeliveryStatusUpsertOne) Ignore() *NotificationEventDeliveryStatusUpsertOne { + 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 *NotificationEventDeliveryStatusUpsertOne) DoNothing() *NotificationEventDeliveryStatusUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the NotificationEventDeliveryStatusCreate.OnConflict +// documentation for more info. +func (u *NotificationEventDeliveryStatusUpsertOne) Update(set func(*NotificationEventDeliveryStatusUpsert)) *NotificationEventDeliveryStatusUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&NotificationEventDeliveryStatusUpsert{UpdateSet: update}) + })) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *NotificationEventDeliveryStatusUpsertOne) SetAnnotations(v models.Annotations) *NotificationEventDeliveryStatusUpsertOne { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *NotificationEventDeliveryStatusUpsertOne) UpdateAnnotations() *NotificationEventDeliveryStatusUpsertOne { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *NotificationEventDeliveryStatusUpsertOne) ClearAnnotations() *NotificationEventDeliveryStatusUpsertOne { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.ClearAnnotations() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *NotificationEventDeliveryStatusUpsertOne) SetUpdatedAt(v time.Time) *NotificationEventDeliveryStatusUpsertOne { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *NotificationEventDeliveryStatusUpsertOne) UpdateUpdatedAt() *NotificationEventDeliveryStatusUpsertOne { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetState sets the "state" field. +func (u *NotificationEventDeliveryStatusUpsertOne) SetState(v notification.EventDeliveryStatusState) *NotificationEventDeliveryStatusUpsertOne { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.SetState(v) + }) +} + +// UpdateState sets the "state" field to the value that was provided on create. +func (u *NotificationEventDeliveryStatusUpsertOne) UpdateState() *NotificationEventDeliveryStatusUpsertOne { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.UpdateState() + }) +} + +// SetReason sets the "reason" field. +func (u *NotificationEventDeliveryStatusUpsertOne) SetReason(v string) *NotificationEventDeliveryStatusUpsertOne { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.SetReason(v) + }) +} + +// UpdateReason sets the "reason" field to the value that was provided on create. +func (u *NotificationEventDeliveryStatusUpsertOne) UpdateReason() *NotificationEventDeliveryStatusUpsertOne { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.UpdateReason() + }) +} + +// ClearReason clears the value of the "reason" field. +func (u *NotificationEventDeliveryStatusUpsertOne) ClearReason() *NotificationEventDeliveryStatusUpsertOne { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.ClearReason() + }) +} + +// SetNextAttemptAt sets the "next_attempt_at" field. +func (u *NotificationEventDeliveryStatusUpsertOne) SetNextAttemptAt(v time.Time) *NotificationEventDeliveryStatusUpsertOne { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.SetNextAttemptAt(v) + }) +} + +// UpdateNextAttemptAt sets the "next_attempt_at" field to the value that was provided on create. +func (u *NotificationEventDeliveryStatusUpsertOne) UpdateNextAttemptAt() *NotificationEventDeliveryStatusUpsertOne { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.UpdateNextAttemptAt() + }) +} + +// ClearNextAttemptAt clears the value of the "next_attempt_at" field. +func (u *NotificationEventDeliveryStatusUpsertOne) ClearNextAttemptAt() *NotificationEventDeliveryStatusUpsertOne { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.ClearNextAttemptAt() + }) +} + +// SetAttempts sets the "attempts" field. +func (u *NotificationEventDeliveryStatusUpsertOne) SetAttempts(v []notification.EventDeliveryAttempt) *NotificationEventDeliveryStatusUpsertOne { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.SetAttempts(v) + }) +} + +// UpdateAttempts sets the "attempts" field to the value that was provided on create. +func (u *NotificationEventDeliveryStatusUpsertOne) UpdateAttempts() *NotificationEventDeliveryStatusUpsertOne { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.UpdateAttempts() + }) +} + +// ClearAttempts clears the value of the "attempts" field. +func (u *NotificationEventDeliveryStatusUpsertOne) ClearAttempts() *NotificationEventDeliveryStatusUpsertOne { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.ClearAttempts() + }) +} + +// Exec executes the query. +func (u *NotificationEventDeliveryStatusUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for NotificationEventDeliveryStatusCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *NotificationEventDeliveryStatusUpsertOne) 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 *NotificationEventDeliveryStatusUpsertOne) 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: NotificationEventDeliveryStatusUpsertOne.ID is not supported by MySQL driver. Use NotificationEventDeliveryStatusUpsertOne.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 *NotificationEventDeliveryStatusUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// NotificationEventDeliveryStatusCreateBulk is the builder for creating many NotificationEventDeliveryStatus entities in bulk. +type NotificationEventDeliveryStatusCreateBulk struct { + config + err error + builders []*NotificationEventDeliveryStatusCreate + conflict []sql.ConflictOption +} + +// Save creates the NotificationEventDeliveryStatus entities in the database. +func (_c *NotificationEventDeliveryStatusCreateBulk) Save(ctx context.Context) ([]*NotificationEventDeliveryStatus, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*NotificationEventDeliveryStatus, 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.(*NotificationEventDeliveryStatusMutation) + 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 *NotificationEventDeliveryStatusCreateBulk) SaveX(ctx context.Context) []*NotificationEventDeliveryStatus { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *NotificationEventDeliveryStatusCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *NotificationEventDeliveryStatusCreateBulk) 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.NotificationEventDeliveryStatus.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.NotificationEventDeliveryStatusUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *NotificationEventDeliveryStatusCreateBulk) OnConflict(opts ...sql.ConflictOption) *NotificationEventDeliveryStatusUpsertBulk { + _c.conflict = opts + return &NotificationEventDeliveryStatusUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.NotificationEventDeliveryStatus.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *NotificationEventDeliveryStatusCreateBulk) OnConflictColumns(columns ...string) *NotificationEventDeliveryStatusUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &NotificationEventDeliveryStatusUpsertBulk{ + create: _c, + } +} + +// NotificationEventDeliveryStatusUpsertBulk is the builder for "upsert"-ing +// a bulk of NotificationEventDeliveryStatus nodes. +type NotificationEventDeliveryStatusUpsertBulk struct { + create *NotificationEventDeliveryStatusCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.NotificationEventDeliveryStatus.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(notificationeventdeliverystatus.FieldID) +// }), +// ). +// Exec(ctx) +func (u *NotificationEventDeliveryStatusUpsertBulk) UpdateNewValues() *NotificationEventDeliveryStatusUpsertBulk { + 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(notificationeventdeliverystatus.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(notificationeventdeliverystatus.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(notificationeventdeliverystatus.FieldCreatedAt) + } + if _, exists := b.mutation.EventID(); exists { + s.SetIgnore(notificationeventdeliverystatus.FieldEventID) + } + if _, exists := b.mutation.ChannelID(); exists { + s.SetIgnore(notificationeventdeliverystatus.FieldChannelID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.NotificationEventDeliveryStatus.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *NotificationEventDeliveryStatusUpsertBulk) Ignore() *NotificationEventDeliveryStatusUpsertBulk { + 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 *NotificationEventDeliveryStatusUpsertBulk) DoNothing() *NotificationEventDeliveryStatusUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the NotificationEventDeliveryStatusCreateBulk.OnConflict +// documentation for more info. +func (u *NotificationEventDeliveryStatusUpsertBulk) Update(set func(*NotificationEventDeliveryStatusUpsert)) *NotificationEventDeliveryStatusUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&NotificationEventDeliveryStatusUpsert{UpdateSet: update}) + })) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *NotificationEventDeliveryStatusUpsertBulk) SetAnnotations(v models.Annotations) *NotificationEventDeliveryStatusUpsertBulk { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *NotificationEventDeliveryStatusUpsertBulk) UpdateAnnotations() *NotificationEventDeliveryStatusUpsertBulk { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *NotificationEventDeliveryStatusUpsertBulk) ClearAnnotations() *NotificationEventDeliveryStatusUpsertBulk { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.ClearAnnotations() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *NotificationEventDeliveryStatusUpsertBulk) SetUpdatedAt(v time.Time) *NotificationEventDeliveryStatusUpsertBulk { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *NotificationEventDeliveryStatusUpsertBulk) UpdateUpdatedAt() *NotificationEventDeliveryStatusUpsertBulk { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetState sets the "state" field. +func (u *NotificationEventDeliveryStatusUpsertBulk) SetState(v notification.EventDeliveryStatusState) *NotificationEventDeliveryStatusUpsertBulk { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.SetState(v) + }) +} + +// UpdateState sets the "state" field to the value that was provided on create. +func (u *NotificationEventDeliveryStatusUpsertBulk) UpdateState() *NotificationEventDeliveryStatusUpsertBulk { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.UpdateState() + }) +} + +// SetReason sets the "reason" field. +func (u *NotificationEventDeliveryStatusUpsertBulk) SetReason(v string) *NotificationEventDeliveryStatusUpsertBulk { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.SetReason(v) + }) +} + +// UpdateReason sets the "reason" field to the value that was provided on create. +func (u *NotificationEventDeliveryStatusUpsertBulk) UpdateReason() *NotificationEventDeliveryStatusUpsertBulk { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.UpdateReason() + }) +} + +// ClearReason clears the value of the "reason" field. +func (u *NotificationEventDeliveryStatusUpsertBulk) ClearReason() *NotificationEventDeliveryStatusUpsertBulk { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.ClearReason() + }) +} + +// SetNextAttemptAt sets the "next_attempt_at" field. +func (u *NotificationEventDeliveryStatusUpsertBulk) SetNextAttemptAt(v time.Time) *NotificationEventDeliveryStatusUpsertBulk { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.SetNextAttemptAt(v) + }) +} + +// UpdateNextAttemptAt sets the "next_attempt_at" field to the value that was provided on create. +func (u *NotificationEventDeliveryStatusUpsertBulk) UpdateNextAttemptAt() *NotificationEventDeliveryStatusUpsertBulk { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.UpdateNextAttemptAt() + }) +} + +// ClearNextAttemptAt clears the value of the "next_attempt_at" field. +func (u *NotificationEventDeliveryStatusUpsertBulk) ClearNextAttemptAt() *NotificationEventDeliveryStatusUpsertBulk { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.ClearNextAttemptAt() + }) +} + +// SetAttempts sets the "attempts" field. +func (u *NotificationEventDeliveryStatusUpsertBulk) SetAttempts(v []notification.EventDeliveryAttempt) *NotificationEventDeliveryStatusUpsertBulk { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.SetAttempts(v) + }) +} + +// UpdateAttempts sets the "attempts" field to the value that was provided on create. +func (u *NotificationEventDeliveryStatusUpsertBulk) UpdateAttempts() *NotificationEventDeliveryStatusUpsertBulk { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.UpdateAttempts() + }) +} + +// ClearAttempts clears the value of the "attempts" field. +func (u *NotificationEventDeliveryStatusUpsertBulk) ClearAttempts() *NotificationEventDeliveryStatusUpsertBulk { + return u.Update(func(s *NotificationEventDeliveryStatusUpsert) { + s.ClearAttempts() + }) +} + +// Exec executes the query. +func (u *NotificationEventDeliveryStatusUpsertBulk) 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 NotificationEventDeliveryStatusCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for NotificationEventDeliveryStatusCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *NotificationEventDeliveryStatusUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/notificationeventdeliverystatus_delete.go b/ent/db/notificationeventdeliverystatus_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..6ff08e98f849ef2ea51a67bdac59bfe47135d0f7 --- /dev/null +++ b/ent/db/notificationeventdeliverystatus_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/notificationeventdeliverystatus" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// NotificationEventDeliveryStatusDelete is the builder for deleting a NotificationEventDeliveryStatus entity. +type NotificationEventDeliveryStatusDelete struct { + config + hooks []Hook + mutation *NotificationEventDeliveryStatusMutation +} + +// Where appends a list predicates to the NotificationEventDeliveryStatusDelete builder. +func (_d *NotificationEventDeliveryStatusDelete) Where(ps ...predicate.NotificationEventDeliveryStatus) *NotificationEventDeliveryStatusDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *NotificationEventDeliveryStatusDelete) 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 *NotificationEventDeliveryStatusDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *NotificationEventDeliveryStatusDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(notificationeventdeliverystatus.Table, sqlgraph.NewFieldSpec(notificationeventdeliverystatus.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 +} + +// NotificationEventDeliveryStatusDeleteOne is the builder for deleting a single NotificationEventDeliveryStatus entity. +type NotificationEventDeliveryStatusDeleteOne struct { + _d *NotificationEventDeliveryStatusDelete +} + +// Where appends a list predicates to the NotificationEventDeliveryStatusDelete builder. +func (_d *NotificationEventDeliveryStatusDeleteOne) Where(ps ...predicate.NotificationEventDeliveryStatus) *NotificationEventDeliveryStatusDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *NotificationEventDeliveryStatusDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{notificationeventdeliverystatus.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *NotificationEventDeliveryStatusDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/notificationeventdeliverystatus_query.go b/ent/db/notificationeventdeliverystatus_query.go new file mode 100644 index 0000000000000000000000000000000000000000..710831f07f6bbcd42ec1be378f5e3dd83183162e --- /dev/null +++ b/ent/db/notificationeventdeliverystatus_query.go @@ -0,0 +1,676 @@ +// 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/notificationevent" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationeventdeliverystatus" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// NotificationEventDeliveryStatusQuery is the builder for querying NotificationEventDeliveryStatus entities. +type NotificationEventDeliveryStatusQuery struct { + config + ctx *QueryContext + order []notificationeventdeliverystatus.OrderOption + inters []Interceptor + predicates []predicate.NotificationEventDeliveryStatus + withEvents *NotificationEventQuery + 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 NotificationEventDeliveryStatusQuery builder. +func (_q *NotificationEventDeliveryStatusQuery) Where(ps ...predicate.NotificationEventDeliveryStatus) *NotificationEventDeliveryStatusQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *NotificationEventDeliveryStatusQuery) Limit(limit int) *NotificationEventDeliveryStatusQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *NotificationEventDeliveryStatusQuery) Offset(offset int) *NotificationEventDeliveryStatusQuery { + _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 *NotificationEventDeliveryStatusQuery) Unique(unique bool) *NotificationEventDeliveryStatusQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *NotificationEventDeliveryStatusQuery) Order(o ...notificationeventdeliverystatus.OrderOption) *NotificationEventDeliveryStatusQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryEvents chains the current query on the "events" edge. +func (_q *NotificationEventDeliveryStatusQuery) QueryEvents() *NotificationEventQuery { + query := (&NotificationEventClient{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(notificationeventdeliverystatus.Table, notificationeventdeliverystatus.FieldID, selector), + sqlgraph.To(notificationevent.Table, notificationevent.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, notificationeventdeliverystatus.EventsTable, notificationeventdeliverystatus.EventsPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first NotificationEventDeliveryStatus entity from the query. +// Returns a *NotFoundError when no NotificationEventDeliveryStatus was found. +func (_q *NotificationEventDeliveryStatusQuery) First(ctx context.Context) (*NotificationEventDeliveryStatus, 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{notificationeventdeliverystatus.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *NotificationEventDeliveryStatusQuery) FirstX(ctx context.Context) *NotificationEventDeliveryStatus { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first NotificationEventDeliveryStatus ID from the query. +// Returns a *NotFoundError when no NotificationEventDeliveryStatus ID was found. +func (_q *NotificationEventDeliveryStatusQuery) 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{notificationeventdeliverystatus.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *NotificationEventDeliveryStatusQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single NotificationEventDeliveryStatus entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one NotificationEventDeliveryStatus entity is found. +// Returns a *NotFoundError when no NotificationEventDeliveryStatus entities are found. +func (_q *NotificationEventDeliveryStatusQuery) Only(ctx context.Context) (*NotificationEventDeliveryStatus, 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{notificationeventdeliverystatus.Label} + default: + return nil, &NotSingularError{notificationeventdeliverystatus.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *NotificationEventDeliveryStatusQuery) OnlyX(ctx context.Context) *NotificationEventDeliveryStatus { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only NotificationEventDeliveryStatus ID in the query. +// Returns a *NotSingularError when more than one NotificationEventDeliveryStatus ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *NotificationEventDeliveryStatusQuery) 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{notificationeventdeliverystatus.Label} + default: + err = &NotSingularError{notificationeventdeliverystatus.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *NotificationEventDeliveryStatusQuery) 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 NotificationEventDeliveryStatusSlice. +func (_q *NotificationEventDeliveryStatusQuery) All(ctx context.Context) ([]*NotificationEventDeliveryStatus, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*NotificationEventDeliveryStatus, *NotificationEventDeliveryStatusQuery]() + return withInterceptors[[]*NotificationEventDeliveryStatus](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *NotificationEventDeliveryStatusQuery) AllX(ctx context.Context) []*NotificationEventDeliveryStatus { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of NotificationEventDeliveryStatus IDs. +func (_q *NotificationEventDeliveryStatusQuery) 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(notificationeventdeliverystatus.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *NotificationEventDeliveryStatusQuery) 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 *NotificationEventDeliveryStatusQuery) 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[*NotificationEventDeliveryStatusQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *NotificationEventDeliveryStatusQuery) 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 *NotificationEventDeliveryStatusQuery) 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 *NotificationEventDeliveryStatusQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the NotificationEventDeliveryStatusQuery 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 *NotificationEventDeliveryStatusQuery) Clone() *NotificationEventDeliveryStatusQuery { + if _q == nil { + return nil + } + return &NotificationEventDeliveryStatusQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]notificationeventdeliverystatus.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.NotificationEventDeliveryStatus{}, _q.predicates...), + withEvents: _q.withEvents.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithEvents tells the query-builder to eager-load the nodes that are connected to +// the "events" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *NotificationEventDeliveryStatusQuery) WithEvents(opts ...func(*NotificationEventQuery)) *NotificationEventDeliveryStatusQuery { + query := (&NotificationEventClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withEvents = 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.NotificationEventDeliveryStatus.Query(). +// GroupBy(notificationeventdeliverystatus.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *NotificationEventDeliveryStatusQuery) GroupBy(field string, fields ...string) *NotificationEventDeliveryStatusGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &NotificationEventDeliveryStatusGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = notificationeventdeliverystatus.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.NotificationEventDeliveryStatus.Query(). +// Select(notificationeventdeliverystatus.FieldNamespace). +// Scan(ctx, &v) +func (_q *NotificationEventDeliveryStatusQuery) Select(fields ...string) *NotificationEventDeliveryStatusSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &NotificationEventDeliveryStatusSelect{NotificationEventDeliveryStatusQuery: _q} + sbuild.label = notificationeventdeliverystatus.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a NotificationEventDeliveryStatusSelect configured with the given aggregations. +func (_q *NotificationEventDeliveryStatusQuery) Aggregate(fns ...AggregateFunc) *NotificationEventDeliveryStatusSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *NotificationEventDeliveryStatusQuery) 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 !notificationeventdeliverystatus.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 *NotificationEventDeliveryStatusQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*NotificationEventDeliveryStatus, error) { + var ( + nodes = []*NotificationEventDeliveryStatus{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withEvents != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*NotificationEventDeliveryStatus).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &NotificationEventDeliveryStatus{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.withEvents; query != nil { + if err := _q.loadEvents(ctx, query, nodes, + func(n *NotificationEventDeliveryStatus) { n.Edges.Events = []*NotificationEvent{} }, + func(n *NotificationEventDeliveryStatus, e *NotificationEvent) { + n.Edges.Events = append(n.Edges.Events, e) + }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *NotificationEventDeliveryStatusQuery) loadEvents(ctx context.Context, query *NotificationEventQuery, nodes []*NotificationEventDeliveryStatus, init func(*NotificationEventDeliveryStatus), assign func(*NotificationEventDeliveryStatus, *NotificationEvent)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[string]*NotificationEventDeliveryStatus) + nids := make(map[string]map[*NotificationEventDeliveryStatus]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(notificationeventdeliverystatus.EventsTable) + s.Join(joinT).On(s.C(notificationevent.FieldID), joinT.C(notificationeventdeliverystatus.EventsPrimaryKey[1])) + s.Where(sql.InValues(joinT.C(notificationeventdeliverystatus.EventsPrimaryKey[0]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(notificationeventdeliverystatus.EventsPrimaryKey[0])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + if err := query.prepareQuery(ctx); err != nil { + return err + } + qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]any, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]any{new(sql.NullString)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := values[0].(*sql.NullString).String + inValue := values[1].(*sql.NullString).String + if nids[inValue] == nil { + nids[inValue] = map[*NotificationEventDeliveryStatus]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*NotificationEvent](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "events" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} + +func (_q *NotificationEventDeliveryStatusQuery) 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 *NotificationEventDeliveryStatusQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(notificationeventdeliverystatus.Table, notificationeventdeliverystatus.Columns, sqlgraph.NewFieldSpec(notificationeventdeliverystatus.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, notificationeventdeliverystatus.FieldID) + for i := range fields { + if fields[i] != notificationeventdeliverystatus.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 *NotificationEventDeliveryStatusQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(notificationeventdeliverystatus.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = notificationeventdeliverystatus.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 *NotificationEventDeliveryStatusQuery) ForUpdate(opts ...sql.LockOption) *NotificationEventDeliveryStatusQuery { + 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 *NotificationEventDeliveryStatusQuery) ForShare(opts ...sql.LockOption) *NotificationEventDeliveryStatusQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// NotificationEventDeliveryStatusGroupBy is the group-by builder for NotificationEventDeliveryStatus entities. +type NotificationEventDeliveryStatusGroupBy struct { + selector + build *NotificationEventDeliveryStatusQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *NotificationEventDeliveryStatusGroupBy) Aggregate(fns ...AggregateFunc) *NotificationEventDeliveryStatusGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *NotificationEventDeliveryStatusGroupBy) 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[*NotificationEventDeliveryStatusQuery, *NotificationEventDeliveryStatusGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *NotificationEventDeliveryStatusGroupBy) sqlScan(ctx context.Context, root *NotificationEventDeliveryStatusQuery, 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) +} + +// NotificationEventDeliveryStatusSelect is the builder for selecting fields of NotificationEventDeliveryStatus entities. +type NotificationEventDeliveryStatusSelect struct { + *NotificationEventDeliveryStatusQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *NotificationEventDeliveryStatusSelect) Aggregate(fns ...AggregateFunc) *NotificationEventDeliveryStatusSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *NotificationEventDeliveryStatusSelect) 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[*NotificationEventDeliveryStatusQuery, *NotificationEventDeliveryStatusSelect](ctx, _s.NotificationEventDeliveryStatusQuery, _s, _s.inters, v) +} + +func (_s *NotificationEventDeliveryStatusSelect) sqlScan(ctx context.Context, root *NotificationEventDeliveryStatusQuery, 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/ent/db/notificationeventdeliverystatus_update.go b/ent/db/notificationeventdeliverystatus_update.go new file mode 100644 index 0000000000000000000000000000000000000000..9c365113487b6c24d3486aee1423e28644a28f74 --- /dev/null +++ b/ent/db/notificationeventdeliverystatus_update.go @@ -0,0 +1,636 @@ +// 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/dialect/sql/sqljson" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationevent" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationeventdeliverystatus" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/notification" + "github.com/openmeterio/openmeter/pkg/models" +) + +// NotificationEventDeliveryStatusUpdate is the builder for updating NotificationEventDeliveryStatus entities. +type NotificationEventDeliveryStatusUpdate struct { + config + hooks []Hook + mutation *NotificationEventDeliveryStatusMutation +} + +// Where appends a list predicates to the NotificationEventDeliveryStatusUpdate builder. +func (_u *NotificationEventDeliveryStatusUpdate) Where(ps ...predicate.NotificationEventDeliveryStatus) *NotificationEventDeliveryStatusUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *NotificationEventDeliveryStatusUpdate) SetAnnotations(v models.Annotations) *NotificationEventDeliveryStatusUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *NotificationEventDeliveryStatusUpdate) ClearAnnotations() *NotificationEventDeliveryStatusUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *NotificationEventDeliveryStatusUpdate) SetUpdatedAt(v time.Time) *NotificationEventDeliveryStatusUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetState sets the "state" field. +func (_u *NotificationEventDeliveryStatusUpdate) SetState(v notification.EventDeliveryStatusState) *NotificationEventDeliveryStatusUpdate { + _u.mutation.SetState(v) + return _u +} + +// SetNillableState sets the "state" field if the given value is not nil. +func (_u *NotificationEventDeliveryStatusUpdate) SetNillableState(v *notification.EventDeliveryStatusState) *NotificationEventDeliveryStatusUpdate { + if v != nil { + _u.SetState(*v) + } + return _u +} + +// SetReason sets the "reason" field. +func (_u *NotificationEventDeliveryStatusUpdate) SetReason(v string) *NotificationEventDeliveryStatusUpdate { + _u.mutation.SetReason(v) + return _u +} + +// SetNillableReason sets the "reason" field if the given value is not nil. +func (_u *NotificationEventDeliveryStatusUpdate) SetNillableReason(v *string) *NotificationEventDeliveryStatusUpdate { + if v != nil { + _u.SetReason(*v) + } + return _u +} + +// ClearReason clears the value of the "reason" field. +func (_u *NotificationEventDeliveryStatusUpdate) ClearReason() *NotificationEventDeliveryStatusUpdate { + _u.mutation.ClearReason() + return _u +} + +// SetNextAttemptAt sets the "next_attempt_at" field. +func (_u *NotificationEventDeliveryStatusUpdate) SetNextAttemptAt(v time.Time) *NotificationEventDeliveryStatusUpdate { + _u.mutation.SetNextAttemptAt(v) + return _u +} + +// SetNillableNextAttemptAt sets the "next_attempt_at" field if the given value is not nil. +func (_u *NotificationEventDeliveryStatusUpdate) SetNillableNextAttemptAt(v *time.Time) *NotificationEventDeliveryStatusUpdate { + if v != nil { + _u.SetNextAttemptAt(*v) + } + return _u +} + +// ClearNextAttemptAt clears the value of the "next_attempt_at" field. +func (_u *NotificationEventDeliveryStatusUpdate) ClearNextAttemptAt() *NotificationEventDeliveryStatusUpdate { + _u.mutation.ClearNextAttemptAt() + return _u +} + +// SetAttempts sets the "attempts" field. +func (_u *NotificationEventDeliveryStatusUpdate) SetAttempts(v []notification.EventDeliveryAttempt) *NotificationEventDeliveryStatusUpdate { + _u.mutation.SetAttempts(v) + return _u +} + +// AppendAttempts appends value to the "attempts" field. +func (_u *NotificationEventDeliveryStatusUpdate) AppendAttempts(v []notification.EventDeliveryAttempt) *NotificationEventDeliveryStatusUpdate { + _u.mutation.AppendAttempts(v) + return _u +} + +// ClearAttempts clears the value of the "attempts" field. +func (_u *NotificationEventDeliveryStatusUpdate) ClearAttempts() *NotificationEventDeliveryStatusUpdate { + _u.mutation.ClearAttempts() + return _u +} + +// AddEventIDs adds the "events" edge to the NotificationEvent entity by IDs. +func (_u *NotificationEventDeliveryStatusUpdate) AddEventIDs(ids ...string) *NotificationEventDeliveryStatusUpdate { + _u.mutation.AddEventIDs(ids...) + return _u +} + +// AddEvents adds the "events" edges to the NotificationEvent entity. +func (_u *NotificationEventDeliveryStatusUpdate) AddEvents(v ...*NotificationEvent) *NotificationEventDeliveryStatusUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddEventIDs(ids...) +} + +// Mutation returns the NotificationEventDeliveryStatusMutation object of the builder. +func (_u *NotificationEventDeliveryStatusUpdate) Mutation() *NotificationEventDeliveryStatusMutation { + return _u.mutation +} + +// ClearEvents clears all "events" edges to the NotificationEvent entity. +func (_u *NotificationEventDeliveryStatusUpdate) ClearEvents() *NotificationEventDeliveryStatusUpdate { + _u.mutation.ClearEvents() + return _u +} + +// RemoveEventIDs removes the "events" edge to NotificationEvent entities by IDs. +func (_u *NotificationEventDeliveryStatusUpdate) RemoveEventIDs(ids ...string) *NotificationEventDeliveryStatusUpdate { + _u.mutation.RemoveEventIDs(ids...) + return _u +} + +// RemoveEvents removes "events" edges to NotificationEvent entities. +func (_u *NotificationEventDeliveryStatusUpdate) RemoveEvents(v ...*NotificationEvent) *NotificationEventDeliveryStatusUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveEventIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *NotificationEventDeliveryStatusUpdate) 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 *NotificationEventDeliveryStatusUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *NotificationEventDeliveryStatusUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *NotificationEventDeliveryStatusUpdate) 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 *NotificationEventDeliveryStatusUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := notificationeventdeliverystatus.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *NotificationEventDeliveryStatusUpdate) check() error { + if v, ok := _u.mutation.State(); ok { + if err := notificationeventdeliverystatus.StateValidator(v); err != nil { + return &ValidationError{Name: "state", err: fmt.Errorf(`db: validator failed for field "NotificationEventDeliveryStatus.state": %w`, err)} + } + } + return nil +} + +func (_u *NotificationEventDeliveryStatusUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(notificationeventdeliverystatus.Table, notificationeventdeliverystatus.Columns, sqlgraph.NewFieldSpec(notificationeventdeliverystatus.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.Annotations(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(notificationeventdeliverystatus.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.State(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldState, field.TypeEnum, value) + } + if value, ok := _u.mutation.Reason(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldReason, field.TypeString, value) + } + if _u.mutation.ReasonCleared() { + _spec.ClearField(notificationeventdeliverystatus.FieldReason, field.TypeString) + } + if value, ok := _u.mutation.NextAttemptAt(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldNextAttemptAt, field.TypeTime, value) + } + if _u.mutation.NextAttemptAtCleared() { + _spec.ClearField(notificationeventdeliverystatus.FieldNextAttemptAt, field.TypeTime) + } + if value, ok := _u.mutation.Attempts(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldAttempts, field.TypeJSON, value) + } + if value, ok := _u.mutation.AppendedAttempts(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, notificationeventdeliverystatus.FieldAttempts, value) + }) + } + if _u.mutation.AttemptsCleared() { + _spec.ClearField(notificationeventdeliverystatus.FieldAttempts, field.TypeJSON) + } + if _u.mutation.EventsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: notificationeventdeliverystatus.EventsTable, + Columns: notificationeventdeliverystatus.EventsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationevent.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedEventsIDs(); len(nodes) > 0 && !_u.mutation.EventsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: notificationeventdeliverystatus.EventsTable, + Columns: notificationeventdeliverystatus.EventsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationevent.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.EventsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: notificationeventdeliverystatus.EventsTable, + Columns: notificationeventdeliverystatus.EventsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationevent.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{notificationeventdeliverystatus.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// NotificationEventDeliveryStatusUpdateOne is the builder for updating a single NotificationEventDeliveryStatus entity. +type NotificationEventDeliveryStatusUpdateOne struct { + config + fields []string + hooks []Hook + mutation *NotificationEventDeliveryStatusMutation +} + +// SetAnnotations sets the "annotations" field. +func (_u *NotificationEventDeliveryStatusUpdateOne) SetAnnotations(v models.Annotations) *NotificationEventDeliveryStatusUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *NotificationEventDeliveryStatusUpdateOne) ClearAnnotations() *NotificationEventDeliveryStatusUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *NotificationEventDeliveryStatusUpdateOne) SetUpdatedAt(v time.Time) *NotificationEventDeliveryStatusUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetState sets the "state" field. +func (_u *NotificationEventDeliveryStatusUpdateOne) SetState(v notification.EventDeliveryStatusState) *NotificationEventDeliveryStatusUpdateOne { + _u.mutation.SetState(v) + return _u +} + +// SetNillableState sets the "state" field if the given value is not nil. +func (_u *NotificationEventDeliveryStatusUpdateOne) SetNillableState(v *notification.EventDeliveryStatusState) *NotificationEventDeliveryStatusUpdateOne { + if v != nil { + _u.SetState(*v) + } + return _u +} + +// SetReason sets the "reason" field. +func (_u *NotificationEventDeliveryStatusUpdateOne) SetReason(v string) *NotificationEventDeliveryStatusUpdateOne { + _u.mutation.SetReason(v) + return _u +} + +// SetNillableReason sets the "reason" field if the given value is not nil. +func (_u *NotificationEventDeliveryStatusUpdateOne) SetNillableReason(v *string) *NotificationEventDeliveryStatusUpdateOne { + if v != nil { + _u.SetReason(*v) + } + return _u +} + +// ClearReason clears the value of the "reason" field. +func (_u *NotificationEventDeliveryStatusUpdateOne) ClearReason() *NotificationEventDeliveryStatusUpdateOne { + _u.mutation.ClearReason() + return _u +} + +// SetNextAttemptAt sets the "next_attempt_at" field. +func (_u *NotificationEventDeliveryStatusUpdateOne) SetNextAttemptAt(v time.Time) *NotificationEventDeliveryStatusUpdateOne { + _u.mutation.SetNextAttemptAt(v) + return _u +} + +// SetNillableNextAttemptAt sets the "next_attempt_at" field if the given value is not nil. +func (_u *NotificationEventDeliveryStatusUpdateOne) SetNillableNextAttemptAt(v *time.Time) *NotificationEventDeliveryStatusUpdateOne { + if v != nil { + _u.SetNextAttemptAt(*v) + } + return _u +} + +// ClearNextAttemptAt clears the value of the "next_attempt_at" field. +func (_u *NotificationEventDeliveryStatusUpdateOne) ClearNextAttemptAt() *NotificationEventDeliveryStatusUpdateOne { + _u.mutation.ClearNextAttemptAt() + return _u +} + +// SetAttempts sets the "attempts" field. +func (_u *NotificationEventDeliveryStatusUpdateOne) SetAttempts(v []notification.EventDeliveryAttempt) *NotificationEventDeliveryStatusUpdateOne { + _u.mutation.SetAttempts(v) + return _u +} + +// AppendAttempts appends value to the "attempts" field. +func (_u *NotificationEventDeliveryStatusUpdateOne) AppendAttempts(v []notification.EventDeliveryAttempt) *NotificationEventDeliveryStatusUpdateOne { + _u.mutation.AppendAttempts(v) + return _u +} + +// ClearAttempts clears the value of the "attempts" field. +func (_u *NotificationEventDeliveryStatusUpdateOne) ClearAttempts() *NotificationEventDeliveryStatusUpdateOne { + _u.mutation.ClearAttempts() + return _u +} + +// AddEventIDs adds the "events" edge to the NotificationEvent entity by IDs. +func (_u *NotificationEventDeliveryStatusUpdateOne) AddEventIDs(ids ...string) *NotificationEventDeliveryStatusUpdateOne { + _u.mutation.AddEventIDs(ids...) + return _u +} + +// AddEvents adds the "events" edges to the NotificationEvent entity. +func (_u *NotificationEventDeliveryStatusUpdateOne) AddEvents(v ...*NotificationEvent) *NotificationEventDeliveryStatusUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddEventIDs(ids...) +} + +// Mutation returns the NotificationEventDeliveryStatusMutation object of the builder. +func (_u *NotificationEventDeliveryStatusUpdateOne) Mutation() *NotificationEventDeliveryStatusMutation { + return _u.mutation +} + +// ClearEvents clears all "events" edges to the NotificationEvent entity. +func (_u *NotificationEventDeliveryStatusUpdateOne) ClearEvents() *NotificationEventDeliveryStatusUpdateOne { + _u.mutation.ClearEvents() + return _u +} + +// RemoveEventIDs removes the "events" edge to NotificationEvent entities by IDs. +func (_u *NotificationEventDeliveryStatusUpdateOne) RemoveEventIDs(ids ...string) *NotificationEventDeliveryStatusUpdateOne { + _u.mutation.RemoveEventIDs(ids...) + return _u +} + +// RemoveEvents removes "events" edges to NotificationEvent entities. +func (_u *NotificationEventDeliveryStatusUpdateOne) RemoveEvents(v ...*NotificationEvent) *NotificationEventDeliveryStatusUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveEventIDs(ids...) +} + +// Where appends a list predicates to the NotificationEventDeliveryStatusUpdate builder. +func (_u *NotificationEventDeliveryStatusUpdateOne) Where(ps ...predicate.NotificationEventDeliveryStatus) *NotificationEventDeliveryStatusUpdateOne { + _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 *NotificationEventDeliveryStatusUpdateOne) Select(field string, fields ...string) *NotificationEventDeliveryStatusUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated NotificationEventDeliveryStatus entity. +func (_u *NotificationEventDeliveryStatusUpdateOne) Save(ctx context.Context) (*NotificationEventDeliveryStatus, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *NotificationEventDeliveryStatusUpdateOne) SaveX(ctx context.Context) *NotificationEventDeliveryStatus { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *NotificationEventDeliveryStatusUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *NotificationEventDeliveryStatusUpdateOne) 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 *NotificationEventDeliveryStatusUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := notificationeventdeliverystatus.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *NotificationEventDeliveryStatusUpdateOne) check() error { + if v, ok := _u.mutation.State(); ok { + if err := notificationeventdeliverystatus.StateValidator(v); err != nil { + return &ValidationError{Name: "state", err: fmt.Errorf(`db: validator failed for field "NotificationEventDeliveryStatus.state": %w`, err)} + } + } + return nil +} + +func (_u *NotificationEventDeliveryStatusUpdateOne) sqlSave(ctx context.Context) (_node *NotificationEventDeliveryStatus, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(notificationeventdeliverystatus.Table, notificationeventdeliverystatus.Columns, sqlgraph.NewFieldSpec(notificationeventdeliverystatus.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "NotificationEventDeliveryStatus.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, notificationeventdeliverystatus.FieldID) + for _, f := range fields { + if !notificationeventdeliverystatus.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != notificationeventdeliverystatus.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.Annotations(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(notificationeventdeliverystatus.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.State(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldState, field.TypeEnum, value) + } + if value, ok := _u.mutation.Reason(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldReason, field.TypeString, value) + } + if _u.mutation.ReasonCleared() { + _spec.ClearField(notificationeventdeliverystatus.FieldReason, field.TypeString) + } + if value, ok := _u.mutation.NextAttemptAt(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldNextAttemptAt, field.TypeTime, value) + } + if _u.mutation.NextAttemptAtCleared() { + _spec.ClearField(notificationeventdeliverystatus.FieldNextAttemptAt, field.TypeTime) + } + if value, ok := _u.mutation.Attempts(); ok { + _spec.SetField(notificationeventdeliverystatus.FieldAttempts, field.TypeJSON, value) + } + if value, ok := _u.mutation.AppendedAttempts(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, notificationeventdeliverystatus.FieldAttempts, value) + }) + } + if _u.mutation.AttemptsCleared() { + _spec.ClearField(notificationeventdeliverystatus.FieldAttempts, field.TypeJSON) + } + if _u.mutation.EventsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: notificationeventdeliverystatus.EventsTable, + Columns: notificationeventdeliverystatus.EventsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationevent.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedEventsIDs(); len(nodes) > 0 && !_u.mutation.EventsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: notificationeventdeliverystatus.EventsTable, + Columns: notificationeventdeliverystatus.EventsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationevent.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.EventsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: notificationeventdeliverystatus.EventsTable, + Columns: notificationeventdeliverystatus.EventsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationevent.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &NotificationEventDeliveryStatus{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{notificationeventdeliverystatus.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/ent/db/notificationrule.go b/ent/db/notificationrule.go new file mode 100644 index 0000000000000000000000000000000000000000..a6a7a38fc5b809cec1ba762feefff4cdf0f0b8ea --- /dev/null +++ b/ent/db/notificationrule.go @@ -0,0 +1,261 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/notificationrule" + "github.com/openmeterio/openmeter/openmeter/notification" + "github.com/openmeterio/openmeter/pkg/models" +) + +// NotificationRule is the model entity for the NotificationRule schema. +type NotificationRule 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"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,omitempty"` + // Metadata holds the value of the "metadata" field. + Metadata map[string]string `json:"metadata,omitempty"` + // The event type the rule associated with + Type notification.EventType `json:"type,omitempty"` + // The name of the rule + Name string `json:"name,omitempty"` + // Whether the rule is disabled or not + Disabled bool `json:"disabled,omitempty"` + // Config holds the value of the "config" field. + Config notification.RuleConfig `json:"config,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the NotificationRuleQuery when eager-loading is set. + Edges NotificationRuleEdges `json:"edges"` + selectValues sql.SelectValues +} + +// NotificationRuleEdges holds the relations/edges for other nodes in the graph. +type NotificationRuleEdges struct { + // Channels holds the value of the channels edge. + Channels []*NotificationChannel `json:"channels,omitempty"` + // Events holds the value of the events edge. + Events []*NotificationEvent `json:"events,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// ChannelsOrErr returns the Channels value or an error if the edge +// was not loaded in eager-loading. +func (e NotificationRuleEdges) ChannelsOrErr() ([]*NotificationChannel, error) { + if e.loadedTypes[0] { + return e.Channels, nil + } + return nil, &NotLoadedError{edge: "channels"} +} + +// EventsOrErr returns the Events value or an error if the edge +// was not loaded in eager-loading. +func (e NotificationRuleEdges) EventsOrErr() ([]*NotificationEvent, error) { + if e.loadedTypes[1] { + return e.Events, nil + } + return nil, &NotLoadedError{edge: "events"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*NotificationRule) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case notificationrule.FieldAnnotations, notificationrule.FieldMetadata: + values[i] = new([]byte) + case notificationrule.FieldDisabled: + values[i] = new(sql.NullBool) + case notificationrule.FieldID, notificationrule.FieldNamespace, notificationrule.FieldType, notificationrule.FieldName: + values[i] = new(sql.NullString) + case notificationrule.FieldCreatedAt, notificationrule.FieldUpdatedAt, notificationrule.FieldDeletedAt: + values[i] = new(sql.NullTime) + case notificationrule.FieldConfig: + values[i] = notificationrule.ValueScanner.Config.ScanValue() + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the NotificationRule fields. +func (_m *NotificationRule) 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 notificationrule.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 notificationrule.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 notificationrule.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 notificationrule.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 notificationrule.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 notificationrule.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 notificationrule.FieldMetadata: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field metadata", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Metadata); err != nil { + return fmt.Errorf("unmarshal field metadata: %w", err) + } + } + case notificationrule.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 = notification.EventType(value.String) + } + case notificationrule.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case notificationrule.FieldDisabled: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field disabled", values[i]) + } else if value.Valid { + _m.Disabled = value.Bool + } + case notificationrule.FieldConfig: + if value, err := notificationrule.ValueScanner.Config.FromValue(values[i]); err != nil { + return err + } else { + _m.Config = value + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the NotificationRule. +// This includes values selected through modifiers, order, etc. +func (_m *NotificationRule) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryChannels queries the "channels" edge of the NotificationRule entity. +func (_m *NotificationRule) QueryChannels() *NotificationChannelQuery { + return NewNotificationRuleClient(_m.config).QueryChannels(_m) +} + +// QueryEvents queries the "events" edge of the NotificationRule entity. +func (_m *NotificationRule) QueryEvents() *NotificationEventQuery { + return NewNotificationRuleClient(_m.config).QueryEvents(_m) +} + +// Update returns a builder for updating this NotificationRule. +// Note that you need to call NotificationRule.Unwrap() before calling this method if this NotificationRule +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *NotificationRule) Update() *NotificationRuleUpdateOne { + return NewNotificationRuleClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the NotificationRule 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 *NotificationRule) Unwrap() *NotificationRule { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: NotificationRule is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *NotificationRule) String() string { + var builder strings.Builder + builder.WriteString("NotificationRule(") + 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("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + builder.WriteString(", ") + builder.WriteString("metadata=") + builder.WriteString(fmt.Sprintf("%v", _m.Metadata)) + builder.WriteString(", ") + builder.WriteString("type=") + builder.WriteString(fmt.Sprintf("%v", _m.Type)) + builder.WriteString(", ") + builder.WriteString("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + builder.WriteString("disabled=") + builder.WriteString(fmt.Sprintf("%v", _m.Disabled)) + builder.WriteString(", ") + builder.WriteString("config=") + builder.WriteString(fmt.Sprintf("%v", _m.Config)) + builder.WriteByte(')') + return builder.String() +} + +// NotificationRules is a parsable slice of NotificationRule. +type NotificationRules []*NotificationRule diff --git a/ent/db/notificationrule/notificationrule.go b/ent/db/notificationrule/notificationrule.go new file mode 100644 index 0000000000000000000000000000000000000000..1322ea3420d4ac44707e0b8f6feacf6a62b646ab --- /dev/null +++ b/ent/db/notificationrule/notificationrule.go @@ -0,0 +1,210 @@ +// Code generated by ent, DO NOT EDIT. + +package notificationrule + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/notification" +) + +const ( + // Label holds the string label denoting the notificationrule type in the database. + Label = "notification_rule" + // 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" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // FieldType holds the string denoting the type field in the database. + FieldType = "type" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDisabled holds the string denoting the disabled field in the database. + FieldDisabled = "disabled" + // FieldConfig holds the string denoting the config field in the database. + FieldConfig = "config" + // EdgeChannels holds the string denoting the channels edge name in mutations. + EdgeChannels = "channels" + // EdgeEvents holds the string denoting the events edge name in mutations. + EdgeEvents = "events" + // Table holds the table name of the notificationrule in the database. + Table = "notification_rules" + // ChannelsTable is the table that holds the channels relation/edge. The primary key declared below. + ChannelsTable = "notification_channel_rules" + // ChannelsInverseTable is the table name for the NotificationChannel entity. + // It exists in this package in order to avoid circular dependency with the "notificationchannel" package. + ChannelsInverseTable = "notification_channels" + // EventsTable is the table that holds the events relation/edge. + EventsTable = "notification_events" + // EventsInverseTable is the table name for the NotificationEvent entity. + // It exists in this package in order to avoid circular dependency with the "notificationevent" package. + EventsInverseTable = "notification_events" + // EventsColumn is the table column denoting the events relation/edge. + EventsColumn = "rule_id" +) + +// Columns holds all SQL columns for notificationrule fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldAnnotations, + FieldMetadata, + FieldType, + FieldName, + FieldDisabled, + FieldConfig, +} + +var ( + // ChannelsPrimaryKey and ChannelsColumn2 are the table columns denoting the + // primary key for the channels relation (M2M). + ChannelsPrimaryKey = []string{"notification_channel_id", "notification_rule_id"} +) + +// 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 + // NameValidator is a validator for the "name" field. It is called by the builders before save. + NameValidator func(string) error + // DefaultDisabled holds the default value on creation for the "disabled" field. + DefaultDisabled bool + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string + // ValueScanner of all NotificationRule fields. + ValueScanner struct { + Config field.TypeValueScanner[notification.RuleConfig] + } +) + +// TypeValidator is a validator for the "type" field enum values. It is called by the builders before save. +func TypeValidator(_type notification.EventType) error { + switch _type.String() { + case "entitlements.balance.threshold", "entitlements.reset", "invoice.created", "invoice.updated": + return nil + default: + return fmt.Errorf("notificationrule: invalid enum value for type field: %q", _type) + } +} + +// OrderOption defines the ordering options for the NotificationRule 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() +} + +// ByType orders the results by the type field. +func ByType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldType, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDisabled orders the results by the disabled field. +func ByDisabled(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDisabled, opts...).ToFunc() +} + +// ByConfig orders the results by the config field. +func ByConfig(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldConfig, opts...).ToFunc() +} + +// ByChannelsCount orders the results by channels count. +func ByChannelsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newChannelsStep(), opts...) + } +} + +// ByChannels orders the results by channels terms. +func ByChannels(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newChannelsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByEventsCount orders the results by events count. +func ByEventsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newEventsStep(), opts...) + } +} + +// ByEvents orders the results by events terms. +func ByEvents(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newEventsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newChannelsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ChannelsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, ChannelsTable, ChannelsPrimaryKey...), + ) +} +func newEventsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(EventsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, EventsTable, EventsColumn), + ) +} diff --git a/ent/db/notificationrule/where.go b/ent/db/notificationrule/where.go new file mode 100644 index 0000000000000000000000000000000000000000..200747ec1d0921513244b4d1261a8cc2729184ab --- /dev/null +++ b/ent/db/notificationrule/where.go @@ -0,0 +1,488 @@ +// Code generated by ent, DO NOT EDIT. + +package notificationrule + +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/notification" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.NotificationRule { + return predicate.NotificationRule(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.NotificationRule { + return predicate.NotificationRule(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.NotificationRule { + return predicate.NotificationRule(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.NotificationRule { + return predicate.NotificationRule(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldEQ(FieldName, v)) +} + +// Disabled applies equality check predicate on the "disabled" field. It's identical to DisabledEQ. +func Disabled(v bool) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldEQ(FieldDisabled, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldNotNull(FieldDeletedAt)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldNotNull(FieldAnnotations)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldNotNull(FieldMetadata)) +} + +// TypeEQ applies the EQ predicate on the "type" field. +func TypeEQ(v notification.EventType) predicate.NotificationRule { + vc := v + return predicate.NotificationRule(sql.FieldEQ(FieldType, vc)) +} + +// TypeNEQ applies the NEQ predicate on the "type" field. +func TypeNEQ(v notification.EventType) predicate.NotificationRule { + vc := v + return predicate.NotificationRule(sql.FieldNEQ(FieldType, vc)) +} + +// TypeIn applies the In predicate on the "type" field. +func TypeIn(vs ...notification.EventType) predicate.NotificationRule { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.NotificationRule(sql.FieldIn(FieldType, v...)) +} + +// TypeNotIn applies the NotIn predicate on the "type" field. +func TypeNotIn(vs ...notification.EventType) predicate.NotificationRule { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.NotificationRule(sql.FieldNotIn(FieldType, v...)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldContainsFold(FieldName, v)) +} + +// DisabledEQ applies the EQ predicate on the "disabled" field. +func DisabledEQ(v bool) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldEQ(FieldDisabled, v)) +} + +// DisabledNEQ applies the NEQ predicate on the "disabled" field. +func DisabledNEQ(v bool) predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldNEQ(FieldDisabled, v)) +} + +// DisabledIsNil applies the IsNil predicate on the "disabled" field. +func DisabledIsNil() predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldIsNull(FieldDisabled)) +} + +// DisabledNotNil applies the NotNil predicate on the "disabled" field. +func DisabledNotNil() predicate.NotificationRule { + return predicate.NotificationRule(sql.FieldNotNull(FieldDisabled)) +} + +// HasChannels applies the HasEdge predicate on the "channels" edge. +func HasChannels() predicate.NotificationRule { + return predicate.NotificationRule(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, ChannelsTable, ChannelsPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasChannelsWith applies the HasEdge predicate on the "channels" edge with a given conditions (other predicates). +func HasChannelsWith(preds ...predicate.NotificationChannel) predicate.NotificationRule { + return predicate.NotificationRule(func(s *sql.Selector) { + step := newChannelsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasEvents applies the HasEdge predicate on the "events" edge. +func HasEvents() predicate.NotificationRule { + return predicate.NotificationRule(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, EventsTable, EventsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasEventsWith applies the HasEdge predicate on the "events" edge with a given conditions (other predicates). +func HasEventsWith(preds ...predicate.NotificationEvent) predicate.NotificationRule { + return predicate.NotificationRule(func(s *sql.Selector) { + step := newEventsStep() + 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.NotificationRule) predicate.NotificationRule { + return predicate.NotificationRule(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.NotificationRule) predicate.NotificationRule { + return predicate.NotificationRule(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.NotificationRule) predicate.NotificationRule { + return predicate.NotificationRule(sql.NotPredicates(p)) +} diff --git a/ent/db/notificationrule_create.go b/ent/db/notificationrule_create.go new file mode 100644 index 0000000000000000000000000000000000000000..1baa2e1648be9d17c499f52058309cc5c99c5439 --- /dev/null +++ b/ent/db/notificationrule_create.go @@ -0,0 +1,1091 @@ +// 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/notificationchannel" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationevent" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationrule" + "github.com/openmeterio/openmeter/openmeter/notification" + "github.com/openmeterio/openmeter/pkg/models" +) + +// NotificationRuleCreate is the builder for creating a NotificationRule entity. +type NotificationRuleCreate struct { + config + mutation *NotificationRuleMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *NotificationRuleCreate) SetNamespace(v string) *NotificationRuleCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *NotificationRuleCreate) SetCreatedAt(v time.Time) *NotificationRuleCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *NotificationRuleCreate) SetNillableCreatedAt(v *time.Time) *NotificationRuleCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *NotificationRuleCreate) SetUpdatedAt(v time.Time) *NotificationRuleCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *NotificationRuleCreate) SetNillableUpdatedAt(v *time.Time) *NotificationRuleCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *NotificationRuleCreate) SetDeletedAt(v time.Time) *NotificationRuleCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *NotificationRuleCreate) SetNillableDeletedAt(v *time.Time) *NotificationRuleCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *NotificationRuleCreate) SetAnnotations(v models.Annotations) *NotificationRuleCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetMetadata sets the "metadata" field. +func (_c *NotificationRuleCreate) SetMetadata(v map[string]string) *NotificationRuleCreate { + _c.mutation.SetMetadata(v) + return _c +} + +// SetType sets the "type" field. +func (_c *NotificationRuleCreate) SetType(v notification.EventType) *NotificationRuleCreate { + _c.mutation.SetType(v) + return _c +} + +// SetName sets the "name" field. +func (_c *NotificationRuleCreate) SetName(v string) *NotificationRuleCreate { + _c.mutation.SetName(v) + return _c +} + +// SetDisabled sets the "disabled" field. +func (_c *NotificationRuleCreate) SetDisabled(v bool) *NotificationRuleCreate { + _c.mutation.SetDisabled(v) + return _c +} + +// SetNillableDisabled sets the "disabled" field if the given value is not nil. +func (_c *NotificationRuleCreate) SetNillableDisabled(v *bool) *NotificationRuleCreate { + if v != nil { + _c.SetDisabled(*v) + } + return _c +} + +// SetConfig sets the "config" field. +func (_c *NotificationRuleCreate) SetConfig(v notification.RuleConfig) *NotificationRuleCreate { + _c.mutation.SetConfig(v) + return _c +} + +// SetID sets the "id" field. +func (_c *NotificationRuleCreate) SetID(v string) *NotificationRuleCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *NotificationRuleCreate) SetNillableID(v *string) *NotificationRuleCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// AddChannelIDs adds the "channels" edge to the NotificationChannel entity by IDs. +func (_c *NotificationRuleCreate) AddChannelIDs(ids ...string) *NotificationRuleCreate { + _c.mutation.AddChannelIDs(ids...) + return _c +} + +// AddChannels adds the "channels" edges to the NotificationChannel entity. +func (_c *NotificationRuleCreate) AddChannels(v ...*NotificationChannel) *NotificationRuleCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddChannelIDs(ids...) +} + +// AddEventIDs adds the "events" edge to the NotificationEvent entity by IDs. +func (_c *NotificationRuleCreate) AddEventIDs(ids ...string) *NotificationRuleCreate { + _c.mutation.AddEventIDs(ids...) + return _c +} + +// AddEvents adds the "events" edges to the NotificationEvent entity. +func (_c *NotificationRuleCreate) AddEvents(v ...*NotificationEvent) *NotificationRuleCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddEventIDs(ids...) +} + +// Mutation returns the NotificationRuleMutation object of the builder. +func (_c *NotificationRuleCreate) Mutation() *NotificationRuleMutation { + return _c.mutation +} + +// Save creates the NotificationRule in the database. +func (_c *NotificationRuleCreate) Save(ctx context.Context) (*NotificationRule, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *NotificationRuleCreate) SaveX(ctx context.Context) *NotificationRule { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *NotificationRuleCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *NotificationRuleCreate) 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 *NotificationRuleCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := notificationrule.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := notificationrule.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.Disabled(); !ok { + v := notificationrule.DefaultDisabled + _c.mutation.SetDisabled(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := notificationrule.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *NotificationRuleCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "NotificationRule.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := notificationrule.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "NotificationRule.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "NotificationRule.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "NotificationRule.updated_at"`)} + } + if _, ok := _c.mutation.GetType(); !ok { + return &ValidationError{Name: "type", err: errors.New(`db: missing required field "NotificationRule.type"`)} + } + if v, ok := _c.mutation.GetType(); ok { + if err := notificationrule.TypeValidator(v); err != nil { + return &ValidationError{Name: "type", err: fmt.Errorf(`db: validator failed for field "NotificationRule.type": %w`, err)} + } + } + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "NotificationRule.name"`)} + } + if v, ok := _c.mutation.Name(); ok { + if err := notificationrule.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "NotificationRule.name": %w`, err)} + } + } + if _, ok := _c.mutation.Config(); !ok { + return &ValidationError{Name: "config", err: errors.New(`db: missing required field "NotificationRule.config"`)} + } + if v, ok := _c.mutation.Config(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "config", err: fmt.Errorf(`db: validator failed for field "NotificationRule.config": %w`, err)} + } + } + return nil +} + +func (_c *NotificationRuleCreate) sqlSave(ctx context.Context) (*NotificationRule, 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 NotificationRule.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *NotificationRuleCreate) createSpec() (*NotificationRule, *sqlgraph.CreateSpec, error) { + var ( + _node = &NotificationRule{config: _c.config} + _spec = sqlgraph.NewCreateSpec(notificationrule.Table, sqlgraph.NewFieldSpec(notificationrule.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(notificationrule.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(notificationrule.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(notificationrule.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(notificationrule.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(notificationrule.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.Metadata(); ok { + _spec.SetField(notificationrule.FieldMetadata, field.TypeJSON, value) + _node.Metadata = value + } + if value, ok := _c.mutation.GetType(); ok { + _spec.SetField(notificationrule.FieldType, field.TypeEnum, value) + _node.Type = value + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(notificationrule.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Disabled(); ok { + _spec.SetField(notificationrule.FieldDisabled, field.TypeBool, value) + _node.Disabled = value + } + if value, ok := _c.mutation.Config(); ok { + vv, err := notificationrule.ValueScanner.Config.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(notificationrule.FieldConfig, field.TypeString, vv) + _node.Config = value + } + if nodes := _c.mutation.ChannelsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: notificationrule.ChannelsTable, + Columns: notificationrule.ChannelsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationchannel.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.EventsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: notificationrule.EventsTable, + Columns: []string{notificationrule.EventsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationevent.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.NotificationRule.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.NotificationRuleUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *NotificationRuleCreate) OnConflict(opts ...sql.ConflictOption) *NotificationRuleUpsertOne { + _c.conflict = opts + return &NotificationRuleUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.NotificationRule.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *NotificationRuleCreate) OnConflictColumns(columns ...string) *NotificationRuleUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &NotificationRuleUpsertOne{ + create: _c, + } +} + +type ( + // NotificationRuleUpsertOne is the builder for "upsert"-ing + // one NotificationRule node. + NotificationRuleUpsertOne struct { + create *NotificationRuleCreate + } + + // NotificationRuleUpsert is the "OnConflict" setter. + NotificationRuleUpsert struct { + *sql.UpdateSet + } +) + +// SetUpdatedAt sets the "updated_at" field. +func (u *NotificationRuleUpsert) SetUpdatedAt(v time.Time) *NotificationRuleUpsert { + u.Set(notificationrule.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *NotificationRuleUpsert) UpdateUpdatedAt() *NotificationRuleUpsert { + u.SetExcluded(notificationrule.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *NotificationRuleUpsert) SetDeletedAt(v time.Time) *NotificationRuleUpsert { + u.Set(notificationrule.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *NotificationRuleUpsert) UpdateDeletedAt() *NotificationRuleUpsert { + u.SetExcluded(notificationrule.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *NotificationRuleUpsert) ClearDeletedAt() *NotificationRuleUpsert { + u.SetNull(notificationrule.FieldDeletedAt) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *NotificationRuleUpsert) SetAnnotations(v models.Annotations) *NotificationRuleUpsert { + u.Set(notificationrule.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *NotificationRuleUpsert) UpdateAnnotations() *NotificationRuleUpsert { + u.SetExcluded(notificationrule.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *NotificationRuleUpsert) ClearAnnotations() *NotificationRuleUpsert { + u.SetNull(notificationrule.FieldAnnotations) + return u +} + +// SetMetadata sets the "metadata" field. +func (u *NotificationRuleUpsert) SetMetadata(v map[string]string) *NotificationRuleUpsert { + u.Set(notificationrule.FieldMetadata, v) + return u +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *NotificationRuleUpsert) UpdateMetadata() *NotificationRuleUpsert { + u.SetExcluded(notificationrule.FieldMetadata) + return u +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *NotificationRuleUpsert) ClearMetadata() *NotificationRuleUpsert { + u.SetNull(notificationrule.FieldMetadata) + return u +} + +// SetName sets the "name" field. +func (u *NotificationRuleUpsert) SetName(v string) *NotificationRuleUpsert { + u.Set(notificationrule.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *NotificationRuleUpsert) UpdateName() *NotificationRuleUpsert { + u.SetExcluded(notificationrule.FieldName) + return u +} + +// SetDisabled sets the "disabled" field. +func (u *NotificationRuleUpsert) SetDisabled(v bool) *NotificationRuleUpsert { + u.Set(notificationrule.FieldDisabled, v) + return u +} + +// UpdateDisabled sets the "disabled" field to the value that was provided on create. +func (u *NotificationRuleUpsert) UpdateDisabled() *NotificationRuleUpsert { + u.SetExcluded(notificationrule.FieldDisabled) + return u +} + +// ClearDisabled clears the value of the "disabled" field. +func (u *NotificationRuleUpsert) ClearDisabled() *NotificationRuleUpsert { + u.SetNull(notificationrule.FieldDisabled) + return u +} + +// SetConfig sets the "config" field. +func (u *NotificationRuleUpsert) SetConfig(v notification.RuleConfig) *NotificationRuleUpsert { + u.Set(notificationrule.FieldConfig, v) + return u +} + +// UpdateConfig sets the "config" field to the value that was provided on create. +func (u *NotificationRuleUpsert) UpdateConfig() *NotificationRuleUpsert { + u.SetExcluded(notificationrule.FieldConfig) + 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.NotificationRule.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(notificationrule.FieldID) +// }), +// ). +// Exec(ctx) +func (u *NotificationRuleUpsertOne) UpdateNewValues() *NotificationRuleUpsertOne { + 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(notificationrule.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(notificationrule.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(notificationrule.FieldCreatedAt) + } + if _, exists := u.create.mutation.GetType(); exists { + s.SetIgnore(notificationrule.FieldType) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.NotificationRule.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *NotificationRuleUpsertOne) Ignore() *NotificationRuleUpsertOne { + 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 *NotificationRuleUpsertOne) DoNothing() *NotificationRuleUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the NotificationRuleCreate.OnConflict +// documentation for more info. +func (u *NotificationRuleUpsertOne) Update(set func(*NotificationRuleUpsert)) *NotificationRuleUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&NotificationRuleUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *NotificationRuleUpsertOne) SetUpdatedAt(v time.Time) *NotificationRuleUpsertOne { + return u.Update(func(s *NotificationRuleUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *NotificationRuleUpsertOne) UpdateUpdatedAt() *NotificationRuleUpsertOne { + return u.Update(func(s *NotificationRuleUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *NotificationRuleUpsertOne) SetDeletedAt(v time.Time) *NotificationRuleUpsertOne { + return u.Update(func(s *NotificationRuleUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *NotificationRuleUpsertOne) UpdateDeletedAt() *NotificationRuleUpsertOne { + return u.Update(func(s *NotificationRuleUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *NotificationRuleUpsertOne) ClearDeletedAt() *NotificationRuleUpsertOne { + return u.Update(func(s *NotificationRuleUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *NotificationRuleUpsertOne) SetAnnotations(v models.Annotations) *NotificationRuleUpsertOne { + return u.Update(func(s *NotificationRuleUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *NotificationRuleUpsertOne) UpdateAnnotations() *NotificationRuleUpsertOne { + return u.Update(func(s *NotificationRuleUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *NotificationRuleUpsertOne) ClearAnnotations() *NotificationRuleUpsertOne { + return u.Update(func(s *NotificationRuleUpsert) { + s.ClearAnnotations() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *NotificationRuleUpsertOne) SetMetadata(v map[string]string) *NotificationRuleUpsertOne { + return u.Update(func(s *NotificationRuleUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *NotificationRuleUpsertOne) UpdateMetadata() *NotificationRuleUpsertOne { + return u.Update(func(s *NotificationRuleUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *NotificationRuleUpsertOne) ClearMetadata() *NotificationRuleUpsertOne { + return u.Update(func(s *NotificationRuleUpsert) { + s.ClearMetadata() + }) +} + +// SetName sets the "name" field. +func (u *NotificationRuleUpsertOne) SetName(v string) *NotificationRuleUpsertOne { + return u.Update(func(s *NotificationRuleUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *NotificationRuleUpsertOne) UpdateName() *NotificationRuleUpsertOne { + return u.Update(func(s *NotificationRuleUpsert) { + s.UpdateName() + }) +} + +// SetDisabled sets the "disabled" field. +func (u *NotificationRuleUpsertOne) SetDisabled(v bool) *NotificationRuleUpsertOne { + return u.Update(func(s *NotificationRuleUpsert) { + s.SetDisabled(v) + }) +} + +// UpdateDisabled sets the "disabled" field to the value that was provided on create. +func (u *NotificationRuleUpsertOne) UpdateDisabled() *NotificationRuleUpsertOne { + return u.Update(func(s *NotificationRuleUpsert) { + s.UpdateDisabled() + }) +} + +// ClearDisabled clears the value of the "disabled" field. +func (u *NotificationRuleUpsertOne) ClearDisabled() *NotificationRuleUpsertOne { + return u.Update(func(s *NotificationRuleUpsert) { + s.ClearDisabled() + }) +} + +// SetConfig sets the "config" field. +func (u *NotificationRuleUpsertOne) SetConfig(v notification.RuleConfig) *NotificationRuleUpsertOne { + return u.Update(func(s *NotificationRuleUpsert) { + s.SetConfig(v) + }) +} + +// UpdateConfig sets the "config" field to the value that was provided on create. +func (u *NotificationRuleUpsertOne) UpdateConfig() *NotificationRuleUpsertOne { + return u.Update(func(s *NotificationRuleUpsert) { + s.UpdateConfig() + }) +} + +// Exec executes the query. +func (u *NotificationRuleUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for NotificationRuleCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *NotificationRuleUpsertOne) 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 *NotificationRuleUpsertOne) 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: NotificationRuleUpsertOne.ID is not supported by MySQL driver. Use NotificationRuleUpsertOne.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 *NotificationRuleUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// NotificationRuleCreateBulk is the builder for creating many NotificationRule entities in bulk. +type NotificationRuleCreateBulk struct { + config + err error + builders []*NotificationRuleCreate + conflict []sql.ConflictOption +} + +// Save creates the NotificationRule entities in the database. +func (_c *NotificationRuleCreateBulk) Save(ctx context.Context) ([]*NotificationRule, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*NotificationRule, 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.(*NotificationRuleMutation) + 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 *NotificationRuleCreateBulk) SaveX(ctx context.Context) []*NotificationRule { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *NotificationRuleCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *NotificationRuleCreateBulk) 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.NotificationRule.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.NotificationRuleUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *NotificationRuleCreateBulk) OnConflict(opts ...sql.ConflictOption) *NotificationRuleUpsertBulk { + _c.conflict = opts + return &NotificationRuleUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.NotificationRule.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *NotificationRuleCreateBulk) OnConflictColumns(columns ...string) *NotificationRuleUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &NotificationRuleUpsertBulk{ + create: _c, + } +} + +// NotificationRuleUpsertBulk is the builder for "upsert"-ing +// a bulk of NotificationRule nodes. +type NotificationRuleUpsertBulk struct { + create *NotificationRuleCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.NotificationRule.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(notificationrule.FieldID) +// }), +// ). +// Exec(ctx) +func (u *NotificationRuleUpsertBulk) UpdateNewValues() *NotificationRuleUpsertBulk { + 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(notificationrule.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(notificationrule.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(notificationrule.FieldCreatedAt) + } + if _, exists := b.mutation.GetType(); exists { + s.SetIgnore(notificationrule.FieldType) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.NotificationRule.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *NotificationRuleUpsertBulk) Ignore() *NotificationRuleUpsertBulk { + 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 *NotificationRuleUpsertBulk) DoNothing() *NotificationRuleUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the NotificationRuleCreateBulk.OnConflict +// documentation for more info. +func (u *NotificationRuleUpsertBulk) Update(set func(*NotificationRuleUpsert)) *NotificationRuleUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&NotificationRuleUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *NotificationRuleUpsertBulk) SetUpdatedAt(v time.Time) *NotificationRuleUpsertBulk { + return u.Update(func(s *NotificationRuleUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *NotificationRuleUpsertBulk) UpdateUpdatedAt() *NotificationRuleUpsertBulk { + return u.Update(func(s *NotificationRuleUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *NotificationRuleUpsertBulk) SetDeletedAt(v time.Time) *NotificationRuleUpsertBulk { + return u.Update(func(s *NotificationRuleUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *NotificationRuleUpsertBulk) UpdateDeletedAt() *NotificationRuleUpsertBulk { + return u.Update(func(s *NotificationRuleUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *NotificationRuleUpsertBulk) ClearDeletedAt() *NotificationRuleUpsertBulk { + return u.Update(func(s *NotificationRuleUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *NotificationRuleUpsertBulk) SetAnnotations(v models.Annotations) *NotificationRuleUpsertBulk { + return u.Update(func(s *NotificationRuleUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *NotificationRuleUpsertBulk) UpdateAnnotations() *NotificationRuleUpsertBulk { + return u.Update(func(s *NotificationRuleUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *NotificationRuleUpsertBulk) ClearAnnotations() *NotificationRuleUpsertBulk { + return u.Update(func(s *NotificationRuleUpsert) { + s.ClearAnnotations() + }) +} + +// SetMetadata sets the "metadata" field. +func (u *NotificationRuleUpsertBulk) SetMetadata(v map[string]string) *NotificationRuleUpsertBulk { + return u.Update(func(s *NotificationRuleUpsert) { + s.SetMetadata(v) + }) +} + +// UpdateMetadata sets the "metadata" field to the value that was provided on create. +func (u *NotificationRuleUpsertBulk) UpdateMetadata() *NotificationRuleUpsertBulk { + return u.Update(func(s *NotificationRuleUpsert) { + s.UpdateMetadata() + }) +} + +// ClearMetadata clears the value of the "metadata" field. +func (u *NotificationRuleUpsertBulk) ClearMetadata() *NotificationRuleUpsertBulk { + return u.Update(func(s *NotificationRuleUpsert) { + s.ClearMetadata() + }) +} + +// SetName sets the "name" field. +func (u *NotificationRuleUpsertBulk) SetName(v string) *NotificationRuleUpsertBulk { + return u.Update(func(s *NotificationRuleUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *NotificationRuleUpsertBulk) UpdateName() *NotificationRuleUpsertBulk { + return u.Update(func(s *NotificationRuleUpsert) { + s.UpdateName() + }) +} + +// SetDisabled sets the "disabled" field. +func (u *NotificationRuleUpsertBulk) SetDisabled(v bool) *NotificationRuleUpsertBulk { + return u.Update(func(s *NotificationRuleUpsert) { + s.SetDisabled(v) + }) +} + +// UpdateDisabled sets the "disabled" field to the value that was provided on create. +func (u *NotificationRuleUpsertBulk) UpdateDisabled() *NotificationRuleUpsertBulk { + return u.Update(func(s *NotificationRuleUpsert) { + s.UpdateDisabled() + }) +} + +// ClearDisabled clears the value of the "disabled" field. +func (u *NotificationRuleUpsertBulk) ClearDisabled() *NotificationRuleUpsertBulk { + return u.Update(func(s *NotificationRuleUpsert) { + s.ClearDisabled() + }) +} + +// SetConfig sets the "config" field. +func (u *NotificationRuleUpsertBulk) SetConfig(v notification.RuleConfig) *NotificationRuleUpsertBulk { + return u.Update(func(s *NotificationRuleUpsert) { + s.SetConfig(v) + }) +} + +// UpdateConfig sets the "config" field to the value that was provided on create. +func (u *NotificationRuleUpsertBulk) UpdateConfig() *NotificationRuleUpsertBulk { + return u.Update(func(s *NotificationRuleUpsert) { + s.UpdateConfig() + }) +} + +// Exec executes the query. +func (u *NotificationRuleUpsertBulk) 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 NotificationRuleCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for NotificationRuleCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *NotificationRuleUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/notificationrule_delete.go b/ent/db/notificationrule_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..5d29181dc870070c6f449a370499812398dcf2bf --- /dev/null +++ b/ent/db/notificationrule_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/notificationrule" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// NotificationRuleDelete is the builder for deleting a NotificationRule entity. +type NotificationRuleDelete struct { + config + hooks []Hook + mutation *NotificationRuleMutation +} + +// Where appends a list predicates to the NotificationRuleDelete builder. +func (_d *NotificationRuleDelete) Where(ps ...predicate.NotificationRule) *NotificationRuleDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *NotificationRuleDelete) 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 *NotificationRuleDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *NotificationRuleDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(notificationrule.Table, sqlgraph.NewFieldSpec(notificationrule.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 +} + +// NotificationRuleDeleteOne is the builder for deleting a single NotificationRule entity. +type NotificationRuleDeleteOne struct { + _d *NotificationRuleDelete +} + +// Where appends a list predicates to the NotificationRuleDelete builder. +func (_d *NotificationRuleDeleteOne) Where(ps ...predicate.NotificationRule) *NotificationRuleDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *NotificationRuleDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{notificationrule.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *NotificationRuleDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/notificationrule_query.go b/ent/db/notificationrule_query.go new file mode 100644 index 0000000000000000000000000000000000000000..d87f0609efdcb12b2d2ea07faba5a3f59cf8de1f --- /dev/null +++ b/ent/db/notificationrule_query.go @@ -0,0 +1,748 @@ +// 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/notificationchannel" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationevent" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationrule" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// NotificationRuleQuery is the builder for querying NotificationRule entities. +type NotificationRuleQuery struct { + config + ctx *QueryContext + order []notificationrule.OrderOption + inters []Interceptor + predicates []predicate.NotificationRule + withChannels *NotificationChannelQuery + withEvents *NotificationEventQuery + 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 NotificationRuleQuery builder. +func (_q *NotificationRuleQuery) Where(ps ...predicate.NotificationRule) *NotificationRuleQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *NotificationRuleQuery) Limit(limit int) *NotificationRuleQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *NotificationRuleQuery) Offset(offset int) *NotificationRuleQuery { + _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 *NotificationRuleQuery) Unique(unique bool) *NotificationRuleQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *NotificationRuleQuery) Order(o ...notificationrule.OrderOption) *NotificationRuleQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryChannels chains the current query on the "channels" edge. +func (_q *NotificationRuleQuery) QueryChannels() *NotificationChannelQuery { + query := (&NotificationChannelClient{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(notificationrule.Table, notificationrule.FieldID, selector), + sqlgraph.To(notificationchannel.Table, notificationchannel.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, notificationrule.ChannelsTable, notificationrule.ChannelsPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryEvents chains the current query on the "events" edge. +func (_q *NotificationRuleQuery) QueryEvents() *NotificationEventQuery { + query := (&NotificationEventClient{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(notificationrule.Table, notificationrule.FieldID, selector), + sqlgraph.To(notificationevent.Table, notificationevent.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, notificationrule.EventsTable, notificationrule.EventsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first NotificationRule entity from the query. +// Returns a *NotFoundError when no NotificationRule was found. +func (_q *NotificationRuleQuery) First(ctx context.Context) (*NotificationRule, 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{notificationrule.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *NotificationRuleQuery) FirstX(ctx context.Context) *NotificationRule { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first NotificationRule ID from the query. +// Returns a *NotFoundError when no NotificationRule ID was found. +func (_q *NotificationRuleQuery) 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{notificationrule.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *NotificationRuleQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single NotificationRule entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one NotificationRule entity is found. +// Returns a *NotFoundError when no NotificationRule entities are found. +func (_q *NotificationRuleQuery) Only(ctx context.Context) (*NotificationRule, 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{notificationrule.Label} + default: + return nil, &NotSingularError{notificationrule.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *NotificationRuleQuery) OnlyX(ctx context.Context) *NotificationRule { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only NotificationRule ID in the query. +// Returns a *NotSingularError when more than one NotificationRule ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *NotificationRuleQuery) 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{notificationrule.Label} + default: + err = &NotSingularError{notificationrule.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *NotificationRuleQuery) 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 NotificationRules. +func (_q *NotificationRuleQuery) All(ctx context.Context) ([]*NotificationRule, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*NotificationRule, *NotificationRuleQuery]() + return withInterceptors[[]*NotificationRule](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *NotificationRuleQuery) AllX(ctx context.Context) []*NotificationRule { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of NotificationRule IDs. +func (_q *NotificationRuleQuery) 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(notificationrule.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *NotificationRuleQuery) 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 *NotificationRuleQuery) 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[*NotificationRuleQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *NotificationRuleQuery) 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 *NotificationRuleQuery) 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 *NotificationRuleQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the NotificationRuleQuery 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 *NotificationRuleQuery) Clone() *NotificationRuleQuery { + if _q == nil { + return nil + } + return &NotificationRuleQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]notificationrule.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.NotificationRule{}, _q.predicates...), + withChannels: _q.withChannels.Clone(), + withEvents: _q.withEvents.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithChannels tells the query-builder to eager-load the nodes that are connected to +// the "channels" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *NotificationRuleQuery) WithChannels(opts ...func(*NotificationChannelQuery)) *NotificationRuleQuery { + query := (&NotificationChannelClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withChannels = query + return _q +} + +// WithEvents tells the query-builder to eager-load the nodes that are connected to +// the "events" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *NotificationRuleQuery) WithEvents(opts ...func(*NotificationEventQuery)) *NotificationRuleQuery { + query := (&NotificationEventClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withEvents = 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.NotificationRule.Query(). +// GroupBy(notificationrule.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *NotificationRuleQuery) GroupBy(field string, fields ...string) *NotificationRuleGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &NotificationRuleGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = notificationrule.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.NotificationRule.Query(). +// Select(notificationrule.FieldNamespace). +// Scan(ctx, &v) +func (_q *NotificationRuleQuery) Select(fields ...string) *NotificationRuleSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &NotificationRuleSelect{NotificationRuleQuery: _q} + sbuild.label = notificationrule.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a NotificationRuleSelect configured with the given aggregations. +func (_q *NotificationRuleQuery) Aggregate(fns ...AggregateFunc) *NotificationRuleSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *NotificationRuleQuery) 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 !notificationrule.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 *NotificationRuleQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*NotificationRule, error) { + var ( + nodes = []*NotificationRule{} + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withChannels != nil, + _q.withEvents != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*NotificationRule).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &NotificationRule{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.withChannels; query != nil { + if err := _q.loadChannels(ctx, query, nodes, + func(n *NotificationRule) { n.Edges.Channels = []*NotificationChannel{} }, + func(n *NotificationRule, e *NotificationChannel) { n.Edges.Channels = append(n.Edges.Channels, e) }); err != nil { + return nil, err + } + } + if query := _q.withEvents; query != nil { + if err := _q.loadEvents(ctx, query, nodes, + func(n *NotificationRule) { n.Edges.Events = []*NotificationEvent{} }, + func(n *NotificationRule, e *NotificationEvent) { n.Edges.Events = append(n.Edges.Events, e) }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *NotificationRuleQuery) loadChannels(ctx context.Context, query *NotificationChannelQuery, nodes []*NotificationRule, init func(*NotificationRule), assign func(*NotificationRule, *NotificationChannel)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[string]*NotificationRule) + nids := make(map[string]map[*NotificationRule]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(notificationrule.ChannelsTable) + s.Join(joinT).On(s.C(notificationchannel.FieldID), joinT.C(notificationrule.ChannelsPrimaryKey[0])) + s.Where(sql.InValues(joinT.C(notificationrule.ChannelsPrimaryKey[1]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(notificationrule.ChannelsPrimaryKey[1])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + if err := query.prepareQuery(ctx); err != nil { + return err + } + qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]any, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]any{new(sql.NullString)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := values[0].(*sql.NullString).String + inValue := values[1].(*sql.NullString).String + if nids[inValue] == nil { + nids[inValue] = map[*NotificationRule]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*NotificationChannel](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "channels" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} +func (_q *NotificationRuleQuery) loadEvents(ctx context.Context, query *NotificationEventQuery, nodes []*NotificationRule, init func(*NotificationRule), assign func(*NotificationRule, *NotificationEvent)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*NotificationRule) + 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(notificationevent.FieldRuleID) + } + query.Where(predicate.NotificationEvent(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(notificationrule.EventsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.RuleID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "rule_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *NotificationRuleQuery) 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 *NotificationRuleQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(notificationrule.Table, notificationrule.Columns, sqlgraph.NewFieldSpec(notificationrule.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, notificationrule.FieldID) + for i := range fields { + if fields[i] != notificationrule.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 *NotificationRuleQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(notificationrule.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = notificationrule.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 *NotificationRuleQuery) ForUpdate(opts ...sql.LockOption) *NotificationRuleQuery { + 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 *NotificationRuleQuery) ForShare(opts ...sql.LockOption) *NotificationRuleQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// NotificationRuleGroupBy is the group-by builder for NotificationRule entities. +type NotificationRuleGroupBy struct { + selector + build *NotificationRuleQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *NotificationRuleGroupBy) Aggregate(fns ...AggregateFunc) *NotificationRuleGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *NotificationRuleGroupBy) 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[*NotificationRuleQuery, *NotificationRuleGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *NotificationRuleGroupBy) sqlScan(ctx context.Context, root *NotificationRuleQuery, 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) +} + +// NotificationRuleSelect is the builder for selecting fields of NotificationRule entities. +type NotificationRuleSelect struct { + *NotificationRuleQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *NotificationRuleSelect) Aggregate(fns ...AggregateFunc) *NotificationRuleSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *NotificationRuleSelect) 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[*NotificationRuleQuery, *NotificationRuleSelect](ctx, _s.NotificationRuleQuery, _s, _s.inters, v) +} + +func (_s *NotificationRuleSelect) sqlScan(ctx context.Context, root *NotificationRuleQuery, 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/ent/db/notificationrule_update.go b/ent/db/notificationrule_update.go new file mode 100644 index 0000000000000000000000000000000000000000..967823a21afd57c557893ca836b2bcb1b89a425c --- /dev/null +++ b/ent/db/notificationrule_update.go @@ -0,0 +1,828 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/notificationchannel" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationevent" + "github.com/openmeterio/openmeter/openmeter/ent/db/notificationrule" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/notification" + "github.com/openmeterio/openmeter/pkg/models" +) + +// NotificationRuleUpdate is the builder for updating NotificationRule entities. +type NotificationRuleUpdate struct { + config + hooks []Hook + mutation *NotificationRuleMutation +} + +// Where appends a list predicates to the NotificationRuleUpdate builder. +func (_u *NotificationRuleUpdate) Where(ps ...predicate.NotificationRule) *NotificationRuleUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *NotificationRuleUpdate) SetUpdatedAt(v time.Time) *NotificationRuleUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *NotificationRuleUpdate) SetDeletedAt(v time.Time) *NotificationRuleUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *NotificationRuleUpdate) SetNillableDeletedAt(v *time.Time) *NotificationRuleUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *NotificationRuleUpdate) ClearDeletedAt() *NotificationRuleUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *NotificationRuleUpdate) SetAnnotations(v models.Annotations) *NotificationRuleUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *NotificationRuleUpdate) ClearAnnotations() *NotificationRuleUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *NotificationRuleUpdate) SetMetadata(v map[string]string) *NotificationRuleUpdate { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *NotificationRuleUpdate) ClearMetadata() *NotificationRuleUpdate { + _u.mutation.ClearMetadata() + return _u +} + +// SetName sets the "name" field. +func (_u *NotificationRuleUpdate) SetName(v string) *NotificationRuleUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *NotificationRuleUpdate) SetNillableName(v *string) *NotificationRuleUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDisabled sets the "disabled" field. +func (_u *NotificationRuleUpdate) SetDisabled(v bool) *NotificationRuleUpdate { + _u.mutation.SetDisabled(v) + return _u +} + +// SetNillableDisabled sets the "disabled" field if the given value is not nil. +func (_u *NotificationRuleUpdate) SetNillableDisabled(v *bool) *NotificationRuleUpdate { + if v != nil { + _u.SetDisabled(*v) + } + return _u +} + +// ClearDisabled clears the value of the "disabled" field. +func (_u *NotificationRuleUpdate) ClearDisabled() *NotificationRuleUpdate { + _u.mutation.ClearDisabled() + return _u +} + +// SetConfig sets the "config" field. +func (_u *NotificationRuleUpdate) SetConfig(v notification.RuleConfig) *NotificationRuleUpdate { + _u.mutation.SetConfig(v) + return _u +} + +// SetNillableConfig sets the "config" field if the given value is not nil. +func (_u *NotificationRuleUpdate) SetNillableConfig(v *notification.RuleConfig) *NotificationRuleUpdate { + if v != nil { + _u.SetConfig(*v) + } + return _u +} + +// AddChannelIDs adds the "channels" edge to the NotificationChannel entity by IDs. +func (_u *NotificationRuleUpdate) AddChannelIDs(ids ...string) *NotificationRuleUpdate { + _u.mutation.AddChannelIDs(ids...) + return _u +} + +// AddChannels adds the "channels" edges to the NotificationChannel entity. +func (_u *NotificationRuleUpdate) AddChannels(v ...*NotificationChannel) *NotificationRuleUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddChannelIDs(ids...) +} + +// AddEventIDs adds the "events" edge to the NotificationEvent entity by IDs. +func (_u *NotificationRuleUpdate) AddEventIDs(ids ...string) *NotificationRuleUpdate { + _u.mutation.AddEventIDs(ids...) + return _u +} + +// AddEvents adds the "events" edges to the NotificationEvent entity. +func (_u *NotificationRuleUpdate) AddEvents(v ...*NotificationEvent) *NotificationRuleUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddEventIDs(ids...) +} + +// Mutation returns the NotificationRuleMutation object of the builder. +func (_u *NotificationRuleUpdate) Mutation() *NotificationRuleMutation { + return _u.mutation +} + +// ClearChannels clears all "channels" edges to the NotificationChannel entity. +func (_u *NotificationRuleUpdate) ClearChannels() *NotificationRuleUpdate { + _u.mutation.ClearChannels() + return _u +} + +// RemoveChannelIDs removes the "channels" edge to NotificationChannel entities by IDs. +func (_u *NotificationRuleUpdate) RemoveChannelIDs(ids ...string) *NotificationRuleUpdate { + _u.mutation.RemoveChannelIDs(ids...) + return _u +} + +// RemoveChannels removes "channels" edges to NotificationChannel entities. +func (_u *NotificationRuleUpdate) RemoveChannels(v ...*NotificationChannel) *NotificationRuleUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveChannelIDs(ids...) +} + +// ClearEvents clears all "events" edges to the NotificationEvent entity. +func (_u *NotificationRuleUpdate) ClearEvents() *NotificationRuleUpdate { + _u.mutation.ClearEvents() + return _u +} + +// RemoveEventIDs removes the "events" edge to NotificationEvent entities by IDs. +func (_u *NotificationRuleUpdate) RemoveEventIDs(ids ...string) *NotificationRuleUpdate { + _u.mutation.RemoveEventIDs(ids...) + return _u +} + +// RemoveEvents removes "events" edges to NotificationEvent entities. +func (_u *NotificationRuleUpdate) RemoveEvents(v ...*NotificationEvent) *NotificationRuleUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveEventIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *NotificationRuleUpdate) 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 *NotificationRuleUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *NotificationRuleUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *NotificationRuleUpdate) 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 *NotificationRuleUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := notificationrule.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *NotificationRuleUpdate) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := notificationrule.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "NotificationRule.name": %w`, err)} + } + } + if v, ok := _u.mutation.Config(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "config", err: fmt.Errorf(`db: validator failed for field "NotificationRule.config": %w`, err)} + } + } + return nil +} + +func (_u *NotificationRuleUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(notificationrule.Table, notificationrule.Columns, sqlgraph.NewFieldSpec(notificationrule.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(notificationrule.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(notificationrule.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(notificationrule.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(notificationrule.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(notificationrule.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(notificationrule.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(notificationrule.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(notificationrule.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Disabled(); ok { + _spec.SetField(notificationrule.FieldDisabled, field.TypeBool, value) + } + if _u.mutation.DisabledCleared() { + _spec.ClearField(notificationrule.FieldDisabled, field.TypeBool) + } + if value, ok := _u.mutation.Config(); ok { + vv, err := notificationrule.ValueScanner.Config.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(notificationrule.FieldConfig, field.TypeString, vv) + } + if _u.mutation.ChannelsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: notificationrule.ChannelsTable, + Columns: notificationrule.ChannelsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationchannel.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedChannelsIDs(); len(nodes) > 0 && !_u.mutation.ChannelsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: notificationrule.ChannelsTable, + Columns: notificationrule.ChannelsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationchannel.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.ChannelsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: notificationrule.ChannelsTable, + Columns: notificationrule.ChannelsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationchannel.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.EventsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: notificationrule.EventsTable, + Columns: []string{notificationrule.EventsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationevent.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedEventsIDs(); len(nodes) > 0 && !_u.mutation.EventsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: notificationrule.EventsTable, + Columns: []string{notificationrule.EventsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationevent.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.EventsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: notificationrule.EventsTable, + Columns: []string{notificationrule.EventsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationevent.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{notificationrule.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// NotificationRuleUpdateOne is the builder for updating a single NotificationRule entity. +type NotificationRuleUpdateOne struct { + config + fields []string + hooks []Hook + mutation *NotificationRuleMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *NotificationRuleUpdateOne) SetUpdatedAt(v time.Time) *NotificationRuleUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *NotificationRuleUpdateOne) SetDeletedAt(v time.Time) *NotificationRuleUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *NotificationRuleUpdateOne) SetNillableDeletedAt(v *time.Time) *NotificationRuleUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *NotificationRuleUpdateOne) ClearDeletedAt() *NotificationRuleUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *NotificationRuleUpdateOne) SetAnnotations(v models.Annotations) *NotificationRuleUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *NotificationRuleUpdateOne) ClearAnnotations() *NotificationRuleUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *NotificationRuleUpdateOne) SetMetadata(v map[string]string) *NotificationRuleUpdateOne { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *NotificationRuleUpdateOne) ClearMetadata() *NotificationRuleUpdateOne { + _u.mutation.ClearMetadata() + return _u +} + +// SetName sets the "name" field. +func (_u *NotificationRuleUpdateOne) SetName(v string) *NotificationRuleUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *NotificationRuleUpdateOne) SetNillableName(v *string) *NotificationRuleUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDisabled sets the "disabled" field. +func (_u *NotificationRuleUpdateOne) SetDisabled(v bool) *NotificationRuleUpdateOne { + _u.mutation.SetDisabled(v) + return _u +} + +// SetNillableDisabled sets the "disabled" field if the given value is not nil. +func (_u *NotificationRuleUpdateOne) SetNillableDisabled(v *bool) *NotificationRuleUpdateOne { + if v != nil { + _u.SetDisabled(*v) + } + return _u +} + +// ClearDisabled clears the value of the "disabled" field. +func (_u *NotificationRuleUpdateOne) ClearDisabled() *NotificationRuleUpdateOne { + _u.mutation.ClearDisabled() + return _u +} + +// SetConfig sets the "config" field. +func (_u *NotificationRuleUpdateOne) SetConfig(v notification.RuleConfig) *NotificationRuleUpdateOne { + _u.mutation.SetConfig(v) + return _u +} + +// SetNillableConfig sets the "config" field if the given value is not nil. +func (_u *NotificationRuleUpdateOne) SetNillableConfig(v *notification.RuleConfig) *NotificationRuleUpdateOne { + if v != nil { + _u.SetConfig(*v) + } + return _u +} + +// AddChannelIDs adds the "channels" edge to the NotificationChannel entity by IDs. +func (_u *NotificationRuleUpdateOne) AddChannelIDs(ids ...string) *NotificationRuleUpdateOne { + _u.mutation.AddChannelIDs(ids...) + return _u +} + +// AddChannels adds the "channels" edges to the NotificationChannel entity. +func (_u *NotificationRuleUpdateOne) AddChannels(v ...*NotificationChannel) *NotificationRuleUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddChannelIDs(ids...) +} + +// AddEventIDs adds the "events" edge to the NotificationEvent entity by IDs. +func (_u *NotificationRuleUpdateOne) AddEventIDs(ids ...string) *NotificationRuleUpdateOne { + _u.mutation.AddEventIDs(ids...) + return _u +} + +// AddEvents adds the "events" edges to the NotificationEvent entity. +func (_u *NotificationRuleUpdateOne) AddEvents(v ...*NotificationEvent) *NotificationRuleUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddEventIDs(ids...) +} + +// Mutation returns the NotificationRuleMutation object of the builder. +func (_u *NotificationRuleUpdateOne) Mutation() *NotificationRuleMutation { + return _u.mutation +} + +// ClearChannels clears all "channels" edges to the NotificationChannel entity. +func (_u *NotificationRuleUpdateOne) ClearChannels() *NotificationRuleUpdateOne { + _u.mutation.ClearChannels() + return _u +} + +// RemoveChannelIDs removes the "channels" edge to NotificationChannel entities by IDs. +func (_u *NotificationRuleUpdateOne) RemoveChannelIDs(ids ...string) *NotificationRuleUpdateOne { + _u.mutation.RemoveChannelIDs(ids...) + return _u +} + +// RemoveChannels removes "channels" edges to NotificationChannel entities. +func (_u *NotificationRuleUpdateOne) RemoveChannels(v ...*NotificationChannel) *NotificationRuleUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveChannelIDs(ids...) +} + +// ClearEvents clears all "events" edges to the NotificationEvent entity. +func (_u *NotificationRuleUpdateOne) ClearEvents() *NotificationRuleUpdateOne { + _u.mutation.ClearEvents() + return _u +} + +// RemoveEventIDs removes the "events" edge to NotificationEvent entities by IDs. +func (_u *NotificationRuleUpdateOne) RemoveEventIDs(ids ...string) *NotificationRuleUpdateOne { + _u.mutation.RemoveEventIDs(ids...) + return _u +} + +// RemoveEvents removes "events" edges to NotificationEvent entities. +func (_u *NotificationRuleUpdateOne) RemoveEvents(v ...*NotificationEvent) *NotificationRuleUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveEventIDs(ids...) +} + +// Where appends a list predicates to the NotificationRuleUpdate builder. +func (_u *NotificationRuleUpdateOne) Where(ps ...predicate.NotificationRule) *NotificationRuleUpdateOne { + _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 *NotificationRuleUpdateOne) Select(field string, fields ...string) *NotificationRuleUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated NotificationRule entity. +func (_u *NotificationRuleUpdateOne) Save(ctx context.Context) (*NotificationRule, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *NotificationRuleUpdateOne) SaveX(ctx context.Context) *NotificationRule { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *NotificationRuleUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *NotificationRuleUpdateOne) 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 *NotificationRuleUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := notificationrule.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *NotificationRuleUpdateOne) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := notificationrule.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "NotificationRule.name": %w`, err)} + } + } + if v, ok := _u.mutation.Config(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "config", err: fmt.Errorf(`db: validator failed for field "NotificationRule.config": %w`, err)} + } + } + return nil +} + +func (_u *NotificationRuleUpdateOne) sqlSave(ctx context.Context) (_node *NotificationRule, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(notificationrule.Table, notificationrule.Columns, sqlgraph.NewFieldSpec(notificationrule.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "NotificationRule.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, notificationrule.FieldID) + for _, f := range fields { + if !notificationrule.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != notificationrule.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(notificationrule.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(notificationrule.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(notificationrule.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(notificationrule.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(notificationrule.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(notificationrule.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(notificationrule.FieldMetadata, field.TypeJSON) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(notificationrule.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Disabled(); ok { + _spec.SetField(notificationrule.FieldDisabled, field.TypeBool, value) + } + if _u.mutation.DisabledCleared() { + _spec.ClearField(notificationrule.FieldDisabled, field.TypeBool) + } + if value, ok := _u.mutation.Config(); ok { + vv, err := notificationrule.ValueScanner.Config.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(notificationrule.FieldConfig, field.TypeString, vv) + } + if _u.mutation.ChannelsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: notificationrule.ChannelsTable, + Columns: notificationrule.ChannelsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationchannel.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedChannelsIDs(); len(nodes) > 0 && !_u.mutation.ChannelsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: notificationrule.ChannelsTable, + Columns: notificationrule.ChannelsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationchannel.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.ChannelsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: notificationrule.ChannelsTable, + Columns: notificationrule.ChannelsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationchannel.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.EventsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: notificationrule.EventsTable, + Columns: []string{notificationrule.EventsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationevent.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedEventsIDs(); len(nodes) > 0 && !_u.mutation.EventsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: notificationrule.EventsTable, + Columns: []string{notificationrule.EventsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationevent.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.EventsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: notificationrule.EventsTable, + Columns: []string{notificationrule.EventsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(notificationevent.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &NotificationRule{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{notificationrule.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/ent/db/organizationdefaulttaxcodes.go b/ent/db/organizationdefaulttaxcodes.go new file mode 100644 index 0000000000000000000000000000000000000000..8d5806e026509518729aa954bf0ab4d666d45d7c --- /dev/null +++ b/ent/db/organizationdefaulttaxcodes.go @@ -0,0 +1,209 @@ +// 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/organizationdefaulttaxcodes" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" +) + +// OrganizationDefaultTaxCodes is the model entity for the OrganizationDefaultTaxCodes schema. +type OrganizationDefaultTaxCodes struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,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"` + // Namespace holds the value of the "namespace" field. + Namespace string `json:"namespace,omitempty"` + // InvoicingTaxCodeID holds the value of the "invoicing_tax_code_id" field. + InvoicingTaxCodeID string `json:"invoicing_tax_code_id,omitempty"` + // CreditGrantTaxCodeID holds the value of the "credit_grant_tax_code_id" field. + CreditGrantTaxCodeID string `json:"credit_grant_tax_code_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the OrganizationDefaultTaxCodesQuery when eager-loading is set. + Edges OrganizationDefaultTaxCodesEdges `json:"edges"` + selectValues sql.SelectValues +} + +// OrganizationDefaultTaxCodesEdges holds the relations/edges for other nodes in the graph. +type OrganizationDefaultTaxCodesEdges struct { + // InvoicingTaxCode holds the value of the invoicing_tax_code edge. + InvoicingTaxCode *TaxCode `json:"invoicing_tax_code,omitempty"` + // CreditGrantTaxCode holds the value of the credit_grant_tax_code edge. + CreditGrantTaxCode *TaxCode `json:"credit_grant_tax_code,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// InvoicingTaxCodeOrErr returns the InvoicingTaxCode value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e OrganizationDefaultTaxCodesEdges) InvoicingTaxCodeOrErr() (*TaxCode, error) { + if e.InvoicingTaxCode != nil { + return e.InvoicingTaxCode, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: dbtaxcode.Label} + } + return nil, &NotLoadedError{edge: "invoicing_tax_code"} +} + +// CreditGrantTaxCodeOrErr returns the CreditGrantTaxCode value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e OrganizationDefaultTaxCodesEdges) CreditGrantTaxCodeOrErr() (*TaxCode, error) { + if e.CreditGrantTaxCode != nil { + return e.CreditGrantTaxCode, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: dbtaxcode.Label} + } + return nil, &NotLoadedError{edge: "credit_grant_tax_code"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*OrganizationDefaultTaxCodes) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case organizationdefaulttaxcodes.FieldID, organizationdefaulttaxcodes.FieldNamespace, organizationdefaulttaxcodes.FieldInvoicingTaxCodeID, organizationdefaulttaxcodes.FieldCreditGrantTaxCodeID: + values[i] = new(sql.NullString) + case organizationdefaulttaxcodes.FieldCreatedAt, organizationdefaulttaxcodes.FieldUpdatedAt, organizationdefaulttaxcodes.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 OrganizationDefaultTaxCodes fields. +func (_m *OrganizationDefaultTaxCodes) 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 organizationdefaulttaxcodes.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 organizationdefaulttaxcodes.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 organizationdefaulttaxcodes.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 organizationdefaulttaxcodes.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 organizationdefaulttaxcodes.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 organizationdefaulttaxcodes.FieldInvoicingTaxCodeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field invoicing_tax_code_id", values[i]) + } else if value.Valid { + _m.InvoicingTaxCodeID = value.String + } + case organizationdefaulttaxcodes.FieldCreditGrantTaxCodeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field credit_grant_tax_code_id", values[i]) + } else if value.Valid { + _m.CreditGrantTaxCodeID = 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 OrganizationDefaultTaxCodes. +// This includes values selected through modifiers, order, etc. +func (_m *OrganizationDefaultTaxCodes) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryInvoicingTaxCode queries the "invoicing_tax_code" edge of the OrganizationDefaultTaxCodes entity. +func (_m *OrganizationDefaultTaxCodes) QueryInvoicingTaxCode() *TaxCodeQuery { + return NewOrganizationDefaultTaxCodesClient(_m.config).QueryInvoicingTaxCode(_m) +} + +// QueryCreditGrantTaxCode queries the "credit_grant_tax_code" edge of the OrganizationDefaultTaxCodes entity. +func (_m *OrganizationDefaultTaxCodes) QueryCreditGrantTaxCode() *TaxCodeQuery { + return NewOrganizationDefaultTaxCodesClient(_m.config).QueryCreditGrantTaxCode(_m) +} + +// Update returns a builder for updating this OrganizationDefaultTaxCodes. +// Note that you need to call OrganizationDefaultTaxCodes.Unwrap() before calling this method if this OrganizationDefaultTaxCodes +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *OrganizationDefaultTaxCodes) Update() *OrganizationDefaultTaxCodesUpdateOne { + return NewOrganizationDefaultTaxCodesClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the OrganizationDefaultTaxCodes 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 *OrganizationDefaultTaxCodes) Unwrap() *OrganizationDefaultTaxCodes { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: OrganizationDefaultTaxCodes is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *OrganizationDefaultTaxCodes) String() string { + var builder strings.Builder + builder.WriteString("OrganizationDefaultTaxCodes(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + 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("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("invoicing_tax_code_id=") + builder.WriteString(_m.InvoicingTaxCodeID) + builder.WriteString(", ") + builder.WriteString("credit_grant_tax_code_id=") + builder.WriteString(_m.CreditGrantTaxCodeID) + builder.WriteByte(')') + return builder.String() +} + +// OrganizationDefaultTaxCodesSlice is a parsable slice of OrganizationDefaultTaxCodes. +type OrganizationDefaultTaxCodesSlice []*OrganizationDefaultTaxCodes diff --git a/ent/db/organizationdefaulttaxcodes/organizationdefaulttaxcodes.go b/ent/db/organizationdefaulttaxcodes/organizationdefaulttaxcodes.go new file mode 100644 index 0000000000000000000000000000000000000000..b1d60efa506b761b7ddb4b0a15b5c930db4b04d4 --- /dev/null +++ b/ent/db/organizationdefaulttaxcodes/organizationdefaulttaxcodes.go @@ -0,0 +1,149 @@ +// Code generated by ent, DO NOT EDIT. + +package organizationdefaulttaxcodes + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the organizationdefaulttaxcodes type in the database. + Label = "organization_default_tax_codes" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // 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" + // FieldNamespace holds the string denoting the namespace field in the database. + FieldNamespace = "namespace" + // FieldInvoicingTaxCodeID holds the string denoting the invoicing_tax_code_id field in the database. + FieldInvoicingTaxCodeID = "invoicing_tax_code_id" + // FieldCreditGrantTaxCodeID holds the string denoting the credit_grant_tax_code_id field in the database. + FieldCreditGrantTaxCodeID = "credit_grant_tax_code_id" + // EdgeInvoicingTaxCode holds the string denoting the invoicing_tax_code edge name in mutations. + EdgeInvoicingTaxCode = "invoicing_tax_code" + // EdgeCreditGrantTaxCode holds the string denoting the credit_grant_tax_code edge name in mutations. + EdgeCreditGrantTaxCode = "credit_grant_tax_code" + // Table holds the table name of the organizationdefaulttaxcodes in the database. + Table = "organization_default_tax_codes" + // InvoicingTaxCodeTable is the table that holds the invoicing_tax_code relation/edge. + InvoicingTaxCodeTable = "organization_default_tax_codes" + // InvoicingTaxCodeInverseTable is the table name for the TaxCode entity. + // It exists in this package in order to avoid circular dependency with the "dbtaxcode" package. + InvoicingTaxCodeInverseTable = "tax_codes" + // InvoicingTaxCodeColumn is the table column denoting the invoicing_tax_code relation/edge. + InvoicingTaxCodeColumn = "invoicing_tax_code_id" + // CreditGrantTaxCodeTable is the table that holds the credit_grant_tax_code relation/edge. + CreditGrantTaxCodeTable = "organization_default_tax_codes" + // CreditGrantTaxCodeInverseTable is the table name for the TaxCode entity. + // It exists in this package in order to avoid circular dependency with the "dbtaxcode" package. + CreditGrantTaxCodeInverseTable = "tax_codes" + // CreditGrantTaxCodeColumn is the table column denoting the credit_grant_tax_code relation/edge. + CreditGrantTaxCodeColumn = "credit_grant_tax_code_id" +) + +// Columns holds all SQL columns for organizationdefaulttaxcodes fields. +var Columns = []string{ + FieldID, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldNamespace, + FieldInvoicingTaxCodeID, + FieldCreditGrantTaxCodeID, +} + +// 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 ( + // 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 + // NamespaceValidator is a validator for the "namespace" field. It is called by the builders before save. + NamespaceValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// OrderOption defines the ordering options for the OrganizationDefaultTaxCodes 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() +} + +// 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() +} + +// ByNamespace orders the results by the namespace field. +func ByNamespace(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldNamespace, opts...).ToFunc() +} + +// ByInvoicingTaxCodeID orders the results by the invoicing_tax_code_id field. +func ByInvoicingTaxCodeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoicingTaxCodeID, opts...).ToFunc() +} + +// ByCreditGrantTaxCodeID orders the results by the credit_grant_tax_code_id field. +func ByCreditGrantTaxCodeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreditGrantTaxCodeID, opts...).ToFunc() +} + +// ByInvoicingTaxCodeField orders the results by invoicing_tax_code field. +func ByInvoicingTaxCodeField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newInvoicingTaxCodeStep(), sql.OrderByField(field, opts...)) + } +} + +// ByCreditGrantTaxCodeField orders the results by credit_grant_tax_code field. +func ByCreditGrantTaxCodeField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCreditGrantTaxCodeStep(), sql.OrderByField(field, opts...)) + } +} +func newInvoicingTaxCodeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(InvoicingTaxCodeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, InvoicingTaxCodeTable, InvoicingTaxCodeColumn), + ) +} +func newCreditGrantTaxCodeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CreditGrantTaxCodeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, CreditGrantTaxCodeTable, CreditGrantTaxCodeColumn), + ) +} diff --git a/ent/db/organizationdefaulttaxcodes/where.go b/ent/db/organizationdefaulttaxcodes/where.go new file mode 100644 index 0000000000000000000000000000000000000000..52528e60e15f511245a23a87d70b0229a27c9e01 --- /dev/null +++ b/ent/db/organizationdefaulttaxcodes/where.go @@ -0,0 +1,482 @@ +// Code generated by ent, DO NOT EDIT. + +package organizationdefaulttaxcodes + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldContainsFold(FieldID, id)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(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.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(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.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldEQ(FieldNamespace, v)) +} + +// InvoicingTaxCodeID applies equality check predicate on the "invoicing_tax_code_id" field. It's identical to InvoicingTaxCodeIDEQ. +func InvoicingTaxCodeID(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldEQ(FieldInvoicingTaxCodeID, v)) +} + +// CreditGrantTaxCodeID applies equality check predicate on the "credit_grant_tax_code_id" field. It's identical to CreditGrantTaxCodeIDEQ. +func CreditGrantTaxCodeID(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldEQ(FieldCreditGrantTaxCodeID, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldNotNull(FieldDeletedAt)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldContainsFold(FieldNamespace, v)) +} + +// InvoicingTaxCodeIDEQ applies the EQ predicate on the "invoicing_tax_code_id" field. +func InvoicingTaxCodeIDEQ(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldEQ(FieldInvoicingTaxCodeID, v)) +} + +// InvoicingTaxCodeIDNEQ applies the NEQ predicate on the "invoicing_tax_code_id" field. +func InvoicingTaxCodeIDNEQ(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldNEQ(FieldInvoicingTaxCodeID, v)) +} + +// InvoicingTaxCodeIDIn applies the In predicate on the "invoicing_tax_code_id" field. +func InvoicingTaxCodeIDIn(vs ...string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldIn(FieldInvoicingTaxCodeID, vs...)) +} + +// InvoicingTaxCodeIDNotIn applies the NotIn predicate on the "invoicing_tax_code_id" field. +func InvoicingTaxCodeIDNotIn(vs ...string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldNotIn(FieldInvoicingTaxCodeID, vs...)) +} + +// InvoicingTaxCodeIDGT applies the GT predicate on the "invoicing_tax_code_id" field. +func InvoicingTaxCodeIDGT(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldGT(FieldInvoicingTaxCodeID, v)) +} + +// InvoicingTaxCodeIDGTE applies the GTE predicate on the "invoicing_tax_code_id" field. +func InvoicingTaxCodeIDGTE(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldGTE(FieldInvoicingTaxCodeID, v)) +} + +// InvoicingTaxCodeIDLT applies the LT predicate on the "invoicing_tax_code_id" field. +func InvoicingTaxCodeIDLT(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldLT(FieldInvoicingTaxCodeID, v)) +} + +// InvoicingTaxCodeIDLTE applies the LTE predicate on the "invoicing_tax_code_id" field. +func InvoicingTaxCodeIDLTE(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldLTE(FieldInvoicingTaxCodeID, v)) +} + +// InvoicingTaxCodeIDContains applies the Contains predicate on the "invoicing_tax_code_id" field. +func InvoicingTaxCodeIDContains(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldContains(FieldInvoicingTaxCodeID, v)) +} + +// InvoicingTaxCodeIDHasPrefix applies the HasPrefix predicate on the "invoicing_tax_code_id" field. +func InvoicingTaxCodeIDHasPrefix(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldHasPrefix(FieldInvoicingTaxCodeID, v)) +} + +// InvoicingTaxCodeIDHasSuffix applies the HasSuffix predicate on the "invoicing_tax_code_id" field. +func InvoicingTaxCodeIDHasSuffix(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldHasSuffix(FieldInvoicingTaxCodeID, v)) +} + +// InvoicingTaxCodeIDEqualFold applies the EqualFold predicate on the "invoicing_tax_code_id" field. +func InvoicingTaxCodeIDEqualFold(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldEqualFold(FieldInvoicingTaxCodeID, v)) +} + +// InvoicingTaxCodeIDContainsFold applies the ContainsFold predicate on the "invoicing_tax_code_id" field. +func InvoicingTaxCodeIDContainsFold(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldContainsFold(FieldInvoicingTaxCodeID, v)) +} + +// CreditGrantTaxCodeIDEQ applies the EQ predicate on the "credit_grant_tax_code_id" field. +func CreditGrantTaxCodeIDEQ(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldEQ(FieldCreditGrantTaxCodeID, v)) +} + +// CreditGrantTaxCodeIDNEQ applies the NEQ predicate on the "credit_grant_tax_code_id" field. +func CreditGrantTaxCodeIDNEQ(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldNEQ(FieldCreditGrantTaxCodeID, v)) +} + +// CreditGrantTaxCodeIDIn applies the In predicate on the "credit_grant_tax_code_id" field. +func CreditGrantTaxCodeIDIn(vs ...string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldIn(FieldCreditGrantTaxCodeID, vs...)) +} + +// CreditGrantTaxCodeIDNotIn applies the NotIn predicate on the "credit_grant_tax_code_id" field. +func CreditGrantTaxCodeIDNotIn(vs ...string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldNotIn(FieldCreditGrantTaxCodeID, vs...)) +} + +// CreditGrantTaxCodeIDGT applies the GT predicate on the "credit_grant_tax_code_id" field. +func CreditGrantTaxCodeIDGT(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldGT(FieldCreditGrantTaxCodeID, v)) +} + +// CreditGrantTaxCodeIDGTE applies the GTE predicate on the "credit_grant_tax_code_id" field. +func CreditGrantTaxCodeIDGTE(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldGTE(FieldCreditGrantTaxCodeID, v)) +} + +// CreditGrantTaxCodeIDLT applies the LT predicate on the "credit_grant_tax_code_id" field. +func CreditGrantTaxCodeIDLT(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldLT(FieldCreditGrantTaxCodeID, v)) +} + +// CreditGrantTaxCodeIDLTE applies the LTE predicate on the "credit_grant_tax_code_id" field. +func CreditGrantTaxCodeIDLTE(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldLTE(FieldCreditGrantTaxCodeID, v)) +} + +// CreditGrantTaxCodeIDContains applies the Contains predicate on the "credit_grant_tax_code_id" field. +func CreditGrantTaxCodeIDContains(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldContains(FieldCreditGrantTaxCodeID, v)) +} + +// CreditGrantTaxCodeIDHasPrefix applies the HasPrefix predicate on the "credit_grant_tax_code_id" field. +func CreditGrantTaxCodeIDHasPrefix(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldHasPrefix(FieldCreditGrantTaxCodeID, v)) +} + +// CreditGrantTaxCodeIDHasSuffix applies the HasSuffix predicate on the "credit_grant_tax_code_id" field. +func CreditGrantTaxCodeIDHasSuffix(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldHasSuffix(FieldCreditGrantTaxCodeID, v)) +} + +// CreditGrantTaxCodeIDEqualFold applies the EqualFold predicate on the "credit_grant_tax_code_id" field. +func CreditGrantTaxCodeIDEqualFold(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldEqualFold(FieldCreditGrantTaxCodeID, v)) +} + +// CreditGrantTaxCodeIDContainsFold applies the ContainsFold predicate on the "credit_grant_tax_code_id" field. +func CreditGrantTaxCodeIDContainsFold(v string) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.FieldContainsFold(FieldCreditGrantTaxCodeID, v)) +} + +// HasInvoicingTaxCode applies the HasEdge predicate on the "invoicing_tax_code" edge. +func HasInvoicingTaxCode() predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, InvoicingTaxCodeTable, InvoicingTaxCodeColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasInvoicingTaxCodeWith applies the HasEdge predicate on the "invoicing_tax_code" edge with a given conditions (other predicates). +func HasInvoicingTaxCodeWith(preds ...predicate.TaxCode) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(func(s *sql.Selector) { + step := newInvoicingTaxCodeStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasCreditGrantTaxCode applies the HasEdge predicate on the "credit_grant_tax_code" edge. +func HasCreditGrantTaxCode() predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, CreditGrantTaxCodeTable, CreditGrantTaxCodeColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCreditGrantTaxCodeWith applies the HasEdge predicate on the "credit_grant_tax_code" edge with a given conditions (other predicates). +func HasCreditGrantTaxCodeWith(preds ...predicate.TaxCode) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(func(s *sql.Selector) { + step := newCreditGrantTaxCodeStep() + 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.OrganizationDefaultTaxCodes) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.OrganizationDefaultTaxCodes) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.OrganizationDefaultTaxCodes) predicate.OrganizationDefaultTaxCodes { + return predicate.OrganizationDefaultTaxCodes(sql.NotPredicates(p)) +} diff --git a/ent/db/organizationdefaulttaxcodes_create.go b/ent/db/organizationdefaulttaxcodes_create.go new file mode 100644 index 0000000000000000000000000000000000000000..eecc384e56ff37faea5dcbe3f5dc81df96e443b4 --- /dev/null +++ b/ent/db/organizationdefaulttaxcodes_create.go @@ -0,0 +1,802 @@ +// 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/organizationdefaulttaxcodes" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" +) + +// OrganizationDefaultTaxCodesCreate is the builder for creating a OrganizationDefaultTaxCodes entity. +type OrganizationDefaultTaxCodesCreate struct { + config + mutation *OrganizationDefaultTaxCodesMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetCreatedAt sets the "created_at" field. +func (_c *OrganizationDefaultTaxCodesCreate) SetCreatedAt(v time.Time) *OrganizationDefaultTaxCodesCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *OrganizationDefaultTaxCodesCreate) SetNillableCreatedAt(v *time.Time) *OrganizationDefaultTaxCodesCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *OrganizationDefaultTaxCodesCreate) SetUpdatedAt(v time.Time) *OrganizationDefaultTaxCodesCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *OrganizationDefaultTaxCodesCreate) SetNillableUpdatedAt(v *time.Time) *OrganizationDefaultTaxCodesCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *OrganizationDefaultTaxCodesCreate) SetDeletedAt(v time.Time) *OrganizationDefaultTaxCodesCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *OrganizationDefaultTaxCodesCreate) SetNillableDeletedAt(v *time.Time) *OrganizationDefaultTaxCodesCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetNamespace sets the "namespace" field. +func (_c *OrganizationDefaultTaxCodesCreate) SetNamespace(v string) *OrganizationDefaultTaxCodesCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetInvoicingTaxCodeID sets the "invoicing_tax_code_id" field. +func (_c *OrganizationDefaultTaxCodesCreate) SetInvoicingTaxCodeID(v string) *OrganizationDefaultTaxCodesCreate { + _c.mutation.SetInvoicingTaxCodeID(v) + return _c +} + +// SetCreditGrantTaxCodeID sets the "credit_grant_tax_code_id" field. +func (_c *OrganizationDefaultTaxCodesCreate) SetCreditGrantTaxCodeID(v string) *OrganizationDefaultTaxCodesCreate { + _c.mutation.SetCreditGrantTaxCodeID(v) + return _c +} + +// SetID sets the "id" field. +func (_c *OrganizationDefaultTaxCodesCreate) SetID(v string) *OrganizationDefaultTaxCodesCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *OrganizationDefaultTaxCodesCreate) SetNillableID(v *string) *OrganizationDefaultTaxCodesCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetInvoicingTaxCode sets the "invoicing_tax_code" edge to the TaxCode entity. +func (_c *OrganizationDefaultTaxCodesCreate) SetInvoicingTaxCode(v *TaxCode) *OrganizationDefaultTaxCodesCreate { + return _c.SetInvoicingTaxCodeID(v.ID) +} + +// SetCreditGrantTaxCode sets the "credit_grant_tax_code" edge to the TaxCode entity. +func (_c *OrganizationDefaultTaxCodesCreate) SetCreditGrantTaxCode(v *TaxCode) *OrganizationDefaultTaxCodesCreate { + return _c.SetCreditGrantTaxCodeID(v.ID) +} + +// Mutation returns the OrganizationDefaultTaxCodesMutation object of the builder. +func (_c *OrganizationDefaultTaxCodesCreate) Mutation() *OrganizationDefaultTaxCodesMutation { + return _c.mutation +} + +// Save creates the OrganizationDefaultTaxCodes in the database. +func (_c *OrganizationDefaultTaxCodesCreate) Save(ctx context.Context) (*OrganizationDefaultTaxCodes, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *OrganizationDefaultTaxCodesCreate) SaveX(ctx context.Context) *OrganizationDefaultTaxCodes { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *OrganizationDefaultTaxCodesCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *OrganizationDefaultTaxCodesCreate) 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 *OrganizationDefaultTaxCodesCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := organizationdefaulttaxcodes.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := organizationdefaulttaxcodes.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := organizationdefaulttaxcodes.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *OrganizationDefaultTaxCodesCreate) check() error { + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "OrganizationDefaultTaxCodes.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "OrganizationDefaultTaxCodes.updated_at"`)} + } + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "OrganizationDefaultTaxCodes.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := organizationdefaulttaxcodes.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "OrganizationDefaultTaxCodes.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.InvoicingTaxCodeID(); !ok { + return &ValidationError{Name: "invoicing_tax_code_id", err: errors.New(`db: missing required field "OrganizationDefaultTaxCodes.invoicing_tax_code_id"`)} + } + if _, ok := _c.mutation.CreditGrantTaxCodeID(); !ok { + return &ValidationError{Name: "credit_grant_tax_code_id", err: errors.New(`db: missing required field "OrganizationDefaultTaxCodes.credit_grant_tax_code_id"`)} + } + if len(_c.mutation.InvoicingTaxCodeIDs()) == 0 { + return &ValidationError{Name: "invoicing_tax_code", err: errors.New(`db: missing required edge "OrganizationDefaultTaxCodes.invoicing_tax_code"`)} + } + if len(_c.mutation.CreditGrantTaxCodeIDs()) == 0 { + return &ValidationError{Name: "credit_grant_tax_code", err: errors.New(`db: missing required edge "OrganizationDefaultTaxCodes.credit_grant_tax_code"`)} + } + return nil +} + +func (_c *OrganizationDefaultTaxCodesCreate) sqlSave(ctx context.Context) (*OrganizationDefaultTaxCodes, 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 OrganizationDefaultTaxCodes.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *OrganizationDefaultTaxCodesCreate) createSpec() (*OrganizationDefaultTaxCodes, *sqlgraph.CreateSpec) { + var ( + _node = &OrganizationDefaultTaxCodes{config: _c.config} + _spec = sqlgraph.NewCreateSpec(organizationdefaulttaxcodes.Table, sqlgraph.NewFieldSpec(organizationdefaulttaxcodes.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.CreatedAt(); ok { + _spec.SetField(organizationdefaulttaxcodes.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(organizationdefaulttaxcodes.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(organizationdefaulttaxcodes.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(organizationdefaulttaxcodes.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if nodes := _c.mutation.InvoicingTaxCodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: organizationdefaulttaxcodes.InvoicingTaxCodeTable, + Columns: []string{organizationdefaulttaxcodes.InvoicingTaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.InvoicingTaxCodeID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.CreditGrantTaxCodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: organizationdefaulttaxcodes.CreditGrantTaxCodeTable, + Columns: []string{organizationdefaulttaxcodes.CreditGrantTaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.CreditGrantTaxCodeID = 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.OrganizationDefaultTaxCodes.Create(). +// SetCreatedAt(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.OrganizationDefaultTaxCodesUpsert) { +// SetCreatedAt(v+v). +// }). +// Exec(ctx) +func (_c *OrganizationDefaultTaxCodesCreate) OnConflict(opts ...sql.ConflictOption) *OrganizationDefaultTaxCodesUpsertOne { + _c.conflict = opts + return &OrganizationDefaultTaxCodesUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.OrganizationDefaultTaxCodes.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *OrganizationDefaultTaxCodesCreate) OnConflictColumns(columns ...string) *OrganizationDefaultTaxCodesUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &OrganizationDefaultTaxCodesUpsertOne{ + create: _c, + } +} + +type ( + // OrganizationDefaultTaxCodesUpsertOne is the builder for "upsert"-ing + // one OrganizationDefaultTaxCodes node. + OrganizationDefaultTaxCodesUpsertOne struct { + create *OrganizationDefaultTaxCodesCreate + } + + // OrganizationDefaultTaxCodesUpsert is the "OnConflict" setter. + OrganizationDefaultTaxCodesUpsert struct { + *sql.UpdateSet + } +) + +// SetUpdatedAt sets the "updated_at" field. +func (u *OrganizationDefaultTaxCodesUpsert) SetUpdatedAt(v time.Time) *OrganizationDefaultTaxCodesUpsert { + u.Set(organizationdefaulttaxcodes.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *OrganizationDefaultTaxCodesUpsert) UpdateUpdatedAt() *OrganizationDefaultTaxCodesUpsert { + u.SetExcluded(organizationdefaulttaxcodes.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *OrganizationDefaultTaxCodesUpsert) SetDeletedAt(v time.Time) *OrganizationDefaultTaxCodesUpsert { + u.Set(organizationdefaulttaxcodes.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *OrganizationDefaultTaxCodesUpsert) UpdateDeletedAt() *OrganizationDefaultTaxCodesUpsert { + u.SetExcluded(organizationdefaulttaxcodes.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *OrganizationDefaultTaxCodesUpsert) ClearDeletedAt() *OrganizationDefaultTaxCodesUpsert { + u.SetNull(organizationdefaulttaxcodes.FieldDeletedAt) + return u +} + +// SetInvoicingTaxCodeID sets the "invoicing_tax_code_id" field. +func (u *OrganizationDefaultTaxCodesUpsert) SetInvoicingTaxCodeID(v string) *OrganizationDefaultTaxCodesUpsert { + u.Set(organizationdefaulttaxcodes.FieldInvoicingTaxCodeID, v) + return u +} + +// UpdateInvoicingTaxCodeID sets the "invoicing_tax_code_id" field to the value that was provided on create. +func (u *OrganizationDefaultTaxCodesUpsert) UpdateInvoicingTaxCodeID() *OrganizationDefaultTaxCodesUpsert { + u.SetExcluded(organizationdefaulttaxcodes.FieldInvoicingTaxCodeID) + return u +} + +// SetCreditGrantTaxCodeID sets the "credit_grant_tax_code_id" field. +func (u *OrganizationDefaultTaxCodesUpsert) SetCreditGrantTaxCodeID(v string) *OrganizationDefaultTaxCodesUpsert { + u.Set(organizationdefaulttaxcodes.FieldCreditGrantTaxCodeID, v) + return u +} + +// UpdateCreditGrantTaxCodeID sets the "credit_grant_tax_code_id" field to the value that was provided on create. +func (u *OrganizationDefaultTaxCodesUpsert) UpdateCreditGrantTaxCodeID() *OrganizationDefaultTaxCodesUpsert { + u.SetExcluded(organizationdefaulttaxcodes.FieldCreditGrantTaxCodeID) + 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.OrganizationDefaultTaxCodes.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(organizationdefaulttaxcodes.FieldID) +// }), +// ). +// Exec(ctx) +func (u *OrganizationDefaultTaxCodesUpsertOne) UpdateNewValues() *OrganizationDefaultTaxCodesUpsertOne { + 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(organizationdefaulttaxcodes.FieldID) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(organizationdefaulttaxcodes.FieldCreatedAt) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(organizationdefaulttaxcodes.FieldNamespace) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.OrganizationDefaultTaxCodes.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *OrganizationDefaultTaxCodesUpsertOne) Ignore() *OrganizationDefaultTaxCodesUpsertOne { + 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 *OrganizationDefaultTaxCodesUpsertOne) DoNothing() *OrganizationDefaultTaxCodesUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the OrganizationDefaultTaxCodesCreate.OnConflict +// documentation for more info. +func (u *OrganizationDefaultTaxCodesUpsertOne) Update(set func(*OrganizationDefaultTaxCodesUpsert)) *OrganizationDefaultTaxCodesUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&OrganizationDefaultTaxCodesUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *OrganizationDefaultTaxCodesUpsertOne) SetUpdatedAt(v time.Time) *OrganizationDefaultTaxCodesUpsertOne { + return u.Update(func(s *OrganizationDefaultTaxCodesUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *OrganizationDefaultTaxCodesUpsertOne) UpdateUpdatedAt() *OrganizationDefaultTaxCodesUpsertOne { + return u.Update(func(s *OrganizationDefaultTaxCodesUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *OrganizationDefaultTaxCodesUpsertOne) SetDeletedAt(v time.Time) *OrganizationDefaultTaxCodesUpsertOne { + return u.Update(func(s *OrganizationDefaultTaxCodesUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *OrganizationDefaultTaxCodesUpsertOne) UpdateDeletedAt() *OrganizationDefaultTaxCodesUpsertOne { + return u.Update(func(s *OrganizationDefaultTaxCodesUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *OrganizationDefaultTaxCodesUpsertOne) ClearDeletedAt() *OrganizationDefaultTaxCodesUpsertOne { + return u.Update(func(s *OrganizationDefaultTaxCodesUpsert) { + s.ClearDeletedAt() + }) +} + +// SetInvoicingTaxCodeID sets the "invoicing_tax_code_id" field. +func (u *OrganizationDefaultTaxCodesUpsertOne) SetInvoicingTaxCodeID(v string) *OrganizationDefaultTaxCodesUpsertOne { + return u.Update(func(s *OrganizationDefaultTaxCodesUpsert) { + s.SetInvoicingTaxCodeID(v) + }) +} + +// UpdateInvoicingTaxCodeID sets the "invoicing_tax_code_id" field to the value that was provided on create. +func (u *OrganizationDefaultTaxCodesUpsertOne) UpdateInvoicingTaxCodeID() *OrganizationDefaultTaxCodesUpsertOne { + return u.Update(func(s *OrganizationDefaultTaxCodesUpsert) { + s.UpdateInvoicingTaxCodeID() + }) +} + +// SetCreditGrantTaxCodeID sets the "credit_grant_tax_code_id" field. +func (u *OrganizationDefaultTaxCodesUpsertOne) SetCreditGrantTaxCodeID(v string) *OrganizationDefaultTaxCodesUpsertOne { + return u.Update(func(s *OrganizationDefaultTaxCodesUpsert) { + s.SetCreditGrantTaxCodeID(v) + }) +} + +// UpdateCreditGrantTaxCodeID sets the "credit_grant_tax_code_id" field to the value that was provided on create. +func (u *OrganizationDefaultTaxCodesUpsertOne) UpdateCreditGrantTaxCodeID() *OrganizationDefaultTaxCodesUpsertOne { + return u.Update(func(s *OrganizationDefaultTaxCodesUpsert) { + s.UpdateCreditGrantTaxCodeID() + }) +} + +// Exec executes the query. +func (u *OrganizationDefaultTaxCodesUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for OrganizationDefaultTaxCodesCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *OrganizationDefaultTaxCodesUpsertOne) 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 *OrganizationDefaultTaxCodesUpsertOne) 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: OrganizationDefaultTaxCodesUpsertOne.ID is not supported by MySQL driver. Use OrganizationDefaultTaxCodesUpsertOne.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 *OrganizationDefaultTaxCodesUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// OrganizationDefaultTaxCodesCreateBulk is the builder for creating many OrganizationDefaultTaxCodes entities in bulk. +type OrganizationDefaultTaxCodesCreateBulk struct { + config + err error + builders []*OrganizationDefaultTaxCodesCreate + conflict []sql.ConflictOption +} + +// Save creates the OrganizationDefaultTaxCodes entities in the database. +func (_c *OrganizationDefaultTaxCodesCreateBulk) Save(ctx context.Context) ([]*OrganizationDefaultTaxCodes, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*OrganizationDefaultTaxCodes, 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.(*OrganizationDefaultTaxCodesMutation) + 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 *OrganizationDefaultTaxCodesCreateBulk) SaveX(ctx context.Context) []*OrganizationDefaultTaxCodes { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *OrganizationDefaultTaxCodesCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *OrganizationDefaultTaxCodesCreateBulk) 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.OrganizationDefaultTaxCodes.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.OrganizationDefaultTaxCodesUpsert) { +// SetCreatedAt(v+v). +// }). +// Exec(ctx) +func (_c *OrganizationDefaultTaxCodesCreateBulk) OnConflict(opts ...sql.ConflictOption) *OrganizationDefaultTaxCodesUpsertBulk { + _c.conflict = opts + return &OrganizationDefaultTaxCodesUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.OrganizationDefaultTaxCodes.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *OrganizationDefaultTaxCodesCreateBulk) OnConflictColumns(columns ...string) *OrganizationDefaultTaxCodesUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &OrganizationDefaultTaxCodesUpsertBulk{ + create: _c, + } +} + +// OrganizationDefaultTaxCodesUpsertBulk is the builder for "upsert"-ing +// a bulk of OrganizationDefaultTaxCodes nodes. +type OrganizationDefaultTaxCodesUpsertBulk struct { + create *OrganizationDefaultTaxCodesCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.OrganizationDefaultTaxCodes.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(organizationdefaulttaxcodes.FieldID) +// }), +// ). +// Exec(ctx) +func (u *OrganizationDefaultTaxCodesUpsertBulk) UpdateNewValues() *OrganizationDefaultTaxCodesUpsertBulk { + 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(organizationdefaulttaxcodes.FieldID) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(organizationdefaulttaxcodes.FieldCreatedAt) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(organizationdefaulttaxcodes.FieldNamespace) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.OrganizationDefaultTaxCodes.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *OrganizationDefaultTaxCodesUpsertBulk) Ignore() *OrganizationDefaultTaxCodesUpsertBulk { + 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 *OrganizationDefaultTaxCodesUpsertBulk) DoNothing() *OrganizationDefaultTaxCodesUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the OrganizationDefaultTaxCodesCreateBulk.OnConflict +// documentation for more info. +func (u *OrganizationDefaultTaxCodesUpsertBulk) Update(set func(*OrganizationDefaultTaxCodesUpsert)) *OrganizationDefaultTaxCodesUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&OrganizationDefaultTaxCodesUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *OrganizationDefaultTaxCodesUpsertBulk) SetUpdatedAt(v time.Time) *OrganizationDefaultTaxCodesUpsertBulk { + return u.Update(func(s *OrganizationDefaultTaxCodesUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *OrganizationDefaultTaxCodesUpsertBulk) UpdateUpdatedAt() *OrganizationDefaultTaxCodesUpsertBulk { + return u.Update(func(s *OrganizationDefaultTaxCodesUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *OrganizationDefaultTaxCodesUpsertBulk) SetDeletedAt(v time.Time) *OrganizationDefaultTaxCodesUpsertBulk { + return u.Update(func(s *OrganizationDefaultTaxCodesUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *OrganizationDefaultTaxCodesUpsertBulk) UpdateDeletedAt() *OrganizationDefaultTaxCodesUpsertBulk { + return u.Update(func(s *OrganizationDefaultTaxCodesUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *OrganizationDefaultTaxCodesUpsertBulk) ClearDeletedAt() *OrganizationDefaultTaxCodesUpsertBulk { + return u.Update(func(s *OrganizationDefaultTaxCodesUpsert) { + s.ClearDeletedAt() + }) +} + +// SetInvoicingTaxCodeID sets the "invoicing_tax_code_id" field. +func (u *OrganizationDefaultTaxCodesUpsertBulk) SetInvoicingTaxCodeID(v string) *OrganizationDefaultTaxCodesUpsertBulk { + return u.Update(func(s *OrganizationDefaultTaxCodesUpsert) { + s.SetInvoicingTaxCodeID(v) + }) +} + +// UpdateInvoicingTaxCodeID sets the "invoicing_tax_code_id" field to the value that was provided on create. +func (u *OrganizationDefaultTaxCodesUpsertBulk) UpdateInvoicingTaxCodeID() *OrganizationDefaultTaxCodesUpsertBulk { + return u.Update(func(s *OrganizationDefaultTaxCodesUpsert) { + s.UpdateInvoicingTaxCodeID() + }) +} + +// SetCreditGrantTaxCodeID sets the "credit_grant_tax_code_id" field. +func (u *OrganizationDefaultTaxCodesUpsertBulk) SetCreditGrantTaxCodeID(v string) *OrganizationDefaultTaxCodesUpsertBulk { + return u.Update(func(s *OrganizationDefaultTaxCodesUpsert) { + s.SetCreditGrantTaxCodeID(v) + }) +} + +// UpdateCreditGrantTaxCodeID sets the "credit_grant_tax_code_id" field to the value that was provided on create. +func (u *OrganizationDefaultTaxCodesUpsertBulk) UpdateCreditGrantTaxCodeID() *OrganizationDefaultTaxCodesUpsertBulk { + return u.Update(func(s *OrganizationDefaultTaxCodesUpsert) { + s.UpdateCreditGrantTaxCodeID() + }) +} + +// Exec executes the query. +func (u *OrganizationDefaultTaxCodesUpsertBulk) 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 OrganizationDefaultTaxCodesCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for OrganizationDefaultTaxCodesCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *OrganizationDefaultTaxCodesUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/organizationdefaulttaxcodes_delete.go b/ent/db/organizationdefaulttaxcodes_delete.go new file mode 100644 index 0000000000000000000000000000000000000000..f856638c83480e9b85eb06b0a3eb6d802db6f145 --- /dev/null +++ b/ent/db/organizationdefaulttaxcodes_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/organizationdefaulttaxcodes" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// OrganizationDefaultTaxCodesDelete is the builder for deleting a OrganizationDefaultTaxCodes entity. +type OrganizationDefaultTaxCodesDelete struct { + config + hooks []Hook + mutation *OrganizationDefaultTaxCodesMutation +} + +// Where appends a list predicates to the OrganizationDefaultTaxCodesDelete builder. +func (_d *OrganizationDefaultTaxCodesDelete) Where(ps ...predicate.OrganizationDefaultTaxCodes) *OrganizationDefaultTaxCodesDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *OrganizationDefaultTaxCodesDelete) 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 *OrganizationDefaultTaxCodesDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *OrganizationDefaultTaxCodesDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(organizationdefaulttaxcodes.Table, sqlgraph.NewFieldSpec(organizationdefaulttaxcodes.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 +} + +// OrganizationDefaultTaxCodesDeleteOne is the builder for deleting a single OrganizationDefaultTaxCodes entity. +type OrganizationDefaultTaxCodesDeleteOne struct { + _d *OrganizationDefaultTaxCodesDelete +} + +// Where appends a list predicates to the OrganizationDefaultTaxCodesDelete builder. +func (_d *OrganizationDefaultTaxCodesDeleteOne) Where(ps ...predicate.OrganizationDefaultTaxCodes) *OrganizationDefaultTaxCodesDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *OrganizationDefaultTaxCodesDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{organizationdefaulttaxcodes.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *OrganizationDefaultTaxCodesDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/db/organizationdefaulttaxcodes_query.go b/ent/db/organizationdefaulttaxcodes_query.go new file mode 100644 index 0000000000000000000000000000000000000000..6472454d49ccfa6ef2db9d1fc1e920d4bc728605 --- /dev/null +++ b/ent/db/organizationdefaulttaxcodes_query.go @@ -0,0 +1,717 @@ +// 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/organizationdefaulttaxcodes" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" +) + +// OrganizationDefaultTaxCodesQuery is the builder for querying OrganizationDefaultTaxCodes entities. +type OrganizationDefaultTaxCodesQuery struct { + config + ctx *QueryContext + order []organizationdefaulttaxcodes.OrderOption + inters []Interceptor + predicates []predicate.OrganizationDefaultTaxCodes + withInvoicingTaxCode *TaxCodeQuery + withCreditGrantTaxCode *TaxCodeQuery + 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 OrganizationDefaultTaxCodesQuery builder. +func (_q *OrganizationDefaultTaxCodesQuery) Where(ps ...predicate.OrganizationDefaultTaxCodes) *OrganizationDefaultTaxCodesQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *OrganizationDefaultTaxCodesQuery) Limit(limit int) *OrganizationDefaultTaxCodesQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *OrganizationDefaultTaxCodesQuery) Offset(offset int) *OrganizationDefaultTaxCodesQuery { + _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 *OrganizationDefaultTaxCodesQuery) Unique(unique bool) *OrganizationDefaultTaxCodesQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *OrganizationDefaultTaxCodesQuery) Order(o ...organizationdefaulttaxcodes.OrderOption) *OrganizationDefaultTaxCodesQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryInvoicingTaxCode chains the current query on the "invoicing_tax_code" edge. +func (_q *OrganizationDefaultTaxCodesQuery) QueryInvoicingTaxCode() *TaxCodeQuery { + query := (&TaxCodeClient{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(organizationdefaulttaxcodes.Table, organizationdefaulttaxcodes.FieldID, selector), + sqlgraph.To(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, organizationdefaulttaxcodes.InvoicingTaxCodeTable, organizationdefaulttaxcodes.InvoicingTaxCodeColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCreditGrantTaxCode chains the current query on the "credit_grant_tax_code" edge. +func (_q *OrganizationDefaultTaxCodesQuery) QueryCreditGrantTaxCode() *TaxCodeQuery { + query := (&TaxCodeClient{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(organizationdefaulttaxcodes.Table, organizationdefaulttaxcodes.FieldID, selector), + sqlgraph.To(dbtaxcode.Table, dbtaxcode.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, organizationdefaulttaxcodes.CreditGrantTaxCodeTable, organizationdefaulttaxcodes.CreditGrantTaxCodeColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first OrganizationDefaultTaxCodes entity from the query. +// Returns a *NotFoundError when no OrganizationDefaultTaxCodes was found. +func (_q *OrganizationDefaultTaxCodesQuery) First(ctx context.Context) (*OrganizationDefaultTaxCodes, 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{organizationdefaulttaxcodes.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *OrganizationDefaultTaxCodesQuery) FirstX(ctx context.Context) *OrganizationDefaultTaxCodes { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first OrganizationDefaultTaxCodes ID from the query. +// Returns a *NotFoundError when no OrganizationDefaultTaxCodes ID was found. +func (_q *OrganizationDefaultTaxCodesQuery) 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{organizationdefaulttaxcodes.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *OrganizationDefaultTaxCodesQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single OrganizationDefaultTaxCodes entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one OrganizationDefaultTaxCodes entity is found. +// Returns a *NotFoundError when no OrganizationDefaultTaxCodes entities are found. +func (_q *OrganizationDefaultTaxCodesQuery) Only(ctx context.Context) (*OrganizationDefaultTaxCodes, 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{organizationdefaulttaxcodes.Label} + default: + return nil, &NotSingularError{organizationdefaulttaxcodes.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *OrganizationDefaultTaxCodesQuery) OnlyX(ctx context.Context) *OrganizationDefaultTaxCodes { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only OrganizationDefaultTaxCodes ID in the query. +// Returns a *NotSingularError when more than one OrganizationDefaultTaxCodes ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *OrganizationDefaultTaxCodesQuery) 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{organizationdefaulttaxcodes.Label} + default: + err = &NotSingularError{organizationdefaulttaxcodes.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *OrganizationDefaultTaxCodesQuery) 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 OrganizationDefaultTaxCodesSlice. +func (_q *OrganizationDefaultTaxCodesQuery) All(ctx context.Context) ([]*OrganizationDefaultTaxCodes, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*OrganizationDefaultTaxCodes, *OrganizationDefaultTaxCodesQuery]() + return withInterceptors[[]*OrganizationDefaultTaxCodes](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *OrganizationDefaultTaxCodesQuery) AllX(ctx context.Context) []*OrganizationDefaultTaxCodes { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of OrganizationDefaultTaxCodes IDs. +func (_q *OrganizationDefaultTaxCodesQuery) 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(organizationdefaulttaxcodes.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *OrganizationDefaultTaxCodesQuery) 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 *OrganizationDefaultTaxCodesQuery) 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[*OrganizationDefaultTaxCodesQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *OrganizationDefaultTaxCodesQuery) 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 *OrganizationDefaultTaxCodesQuery) 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 *OrganizationDefaultTaxCodesQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the OrganizationDefaultTaxCodesQuery 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 *OrganizationDefaultTaxCodesQuery) Clone() *OrganizationDefaultTaxCodesQuery { + if _q == nil { + return nil + } + return &OrganizationDefaultTaxCodesQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]organizationdefaulttaxcodes.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.OrganizationDefaultTaxCodes{}, _q.predicates...), + withInvoicingTaxCode: _q.withInvoicingTaxCode.Clone(), + withCreditGrantTaxCode: _q.withCreditGrantTaxCode.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithInvoicingTaxCode tells the query-builder to eager-load the nodes that are connected to +// the "invoicing_tax_code" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *OrganizationDefaultTaxCodesQuery) WithInvoicingTaxCode(opts ...func(*TaxCodeQuery)) *OrganizationDefaultTaxCodesQuery { + query := (&TaxCodeClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withInvoicingTaxCode = query + return _q +} + +// WithCreditGrantTaxCode tells the query-builder to eager-load the nodes that are connected to +// the "credit_grant_tax_code" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *OrganizationDefaultTaxCodesQuery) WithCreditGrantTaxCode(opts ...func(*TaxCodeQuery)) *OrganizationDefaultTaxCodesQuery { + query := (&TaxCodeClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCreditGrantTaxCode = 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 { +// CreatedAt time.Time `json:"created_at,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.OrganizationDefaultTaxCodes.Query(). +// GroupBy(organizationdefaulttaxcodes.FieldCreatedAt). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *OrganizationDefaultTaxCodesQuery) GroupBy(field string, fields ...string) *OrganizationDefaultTaxCodesGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &OrganizationDefaultTaxCodesGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = organizationdefaulttaxcodes.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 { +// CreatedAt time.Time `json:"created_at,omitempty"` +// } +// +// client.OrganizationDefaultTaxCodes.Query(). +// Select(organizationdefaulttaxcodes.FieldCreatedAt). +// Scan(ctx, &v) +func (_q *OrganizationDefaultTaxCodesQuery) Select(fields ...string) *OrganizationDefaultTaxCodesSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &OrganizationDefaultTaxCodesSelect{OrganizationDefaultTaxCodesQuery: _q} + sbuild.label = organizationdefaulttaxcodes.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a OrganizationDefaultTaxCodesSelect configured with the given aggregations. +func (_q *OrganizationDefaultTaxCodesQuery) Aggregate(fns ...AggregateFunc) *OrganizationDefaultTaxCodesSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *OrganizationDefaultTaxCodesQuery) 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 !organizationdefaulttaxcodes.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 *OrganizationDefaultTaxCodesQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*OrganizationDefaultTaxCodes, error) { + var ( + nodes = []*OrganizationDefaultTaxCodes{} + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withInvoicingTaxCode != nil, + _q.withCreditGrantTaxCode != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*OrganizationDefaultTaxCodes).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &OrganizationDefaultTaxCodes{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.withInvoicingTaxCode; query != nil { + if err := _q.loadInvoicingTaxCode(ctx, query, nodes, nil, + func(n *OrganizationDefaultTaxCodes, e *TaxCode) { n.Edges.InvoicingTaxCode = e }); err != nil { + return nil, err + } + } + if query := _q.withCreditGrantTaxCode; query != nil { + if err := _q.loadCreditGrantTaxCode(ctx, query, nodes, nil, + func(n *OrganizationDefaultTaxCodes, e *TaxCode) { n.Edges.CreditGrantTaxCode = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *OrganizationDefaultTaxCodesQuery) loadInvoicingTaxCode(ctx context.Context, query *TaxCodeQuery, nodes []*OrganizationDefaultTaxCodes, init func(*OrganizationDefaultTaxCodes), assign func(*OrganizationDefaultTaxCodes, *TaxCode)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*OrganizationDefaultTaxCodes) + for i := range nodes { + fk := nodes[i].InvoicingTaxCodeID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(dbtaxcode.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 "invoicing_tax_code_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *OrganizationDefaultTaxCodesQuery) loadCreditGrantTaxCode(ctx context.Context, query *TaxCodeQuery, nodes []*OrganizationDefaultTaxCodes, init func(*OrganizationDefaultTaxCodes), assign func(*OrganizationDefaultTaxCodes, *TaxCode)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*OrganizationDefaultTaxCodes) + for i := range nodes { + fk := nodes[i].CreditGrantTaxCodeID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(dbtaxcode.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 "credit_grant_tax_code_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *OrganizationDefaultTaxCodesQuery) 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 *OrganizationDefaultTaxCodesQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(organizationdefaulttaxcodes.Table, organizationdefaulttaxcodes.Columns, sqlgraph.NewFieldSpec(organizationdefaulttaxcodes.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, organizationdefaulttaxcodes.FieldID) + for i := range fields { + if fields[i] != organizationdefaulttaxcodes.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withInvoicingTaxCode != nil { + _spec.Node.AddColumnOnce(organizationdefaulttaxcodes.FieldInvoicingTaxCodeID) + } + if _q.withCreditGrantTaxCode != nil { + _spec.Node.AddColumnOnce(organizationdefaulttaxcodes.FieldCreditGrantTaxCodeID) + } + } + 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 *OrganizationDefaultTaxCodesQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(organizationdefaulttaxcodes.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = organizationdefaulttaxcodes.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 *OrganizationDefaultTaxCodesQuery) ForUpdate(opts ...sql.LockOption) *OrganizationDefaultTaxCodesQuery { + 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 *OrganizationDefaultTaxCodesQuery) ForShare(opts ...sql.LockOption) *OrganizationDefaultTaxCodesQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// OrganizationDefaultTaxCodesGroupBy is the group-by builder for OrganizationDefaultTaxCodes entities. +type OrganizationDefaultTaxCodesGroupBy struct { + selector + build *OrganizationDefaultTaxCodesQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *OrganizationDefaultTaxCodesGroupBy) Aggregate(fns ...AggregateFunc) *OrganizationDefaultTaxCodesGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *OrganizationDefaultTaxCodesGroupBy) 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[*OrganizationDefaultTaxCodesQuery, *OrganizationDefaultTaxCodesGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *OrganizationDefaultTaxCodesGroupBy) sqlScan(ctx context.Context, root *OrganizationDefaultTaxCodesQuery, 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) +} + +// OrganizationDefaultTaxCodesSelect is the builder for selecting fields of OrganizationDefaultTaxCodes entities. +type OrganizationDefaultTaxCodesSelect struct { + *OrganizationDefaultTaxCodesQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *OrganizationDefaultTaxCodesSelect) Aggregate(fns ...AggregateFunc) *OrganizationDefaultTaxCodesSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *OrganizationDefaultTaxCodesSelect) 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[*OrganizationDefaultTaxCodesQuery, *OrganizationDefaultTaxCodesSelect](ctx, _s.OrganizationDefaultTaxCodesQuery, _s, _s.inters, v) +} + +func (_s *OrganizationDefaultTaxCodesSelect) sqlScan(ctx context.Context, root *OrganizationDefaultTaxCodesQuery, 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/ent/db/organizationdefaulttaxcodes_update.go b/ent/db/organizationdefaulttaxcodes_update.go new file mode 100644 index 0000000000000000000000000000000000000000..0dc7091956b02ff58a7d8ece3b08ef6779113dd6 --- /dev/null +++ b/ent/db/organizationdefaulttaxcodes_update.go @@ -0,0 +1,509 @@ +// 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/openmeterio/openmeter/openmeter/ent/db/organizationdefaulttaxcodes" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + dbtaxcode "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode" +) + +// OrganizationDefaultTaxCodesUpdate is the builder for updating OrganizationDefaultTaxCodes entities. +type OrganizationDefaultTaxCodesUpdate struct { + config + hooks []Hook + mutation *OrganizationDefaultTaxCodesMutation +} + +// Where appends a list predicates to the OrganizationDefaultTaxCodesUpdate builder. +func (_u *OrganizationDefaultTaxCodesUpdate) Where(ps ...predicate.OrganizationDefaultTaxCodes) *OrganizationDefaultTaxCodesUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *OrganizationDefaultTaxCodesUpdate) SetUpdatedAt(v time.Time) *OrganizationDefaultTaxCodesUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *OrganizationDefaultTaxCodesUpdate) SetDeletedAt(v time.Time) *OrganizationDefaultTaxCodesUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *OrganizationDefaultTaxCodesUpdate) SetNillableDeletedAt(v *time.Time) *OrganizationDefaultTaxCodesUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *OrganizationDefaultTaxCodesUpdate) ClearDeletedAt() *OrganizationDefaultTaxCodesUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetInvoicingTaxCodeID sets the "invoicing_tax_code_id" field. +func (_u *OrganizationDefaultTaxCodesUpdate) SetInvoicingTaxCodeID(v string) *OrganizationDefaultTaxCodesUpdate { + _u.mutation.SetInvoicingTaxCodeID(v) + return _u +} + +// SetNillableInvoicingTaxCodeID sets the "invoicing_tax_code_id" field if the given value is not nil. +func (_u *OrganizationDefaultTaxCodesUpdate) SetNillableInvoicingTaxCodeID(v *string) *OrganizationDefaultTaxCodesUpdate { + if v != nil { + _u.SetInvoicingTaxCodeID(*v) + } + return _u +} + +// SetCreditGrantTaxCodeID sets the "credit_grant_tax_code_id" field. +func (_u *OrganizationDefaultTaxCodesUpdate) SetCreditGrantTaxCodeID(v string) *OrganizationDefaultTaxCodesUpdate { + _u.mutation.SetCreditGrantTaxCodeID(v) + return _u +} + +// SetNillableCreditGrantTaxCodeID sets the "credit_grant_tax_code_id" field if the given value is not nil. +func (_u *OrganizationDefaultTaxCodesUpdate) SetNillableCreditGrantTaxCodeID(v *string) *OrganizationDefaultTaxCodesUpdate { + if v != nil { + _u.SetCreditGrantTaxCodeID(*v) + } + return _u +} + +// SetInvoicingTaxCode sets the "invoicing_tax_code" edge to the TaxCode entity. +func (_u *OrganizationDefaultTaxCodesUpdate) SetInvoicingTaxCode(v *TaxCode) *OrganizationDefaultTaxCodesUpdate { + return _u.SetInvoicingTaxCodeID(v.ID) +} + +// SetCreditGrantTaxCode sets the "credit_grant_tax_code" edge to the TaxCode entity. +func (_u *OrganizationDefaultTaxCodesUpdate) SetCreditGrantTaxCode(v *TaxCode) *OrganizationDefaultTaxCodesUpdate { + return _u.SetCreditGrantTaxCodeID(v.ID) +} + +// Mutation returns the OrganizationDefaultTaxCodesMutation object of the builder. +func (_u *OrganizationDefaultTaxCodesUpdate) Mutation() *OrganizationDefaultTaxCodesMutation { + return _u.mutation +} + +// ClearInvoicingTaxCode clears the "invoicing_tax_code" edge to the TaxCode entity. +func (_u *OrganizationDefaultTaxCodesUpdate) ClearInvoicingTaxCode() *OrganizationDefaultTaxCodesUpdate { + _u.mutation.ClearInvoicingTaxCode() + return _u +} + +// ClearCreditGrantTaxCode clears the "credit_grant_tax_code" edge to the TaxCode entity. +func (_u *OrganizationDefaultTaxCodesUpdate) ClearCreditGrantTaxCode() *OrganizationDefaultTaxCodesUpdate { + _u.mutation.ClearCreditGrantTaxCode() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *OrganizationDefaultTaxCodesUpdate) 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 *OrganizationDefaultTaxCodesUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *OrganizationDefaultTaxCodesUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *OrganizationDefaultTaxCodesUpdate) 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 *OrganizationDefaultTaxCodesUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := organizationdefaulttaxcodes.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *OrganizationDefaultTaxCodesUpdate) check() error { + if _u.mutation.InvoicingTaxCodeCleared() && len(_u.mutation.InvoicingTaxCodeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "OrganizationDefaultTaxCodes.invoicing_tax_code"`) + } + if _u.mutation.CreditGrantTaxCodeCleared() && len(_u.mutation.CreditGrantTaxCodeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "OrganizationDefaultTaxCodes.credit_grant_tax_code"`) + } + return nil +} + +func (_u *OrganizationDefaultTaxCodesUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(organizationdefaulttaxcodes.Table, organizationdefaulttaxcodes.Columns, sqlgraph.NewFieldSpec(organizationdefaulttaxcodes.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(organizationdefaulttaxcodes.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(organizationdefaulttaxcodes.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(organizationdefaulttaxcodes.FieldDeletedAt, field.TypeTime) + } + if _u.mutation.InvoicingTaxCodeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: organizationdefaulttaxcodes.InvoicingTaxCodeTable, + Columns: []string{organizationdefaulttaxcodes.InvoicingTaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.InvoicingTaxCodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: organizationdefaulttaxcodes.InvoicingTaxCodeTable, + Columns: []string{organizationdefaulttaxcodes.InvoicingTaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.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.CreditGrantTaxCodeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: organizationdefaulttaxcodes.CreditGrantTaxCodeTable, + Columns: []string{organizationdefaulttaxcodes.CreditGrantTaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.CreditGrantTaxCodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: organizationdefaulttaxcodes.CreditGrantTaxCodeTable, + Columns: []string{organizationdefaulttaxcodes.CreditGrantTaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.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{organizationdefaulttaxcodes.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// OrganizationDefaultTaxCodesUpdateOne is the builder for updating a single OrganizationDefaultTaxCodes entity. +type OrganizationDefaultTaxCodesUpdateOne struct { + config + fields []string + hooks []Hook + mutation *OrganizationDefaultTaxCodesMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *OrganizationDefaultTaxCodesUpdateOne) SetUpdatedAt(v time.Time) *OrganizationDefaultTaxCodesUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *OrganizationDefaultTaxCodesUpdateOne) SetDeletedAt(v time.Time) *OrganizationDefaultTaxCodesUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *OrganizationDefaultTaxCodesUpdateOne) SetNillableDeletedAt(v *time.Time) *OrganizationDefaultTaxCodesUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *OrganizationDefaultTaxCodesUpdateOne) ClearDeletedAt() *OrganizationDefaultTaxCodesUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetInvoicingTaxCodeID sets the "invoicing_tax_code_id" field. +func (_u *OrganizationDefaultTaxCodesUpdateOne) SetInvoicingTaxCodeID(v string) *OrganizationDefaultTaxCodesUpdateOne { + _u.mutation.SetInvoicingTaxCodeID(v) + return _u +} + +// SetNillableInvoicingTaxCodeID sets the "invoicing_tax_code_id" field if the given value is not nil. +func (_u *OrganizationDefaultTaxCodesUpdateOne) SetNillableInvoicingTaxCodeID(v *string) *OrganizationDefaultTaxCodesUpdateOne { + if v != nil { + _u.SetInvoicingTaxCodeID(*v) + } + return _u +} + +// SetCreditGrantTaxCodeID sets the "credit_grant_tax_code_id" field. +func (_u *OrganizationDefaultTaxCodesUpdateOne) SetCreditGrantTaxCodeID(v string) *OrganizationDefaultTaxCodesUpdateOne { + _u.mutation.SetCreditGrantTaxCodeID(v) + return _u +} + +// SetNillableCreditGrantTaxCodeID sets the "credit_grant_tax_code_id" field if the given value is not nil. +func (_u *OrganizationDefaultTaxCodesUpdateOne) SetNillableCreditGrantTaxCodeID(v *string) *OrganizationDefaultTaxCodesUpdateOne { + if v != nil { + _u.SetCreditGrantTaxCodeID(*v) + } + return _u +} + +// SetInvoicingTaxCode sets the "invoicing_tax_code" edge to the TaxCode entity. +func (_u *OrganizationDefaultTaxCodesUpdateOne) SetInvoicingTaxCode(v *TaxCode) *OrganizationDefaultTaxCodesUpdateOne { + return _u.SetInvoicingTaxCodeID(v.ID) +} + +// SetCreditGrantTaxCode sets the "credit_grant_tax_code" edge to the TaxCode entity. +func (_u *OrganizationDefaultTaxCodesUpdateOne) SetCreditGrantTaxCode(v *TaxCode) *OrganizationDefaultTaxCodesUpdateOne { + return _u.SetCreditGrantTaxCodeID(v.ID) +} + +// Mutation returns the OrganizationDefaultTaxCodesMutation object of the builder. +func (_u *OrganizationDefaultTaxCodesUpdateOne) Mutation() *OrganizationDefaultTaxCodesMutation { + return _u.mutation +} + +// ClearInvoicingTaxCode clears the "invoicing_tax_code" edge to the TaxCode entity. +func (_u *OrganizationDefaultTaxCodesUpdateOne) ClearInvoicingTaxCode() *OrganizationDefaultTaxCodesUpdateOne { + _u.mutation.ClearInvoicingTaxCode() + return _u +} + +// ClearCreditGrantTaxCode clears the "credit_grant_tax_code" edge to the TaxCode entity. +func (_u *OrganizationDefaultTaxCodesUpdateOne) ClearCreditGrantTaxCode() *OrganizationDefaultTaxCodesUpdateOne { + _u.mutation.ClearCreditGrantTaxCode() + return _u +} + +// Where appends a list predicates to the OrganizationDefaultTaxCodesUpdate builder. +func (_u *OrganizationDefaultTaxCodesUpdateOne) Where(ps ...predicate.OrganizationDefaultTaxCodes) *OrganizationDefaultTaxCodesUpdateOne { + _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 *OrganizationDefaultTaxCodesUpdateOne) Select(field string, fields ...string) *OrganizationDefaultTaxCodesUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated OrganizationDefaultTaxCodes entity. +func (_u *OrganizationDefaultTaxCodesUpdateOne) Save(ctx context.Context) (*OrganizationDefaultTaxCodes, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *OrganizationDefaultTaxCodesUpdateOne) SaveX(ctx context.Context) *OrganizationDefaultTaxCodes { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *OrganizationDefaultTaxCodesUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *OrganizationDefaultTaxCodesUpdateOne) 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 *OrganizationDefaultTaxCodesUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := organizationdefaulttaxcodes.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *OrganizationDefaultTaxCodesUpdateOne) check() error { + if _u.mutation.InvoicingTaxCodeCleared() && len(_u.mutation.InvoicingTaxCodeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "OrganizationDefaultTaxCodes.invoicing_tax_code"`) + } + if _u.mutation.CreditGrantTaxCodeCleared() && len(_u.mutation.CreditGrantTaxCodeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "OrganizationDefaultTaxCodes.credit_grant_tax_code"`) + } + return nil +} + +func (_u *OrganizationDefaultTaxCodesUpdateOne) sqlSave(ctx context.Context) (_node *OrganizationDefaultTaxCodes, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(organizationdefaulttaxcodes.Table, organizationdefaulttaxcodes.Columns, sqlgraph.NewFieldSpec(organizationdefaulttaxcodes.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "OrganizationDefaultTaxCodes.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, organizationdefaulttaxcodes.FieldID) + for _, f := range fields { + if !organizationdefaulttaxcodes.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != organizationdefaulttaxcodes.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(organizationdefaulttaxcodes.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(organizationdefaulttaxcodes.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(organizationdefaulttaxcodes.FieldDeletedAt, field.TypeTime) + } + if _u.mutation.InvoicingTaxCodeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: organizationdefaulttaxcodes.InvoicingTaxCodeTable, + Columns: []string{organizationdefaulttaxcodes.InvoicingTaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.InvoicingTaxCodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: organizationdefaulttaxcodes.InvoicingTaxCodeTable, + Columns: []string{organizationdefaulttaxcodes.InvoicingTaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.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.CreditGrantTaxCodeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: organizationdefaulttaxcodes.CreditGrantTaxCodeTable, + Columns: []string{organizationdefaulttaxcodes.CreditGrantTaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.CreditGrantTaxCodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: organizationdefaulttaxcodes.CreditGrantTaxCodeTable, + Columns: []string{organizationdefaulttaxcodes.CreditGrantTaxCodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(dbtaxcode.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &OrganizationDefaultTaxCodes{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{organizationdefaulttaxcodes.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/ent/db/paginate.go b/ent/db/paginate.go new file mode 100644 index 0000000000000000000000000000000000000000..bd7a7c9ce5bae01f69e5141207ad5685ccd881ed --- /dev/null +++ b/ent/db/paginate.go @@ -0,0 +1,4824 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "fmt" + + "github.com/openmeterio/openmeter/pkg/pagination" +) + +// 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 *AddonQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*Addon], 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[*Addon]{ + 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([]*Addon, 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[*Addon] = (*AddonQuery)(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 *AddonRateCardQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*AddonRateCard], 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[*AddonRateCard]{ + 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([]*AddonRateCard, 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[*AddonRateCard] = (*AddonRateCardQuery)(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 *AppQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*App], 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[*App]{ + 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([]*App, 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[*App] = (*AppQuery)(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 *AppCustomInvoicingQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*AppCustomInvoicing], 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[*AppCustomInvoicing]{ + 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([]*AppCustomInvoicing, 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[*AppCustomInvoicing] = (*AppCustomInvoicingQuery)(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 *AppCustomInvoicingCustomerQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*AppCustomInvoicingCustomer], 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[*AppCustomInvoicingCustomer]{ + 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([]*AppCustomInvoicingCustomer, 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[*AppCustomInvoicingCustomer] = (*AppCustomInvoicingCustomerQuery)(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 *AppCustomerQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*AppCustomer], 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[*AppCustomer]{ + 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([]*AppCustomer, 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[*AppCustomer] = (*AppCustomerQuery)(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 *AppStripeQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*AppStripe], 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[*AppStripe]{ + 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([]*AppStripe, 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[*AppStripe] = (*AppStripeQuery)(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 *AppStripeCustomerQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*AppStripeCustomer], 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[*AppStripeCustomer]{ + 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([]*AppStripeCustomer, 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[*AppStripeCustomer] = (*AppStripeCustomerQuery)(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 *BalanceSnapshotQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*BalanceSnapshot], 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[*BalanceSnapshot]{ + 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([]*BalanceSnapshot, 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[*BalanceSnapshot] = (*BalanceSnapshotQuery)(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 *BillingCustomerLockQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*BillingCustomerLock], 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[*BillingCustomerLock]{ + 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([]*BillingCustomerLock, 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[*BillingCustomerLock] = (*BillingCustomerLockQuery)(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 *BillingCustomerOverrideQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*BillingCustomerOverride], 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[*BillingCustomerOverride]{ + 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([]*BillingCustomerOverride, 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[*BillingCustomerOverride] = (*BillingCustomerOverrideQuery)(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 *BillingInvoiceQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*BillingInvoice], 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[*BillingInvoice]{ + 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([]*BillingInvoice, 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[*BillingInvoice] = (*BillingInvoiceQuery)(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 *BillingInvoiceFlatFeeLineConfigQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*BillingInvoiceFlatFeeLineConfig], 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[*BillingInvoiceFlatFeeLineConfig]{ + 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([]*BillingInvoiceFlatFeeLineConfig, 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[*BillingInvoiceFlatFeeLineConfig] = (*BillingInvoiceFlatFeeLineConfigQuery)(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 *BillingInvoiceLineQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*BillingInvoiceLine], 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[*BillingInvoiceLine]{ + 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([]*BillingInvoiceLine, 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[*BillingInvoiceLine] = (*BillingInvoiceLineQuery)(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 *BillingInvoiceLineDiscountQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*BillingInvoiceLineDiscount], 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[*BillingInvoiceLineDiscount]{ + 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([]*BillingInvoiceLineDiscount, 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[*BillingInvoiceLineDiscount] = (*BillingInvoiceLineDiscountQuery)(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 *BillingInvoiceLineUsageDiscountQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*BillingInvoiceLineUsageDiscount], 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[*BillingInvoiceLineUsageDiscount]{ + 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([]*BillingInvoiceLineUsageDiscount, 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[*BillingInvoiceLineUsageDiscount] = (*BillingInvoiceLineUsageDiscountQuery)(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 *BillingInvoiceSplitLineGroupQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*BillingInvoiceSplitLineGroup], 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[*BillingInvoiceSplitLineGroup]{ + 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([]*BillingInvoiceSplitLineGroup, 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[*BillingInvoiceSplitLineGroup] = (*BillingInvoiceSplitLineGroupQuery)(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 *BillingInvoiceUsageBasedLineConfigQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*BillingInvoiceUsageBasedLineConfig], 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[*BillingInvoiceUsageBasedLineConfig]{ + 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([]*BillingInvoiceUsageBasedLineConfig, 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[*BillingInvoiceUsageBasedLineConfig] = (*BillingInvoiceUsageBasedLineConfigQuery)(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 *BillingInvoiceValidationIssueQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*BillingInvoiceValidationIssue], 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[*BillingInvoiceValidationIssue]{ + 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([]*BillingInvoiceValidationIssue, 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[*BillingInvoiceValidationIssue] = (*BillingInvoiceValidationIssueQuery)(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 *BillingInvoiceWriteSchemaLevelQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*BillingInvoiceWriteSchemaLevel], 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[*BillingInvoiceWriteSchemaLevel]{ + 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([]*BillingInvoiceWriteSchemaLevel, 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[*BillingInvoiceWriteSchemaLevel] = (*BillingInvoiceWriteSchemaLevelQuery)(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 *BillingProfileQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*BillingProfile], 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[*BillingProfile]{ + 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([]*BillingProfile, 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[*BillingProfile] = (*BillingProfileQuery)(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 *BillingSequenceNumbersQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*BillingSequenceNumbers], 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[*BillingSequenceNumbers]{ + 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([]*BillingSequenceNumbers, 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[*BillingSequenceNumbers] = (*BillingSequenceNumbersQuery)(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 *BillingStandardInvoiceDetailedLineQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*BillingStandardInvoiceDetailedLine], 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[*BillingStandardInvoiceDetailedLine]{ + 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([]*BillingStandardInvoiceDetailedLine, 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[*BillingStandardInvoiceDetailedLine] = (*BillingStandardInvoiceDetailedLineQuery)(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 *BillingStandardInvoiceDetailedLineAmountDiscountQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*BillingStandardInvoiceDetailedLineAmountDiscount], 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[*BillingStandardInvoiceDetailedLineAmountDiscount]{ + 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([]*BillingStandardInvoiceDetailedLineAmountDiscount, 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[*BillingStandardInvoiceDetailedLineAmountDiscount] = (*BillingStandardInvoiceDetailedLineAmountDiscountQuery)(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 *BillingWorkflowConfigQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*BillingWorkflowConfig], 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[*BillingWorkflowConfig]{ + 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([]*BillingWorkflowConfig, 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[*BillingWorkflowConfig] = (*BillingWorkflowConfigQuery)(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 *ChargeQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*Charge], 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[*Charge]{ + 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([]*Charge, 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[*Charge] = (*ChargeQuery)(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 *ChargeCreditPurchaseQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*ChargeCreditPurchase], 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[*ChargeCreditPurchase]{ + 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([]*ChargeCreditPurchase, 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[*ChargeCreditPurchase] = (*ChargeCreditPurchaseQuery)(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 *ChargeCreditPurchaseCreditGrantQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*ChargeCreditPurchaseCreditGrant], 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[*ChargeCreditPurchaseCreditGrant]{ + 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([]*ChargeCreditPurchaseCreditGrant, 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[*ChargeCreditPurchaseCreditGrant] = (*ChargeCreditPurchaseCreditGrantQuery)(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 *ChargeCreditPurchaseExternalPaymentQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*ChargeCreditPurchaseExternalPayment], 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[*ChargeCreditPurchaseExternalPayment]{ + 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([]*ChargeCreditPurchaseExternalPayment, 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[*ChargeCreditPurchaseExternalPayment] = (*ChargeCreditPurchaseExternalPaymentQuery)(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 *ChargeCreditPurchaseInvoicedPaymentQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*ChargeCreditPurchaseInvoicedPayment], 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[*ChargeCreditPurchaseInvoicedPayment]{ + 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([]*ChargeCreditPurchaseInvoicedPayment, 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[*ChargeCreditPurchaseInvoicedPayment] = (*ChargeCreditPurchaseInvoicedPaymentQuery)(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 *ChargeFlatFeeQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*ChargeFlatFee], 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[*ChargeFlatFee]{ + 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([]*ChargeFlatFee, 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[*ChargeFlatFee] = (*ChargeFlatFeeQuery)(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 *ChargeFlatFeeOverrideQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*ChargeFlatFeeOverride], 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[*ChargeFlatFeeOverride]{ + 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([]*ChargeFlatFeeOverride, 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[*ChargeFlatFeeOverride] = (*ChargeFlatFeeOverrideQuery)(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 *ChargeFlatFeeRunQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*ChargeFlatFeeRun], 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[*ChargeFlatFeeRun]{ + 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([]*ChargeFlatFeeRun, 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[*ChargeFlatFeeRun] = (*ChargeFlatFeeRunQuery)(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 *ChargeFlatFeeRunCreditAllocationsQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*ChargeFlatFeeRunCreditAllocations], 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[*ChargeFlatFeeRunCreditAllocations]{ + 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([]*ChargeFlatFeeRunCreditAllocations, 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[*ChargeFlatFeeRunCreditAllocations] = (*ChargeFlatFeeRunCreditAllocationsQuery)(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 *ChargeFlatFeeRunDetailedLineQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*ChargeFlatFeeRunDetailedLine], 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[*ChargeFlatFeeRunDetailedLine]{ + 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([]*ChargeFlatFeeRunDetailedLine, 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[*ChargeFlatFeeRunDetailedLine] = (*ChargeFlatFeeRunDetailedLineQuery)(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 *ChargeFlatFeeRunInvoicedUsageQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*ChargeFlatFeeRunInvoicedUsage], 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[*ChargeFlatFeeRunInvoicedUsage]{ + 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([]*ChargeFlatFeeRunInvoicedUsage, 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[*ChargeFlatFeeRunInvoicedUsage] = (*ChargeFlatFeeRunInvoicedUsageQuery)(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 *ChargeFlatFeeRunPaymentQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*ChargeFlatFeeRunPayment], 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[*ChargeFlatFeeRunPayment]{ + 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([]*ChargeFlatFeeRunPayment, 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[*ChargeFlatFeeRunPayment] = (*ChargeFlatFeeRunPaymentQuery)(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 *ChargeUsageBasedOverrideQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*ChargeUsageBasedOverride], 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[*ChargeUsageBasedOverride]{ + 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([]*ChargeUsageBasedOverride, 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[*ChargeUsageBasedOverride] = (*ChargeUsageBasedOverrideQuery)(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 *ChargeUsageBasedRunDetailedLineQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*ChargeUsageBasedRunDetailedLine], 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[*ChargeUsageBasedRunDetailedLine]{ + 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([]*ChargeUsageBasedRunDetailedLine, 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[*ChargeUsageBasedRunDetailedLine] = (*ChargeUsageBasedRunDetailedLineQuery)(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 *ChargesSearchV1Query) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*ChargesSearchV1], 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[*ChargesSearchV1]{ + 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([]*ChargesSearchV1, 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[*ChargesSearchV1] = (*ChargesSearchV1Query)(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 *CreditRealizationLineageQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*CreditRealizationLineage], 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[*CreditRealizationLineage]{ + 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([]*CreditRealizationLineage, 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[*CreditRealizationLineage] = (*CreditRealizationLineageQuery)(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 *CreditRealizationLineageSegmentQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*CreditRealizationLineageSegment], 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[*CreditRealizationLineageSegment]{ + 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([]*CreditRealizationLineageSegment, 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[*CreditRealizationLineageSegment] = (*CreditRealizationLineageSegmentQuery)(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) { + // 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[*CurrencyCostBasis]{ + 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([]*CurrencyCostBasis, 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[*CurrencyCostBasis] = (*CurrencyCostBasisQuery)(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 *CustomCurrencyQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*CustomCurrency], 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[*CustomCurrency]{ + 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([]*CustomCurrency, 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[*CustomCurrency] = (*CustomCurrencyQuery)(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 *CustomerQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*Customer], 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[*Customer]{ + 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([]*Customer, 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[*Customer] = (*CustomerQuery)(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 *CustomerSubjectsQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*CustomerSubjects], 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[*CustomerSubjects]{ + 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([]*CustomerSubjects, 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[*CustomerSubjects] = (*CustomerSubjectsQuery)(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 *EntitlementQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*Entitlement], 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[*Entitlement]{ + 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([]*Entitlement, 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[*Entitlement] = (*EntitlementQuery)(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 *FeatureQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*Feature], 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[*Feature]{ + 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([]*Feature, 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[*Feature] = (*FeatureQuery)(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 *GrantQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*Grant], 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[*Grant]{ + 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([]*Grant, 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[*Grant] = (*GrantQuery)(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 *LLMCostPriceQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*LLMCostPrice], 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[*LLMCostPrice]{ + 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([]*LLMCostPrice, 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[*LLMCostPrice] = (*LLMCostPriceQuery)(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 *LedgerAccountQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*LedgerAccount], 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[*LedgerAccount]{ + 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([]*LedgerAccount, 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[*LedgerAccount] = (*LedgerAccountQuery)(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 *LedgerBreakageRecordQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*LedgerBreakageRecord], 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[*LedgerBreakageRecord]{ + 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([]*LedgerBreakageRecord, 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[*LedgerBreakageRecord] = (*LedgerBreakageRecordQuery)(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 *LedgerCreditVoidRecordQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*LedgerCreditVoidRecord], 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[*LedgerCreditVoidRecord]{ + 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([]*LedgerCreditVoidRecord, 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[*LedgerCreditVoidRecord] = (*LedgerCreditVoidRecordQuery)(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 *LedgerCustomerAccountQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*LedgerCustomerAccount], 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[*LedgerCustomerAccount]{ + 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([]*LedgerCustomerAccount, 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[*LedgerCustomerAccount] = (*LedgerCustomerAccountQuery)(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 *LedgerEntryQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*LedgerEntry], 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[*LedgerEntry]{ + 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([]*LedgerEntry, 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[*LedgerEntry] = (*LedgerEntryQuery)(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 *LedgerSubAccountQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*LedgerSubAccount], 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[*LedgerSubAccount]{ + 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([]*LedgerSubAccount, 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[*LedgerSubAccount] = (*LedgerSubAccountQuery)(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 *LedgerSubAccountRouteQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*LedgerSubAccountRoute], 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[*LedgerSubAccountRoute]{ + 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([]*LedgerSubAccountRoute, 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[*LedgerSubAccountRoute] = (*LedgerSubAccountRouteQuery)(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 *LedgerTransactionQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*LedgerTransaction], 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[*LedgerTransaction]{ + 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([]*LedgerTransaction, 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[*LedgerTransaction] = (*LedgerTransactionQuery)(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 *LedgerTransactionGroupQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*LedgerTransactionGroup], 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[*LedgerTransactionGroup]{ + 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([]*LedgerTransactionGroup, 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[*LedgerTransactionGroup] = (*LedgerTransactionGroupQuery)(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 *MeterQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*Meter], 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[*Meter]{ + 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([]*Meter, 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[*Meter] = (*MeterQuery)(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 *NotificationChannelQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*NotificationChannel], 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[*NotificationChannel]{ + 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([]*NotificationChannel, 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[*NotificationChannel] = (*NotificationChannelQuery)(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 *NotificationEventQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*NotificationEvent], 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[*NotificationEvent]{ + 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([]*NotificationEvent, 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[*NotificationEvent] = (*NotificationEventQuery)(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 *NotificationEventDeliveryStatusQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*NotificationEventDeliveryStatus], 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[*NotificationEventDeliveryStatus]{ + 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([]*NotificationEventDeliveryStatus, 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[*NotificationEventDeliveryStatus] = (*NotificationEventDeliveryStatusQuery)(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 *NotificationRuleQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*NotificationRule], 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[*NotificationRule]{ + 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([]*NotificationRule, 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[*NotificationRule] = (*NotificationRuleQuery)(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 *OrganizationDefaultTaxCodesQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*OrganizationDefaultTaxCodes], 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[*OrganizationDefaultTaxCodes]{ + 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([]*OrganizationDefaultTaxCodes, 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[*OrganizationDefaultTaxCodes] = (*OrganizationDefaultTaxCodesQuery)(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 *PlanQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*Plan], 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[*Plan]{ + 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([]*Plan, 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[*Plan] = (*PlanQuery)(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 *PlanAddonQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*PlanAddon], 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[*PlanAddon]{ + 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([]*PlanAddon, 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[*PlanAddon] = (*PlanAddonQuery)(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 *PlanPhaseQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*PlanPhase], 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[*PlanPhase]{ + 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([]*PlanPhase, 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[*PlanPhase] = (*PlanPhaseQuery)(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 *PlanRateCardQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*PlanRateCard], 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[*PlanRateCard]{ + 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([]*PlanRateCard, 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[*PlanRateCard] = (*PlanRateCardQuery)(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 *SubjectQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*Subject], 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[*Subject]{ + 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([]*Subject, 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[*Subject] = (*SubjectQuery)(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 *SubscriptionQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*Subscription], 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[*Subscription]{ + 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([]*Subscription, 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[*Subscription] = (*SubscriptionQuery)(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 *SubscriptionAddonQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*SubscriptionAddon], 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[*SubscriptionAddon]{ + 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([]*SubscriptionAddon, 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[*SubscriptionAddon] = (*SubscriptionAddonQuery)(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 *SubscriptionAddonQuantityQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*SubscriptionAddonQuantity], 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[*SubscriptionAddonQuantity]{ + 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([]*SubscriptionAddonQuantity, 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[*SubscriptionAddonQuantity] = (*SubscriptionAddonQuantityQuery)(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 *SubscriptionBillingSyncStateQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*SubscriptionBillingSyncState], 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[*SubscriptionBillingSyncState]{ + 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([]*SubscriptionBillingSyncState, 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[*SubscriptionBillingSyncState] = (*SubscriptionBillingSyncStateQuery)(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 *SubscriptionItemQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*SubscriptionItem], 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[*SubscriptionItem]{ + 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([]*SubscriptionItem, 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[*SubscriptionItem] = (*SubscriptionItemQuery)(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 *SubscriptionPhaseQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*SubscriptionPhase], 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[*SubscriptionPhase]{ + 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([]*SubscriptionPhase, 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[*SubscriptionPhase] = (*SubscriptionPhaseQuery)(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 *TaxCodeQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*TaxCode], 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[*TaxCode]{ + 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([]*TaxCode, 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[*TaxCode] = (*TaxCodeQuery)(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 *UsageResetQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*UsageReset], 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[*UsageReset]{ + 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([]*UsageReset, 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[*UsageReset] = (*UsageResetQuery)(nil) diff --git a/ent/db/plan/plan.go b/ent/db/plan/plan.go new file mode 100644 index 0000000000000000000000000000000000000000..396f905480278a2889500d40f5f5e1609814b4e5 --- /dev/null +++ b/ent/db/plan/plan.go @@ -0,0 +1,289 @@ +// Code generated by ent, DO NOT EDIT. + +package plan + +import ( + "fmt" + "time" + + "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 plan type in the database. + Label = "plan" + // 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" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // 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" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // FieldKey holds the string denoting the key field in the database. + FieldKey = "key" + // FieldVersion holds the string denoting the version field in the database. + FieldVersion = "version" + // FieldCurrency holds the string denoting the currency field in the database. + FieldCurrency = "currency" + // FieldBillingCadence holds the string denoting the billing_cadence field in the database. + FieldBillingCadence = "billing_cadence" + // FieldProRatingConfig holds the string denoting the pro_rating_config field in the database. + FieldProRatingConfig = "pro_rating_config" + // FieldEffectiveFrom holds the string denoting the effective_from field in the database. + FieldEffectiveFrom = "effective_from" + // FieldEffectiveTo holds the string denoting the effective_to field in the database. + FieldEffectiveTo = "effective_to" + // FieldSettlementMode holds the string denoting the settlement_mode field in the database. + FieldSettlementMode = "settlement_mode" + // EdgePhases holds the string denoting the phases edge name in mutations. + EdgePhases = "phases" + // EdgeAddons holds the string denoting the addons edge name in mutations. + EdgeAddons = "addons" + // EdgeSubscriptions holds the string denoting the subscriptions edge name in mutations. + EdgeSubscriptions = "subscriptions" + // Table holds the table name of the plan in the database. + Table = "plans" + // PhasesTable is the table that holds the phases relation/edge. + PhasesTable = "plan_phases" + // PhasesInverseTable is the table name for the PlanPhase entity. + // It exists in this package in order to avoid circular dependency with the "planphase" package. + PhasesInverseTable = "plan_phases" + // PhasesColumn is the table column denoting the phases relation/edge. + PhasesColumn = "plan_id" + // AddonsTable is the table that holds the addons relation/edge. + AddonsTable = "plan_addons" + // AddonsInverseTable is the table name for the PlanAddon entity. + // It exists in this package in order to avoid circular dependency with the "planaddon" package. + AddonsInverseTable = "plan_addons" + // AddonsColumn is the table column denoting the addons relation/edge. + AddonsColumn = "plan_id" + // SubscriptionsTable is the table that holds the subscriptions relation/edge. + SubscriptionsTable = "subscriptions" + // SubscriptionsInverseTable is the table name for the Subscription entity. + // It exists in this package in order to avoid circular dependency with the "subscription" package. + SubscriptionsInverseTable = "subscriptions" + // SubscriptionsColumn is the table column denoting the subscriptions relation/edge. + SubscriptionsColumn = "plan_id" +) + +// Columns holds all SQL columns for plan fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldMetadata, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldName, + FieldDescription, + FieldKey, + FieldVersion, + FieldCurrency, + FieldBillingCadence, + FieldProRatingConfig, + FieldEffectiveFrom, + FieldEffectiveTo, + FieldSettlementMode, +} + +// 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 + // KeyValidator is a validator for the "key" field. It is called by the builders before save. + KeyValidator func(string) error + // VersionValidator is a validator for the "version" field. It is called by the builders before save. + VersionValidator func(int) error + // DefaultCurrency holds the default value on creation for the "currency" field. + DefaultCurrency string + // CurrencyValidator is a validator for the "currency" field. It is called by the builders before save. + CurrencyValidator func(string) error + // DefaultProRatingConfig holds the default value on creation for the "pro_rating_config" field. + DefaultProRatingConfig func() productcatalog.ProRatingConfig + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string + // ValueScanner of all Plan fields. + ValueScanner struct { + ProRatingConfig field.TypeValueScanner[productcatalog.ProRatingConfig] + } +) + +const DefaultSettlementMode productcatalog.SettlementMode = "credit_then_invoice" + +// 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 "credit_then_invoice", "credit_only": + return nil + default: + return fmt.Errorf("plan: invalid enum value for settlement_mode field: %q", sm) + } +} + +// OrderOption defines the ordering options for the Plan 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() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, opts...).ToFunc() +} + +// ByKey orders the results by the key field. +func ByKey(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldKey, opts...).ToFunc() +} + +// ByVersion orders the results by the version field. +func ByVersion(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVersion, opts...).ToFunc() +} + +// ByCurrency orders the results by the currency field. +func ByCurrency(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCurrency, opts...).ToFunc() +} + +// ByBillingCadence orders the results by the billing_cadence field. +func ByBillingCadence(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBillingCadence, opts...).ToFunc() +} + +// ByProRatingConfig orders the results by the pro_rating_config field. +func ByProRatingConfig(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldProRatingConfig, opts...).ToFunc() +} + +// ByEffectiveFrom orders the results by the effective_from field. +func ByEffectiveFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEffectiveFrom, opts...).ToFunc() +} + +// ByEffectiveTo orders the results by the effective_to field. +func ByEffectiveTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEffectiveTo, opts...).ToFunc() +} + +// BySettlementMode orders the results by the settlement_mode field. +func BySettlementMode(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSettlementMode, opts...).ToFunc() +} + +// ByPhasesCount orders the results by phases count. +func ByPhasesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newPhasesStep(), opts...) + } +} + +// ByPhases orders the results by phases terms. +func ByPhases(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newPhasesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByAddonsCount orders the results by addons count. +func ByAddonsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newAddonsStep(), opts...) + } +} + +// ByAddons orders the results by addons terms. +func ByAddons(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newAddonsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// BySubscriptionsCount orders the results by subscriptions count. +func BySubscriptionsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newSubscriptionsStep(), opts...) + } +} + +// BySubscriptions orders the results by subscriptions terms. +func BySubscriptions(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubscriptionsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newPhasesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(PhasesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, PhasesTable, PhasesColumn), + ) +} +func newAddonsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(AddonsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, AddonsTable, AddonsColumn), + ) +} +func newSubscriptionsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SubscriptionsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SubscriptionsTable, SubscriptionsColumn), + ) +} diff --git a/ent/db/plan/where.go b/ent/db/plan/where.go new file mode 100644 index 0000000000000000000000000000000000000000..827d2207d0227bb834cfe95eb2be4af0554cd227 --- /dev/null +++ b/ent/db/plan/where.go @@ -0,0 +1,942 @@ +// Code generated by ent, DO NOT EDIT. + +package plan + +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" + "github.com/openmeterio/openmeter/pkg/datetime" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.Plan { + return predicate.Plan(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.Plan { + return predicate.Plan(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.Plan { + return predicate.Plan(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.Plan { + return predicate.Plan(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.Plan { + return predicate.Plan(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.Plan { + return predicate.Plan(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.Plan { + return predicate.Plan(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.Plan { + return predicate.Plan(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.Plan { + return predicate.Plan(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.Plan { + return predicate.Plan(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.Plan { + return predicate.Plan(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.Plan { + return predicate.Plan(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.Plan { + return predicate.Plan(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.Plan { + return predicate.Plan(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.Plan { + return predicate.Plan(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.Plan { + return predicate.Plan(sql.FieldEQ(FieldName, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.Plan { + return predicate.Plan(sql.FieldEQ(FieldDescription, v)) +} + +// Key applies equality check predicate on the "key" field. It's identical to KeyEQ. +func Key(v string) predicate.Plan { + return predicate.Plan(sql.FieldEQ(FieldKey, v)) +} + +// Version applies equality check predicate on the "version" field. It's identical to VersionEQ. +func Version(v int) predicate.Plan { + return predicate.Plan(sql.FieldEQ(FieldVersion, v)) +} + +// Currency applies equality check predicate on the "currency" field. It's identical to CurrencyEQ. +func Currency(v string) predicate.Plan { + return predicate.Plan(sql.FieldEQ(FieldCurrency, v)) +} + +// BillingCadence applies equality check predicate on the "billing_cadence" field. It's identical to BillingCadenceEQ. +func BillingCadence(v datetime.ISODurationString) predicate.Plan { + vc := string(v) + return predicate.Plan(sql.FieldEQ(FieldBillingCadence, vc)) +} + +// EffectiveFrom applies equality check predicate on the "effective_from" field. It's identical to EffectiveFromEQ. +func EffectiveFrom(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldEQ(FieldEffectiveFrom, v)) +} + +// EffectiveTo applies equality check predicate on the "effective_to" field. It's identical to EffectiveToEQ. +func EffectiveTo(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldEQ(FieldEffectiveTo, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.Plan { + return predicate.Plan(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.Plan { + return predicate.Plan(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.Plan { + return predicate.Plan(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.Plan { + return predicate.Plan(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.Plan { + return predicate.Plan(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.Plan { + return predicate.Plan(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.Plan { + return predicate.Plan(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.Plan { + return predicate.Plan(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.Plan { + return predicate.Plan(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.Plan { + return predicate.Plan(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.Plan { + return predicate.Plan(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.Plan { + return predicate.Plan(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.Plan { + return predicate.Plan(sql.FieldContainsFold(FieldNamespace, v)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.Plan { + return predicate.Plan(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.Plan { + return predicate.Plan(sql.FieldNotNull(FieldMetadata)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Plan { + return predicate.Plan(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Plan { + return predicate.Plan(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.Plan { + return predicate.Plan(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.Plan { + return predicate.Plan(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.Plan { + return predicate.Plan(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.Plan { + return predicate.Plan(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.Plan { + return predicate.Plan(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.Plan { + return predicate.Plan(sql.FieldNotNull(FieldDeletedAt)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.Plan { + return predicate.Plan(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.Plan { + return predicate.Plan(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.Plan { + return predicate.Plan(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.Plan { + return predicate.Plan(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.Plan { + return predicate.Plan(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.Plan { + return predicate.Plan(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.Plan { + return predicate.Plan(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.Plan { + return predicate.Plan(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.Plan { + return predicate.Plan(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.Plan { + return predicate.Plan(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.Plan { + return predicate.Plan(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.Plan { + return predicate.Plan(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.Plan { + return predicate.Plan(sql.FieldContainsFold(FieldName, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.Plan { + return predicate.Plan(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.Plan { + return predicate.Plan(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.Plan { + return predicate.Plan(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.Plan { + return predicate.Plan(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.Plan { + return predicate.Plan(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.Plan { + return predicate.Plan(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.Plan { + return predicate.Plan(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.Plan { + return predicate.Plan(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.Plan { + return predicate.Plan(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.Plan { + return predicate.Plan(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.Plan { + return predicate.Plan(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.Plan { + return predicate.Plan(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.Plan { + return predicate.Plan(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.Plan { + return predicate.Plan(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.Plan { + return predicate.Plan(sql.FieldContainsFold(FieldDescription, v)) +} + +// KeyEQ applies the EQ predicate on the "key" field. +func KeyEQ(v string) predicate.Plan { + return predicate.Plan(sql.FieldEQ(FieldKey, v)) +} + +// KeyNEQ applies the NEQ predicate on the "key" field. +func KeyNEQ(v string) predicate.Plan { + return predicate.Plan(sql.FieldNEQ(FieldKey, v)) +} + +// KeyIn applies the In predicate on the "key" field. +func KeyIn(vs ...string) predicate.Plan { + return predicate.Plan(sql.FieldIn(FieldKey, vs...)) +} + +// KeyNotIn applies the NotIn predicate on the "key" field. +func KeyNotIn(vs ...string) predicate.Plan { + return predicate.Plan(sql.FieldNotIn(FieldKey, vs...)) +} + +// KeyGT applies the GT predicate on the "key" field. +func KeyGT(v string) predicate.Plan { + return predicate.Plan(sql.FieldGT(FieldKey, v)) +} + +// KeyGTE applies the GTE predicate on the "key" field. +func KeyGTE(v string) predicate.Plan { + return predicate.Plan(sql.FieldGTE(FieldKey, v)) +} + +// KeyLT applies the LT predicate on the "key" field. +func KeyLT(v string) predicate.Plan { + return predicate.Plan(sql.FieldLT(FieldKey, v)) +} + +// KeyLTE applies the LTE predicate on the "key" field. +func KeyLTE(v string) predicate.Plan { + return predicate.Plan(sql.FieldLTE(FieldKey, v)) +} + +// KeyContains applies the Contains predicate on the "key" field. +func KeyContains(v string) predicate.Plan { + return predicate.Plan(sql.FieldContains(FieldKey, v)) +} + +// KeyHasPrefix applies the HasPrefix predicate on the "key" field. +func KeyHasPrefix(v string) predicate.Plan { + return predicate.Plan(sql.FieldHasPrefix(FieldKey, v)) +} + +// KeyHasSuffix applies the HasSuffix predicate on the "key" field. +func KeyHasSuffix(v string) predicate.Plan { + return predicate.Plan(sql.FieldHasSuffix(FieldKey, v)) +} + +// KeyEqualFold applies the EqualFold predicate on the "key" field. +func KeyEqualFold(v string) predicate.Plan { + return predicate.Plan(sql.FieldEqualFold(FieldKey, v)) +} + +// KeyContainsFold applies the ContainsFold predicate on the "key" field. +func KeyContainsFold(v string) predicate.Plan { + return predicate.Plan(sql.FieldContainsFold(FieldKey, v)) +} + +// VersionEQ applies the EQ predicate on the "version" field. +func VersionEQ(v int) predicate.Plan { + return predicate.Plan(sql.FieldEQ(FieldVersion, v)) +} + +// VersionNEQ applies the NEQ predicate on the "version" field. +func VersionNEQ(v int) predicate.Plan { + return predicate.Plan(sql.FieldNEQ(FieldVersion, v)) +} + +// VersionIn applies the In predicate on the "version" field. +func VersionIn(vs ...int) predicate.Plan { + return predicate.Plan(sql.FieldIn(FieldVersion, vs...)) +} + +// VersionNotIn applies the NotIn predicate on the "version" field. +func VersionNotIn(vs ...int) predicate.Plan { + return predicate.Plan(sql.FieldNotIn(FieldVersion, vs...)) +} + +// VersionGT applies the GT predicate on the "version" field. +func VersionGT(v int) predicate.Plan { + return predicate.Plan(sql.FieldGT(FieldVersion, v)) +} + +// VersionGTE applies the GTE predicate on the "version" field. +func VersionGTE(v int) predicate.Plan { + return predicate.Plan(sql.FieldGTE(FieldVersion, v)) +} + +// VersionLT applies the LT predicate on the "version" field. +func VersionLT(v int) predicate.Plan { + return predicate.Plan(sql.FieldLT(FieldVersion, v)) +} + +// VersionLTE applies the LTE predicate on the "version" field. +func VersionLTE(v int) predicate.Plan { + return predicate.Plan(sql.FieldLTE(FieldVersion, v)) +} + +// CurrencyEQ applies the EQ predicate on the "currency" field. +func CurrencyEQ(v string) predicate.Plan { + return predicate.Plan(sql.FieldEQ(FieldCurrency, v)) +} + +// CurrencyNEQ applies the NEQ predicate on the "currency" field. +func CurrencyNEQ(v string) predicate.Plan { + return predicate.Plan(sql.FieldNEQ(FieldCurrency, v)) +} + +// CurrencyIn applies the In predicate on the "currency" field. +func CurrencyIn(vs ...string) predicate.Plan { + return predicate.Plan(sql.FieldIn(FieldCurrency, vs...)) +} + +// CurrencyNotIn applies the NotIn predicate on the "currency" field. +func CurrencyNotIn(vs ...string) predicate.Plan { + return predicate.Plan(sql.FieldNotIn(FieldCurrency, vs...)) +} + +// CurrencyGT applies the GT predicate on the "currency" field. +func CurrencyGT(v string) predicate.Plan { + return predicate.Plan(sql.FieldGT(FieldCurrency, v)) +} + +// CurrencyGTE applies the GTE predicate on the "currency" field. +func CurrencyGTE(v string) predicate.Plan { + return predicate.Plan(sql.FieldGTE(FieldCurrency, v)) +} + +// CurrencyLT applies the LT predicate on the "currency" field. +func CurrencyLT(v string) predicate.Plan { + return predicate.Plan(sql.FieldLT(FieldCurrency, v)) +} + +// CurrencyLTE applies the LTE predicate on the "currency" field. +func CurrencyLTE(v string) predicate.Plan { + return predicate.Plan(sql.FieldLTE(FieldCurrency, v)) +} + +// CurrencyContains applies the Contains predicate on the "currency" field. +func CurrencyContains(v string) predicate.Plan { + return predicate.Plan(sql.FieldContains(FieldCurrency, v)) +} + +// CurrencyHasPrefix applies the HasPrefix predicate on the "currency" field. +func CurrencyHasPrefix(v string) predicate.Plan { + return predicate.Plan(sql.FieldHasPrefix(FieldCurrency, v)) +} + +// CurrencyHasSuffix applies the HasSuffix predicate on the "currency" field. +func CurrencyHasSuffix(v string) predicate.Plan { + return predicate.Plan(sql.FieldHasSuffix(FieldCurrency, v)) +} + +// CurrencyEqualFold applies the EqualFold predicate on the "currency" field. +func CurrencyEqualFold(v string) predicate.Plan { + return predicate.Plan(sql.FieldEqualFold(FieldCurrency, v)) +} + +// CurrencyContainsFold applies the ContainsFold predicate on the "currency" field. +func CurrencyContainsFold(v string) predicate.Plan { + return predicate.Plan(sql.FieldContainsFold(FieldCurrency, v)) +} + +// BillingCadenceEQ applies the EQ predicate on the "billing_cadence" field. +func BillingCadenceEQ(v datetime.ISODurationString) predicate.Plan { + vc := string(v) + return predicate.Plan(sql.FieldEQ(FieldBillingCadence, vc)) +} + +// BillingCadenceNEQ applies the NEQ predicate on the "billing_cadence" field. +func BillingCadenceNEQ(v datetime.ISODurationString) predicate.Plan { + vc := string(v) + return predicate.Plan(sql.FieldNEQ(FieldBillingCadence, vc)) +} + +// BillingCadenceIn applies the In predicate on the "billing_cadence" field. +func BillingCadenceIn(vs ...datetime.ISODurationString) predicate.Plan { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.Plan(sql.FieldIn(FieldBillingCadence, v...)) +} + +// BillingCadenceNotIn applies the NotIn predicate on the "billing_cadence" field. +func BillingCadenceNotIn(vs ...datetime.ISODurationString) predicate.Plan { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.Plan(sql.FieldNotIn(FieldBillingCadence, v...)) +} + +// BillingCadenceGT applies the GT predicate on the "billing_cadence" field. +func BillingCadenceGT(v datetime.ISODurationString) predicate.Plan { + vc := string(v) + return predicate.Plan(sql.FieldGT(FieldBillingCadence, vc)) +} + +// BillingCadenceGTE applies the GTE predicate on the "billing_cadence" field. +func BillingCadenceGTE(v datetime.ISODurationString) predicate.Plan { + vc := string(v) + return predicate.Plan(sql.FieldGTE(FieldBillingCadence, vc)) +} + +// BillingCadenceLT applies the LT predicate on the "billing_cadence" field. +func BillingCadenceLT(v datetime.ISODurationString) predicate.Plan { + vc := string(v) + return predicate.Plan(sql.FieldLT(FieldBillingCadence, vc)) +} + +// BillingCadenceLTE applies the LTE predicate on the "billing_cadence" field. +func BillingCadenceLTE(v datetime.ISODurationString) predicate.Plan { + vc := string(v) + return predicate.Plan(sql.FieldLTE(FieldBillingCadence, vc)) +} + +// BillingCadenceContains applies the Contains predicate on the "billing_cadence" field. +func BillingCadenceContains(v datetime.ISODurationString) predicate.Plan { + vc := string(v) + return predicate.Plan(sql.FieldContains(FieldBillingCadence, vc)) +} + +// BillingCadenceHasPrefix applies the HasPrefix predicate on the "billing_cadence" field. +func BillingCadenceHasPrefix(v datetime.ISODurationString) predicate.Plan { + vc := string(v) + return predicate.Plan(sql.FieldHasPrefix(FieldBillingCadence, vc)) +} + +// BillingCadenceHasSuffix applies the HasSuffix predicate on the "billing_cadence" field. +func BillingCadenceHasSuffix(v datetime.ISODurationString) predicate.Plan { + vc := string(v) + return predicate.Plan(sql.FieldHasSuffix(FieldBillingCadence, vc)) +} + +// BillingCadenceEqualFold applies the EqualFold predicate on the "billing_cadence" field. +func BillingCadenceEqualFold(v datetime.ISODurationString) predicate.Plan { + vc := string(v) + return predicate.Plan(sql.FieldEqualFold(FieldBillingCadence, vc)) +} + +// BillingCadenceContainsFold applies the ContainsFold predicate on the "billing_cadence" field. +func BillingCadenceContainsFold(v datetime.ISODurationString) predicate.Plan { + vc := string(v) + return predicate.Plan(sql.FieldContainsFold(FieldBillingCadence, vc)) +} + +// EffectiveFromEQ applies the EQ predicate on the "effective_from" field. +func EffectiveFromEQ(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldEQ(FieldEffectiveFrom, v)) +} + +// EffectiveFromNEQ applies the NEQ predicate on the "effective_from" field. +func EffectiveFromNEQ(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldNEQ(FieldEffectiveFrom, v)) +} + +// EffectiveFromIn applies the In predicate on the "effective_from" field. +func EffectiveFromIn(vs ...time.Time) predicate.Plan { + return predicate.Plan(sql.FieldIn(FieldEffectiveFrom, vs...)) +} + +// EffectiveFromNotIn applies the NotIn predicate on the "effective_from" field. +func EffectiveFromNotIn(vs ...time.Time) predicate.Plan { + return predicate.Plan(sql.FieldNotIn(FieldEffectiveFrom, vs...)) +} + +// EffectiveFromGT applies the GT predicate on the "effective_from" field. +func EffectiveFromGT(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldGT(FieldEffectiveFrom, v)) +} + +// EffectiveFromGTE applies the GTE predicate on the "effective_from" field. +func EffectiveFromGTE(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldGTE(FieldEffectiveFrom, v)) +} + +// EffectiveFromLT applies the LT predicate on the "effective_from" field. +func EffectiveFromLT(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldLT(FieldEffectiveFrom, v)) +} + +// EffectiveFromLTE applies the LTE predicate on the "effective_from" field. +func EffectiveFromLTE(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldLTE(FieldEffectiveFrom, v)) +} + +// EffectiveFromIsNil applies the IsNil predicate on the "effective_from" field. +func EffectiveFromIsNil() predicate.Plan { + return predicate.Plan(sql.FieldIsNull(FieldEffectiveFrom)) +} + +// EffectiveFromNotNil applies the NotNil predicate on the "effective_from" field. +func EffectiveFromNotNil() predicate.Plan { + return predicate.Plan(sql.FieldNotNull(FieldEffectiveFrom)) +} + +// EffectiveToEQ applies the EQ predicate on the "effective_to" field. +func EffectiveToEQ(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldEQ(FieldEffectiveTo, v)) +} + +// EffectiveToNEQ applies the NEQ predicate on the "effective_to" field. +func EffectiveToNEQ(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldNEQ(FieldEffectiveTo, v)) +} + +// EffectiveToIn applies the In predicate on the "effective_to" field. +func EffectiveToIn(vs ...time.Time) predicate.Plan { + return predicate.Plan(sql.FieldIn(FieldEffectiveTo, vs...)) +} + +// EffectiveToNotIn applies the NotIn predicate on the "effective_to" field. +func EffectiveToNotIn(vs ...time.Time) predicate.Plan { + return predicate.Plan(sql.FieldNotIn(FieldEffectiveTo, vs...)) +} + +// EffectiveToGT applies the GT predicate on the "effective_to" field. +func EffectiveToGT(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldGT(FieldEffectiveTo, v)) +} + +// EffectiveToGTE applies the GTE predicate on the "effective_to" field. +func EffectiveToGTE(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldGTE(FieldEffectiveTo, v)) +} + +// EffectiveToLT applies the LT predicate on the "effective_to" field. +func EffectiveToLT(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldLT(FieldEffectiveTo, v)) +} + +// EffectiveToLTE applies the LTE predicate on the "effective_to" field. +func EffectiveToLTE(v time.Time) predicate.Plan { + return predicate.Plan(sql.FieldLTE(FieldEffectiveTo, v)) +} + +// EffectiveToIsNil applies the IsNil predicate on the "effective_to" field. +func EffectiveToIsNil() predicate.Plan { + return predicate.Plan(sql.FieldIsNull(FieldEffectiveTo)) +} + +// EffectiveToNotNil applies the NotNil predicate on the "effective_to" field. +func EffectiveToNotNil() predicate.Plan { + return predicate.Plan(sql.FieldNotNull(FieldEffectiveTo)) +} + +// SettlementModeEQ applies the EQ predicate on the "settlement_mode" field. +func SettlementModeEQ(v productcatalog.SettlementMode) predicate.Plan { + vc := v + return predicate.Plan(sql.FieldEQ(FieldSettlementMode, vc)) +} + +// SettlementModeNEQ applies the NEQ predicate on the "settlement_mode" field. +func SettlementModeNEQ(v productcatalog.SettlementMode) predicate.Plan { + vc := v + return predicate.Plan(sql.FieldNEQ(FieldSettlementMode, vc)) +} + +// SettlementModeIn applies the In predicate on the "settlement_mode" field. +func SettlementModeIn(vs ...productcatalog.SettlementMode) predicate.Plan { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Plan(sql.FieldIn(FieldSettlementMode, v...)) +} + +// SettlementModeNotIn applies the NotIn predicate on the "settlement_mode" field. +func SettlementModeNotIn(vs ...productcatalog.SettlementMode) predicate.Plan { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Plan(sql.FieldNotIn(FieldSettlementMode, v...)) +} + +// HasPhases applies the HasEdge predicate on the "phases" edge. +func HasPhases() predicate.Plan { + return predicate.Plan(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, PhasesTable, PhasesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasPhasesWith applies the HasEdge predicate on the "phases" edge with a given conditions (other predicates). +func HasPhasesWith(preds ...predicate.PlanPhase) predicate.Plan { + return predicate.Plan(func(s *sql.Selector) { + step := newPhasesStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasAddons applies the HasEdge predicate on the "addons" edge. +func HasAddons() predicate.Plan { + return predicate.Plan(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, AddonsTable, AddonsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasAddonsWith applies the HasEdge predicate on the "addons" edge with a given conditions (other predicates). +func HasAddonsWith(preds ...predicate.PlanAddon) predicate.Plan { + return predicate.Plan(func(s *sql.Selector) { + step := newAddonsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSubscriptions applies the HasEdge predicate on the "subscriptions" edge. +func HasSubscriptions() predicate.Plan { + return predicate.Plan(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SubscriptionsTable, SubscriptionsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubscriptionsWith applies the HasEdge predicate on the "subscriptions" edge with a given conditions (other predicates). +func HasSubscriptionsWith(preds ...predicate.Subscription) predicate.Plan { + return predicate.Plan(func(s *sql.Selector) { + step := newSubscriptionsStep() + 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.Plan) predicate.Plan { + return predicate.Plan(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Plan) predicate.Plan { + return predicate.Plan(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Plan) predicate.Plan { + return predicate.Plan(sql.NotPredicates(p)) +}